gmock-spec-builders.cc 33 KB

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