/testlibs/gmock/src/gmock-spec-builders.cc

https://github.com/deltaforge/nebu-app-hadoop · C++ · 797 lines · 472 code · 91 blank · 234 comment · 97 complexity · c99cdd67bb75bf3bb7c23f5417ca3e4a MD5 · raw file

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