123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139 |
- #include <stdio.h>
- #include <stdlib.h>
- #include "gtest/gtest.h"
- using ::testing::EmptyTestEventListener;
- using ::testing::InitGoogleTest;
- using ::testing::Test;
- using ::testing::TestEventListeners;
- using ::testing::TestInfo;
- using ::testing::TestPartResult;
- using ::testing::UnitTest;
- namespace {
- class Water {
- public:
-
-
- void* operator new(size_t allocation_size) {
- allocated_++;
- return malloc(allocation_size);
- }
- void operator delete(void* block, size_t ) {
- allocated_--;
- free(block);
- }
- static int allocated() { return allocated_; }
- private:
- static int allocated_;
- };
- int Water::allocated_ = 0;
- class LeakChecker : public EmptyTestEventListener {
- private:
-
- void OnTestStart(const TestInfo& ) override {
- initially_allocated_ = Water::allocated();
- }
-
- void OnTestEnd(const TestInfo& ) override {
- int difference = Water::allocated() - initially_allocated_;
-
-
-
- EXPECT_LE(difference, 0) << "Leaked " << difference << " unit(s) of Water!";
- }
- int initially_allocated_;
- };
- TEST(ListenersTest, DoesNotLeak) {
- Water* water = new Water;
- delete water;
- }
- TEST(ListenersTest, LeaksWater) {
- Water* water = new Water;
- EXPECT_TRUE(water != nullptr);
- }
- }
- int main(int argc, char **argv) {
- InitGoogleTest(&argc, argv);
- bool check_for_leaks = false;
- if (argc > 1 && strcmp(argv[1], "--check_for_leaks") == 0 )
- check_for_leaks = true;
- else
- printf("%s\n", "Run this program with --check_for_leaks to enable "
- "custom leak checking in the tests.");
-
-
- if (check_for_leaks) {
- TestEventListeners& listeners = UnitTest::GetInstance()->listeners();
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- listeners.Append(new LeakChecker);
- }
- return RUN_ALL_TESTS();
- }
|