1// Copyright 2009 Google Inc. All Rights Reserved.
2//
3// Redistribution and use in source and binary forms, with or without
4// modification, are permitted provided that the following conditions are
5// met:
6//
7//     * Redistributions of source code must retain the above copyright
8// notice, this list of conditions and the following disclaimer.
9//     * Redistributions in binary form must reproduce the above
10// copyright notice, this list of conditions and the following disclaimer
11// in the documentation and/or other materials provided with the
12// distribution.
13//     * Neither the name of Google Inc. nor the names of its
14// contributors may be used to endorse or promote products derived from
15// this software without specific prior written permission.
16//
17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29// This sample shows how to use Google Test listener API to implement
30// a primitive leak checker.
31
32#include <stdio.h>
33#include <stdlib.h>
34
35#include "gtest/gtest.h"
36using ::testing::EmptyTestEventListener;
37using ::testing::InitGoogleTest;
38using ::testing::Test;
39using ::testing::TestEventListeners;
40using ::testing::TestInfo;
41using ::testing::UnitTest;
42
43namespace {
44// We will track memory used by this class.
45class Water {
46 public:
47  // Normal Water declarations go here.
48
49  // operator new and operator delete help us control water allocation.
50  void* operator new(size_t allocation_size) {
51    allocated_++;
52    return malloc(allocation_size);
53  }
54
55  void operator delete(void* block, size_t /* allocation_size */) {
56    allocated_--;
57    free(block);
58  }
59
60  static int allocated() { return allocated_; }
61
62 private:
63  static int allocated_;
64};
65
66int Water::allocated_ = 0;
67
68// This event listener monitors how many Water objects are created and
69// destroyed by each test, and reports a failure if a test leaks some Water
70// objects. It does this by comparing the number of live Water objects at
71// the beginning of a test and at the end of a test.
72class LeakChecker : public EmptyTestEventListener {
73 private:
74  // Called before a test starts.
75  void OnTestStart(const TestInfo& /* test_info */) override {
76    initially_allocated_ = Water::allocated();
77  }
78
79  // Called after a test ends.
80  void OnTestEnd(const TestInfo& /* test_info */) override {
81    int difference = Water::allocated() - initially_allocated_;
82
83    // You can generate a failure in any event handler except
84    // OnTestPartResult. Just use an appropriate Google Test assertion to do
85    // it.
86    EXPECT_LE(difference, 0) << "Leaked " << difference << " unit(s) of Water!";
87  }
88
89  int initially_allocated_;
90};
91
92TEST(ListenersTest, DoesNotLeak) {
93  Water* water = new Water;
94  delete water;
95}
96
97// This should fail when the --check_for_leaks command line flag is
98// specified.
99TEST(ListenersTest, LeaksWater) {
100  Water* water = new Water;
101  EXPECT_TRUE(water != nullptr);
102}
103}  // namespace
104
105int main(int argc, char** argv) {
106  InitGoogleTest(&argc, argv);
107
108  bool check_for_leaks = false;
109  if (argc > 1 && strcmp(argv[1], "--check_for_leaks") == 0)
110    check_for_leaks = true;
111  else
112    printf("%s\n",
113           "Run this program with --check_for_leaks to enable "
114           "custom leak checking in the tests.");
115
116  // If we are given the --check_for_leaks command line flag, installs the
117  // leak checker.
118  if (check_for_leaks) {
119    TestEventListeners& listeners = UnitTest::GetInstance()->listeners();
120
121    // Adds the leak checker to the end of the test event listener list,
122    // after the default text output printer and the default XML report
123    // generator.
124    //
125    // The order is important - it ensures that failures generated in the
126    // leak checker's OnTestEnd() method are processed by the text and XML
127    // printers *before* their OnTestEnd() methods are called, such that
128    // they are attributed to the right test. Remember that a listener
129    // receives an OnXyzStart event *after* listeners preceding it in the
130    // list received that event, and receives an OnXyzEnd event *before*
131    // listeners preceding it.
132    //
133    // We don't need to worry about deleting the new listener later, as
134    // Google Test will do it.
135    listeners.Append(new LeakChecker);
136  }
137  return RUN_ALL_TESTS();
138}
139