Path: blob/main/contrib/googletest/googlemock/src/gmock-spec-builders.cc
48255 views
// Copyright 2007, Google Inc.1// All rights reserved.2//3// Redistribution and use in source and binary forms, with or without4// modification, are permitted provided that the following conditions are5// met:6//7// * Redistributions of source code must retain the above copyright8// notice, this list of conditions and the following disclaimer.9// * Redistributions in binary form must reproduce the above10// copyright notice, this list of conditions and the following disclaimer11// in the documentation and/or other materials provided with the12// distribution.13// * Neither the name of Google Inc. nor the names of its14// contributors may be used to endorse or promote products derived from15// this software without specific prior written permission.16//17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2829// Google Mock - a framework for writing C++ mock classes.30//31// This file implements the spec builder syntax (ON_CALL and32// EXPECT_CALL).3334#include "gmock/gmock-spec-builders.h"3536#include <stdlib.h>3738#include <iostream> // NOLINT39#include <map>40#include <memory>41#include <set>42#include <sstream>43#include <string>44#include <unordered_map>45#include <vector>4647#include "gmock/gmock.h"48#include "gtest/gtest.h"49#include "gtest/internal/gtest-port.h"5051#if defined(GTEST_OS_CYGWIN) || defined(GTEST_OS_LINUX) || defined(GTEST_OS_MAC)52#include <unistd.h> // NOLINT53#endif54#ifdef GTEST_OS_QURT55#include <qurt_event.h>56#endif5758// Silence C4800 (C4800: 'int *const ': forcing value59// to bool 'true' or 'false') for MSVC 1560#if defined(_MSC_VER) && (_MSC_VER == 1900)61GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800)62#endif6364namespace testing {65namespace internal {6667// Protects the mock object registry (in class Mock), all function68// mockers, and all expectations.69GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);7071// Logs a message including file and line number information.72GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,73const char* file, int line,74const std::string& message) {75::std::ostringstream s;76s << internal::FormatFileLocation(file, line) << " " << message77<< ::std::endl;78Log(severity, s.str(), 0);79}8081// Constructs an ExpectationBase object.82ExpectationBase::ExpectationBase(const char* a_file, int a_line,83const std::string& a_source_text)84: file_(a_file),85line_(a_line),86source_text_(a_source_text),87cardinality_specified_(false),88cardinality_(Exactly(1)),89call_count_(0),90retired_(false),91extra_matcher_specified_(false),92repeated_action_specified_(false),93retires_on_saturation_(false),94last_clause_(kNone),95action_count_checked_(false) {}9697// Destructs an ExpectationBase object.98ExpectationBase::~ExpectationBase() = default;99100// Explicitly specifies the cardinality of this expectation. Used by101// the subclasses to implement the .Times() clause.102void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {103cardinality_specified_ = true;104cardinality_ = a_cardinality;105}106107// Retires all pre-requisites of this expectation.108void ExpectationBase::RetireAllPreRequisites()109GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {110if (is_retired()) {111// We can take this short-cut as we never retire an expectation112// until we have retired all its pre-requisites.113return;114}115116::std::vector<ExpectationBase*> expectations(1, this);117while (!expectations.empty()) {118ExpectationBase* exp = expectations.back();119expectations.pop_back();120121for (ExpectationSet::const_iterator it =122exp->immediate_prerequisites_.begin();123it != exp->immediate_prerequisites_.end(); ++it) {124ExpectationBase* next = it->expectation_base().get();125if (!next->is_retired()) {126next->Retire();127expectations.push_back(next);128}129}130}131}132133// Returns true if and only if all pre-requisites of this expectation134// have been satisfied.135bool ExpectationBase::AllPrerequisitesAreSatisfied() const136GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {137g_gmock_mutex.AssertHeld();138::std::vector<const ExpectationBase*> expectations(1, this);139while (!expectations.empty()) {140const ExpectationBase* exp = expectations.back();141expectations.pop_back();142143for (ExpectationSet::const_iterator it =144exp->immediate_prerequisites_.begin();145it != exp->immediate_prerequisites_.end(); ++it) {146const ExpectationBase* next = it->expectation_base().get();147if (!next->IsSatisfied()) return false;148expectations.push_back(next);149}150}151return true;152}153154// Adds unsatisfied pre-requisites of this expectation to 'result'.155void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const156GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {157g_gmock_mutex.AssertHeld();158::std::vector<const ExpectationBase*> expectations(1, this);159while (!expectations.empty()) {160const ExpectationBase* exp = expectations.back();161expectations.pop_back();162163for (ExpectationSet::const_iterator it =164exp->immediate_prerequisites_.begin();165it != exp->immediate_prerequisites_.end(); ++it) {166const ExpectationBase* next = it->expectation_base().get();167168if (next->IsSatisfied()) {169// If *it is satisfied and has a call count of 0, some of its170// pre-requisites may not be satisfied yet.171if (next->call_count_ == 0) {172expectations.push_back(next);173}174} else {175// Now that we know next is unsatisfied, we are not so interested176// in whether its pre-requisites are satisfied. Therefore we177// don't iterate into it here.178*result += *it;179}180}181}182}183184// Describes how many times a function call matching this185// expectation has occurred.186void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const187GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {188g_gmock_mutex.AssertHeld();189190// Describes how many times the function is expected to be called.191*os << " Expected: to be ";192cardinality().DescribeTo(os);193*os << "\n Actual: ";194Cardinality::DescribeActualCallCountTo(call_count(), os);195196// Describes the state of the expectation (e.g. is it satisfied?197// is it active?).198*os << " - "199<< (IsOverSaturated() ? "over-saturated"200: IsSaturated() ? "saturated"201: IsSatisfied() ? "satisfied"202: "unsatisfied")203<< " and " << (is_retired() ? "retired" : "active");204}205206// Checks the action count (i.e. the number of WillOnce() and207// WillRepeatedly() clauses) against the cardinality if this hasn't208// been done before. Prints a warning if there are too many or too209// few actions.210void ExpectationBase::CheckActionCountIfNotDone() const211GTEST_LOCK_EXCLUDED_(mutex_) {212bool should_check = false;213{214MutexLock l(&mutex_);215if (!action_count_checked_) {216action_count_checked_ = true;217should_check = true;218}219}220221if (should_check) {222if (!cardinality_specified_) {223// The cardinality was inferred - no need to check the action224// count against it.225return;226}227228// The cardinality was explicitly specified.229const int action_count = static_cast<int>(untyped_actions_.size());230const int upper_bound = cardinality().ConservativeUpperBound();231const int lower_bound = cardinality().ConservativeLowerBound();232bool too_many; // True if there are too many actions, or false233// if there are too few.234if (action_count > upper_bound ||235(action_count == upper_bound && repeated_action_specified_)) {236too_many = true;237} else if (0 < action_count && action_count < lower_bound &&238!repeated_action_specified_) {239too_many = false;240} else {241return;242}243244::std::stringstream ss;245DescribeLocationTo(&ss);246ss << "Too " << (too_many ? "many" : "few") << " actions specified in "247<< source_text() << "...\n"248<< "Expected to be ";249cardinality().DescribeTo(&ss);250ss << ", but has " << (too_many ? "" : "only ") << action_count251<< " WillOnce()" << (action_count == 1 ? "" : "s");252if (repeated_action_specified_) {253ss << " and a WillRepeatedly()";254}255ss << ".";256Log(kWarning, ss.str(), -1); // -1 means "don't print stack trace".257}258}259260// Implements the .Times() clause.261void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {262if (last_clause_ == kTimes) {263ExpectSpecProperty(false,264".Times() cannot appear "265"more than once in an EXPECT_CALL().");266} else {267ExpectSpecProperty(268last_clause_ < kTimes,269".Times() may only appear *before* .InSequence(), .WillOnce(), "270".WillRepeatedly(), or .RetiresOnSaturation(), not after.");271}272last_clause_ = kTimes;273274SpecifyCardinality(a_cardinality);275}276277// Points to the implicit sequence introduced by a living InSequence278// object (if any) in the current thread or NULL.279GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;280281// Reports an uninteresting call (whose description is in msg) in the282// manner specified by 'reaction'.283void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {284// Include a stack trace only if --gmock_verbose=info is specified.285const int stack_frames_to_skip =286GMOCK_FLAG_GET(verbose) == kInfoVerbosity ? 3 : -1;287switch (reaction) {288case kAllow:289Log(kInfo, msg, stack_frames_to_skip);290break;291case kWarn:292Log(kWarning,293msg +294"\nNOTE: You can safely ignore the above warning unless this "295"call should not happen. Do not suppress it by blindly adding "296"an EXPECT_CALL() if you don't mean to enforce the call. "297"See "298"https://github.com/google/googletest/blob/main/docs/"299"gmock_cook_book.md#"300"knowing-when-to-expect-useoncall for details.\n",301stack_frames_to_skip);302break;303default: // FAIL304Expect(false, nullptr, -1, msg);305}306}307308UntypedFunctionMockerBase::UntypedFunctionMockerBase()309: mock_obj_(nullptr), name_("") {}310311UntypedFunctionMockerBase::~UntypedFunctionMockerBase() = default;312313// Sets the mock object this mock method belongs to, and registers314// this information in the global mock registry. Will be called315// whenever an EXPECT_CALL() or ON_CALL() is executed on this mock316// method.317void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)318GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {319{320MutexLock l(&g_gmock_mutex);321mock_obj_ = mock_obj;322}323Mock::Register(mock_obj, this);324}325326// Sets the mock object this mock method belongs to, and sets the name327// of the mock function. Will be called upon each invocation of this328// mock function.329void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,330const char* name)331GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {332// We protect name_ under g_gmock_mutex in case this mock function333// is called from two threads concurrently.334MutexLock l(&g_gmock_mutex);335mock_obj_ = mock_obj;336name_ = name;337}338339// Returns the name of the function being mocked. Must be called340// after RegisterOwner() or SetOwnerAndName() has been called.341const void* UntypedFunctionMockerBase::MockObject() const342GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {343const void* mock_obj;344{345// We protect mock_obj_ under g_gmock_mutex in case this mock346// function is called from two threads concurrently.347MutexLock l(&g_gmock_mutex);348Assert(mock_obj_ != nullptr, __FILE__, __LINE__,349"MockObject() must not be called before RegisterOwner() or "350"SetOwnerAndName() has been called.");351mock_obj = mock_obj_;352}353return mock_obj;354}355356// Returns the name of this mock method. Must be called after357// SetOwnerAndName() has been called.358const char* UntypedFunctionMockerBase::Name() const359GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {360const char* name;361{362// We protect name_ under g_gmock_mutex in case this mock363// function is called from two threads concurrently.364MutexLock l(&g_gmock_mutex);365Assert(name_ != nullptr, __FILE__, __LINE__,366"Name() must not be called before SetOwnerAndName() has "367"been called.");368name = name_;369}370return name;371}372373// Returns an Expectation object that references and co-owns exp,374// which must be an expectation on this mock function.375Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {376// See the definition of untyped_expectations_ for why access to it377// is unprotected here.378for (UntypedExpectations::const_iterator it = untyped_expectations_.begin();379it != untyped_expectations_.end(); ++it) {380if (it->get() == exp) {381return Expectation(*it);382}383}384385Assert(false, __FILE__, __LINE__, "Cannot find expectation.");386return Expectation();387// The above statement is just to make the code compile, and will388// never be executed.389}390391// Verifies that all expectations on this mock function have been392// satisfied. Reports one or more Google Test non-fatal failures393// and returns false if not.394bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()395GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {396g_gmock_mutex.AssertHeld();397bool expectations_met = true;398for (UntypedExpectations::const_iterator it = untyped_expectations_.begin();399it != untyped_expectations_.end(); ++it) {400ExpectationBase* const untyped_expectation = it->get();401if (untyped_expectation->IsOverSaturated()) {402// There was an upper-bound violation. Since the error was403// already reported when it occurred, there is no need to do404// anything here.405expectations_met = false;406} else if (!untyped_expectation->IsSatisfied()) {407expectations_met = false;408::std::stringstream ss;409410const ::std::string& expectation_name =411untyped_expectation->GetDescription();412ss << "Actual function ";413if (!expectation_name.empty()) {414ss << "\"" << expectation_name << "\" ";415}416ss << "call count doesn't match " << untyped_expectation->source_text()417<< "...\n";418// No need to show the source file location of the expectation419// in the description, as the Expect() call that follows already420// takes care of it.421untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);422untyped_expectation->DescribeCallCountTo(&ss);423Expect(false, untyped_expectation->file(), untyped_expectation->line(),424ss.str());425}426}427428// Deleting our expectations may trigger other mock objects to be deleted, for429// example if an action contains a reference counted smart pointer to that430// mock object, and that is the last reference. So if we delete our431// expectations within the context of the global mutex we may deadlock when432// this method is called again. Instead, make a copy of the set of433// expectations to delete, clear our set within the mutex, and then clear the434// copied set outside of it.435UntypedExpectations expectations_to_delete;436untyped_expectations_.swap(expectations_to_delete);437438g_gmock_mutex.Unlock();439expectations_to_delete.clear();440g_gmock_mutex.Lock();441442return expectations_met;443}444445static CallReaction intToCallReaction(int mock_behavior) {446if (mock_behavior >= kAllow && mock_behavior <= kFail) {447return static_cast<internal::CallReaction>(mock_behavior);448}449return kWarn;450}451452} // namespace internal453454// Class Mock.455456namespace {457458typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;459460// The current state of a mock object. Such information is needed for461// detecting leaked mock objects and explicitly verifying a mock's462// expectations.463struct MockObjectState {464MockObjectState()465: first_used_file(nullptr), first_used_line(-1), leakable(false) {}466467// Where in the source file an ON_CALL or EXPECT_CALL is first468// invoked on this mock object.469const char* first_used_file;470int first_used_line;471::std::string first_used_test_suite;472::std::string first_used_test;473bool leakable; // true if and only if it's OK to leak the object.474FunctionMockers function_mockers; // All registered methods of the object.475};476477// A global registry holding the state of all mock objects that are478// alive. A mock object is added to this registry the first time479// Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It480// is removed from the registry in the mock object's destructor.481class MockObjectRegistry {482public:483// Maps a mock object (identified by its address) to its state.484typedef std::map<const void*, MockObjectState> StateMap;485486// This destructor will be called when a program exits, after all487// tests in it have been run. By then, there should be no mock488// object alive. Therefore we report any living object as test489// failure, unless the user explicitly asked us to ignore it.490~MockObjectRegistry() {491if (!GMOCK_FLAG_GET(catch_leaked_mocks)) return;492internal::MutexLock l(&internal::g_gmock_mutex);493494int leaked_count = 0;495for (StateMap::const_iterator it = states_.begin(); it != states_.end();496++it) {497if (it->second.leakable) // The user said it's fine to leak this object.498continue;499500// FIXME: Print the type of the leaked object.501// This can help the user identify the leaked object.502std::cout << "\n";503const MockObjectState& state = it->second;504std::cout << internal::FormatFileLocation(state.first_used_file,505state.first_used_line);506std::cout << " ERROR: this mock object";507if (!state.first_used_test.empty()) {508std::cout << " (used in test " << state.first_used_test_suite << "."509<< state.first_used_test << ")";510}511std::cout << " should be deleted but never is. Its address is @"512<< it->first << ".";513leaked_count++;514}515if (leaked_count > 0) {516std::cout << "\nERROR: " << leaked_count << " leaked mock "517<< (leaked_count == 1 ? "object" : "objects")518<< " found at program exit. Expectations on a mock object are "519"verified when the object is destructed. Leaking a mock "520"means that its expectations aren't verified, which is "521"usually a test bug. If you really intend to leak a mock, "522"you can suppress this error using "523"testing::Mock::AllowLeak(mock_object), or you may use a "524"fake or stub instead of a mock.\n";525std::cout.flush();526::std::cerr.flush();527// RUN_ALL_TESTS() has already returned when this destructor is528// called. Therefore we cannot use the normal Google Test529// failure reporting mechanism.530#ifdef GTEST_OS_QURT531qurt_exception_raise_fatal();532#else533_Exit(1); // We cannot call exit() as it is not reentrant and534// may already have been called.535#endif536}537}538539StateMap& states() { return states_; }540541private:542StateMap states_;543};544545// Protected by g_gmock_mutex.546MockObjectRegistry g_mock_object_registry;547548// Maps a mock object to the reaction Google Mock should have when an549// uninteresting method is called. Protected by g_gmock_mutex.550std::unordered_map<uintptr_t, internal::CallReaction>&551UninterestingCallReactionMap() {552static auto* map = new std::unordered_map<uintptr_t, internal::CallReaction>;553return *map;554}555556// Sets the reaction Google Mock should have when an uninteresting557// method of the given mock object is called.558void SetReactionOnUninterestingCalls(uintptr_t mock_obj,559internal::CallReaction reaction)560GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {561internal::MutexLock l(&internal::g_gmock_mutex);562UninterestingCallReactionMap()[mock_obj] = reaction;563}564565} // namespace566567// Tells Google Mock to allow uninteresting calls on the given mock568// object.569void Mock::AllowUninterestingCalls(uintptr_t mock_obj)570GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {571SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);572}573574// Tells Google Mock to warn the user about uninteresting calls on the575// given mock object.576void Mock::WarnUninterestingCalls(uintptr_t mock_obj)577GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {578SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);579}580581// Tells Google Mock to fail uninteresting calls on the given mock582// object.583void Mock::FailUninterestingCalls(uintptr_t mock_obj)584GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {585SetReactionOnUninterestingCalls(mock_obj, internal::kFail);586}587588// Tells Google Mock the given mock object is being destroyed and its589// entry in the call-reaction table should be removed.590void Mock::UnregisterCallReaction(uintptr_t mock_obj)591GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {592internal::MutexLock l(&internal::g_gmock_mutex);593UninterestingCallReactionMap().erase(static_cast<uintptr_t>(mock_obj));594}595596// Returns the reaction Google Mock will have on uninteresting calls597// made on the given mock object.598internal::CallReaction Mock::GetReactionOnUninterestingCalls(599const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {600internal::MutexLock l(&internal::g_gmock_mutex);601return (UninterestingCallReactionMap().count(602reinterpret_cast<uintptr_t>(mock_obj)) == 0)603? internal::intToCallReaction(604GMOCK_FLAG_GET(default_mock_behavior))605: UninterestingCallReactionMap()[reinterpret_cast<uintptr_t>(606mock_obj)];607}608609// Tells Google Mock to ignore mock_obj when checking for leaked mock610// objects.611void Mock::AllowLeak(const void* mock_obj)612GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {613internal::MutexLock l(&internal::g_gmock_mutex);614g_mock_object_registry.states()[mock_obj].leakable = true;615}616617// Verifies and clears all expectations on the given mock object. If618// the expectations aren't satisfied, generates one or more Google619// Test non-fatal failures and returns false.620bool Mock::VerifyAndClearExpectations(void* mock_obj)621GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {622internal::MutexLock l(&internal::g_gmock_mutex);623return VerifyAndClearExpectationsLocked(mock_obj);624}625626// Verifies all expectations on the given mock object and clears its627// default actions and expectations. Returns true if and only if the628// verification was successful.629bool Mock::VerifyAndClear(void* mock_obj)630GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {631internal::MutexLock l(&internal::g_gmock_mutex);632ClearDefaultActionsLocked(mock_obj);633return VerifyAndClearExpectationsLocked(mock_obj);634}635636// Verifies and clears all expectations on the given mock object. If637// the expectations aren't satisfied, generates one or more Google638// Test non-fatal failures and returns false.639bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)640GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {641internal::g_gmock_mutex.AssertHeld();642if (g_mock_object_registry.states().count(mock_obj) == 0) {643// No EXPECT_CALL() was set on the given mock object.644return true;645}646647// Verifies and clears the expectations on each mock method in the648// given mock object.649bool expectations_met = true;650FunctionMockers& mockers =651g_mock_object_registry.states()[mock_obj].function_mockers;652for (FunctionMockers::const_iterator it = mockers.begin();653it != mockers.end(); ++it) {654if (!(*it)->VerifyAndClearExpectationsLocked()) {655expectations_met = false;656}657}658659// We don't clear the content of mockers, as they may still be660// needed by ClearDefaultActionsLocked().661return expectations_met;662}663664bool Mock::IsNaggy(void* mock_obj)665GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {666return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kWarn;667}668bool Mock::IsNice(void* mock_obj)669GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {670return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kAllow;671}672bool Mock::IsStrict(void* mock_obj)673GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {674return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kFail;675}676677// Registers a mock object and a mock method it owns.678void Mock::Register(const void* mock_obj,679internal::UntypedFunctionMockerBase* mocker)680GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {681internal::MutexLock l(&internal::g_gmock_mutex);682g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);683}684685// Tells Google Mock where in the source code mock_obj is used in an686// ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this687// information helps the user identify which object it is.688void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,689const char* file, int line)690GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {691internal::MutexLock l(&internal::g_gmock_mutex);692MockObjectState& state = g_mock_object_registry.states()[mock_obj];693if (state.first_used_file == nullptr) {694state.first_used_file = file;695state.first_used_line = line;696const TestInfo* const test_info =697UnitTest::GetInstance()->current_test_info();698if (test_info != nullptr) {699state.first_used_test_suite = test_info->test_suite_name();700state.first_used_test = test_info->name();701}702}703}704705// Unregisters a mock method; removes the owning mock object from the706// registry when the last mock method associated with it has been707// unregistered. This is called only in the destructor of708// FunctionMockerBase.709void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)710GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {711internal::g_gmock_mutex.AssertHeld();712for (MockObjectRegistry::StateMap::iterator it =713g_mock_object_registry.states().begin();714it != g_mock_object_registry.states().end(); ++it) {715FunctionMockers& mockers = it->second.function_mockers;716if (mockers.erase(mocker) > 0) {717// mocker was in mockers and has been just removed.718if (mockers.empty()) {719g_mock_object_registry.states().erase(it);720}721return;722}723}724}725726// Clears all ON_CALL()s set on the given mock object.727void Mock::ClearDefaultActionsLocked(void* mock_obj)728GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {729internal::g_gmock_mutex.AssertHeld();730731if (g_mock_object_registry.states().count(mock_obj) == 0) {732// No ON_CALL() was set on the given mock object.733return;734}735736// Clears the default actions for each mock method in the given mock737// object.738FunctionMockers& mockers =739g_mock_object_registry.states()[mock_obj].function_mockers;740for (FunctionMockers::const_iterator it = mockers.begin();741it != mockers.end(); ++it) {742(*it)->ClearDefaultActionsLocked();743}744745// We don't clear the content of mockers, as they may still be746// needed by VerifyAndClearExpectationsLocked().747}748749Expectation::Expectation() = default;750751Expectation::Expectation(752const std::shared_ptr<internal::ExpectationBase>& an_expectation_base)753: expectation_base_(an_expectation_base) {}754755Expectation::~Expectation() = default;756757// Adds an expectation to a sequence.758void Sequence::AddExpectation(const Expectation& expectation) const {759if (*last_expectation_ != expectation) {760if (last_expectation_->expectation_base() != nullptr) {761expectation.expectation_base()->immediate_prerequisites_ +=762*last_expectation_;763}764*last_expectation_ = expectation;765}766}767768// Creates the implicit sequence if there isn't one.769InSequence::InSequence() {770if (internal::g_gmock_implicit_sequence.get() == nullptr) {771internal::g_gmock_implicit_sequence.set(new Sequence);772sequence_created_ = true;773} else {774sequence_created_ = false;775}776}777778// Deletes the implicit sequence if it was created by the constructor779// of this object.780InSequence::~InSequence() {781if (sequence_created_) {782delete internal::g_gmock_implicit_sequence.get();783internal::g_gmock_implicit_sequence.set(nullptr);784}785}786787} // namespace testing788789#if defined(_MSC_VER) && (_MSC_VER == 1900)790GTEST_DISABLE_MSC_WARNINGS_POP_() // 4800791#endif792793794