gmock-spec-builders.cc
Go to the documentation of this file.
00001 // Copyright 2007, Google Inc.
00002 // All rights reserved.
00003 //
00004 // Redistribution and use in source and binary forms, with or without
00005 // modification, are permitted provided that the following conditions are
00006 // met:
00007 //
00008 //     * Redistributions of source code must retain the above copyright
00009 // notice, this list of conditions and the following disclaimer.
00010 //     * Redistributions in binary form must reproduce the above
00011 // copyright notice, this list of conditions and the following disclaimer
00012 // in the documentation and/or other materials provided with the
00013 // distribution.
00014 //     * Neither the name of Google Inc. nor the names of its
00015 // contributors may be used to endorse or promote products derived from
00016 // this software without specific prior written permission.
00017 //
00018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00019 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00020 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00021 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00022 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00023 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00024 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00025 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00026 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00027 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00028 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00029 //
00030 // Author: wan@google.com (Zhanyong Wan)
00031 
00032 // Google Mock - a framework for writing C++ mock classes.
00033 //
00034 // This file implements the spec builder syntax (ON_CALL and
00035 // EXPECT_CALL).
00036 
00037 #include "gmock/gmock-spec-builders.h"
00038 
00039 #include <stdlib.h>
00040 #include <iostream>  // NOLINT
00041 #include <map>
00042 #include <set>
00043 #include <string>
00044 #include "gmock/gmock.h"
00045 #include "gtest/gtest.h"
00046 
00047 #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
00048 # include <unistd.h>  // NOLINT
00049 #endif
00050 
00051 namespace testing {
00052 namespace internal {
00053 
00054 // Protects the mock object registry (in class Mock), all function
00055 // mockers, and all expectations.
00056 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
00057 
00058 // Logs a message including file and line number information.
00059 GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
00060                                 const char* file, int line,
00061                                 const string& message) {
00062   ::std::ostringstream s;
00063   s << file << ":" << line << ": " << message << ::std::endl;
00064   Log(severity, s.str(), 0);
00065 }
00066 
00067 // Constructs an ExpectationBase object.
00068 ExpectationBase::ExpectationBase(const char* a_file,
00069                                  int a_line,
00070                                  const string& a_source_text)
00071     : file_(a_file),
00072       line_(a_line),
00073       source_text_(a_source_text),
00074       cardinality_specified_(false),
00075       cardinality_(Exactly(1)),
00076       call_count_(0),
00077       retired_(false),
00078       extra_matcher_specified_(false),
00079       repeated_action_specified_(false),
00080       retires_on_saturation_(false),
00081       last_clause_(kNone),
00082       action_count_checked_(false) {}
00083 
00084 // Destructs an ExpectationBase object.
00085 ExpectationBase::~ExpectationBase() {}
00086 
00087 // Explicitly specifies the cardinality of this expectation.  Used by
00088 // the subclasses to implement the .Times() clause.
00089 void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {
00090   cardinality_specified_ = true;
00091   cardinality_ = a_cardinality;
00092 }
00093 
00094 // Retires all pre-requisites of this expectation.
00095 void ExpectationBase::RetireAllPreRequisites()
00096     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
00097   if (is_retired()) {
00098     // We can take this short-cut as we never retire an expectation
00099     // until we have retired all its pre-requisites.
00100     return;
00101   }
00102 
00103   for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
00104        it != immediate_prerequisites_.end(); ++it) {
00105     ExpectationBase* const prerequisite = it->expectation_base().get();
00106     if (!prerequisite->is_retired()) {
00107       prerequisite->RetireAllPreRequisites();
00108       prerequisite->Retire();
00109     }
00110   }
00111 }
00112 
00113 // Returns true iff all pre-requisites of this expectation have been
00114 // satisfied.
00115 bool ExpectationBase::AllPrerequisitesAreSatisfied() const
00116     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
00117   g_gmock_mutex.AssertHeld();
00118   for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
00119        it != immediate_prerequisites_.end(); ++it) {
00120     if (!(it->expectation_base()->IsSatisfied()) ||
00121         !(it->expectation_base()->AllPrerequisitesAreSatisfied()))
00122       return false;
00123   }
00124   return true;
00125 }
00126 
00127 // Adds unsatisfied pre-requisites of this expectation to 'result'.
00128 void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const
00129     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
00130   g_gmock_mutex.AssertHeld();
00131   for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
00132        it != immediate_prerequisites_.end(); ++it) {
00133     if (it->expectation_base()->IsSatisfied()) {
00134       // If *it is satisfied and has a call count of 0, some of its
00135       // pre-requisites may not be satisfied yet.
00136       if (it->expectation_base()->call_count_ == 0) {
00137         it->expectation_base()->FindUnsatisfiedPrerequisites(result);
00138       }
00139     } else {
00140       // Now that we know *it is unsatisfied, we are not so interested
00141       // in whether its pre-requisites are satisfied.  Therefore we
00142       // don't recursively call FindUnsatisfiedPrerequisites() here.
00143       *result += *it;
00144     }
00145   }
00146 }
00147 
00148 // Describes how many times a function call matching this
00149 // expectation has occurred.
00150 void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
00151     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
00152   g_gmock_mutex.AssertHeld();
00153 
00154   // Describes how many times the function is expected to be called.
00155   *os << "         Expected: to be ";
00156   cardinality().DescribeTo(os);
00157   *os << "\n           Actual: ";
00158   Cardinality::DescribeActualCallCountTo(call_count(), os);
00159 
00160   // Describes the state of the expectation (e.g. is it satisfied?
00161   // is it active?).
00162   *os << " - " << (IsOverSaturated() ? "over-saturated" :
00163                    IsSaturated() ? "saturated" :
00164                    IsSatisfied() ? "satisfied" : "unsatisfied")
00165       << " and "
00166       << (is_retired() ? "retired" : "active");
00167 }
00168 
00169 // Checks the action count (i.e. the number of WillOnce() and
00170 // WillRepeatedly() clauses) against the cardinality if this hasn't
00171 // been done before.  Prints a warning if there are too many or too
00172 // few actions.
00173 void ExpectationBase::CheckActionCountIfNotDone() const
00174     GTEST_LOCK_EXCLUDED_(mutex_) {
00175   bool should_check = false;
00176   {
00177     MutexLock l(&mutex_);
00178     if (!action_count_checked_) {
00179       action_count_checked_ = true;
00180       should_check = true;
00181     }
00182   }
00183 
00184   if (should_check) {
00185     if (!cardinality_specified_) {
00186       // The cardinality was inferred - no need to check the action
00187       // count against it.
00188       return;
00189     }
00190 
00191     // The cardinality was explicitly specified.
00192     const int action_count = static_cast<int>(untyped_actions_.size());
00193     const int upper_bound = cardinality().ConservativeUpperBound();
00194     const int lower_bound = cardinality().ConservativeLowerBound();
00195     bool too_many;  // True if there are too many actions, or false
00196     // if there are too few.
00197     if (action_count > upper_bound ||
00198         (action_count == upper_bound && repeated_action_specified_)) {
00199       too_many = true;
00200     } else if (0 < action_count && action_count < lower_bound &&
00201                !repeated_action_specified_) {
00202       too_many = false;
00203     } else {
00204       return;
00205     }
00206 
00207     ::std::stringstream ss;
00208     DescribeLocationTo(&ss);
00209     ss << "Too " << (too_many ? "many" : "few")
00210        << " actions specified in " << source_text() << "...\n"
00211        << "Expected to be ";
00212     cardinality().DescribeTo(&ss);
00213     ss << ", but has " << (too_many ? "" : "only ")
00214        << action_count << " WillOnce()"
00215        << (action_count == 1 ? "" : "s");
00216     if (repeated_action_specified_) {
00217       ss << " and a WillRepeatedly()";
00218     }
00219     ss << ".";
00220     Log(kWarning, ss.str(), -1);  // -1 means "don't print stack trace".
00221   }
00222 }
00223 
00224 // Implements the .Times() clause.
00225 void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
00226   if (last_clause_ == kTimes) {
00227     ExpectSpecProperty(false,
00228                        ".Times() cannot appear "
00229                        "more than once in an EXPECT_CALL().");
00230   } else {
00231     ExpectSpecProperty(last_clause_ < kTimes,
00232                        ".Times() cannot appear after "
00233                        ".InSequence(), .WillOnce(), .WillRepeatedly(), "
00234                        "or .RetiresOnSaturation().");
00235   }
00236   last_clause_ = kTimes;
00237 
00238   SpecifyCardinality(a_cardinality);
00239 }
00240 
00241 // Points to the implicit sequence introduced by a living InSequence
00242 // object (if any) in the current thread or NULL.
00243 GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
00244 
00245 // Reports an uninteresting call (whose description is in msg) in the
00246 // manner specified by 'reaction'.
00247 void ReportUninterestingCall(CallReaction reaction, const string& msg) {
00248   switch (reaction) {
00249     case kAllow:
00250       Log(kInfo, msg, 3);
00251       break;
00252     case kWarn:
00253       Log(kWarning, msg, 3);
00254       break;
00255     default:  // FAIL
00256       Expect(false, NULL, -1, msg);
00257   }
00258 }
00259 
00260 UntypedFunctionMockerBase::UntypedFunctionMockerBase()
00261     : mock_obj_(NULL), name_("") {}
00262 
00263 UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
00264 
00265 // Sets the mock object this mock method belongs to, and registers
00266 // this information in the global mock registry.  Will be called
00267 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
00268 // method.
00269 void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
00270     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
00271   {
00272     MutexLock l(&g_gmock_mutex);
00273     mock_obj_ = mock_obj;
00274   }
00275   Mock::Register(mock_obj, this);
00276 }
00277 
00278 // Sets the mock object this mock method belongs to, and sets the name
00279 // of the mock function.  Will be called upon each invocation of this
00280 // mock function.
00281 void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
00282                                                 const char* name)
00283     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
00284   // We protect name_ under g_gmock_mutex in case this mock function
00285   // is called from two threads concurrently.
00286   MutexLock l(&g_gmock_mutex);
00287   mock_obj_ = mock_obj;
00288   name_ = name;
00289 }
00290 
00291 // Returns the name of the function being mocked.  Must be called
00292 // after RegisterOwner() or SetOwnerAndName() has been called.
00293 const void* UntypedFunctionMockerBase::MockObject() const
00294     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
00295   const void* mock_obj;
00296   {
00297     // We protect mock_obj_ under g_gmock_mutex in case this mock
00298     // function is called from two threads concurrently.
00299     MutexLock l(&g_gmock_mutex);
00300     Assert(mock_obj_ != NULL, __FILE__, __LINE__,
00301            "MockObject() must not be called before RegisterOwner() or "
00302            "SetOwnerAndName() has been called.");
00303     mock_obj = mock_obj_;
00304   }
00305   return mock_obj;
00306 }
00307 
00308 // Returns the name of this mock method.  Must be called after
00309 // SetOwnerAndName() has been called.
00310 const char* UntypedFunctionMockerBase::Name() const
00311     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
00312   const char* name;
00313   {
00314     // We protect name_ under g_gmock_mutex in case this mock
00315     // function is called from two threads concurrently.
00316     MutexLock l(&g_gmock_mutex);
00317     Assert(name_ != NULL, __FILE__, __LINE__,
00318            "Name() must not be called before SetOwnerAndName() has "
00319            "been called.");
00320     name = name_;
00321   }
00322   return name;
00323 }
00324 
00325 // Calculates the result of invoking this mock function with the given
00326 // arguments, prints it, and returns it.  The caller is responsible
00327 // for deleting the result.
00328 const UntypedActionResultHolderBase*
00329 UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args)
00330     GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
00331   if (untyped_expectations_.size() == 0) {
00332     // No expectation is set on this mock method - we have an
00333     // uninteresting call.
00334 
00335     // We must get Google Mock's reaction on uninteresting calls
00336     // made on this mock object BEFORE performing the action,
00337     // because the action may DELETE the mock object and make the
00338     // following expression meaningless.
00339     const CallReaction reaction =
00340         Mock::GetReactionOnUninterestingCalls(MockObject());
00341 
00342     // True iff we need to print this call's arguments and return
00343     // value.  This definition must be kept in sync with
00344     // the behavior of ReportUninterestingCall().
00345     const bool need_to_report_uninteresting_call =
00346         // If the user allows this uninteresting call, we print it
00347         // only when he wants informational messages.
00348         reaction == kAllow ? LogIsVisible(kInfo) :
00349         // If the user wants this to be a warning, we print it only
00350         // when he wants to see warnings.
00351         reaction == kWarn ? LogIsVisible(kWarning) :
00352         // Otherwise, the user wants this to be an error, and we
00353         // should always print detailed information in the error.
00354         true;
00355 
00356     if (!need_to_report_uninteresting_call) {
00357       // Perform the action without printing the call information.
00358       return this->UntypedPerformDefaultAction(untyped_args, "");
00359     }
00360 
00361     // Warns about the uninteresting call.
00362     ::std::stringstream ss;
00363     this->UntypedDescribeUninterestingCall(untyped_args, &ss);
00364 
00365     // Calculates the function result.
00366     const UntypedActionResultHolderBase* const result =
00367         this->UntypedPerformDefaultAction(untyped_args, ss.str());
00368 
00369     // Prints the function result.
00370     if (result != NULL)
00371       result->PrintAsActionResult(&ss);
00372 
00373     ReportUninterestingCall(reaction, ss.str());
00374     return result;
00375   }
00376 
00377   bool is_excessive = false;
00378   ::std::stringstream ss;
00379   ::std::stringstream why;
00380   ::std::stringstream loc;
00381   const void* untyped_action = NULL;
00382 
00383   // The UntypedFindMatchingExpectation() function acquires and
00384   // releases g_gmock_mutex.
00385   const ExpectationBase* const untyped_expectation =
00386       this->UntypedFindMatchingExpectation(
00387           untyped_args, &untyped_action, &is_excessive,
00388           &ss, &why);
00389   const bool found = untyped_expectation != NULL;
00390 
00391   // True iff we need to print the call's arguments and return value.
00392   // This definition must be kept in sync with the uses of Expect()
00393   // and Log() in this function.
00394   const bool need_to_report_call =
00395       !found || is_excessive || LogIsVisible(kInfo);
00396   if (!need_to_report_call) {
00397     // Perform the action without printing the call information.
00398     return
00399         untyped_action == NULL ?
00400         this->UntypedPerformDefaultAction(untyped_args, "") :
00401         this->UntypedPerformAction(untyped_action, untyped_args);
00402   }
00403 
00404   ss << "    Function call: " << Name();
00405   this->UntypedPrintArgs(untyped_args, &ss);
00406 
00407   // In case the action deletes a piece of the expectation, we
00408   // generate the message beforehand.
00409   if (found && !is_excessive) {
00410     untyped_expectation->DescribeLocationTo(&loc);
00411   }
00412 
00413   const UntypedActionResultHolderBase* const result =
00414       untyped_action == NULL ?
00415       this->UntypedPerformDefaultAction(untyped_args, ss.str()) :
00416       this->UntypedPerformAction(untyped_action, untyped_args);
00417   if (result != NULL)
00418     result->PrintAsActionResult(&ss);
00419   ss << "\n" << why.str();
00420 
00421   if (!found) {
00422     // No expectation matches this call - reports a failure.
00423     Expect(false, NULL, -1, ss.str());
00424   } else if (is_excessive) {
00425     // We had an upper-bound violation and the failure message is in ss.
00426     Expect(false, untyped_expectation->file(),
00427            untyped_expectation->line(), ss.str());
00428   } else {
00429     // We had an expected call and the matching expectation is
00430     // described in ss.
00431     Log(kInfo, loc.str() + ss.str(), 2);
00432   }
00433 
00434   return result;
00435 }
00436 
00437 // Returns an Expectation object that references and co-owns exp,
00438 // which must be an expectation on this mock function.
00439 Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
00440   for (UntypedExpectations::const_iterator it =
00441            untyped_expectations_.begin();
00442        it != untyped_expectations_.end(); ++it) {
00443     if (it->get() == exp) {
00444       return Expectation(*it);
00445     }
00446   }
00447 
00448   Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
00449   return Expectation();
00450   // The above statement is just to make the code compile, and will
00451   // never be executed.
00452 }
00453 
00454 // Verifies that all expectations on this mock function have been
00455 // satisfied.  Reports one or more Google Test non-fatal failures
00456 // and returns false if not.
00457 bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
00458     GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
00459   g_gmock_mutex.AssertHeld();
00460   bool expectations_met = true;
00461   for (UntypedExpectations::const_iterator it =
00462            untyped_expectations_.begin();
00463        it != untyped_expectations_.end(); ++it) {
00464     ExpectationBase* const untyped_expectation = it->get();
00465     if (untyped_expectation->IsOverSaturated()) {
00466       // There was an upper-bound violation.  Since the error was
00467       // already reported when it occurred, there is no need to do
00468       // anything here.
00469       expectations_met = false;
00470     } else if (!untyped_expectation->IsSatisfied()) {
00471       expectations_met = false;
00472       ::std::stringstream ss;
00473       ss  << "Actual function call count doesn't match "
00474           << untyped_expectation->source_text() << "...\n";
00475       // No need to show the source file location of the expectation
00476       // in the description, as the Expect() call that follows already
00477       // takes care of it.
00478       untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
00479       untyped_expectation->DescribeCallCountTo(&ss);
00480       Expect(false, untyped_expectation->file(),
00481              untyped_expectation->line(), ss.str());
00482     }
00483   }
00484 
00485   // Deleting our expectations may trigger other mock objects to be deleted, for
00486   // example if an action contains a reference counted smart pointer to that
00487   // mock object, and that is the last reference. So if we delete our
00488   // expectations within the context of the global mutex we may deadlock when
00489   // this method is called again. Instead, make a copy of the set of
00490   // expectations to delete, clear our set within the mutex, and then clear the
00491   // copied set outside of it.
00492   UntypedExpectations expectations_to_delete;
00493   untyped_expectations_.swap(expectations_to_delete);
00494 
00495   g_gmock_mutex.Unlock();
00496   expectations_to_delete.clear();
00497   g_gmock_mutex.Lock();
00498 
00499   return expectations_met;
00500 }
00501 
00502 }  // namespace internal
00503 
00504 // Class Mock.
00505 
00506 namespace {
00507 
00508 typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
00509 
00510 // The current state of a mock object.  Such information is needed for
00511 // detecting leaked mock objects and explicitly verifying a mock's
00512 // expectations.
00513 struct MockObjectState {
00514   MockObjectState()
00515       : first_used_file(NULL), first_used_line(-1), leakable(false) {}
00516 
00517   // Where in the source file an ON_CALL or EXPECT_CALL is first
00518   // invoked on this mock object.
00519   const char* first_used_file;
00520   int first_used_line;
00521   ::std::string first_used_test_case;
00522   ::std::string first_used_test;
00523   bool leakable;  // true iff it's OK to leak the object.
00524   FunctionMockers function_mockers;  // All registered methods of the object.
00525 };
00526 
00527 // A global registry holding the state of all mock objects that are
00528 // alive.  A mock object is added to this registry the first time
00529 // Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it.  It
00530 // is removed from the registry in the mock object's destructor.
00531 class MockObjectRegistry {
00532  public:
00533   // Maps a mock object (identified by its address) to its state.
00534   typedef std::map<const void*, MockObjectState> StateMap;
00535 
00536   // This destructor will be called when a program exits, after all
00537   // tests in it have been run.  By then, there should be no mock
00538   // object alive.  Therefore we report any living object as test
00539   // failure, unless the user explicitly asked us to ignore it.
00540   ~MockObjectRegistry() {
00541     // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is
00542     // a macro.
00543 
00544     if (!GMOCK_FLAG(catch_leaked_mocks))
00545       return;
00546 
00547     int leaked_count = 0;
00548     for (StateMap::const_iterator it = states_.begin(); it != states_.end();
00549          ++it) {
00550       if (it->second.leakable)  // The user said it's fine to leak this object.
00551         continue;
00552 
00553       // TODO(wan@google.com): Print the type of the leaked object.
00554       // This can help the user identify the leaked object.
00555       std::cout << "\n";
00556       const MockObjectState& state = it->second;
00557       std::cout << internal::FormatFileLocation(state.first_used_file,
00558                                                 state.first_used_line);
00559       std::cout << " ERROR: this mock object";
00560       if (state.first_used_test != "") {
00561         std::cout << " (used in test " << state.first_used_test_case << "."
00562              << state.first_used_test << ")";
00563       }
00564       std::cout << " should be deleted but never is. Its address is @"
00565            << it->first << ".";
00566       leaked_count++;
00567     }
00568     if (leaked_count > 0) {
00569       std::cout << "\nERROR: " << leaked_count
00570            << " leaked mock " << (leaked_count == 1 ? "object" : "objects")
00571            << " found at program exit.\n";
00572       std::cout.flush();
00573       ::std::cerr.flush();
00574       // RUN_ALL_TESTS() has already returned when this destructor is
00575       // called.  Therefore we cannot use the normal Google Test
00576       // failure reporting mechanism.
00577       _exit(1);  // We cannot call exit() as it is not reentrant and
00578                  // may already have been called.
00579     }
00580   }
00581 
00582   StateMap& states() { return states_; }
00583 
00584  private:
00585   StateMap states_;
00586 };
00587 
00588 // Protected by g_gmock_mutex.
00589 MockObjectRegistry g_mock_object_registry;
00590 
00591 // Maps a mock object to the reaction Google Mock should have when an
00592 // uninteresting method is called.  Protected by g_gmock_mutex.
00593 std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
00594 
00595 // Sets the reaction Google Mock should have when an uninteresting
00596 // method of the given mock object is called.
00597 void SetReactionOnUninterestingCalls(const void* mock_obj,
00598                                      internal::CallReaction reaction)
00599     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
00600   internal::MutexLock l(&internal::g_gmock_mutex);
00601   g_uninteresting_call_reaction[mock_obj] = reaction;
00602 }
00603 
00604 }  // namespace
00605 
00606 // Tells Google Mock to allow uninteresting calls on the given mock
00607 // object.
00608 void Mock::AllowUninterestingCalls(const void* mock_obj)
00609     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
00610   SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
00611 }
00612 
00613 // Tells Google Mock to warn the user about uninteresting calls on the
00614 // given mock object.
00615 void Mock::WarnUninterestingCalls(const void* mock_obj)
00616     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
00617   SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
00618 }
00619 
00620 // Tells Google Mock to fail uninteresting calls on the given mock
00621 // object.
00622 void Mock::FailUninterestingCalls(const void* mock_obj)
00623     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
00624   SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
00625 }
00626 
00627 // Tells Google Mock the given mock object is being destroyed and its
00628 // entry in the call-reaction table should be removed.
00629 void Mock::UnregisterCallReaction(const void* mock_obj)
00630     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
00631   internal::MutexLock l(&internal::g_gmock_mutex);
00632   g_uninteresting_call_reaction.erase(mock_obj);
00633 }
00634 
00635 // Returns the reaction Google Mock will have on uninteresting calls
00636 // made on the given mock object.
00637 internal::CallReaction Mock::GetReactionOnUninterestingCalls(
00638     const void* mock_obj)
00639         GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
00640   internal::MutexLock l(&internal::g_gmock_mutex);
00641   return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
00642       internal::kDefault : g_uninteresting_call_reaction[mock_obj];
00643 }
00644 
00645 // Tells Google Mock to ignore mock_obj when checking for leaked mock
00646 // objects.
00647 void Mock::AllowLeak(const void* mock_obj)
00648     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
00649   internal::MutexLock l(&internal::g_gmock_mutex);
00650   g_mock_object_registry.states()[mock_obj].leakable = true;
00651 }
00652 
00653 // Verifies and clears all expectations on the given mock object.  If
00654 // the expectations aren't satisfied, generates one or more Google
00655 // Test non-fatal failures and returns false.
00656 bool Mock::VerifyAndClearExpectations(void* mock_obj)
00657     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
00658   internal::MutexLock l(&internal::g_gmock_mutex);
00659   return VerifyAndClearExpectationsLocked(mock_obj);
00660 }
00661 
00662 // Verifies all expectations on the given mock object and clears its
00663 // default actions and expectations.  Returns true iff the
00664 // verification was successful.
00665 bool Mock::VerifyAndClear(void* mock_obj)
00666     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
00667   internal::MutexLock l(&internal::g_gmock_mutex);
00668   ClearDefaultActionsLocked(mock_obj);
00669   return VerifyAndClearExpectationsLocked(mock_obj);
00670 }
00671 
00672 // Verifies and clears all expectations on the given mock object.  If
00673 // the expectations aren't satisfied, generates one or more Google
00674 // Test non-fatal failures and returns false.
00675 bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
00676     GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
00677   internal::g_gmock_mutex.AssertHeld();
00678   if (g_mock_object_registry.states().count(mock_obj) == 0) {
00679     // No EXPECT_CALL() was set on the given mock object.
00680     return true;
00681   }
00682 
00683   // Verifies and clears the expectations on each mock method in the
00684   // given mock object.
00685   bool expectations_met = true;
00686   FunctionMockers& mockers =
00687       g_mock_object_registry.states()[mock_obj].function_mockers;
00688   for (FunctionMockers::const_iterator it = mockers.begin();
00689        it != mockers.end(); ++it) {
00690     if (!(*it)->VerifyAndClearExpectationsLocked()) {
00691       expectations_met = false;
00692     }
00693   }
00694 
00695   // We don't clear the content of mockers, as they may still be
00696   // needed by ClearDefaultActionsLocked().
00697   return expectations_met;
00698 }
00699 
00700 // Registers a mock object and a mock method it owns.
00701 void Mock::Register(const void* mock_obj,
00702                     internal::UntypedFunctionMockerBase* mocker)
00703     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
00704   internal::MutexLock l(&internal::g_gmock_mutex);
00705   g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
00706 }
00707 
00708 // Tells Google Mock where in the source code mock_obj is used in an
00709 // ON_CALL or EXPECT_CALL.  In case mock_obj is leaked, this
00710 // information helps the user identify which object it is.
00711 void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
00712                                            const char* file, int line)
00713     GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
00714   internal::MutexLock l(&internal::g_gmock_mutex);
00715   MockObjectState& state = g_mock_object_registry.states()[mock_obj];
00716   if (state.first_used_file == NULL) {
00717     state.first_used_file = file;
00718     state.first_used_line = line;
00719     const TestInfo* const test_info =
00720         UnitTest::GetInstance()->current_test_info();
00721     if (test_info != NULL) {
00722       // TODO(wan@google.com): record the test case name when the
00723       // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or
00724       // TearDownTestCase().
00725       state.first_used_test_case = test_info->test_case_name();
00726       state.first_used_test = test_info->name();
00727     }
00728   }
00729 }
00730 
00731 // Unregisters a mock method; removes the owning mock object from the
00732 // registry when the last mock method associated with it has been
00733 // unregistered.  This is called only in the destructor of
00734 // FunctionMockerBase.
00735 void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
00736     GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
00737   internal::g_gmock_mutex.AssertHeld();
00738   for (MockObjectRegistry::StateMap::iterator it =
00739            g_mock_object_registry.states().begin();
00740        it != g_mock_object_registry.states().end(); ++it) {
00741     FunctionMockers& mockers = it->second.function_mockers;
00742     if (mockers.erase(mocker) > 0) {
00743       // mocker was in mockers and has been just removed.
00744       if (mockers.empty()) {
00745         g_mock_object_registry.states().erase(it);
00746       }
00747       return;
00748     }
00749   }
00750 }
00751 
00752 // Clears all ON_CALL()s set on the given mock object.
00753 void Mock::ClearDefaultActionsLocked(void* mock_obj)
00754     GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
00755   internal::g_gmock_mutex.AssertHeld();
00756 
00757   if (g_mock_object_registry.states().count(mock_obj) == 0) {
00758     // No ON_CALL() was set on the given mock object.
00759     return;
00760   }
00761 
00762   // Clears the default actions for each mock method in the given mock
00763   // object.
00764   FunctionMockers& mockers =
00765       g_mock_object_registry.states()[mock_obj].function_mockers;
00766   for (FunctionMockers::const_iterator it = mockers.begin();
00767        it != mockers.end(); ++it) {
00768     (*it)->ClearDefaultActionsLocked();
00769   }
00770 
00771   // We don't clear the content of mockers, as they may still be
00772   // needed by VerifyAndClearExpectationsLocked().
00773 }
00774 
00775 Expectation::Expectation() {}
00776 
00777 Expectation::Expectation(
00778     const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base)
00779     : expectation_base_(an_expectation_base) {}
00780 
00781 Expectation::~Expectation() {}
00782 
00783 // Adds an expectation to a sequence.
00784 void Sequence::AddExpectation(const Expectation& expectation) const {
00785   if (*last_expectation_ != expectation) {
00786     if (last_expectation_->expectation_base() != NULL) {
00787       expectation.expectation_base()->immediate_prerequisites_
00788           += *last_expectation_;
00789     }
00790     *last_expectation_ = expectation;
00791   }
00792 }
00793 
00794 // Creates the implicit sequence if there isn't one.
00795 InSequence::InSequence() {
00796   if (internal::g_gmock_implicit_sequence.get() == NULL) {
00797     internal::g_gmock_implicit_sequence.set(new Sequence);
00798     sequence_created_ = true;
00799   } else {
00800     sequence_created_ = false;
00801   }
00802 }
00803 
00804 // Deletes the implicit sequence if it was created by the constructor
00805 // of this object.
00806 InSequence::~InSequence() {
00807   if (sequence_created_) {
00808     delete internal::g_gmock_implicit_sequence.get();
00809     internal::g_gmock_implicit_sequence.set(NULL);
00810   }
00811 }
00812 
00813 }  // namespace testing


ros_opcua_impl_freeopcua
Author(s): Denis Štogl
autogenerated on Sat Jun 8 2019 18:24:42