Back to home page

sPhenix code displayed by LXR

 
 

    


File indexing completed on 2025-08-06 08:19:54

0001 // Copyright 2007, Google Inc.
0002 // All rights reserved.
0003 //
0004 // Redistribution and use in source and binary forms, with or without
0005 // modification, are permitted provided that the following conditions are
0006 // met:
0007 //
0008 //     * Redistributions of source code must retain the above copyright
0009 // notice, this list of conditions and the following disclaimer.
0010 //     * Redistributions in binary form must reproduce the above
0011 // copyright notice, this list of conditions and the following disclaimer
0012 // in the documentation and/or other materials provided with the
0013 // distribution.
0014 //     * Neither the name of Google Inc. nor the names of its
0015 // contributors may be used to endorse or promote products derived from
0016 // this software without specific prior written permission.
0017 //
0018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
0019 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
0020 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
0021 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
0022 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
0023 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
0024 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
0025 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
0026 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
0027 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
0028 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
0029 //
0030 // Author: wan@google.com (Zhanyong Wan)
0031 
0032 // Google Mock - a framework for writing C++ mock classes.
0033 //
0034 // This file implements the spec builder syntax (ON_CALL and
0035 // EXPECT_CALL).
0036 
0037 #include "gmock/gmock-spec-builders.h"
0038 
0039 #include <stdlib.h>
0040 #include <iostream>  // NOLINT
0041 #include <map>
0042 #include <set>
0043 #include <string>
0044 #include "gmock/gmock.h"
0045 #include "gtest/gtest.h"
0046 
0047 #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
0048 # include <unistd.h>  // NOLINT
0049 #endif
0050 
0051 namespace testing {
0052 namespace internal {
0053 
0054 // Protects the mock object registry (in class Mock), all function
0055 // mockers, and all expectations.
0056 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
0057 
0058 // Logs a message including file and line number information.
0059 GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
0060                                 const char* file, int line,
0061                                 const string& message) {
0062   ::std::ostringstream s;
0063   s << file << ":" << line << ": " << message << ::std::endl;
0064   Log(severity, s.str(), 0);
0065 }
0066 
0067 // Constructs an ExpectationBase object.
0068 ExpectationBase::ExpectationBase(const char* a_file,
0069                                  int a_line,
0070                                  const string& a_source_text)
0071     : file_(a_file),
0072       line_(a_line),
0073       source_text_(a_source_text),
0074       cardinality_specified_(false),
0075       cardinality_(Exactly(1)),
0076       call_count_(0),
0077       retired_(false),
0078       extra_matcher_specified_(false),
0079       repeated_action_specified_(false),
0080       retires_on_saturation_(false),
0081       last_clause_(kNone),
0082       action_count_checked_(false) {}
0083 
0084 // Destructs an ExpectationBase object.
0085 ExpectationBase::~ExpectationBase() {}
0086 
0087 // Explicitly specifies the cardinality of this expectation.  Used by
0088 // the subclasses to implement the .Times() clause.
0089 void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {
0090   cardinality_specified_ = true;
0091   cardinality_ = a_cardinality;
0092 }
0093 
0094 // Retires all pre-requisites of this expectation.
0095 void ExpectationBase::RetireAllPreRequisites()
0096     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
0097   if (is_retired()) {
0098     // We can take this short-cut as we never retire an expectation
0099     // until we have retired all its pre-requisites.
0100     return;
0101   }
0102 
0103   for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
0104        it != immediate_prerequisites_.end(); ++it) {
0105     ExpectationBase* const prerequisite = it->expectation_base().get();
0106     if (!prerequisite->is_retired()) {
0107       prerequisite->RetireAllPreRequisites();
0108       prerequisite->Retire();
0109     }
0110   }
0111 }
0112 
0113 // Returns true iff all pre-requisites of this expectation have been
0114 // satisfied.
0115 bool ExpectationBase::AllPrerequisitesAreSatisfied() const
0116     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
0117   g_gmock_mutex.AssertHeld();
0118   for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
0119        it != immediate_prerequisites_.end(); ++it) {
0120     if (!(it->expectation_base()->IsSatisfied()) ||
0121         !(it->expectation_base()->AllPrerequisitesAreSatisfied()))
0122       return false;
0123   }
0124   return true;
0125 }
0126 
0127 // Adds unsatisfied pre-requisites of this expectation to 'result'.
0128 void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const
0129     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
0130   g_gmock_mutex.AssertHeld();
0131   for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
0132        it != immediate_prerequisites_.end(); ++it) {
0133     if (it->expectation_base()->IsSatisfied()) {
0134       // If *it is satisfied and has a call count of 0, some of its
0135       // pre-requisites may not be satisfied yet.
0136       if (it->expectation_base()->call_count_ == 0) {
0137         it->expectation_base()->FindUnsatisfiedPrerequisites(result);
0138       }
0139     } else {
0140       // Now that we know *it is unsatisfied, we are not so interested
0141       // in whether its pre-requisites are satisfied.  Therefore we
0142       // don't recursively call FindUnsatisfiedPrerequisites() here.
0143       *result += *it;
0144     }
0145   }
0146 }
0147 
0148 // Describes how many times a function call matching this
0149 // expectation has occurred.
0150 void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
0151     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
0152   g_gmock_mutex.AssertHeld();
0153 
0154   // Describes how many times the function is expected to be called.
0155   *os << "         Expected: to be ";
0156   cardinality().DescribeTo(os);
0157   *os << "\n           Actual: ";
0158   Cardinality::DescribeActualCallCountTo(call_count(), os);
0159 
0160   // Describes the state of the expectation (e.g. is it satisfied?
0161   // is it active?).
0162   *os << " - " << (IsOverSaturated() ? "over-saturated" :
0163                    IsSaturated() ? "saturated" :
0164                    IsSatisfied() ? "satisfied" : "unsatisfied")
0165       << " and "
0166       << (is_retired() ? "retired" : "active");
0167 }
0168 
0169 // Checks the action count (i.e. the number of WillOnce() and
0170 // WillRepeatedly() clauses) against the cardinality if this hasn't
0171 // been done before.  Prints a warning if there are too many or too
0172 // few actions.
0173 void ExpectationBase::CheckActionCountIfNotDone() const
0174     GTEST_LOCK_EXCLUDED_(mutex_) {
0175   bool should_check = false;
0176   {
0177     MutexLock l(&mutex_);
0178     if (!action_count_checked_) {
0179       action_count_checked_ = true;
0180       should_check = true;
0181     }
0182   }
0183 
0184   if (should_check) {
0185     if (!cardinality_specified_) {
0186       // The cardinality was inferred - no need to check the action
0187       // count against it.
0188       return;
0189     }
0190 
0191     // The cardinality was explicitly specified.
0192     const int action_count = static_cast<int>(untyped_actions_.size());
0193     const int upper_bound = cardinality().ConservativeUpperBound();
0194     const int lower_bound = cardinality().ConservativeLowerBound();
0195     bool too_many;  // True if there are too many actions, or false
0196     // if there are too few.
0197     if (action_count > upper_bound ||
0198         (action_count == upper_bound && repeated_action_specified_)) {
0199       too_many = true;
0200     } else if (0 < action_count && action_count < lower_bound &&
0201                !repeated_action_specified_) {
0202       too_many = false;
0203     } else {
0204       return;
0205     }
0206 
0207     ::std::stringstream ss;
0208     DescribeLocationTo(&ss);
0209     ss << "Too " << (too_many ? "many" : "few")
0210        << " actions specified in " << source_text() << "...\n"
0211        << "Expected to be ";
0212     cardinality().DescribeTo(&ss);
0213     ss << ", but has " << (too_many ? "" : "only ")
0214        << action_count << " WillOnce()"
0215        << (action_count == 1 ? "" : "s");
0216     if (repeated_action_specified_) {
0217       ss << " and a WillRepeatedly()";
0218     }
0219     ss << ".";
0220     Log(kWarning, ss.str(), -1);  // -1 means "don't print stack trace".
0221   }
0222 }
0223 
0224 // Implements the .Times() clause.
0225 void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
0226   if (last_clause_ == kTimes) {
0227     ExpectSpecProperty(false,
0228                        ".Times() cannot appear "
0229                        "more than once in an EXPECT_CALL().");
0230   } else {
0231     ExpectSpecProperty(last_clause_ < kTimes,
0232                        ".Times() cannot appear after "
0233                        ".InSequence(), .WillOnce(), .WillRepeatedly(), "
0234                        "or .RetiresOnSaturation().");
0235   }
0236   last_clause_ = kTimes;
0237 
0238   SpecifyCardinality(a_cardinality);
0239 }
0240 
0241 // Points to the implicit sequence introduced by a living InSequence
0242 // object (if any) in the current thread or NULL.
0243 GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
0244 
0245 // Reports an uninteresting call (whose description is in msg) in the
0246 // manner specified by 'reaction'.
0247 void ReportUninterestingCall(CallReaction reaction, const string& msg) {
0248   // Include a stack trace only if --gmock_verbose=info is specified.
0249   const int stack_frames_to_skip =
0250       GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1;
0251   switch (reaction) {
0252     case kAllow:
0253       Log(kInfo, msg, stack_frames_to_skip);
0254       break;
0255     case kWarn:
0256       Log(kWarning,
0257           msg +
0258           "\nNOTE: You can safely ignore the above warning unless this "
0259           "call should not happen.  Do not suppress it by blindly adding "
0260           "an EXPECT_CALL() if you don't mean to enforce the call.  "
0261           "See https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#"
0262           "knowing-when-to-expect for details.\n",
0263           stack_frames_to_skip);
0264       break;
0265     default:  // FAIL
0266       Expect(false, NULL, -1, msg);
0267   }
0268 }
0269 
0270 UntypedFunctionMockerBase::UntypedFunctionMockerBase()
0271     : mock_obj_(NULL), name_("") {}
0272 
0273 UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
0274 
0275 // Sets the mock object this mock method belongs to, and registers
0276 // this information in the global mock registry.  Will be called
0277 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
0278 // method.
0279 void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
0280     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
0281   {
0282     MutexLock l(&g_gmock_mutex);
0283     mock_obj_ = mock_obj;
0284   }
0285   Mock::Register(mock_obj, this);
0286 }
0287 
0288 // Sets the mock object this mock method belongs to, and sets the name
0289 // of the mock function.  Will be called upon each invocation of this
0290 // mock function.
0291 void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
0292                                                 const char* name)
0293     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
0294   // We protect name_ under g_gmock_mutex in case this mock function
0295   // is called from two threads concurrently.
0296   MutexLock l(&g_gmock_mutex);
0297   mock_obj_ = mock_obj;
0298   name_ = name;
0299 }
0300 
0301 // Returns the name of the function being mocked.  Must be called
0302 // after RegisterOwner() or SetOwnerAndName() has been called.
0303 const void* UntypedFunctionMockerBase::MockObject() const
0304     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
0305   const void* mock_obj;
0306   {
0307     // We protect mock_obj_ under g_gmock_mutex in case this mock
0308     // function is called from two threads concurrently.
0309     MutexLock l(&g_gmock_mutex);
0310     Assert(mock_obj_ != NULL, __FILE__, __LINE__,
0311            "MockObject() must not be called before RegisterOwner() or "
0312            "SetOwnerAndName() has been called.");
0313     mock_obj = mock_obj_;
0314   }
0315   return mock_obj;
0316 }
0317 
0318 // Returns the name of this mock method.  Must be called after
0319 // SetOwnerAndName() has been called.
0320 const char* UntypedFunctionMockerBase::Name() const
0321     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
0322   const char* name;
0323   {
0324     // We protect name_ under g_gmock_mutex in case this mock
0325     // function is called from two threads concurrently.
0326     MutexLock l(&g_gmock_mutex);
0327     Assert(name_ != NULL, __FILE__, __LINE__,
0328            "Name() must not be called before SetOwnerAndName() has "
0329            "been called.");
0330     name = name_;
0331   }
0332   return name;
0333 }
0334 
0335 // Calculates the result of invoking this mock function with the given
0336 // arguments, prints it, and returns it.  The caller is responsible
0337 // for deleting the result.
0338 UntypedActionResultHolderBase*
0339 UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args)
0340     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
0341   if (untyped_expectations_.size() == 0) {
0342     // No expectation is set on this mock method - we have an
0343     // uninteresting call.
0344 
0345     // We must get Google Mock's reaction on uninteresting calls
0346     // made on this mock object BEFORE performing the action,
0347     // because the action may DELETE the mock object and make the
0348     // following expression meaningless.
0349     const CallReaction reaction =
0350         Mock::GetReactionOnUninterestingCalls(MockObject());
0351 
0352     // True iff we need to print this call's arguments and return
0353     // value.  This definition must be kept in sync with
0354     // the behavior of ReportUninterestingCall().
0355     const bool need_to_report_uninteresting_call =
0356         // If the user allows this uninteresting call, we print it
0357         // only when he wants informational messages.
0358         reaction == kAllow ? LogIsVisible(kInfo) :
0359         // If the user wants this to be a warning, we print it only
0360         // when he wants to see warnings.
0361         reaction == kWarn ? LogIsVisible(kWarning) :
0362         // Otherwise, the user wants this to be an error, and we
0363         // should always print detailed information in the error.
0364         true;
0365 
0366     if (!need_to_report_uninteresting_call) {
0367       // Perform the action without printing the call information.
0368       return this->UntypedPerformDefaultAction(untyped_args, "");
0369     }
0370 
0371     // Warns about the uninteresting call.
0372     ::std::stringstream ss;
0373     this->UntypedDescribeUninterestingCall(untyped_args, &ss);
0374 
0375     // Calculates the function result.
0376     UntypedActionResultHolderBase* const result =
0377         this->UntypedPerformDefaultAction(untyped_args, ss.str());
0378 
0379     // Prints the function result.
0380     if (result != NULL)
0381       result->PrintAsActionResult(&ss);
0382 
0383     ReportUninterestingCall(reaction, ss.str());
0384     return result;
0385   }
0386 
0387   bool is_excessive = false;
0388   ::std::stringstream ss;
0389   ::std::stringstream why;
0390   ::std::stringstream loc;
0391   const void* untyped_action = NULL;
0392 
0393   // The UntypedFindMatchingExpectation() function acquires and
0394   // releases g_gmock_mutex.
0395   const ExpectationBase* const untyped_expectation =
0396       this->UntypedFindMatchingExpectation(
0397           untyped_args, &untyped_action, &is_excessive,
0398           &ss, &why);
0399   const bool found = untyped_expectation != NULL;
0400 
0401   // True iff we need to print the call's arguments and return value.
0402   // This definition must be kept in sync with the uses of Expect()
0403   // and Log() in this function.
0404   const bool need_to_report_call =
0405       !found || is_excessive || LogIsVisible(kInfo);
0406   if (!need_to_report_call) {
0407     // Perform the action without printing the call information.
0408     return
0409         untyped_action == NULL ?
0410         this->UntypedPerformDefaultAction(untyped_args, "") :
0411         this->UntypedPerformAction(untyped_action, untyped_args);
0412   }
0413 
0414   ss << "    Function call: " << Name();
0415   this->UntypedPrintArgs(untyped_args, &ss);
0416 
0417   // In case the action deletes a piece of the expectation, we
0418   // generate the message beforehand.
0419   if (found && !is_excessive) {
0420     untyped_expectation->DescribeLocationTo(&loc);
0421   }
0422 
0423   UntypedActionResultHolderBase* const result =
0424       untyped_action == NULL ?
0425       this->UntypedPerformDefaultAction(untyped_args, ss.str()) :
0426       this->UntypedPerformAction(untyped_action, untyped_args);
0427   if (result != NULL)
0428     result->PrintAsActionResult(&ss);
0429   ss << "\n" << why.str();
0430 
0431   if (!found) {
0432     // No expectation matches this call - reports a failure.
0433     Expect(false, NULL, -1, ss.str());
0434   } else if (is_excessive) {
0435     // We had an upper-bound violation and the failure message is in ss.
0436     Expect(false, untyped_expectation->file(),
0437            untyped_expectation->line(), ss.str());
0438   } else {
0439     // We had an expected call and the matching expectation is
0440     // described in ss.
0441     Log(kInfo, loc.str() + ss.str(), 2);
0442   }
0443 
0444   return result;
0445 }
0446 
0447 // Returns an Expectation object that references and co-owns exp,
0448 // which must be an expectation on this mock function.
0449 Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
0450   for (UntypedExpectations::const_iterator it =
0451            untyped_expectations_.begin();
0452        it != untyped_expectations_.end(); ++it) {
0453     if (it->get() == exp) {
0454       return Expectation(*it);
0455     }
0456   }
0457 
0458   Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
0459   return Expectation();
0460   // The above statement is just to make the code compile, and will
0461   // never be executed.
0462 }
0463 
0464 // Verifies that all expectations on this mock function have been
0465 // satisfied.  Reports one or more Google Test non-fatal failures
0466 // and returns false if not.
0467 bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
0468     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
0469   g_gmock_mutex.AssertHeld();
0470   bool expectations_met = true;
0471   for (UntypedExpectations::const_iterator it =
0472            untyped_expectations_.begin();
0473        it != untyped_expectations_.end(); ++it) {
0474     ExpectationBase* const untyped_expectation = it->get();
0475     if (untyped_expectation->IsOverSaturated()) {
0476       // There was an upper-bound violation.  Since the error was
0477       // already reported when it occurred, there is no need to do
0478       // anything here.
0479       expectations_met = false;
0480     } else if (!untyped_expectation->IsSatisfied()) {
0481       expectations_met = false;
0482       ::std::stringstream ss;
0483       ss  << "Actual function call count doesn't match "
0484           << untyped_expectation->source_text() << "...\n";
0485       // No need to show the source file location of the expectation
0486       // in the description, as the Expect() call that follows already
0487       // takes care of it.
0488       untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
0489       untyped_expectation->DescribeCallCountTo(&ss);
0490       Expect(false, untyped_expectation->file(),
0491              untyped_expectation->line(), ss.str());
0492     }
0493   }
0494 
0495   // Deleting our expectations may trigger other mock objects to be deleted, for
0496   // example if an action contains a reference counted smart pointer to that
0497   // mock object, and that is the last reference. So if we delete our
0498   // expectations within the context of the global mutex we may deadlock when
0499   // this method is called again. Instead, make a copy of the set of
0500   // expectations to delete, clear our set within the mutex, and then clear the
0501   // copied set outside of it.
0502   UntypedExpectations expectations_to_delete;
0503   untyped_expectations_.swap(expectations_to_delete);
0504 
0505   g_gmock_mutex.Unlock();
0506   expectations_to_delete.clear();
0507   g_gmock_mutex.Lock();
0508 
0509   return expectations_met;
0510 }
0511 
0512 }  // namespace internal
0513 
0514 // Class Mock.
0515 
0516 namespace {
0517 
0518 typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
0519 
0520 // The current state of a mock object.  Such information is needed for
0521 // detecting leaked mock objects and explicitly verifying a mock's
0522 // expectations.
0523 struct MockObjectState {
0524   MockObjectState()
0525       : first_used_file(NULL), first_used_line(-1), leakable(false) {}
0526 
0527   // Where in the source file an ON_CALL or EXPECT_CALL is first
0528   // invoked on this mock object.
0529   const char* first_used_file;
0530   int first_used_line;
0531   ::std::string first_used_test_case;
0532   ::std::string first_used_test;
0533   bool leakable;  // true iff it's OK to leak the object.
0534   FunctionMockers function_mockers;  // All registered methods of the object.
0535 };
0536 
0537 // A global registry holding the state of all mock objects that are
0538 // alive.  A mock object is added to this registry the first time
0539 // Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it.  It
0540 // is removed from the registry in the mock object's destructor.
0541 class MockObjectRegistry {
0542  public:
0543   // Maps a mock object (identified by its address) to its state.
0544   typedef std::map<const void*, MockObjectState> StateMap;
0545 
0546   // This destructor will be called when a program exits, after all
0547   // tests in it have been run.  By then, there should be no mock
0548   // object alive.  Therefore we report any living object as test
0549   // failure, unless the user explicitly asked us to ignore it.
0550   ~MockObjectRegistry() {
0551     // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is
0552     // a macro.
0553 
0554     if (!GMOCK_FLAG(catch_leaked_mocks))
0555       return;
0556 
0557     int leaked_count = 0;
0558     for (StateMap::const_iterator it = states_.begin(); it != states_.end();
0559          ++it) {
0560       if (it->second.leakable)  // The user said it's fine to leak this object.
0561         continue;
0562 
0563       // TODO(wan@google.com): Print the type of the leaked object.
0564       // This can help the user identify the leaked object.
0565       std::cout << "\n";
0566       const MockObjectState& state = it->second;
0567       std::cout << internal::FormatFileLocation(state.first_used_file,
0568                                                 state.first_used_line);
0569       std::cout << " ERROR: this mock object";
0570       if (state.first_used_test != "") {
0571         std::cout << " (used in test " << state.first_used_test_case << "."
0572              << state.first_used_test << ")";
0573       }
0574       std::cout << " should be deleted but never is. Its address is @"
0575            << it->first << ".";
0576       leaked_count++;
0577     }
0578     if (leaked_count > 0) {
0579       std::cout << "\nERROR: " << leaked_count
0580            << " leaked mock " << (leaked_count == 1 ? "object" : "objects")
0581            << " found at program exit.\n";
0582       std::cout.flush();
0583       ::std::cerr.flush();
0584       // RUN_ALL_TESTS() has already returned when this destructor is
0585       // called.  Therefore we cannot use the normal Google Test
0586       // failure reporting mechanism.
0587       _exit(1);  // We cannot call exit() as it is not reentrant and
0588                  // may already have been called.
0589     }
0590   }
0591 
0592   StateMap& states() { return states_; }
0593 
0594  private:
0595   StateMap states_;
0596 };
0597 
0598 // Protected by g_gmock_mutex.
0599 MockObjectRegistry g_mock_object_registry;
0600 
0601 // Maps a mock object to the reaction Google Mock should have when an
0602 // uninteresting method is called.  Protected by g_gmock_mutex.
0603 std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
0604 
0605 // Sets the reaction Google Mock should have when an uninteresting
0606 // method of the given mock object is called.
0607 void SetReactionOnUninterestingCalls(const void* mock_obj,
0608                                      internal::CallReaction reaction)
0609     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
0610   internal::MutexLock l(&internal::g_gmock_mutex);
0611   g_uninteresting_call_reaction[mock_obj] = reaction;
0612 }
0613 
0614 }  // namespace
0615 
0616 // Tells Google Mock to allow uninteresting calls on the given mock
0617 // object.
0618 void Mock::AllowUninterestingCalls(const void* mock_obj)
0619     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
0620   SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
0621 }
0622 
0623 // Tells Google Mock to warn the user about uninteresting calls on the
0624 // given mock object.
0625 void Mock::WarnUninterestingCalls(const void* mock_obj)
0626     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
0627   SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
0628 }
0629 
0630 // Tells Google Mock to fail uninteresting calls on the given mock
0631 // object.
0632 void Mock::FailUninterestingCalls(const void* mock_obj)
0633     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
0634   SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
0635 }
0636 
0637 // Tells Google Mock the given mock object is being destroyed and its
0638 // entry in the call-reaction table should be removed.
0639 void Mock::UnregisterCallReaction(const void* mock_obj)
0640     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
0641   internal::MutexLock l(&internal::g_gmock_mutex);
0642   g_uninteresting_call_reaction.erase(mock_obj);
0643 }
0644 
0645 // Returns the reaction Google Mock will have on uninteresting calls
0646 // made on the given mock object.
0647 internal::CallReaction Mock::GetReactionOnUninterestingCalls(
0648     const void* mock_obj)
0649         GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
0650   internal::MutexLock l(&internal::g_gmock_mutex);
0651   return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
0652       internal::kDefault : g_uninteresting_call_reaction[mock_obj];
0653 }
0654 
0655 // Tells Google Mock to ignore mock_obj when checking for leaked mock
0656 // objects.
0657 void Mock::AllowLeak(const void* mock_obj)
0658     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
0659   internal::MutexLock l(&internal::g_gmock_mutex);
0660   g_mock_object_registry.states()[mock_obj].leakable = true;
0661 }
0662 
0663 // Verifies and clears all expectations on the given mock object.  If
0664 // the expectations aren't satisfied, generates one or more Google
0665 // Test non-fatal failures and returns false.
0666 bool Mock::VerifyAndClearExpectations(void* mock_obj)
0667     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
0668   internal::MutexLock l(&internal::g_gmock_mutex);
0669   return VerifyAndClearExpectationsLocked(mock_obj);
0670 }
0671 
0672 // Verifies all expectations on the given mock object and clears its
0673 // default actions and expectations.  Returns true iff the
0674 // verification was successful.
0675 bool Mock::VerifyAndClear(void* mock_obj)
0676     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
0677   internal::MutexLock l(&internal::g_gmock_mutex);
0678   ClearDefaultActionsLocked(mock_obj);
0679   return VerifyAndClearExpectationsLocked(mock_obj);
0680 }
0681 
0682 // Verifies and clears all expectations on the given mock object.  If
0683 // the expectations aren't satisfied, generates one or more Google
0684 // Test non-fatal failures and returns false.
0685 bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
0686     GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
0687   internal::g_gmock_mutex.AssertHeld();
0688   if (g_mock_object_registry.states().count(mock_obj) == 0) {
0689     // No EXPECT_CALL() was set on the given mock object.
0690     return true;
0691   }
0692 
0693   // Verifies and clears the expectations on each mock method in the
0694   // given mock object.
0695   bool expectations_met = true;
0696   FunctionMockers& mockers =
0697       g_mock_object_registry.states()[mock_obj].function_mockers;
0698   for (FunctionMockers::const_iterator it = mockers.begin();
0699        it != mockers.end(); ++it) {
0700     if (!(*it)->VerifyAndClearExpectationsLocked()) {
0701       expectations_met = false;
0702     }
0703   }
0704 
0705   // We don't clear the content of mockers, as they may still be
0706   // needed by ClearDefaultActionsLocked().
0707   return expectations_met;
0708 }
0709 
0710 // Registers a mock object and a mock method it owns.
0711 void Mock::Register(const void* mock_obj,
0712                     internal::UntypedFunctionMockerBase* mocker)
0713     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
0714   internal::MutexLock l(&internal::g_gmock_mutex);
0715   g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
0716 }
0717 
0718 // Tells Google Mock where in the source code mock_obj is used in an
0719 // ON_CALL or EXPECT_CALL.  In case mock_obj is leaked, this
0720 // information helps the user identify which object it is.
0721 void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
0722                                            const char* file, int line)
0723     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
0724   internal::MutexLock l(&internal::g_gmock_mutex);
0725   MockObjectState& state = g_mock_object_registry.states()[mock_obj];
0726   if (state.first_used_file == NULL) {
0727     state.first_used_file = file;
0728     state.first_used_line = line;
0729     const TestInfo* const test_info =
0730         UnitTest::GetInstance()->current_test_info();
0731     if (test_info != NULL) {
0732       // TODO(wan@google.com): record the test case name when the
0733       // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or
0734       // TearDownTestCase().
0735       state.first_used_test_case = test_info->test_case_name();
0736       state.first_used_test = test_info->name();
0737     }
0738   }
0739 }
0740 
0741 // Unregisters a mock method; removes the owning mock object from the
0742 // registry when the last mock method associated with it has been
0743 // unregistered.  This is called only in the destructor of
0744 // FunctionMockerBase.
0745 void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
0746     GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
0747   internal::g_gmock_mutex.AssertHeld();
0748   for (MockObjectRegistry::StateMap::iterator it =
0749            g_mock_object_registry.states().begin();
0750        it != g_mock_object_registry.states().end(); ++it) {
0751     FunctionMockers& mockers = it->second.function_mockers;
0752     if (mockers.erase(mocker) > 0) {
0753       // mocker was in mockers and has been just removed.
0754       if (mockers.empty()) {
0755         g_mock_object_registry.states().erase(it);
0756       }
0757       return;
0758     }
0759   }
0760 }
0761 
0762 // Clears all ON_CALL()s set on the given mock object.
0763 void Mock::ClearDefaultActionsLocked(void* mock_obj)
0764     GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
0765   internal::g_gmock_mutex.AssertHeld();
0766 
0767   if (g_mock_object_registry.states().count(mock_obj) == 0) {
0768     // No ON_CALL() was set on the given mock object.
0769     return;
0770   }
0771 
0772   // Clears the default actions for each mock method in the given mock
0773   // object.
0774   FunctionMockers& mockers =
0775       g_mock_object_registry.states()[mock_obj].function_mockers;
0776   for (FunctionMockers::const_iterator it = mockers.begin();
0777        it != mockers.end(); ++it) {
0778     (*it)->ClearDefaultActionsLocked();
0779   }
0780 
0781   // We don't clear the content of mockers, as they may still be
0782   // needed by VerifyAndClearExpectationsLocked().
0783 }
0784 
0785 Expectation::Expectation() {}
0786 
0787 Expectation::Expectation(
0788     const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base)
0789     : expectation_base_(an_expectation_base) {}
0790 
0791 Expectation::~Expectation() {}
0792 
0793 // Adds an expectation to a sequence.
0794 void Sequence::AddExpectation(const Expectation& expectation) const {
0795   if (*last_expectation_ != expectation) {
0796     if (last_expectation_->expectation_base() != NULL) {
0797       expectation.expectation_base()->immediate_prerequisites_
0798           += *last_expectation_;
0799     }
0800     *last_expectation_ = expectation;
0801   }
0802 }
0803 
0804 // Creates the implicit sequence if there isn't one.
0805 InSequence::InSequence() {
0806   if (internal::g_gmock_implicit_sequence.get() == NULL) {
0807     internal::g_gmock_implicit_sequence.set(new Sequence);
0808     sequence_created_ = true;
0809   } else {
0810     sequence_created_ = false;
0811   }
0812 }
0813 
0814 // Deletes the implicit sequence if it was created by the constructor
0815 // of this object.
0816 InSequence::~InSequence() {
0817   if (sequence_created_) {
0818     delete internal::g_gmock_implicit_sequence.get();
0819     internal::g_gmock_implicit_sequence.set(NULL);
0820   }
0821 }
0822 
0823 }  // namespace testing