tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

gmock-spec-builders.cc (29379B)


      1 // Copyright 2007, Google Inc.
      2 // All rights reserved.
      3 //
      4 // Redistribution and use in source and binary forms, with or without
      5 // modification, are permitted provided that the following conditions are
      6 // met:
      7 //
      8 //     * Redistributions of source code must retain the above copyright
      9 // notice, this list of conditions and the following disclaimer.
     10 //     * Redistributions in binary form must reproduce the above
     11 // copyright notice, this list of conditions and the following disclaimer
     12 // in the documentation and/or other materials provided with the
     13 // distribution.
     14 //     * Neither the name of Google Inc. nor the names of its
     15 // contributors may be used to endorse or promote products derived from
     16 // this software without specific prior written permission.
     17 //
     18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
     22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
     24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     29 
     30 // Google Mock - a framework for writing C++ mock classes.
     31 //
     32 // This file implements the spec builder syntax (ON_CALL and
     33 // EXPECT_CALL).
     34 
     35 #include "gmock/gmock-spec-builders.h"
     36 
     37 #include <stdlib.h>
     38 
     39 #include <iostream>  // NOLINT
     40 #include <map>
     41 #include <memory>
     42 #include <set>
     43 #include <sstream>
     44 #include <string>
     45 #include <unordered_map>
     46 #include <vector>
     47 
     48 #include "gmock/gmock.h"
     49 #include "gtest/gtest.h"
     50 #include "gtest/internal/gtest-port.h"
     51 
     52 #if defined(GTEST_OS_CYGWIN) || defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC)
     53 #include <unistd.h>  // NOLINT
     54 #endif
     55 #ifdef GTEST_OS_QURT
     56 #include <qurt_event.h>
     57 #endif
     58 
     59 // Silence C4800 (C4800: 'int *const ': forcing value
     60 // to bool 'true' or 'false') for MSVC 15
     61 #if defined(_MSC_VER) && (_MSC_VER == 1900)
     62 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800)
     63 #endif
     64 
     65 namespace testing {
     66 namespace internal {
     67 
     68 // Protects the mock object registry (in class Mock), all function
     69 // mockers, and all expectations.
     70 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
     71 
     72 // Logs a message including file and line number information.
     73 GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
     74                                const char* file, int line,
     75                                const std::string& message) {
     76  ::std::ostringstream s;
     77  s << internal::FormatFileLocation(file, line) << " " << message
     78    << ::std::endl;
     79  Log(severity, s.str(), 0);
     80 }
     81 
     82 // Constructs an ExpectationBase object.
     83 ExpectationBase::ExpectationBase(const char* a_file, int a_line,
     84                                 const std::string& a_source_text)
     85    : file_(a_file),
     86      line_(a_line),
     87      source_text_(a_source_text),
     88      cardinality_specified_(false),
     89      cardinality_(Exactly(1)),
     90      call_count_(0),
     91      retired_(false),
     92      extra_matcher_specified_(false),
     93      repeated_action_specified_(false),
     94      retires_on_saturation_(false),
     95      last_clause_(kNone),
     96      action_count_checked_(false) {}
     97 
     98 // Destructs an ExpectationBase object.
     99 ExpectationBase::~ExpectationBase() = default;
    100 
    101 // Explicitly specifies the cardinality of this expectation.  Used by
    102 // the subclasses to implement the .Times() clause.
    103 void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {
    104  cardinality_specified_ = true;
    105  cardinality_ = a_cardinality;
    106 }
    107 
    108 // Retires all pre-requisites of this expectation.
    109 void ExpectationBase::RetireAllPreRequisites()
    110    GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
    111  if (is_retired()) {
    112    // We can take this short-cut as we never retire an expectation
    113    // until we have retired all its pre-requisites.
    114    return;
    115  }
    116 
    117  ::std::vector<ExpectationBase*> expectations(1, this);
    118  while (!expectations.empty()) {
    119    ExpectationBase* exp = expectations.back();
    120    expectations.pop_back();
    121 
    122    for (ExpectationSet::const_iterator it =
    123             exp->immediate_prerequisites_.begin();
    124         it != exp->immediate_prerequisites_.end(); ++it) {
    125      ExpectationBase* next = it->expectation_base().get();
    126      if (!next->is_retired()) {
    127        next->Retire();
    128        expectations.push_back(next);
    129      }
    130    }
    131  }
    132 }
    133 
    134 // Returns true if and only if all pre-requisites of this expectation
    135 // have been satisfied.
    136 bool ExpectationBase::AllPrerequisitesAreSatisfied() const
    137    GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
    138  g_gmock_mutex.AssertHeld();
    139  ::std::vector<const ExpectationBase*> expectations(1, this);
    140  while (!expectations.empty()) {
    141    const ExpectationBase* exp = expectations.back();
    142    expectations.pop_back();
    143 
    144    for (ExpectationSet::const_iterator it =
    145             exp->immediate_prerequisites_.begin();
    146         it != exp->immediate_prerequisites_.end(); ++it) {
    147      const ExpectationBase* next = it->expectation_base().get();
    148      if (!next->IsSatisfied()) return false;
    149      expectations.push_back(next);
    150    }
    151  }
    152  return true;
    153 }
    154 
    155 // Adds unsatisfied pre-requisites of this expectation to 'result'.
    156 void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const
    157    GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
    158  g_gmock_mutex.AssertHeld();
    159  ::std::vector<const ExpectationBase*> expectations(1, this);
    160  while (!expectations.empty()) {
    161    const ExpectationBase* exp = expectations.back();
    162    expectations.pop_back();
    163 
    164    for (ExpectationSet::const_iterator it =
    165             exp->immediate_prerequisites_.begin();
    166         it != exp->immediate_prerequisites_.end(); ++it) {
    167      const ExpectationBase* next = it->expectation_base().get();
    168 
    169      if (next->IsSatisfied()) {
    170        // If *it is satisfied and has a call count of 0, some of its
    171        // pre-requisites may not be satisfied yet.
    172        if (next->call_count_ == 0) {
    173          expectations.push_back(next);
    174        }
    175      } else {
    176        // Now that we know next is unsatisfied, we are not so interested
    177        // in whether its pre-requisites are satisfied.  Therefore we
    178        // don't iterate into it here.
    179        *result += *it;
    180      }
    181    }
    182  }
    183 }
    184 
    185 // Describes how many times a function call matching this
    186 // expectation has occurred.
    187 void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
    188    GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
    189  g_gmock_mutex.AssertHeld();
    190 
    191  // Describes how many times the function is expected to be called.
    192  *os << "         Expected: to be ";
    193  cardinality().DescribeTo(os);
    194  *os << "\n           Actual: ";
    195  Cardinality::DescribeActualCallCountTo(call_count(), os);
    196 
    197  // Describes the state of the expectation (e.g. is it satisfied?
    198  // is it active?).
    199  *os << " - "
    200      << (IsOverSaturated() ? "over-saturated"
    201          : IsSaturated()   ? "saturated"
    202          : IsSatisfied()   ? "satisfied"
    203                            : "unsatisfied")
    204      << " and " << (is_retired() ? "retired" : "active");
    205 }
    206 
    207 // Checks the action count (i.e. the number of WillOnce() and
    208 // WillRepeatedly() clauses) against the cardinality if this hasn't
    209 // been done before.  Prints a warning if there are too many or too
    210 // few actions.
    211 void ExpectationBase::CheckActionCountIfNotDone() const
    212    GTEST_LOCK_EXCLUDED_(mutex_) {
    213  bool should_check = false;
    214  {
    215    MutexLock l(&mutex_);
    216    if (!action_count_checked_) {
    217      action_count_checked_ = true;
    218      should_check = true;
    219    }
    220  }
    221 
    222  if (should_check) {
    223    if (!cardinality_specified_) {
    224      // The cardinality was inferred - no need to check the action
    225      // count against it.
    226      return;
    227    }
    228 
    229    // The cardinality was explicitly specified.
    230    const int action_count = static_cast<int>(untyped_actions_.size());
    231    const int upper_bound = cardinality().ConservativeUpperBound();
    232    const int lower_bound = cardinality().ConservativeLowerBound();
    233    bool too_many;  // True if there are too many actions, or false
    234    // if there are too few.
    235    if (action_count > upper_bound ||
    236        (action_count == upper_bound && repeated_action_specified_)) {
    237      too_many = true;
    238    } else if (0 < action_count && action_count < lower_bound &&
    239               !repeated_action_specified_) {
    240      too_many = false;
    241    } else {
    242      return;
    243    }
    244 
    245    ::std::stringstream ss;
    246    DescribeLocationTo(&ss);
    247    ss << "Too " << (too_many ? "many" : "few") << " actions specified in "
    248       << source_text() << "...\n"
    249       << "Expected to be ";
    250    cardinality().DescribeTo(&ss);
    251    ss << ", but has " << (too_many ? "" : "only ") << action_count
    252       << " WillOnce()" << (action_count == 1 ? "" : "s");
    253    if (repeated_action_specified_) {
    254      ss << " and a WillRepeatedly()";
    255    }
    256    ss << ".";
    257    Log(kWarning, ss.str(), -1);  // -1 means "don't print stack trace".
    258  }
    259 }
    260 
    261 // Implements the .Times() clause.
    262 void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
    263  if (last_clause_ == kTimes) {
    264    ExpectSpecProperty(false,
    265                       ".Times() cannot appear "
    266                       "more than once in an EXPECT_CALL().");
    267  } else {
    268    ExpectSpecProperty(
    269        last_clause_ < kTimes,
    270        ".Times() may only appear *before* .InSequence(), .WillOnce(), "
    271        ".WillRepeatedly(), or .RetiresOnSaturation(), not after.");
    272  }
    273  last_clause_ = kTimes;
    274 
    275  SpecifyCardinality(a_cardinality);
    276 }
    277 
    278 // Points to the implicit sequence introduced by a living InSequence
    279 // object (if any) in the current thread or NULL.
    280 GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
    281 
    282 // Reports an uninteresting call (whose description is in msg) in the
    283 // manner specified by 'reaction'.
    284 void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
    285  // Include a stack trace only if --gmock_verbose=info is specified.
    286  const int stack_frames_to_skip =
    287      GMOCK_FLAG_GET(verbose) == kInfoVerbosity ? 3 : -1;
    288  switch (reaction) {
    289    case kAllow:
    290      Log(kInfo, msg, stack_frames_to_skip);
    291      break;
    292    case kWarn:
    293      Log(kWarning,
    294          msg +
    295              "\nNOTE: You can safely ignore the above warning unless this "
    296              "call should not happen.  Do not suppress it by adding "
    297              "an EXPECT_CALL() if you don't mean to enforce the call.  "
    298              "See "
    299              "https://github.com/google/googletest/blob/main/docs/"
    300              "gmock_cook_book.md#"
    301              "knowing-when-to-expect-useoncall for details.\n",
    302          stack_frames_to_skip);
    303      break;
    304    default:  // FAIL
    305      Expect(false, nullptr, -1, msg);
    306  }
    307 }
    308 
    309 UntypedFunctionMockerBase::UntypedFunctionMockerBase()
    310    : mock_obj_(nullptr), name_("") {}
    311 
    312 UntypedFunctionMockerBase::~UntypedFunctionMockerBase() = default;
    313 
    314 // Sets the mock object this mock method belongs to, and registers
    315 // this information in the global mock registry.  Will be called
    316 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
    317 // method.
    318 void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
    319    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
    320  {
    321    MutexLock l(&g_gmock_mutex);
    322    mock_obj_ = mock_obj;
    323  }
    324  Mock::Register(mock_obj, this);
    325 }
    326 
    327 // Sets the mock object this mock method belongs to, and sets the name
    328 // of the mock function.  Will be called upon each invocation of this
    329 // mock function.
    330 void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
    331                                                const char* name)
    332    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
    333  // We protect name_ under g_gmock_mutex in case this mock function
    334  // is called from two threads concurrently.
    335  MutexLock l(&g_gmock_mutex);
    336  mock_obj_ = mock_obj;
    337  name_ = name;
    338 }
    339 
    340 // Returns the name of the function being mocked.  Must be called
    341 // after RegisterOwner() or SetOwnerAndName() has been called.
    342 const void* UntypedFunctionMockerBase::MockObject() const
    343    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
    344  const void* mock_obj;
    345  {
    346    // We protect mock_obj_ under g_gmock_mutex in case this mock
    347    // function is called from two threads concurrently.
    348    MutexLock l(&g_gmock_mutex);
    349    Assert(mock_obj_ != nullptr, __FILE__, __LINE__,
    350           "MockObject() must not be called before RegisterOwner() or "
    351           "SetOwnerAndName() has been called.");
    352    mock_obj = mock_obj_;
    353  }
    354  return mock_obj;
    355 }
    356 
    357 // Returns the name of this mock method.  Must be called after
    358 // SetOwnerAndName() has been called.
    359 const char* UntypedFunctionMockerBase::Name() const
    360    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
    361  const char* name;
    362  {
    363    // We protect name_ under g_gmock_mutex in case this mock
    364    // function is called from two threads concurrently.
    365    MutexLock l(&g_gmock_mutex);
    366    Assert(name_ != nullptr, __FILE__, __LINE__,
    367           "Name() must not be called before SetOwnerAndName() has "
    368           "been called.");
    369    name = name_;
    370  }
    371  return name;
    372 }
    373 
    374 // Returns an Expectation object that references and co-owns exp,
    375 // which must be an expectation on this mock function.
    376 Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
    377  // See the definition of untyped_expectations_ for why access to it
    378  // is unprotected here.
    379  for (UntypedExpectations::const_iterator it = untyped_expectations_.begin();
    380       it != untyped_expectations_.end(); ++it) {
    381    if (it->get() == exp) {
    382      return Expectation(*it);
    383    }
    384  }
    385 
    386  Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
    387  return Expectation();
    388  // The above statement is just to make the code compile, and will
    389  // never be executed.
    390 }
    391 
    392 // Verifies that all expectations on this mock function have been
    393 // satisfied.  Reports one or more Google Test non-fatal failures
    394 // and returns false if not.
    395 bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
    396    GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
    397  g_gmock_mutex.AssertHeld();
    398  bool expectations_met = true;
    399  for (UntypedExpectations::const_iterator it = untyped_expectations_.begin();
    400       it != untyped_expectations_.end(); ++it) {
    401    ExpectationBase* const untyped_expectation = it->get();
    402    if (untyped_expectation->IsOverSaturated()) {
    403      // There was an upper-bound violation.  Since the error was
    404      // already reported when it occurred, there is no need to do
    405      // anything here.
    406      expectations_met = false;
    407    } else if (!untyped_expectation->IsSatisfied()) {
    408      expectations_met = false;
    409      ::std::stringstream ss;
    410 
    411      const ::std::string& expectation_name =
    412          untyped_expectation->GetDescription();
    413      ss << "Actual function ";
    414      if (!expectation_name.empty()) {
    415        ss << "\"" << expectation_name << "\" ";
    416      }
    417      ss << "call count doesn't match " << untyped_expectation->source_text()
    418         << "...\n";
    419      // No need to show the source file location of the expectation
    420      // in the description, as the Expect() call that follows already
    421      // takes care of it.
    422      untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
    423      untyped_expectation->DescribeCallCountTo(&ss);
    424      Expect(false, untyped_expectation->file(), untyped_expectation->line(),
    425             ss.str());
    426    }
    427  }
    428 
    429  // Deleting our expectations may trigger other mock objects to be deleted, for
    430  // example if an action contains a reference counted smart pointer to that
    431  // mock object, and that is the last reference. So if we delete our
    432  // expectations within the context of the global mutex we may deadlock when
    433  // this method is called again. Instead, make a copy of the set of
    434  // expectations to delete, clear our set within the mutex, and then clear the
    435  // copied set outside of it.
    436  UntypedExpectations expectations_to_delete;
    437  untyped_expectations_.swap(expectations_to_delete);
    438 
    439  g_gmock_mutex.unlock();
    440  expectations_to_delete.clear();
    441  g_gmock_mutex.lock();
    442 
    443  return expectations_met;
    444 }
    445 
    446 static CallReaction intToCallReaction(int mock_behavior) {
    447  if (mock_behavior >= kAllow && mock_behavior <= kFail) {
    448    return static_cast<internal::CallReaction>(mock_behavior);
    449  }
    450  return kWarn;
    451 }
    452 
    453 }  // namespace internal
    454 
    455 // Class Mock.
    456 
    457 namespace {
    458 
    459 typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
    460 
    461 // The current state of a mock object.  Such information is needed for
    462 // detecting leaked mock objects and explicitly verifying a mock's
    463 // expectations.
    464 struct MockObjectState {
    465  MockObjectState()
    466      : first_used_file(nullptr), first_used_line(-1), leakable(false) {}
    467 
    468  // Where in the source file an ON_CALL or EXPECT_CALL is first
    469  // invoked on this mock object.
    470  const char* first_used_file;
    471  int first_used_line;
    472  ::std::string first_used_test_suite;
    473  ::std::string first_used_test;
    474  bool leakable;  // true if and only if it's OK to leak the object.
    475  FunctionMockers function_mockers;  // All registered methods of the object.
    476 };
    477 
    478 // A global registry holding the state of all mock objects that are
    479 // alive.  A mock object is added to this registry the first time
    480 // Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it.  It
    481 // is removed from the registry in the mock object's destructor.
    482 class MockObjectRegistry {
    483 public:
    484  // Maps a mock object (identified by its address) to its state.
    485  typedef std::map<const void*, MockObjectState> StateMap;
    486 
    487  // This destructor will be called when a program exits, after all
    488  // tests in it have been run.  By then, there should be no mock
    489  // object alive.  Therefore we report any living object as test
    490  // failure, unless the user explicitly asked us to ignore it.
    491  ~MockObjectRegistry() {
    492    if (!GMOCK_FLAG_GET(catch_leaked_mocks)) return;
    493    internal::MutexLock l(&internal::g_gmock_mutex);
    494 
    495    int leaked_count = 0;
    496    for (StateMap::const_iterator it = states_.begin(); it != states_.end();
    497         ++it) {
    498      if (it->second.leakable)  // The user said it's fine to leak this object.
    499        continue;
    500 
    501      // FIXME: Print the type of the leaked object.
    502      // This can help the user identify the leaked object.
    503      std::cout << "\n";
    504      const MockObjectState& state = it->second;
    505      std::cout << internal::FormatFileLocation(state.first_used_file,
    506                                                state.first_used_line);
    507      std::cout << " ERROR: this mock object";
    508      if (!state.first_used_test.empty()) {
    509        std::cout << " (used in test " << state.first_used_test_suite << "."
    510                  << state.first_used_test << ")";
    511      }
    512      std::cout << " should be deleted but never is. Its address is @"
    513                << it->first << ".";
    514      leaked_count++;
    515    }
    516    if (leaked_count > 0) {
    517      std::cout << "\nERROR: " << leaked_count << " leaked mock "
    518                << (leaked_count == 1 ? "object" : "objects")
    519                << " found at program exit. Expectations on a mock object are "
    520                   "verified when the object is destructed. Leaking a mock "
    521                   "means that its expectations aren't verified, which is "
    522                   "usually a test bug. If you really intend to leak a mock, "
    523                   "you can suppress this error using "
    524                   "testing::Mock::AllowLeak(mock_object), or you may use a "
    525                   "fake or stub instead of a mock.\n";
    526      std::cout.flush();
    527      ::std::cerr.flush();
    528      // RUN_ALL_TESTS() has already returned when this destructor is
    529      // called.  Therefore we cannot use the normal Google Test
    530      // failure reporting mechanism.
    531 #ifdef GTEST_OS_QURT
    532      qurt_exception_raise_fatal();
    533 #else
    534      _Exit(1);  // We cannot call exit() as it is not reentrant and
    535                 // may already have been called.
    536 #endif
    537    }
    538  }
    539 
    540  StateMap& states() { return states_; }
    541 
    542 private:
    543  StateMap states_;
    544 };
    545 
    546 // Protected by g_gmock_mutex.
    547 MockObjectRegistry g_mock_object_registry;
    548 
    549 // Maps a mock object to the reaction Google Mock should have when an
    550 // uninteresting method is called.  Protected by g_gmock_mutex.
    551 std::unordered_map<uintptr_t, internal::CallReaction>&
    552 UninterestingCallReactionMap() {
    553  static auto* map = new std::unordered_map<uintptr_t, internal::CallReaction>;
    554  return *map;
    555 }
    556 
    557 // Sets the reaction Google Mock should have when an uninteresting
    558 // method of the given mock object is called.
    559 void SetReactionOnUninterestingCalls(uintptr_t mock_obj,
    560                                     internal::CallReaction reaction)
    561    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
    562  internal::MutexLock l(&internal::g_gmock_mutex);
    563  UninterestingCallReactionMap()[mock_obj] = reaction;
    564 }
    565 
    566 }  // namespace
    567 
    568 // Tells Google Mock to allow uninteresting calls on the given mock
    569 // object.
    570 void Mock::AllowUninterestingCalls(uintptr_t mock_obj)
    571    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
    572  SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
    573 }
    574 
    575 // Tells Google Mock to warn the user about uninteresting calls on the
    576 // given mock object.
    577 void Mock::WarnUninterestingCalls(uintptr_t mock_obj)
    578    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
    579  SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
    580 }
    581 
    582 // Tells Google Mock to fail uninteresting calls on the given mock
    583 // object.
    584 void Mock::FailUninterestingCalls(uintptr_t mock_obj)
    585    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
    586  SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
    587 }
    588 
    589 // Tells Google Mock the given mock object is being destroyed and its
    590 // entry in the call-reaction table should be removed.
    591 void Mock::UnregisterCallReaction(uintptr_t mock_obj)
    592    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
    593  internal::MutexLock l(&internal::g_gmock_mutex);
    594  UninterestingCallReactionMap().erase(static_cast<uintptr_t>(mock_obj));
    595 }
    596 
    597 // Returns the reaction Google Mock will have on uninteresting calls
    598 // made on the given mock object.
    599 internal::CallReaction Mock::GetReactionOnUninterestingCalls(
    600    const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
    601  internal::MutexLock l(&internal::g_gmock_mutex);
    602  return (UninterestingCallReactionMap().count(
    603              reinterpret_cast<uintptr_t>(mock_obj)) == 0)
    604             ? internal::intToCallReaction(
    605                   GMOCK_FLAG_GET(default_mock_behavior))
    606             : UninterestingCallReactionMap()[reinterpret_cast<uintptr_t>(
    607                   mock_obj)];
    608 }
    609 
    610 // Tells Google Mock to ignore mock_obj when checking for leaked mock
    611 // objects.
    612 void Mock::AllowLeak(const void* mock_obj)
    613    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
    614  internal::MutexLock l(&internal::g_gmock_mutex);
    615  g_mock_object_registry.states()[mock_obj].leakable = true;
    616 }
    617 
    618 // Verifies and clears all expectations on the given mock object.  If
    619 // the expectations aren't satisfied, generates one or more Google
    620 // Test non-fatal failures and returns false.
    621 bool Mock::VerifyAndClearExpectations(void* mock_obj)
    622    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
    623  internal::MutexLock l(&internal::g_gmock_mutex);
    624  return VerifyAndClearExpectationsLocked(mock_obj);
    625 }
    626 
    627 // Verifies all expectations on the given mock object and clears its
    628 // default actions and expectations.  Returns true if and only if the
    629 // verification was successful.
    630 bool Mock::VerifyAndClear(void* mock_obj)
    631    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
    632  internal::MutexLock l(&internal::g_gmock_mutex);
    633  ClearDefaultActionsLocked(mock_obj);
    634  return VerifyAndClearExpectationsLocked(mock_obj);
    635 }
    636 
    637 // Verifies and clears all expectations on the given mock object.  If
    638 // the expectations aren't satisfied, generates one or more Google
    639 // Test non-fatal failures and returns false.
    640 bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
    641    GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
    642  internal::g_gmock_mutex.AssertHeld();
    643  if (g_mock_object_registry.states().count(mock_obj) == 0) {
    644    // No EXPECT_CALL() was set on the given mock object.
    645    return true;
    646  }
    647 
    648  // Verifies and clears the expectations on each mock method in the
    649  // given mock object.
    650  bool expectations_met = true;
    651  FunctionMockers& mockers =
    652      g_mock_object_registry.states()[mock_obj].function_mockers;
    653  for (FunctionMockers::const_iterator it = mockers.begin();
    654       it != mockers.end(); ++it) {
    655    if (!(*it)->VerifyAndClearExpectationsLocked()) {
    656      expectations_met = false;
    657    }
    658  }
    659 
    660  // We don't clear the content of mockers, as they may still be
    661  // needed by ClearDefaultActionsLocked().
    662  return expectations_met;
    663 }
    664 
    665 bool Mock::IsNaggy(void* mock_obj)
    666    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
    667  return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kWarn;
    668 }
    669 bool Mock::IsNice(void* mock_obj)
    670    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
    671  return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kAllow;
    672 }
    673 bool Mock::IsStrict(void* mock_obj)
    674    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
    675  return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kFail;
    676 }
    677 
    678 // Registers a mock object and a mock method it owns.
    679 void Mock::Register(const void* mock_obj,
    680                    internal::UntypedFunctionMockerBase* mocker)
    681    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
    682  internal::MutexLock l(&internal::g_gmock_mutex);
    683  g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
    684 }
    685 
    686 // Tells Google Mock where in the source code mock_obj is used in an
    687 // ON_CALL or EXPECT_CALL.  In case mock_obj is leaked, this
    688 // information helps the user identify which object it is.
    689 void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
    690                                           const char* file, int line)
    691    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
    692  internal::MutexLock l(&internal::g_gmock_mutex);
    693  MockObjectState& state = g_mock_object_registry.states()[mock_obj];
    694  if (state.first_used_file == nullptr) {
    695    state.first_used_file = file;
    696    state.first_used_line = line;
    697    const TestInfo* const test_info =
    698        UnitTest::GetInstance()->current_test_info();
    699    if (test_info != nullptr) {
    700      state.first_used_test_suite = test_info->test_suite_name();
    701      state.first_used_test = test_info->name();
    702    }
    703  }
    704 }
    705 
    706 // Unregisters a mock method; removes the owning mock object from the
    707 // registry when the last mock method associated with it has been
    708 // unregistered.  This is called only in the destructor of
    709 // FunctionMockerBase.
    710 void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
    711    GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
    712  internal::g_gmock_mutex.AssertHeld();
    713  for (MockObjectRegistry::StateMap::iterator it =
    714           g_mock_object_registry.states().begin();
    715       it != g_mock_object_registry.states().end(); ++it) {
    716    FunctionMockers& mockers = it->second.function_mockers;
    717    if (mockers.erase(mocker) > 0) {
    718      // mocker was in mockers and has been just removed.
    719      if (mockers.empty()) {
    720        g_mock_object_registry.states().erase(it);
    721      }
    722      return;
    723    }
    724  }
    725 }
    726 
    727 // Clears all ON_CALL()s set on the given mock object.
    728 void Mock::ClearDefaultActionsLocked(void* mock_obj)
    729    GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
    730  internal::g_gmock_mutex.AssertHeld();
    731 
    732  if (g_mock_object_registry.states().count(mock_obj) == 0) {
    733    // No ON_CALL() was set on the given mock object.
    734    return;
    735  }
    736 
    737  // Clears the default actions for each mock method in the given mock
    738  // object.
    739  FunctionMockers& mockers =
    740      g_mock_object_registry.states()[mock_obj].function_mockers;
    741  for (FunctionMockers::const_iterator it = mockers.begin();
    742       it != mockers.end(); ++it) {
    743    (*it)->ClearDefaultActionsLocked();
    744  }
    745 
    746  // We don't clear the content of mockers, as they may still be
    747  // needed by VerifyAndClearExpectationsLocked().
    748 }
    749 
    750 Expectation::Expectation() = default;
    751 
    752 Expectation::Expectation(
    753    const std::shared_ptr<internal::ExpectationBase>& an_expectation_base)
    754    : expectation_base_(an_expectation_base) {}
    755 
    756 Expectation::~Expectation() = default;
    757 
    758 // Adds an expectation to a sequence.
    759 void Sequence::AddExpectation(const Expectation& expectation) const {
    760  if (*last_expectation_ != expectation) {
    761    if (last_expectation_->expectation_base() != nullptr) {
    762      expectation.expectation_base()->immediate_prerequisites_ +=
    763          *last_expectation_;
    764    }
    765    *last_expectation_ = expectation;
    766  }
    767 }
    768 
    769 // Creates the implicit sequence if there isn't one.
    770 InSequence::InSequence() {
    771  if (internal::g_gmock_implicit_sequence.get() == nullptr) {
    772    internal::g_gmock_implicit_sequence.set(new Sequence);
    773    sequence_created_ = true;
    774  } else {
    775    sequence_created_ = false;
    776  }
    777 }
    778 
    779 // Deletes the implicit sequence if it was created by the constructor
    780 // of this object.
    781 InSequence::~InSequence() {
    782  if (sequence_created_) {
    783    delete internal::g_gmock_implicit_sequence.get();
    784    internal::g_gmock_implicit_sequence.set(nullptr);
    785  }
    786 }
    787 
    788 }  // namespace testing
    789 
    790 #if defined(_MSC_VER) && (_MSC_VER == 1900)
    791 GTEST_DISABLE_MSC_WARNINGS_POP_()  // 4800
    792 #endif