gmock-spec-builders.cc 29 KB

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