gmock-spec-builders.cc 32 KB

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