792 lines · plain
1// Copyright 2007, Google Inc.2// All rights reserved.3//4// Redistribution and use in source and binary forms, with or without5// modification, are permitted provided that the following conditions are6// met:7//8// * Redistributions of source code must retain the above copyright9// notice, this list of conditions and the following disclaimer.10// * Redistributions in binary form must reproduce the above11// copyright notice, this list of conditions and the following disclaimer12// in the documentation and/or other materials provided with the13// distribution.14// * Neither the name of Google Inc. nor the names of its15// contributors may be used to endorse or promote products derived from16// this software without specific prior written permission.17//18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE28// 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 and33// EXPECT_CALL).34 35#include "gmock/gmock-spec-builders.h"36 37#include <stdlib.h>38 39#include <iostream> // NOLINT40#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> // NOLINT54#endif55#ifdef GTEST_OS_QURT56#include <qurt_event.h>57#endif58 59// Silence C4800 (C4800: 'int *const ': forcing value60// to bool 'true' or 'false') for MSVC 1561#if defined(_MSC_VER) && (_MSC_VER == 1900)62GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800)63#endif64 65namespace testing {66namespace internal {67 68// Protects the mock object registry (in class Mock), all function69// mockers, and all expectations.70GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);71 72// Logs a message including file and line number information.73GTEST_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) << " " << message78 << ::std::endl;79 Log(severity, s.str(), 0);80}81 82// Constructs an ExpectationBase object.83ExpectationBase::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.99ExpectationBase::~ExpectationBase() = default;100 101// Explicitly specifies the cardinality of this expectation. Used by102// the subclasses to implement the .Times() clause.103void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {104 cardinality_specified_ = true;105 cardinality_ = a_cardinality;106}107 108// Retires all pre-requisites of this expectation.109void 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 expectation113 // 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 expectation135// have been satisfied.136bool ExpectationBase::AllPrerequisitesAreSatisfied() const137 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'.156void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const157 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 its171 // 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 interested177 // in whether its pre-requisites are satisfied. Therefore we178 // don't iterate into it here.179 *result += *it;180 }181 }182 }183}184 185// Describes how many times a function call matching this186// expectation has occurred.187void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const188 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() and208// WillRepeatedly() clauses) against the cardinality if this hasn't209// been done before. Prints a warning if there are too many or too210// few actions.211void ExpectationBase::CheckActionCountIfNotDone() const212 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 action225 // 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 false234 // 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_count252 << " 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.262void 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 InSequence279// object (if any) in the current thread or NULL.280GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;281 282// Reports an uninteresting call (whose description is in msg) in the283// manner specified by 'reaction'.284void 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 blindly 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: // FAIL305 Expect(false, nullptr, -1, msg);306 }307}308 309UntypedFunctionMockerBase::UntypedFunctionMockerBase()310 : mock_obj_(nullptr), name_("") {}311 312UntypedFunctionMockerBase::~UntypedFunctionMockerBase() = default;313 314// Sets the mock object this mock method belongs to, and registers315// this information in the global mock registry. Will be called316// whenever an EXPECT_CALL() or ON_CALL() is executed on this mock317// method.318void 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 name328// of the mock function. Will be called upon each invocation of this329// mock function.330void 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 function334 // 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 called341// after RegisterOwner() or SetOwnerAndName() has been called.342const void* UntypedFunctionMockerBase::MockObject() const343 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {344 const void* mock_obj;345 {346 // We protect mock_obj_ under g_gmock_mutex in case this mock347 // 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 after358// SetOwnerAndName() has been called.359const char* UntypedFunctionMockerBase::Name() const360 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {361 const char* name;362 {363 // We protect name_ under g_gmock_mutex in case this mock364 // 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.376Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {377 // See the definition of untyped_expectations_ for why access to it378 // 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 will389 // never be executed.390}391 392// Verifies that all expectations on this mock function have been393// satisfied. Reports one or more Google Test non-fatal failures394// and returns false if not.395bool 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 was404 // already reported when it occurred, there is no need to do405 // 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 expectation420 // in the description, as the Expect() call that follows already421 // 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, for430 // example if an action contains a reference counted smart pointer to that431 // mock object, and that is the last reference. So if we delete our432 // expectations within the context of the global mutex we may deadlock when433 // this method is called again. Instead, make a copy of the set of434 // expectations to delete, clear our set within the mutex, and then clear the435 // 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 446static 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 internal454 455// Class Mock.456 457namespace {458 459typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;460 461// The current state of a mock object. Such information is needed for462// detecting leaked mock objects and explicitly verifying a mock's463// expectations.464struct 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 first469 // 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 are479// alive. A mock object is added to this registry the first time480// Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It481// is removed from the registry in the mock object's destructor.482class 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 all488 // tests in it have been run. By then, there should be no mock489 // object alive. Therefore we report any living object as test490 // failure, unless the user explicitly asked us to ignore it.491 ~MockObjectRegistry() {492 if (!GMOCK_FLAG_GET(catch_leaked_mocks)) return;493 494 int leaked_count = 0;495 for (StateMap::const_iterator it = states_.begin(); it != states_.end();496 ++it) {497 if (it->second.leakable) // The user said it's fine to leak this object.498 continue;499 500 // FIXME: Print the type of the leaked object.501 // This can help the user identify the leaked object.502 std::cout << "\n";503 const MockObjectState& state = it->second;504 std::cout << internal::FormatFileLocation(state.first_used_file,505 state.first_used_line);506 std::cout << " ERROR: this mock object";507 if (!state.first_used_test.empty()) {508 std::cout << " (used in test " << state.first_used_test_suite << "."509 << state.first_used_test << ")";510 }511 std::cout << " should be deleted but never is. Its address is @"512 << it->first << ".";513 leaked_count++;514 }515 if (leaked_count > 0) {516 std::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";525 std::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_QURT531 qurt_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 }538 539 StateMap& states() { return states_; }540 541 private:542 StateMap states_;543};544 545// Protected by g_gmock_mutex.546MockObjectRegistry g_mock_object_registry;547 548// 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() {552 static auto* map = new std::unordered_map<uintptr_t, internal::CallReaction>;553 return *map;554}555 556// Sets the reaction Google Mock should have when an uninteresting557// method of the given mock object is called.558void SetReactionOnUninterestingCalls(uintptr_t mock_obj,559 internal::CallReaction reaction)560 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {561 internal::MutexLock l(&internal::g_gmock_mutex);562 UninterestingCallReactionMap()[mock_obj] = reaction;563}564 565} // namespace566 567// Tells Google Mock to allow uninteresting calls on the given mock568// object.569void Mock::AllowUninterestingCalls(uintptr_t mock_obj)570 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {571 SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);572}573 574// Tells Google Mock to warn the user about uninteresting calls on the575// given mock object.576void Mock::WarnUninterestingCalls(uintptr_t mock_obj)577 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {578 SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);579}580 581// Tells Google Mock to fail uninteresting calls on the given mock582// object.583void Mock::FailUninterestingCalls(uintptr_t mock_obj)584 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {585 SetReactionOnUninterestingCalls(mock_obj, internal::kFail);586}587 588// 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)591 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {592 internal::MutexLock l(&internal::g_gmock_mutex);593 UninterestingCallReactionMap().erase(static_cast<uintptr_t>(mock_obj));594}595 596// Returns the reaction Google Mock will have on uninteresting calls597// made on the given mock object.598internal::CallReaction Mock::GetReactionOnUninterestingCalls(599 const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {600 internal::MutexLock l(&internal::g_gmock_mutex);601 return (UninterestingCallReactionMap().count(602 reinterpret_cast<uintptr_t>(mock_obj)) == 0)603 ? internal::intToCallReaction(604 GMOCK_FLAG_GET(default_mock_behavior))605 : UninterestingCallReactionMap()[reinterpret_cast<uintptr_t>(606 mock_obj)];607}608 609// Tells Google Mock to ignore mock_obj when checking for leaked mock610// objects.611void Mock::AllowLeak(const void* mock_obj)612 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {613 internal::MutexLock l(&internal::g_gmock_mutex);614 g_mock_object_registry.states()[mock_obj].leakable = true;615}616 617// 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)621 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {622 internal::MutexLock l(&internal::g_gmock_mutex);623 return VerifyAndClearExpectationsLocked(mock_obj);624}625 626// 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)630 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {631 internal::MutexLock l(&internal::g_gmock_mutex);632 ClearDefaultActionsLocked(mock_obj);633 return VerifyAndClearExpectationsLocked(mock_obj);634}635 636// 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)640 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {641 internal::g_gmock_mutex.AssertHeld();642 if (g_mock_object_registry.states().count(mock_obj) == 0) {643 // No EXPECT_CALL() was set on the given mock object.644 return true;645 }646 647 // Verifies and clears the expectations on each mock method in the648 // given mock object.649 bool expectations_met = true;650 FunctionMockers& mockers =651 g_mock_object_registry.states()[mock_obj].function_mockers;652 for (FunctionMockers::const_iterator it = mockers.begin();653 it != mockers.end(); ++it) {654 if (!(*it)->VerifyAndClearExpectationsLocked()) {655 expectations_met = false;656 }657 }658 659 // We don't clear the content of mockers, as they may still be660 // needed by ClearDefaultActionsLocked().661 return expectations_met;662}663 664bool Mock::IsNaggy(void* mock_obj)665 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {666 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kWarn;667}668bool Mock::IsNice(void* mock_obj)669 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {670 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kAllow;671}672bool Mock::IsStrict(void* mock_obj)673 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {674 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kFail;675}676 677// Registers a mock object and a mock method it owns.678void Mock::Register(const void* mock_obj,679 internal::UntypedFunctionMockerBase* mocker)680 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {681 internal::MutexLock l(&internal::g_gmock_mutex);682 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);683}684 685// 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,689 const char* file, int line)690 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {691 internal::MutexLock l(&internal::g_gmock_mutex);692 MockObjectState& state = g_mock_object_registry.states()[mock_obj];693 if (state.first_used_file == nullptr) {694 state.first_used_file = file;695 state.first_used_line = line;696 const TestInfo* const test_info =697 UnitTest::GetInstance()->current_test_info();698 if (test_info != nullptr) {699 state.first_used_test_suite = test_info->test_suite_name();700 state.first_used_test = test_info->name();701 }702 }703}704 705// 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)710 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {711 internal::g_gmock_mutex.AssertHeld();712 for (MockObjectRegistry::StateMap::iterator it =713 g_mock_object_registry.states().begin();714 it != g_mock_object_registry.states().end(); ++it) {715 FunctionMockers& mockers = it->second.function_mockers;716 if (mockers.erase(mocker) > 0) {717 // mocker was in mockers and has been just removed.718 if (mockers.empty()) {719 g_mock_object_registry.states().erase(it);720 }721 return;722 }723 }724}725 726// Clears all ON_CALL()s set on the given mock object.727void Mock::ClearDefaultActionsLocked(void* mock_obj)728 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {729 internal::g_gmock_mutex.AssertHeld();730 731 if (g_mock_object_registry.states().count(mock_obj) == 0) {732 // No ON_CALL() was set on the given mock object.733 return;734 }735 736 // Clears the default actions for each mock method in the given mock737 // object.738 FunctionMockers& mockers =739 g_mock_object_registry.states()[mock_obj].function_mockers;740 for (FunctionMockers::const_iterator it = mockers.begin();741 it != mockers.end(); ++it) {742 (*it)->ClearDefaultActionsLocked();743 }744 745 // We don't clear the content of mockers, as they may still be746 // needed by VerifyAndClearExpectationsLocked().747}748 749Expectation::Expectation() = default;750 751Expectation::Expectation(752 const std::shared_ptr<internal::ExpectationBase>& an_expectation_base)753 : expectation_base_(an_expectation_base) {}754 755Expectation::~Expectation() = default;756 757// Adds an expectation to a sequence.758void Sequence::AddExpectation(const Expectation& expectation) const {759 if (*last_expectation_ != expectation) {760 if (last_expectation_->expectation_base() != nullptr) {761 expectation.expectation_base()->immediate_prerequisites_ +=762 *last_expectation_;763 }764 *last_expectation_ = expectation;765 }766}767 768// Creates the implicit sequence if there isn't one.769InSequence::InSequence() {770 if (internal::g_gmock_implicit_sequence.get() == nullptr) {771 internal::g_gmock_implicit_sequence.set(new Sequence);772 sequence_created_ = true;773 } else {774 sequence_created_ = false;775 }776}777 778// Deletes the implicit sequence if it was created by the constructor779// of this object.780InSequence::~InSequence() {781 if (sequence_created_) {782 delete internal::g_gmock_implicit_sequence.get();783 internal::g_gmock_implicit_sequence.set(nullptr);784 }785}786 787} // namespace testing788 789#if defined(_MSC_VER) && (_MSC_VER == 1900)790GTEST_DISABLE_MSC_WARNINGS_POP_() // 4800791#endif792