PageRenderTime 63ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/testlibs/gmock/include/gmock/gmock-spec-builders.h

https://github.com/deltaforge/nebu-app-mongo
C Header | 1749 lines | 873 code | 249 blank | 627 comment | 61 complexity | 89b340ccf0bd3a5abea06db2622c550e MD5 | raw file
Possible License(s): LGPL-3.0, BSD-3-Clause
  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 ON_CALL() and EXPECT_CALL() macros.
  34. //
  35. // A user can use the ON_CALL() macro to specify the default action of
  36. // a mock method. The syntax is:
  37. //
  38. // ON_CALL(mock_object, Method(argument-matchers))
  39. // .With(multi-argument-matcher)
  40. // .WillByDefault(action);
  41. //
  42. // where the .With() clause is optional.
  43. //
  44. // A user can use the EXPECT_CALL() macro to specify an expectation on
  45. // a mock method. The syntax is:
  46. //
  47. // EXPECT_CALL(mock_object, Method(argument-matchers))
  48. // .With(multi-argument-matchers)
  49. // .Times(cardinality)
  50. // .InSequence(sequences)
  51. // .After(expectations)
  52. // .WillOnce(action)
  53. // .WillRepeatedly(action)
  54. // .RetiresOnSaturation();
  55. //
  56. // where all clauses are optional, and .InSequence()/.After()/
  57. // .WillOnce() can appear any number of times.
  58. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
  59. #define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
  60. #include <map>
  61. #include <set>
  62. #include <sstream>
  63. #include <string>
  64. #include <vector>
  65. #include "gmock/gmock-actions.h"
  66. #include "gmock/gmock-cardinalities.h"
  67. #include "gmock/gmock-matchers.h"
  68. #include "gmock/internal/gmock-internal-utils.h"
  69. #include "gmock/internal/gmock-port.h"
  70. #include "gtest/gtest.h"
  71. namespace testing {
  72. // An abstract handle of an expectation.
  73. class Expectation;
  74. // A set of expectation handles.
  75. class ExpectationSet;
  76. // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
  77. // and MUST NOT BE USED IN USER CODE!!!
  78. namespace internal {
  79. // Implements a mock function.
  80. template <typename F> class FunctionMocker;
  81. // Base class for expectations.
  82. class ExpectationBase;
  83. // Implements an expectation.
  84. template <typename F> class TypedExpectation;
  85. // Helper class for testing the Expectation class template.
  86. class ExpectationTester;
  87. // Base class for function mockers.
  88. template <typename F> class FunctionMockerBase;
  89. // Protects the mock object registry (in class Mock), all function
  90. // mockers, and all expectations.
  91. //
  92. // The reason we don't use more fine-grained protection is: when a
  93. // mock function Foo() is called, it needs to consult its expectations
  94. // to see which one should be picked. If another thread is allowed to
  95. // call a mock function (either Foo() or a different one) at the same
  96. // time, it could affect the "retired" attributes of Foo()'s
  97. // expectations when InSequence() is used, and thus affect which
  98. // expectation gets picked. Therefore, we sequence all mock function
  99. // calls to ensure the integrity of the mock objects' states.
  100. GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
  101. // Untyped base class for ActionResultHolder<R>.
  102. class UntypedActionResultHolderBase;
  103. // Abstract base class of FunctionMockerBase. This is the
  104. // type-agnostic part of the function mocker interface. Its pure
  105. // virtual methods are implemented by FunctionMockerBase.
  106. class UntypedFunctionMockerBase {
  107. public:
  108. UntypedFunctionMockerBase();
  109. virtual ~UntypedFunctionMockerBase();
  110. // Verifies that all expectations on this mock function have been
  111. // satisfied. Reports one or more Google Test non-fatal failures
  112. // and returns false if not.
  113. // L >= g_gmock_mutex
  114. bool VerifyAndClearExpectationsLocked();
  115. // Clears the ON_CALL()s set on this mock function.
  116. // L >= g_gmock_mutex
  117. virtual void ClearDefaultActionsLocked() = 0;
  118. // In all of the following Untyped* functions, it's the caller's
  119. // responsibility to guarantee the correctness of the arguments'
  120. // types.
  121. // Performs the default action with the given arguments and returns
  122. // the action's result. The call description string will be used in
  123. // the error message to describe the call in the case the default
  124. // action fails.
  125. // L = *
  126. virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
  127. const void* untyped_args,
  128. const string& call_description) const = 0;
  129. // Performs the given action with the given arguments and returns
  130. // the action's result.
  131. // L = *
  132. virtual UntypedActionResultHolderBase* UntypedPerformAction(
  133. const void* untyped_action,
  134. const void* untyped_args) const = 0;
  135. // Writes a message that the call is uninteresting (i.e. neither
  136. // explicitly expected nor explicitly unexpected) to the given
  137. // ostream.
  138. // L < g_gmock_mutex
  139. virtual void UntypedDescribeUninterestingCall(const void* untyped_args,
  140. ::std::ostream* os) const = 0;
  141. // Returns the expectation that matches the given function arguments
  142. // (or NULL is there's no match); when a match is found,
  143. // untyped_action is set to point to the action that should be
  144. // performed (or NULL if the action is "do default"), and
  145. // is_excessive is modified to indicate whether the call exceeds the
  146. // expected number.
  147. // L < g_gmock_mutex
  148. virtual const ExpectationBase* UntypedFindMatchingExpectation(
  149. const void* untyped_args,
  150. const void** untyped_action, bool* is_excessive,
  151. ::std::ostream* what, ::std::ostream* why) = 0;
  152. // Prints the given function arguments to the ostream.
  153. virtual void UntypedPrintArgs(const void* untyped_args,
  154. ::std::ostream* os) const = 0;
  155. // Sets the mock object this mock method belongs to, and registers
  156. // this information in the global mock registry. Will be called
  157. // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
  158. // method.
  159. // TODO(wan@google.com): rename to SetAndRegisterOwner().
  160. // L < g_gmock_mutex
  161. void RegisterOwner(const void* mock_obj);
  162. // Sets the mock object this mock method belongs to, and sets the
  163. // name of the mock function. Will be called upon each invocation
  164. // of this mock function.
  165. // L < g_gmock_mutex
  166. void SetOwnerAndName(const void* mock_obj, const char* name);
  167. // Returns the mock object this mock method belongs to. Must be
  168. // called after RegisterOwner() or SetOwnerAndName() has been
  169. // called.
  170. // L < g_gmock_mutex
  171. const void* MockObject() const;
  172. // Returns the name of this mock method. Must be called after
  173. // SetOwnerAndName() has been called.
  174. // L < g_gmock_mutex
  175. const char* Name() const;
  176. // Returns the result of invoking this mock function with the given
  177. // arguments. This function can be safely called from multiple
  178. // threads concurrently. The caller is responsible for deleting the
  179. // result.
  180. // L < g_gmock_mutex
  181. const UntypedActionResultHolderBase* UntypedInvokeWith(
  182. const void* untyped_args);
  183. protected:
  184. typedef std::vector<const void*> UntypedOnCallSpecs;
  185. typedef std::vector<internal::linked_ptr<ExpectationBase> >
  186. UntypedExpectations;
  187. // Returns an Expectation object that references and co-owns exp,
  188. // which must be an expectation on this mock function.
  189. Expectation GetHandleOf(ExpectationBase* exp);
  190. // Address of the mock object this mock method belongs to. Only
  191. // valid after this mock method has been called or
  192. // ON_CALL/EXPECT_CALL has been invoked on it.
  193. const void* mock_obj_; // Protected by g_gmock_mutex.
  194. // Name of the function being mocked. Only valid after this mock
  195. // method has been called.
  196. const char* name_; // Protected by g_gmock_mutex.
  197. // All default action specs for this function mocker.
  198. UntypedOnCallSpecs untyped_on_call_specs_;
  199. // All expectations for this function mocker.
  200. UntypedExpectations untyped_expectations_;
  201. }; // class UntypedFunctionMockerBase
  202. // Untyped base class for OnCallSpec<F>.
  203. class UntypedOnCallSpecBase {
  204. public:
  205. // The arguments are the location of the ON_CALL() statement.
  206. UntypedOnCallSpecBase(const char* a_file, int a_line)
  207. : file_(a_file), line_(a_line), last_clause_(kNone) {}
  208. // Where in the source file was the default action spec defined?
  209. const char* file() const { return file_; }
  210. int line() const { return line_; }
  211. protected:
  212. // Gives each clause in the ON_CALL() statement a name.
  213. enum Clause {
  214. // Do not change the order of the enum members! The run-time
  215. // syntax checking relies on it.
  216. kNone,
  217. kWith,
  218. kWillByDefault
  219. };
  220. // Asserts that the ON_CALL() statement has a certain property.
  221. void AssertSpecProperty(bool property, const string& failure_message) const {
  222. Assert(property, file_, line_, failure_message);
  223. }
  224. // Expects that the ON_CALL() statement has a certain property.
  225. void ExpectSpecProperty(bool property, const string& failure_message) const {
  226. Expect(property, file_, line_, failure_message);
  227. }
  228. const char* file_;
  229. int line_;
  230. // The last clause in the ON_CALL() statement as seen so far.
  231. // Initially kNone and changes as the statement is parsed.
  232. Clause last_clause_;
  233. }; // class UntypedOnCallSpecBase
  234. // This template class implements an ON_CALL spec.
  235. template <typename F>
  236. class OnCallSpec : public UntypedOnCallSpecBase {
  237. public:
  238. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  239. typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
  240. // Constructs an OnCallSpec object from the information inside
  241. // the parenthesis of an ON_CALL() statement.
  242. OnCallSpec(const char* a_file, int a_line,
  243. const ArgumentMatcherTuple& matchers)
  244. : UntypedOnCallSpecBase(a_file, a_line),
  245. matchers_(matchers),
  246. // By default, extra_matcher_ should match anything. However,
  247. // we cannot initialize it with _ as that triggers a compiler
  248. // bug in Symbian's C++ compiler (cannot decide between two
  249. // overloaded constructors of Matcher<const ArgumentTuple&>).
  250. extra_matcher_(A<const ArgumentTuple&>()) {
  251. }
  252. // Implements the .With() clause.
  253. OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
  254. // Makes sure this is called at most once.
  255. ExpectSpecProperty(last_clause_ < kWith,
  256. ".With() cannot appear "
  257. "more than once in an ON_CALL().");
  258. last_clause_ = kWith;
  259. extra_matcher_ = m;
  260. return *this;
  261. }
  262. // Implements the .WillByDefault() clause.
  263. OnCallSpec& WillByDefault(const Action<F>& action) {
  264. ExpectSpecProperty(last_clause_ < kWillByDefault,
  265. ".WillByDefault() must appear "
  266. "exactly once in an ON_CALL().");
  267. last_clause_ = kWillByDefault;
  268. ExpectSpecProperty(!action.IsDoDefault(),
  269. "DoDefault() cannot be used in ON_CALL().");
  270. action_ = action;
  271. return *this;
  272. }
  273. // Returns true iff the given arguments match the matchers.
  274. bool Matches(const ArgumentTuple& args) const {
  275. return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
  276. }
  277. // Returns the action specified by the user.
  278. const Action<F>& GetAction() const {
  279. AssertSpecProperty(last_clause_ == kWillByDefault,
  280. ".WillByDefault() must appear exactly "
  281. "once in an ON_CALL().");
  282. return action_;
  283. }
  284. private:
  285. // The information in statement
  286. //
  287. // ON_CALL(mock_object, Method(matchers))
  288. // .With(multi-argument-matcher)
  289. // .WillByDefault(action);
  290. //
  291. // is recorded in the data members like this:
  292. //
  293. // source file that contains the statement => file_
  294. // line number of the statement => line_
  295. // matchers => matchers_
  296. // multi-argument-matcher => extra_matcher_
  297. // action => action_
  298. ArgumentMatcherTuple matchers_;
  299. Matcher<const ArgumentTuple&> extra_matcher_;
  300. Action<F> action_;
  301. }; // class OnCallSpec
  302. // Possible reactions on uninteresting calls. TODO(wan@google.com):
  303. // rename the enum values to the kFoo style.
  304. enum CallReaction {
  305. ALLOW,
  306. WARN,
  307. FAIL
  308. };
  309. } // namespace internal
  310. // Utilities for manipulating mock objects.
  311. class Mock {
  312. public:
  313. // The following public methods can be called concurrently.
  314. // Tells Google Mock to ignore mock_obj when checking for leaked
  315. // mock objects.
  316. static void AllowLeak(const void* mock_obj);
  317. // Verifies and clears all expectations on the given mock object.
  318. // If the expectations aren't satisfied, generates one or more
  319. // Google Test non-fatal failures and returns false.
  320. static bool VerifyAndClearExpectations(void* mock_obj);
  321. // Verifies all expectations on the given mock object and clears its
  322. // default actions and expectations. Returns true iff the
  323. // verification was successful.
  324. static bool VerifyAndClear(void* mock_obj);
  325. private:
  326. friend class internal::UntypedFunctionMockerBase;
  327. // Needed for a function mocker to register itself (so that we know
  328. // how to clear a mock object).
  329. template <typename F>
  330. friend class internal::FunctionMockerBase;
  331. template <typename M>
  332. friend class NiceMock;
  333. template <typename M>
  334. friend class StrictMock;
  335. // Tells Google Mock to allow uninteresting calls on the given mock
  336. // object.
  337. // L < g_gmock_mutex
  338. static void AllowUninterestingCalls(const void* mock_obj);
  339. // Tells Google Mock to warn the user about uninteresting calls on
  340. // the given mock object.
  341. // L < g_gmock_mutex
  342. static void WarnUninterestingCalls(const void* mock_obj);
  343. // Tells Google Mock to fail uninteresting calls on the given mock
  344. // object.
  345. // L < g_gmock_mutex
  346. static void FailUninterestingCalls(const void* mock_obj);
  347. // Tells Google Mock the given mock object is being destroyed and
  348. // its entry in the call-reaction table should be removed.
  349. // L < g_gmock_mutex
  350. static void UnregisterCallReaction(const void* mock_obj);
  351. // Returns the reaction Google Mock will have on uninteresting calls
  352. // made on the given mock object.
  353. // L < g_gmock_mutex
  354. static internal::CallReaction GetReactionOnUninterestingCalls(
  355. const void* mock_obj);
  356. // Verifies that all expectations on the given mock object have been
  357. // satisfied. Reports one or more Google Test non-fatal failures
  358. // and returns false if not.
  359. // L >= g_gmock_mutex
  360. static bool VerifyAndClearExpectationsLocked(void* mock_obj);
  361. // Clears all ON_CALL()s set on the given mock object.
  362. // L >= g_gmock_mutex
  363. static void ClearDefaultActionsLocked(void* mock_obj);
  364. // Registers a mock object and a mock method it owns.
  365. // L < g_gmock_mutex
  366. static void Register(const void* mock_obj,
  367. internal::UntypedFunctionMockerBase* mocker);
  368. // Tells Google Mock where in the source code mock_obj is used in an
  369. // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
  370. // information helps the user identify which object it is.
  371. // L < g_gmock_mutex
  372. static void RegisterUseByOnCallOrExpectCall(
  373. const void* mock_obj, const char* file, int line);
  374. // Unregisters a mock method; removes the owning mock object from
  375. // the registry when the last mock method associated with it has
  376. // been unregistered. This is called only in the destructor of
  377. // FunctionMockerBase.
  378. // L >= g_gmock_mutex
  379. static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker);
  380. }; // class Mock
  381. // An abstract handle of an expectation. Useful in the .After()
  382. // clause of EXPECT_CALL() for setting the (partial) order of
  383. // expectations. The syntax:
  384. //
  385. // Expectation e1 = EXPECT_CALL(...)...;
  386. // EXPECT_CALL(...).After(e1)...;
  387. //
  388. // sets two expectations where the latter can only be matched after
  389. // the former has been satisfied.
  390. //
  391. // Notes:
  392. // - This class is copyable and has value semantics.
  393. // - Constness is shallow: a const Expectation object itself cannot
  394. // be modified, but the mutable methods of the ExpectationBase
  395. // object it references can be called via expectation_base().
  396. // - The constructors and destructor are defined out-of-line because
  397. // the Symbian WINSCW compiler wants to otherwise instantiate them
  398. // when it sees this class definition, at which point it doesn't have
  399. // ExpectationBase available yet, leading to incorrect destruction
  400. // in the linked_ptr (or compilation errors if using a checking
  401. // linked_ptr).
  402. class Expectation {
  403. public:
  404. // Constructs a null object that doesn't reference any expectation.
  405. Expectation();
  406. ~Expectation();
  407. // This single-argument ctor must not be explicit, in order to support the
  408. // Expectation e = EXPECT_CALL(...);
  409. // syntax.
  410. //
  411. // A TypedExpectation object stores its pre-requisites as
  412. // Expectation objects, and needs to call the non-const Retire()
  413. // method on the ExpectationBase objects they reference. Therefore
  414. // Expectation must receive a *non-const* reference to the
  415. // ExpectationBase object.
  416. Expectation(internal::ExpectationBase& exp); // NOLINT
  417. // The compiler-generated copy ctor and operator= work exactly as
  418. // intended, so we don't need to define our own.
  419. // Returns true iff rhs references the same expectation as this object does.
  420. bool operator==(const Expectation& rhs) const {
  421. return expectation_base_ == rhs.expectation_base_;
  422. }
  423. bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
  424. private:
  425. friend class ExpectationSet;
  426. friend class Sequence;
  427. friend class ::testing::internal::ExpectationBase;
  428. friend class ::testing::internal::UntypedFunctionMockerBase;
  429. template <typename F>
  430. friend class ::testing::internal::FunctionMockerBase;
  431. template <typename F>
  432. friend class ::testing::internal::TypedExpectation;
  433. // This comparator is needed for putting Expectation objects into a set.
  434. class Less {
  435. public:
  436. bool operator()(const Expectation& lhs, const Expectation& rhs) const {
  437. return lhs.expectation_base_.get() < rhs.expectation_base_.get();
  438. }
  439. };
  440. typedef ::std::set<Expectation, Less> Set;
  441. Expectation(
  442. const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
  443. // Returns the expectation this object references.
  444. const internal::linked_ptr<internal::ExpectationBase>&
  445. expectation_base() const {
  446. return expectation_base_;
  447. }
  448. // A linked_ptr that co-owns the expectation this handle references.
  449. internal::linked_ptr<internal::ExpectationBase> expectation_base_;
  450. };
  451. // A set of expectation handles. Useful in the .After() clause of
  452. // EXPECT_CALL() for setting the (partial) order of expectations. The
  453. // syntax:
  454. //
  455. // ExpectationSet es;
  456. // es += EXPECT_CALL(...)...;
  457. // es += EXPECT_CALL(...)...;
  458. // EXPECT_CALL(...).After(es)...;
  459. //
  460. // sets three expectations where the last one can only be matched
  461. // after the first two have both been satisfied.
  462. //
  463. // This class is copyable and has value semantics.
  464. class ExpectationSet {
  465. public:
  466. // A bidirectional iterator that can read a const element in the set.
  467. typedef Expectation::Set::const_iterator const_iterator;
  468. // An object stored in the set. This is an alias of Expectation.
  469. typedef Expectation::Set::value_type value_type;
  470. // Constructs an empty set.
  471. ExpectationSet() {}
  472. // This single-argument ctor must not be explicit, in order to support the
  473. // ExpectationSet es = EXPECT_CALL(...);
  474. // syntax.
  475. ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
  476. *this += Expectation(exp);
  477. }
  478. // This single-argument ctor implements implicit conversion from
  479. // Expectation and thus must not be explicit. This allows either an
  480. // Expectation or an ExpectationSet to be used in .After().
  481. ExpectationSet(const Expectation& e) { // NOLINT
  482. *this += e;
  483. }
  484. // The compiler-generator ctor and operator= works exactly as
  485. // intended, so we don't need to define our own.
  486. // Returns true iff rhs contains the same set of Expectation objects
  487. // as this does.
  488. bool operator==(const ExpectationSet& rhs) const {
  489. return expectations_ == rhs.expectations_;
  490. }
  491. bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
  492. // Implements the syntax
  493. // expectation_set += EXPECT_CALL(...);
  494. ExpectationSet& operator+=(const Expectation& e) {
  495. expectations_.insert(e);
  496. return *this;
  497. }
  498. int size() const { return static_cast<int>(expectations_.size()); }
  499. const_iterator begin() const { return expectations_.begin(); }
  500. const_iterator end() const { return expectations_.end(); }
  501. private:
  502. Expectation::Set expectations_;
  503. };
  504. // Sequence objects are used by a user to specify the relative order
  505. // in which the expectations should match. They are copyable (we rely
  506. // on the compiler-defined copy constructor and assignment operator).
  507. class Sequence {
  508. public:
  509. // Constructs an empty sequence.
  510. Sequence() : last_expectation_(new Expectation) {}
  511. // Adds an expectation to this sequence. The caller must ensure
  512. // that no other thread is accessing this Sequence object.
  513. void AddExpectation(const Expectation& expectation) const;
  514. private:
  515. // The last expectation in this sequence. We use a linked_ptr here
  516. // because Sequence objects are copyable and we want the copies to
  517. // be aliases. The linked_ptr allows the copies to co-own and share
  518. // the same Expectation object.
  519. internal::linked_ptr<Expectation> last_expectation_;
  520. }; // class Sequence
  521. // An object of this type causes all EXPECT_CALL() statements
  522. // encountered in its scope to be put in an anonymous sequence. The
  523. // work is done in the constructor and destructor. You should only
  524. // create an InSequence object on the stack.
  525. //
  526. // The sole purpose for this class is to support easy definition of
  527. // sequential expectations, e.g.
  528. //
  529. // {
  530. // InSequence dummy; // The name of the object doesn't matter.
  531. //
  532. // // The following expectations must match in the order they appear.
  533. // EXPECT_CALL(a, Bar())...;
  534. // EXPECT_CALL(a, Baz())...;
  535. // ...
  536. // EXPECT_CALL(b, Xyz())...;
  537. // }
  538. //
  539. // You can create InSequence objects in multiple threads, as long as
  540. // they are used to affect different mock objects. The idea is that
  541. // each thread can create and set up its own mocks as if it's the only
  542. // thread. However, for clarity of your tests we recommend you to set
  543. // up mocks in the main thread unless you have a good reason not to do
  544. // so.
  545. class InSequence {
  546. public:
  547. InSequence();
  548. ~InSequence();
  549. private:
  550. bool sequence_created_;
  551. GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
  552. } GTEST_ATTRIBUTE_UNUSED_;
  553. namespace internal {
  554. // Points to the implicit sequence introduced by a living InSequence
  555. // object (if any) in the current thread or NULL.
  556. extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
  557. // Base class for implementing expectations.
  558. //
  559. // There are two reasons for having a type-agnostic base class for
  560. // Expectation:
  561. //
  562. // 1. We need to store collections of expectations of different
  563. // types (e.g. all pre-requisites of a particular expectation, all
  564. // expectations in a sequence). Therefore these expectation objects
  565. // must share a common base class.
  566. //
  567. // 2. We can avoid binary code bloat by moving methods not depending
  568. // on the template argument of Expectation to the base class.
  569. //
  570. // This class is internal and mustn't be used by user code directly.
  571. class ExpectationBase {
  572. public:
  573. // source_text is the EXPECT_CALL(...) source that created this Expectation.
  574. ExpectationBase(const char* file, int line, const string& source_text);
  575. virtual ~ExpectationBase();
  576. // Where in the source file was the expectation spec defined?
  577. const char* file() const { return file_; }
  578. int line() const { return line_; }
  579. const char* source_text() const { return source_text_.c_str(); }
  580. // Returns the cardinality specified in the expectation spec.
  581. const Cardinality& cardinality() const { return cardinality_; }
  582. // Describes the source file location of this expectation.
  583. void DescribeLocationTo(::std::ostream* os) const {
  584. *os << FormatFileLocation(file(), line()) << " ";
  585. }
  586. // Describes how many times a function call matching this
  587. // expectation has occurred.
  588. // L >= g_gmock_mutex
  589. void DescribeCallCountTo(::std::ostream* os) const;
  590. // If this mock method has an extra matcher (i.e. .With(matcher)),
  591. // describes it to the ostream.
  592. virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
  593. protected:
  594. friend class ::testing::Expectation;
  595. friend class UntypedFunctionMockerBase;
  596. enum Clause {
  597. // Don't change the order of the enum members!
  598. kNone,
  599. kWith,
  600. kTimes,
  601. kInSequence,
  602. kAfter,
  603. kWillOnce,
  604. kWillRepeatedly,
  605. kRetiresOnSaturation
  606. };
  607. typedef std::vector<const void*> UntypedActions;
  608. // Returns an Expectation object that references and co-owns this
  609. // expectation.
  610. virtual Expectation GetHandle() = 0;
  611. // Asserts that the EXPECT_CALL() statement has the given property.
  612. void AssertSpecProperty(bool property, const string& failure_message) const {
  613. Assert(property, file_, line_, failure_message);
  614. }
  615. // Expects that the EXPECT_CALL() statement has the given property.
  616. void ExpectSpecProperty(bool property, const string& failure_message) const {
  617. Expect(property, file_, line_, failure_message);
  618. }
  619. // Explicitly specifies the cardinality of this expectation. Used
  620. // by the subclasses to implement the .Times() clause.
  621. void SpecifyCardinality(const Cardinality& cardinality);
  622. // Returns true iff the user specified the cardinality explicitly
  623. // using a .Times().
  624. bool cardinality_specified() const { return cardinality_specified_; }
  625. // Sets the cardinality of this expectation spec.
  626. void set_cardinality(const Cardinality& a_cardinality) {
  627. cardinality_ = a_cardinality;
  628. }
  629. // The following group of methods should only be called after the
  630. // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
  631. // the current thread.
  632. // Retires all pre-requisites of this expectation.
  633. // L >= g_gmock_mutex
  634. void RetireAllPreRequisites();
  635. // Returns true iff this expectation is retired.
  636. // L >= g_gmock_mutex
  637. bool is_retired() const {
  638. g_gmock_mutex.AssertHeld();
  639. return retired_;
  640. }
  641. // Retires this expectation.
  642. // L >= g_gmock_mutex
  643. void Retire() {
  644. g_gmock_mutex.AssertHeld();
  645. retired_ = true;
  646. }
  647. // Returns true iff this expectation is satisfied.
  648. // L >= g_gmock_mutex
  649. bool IsSatisfied() const {
  650. g_gmock_mutex.AssertHeld();
  651. return cardinality().IsSatisfiedByCallCount(call_count_);
  652. }
  653. // Returns true iff this expectation is saturated.
  654. // L >= g_gmock_mutex
  655. bool IsSaturated() const {
  656. g_gmock_mutex.AssertHeld();
  657. return cardinality().IsSaturatedByCallCount(call_count_);
  658. }
  659. // Returns true iff this expectation is over-saturated.
  660. // L >= g_gmock_mutex
  661. bool IsOverSaturated() const {
  662. g_gmock_mutex.AssertHeld();
  663. return cardinality().IsOverSaturatedByCallCount(call_count_);
  664. }
  665. // Returns true iff all pre-requisites of this expectation are satisfied.
  666. // L >= g_gmock_mutex
  667. bool AllPrerequisitesAreSatisfied() const;
  668. // Adds unsatisfied pre-requisites of this expectation to 'result'.
  669. // L >= g_gmock_mutex
  670. void FindUnsatisfiedPrerequisites(ExpectationSet* result) const;
  671. // Returns the number this expectation has been invoked.
  672. // L >= g_gmock_mutex
  673. int call_count() const {
  674. g_gmock_mutex.AssertHeld();
  675. return call_count_;
  676. }
  677. // Increments the number this expectation has been invoked.
  678. // L >= g_gmock_mutex
  679. void IncrementCallCount() {
  680. g_gmock_mutex.AssertHeld();
  681. call_count_++;
  682. }
  683. // Checks the action count (i.e. the number of WillOnce() and
  684. // WillRepeatedly() clauses) against the cardinality if this hasn't
  685. // been done before. Prints a warning if there are too many or too
  686. // few actions.
  687. // L < mutex_
  688. void CheckActionCountIfNotDone() const;
  689. friend class ::testing::Sequence;
  690. friend class ::testing::internal::ExpectationTester;
  691. template <typename Function>
  692. friend class TypedExpectation;
  693. // Implements the .Times() clause.
  694. void UntypedTimes(const Cardinality& a_cardinality);
  695. // This group of fields are part of the spec and won't change after
  696. // an EXPECT_CALL() statement finishes.
  697. const char* file_; // The file that contains the expectation.
  698. int line_; // The line number of the expectation.
  699. const string source_text_; // The EXPECT_CALL(...) source text.
  700. // True iff the cardinality is specified explicitly.
  701. bool cardinality_specified_;
  702. Cardinality cardinality_; // The cardinality of the expectation.
  703. // The immediate pre-requisites (i.e. expectations that must be
  704. // satisfied before this expectation can be matched) of this
  705. // expectation. We use linked_ptr in the set because we want an
  706. // Expectation object to be co-owned by its FunctionMocker and its
  707. // successors. This allows multiple mock objects to be deleted at
  708. // different times.
  709. ExpectationSet immediate_prerequisites_;
  710. // This group of fields are the current state of the expectation,
  711. // and can change as the mock function is called.
  712. int call_count_; // How many times this expectation has been invoked.
  713. bool retired_; // True iff this expectation has retired.
  714. UntypedActions untyped_actions_;
  715. bool extra_matcher_specified_;
  716. bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
  717. bool retires_on_saturation_;
  718. Clause last_clause_;
  719. mutable bool action_count_checked_; // Under mutex_.
  720. mutable Mutex mutex_; // Protects action_count_checked_.
  721. GTEST_DISALLOW_ASSIGN_(ExpectationBase);
  722. }; // class ExpectationBase
  723. // Impements an expectation for the given function type.
  724. template <typename F>
  725. class TypedExpectation : public ExpectationBase {
  726. public:
  727. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  728. typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
  729. typedef typename Function<F>::Result Result;
  730. TypedExpectation(FunctionMockerBase<F>* owner,
  731. const char* a_file, int a_line, const string& a_source_text,
  732. const ArgumentMatcherTuple& m)
  733. : ExpectationBase(a_file, a_line, a_source_text),
  734. owner_(owner),
  735. matchers_(m),
  736. // By default, extra_matcher_ should match anything. However,
  737. // we cannot initialize it with _ as that triggers a compiler
  738. // bug in Symbian's C++ compiler (cannot decide between two
  739. // overloaded constructors of Matcher<const ArgumentTuple&>).
  740. extra_matcher_(A<const ArgumentTuple&>()),
  741. repeated_action_(DoDefault()) {}
  742. virtual ~TypedExpectation() {
  743. // Check the validity of the action count if it hasn't been done
  744. // yet (for example, if the expectation was never used).
  745. CheckActionCountIfNotDone();
  746. for (UntypedActions::const_iterator it = untyped_actions_.begin();
  747. it != untyped_actions_.end(); ++it) {
  748. delete static_cast<const Action<F>*>(*it);
  749. }
  750. }
  751. // Implements the .With() clause.
  752. TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
  753. if (last_clause_ == kWith) {
  754. ExpectSpecProperty(false,
  755. ".With() cannot appear "
  756. "more than once in an EXPECT_CALL().");
  757. } else {
  758. ExpectSpecProperty(last_clause_ < kWith,
  759. ".With() must be the first "
  760. "clause in an EXPECT_CALL().");
  761. }
  762. last_clause_ = kWith;
  763. extra_matcher_ = m;
  764. extra_matcher_specified_ = true;
  765. return *this;
  766. }
  767. // Implements the .Times() clause.
  768. TypedExpectation& Times(const Cardinality& a_cardinality) {
  769. ExpectationBase::UntypedTimes(a_cardinality);
  770. return *this;
  771. }
  772. // Implements the .Times() clause.
  773. TypedExpectation& Times(int n) {
  774. return Times(Exactly(n));
  775. }
  776. // Implements the .InSequence() clause.
  777. TypedExpectation& InSequence(const Sequence& s) {
  778. ExpectSpecProperty(last_clause_ <= kInSequence,
  779. ".InSequence() cannot appear after .After(),"
  780. " .WillOnce(), .WillRepeatedly(), or "
  781. ".RetiresOnSaturation().");
  782. last_clause_ = kInSequence;
  783. s.AddExpectation(GetHandle());
  784. return *this;
  785. }
  786. TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
  787. return InSequence(s1).InSequence(s2);
  788. }
  789. TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
  790. const Sequence& s3) {
  791. return InSequence(s1, s2).InSequence(s3);
  792. }
  793. TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
  794. const Sequence& s3, const Sequence& s4) {
  795. return InSequence(s1, s2, s3).InSequence(s4);
  796. }
  797. TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
  798. const Sequence& s3, const Sequence& s4,
  799. const Sequence& s5) {
  800. return InSequence(s1, s2, s3, s4).InSequence(s5);
  801. }
  802. // Implements that .After() clause.
  803. TypedExpectation& After(const ExpectationSet& s) {
  804. ExpectSpecProperty(last_clause_ <= kAfter,
  805. ".After() cannot appear after .WillOnce(),"
  806. " .WillRepeatedly(), or "
  807. ".RetiresOnSaturation().");
  808. last_clause_ = kAfter;
  809. for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
  810. immediate_prerequisites_ += *it;
  811. }
  812. return *this;
  813. }
  814. TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
  815. return After(s1).After(s2);
  816. }
  817. TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
  818. const ExpectationSet& s3) {
  819. return After(s1, s2).After(s3);
  820. }
  821. TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
  822. const ExpectationSet& s3, const ExpectationSet& s4) {
  823. return After(s1, s2, s3).After(s4);
  824. }
  825. TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
  826. const ExpectationSet& s3, const ExpectationSet& s4,
  827. const ExpectationSet& s5) {
  828. return After(s1, s2, s3, s4).After(s5);
  829. }
  830. // Implements the .WillOnce() clause.
  831. TypedExpectation& WillOnce(const Action<F>& action) {
  832. ExpectSpecProperty(last_clause_ <= kWillOnce,
  833. ".WillOnce() cannot appear after "
  834. ".WillRepeatedly() or .RetiresOnSaturation().");
  835. last_clause_ = kWillOnce;
  836. untyped_actions_.push_back(new Action<F>(action));
  837. if (!cardinality_specified()) {
  838. set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
  839. }
  840. return *this;
  841. }
  842. // Implements the .WillRepeatedly() clause.
  843. TypedExpectation& WillRepeatedly(const Action<F>& action) {
  844. if (last_clause_ == kWillRepeatedly) {
  845. ExpectSpecProperty(false,
  846. ".WillRepeatedly() cannot appear "
  847. "more than once in an EXPECT_CALL().");
  848. } else {
  849. ExpectSpecProperty(last_clause_ < kWillRepeatedly,
  850. ".WillRepeatedly() cannot appear "
  851. "after .RetiresOnSaturation().");
  852. }
  853. last_clause_ = kWillRepeatedly;
  854. repeated_action_specified_ = true;
  855. repeated_action_ = action;
  856. if (!cardinality_specified()) {
  857. set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
  858. }
  859. // Now that no more action clauses can be specified, we check
  860. // whether their count makes sense.
  861. CheckActionCountIfNotDone();
  862. return *this;
  863. }
  864. // Implements the .RetiresOnSaturation() clause.
  865. TypedExpectation& RetiresOnSaturation() {
  866. ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
  867. ".RetiresOnSaturation() cannot appear "
  868. "more than once.");
  869. last_clause_ = kRetiresOnSaturation;
  870. retires_on_saturation_ = true;
  871. // Now that no more action clauses can be specified, we check
  872. // whether their count makes sense.
  873. CheckActionCountIfNotDone();
  874. return *this;
  875. }
  876. // Returns the matchers for the arguments as specified inside the
  877. // EXPECT_CALL() macro.
  878. const ArgumentMatcherTuple& matchers() const {
  879. return matchers_;
  880. }
  881. // Returns the matcher specified by the .With() clause.
  882. const Matcher<const ArgumentTuple&>& extra_matcher() const {
  883. return extra_matcher_;
  884. }
  885. // Returns the action specified by the .WillRepeatedly() clause.
  886. const Action<F>& repeated_action() const { return repeated_action_; }
  887. // If this mock method has an extra matcher (i.e. .With(matcher)),
  888. // describes it to the ostream.
  889. virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
  890. if (extra_matcher_specified_) {
  891. *os << " Expected args: ";
  892. extra_matcher_.DescribeTo(os);
  893. *os << "\n";
  894. }
  895. }
  896. private:
  897. template <typename Function>
  898. friend class FunctionMockerBase;
  899. // Returns an Expectation object that references and co-owns this
  900. // expectation.
  901. virtual Expectation GetHandle() {
  902. return owner_->GetHandleOf(this);
  903. }
  904. // The following methods will be called only after the EXPECT_CALL()
  905. // statement finishes and when the current thread holds
  906. // g_gmock_mutex.
  907. // Returns true iff this expectation matches the given arguments.
  908. // L >= g_gmock_mutex
  909. bool Matches(const ArgumentTuple& args) const {
  910. g_gmock_mutex.AssertHeld();
  911. return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
  912. }
  913. // Returns true iff this expectation should handle the given arguments.
  914. // L >= g_gmock_mutex
  915. bool ShouldHandleArguments(const ArgumentTuple& args) const {
  916. g_gmock_mutex.AssertHeld();
  917. // In case the action count wasn't checked when the expectation
  918. // was defined (e.g. if this expectation has no WillRepeatedly()
  919. // or RetiresOnSaturation() clause), we check it when the
  920. // expectation is used for the first time.
  921. CheckActionCountIfNotDone();
  922. return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
  923. }
  924. // Describes the result of matching the arguments against this
  925. // expectation to the given ostream.
  926. // L >= g_gmock_mutex
  927. void ExplainMatchResultTo(const ArgumentTuple& args,
  928. ::std::ostream* os) const {
  929. g_gmock_mutex.AssertHeld();
  930. if (is_retired()) {
  931. *os << " Expected: the expectation is active\n"
  932. << " Actual: it is retired\n";
  933. } else if (!Matches(args)) {
  934. if (!TupleMatches(matchers_, args)) {
  935. ExplainMatchFailureTupleTo(matchers_, args, os);
  936. }
  937. StringMatchResultListener listener;
  938. if (!extra_matcher_.MatchAndExplain(args, &listener)) {
  939. *os << " Expected args: ";
  940. extra_matcher_.DescribeTo(os);
  941. *os << "\n Actual: don't match";
  942. internal::PrintIfNotEmpty(listener.str(), os);
  943. *os << "\n";
  944. }
  945. } else if (!AllPrerequisitesAreSatisfied()) {
  946. *os << " Expected: all pre-requisites are satisfied\n"
  947. << " Actual: the following immediate pre-requisites "
  948. << "are not satisfied:\n";
  949. ExpectationSet unsatisfied_prereqs;
  950. FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
  951. int i = 0;
  952. for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
  953. it != unsatisfied_prereqs.end(); ++it) {
  954. it->expectation_base()->DescribeLocationTo(os);
  955. *os << "pre-requisite #" << i++ << "\n";
  956. }
  957. *os << " (end of pre-requisites)\n";
  958. } else {
  959. // This line is here just for completeness' sake. It will never
  960. // be executed as currently the ExplainMatchResultTo() function
  961. // is called only when the mock function call does NOT match the
  962. // expectation.
  963. *os << "The call matches the expectation.\n";
  964. }
  965. }
  966. // Returns the action that should be taken for the current invocation.
  967. // L >= g_gmock_mutex
  968. const Action<F>& GetCurrentAction(const FunctionMockerBase<F>* mocker,
  969. const ArgumentTuple& args) const {
  970. g_gmock_mutex.AssertHeld();
  971. const int count = call_count();
  972. Assert(count >= 1, __FILE__, __LINE__,
  973. "call_count() is <= 0 when GetCurrentAction() is "
  974. "called - this should never happen.");
  975. const int action_count = static_cast<int>(untyped_actions_.size());
  976. if (action_count > 0 && !repeated_action_specified_ &&
  977. count > action_count) {
  978. // If there is at least one WillOnce() and no WillRepeatedly(),
  979. // we warn the user when the WillOnce() clauses ran out.
  980. ::std::stringstream ss;
  981. DescribeLocationTo(&ss);
  982. ss << "Actions ran out in " << source_text() << "...\n"
  983. << "Called " << count << " times, but only "
  984. << action_count << " WillOnce()"
  985. << (action_count == 1 ? " is" : "s are") << " specified - ";
  986. mocker->DescribeDefaultActionTo(args, &ss);
  987. Log(WARNING, ss.str(), 1);
  988. }
  989. return count <= action_count ?
  990. *static_cast<const Action<F>*>(untyped_actions_[count - 1]) :
  991. repeated_action();
  992. }
  993. // Given the arguments of a mock function call, if the call will
  994. // over-saturate this expectation, returns the default action;
  995. // otherwise, returns the next action in this expectation. Also
  996. // describes *what* happened to 'what', and explains *why* Google
  997. // Mock does it to 'why'. This method is not const as it calls
  998. // IncrementCallCount(). A return value of NULL means the default
  999. // action.
  1000. // L >= g_gmock_mutex
  1001. const Action<F>* GetActionForArguments(const FunctionMockerBase<F>* mocker,
  1002. const ArgumentTuple& args,
  1003. ::std::ostream* what,
  1004. ::std::ostream* why) {
  1005. g_gmock_mutex.AssertHeld();
  1006. if (IsSaturated()) {
  1007. // We have an excessive call.
  1008. IncrementCallCount();
  1009. *what << "Mock function called more times than expected - ";
  1010. mocker->DescribeDefaultActionTo(args, what);
  1011. DescribeCallCountTo(why);
  1012. // TODO(wan@google.com): allow the user to control whether
  1013. // unexpected calls should fail immediately or continue using a
  1014. // flag --gmock_unexpected_calls_are_fatal.
  1015. return NULL;
  1016. }
  1017. IncrementCallCount();
  1018. RetireAllPreRequisites();
  1019. if (retires_on_saturation_ && IsSaturated()) {
  1020. Retire();
  1021. }
  1022. // Must be done after IncrementCount()!
  1023. *what << "Mock function call matches " << source_text() <<"...\n";
  1024. return &(GetCurrentAction(mocker, args));
  1025. }
  1026. // All the fields below won't change once the EXPECT_CALL()
  1027. // statement finishes.
  1028. FunctionMockerBase<F>* const owner_;
  1029. ArgumentMatcherTuple matchers_;
  1030. Matcher<const ArgumentTuple&> extra_matcher_;
  1031. Action<F> repeated_action_;
  1032. GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
  1033. }; // class TypedExpectation
  1034. // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
  1035. // specifying the default behavior of, or expectation on, a mock
  1036. // function.
  1037. // Note: class MockSpec really belongs to the ::testing namespace.
  1038. // However if we define it in ::testing, MSVC will complain when
  1039. // classes in ::testing::internal declare it as a friend class
  1040. // template. To workaround this compiler bug, we define MockSpec in
  1041. // ::testing::internal and import it into ::testing.
  1042. // Logs a message including file and line number information.
  1043. void LogWithLocation(testing::internal::LogSeverity severity,
  1044. const char* file, int line,
  1045. const string& message);
  1046. template <typename F>
  1047. class MockSpec {
  1048. public:
  1049. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  1050. typedef typename internal::Function<F>::ArgumentMatcherTuple
  1051. ArgumentMatcherTuple;
  1052. // Constructs a MockSpec object, given the function mocker object
  1053. // that the spec is associated with.
  1054. explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker)
  1055. : function_mocker_(function_mocker) {}
  1056. // Adds a new default action spec to the function mocker and returns
  1057. // the newly created spec.
  1058. internal::OnCallSpec<F>& InternalDefaultActionSetAt(
  1059. const char* file, int line, const char* obj, const char* call) {
  1060. LogWithLocation(internal::INFO, file, line,
  1061. string("ON_CALL(") + obj + ", " + call + ") invoked");
  1062. return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
  1063. }
  1064. // Adds a new expectation spec to the function mocker and returns
  1065. // the newly created spec.
  1066. internal::TypedExpectation<F>& InternalExpectedAt(
  1067. const char* file, int line, const char* obj, const char* call) {
  1068. const string source_text(string("EXPECT_CALL(") + obj + ", " + call + ")");
  1069. LogWithLocation(internal::INFO, file, line, source_text + " invoked");
  1070. return function_mocker_->AddNewExpectation(
  1071. file, line, source_text, matchers_);
  1072. }
  1073. private:
  1074. template <typename Function>
  1075. friend class internal::FunctionMocker;
  1076. void SetMatchers(const ArgumentMatcherTuple& matchers) {
  1077. matchers_ = matchers;
  1078. }
  1079. // The function mocker that owns this spec.
  1080. internal::FunctionMockerBase<F>* const function_mocker_;
  1081. // The argument matchers specified in the spec.
  1082. ArgumentMatcherTuple matchers_;
  1083. GTEST_DISALLOW_ASSIGN_(MockSpec);
  1084. }; // class MockSpec
  1085. // MSVC warns about using 'this' in base member initializer list, so
  1086. // we need to temporarily disable the warning. We have to do it for
  1087. // the entire class to suppress the warning, even though it's about
  1088. // the constructor only.
  1089. #ifdef _MSC_VER
  1090. # pragma warning(push) // Saves the current warning state.
  1091. # pragma warning(disable:4355) // Temporarily disables warning 4355.
  1092. #endif // _MSV_VER
  1093. // C++ treats the void type specially. For example, you cannot define
  1094. // a void-typed variable or pass a void value to a function.
  1095. // ActionResultHolder<T> holds a value of type T, where T must be a
  1096. // copyable type or void (T doesn't need to be default-constructable).
  1097. // It hides the syntactic difference between void and other types, and
  1098. // is used to unify the code for invoking both void-returning and
  1099. // non-void-returning mock functions.
  1100. // Untyped base class for ActionResultHolder<T>.
  1101. class UntypedActionResultHolderBase {
  1102. public:
  1103. virtual ~UntypedActionResultHolderBase() {}
  1104. // Prints the held value as an action's result to os.
  1105. virtual void PrintAsActionResult(::std::ostream* os) const = 0;
  1106. };
  1107. // This generic definition is used when T is not void.
  1108. template <typename T>
  1109. class ActionResultHolder : public UntypedActionResultHolderBase {
  1110. public:
  1111. explicit ActionResultHolder(T a_value) : value_(a_value) {}
  1112. // The compiler-generated copy constructor and assignment operator
  1113. // are exactly what we need, so we don't need to define them.
  1114. // Returns the held value and deletes this object.
  1115. T GetValueAndDelete() const {
  1116. T retval(value_);
  1117. delete this;
  1118. return retval;
  1119. }
  1120. // Prints the held value as an action's result to os.
  1121. virtual void PrintAsActionResult(::std::ostream* os) const {
  1122. *os << "\n Returns: ";
  1123. // T may be a reference type, so we don't use UniversalPrint().
  1124. UniversalPrinter<T>::Print(value_, os);
  1125. }
  1126. // Performs the given mock function's default action and returns the
  1127. // result in a new-ed ActionResultHolder.
  1128. template <typename F>
  1129. static ActionResultHolder* PerformDefaultAction(
  1130. const FunctionMockerBase<F>* func_mocker,
  1131. const typename Function<F>::ArgumentTuple& args,
  1132. const string& call_description) {
  1133. return new ActionResultHolder(
  1134. func_mocker->PerformDefaultAction(args, call_description));
  1135. }
  1136. // Performs the given action and returns the result in a new-ed
  1137. // ActionResultHolder.
  1138. template <typename F>
  1139. static ActionResultHolder*
  1140. PerformAction(const Action<F>& action,
  1141. const typename Function<F>::ArgumentTuple& args) {
  1142. return new ActionResultHolder(action.Perform(args));
  1143. }
  1144. private:
  1145. T value_;
  1146. // T could be a reference type, so = isn't supported.
  1147. GTEST_DISALLOW_ASSIGN_(ActionResultHolder);
  1148. };
  1149. // Specialization for T = void.
  1150. template <>
  1151. class ActionResultHolder<void> : public UntypedActionResultHolderBase {
  1152. public:
  1153. void GetValueAndDelete() const { delete this; }
  1154. virtual void PrintAsActionResult(::std::ostream* /* os */) const {}
  1155. // Performs the given mock function's default action and returns NULL;
  1156. template <typename F>
  1157. static ActionResultHolder* PerformDefaultAction(
  1158. const FunctionMockerBase<F>* func_mocker,
  1159. const typename Function<F>::ArgumentTuple& args,
  1160. const string& call_description) {
  1161. func_mocker->PerformDefaultAction(args, call_description);
  1162. return NULL;
  1163. }
  1164. // Performs the given action and returns NULL.
  1165. template <typename F>
  1166. static ActionResultHolder* PerformAction(
  1167. const Action<F>& action,
  1168. const typename Function<F>::ArgumentTuple& args) {
  1169. action.Perform(args);
  1170. return NULL;
  1171. }
  1172. };
  1173. // The base of the function mocker class for the given function type.
  1174. // We put the methods in this class instead of its child to avoid code
  1175. // bloat.
  1176. template <typename F>
  1177. class FunctionMockerBase : public UntypedFunctionMockerBase {
  1178. public:
  1179. typedef typename Function<F>::Result Result;
  1180. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  1181. typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
  1182. FunctionMockerBase() : current_spec_(this) {}
  1183. // The destructor verifies that all expectations on this mock
  1184. // function have been satisfied. If not, it will report Google Test
  1185. // non-fatal failures for the violations.
  1186. // L < g_gmock_mutex
  1187. virtual ~FunctionMockerBase() {
  1188. MutexLock l(&g_gmock_mutex);
  1189. VerifyAndClearExpectationsLocked();
  1190. Mock::UnregisterLocked(this);
  1191. ClearDefaultActionsLocked();
  1192. }
  1193. // Returns the ON_CALL spec that matches this mock function with the
  1194. // given arguments; returns NULL if no matching ON_CALL is found.
  1195. // L = *
  1196. const OnCallSpec<F>* FindOnCallSpec(
  1197. const ArgumentTuple& args) const {
  1198. for (UntypedOnCallSpecs::const_reverse_iterator it
  1199. = untyped_on_call_specs_.rbegin();
  1200. it != untyped_on_call_specs_.rend(); ++it) {
  1201. const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
  1202. if (spec->Matches(args))
  1203. return spec;
  1204. }
  1205. return NULL;
  1206. }
  1207. // Performs the default action of this mock function on the given arguments
  1208. // and returns the result. Asserts with a helpful call descrption if there is
  1209. // no valid return value. This method doesn't depend on the mutable state of
  1210. // this object, and thus can be called concurrently without locking.
  1211. // L = *
  1212. Result PerformDefaultAction(const ArgumentTuple& args,
  1213. const string& call_description) const {
  1214. const OnCallSpec<F>* const spec =
  1215. this->FindOnCallSpec(args);
  1216. if (spec != NULL) {
  1217. return spec->GetAction().Perform(args);
  1218. }
  1219. Assert(DefaultValue<Result>::Exists(), "", -1,
  1220. call_description + "\n The mock function has no default action "
  1221. "set, and its return type has no default value set.");
  1222. return DefaultValue<Result>::Get();
  1223. }
  1224. // Performs the default action with the given arguments and returns
  1225. // the action's result. The call description string will be used in
  1226. // the error message to describe the call in the case the default
  1227. // action fails. The caller is responsible for deleting the result.
  1228. // L = *
  1229. virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
  1230. const void* untyped_args, // must point to an ArgumentTuple
  1231. const string& call_description) const {
  1232. const ArgumentTuple& args =
  1233. *static_cast<const ArgumentTuple*>(untyped_args);
  1234. return ResultHolder::PerformDefaultAction(this, args, call_description);
  1235. }
  1236. // Performs the given action with the given arguments and returns
  1237. // the action's result. The caller is responsible for deleting the
  1238. // result.
  1239. // L = *
  1240. virtual UntypedActionResultHolderBase* UntypedPerformAction(
  1241. const void* untyped_action, const void* untyped_args) const {
  1242. // Make a copy of the action before performing it, in case the
  1243. // action deletes the mock object (and thus deletes itself).
  1244. const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
  1245. const ArgumentTuple& args =
  1246. *static_cast<const ArgumentTuple*>(untyped_args);
  1247. return ResultHolder::PerformAction(action, args);
  1248. }
  1249. // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
  1250. // clears the ON_CALL()s set on this mock function.
  1251. // L >= g_gmock_mutex
  1252. virtual void ClearDefaultActionsLocked() {
  1253. g_gmock_mutex.AssertHeld();
  1254. for (UntypedOnCallSpecs::const_iterator it =
  1255. untyped_on_call_specs_.begin();
  1256. it != untyped_on_call_specs_.end(); ++it) {
  1257. delete static_cast<const OnCallSpec<F>*>(*it);
  1258. }
  1259. untyped_on_call_specs_.clear();
  1260. }
  1261. protected:
  1262. template <typename Function>
  1263. friend class MockSpec;
  1264. typedef ActionResultHolder<Result> ResultHolder;
  1265. // Returns the result of invoking this mock function with the given
  1266. // arguments. This function can be safely called from multiple
  1267. // threads concurrently.
  1268. // L < g_gmock_mutex
  1269. Result InvokeWith(const ArgumentTuple& args) {
  1270. return static_cast<const ResultHolder*>(
  1271. this->UntypedInvokeWith(&args))->GetValueAndDelete();
  1272. }
  1273. // Adds and returns a default action spec for this mock function.
  1274. // L < g_gmock_mutex
  1275. OnCallSpec<F>& AddNewOnCallSpec(
  1276. const char* file, int line,
  1277. const ArgumentMatcherTuple& m) {
  1278. Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
  1279. OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
  1280. untyped_on_call_specs_.push_back(on_call_spec);
  1281. return *on_call_spec;
  1282. }
  1283. // Adds and returns an expectation spec for this mock function.
  1284. // L < g_gmock_mutex
  1285. TypedExpectation<F>& AddNewExpectation(
  1286. const char* file,
  1287. int line,
  1288. const string& source_text,
  1289. const ArgumentMatcherTuple& m) {
  1290. Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
  1291. TypedExpectation<F>* const expectation =
  1292. new TypedExpectation<F>(this, file, line, source_text, m);
  1293. const linked_ptr<ExpectationBase> untyped_expectation(expectation);
  1294. untyped_expectations_.push_back(untyped_expectation);
  1295. // Adds this expectation into the implicit sequence if there is one.
  1296. Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
  1297. if (implicit_sequence != NULL) {
  1298. implicit_sequence->AddExpectation(Expectation(untyped_expectation));
  1299. }
  1300. return *expectation;
  1301. }
  1302. // The current spec (either default action spec or expectation spec)
  1303. // being described on this function mocker.
  1304. MockSpec<F>& current_spec() { return current_spec_; }
  1305. private:
  1306. template <typename Func> friend class TypedExpectation;
  1307. // Some utilities needed for implementing UntypedInvokeWith().
  1308. // Describes what default action will be performed for the given
  1309. // arguments.
  1310. // L = *
  1311. void DescribeDefaultActionTo(const ArgumentTuple& args,
  1312. ::std::ostream* os) const {
  1313. const OnCallSpec<F>* const spec = FindOnCallSpec(args);
  1314. if (spec == NULL) {
  1315. *os << (internal::type_equals<Result, void>::value ?
  1316. "returning directly.\n" :
  1317. "returning default value.\n");
  1318. } else {
  1319. *os << "taking default action specified at:\n"
  1320. << FormatFileLocation(spec->file(), spec->line()) << "\n";
  1321. }
  1322. }
  1323. // Writes a message that the call is uninteresting (i.e. neither
  1324. // explicitly expected nor explicitly unexpected) to the given
  1325. // ostream.
  1326. // L < g_gmock_mutex
  1327. virtual void UntypedDescribeUninterestingCall(const void* untyped_args,
  1328. ::std::ostream* os) const {
  1329. const ArgumentTuple& args =
  1330. *static_cast<const ArgumentTuple*>(untyped_args);
  1331. *os << "Uninteresting mock function call - ";
  1332. DescribeDefaultActionTo(args, os);
  1333. *os << " Function call: " << Name();
  1334. UniversalPrint(args, os);
  1335. }
  1336. // Returns the expectation that matches the given function arguments
  1337. // (or NULL is there's no match); when a match is found,
  1338. // untyped_action is set to point to the action that should be
  1339. // performed (or NULL if the action is "do default"), and
  1340. // is_excessive is modified to indicate whether the call exceeds the
  1341. // expected number.
  1342. //
  1343. // Critical section: We must find the matching expectation and the
  1344. // corresponding action that needs to be taken in an ATOMIC
  1345. // transaction. Otherwise another thread may call this mock
  1346. // method in the middle and mess up the state.
  1347. //
  1348. // However, performing the action has to be left out of the critical
  1349. // section. The reason is that we have no control on what the
  1350. // action does (it can invoke an arbitrary user function or even a
  1351. // mock function) and excessive locking could cause a dead lock.
  1352. // L < g_gmock_mutex
  1353. virtual const ExpectationBase* UntypedFindMatchingExpectation(
  1354. const void* untyped_args,
  1355. const void** untyped_action, bool* is_excessive,
  1356. ::std::ostream* what, ::std::ostream* why) {
  1357. const ArgumentTuple& args =
  1358. *static_cast<const ArgumentTuple*>(untyped_args);
  1359. MutexLock l(&g_gmock_mutex);
  1360. TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
  1361. if (exp == NULL) { // A match wasn't found.
  1362. this->FormatUnexpectedCallMessageLocked(args, what, why);
  1363. return NULL;
  1364. }
  1365. // This line must be done before calling GetActionForArguments(),
  1366. // which will increment the call count for *exp and thus affect
  1367. // its saturation status.
  1368. *is_excessive = exp->IsSaturated();
  1369. const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
  1370. if (action != NULL && action->IsDoDefault())
  1371. action = NULL; // Normalize "do default" to NULL.
  1372. *untyped_action = action;
  1373. return exp;
  1374. }
  1375. // Prints the given function arguments to the ostream.
  1376. virtual void UntypedPrintArgs(const void* untyped_args,
  1377. ::std::ostream* os) const {
  1378. const ArgumentTuple& args =
  1379. *static_cast<const ArgumentTuple*>(untyped_args);
  1380. UniversalPrint(args, os);
  1381. }
  1382. // Returns the expectation that matches the arguments, or NULL if no
  1383. // expectation matches them.
  1384. // L >= g_gmock_mutex
  1385. TypedExpectation<F>* FindMatchingExpectationLocked(
  1386. const ArgumentTuple& args) const {
  1387. g_gmock_mutex.AssertHeld();
  1388. for (typename UntypedExpectations::const_reverse_iterator it =
  1389. untyped_expectations_.rbegin();
  1390. it != untyped_expectations_.rend(); ++it) {
  1391. TypedExpectation<F>* const exp =
  1392. static_cast<TypedExpectation<F>*>(it->get());
  1393. if (exp->ShouldHandleArguments(args)) {
  1394. return exp;
  1395. }
  1396. }
  1397. return NULL;
  1398. }
  1399. // Returns a message that the arguments don't match any expectation.
  1400. // L >= g_gmock_mutex
  1401. void FormatUnexpectedCallMessageLocked(const ArgumentTuple& args,
  1402. ::std::ostream* os,
  1403. ::std::ostream* why) const {
  1404. g_gmock_mutex.AssertHeld();
  1405. *os << "\nUnexpected mock function call - ";
  1406. DescribeDefaultActionTo(args, os);
  1407. PrintTriedExpectationsLocked(args, why);
  1408. }
  1409. // Prints a list of expectations that have been tried against the
  1410. // current mock function call.
  1411. // L >= g_gmock_mutex
  1412. void PrintTriedExpectationsLocked(const ArgumentTuple& args,
  1413. ::std::ostream* why) const {
  1414. g_gmock_mutex.AssertHeld();
  1415. const int count = static_cast<int>(untyped_expectations_.size());
  1416. *why << "Google Mock tried the following " << count << " "
  1417. << (count == 1 ? "expectation, but it didn't match" :
  1418. "expectations, but none matched")
  1419. << ":\n";
  1420. for (int i = 0; i < count; i++) {
  1421. TypedExpectation<F>* const expectation =
  1422. static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
  1423. *why << "\n";
  1424. expectation->DescribeLocationTo(why);
  1425. if (count > 1) {
  1426. *why << "tried expectation #" << i << ": ";
  1427. }
  1428. *why << expectation->source_text() << "...\n";
  1429. expectation->ExplainMatchResultTo(args, why);
  1430. expectation->DescribeCallCountTo(why);
  1431. }
  1432. }
  1433. // The current spec (either default action spec or expectation spec)
  1434. // being described on this function mocker.
  1435. MockSpec<F> current_spec_;
  1436. // There is no generally useful and implementable semantics of
  1437. // copying a mock object, so copying a mock is usually a user error.
  1438. // Thus we disallow copying function mockers. If the user really
  1439. // wants to copy a mock object, he should implement his own copy
  1440. // operation, for example:
  1441. //
  1442. // class MockFoo : public Foo {
  1443. // public:
  1444. // // Defines a copy constructor explicitly.
  1445. // MockFoo(const MockFoo& src) {}
  1446. // ...
  1447. // };
  1448. GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
  1449. }; // class FunctionMockerBase
  1450. #ifdef _MSC_VER
  1451. # pragma warning(pop) // Restores the warning state.
  1452. #endif // _MSV_VER
  1453. // Implements methods of FunctionMockerBase.
  1454. // Verifies that all expectations on this mock function have been
  1455. // satisfied. Reports one or more Google Test non-fatal failures and
  1456. // returns false if not.
  1457. // L >= g_gmock_mutex
  1458. // Reports an uninteresting call (whose description is in msg) in the
  1459. // manner specified by 'reaction'.
  1460. void ReportUninterestingCall(CallReaction reaction, const string& msg);
  1461. } // namespace internal
  1462. // The style guide prohibits "using" statements in a namespace scope
  1463. // inside a header file. However, the MockSpec class template is
  1464. // meant to be defined in the ::testing namespace. The following line
  1465. // is just a trick for working around a bug in MSVC 8.0, which cannot
  1466. // handle it if we define MockSpec in ::testing.
  1467. using internal::MockSpec;
  1468. // Const(x) is a convenient function for obtaining a const reference
  1469. // to x. This is useful for setting expectations on an overloaded
  1470. // const mock method, e.g.
  1471. //
  1472. // class MockFoo : public FooInterface {
  1473. // public:
  1474. // MOCK_METHOD0(Bar, int());
  1475. // MOCK_CONST_METHOD0(Bar, int&());
  1476. // };
  1477. //
  1478. // MockFoo foo;
  1479. // // Expects a call to non-const MockFoo::Bar().
  1480. // EXPECT_CALL(foo, Bar());
  1481. // // Expects a call to const MockFoo::Bar().
  1482. // EXPECT_CALL(Const(foo), Bar());
  1483. template <typename T>
  1484. inline const T& Const(const T& x) { return x; }
  1485. // Constructs an Expectation object that references and co-owns exp.
  1486. inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
  1487. : expectation_base_(exp.GetHandle().expectation_base()) {}
  1488. } // namespace testing
  1489. // A separate macro is required to avoid compile errors when the name
  1490. // of the method used in call is a result of macro expansion.
  1491. // See CompilesWithMethodNameExpandedFromMacro tests in
  1492. // internal/gmock-spec-builders_test.cc for more details.
  1493. #define GMOCK_ON_CALL_IMPL_(obj, call) \
  1494. ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \
  1495. #obj, #call)
  1496. #define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call)
  1497. #define GMOCK_EXPECT_CALL_IMPL_(obj, call) \
  1498. ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
  1499. #define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call)
  1500. #endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_