The source code and dockerfile for the GSW2024 AI Lab.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

2038 lines
75 KiB

2 months ago
  1. // Copyright 2007, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. // Google Mock - a framework for writing C++ mock classes.
  30. //
  31. // This file implements the ON_CALL() and EXPECT_CALL() macros.
  32. //
  33. // A user can use the ON_CALL() macro to specify the default action of
  34. // a mock method. The syntax is:
  35. //
  36. // ON_CALL(mock_object, Method(argument-matchers))
  37. // .With(multi-argument-matcher)
  38. // .WillByDefault(action);
  39. //
  40. // where the .With() clause is optional.
  41. //
  42. // A user can use the EXPECT_CALL() macro to specify an expectation on
  43. // a mock method. The syntax is:
  44. //
  45. // EXPECT_CALL(mock_object, Method(argument-matchers))
  46. // .With(multi-argument-matchers)
  47. // .Times(cardinality)
  48. // .InSequence(sequences)
  49. // .After(expectations)
  50. // .WillOnce(action)
  51. // .WillRepeatedly(action)
  52. // .RetiresOnSaturation();
  53. //
  54. // where all clauses are optional, and .InSequence()/.After()/
  55. // .WillOnce() can appear any number of times.
  56. // GOOGLETEST_CM0002 DO NOT DELETE
  57. #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
  58. #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
  59. #include <functional>
  60. #include <map>
  61. #include <memory>
  62. #include <set>
  63. #include <sstream>
  64. #include <string>
  65. #include <type_traits>
  66. #include <utility>
  67. #include <vector>
  68. #include "gmock/gmock-actions.h"
  69. #include "gmock/gmock-cardinalities.h"
  70. #include "gmock/gmock-matchers.h"
  71. #include "gmock/internal/gmock-internal-utils.h"
  72. #include "gmock/internal/gmock-port.h"
  73. #include "gtest/gtest.h"
  74. #if GTEST_HAS_EXCEPTIONS
  75. # include <stdexcept> // NOLINT
  76. #endif
  77. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
  78. /* class A needs to have dll-interface to be used by clients of class B */)
  79. namespace testing {
  80. // An abstract handle of an expectation.
  81. class Expectation;
  82. // A set of expectation handles.
  83. class ExpectationSet;
  84. // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
  85. // and MUST NOT BE USED IN USER CODE!!!
  86. namespace internal {
  87. // Implements a mock function.
  88. template <typename F> class FunctionMocker;
  89. // Base class for expectations.
  90. class ExpectationBase;
  91. // Implements an expectation.
  92. template <typename F> class TypedExpectation;
  93. // Helper class for testing the Expectation class template.
  94. class ExpectationTester;
  95. // Helper classes for implementing NiceMock, StrictMock, and NaggyMock.
  96. template <typename MockClass>
  97. class NiceMockImpl;
  98. template <typename MockClass>
  99. class StrictMockImpl;
  100. template <typename MockClass>
  101. class NaggyMockImpl;
  102. // Protects the mock object registry (in class Mock), all function
  103. // mockers, and all expectations.
  104. //
  105. // The reason we don't use more fine-grained protection is: when a
  106. // mock function Foo() is called, it needs to consult its expectations
  107. // to see which one should be picked. If another thread is allowed to
  108. // call a mock function (either Foo() or a different one) at the same
  109. // time, it could affect the "retired" attributes of Foo()'s
  110. // expectations when InSequence() is used, and thus affect which
  111. // expectation gets picked. Therefore, we sequence all mock function
  112. // calls to ensure the integrity of the mock objects' states.
  113. GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
  114. // Untyped base class for ActionResultHolder<R>.
  115. class UntypedActionResultHolderBase;
  116. // Abstract base class of FunctionMocker. This is the
  117. // type-agnostic part of the function mocker interface. Its pure
  118. // virtual methods are implemented by FunctionMocker.
  119. class GTEST_API_ UntypedFunctionMockerBase {
  120. public:
  121. UntypedFunctionMockerBase();
  122. virtual ~UntypedFunctionMockerBase();
  123. // Verifies that all expectations on this mock function have been
  124. // satisfied. Reports one or more Google Test non-fatal failures
  125. // and returns false if not.
  126. bool VerifyAndClearExpectationsLocked()
  127. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
  128. // Clears the ON_CALL()s set on this mock function.
  129. virtual void ClearDefaultActionsLocked()
  130. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
  131. // In all of the following Untyped* functions, it's the caller's
  132. // responsibility to guarantee the correctness of the arguments'
  133. // types.
  134. // Performs the default action with the given arguments and returns
  135. // the action's result. The call description string will be used in
  136. // the error message to describe the call in the case the default
  137. // action fails.
  138. // L = *
  139. virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
  140. void* untyped_args, const std::string& call_description) const = 0;
  141. // Performs the given action with the given arguments and returns
  142. // the action's result.
  143. // L = *
  144. virtual UntypedActionResultHolderBase* UntypedPerformAction(
  145. const void* untyped_action, void* untyped_args) const = 0;
  146. // Writes a message that the call is uninteresting (i.e. neither
  147. // explicitly expected nor explicitly unexpected) to the given
  148. // ostream.
  149. virtual void UntypedDescribeUninterestingCall(
  150. const void* untyped_args,
  151. ::std::ostream* os) const
  152. GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
  153. // Returns the expectation that matches the given function arguments
  154. // (or NULL is there's no match); when a match is found,
  155. // untyped_action is set to point to the action that should be
  156. // performed (or NULL if the action is "do default"), and
  157. // is_excessive is modified to indicate whether the call exceeds the
  158. // expected number.
  159. virtual const ExpectationBase* UntypedFindMatchingExpectation(
  160. const void* untyped_args,
  161. const void** untyped_action, bool* is_excessive,
  162. ::std::ostream* what, ::std::ostream* why)
  163. GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
  164. // Prints the given function arguments to the ostream.
  165. virtual void UntypedPrintArgs(const void* untyped_args,
  166. ::std::ostream* os) const = 0;
  167. // Sets the mock object this mock method belongs to, and registers
  168. // this information in the global mock registry. Will be called
  169. // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
  170. // method.
  171. void RegisterOwner(const void* mock_obj)
  172. GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
  173. // Sets the mock object this mock method belongs to, and sets the
  174. // name of the mock function. Will be called upon each invocation
  175. // of this mock function.
  176. void SetOwnerAndName(const void* mock_obj, const char* name)
  177. GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
  178. // Returns the mock object this mock method belongs to. Must be
  179. // called after RegisterOwner() or SetOwnerAndName() has been
  180. // called.
  181. const void* MockObject() const
  182. GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
  183. // Returns the name of this mock method. Must be called after
  184. // SetOwnerAndName() has been called.
  185. const char* Name() const
  186. GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
  187. // Returns the result of invoking this mock function with the given
  188. // arguments. This function can be safely called from multiple
  189. // threads concurrently. The caller is responsible for deleting the
  190. // result.
  191. UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args)
  192. GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
  193. protected:
  194. typedef std::vector<const void*> UntypedOnCallSpecs;
  195. using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
  196. // Returns an Expectation object that references and co-owns exp,
  197. // which must be an expectation on this mock function.
  198. Expectation GetHandleOf(ExpectationBase* exp);
  199. // Address of the mock object this mock method belongs to. Only
  200. // valid after this mock method has been called or
  201. // ON_CALL/EXPECT_CALL has been invoked on it.
  202. const void* mock_obj_; // Protected by g_gmock_mutex.
  203. // Name of the function being mocked. Only valid after this mock
  204. // method has been called.
  205. const char* name_; // Protected by g_gmock_mutex.
  206. // All default action specs for this function mocker.
  207. UntypedOnCallSpecs untyped_on_call_specs_;
  208. // All expectations for this function mocker.
  209. //
  210. // It's undefined behavior to interleave expectations (EXPECT_CALLs
  211. // or ON_CALLs) and mock function calls. Also, the order of
  212. // expectations is important. Therefore it's a logic race condition
  213. // to read/write untyped_expectations_ concurrently. In order for
  214. // tools like tsan to catch concurrent read/write accesses to
  215. // untyped_expectations, we deliberately leave accesses to it
  216. // unprotected.
  217. UntypedExpectations untyped_expectations_;
  218. }; // class UntypedFunctionMockerBase
  219. // Untyped base class for OnCallSpec<F>.
  220. class UntypedOnCallSpecBase {
  221. public:
  222. // The arguments are the location of the ON_CALL() statement.
  223. UntypedOnCallSpecBase(const char* a_file, int a_line)
  224. : file_(a_file), line_(a_line), last_clause_(kNone) {}
  225. // Where in the source file was the default action spec defined?
  226. const char* file() const { return file_; }
  227. int line() const { return line_; }
  228. protected:
  229. // Gives each clause in the ON_CALL() statement a name.
  230. enum Clause {
  231. // Do not change the order of the enum members! The run-time
  232. // syntax checking relies on it.
  233. kNone,
  234. kWith,
  235. kWillByDefault
  236. };
  237. // Asserts that the ON_CALL() statement has a certain property.
  238. void AssertSpecProperty(bool property,
  239. const std::string& failure_message) const {
  240. Assert(property, file_, line_, failure_message);
  241. }
  242. // Expects that the ON_CALL() statement has a certain property.
  243. void ExpectSpecProperty(bool property,
  244. const std::string& failure_message) const {
  245. Expect(property, file_, line_, failure_message);
  246. }
  247. const char* file_;
  248. int line_;
  249. // The last clause in the ON_CALL() statement as seen so far.
  250. // Initially kNone and changes as the statement is parsed.
  251. Clause last_clause_;
  252. }; // class UntypedOnCallSpecBase
  253. // This template class implements an ON_CALL spec.
  254. template <typename F>
  255. class OnCallSpec : public UntypedOnCallSpecBase {
  256. public:
  257. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  258. typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
  259. // Constructs an OnCallSpec object from the information inside
  260. // the parenthesis of an ON_CALL() statement.
  261. OnCallSpec(const char* a_file, int a_line,
  262. const ArgumentMatcherTuple& matchers)
  263. : UntypedOnCallSpecBase(a_file, a_line),
  264. matchers_(matchers),
  265. // By default, extra_matcher_ should match anything. However,
  266. // we cannot initialize it with _ as that causes ambiguity between
  267. // Matcher's copy and move constructor for some argument types.
  268. extra_matcher_(A<const ArgumentTuple&>()) {}
  269. // Implements the .With() clause.
  270. OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
  271. // Makes sure this is called at most once.
  272. ExpectSpecProperty(last_clause_ < kWith,
  273. ".With() cannot appear "
  274. "more than once in an ON_CALL().");
  275. last_clause_ = kWith;
  276. extra_matcher_ = m;
  277. return *this;
  278. }
  279. // Implements the .WillByDefault() clause.
  280. OnCallSpec& WillByDefault(const Action<F>& action) {
  281. ExpectSpecProperty(last_clause_ < kWillByDefault,
  282. ".WillByDefault() must appear "
  283. "exactly once in an ON_CALL().");
  284. last_clause_ = kWillByDefault;
  285. ExpectSpecProperty(!action.IsDoDefault(),
  286. "DoDefault() cannot be used in ON_CALL().");
  287. action_ = action;
  288. return *this;
  289. }
  290. // Returns true if and only if the given arguments match the matchers.
  291. bool Matches(const ArgumentTuple& args) const {
  292. return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
  293. }
  294. // Returns the action specified by the user.
  295. const Action<F>& GetAction() const {
  296. AssertSpecProperty(last_clause_ == kWillByDefault,
  297. ".WillByDefault() must appear exactly "
  298. "once in an ON_CALL().");
  299. return action_;
  300. }
  301. private:
  302. // The information in statement
  303. //
  304. // ON_CALL(mock_object, Method(matchers))
  305. // .With(multi-argument-matcher)
  306. // .WillByDefault(action);
  307. //
  308. // is recorded in the data members like this:
  309. //
  310. // source file that contains the statement => file_
  311. // line number of the statement => line_
  312. // matchers => matchers_
  313. // multi-argument-matcher => extra_matcher_
  314. // action => action_
  315. ArgumentMatcherTuple matchers_;
  316. Matcher<const ArgumentTuple&> extra_matcher_;
  317. Action<F> action_;
  318. }; // class OnCallSpec
  319. // Possible reactions on uninteresting calls.
  320. enum CallReaction {
  321. kAllow,
  322. kWarn,
  323. kFail,
  324. };
  325. } // namespace internal
  326. // Utilities for manipulating mock objects.
  327. class GTEST_API_ Mock {
  328. public:
  329. // The following public methods can be called concurrently.
  330. // Tells Google Mock to ignore mock_obj when checking for leaked
  331. // mock objects.
  332. static void AllowLeak(const void* mock_obj)
  333. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  334. // Verifies and clears all expectations on the given mock object.
  335. // If the expectations aren't satisfied, generates one or more
  336. // Google Test non-fatal failures and returns false.
  337. static bool VerifyAndClearExpectations(void* mock_obj)
  338. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  339. // Verifies all expectations on the given mock object and clears its
  340. // default actions and expectations. Returns true if and only if the
  341. // verification was successful.
  342. static bool VerifyAndClear(void* mock_obj)
  343. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  344. // Returns whether the mock was created as a naggy mock (default)
  345. static bool IsNaggy(void* mock_obj)
  346. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  347. // Returns whether the mock was created as a nice mock
  348. static bool IsNice(void* mock_obj)
  349. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  350. // Returns whether the mock was created as a strict mock
  351. static bool IsStrict(void* mock_obj)
  352. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  353. private:
  354. friend class internal::UntypedFunctionMockerBase;
  355. // Needed for a function mocker to register itself (so that we know
  356. // how to clear a mock object).
  357. template <typename F>
  358. friend class internal::FunctionMocker;
  359. template <typename MockClass>
  360. friend class internal::NiceMockImpl;
  361. template <typename MockClass>
  362. friend class internal::NaggyMockImpl;
  363. template <typename MockClass>
  364. friend class internal::StrictMockImpl;
  365. // Tells Google Mock to allow uninteresting calls on the given mock
  366. // object.
  367. static void AllowUninterestingCalls(const void* mock_obj)
  368. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  369. // Tells Google Mock to warn the user about uninteresting calls on
  370. // the given mock object.
  371. static void WarnUninterestingCalls(const void* mock_obj)
  372. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  373. // Tells Google Mock to fail uninteresting calls on the given mock
  374. // object.
  375. static void FailUninterestingCalls(const void* mock_obj)
  376. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  377. // Tells Google Mock the given mock object is being destroyed and
  378. // its entry in the call-reaction table should be removed.
  379. static void UnregisterCallReaction(const void* mock_obj)
  380. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  381. // Returns the reaction Google Mock will have on uninteresting calls
  382. // made on the given mock object.
  383. static internal::CallReaction GetReactionOnUninterestingCalls(
  384. const void* mock_obj)
  385. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  386. // Verifies that all expectations on the given mock object have been
  387. // satisfied. Reports one or more Google Test non-fatal failures
  388. // and returns false if not.
  389. static bool VerifyAndClearExpectationsLocked(void* mock_obj)
  390. GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
  391. // Clears all ON_CALL()s set on the given mock object.
  392. static void ClearDefaultActionsLocked(void* mock_obj)
  393. GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
  394. // Registers a mock object and a mock method it owns.
  395. static void Register(
  396. const void* mock_obj,
  397. internal::UntypedFunctionMockerBase* mocker)
  398. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  399. // Tells Google Mock where in the source code mock_obj is used in an
  400. // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
  401. // information helps the user identify which object it is.
  402. static void RegisterUseByOnCallOrExpectCall(
  403. const void* mock_obj, const char* file, int line)
  404. GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
  405. // Unregisters a mock method; removes the owning mock object from
  406. // the registry when the last mock method associated with it has
  407. // been unregistered. This is called only in the destructor of
  408. // FunctionMocker.
  409. static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
  410. GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
  411. }; // class Mock
  412. // An abstract handle of an expectation. Useful in the .After()
  413. // clause of EXPECT_CALL() for setting the (partial) order of
  414. // expectations. The syntax:
  415. //
  416. // Expectation e1 = EXPECT_CALL(...)...;
  417. // EXPECT_CALL(...).After(e1)...;
  418. //
  419. // sets two expectations where the latter can only be matched after
  420. // the former has been satisfied.
  421. //
  422. // Notes:
  423. // - This class is copyable and has value semantics.
  424. // - Constness is shallow: a const Expectation object itself cannot
  425. // be modified, but the mutable methods of the ExpectationBase
  426. // object it references can be called via expectation_base().
  427. class GTEST_API_ Expectation {
  428. public:
  429. // Constructs a null object that doesn't reference any expectation.
  430. Expectation();
  431. Expectation(Expectation&&) = default;
  432. Expectation(const Expectation&) = default;
  433. Expectation& operator=(Expectation&&) = default;
  434. Expectation& operator=(const Expectation&) = default;
  435. ~Expectation();
  436. // This single-argument ctor must not be explicit, in order to support the
  437. // Expectation e = EXPECT_CALL(...);
  438. // syntax.
  439. //
  440. // A TypedExpectation object stores its pre-requisites as
  441. // Expectation objects, and needs to call the non-const Retire()
  442. // method on the ExpectationBase objects they reference. Therefore
  443. // Expectation must receive a *non-const* reference to the
  444. // ExpectationBase object.
  445. Expectation(internal::ExpectationBase& exp); // NOLINT
  446. // The compiler-generated copy ctor and operator= work exactly as
  447. // intended, so we don't need to define our own.
  448. // Returns true if and only if rhs references the same expectation as this
  449. // object does.
  450. bool operator==(const Expectation& rhs) const {
  451. return expectation_base_ == rhs.expectation_base_;
  452. }
  453. bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
  454. private:
  455. friend class ExpectationSet;
  456. friend class Sequence;
  457. friend class ::testing::internal::ExpectationBase;
  458. friend class ::testing::internal::UntypedFunctionMockerBase;
  459. template <typename F>
  460. friend class ::testing::internal::FunctionMocker;
  461. template <typename F>
  462. friend class ::testing::internal::TypedExpectation;
  463. // This comparator is needed for putting Expectation objects into a set.
  464. class Less {
  465. public:
  466. bool operator()(const Expectation& lhs, const Expectation& rhs) const {
  467. return lhs.expectation_base_.get() < rhs.expectation_base_.get();
  468. }
  469. };
  470. typedef ::std::set<Expectation, Less> Set;
  471. Expectation(
  472. const std::shared_ptr<internal::ExpectationBase>& expectation_base);
  473. // Returns the expectation this object references.
  474. const std::shared_ptr<internal::ExpectationBase>& expectation_base() const {
  475. return expectation_base_;
  476. }
  477. // A shared_ptr that co-owns the expectation this handle references.
  478. std::shared_ptr<internal::ExpectationBase> expectation_base_;
  479. };
  480. // A set of expectation handles. Useful in the .After() clause of
  481. // EXPECT_CALL() for setting the (partial) order of expectations. The
  482. // syntax:
  483. //
  484. // ExpectationSet es;
  485. // es += EXPECT_CALL(...)...;
  486. // es += EXPECT_CALL(...)...;
  487. // EXPECT_CALL(...).After(es)...;
  488. //
  489. // sets three expectations where the last one can only be matched
  490. // after the first two have both been satisfied.
  491. //
  492. // This class is copyable and has value semantics.
  493. class ExpectationSet {
  494. public:
  495. // A bidirectional iterator that can read a const element in the set.
  496. typedef Expectation::Set::const_iterator const_iterator;
  497. // An object stored in the set. This is an alias of Expectation.
  498. typedef Expectation::Set::value_type value_type;
  499. // Constructs an empty set.
  500. ExpectationSet() {}
  501. // This single-argument ctor must not be explicit, in order to support the
  502. // ExpectationSet es = EXPECT_CALL(...);
  503. // syntax.
  504. ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
  505. *this += Expectation(exp);
  506. }
  507. // This single-argument ctor implements implicit conversion from
  508. // Expectation and thus must not be explicit. This allows either an
  509. // Expectation or an ExpectationSet to be used in .After().
  510. ExpectationSet(const Expectation& e) { // NOLINT
  511. *this += e;
  512. }
  513. // The compiler-generator ctor and operator= works exactly as
  514. // intended, so we don't need to define our own.
  515. // Returns true if and only if rhs contains the same set of Expectation
  516. // objects as this does.
  517. bool operator==(const ExpectationSet& rhs) const {
  518. return expectations_ == rhs.expectations_;
  519. }
  520. bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
  521. // Implements the syntax
  522. // expectation_set += EXPECT_CALL(...);
  523. ExpectationSet& operator+=(const Expectation& e) {
  524. expectations_.insert(e);
  525. return *this;
  526. }
  527. int size() const { return static_cast<int>(expectations_.size()); }
  528. const_iterator begin() const { return expectations_.begin(); }
  529. const_iterator end() const { return expectations_.end(); }
  530. private:
  531. Expectation::Set expectations_;
  532. };
  533. // Sequence objects are used by a user to specify the relative order
  534. // in which the expectations should match. They are copyable (we rely
  535. // on the compiler-defined copy constructor and assignment operator).
  536. class GTEST_API_ Sequence {
  537. public:
  538. // Constructs an empty sequence.
  539. Sequence() : last_expectation_(new Expectation) {}
  540. // Adds an expectation to this sequence. The caller must ensure
  541. // that no other thread is accessing this Sequence object.
  542. void AddExpectation(const Expectation& expectation) const;
  543. private:
  544. // The last expectation in this sequence.
  545. std::shared_ptr<Expectation> last_expectation_;
  546. }; // class Sequence
  547. // An object of this type causes all EXPECT_CALL() statements
  548. // encountered in its scope to be put in an anonymous sequence. The
  549. // work is done in the constructor and destructor. You should only
  550. // create an InSequence object on the stack.
  551. //
  552. // The sole purpose for this class is to support easy definition of
  553. // sequential expectations, e.g.
  554. //
  555. // {
  556. // InSequence dummy; // The name of the object doesn't matter.
  557. //
  558. // // The following expectations must match in the order they appear.
  559. // EXPECT_CALL(a, Bar())...;
  560. // EXPECT_CALL(a, Baz())...;
  561. // ...
  562. // EXPECT_CALL(b, Xyz())...;
  563. // }
  564. //
  565. // You can create InSequence objects in multiple threads, as long as
  566. // they are used to affect different mock objects. The idea is that
  567. // each thread can create and set up its own mocks as if it's the only
  568. // thread. However, for clarity of your tests we recommend you to set
  569. // up mocks in the main thread unless you have a good reason not to do
  570. // so.
  571. class GTEST_API_ InSequence {
  572. public:
  573. InSequence();
  574. ~InSequence();
  575. private:
  576. bool sequence_created_;
  577. GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
  578. } GTEST_ATTRIBUTE_UNUSED_;
  579. namespace internal {
  580. // Points to the implicit sequence introduced by a living InSequence
  581. // object (if any) in the current thread or NULL.
  582. GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
  583. // Base class for implementing expectations.
  584. //
  585. // There are two reasons for having a type-agnostic base class for
  586. // Expectation:
  587. //
  588. // 1. We need to store collections of expectations of different
  589. // types (e.g. all pre-requisites of a particular expectation, all
  590. // expectations in a sequence). Therefore these expectation objects
  591. // must share a common base class.
  592. //
  593. // 2. We can avoid binary code bloat by moving methods not depending
  594. // on the template argument of Expectation to the base class.
  595. //
  596. // This class is internal and mustn't be used by user code directly.
  597. class GTEST_API_ ExpectationBase {
  598. public:
  599. // source_text is the EXPECT_CALL(...) source that created this Expectation.
  600. ExpectationBase(const char* file, int line, const std::string& source_text);
  601. virtual ~ExpectationBase();
  602. // Where in the source file was the expectation spec defined?
  603. const char* file() const { return file_; }
  604. int line() const { return line_; }
  605. const char* source_text() const { return source_text_.c_str(); }
  606. // Returns the cardinality specified in the expectation spec.
  607. const Cardinality& cardinality() const { return cardinality_; }
  608. // Describes the source file location of this expectation.
  609. void DescribeLocationTo(::std::ostream* os) const {
  610. *os << FormatFileLocation(file(), line()) << " ";
  611. }
  612. // Describes how many times a function call matching this
  613. // expectation has occurred.
  614. void DescribeCallCountTo(::std::ostream* os) const
  615. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
  616. // If this mock method has an extra matcher (i.e. .With(matcher)),
  617. // describes it to the ostream.
  618. virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
  619. protected:
  620. friend class ::testing::Expectation;
  621. friend class UntypedFunctionMockerBase;
  622. enum Clause {
  623. // Don't change the order of the enum members!
  624. kNone,
  625. kWith,
  626. kTimes,
  627. kInSequence,
  628. kAfter,
  629. kWillOnce,
  630. kWillRepeatedly,
  631. kRetiresOnSaturation
  632. };
  633. typedef std::vector<const void*> UntypedActions;
  634. // Returns an Expectation object that references and co-owns this
  635. // expectation.
  636. virtual Expectation GetHandle() = 0;
  637. // Asserts that the EXPECT_CALL() statement has the given property.
  638. void AssertSpecProperty(bool property,
  639. const std::string& failure_message) const {
  640. Assert(property, file_, line_, failure_message);
  641. }
  642. // Expects that the EXPECT_CALL() statement has the given property.
  643. void ExpectSpecProperty(bool property,
  644. const std::string& failure_message) const {
  645. Expect(property, file_, line_, failure_message);
  646. }
  647. // Explicitly specifies the cardinality of this expectation. Used
  648. // by the subclasses to implement the .Times() clause.
  649. void SpecifyCardinality(const Cardinality& cardinality);
  650. // Returns true if and only if the user specified the cardinality
  651. // explicitly using a .Times().
  652. bool cardinality_specified() const { return cardinality_specified_; }
  653. // Sets the cardinality of this expectation spec.
  654. void set_cardinality(const Cardinality& a_cardinality) {
  655. cardinality_ = a_cardinality;
  656. }
  657. // The following group of methods should only be called after the
  658. // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
  659. // the current thread.
  660. // Retires all pre-requisites of this expectation.
  661. void RetireAllPreRequisites()
  662. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
  663. // Returns true if and only if this expectation is retired.
  664. bool is_retired() const
  665. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  666. g_gmock_mutex.AssertHeld();
  667. return retired_;
  668. }
  669. // Retires this expectation.
  670. void Retire()
  671. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  672. g_gmock_mutex.AssertHeld();
  673. retired_ = true;
  674. }
  675. // Returns true if and only if this expectation is satisfied.
  676. bool IsSatisfied() const
  677. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  678. g_gmock_mutex.AssertHeld();
  679. return cardinality().IsSatisfiedByCallCount(call_count_);
  680. }
  681. // Returns true if and only if this expectation is saturated.
  682. bool IsSaturated() const
  683. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  684. g_gmock_mutex.AssertHeld();
  685. return cardinality().IsSaturatedByCallCount(call_count_);
  686. }
  687. // Returns true if and only if this expectation is over-saturated.
  688. bool IsOverSaturated() const
  689. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  690. g_gmock_mutex.AssertHeld();
  691. return cardinality().IsOverSaturatedByCallCount(call_count_);
  692. }
  693. // Returns true if and only if all pre-requisites of this expectation are
  694. // satisfied.
  695. bool AllPrerequisitesAreSatisfied() const
  696. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
  697. // Adds unsatisfied pre-requisites of this expectation to 'result'.
  698. void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
  699. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
  700. // Returns the number this expectation has been invoked.
  701. int call_count() const
  702. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  703. g_gmock_mutex.AssertHeld();
  704. return call_count_;
  705. }
  706. // Increments the number this expectation has been invoked.
  707. void IncrementCallCount()
  708. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  709. g_gmock_mutex.AssertHeld();
  710. call_count_++;
  711. }
  712. // Checks the action count (i.e. the number of WillOnce() and
  713. // WillRepeatedly() clauses) against the cardinality if this hasn't
  714. // been done before. Prints a warning if there are too many or too
  715. // few actions.
  716. void CheckActionCountIfNotDone() const
  717. GTEST_LOCK_EXCLUDED_(mutex_);
  718. friend class ::testing::Sequence;
  719. friend class ::testing::internal::ExpectationTester;
  720. template <typename Function>
  721. friend class TypedExpectation;
  722. // Implements the .Times() clause.
  723. void UntypedTimes(const Cardinality& a_cardinality);
  724. // This group of fields are part of the spec and won't change after
  725. // an EXPECT_CALL() statement finishes.
  726. const char* file_; // The file that contains the expectation.
  727. int line_; // The line number of the expectation.
  728. const std::string source_text_; // The EXPECT_CALL(...) source text.
  729. // True if and only if the cardinality is specified explicitly.
  730. bool cardinality_specified_;
  731. Cardinality cardinality_; // The cardinality of the expectation.
  732. // The immediate pre-requisites (i.e. expectations that must be
  733. // satisfied before this expectation can be matched) of this
  734. // expectation. We use std::shared_ptr in the set because we want an
  735. // Expectation object to be co-owned by its FunctionMocker and its
  736. // successors. This allows multiple mock objects to be deleted at
  737. // different times.
  738. ExpectationSet immediate_prerequisites_;
  739. // This group of fields are the current state of the expectation,
  740. // and can change as the mock function is called.
  741. int call_count_; // How many times this expectation has been invoked.
  742. bool retired_; // True if and only if this expectation has retired.
  743. UntypedActions untyped_actions_;
  744. bool extra_matcher_specified_;
  745. bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
  746. bool retires_on_saturation_;
  747. Clause last_clause_;
  748. mutable bool action_count_checked_; // Under mutex_.
  749. mutable Mutex mutex_; // Protects action_count_checked_.
  750. }; // class ExpectationBase
  751. // Impements an expectation for the given function type.
  752. template <typename F>
  753. class TypedExpectation : public ExpectationBase {
  754. public:
  755. typedef typename Function<F>::ArgumentTuple ArgumentTuple;
  756. typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
  757. typedef typename Function<F>::Result Result;
  758. TypedExpectation(FunctionMocker<F>* owner, const char* a_file, int a_line,
  759. const std::string& a_source_text,
  760. const ArgumentMatcherTuple& m)
  761. : ExpectationBase(a_file, a_line, a_source_text),
  762. owner_(owner),
  763. matchers_(m),
  764. // By default, extra_matcher_ should match anything. However,
  765. // we cannot initialize it with _ as that causes ambiguity between
  766. // Matcher's copy and move constructor for some argument types.
  767. extra_matcher_(A<const ArgumentTuple&>()),
  768. repeated_action_(DoDefault()) {}
  769. ~TypedExpectation() override {
  770. // Check the validity of the action count if it hasn't been done
  771. // yet (for example, if the expectation was never used).
  772. CheckActionCountIfNotDone();
  773. for (UntypedActions::const_iterator it = untyped_actions_.begin();
  774. it != untyped_actions_.end(); ++it) {
  775. delete static_cast<const Action<F>*>(*it);
  776. }
  777. }
  778. // Implements the .With() clause.
  779. TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
  780. if (last_clause_ == kWith) {
  781. ExpectSpecProperty(false,
  782. ".With() cannot appear "
  783. "more than once in an EXPECT_CALL().");
  784. } else {
  785. ExpectSpecProperty(last_clause_ < kWith,
  786. ".With() must be the first "
  787. "clause in an EXPECT_CALL().");
  788. }
  789. last_clause_ = kWith;
  790. extra_matcher_ = m;
  791. extra_matcher_specified_ = true;
  792. return *this;
  793. }
  794. // Implements the .Times() clause.
  795. TypedExpectation& Times(const Cardinality& a_cardinality) {
  796. ExpectationBase::UntypedTimes(a_cardinality);
  797. return *this;
  798. }
  799. // Implements the .Times() clause.
  800. TypedExpectation& Times(int n) {
  801. return Times(Exactly(n));
  802. }
  803. // Implements the .InSequence() clause.
  804. TypedExpectation& InSequence(const Sequence& s) {
  805. ExpectSpecProperty(last_clause_ <= kInSequence,
  806. ".InSequence() cannot appear after .After(),"
  807. " .WillOnce(), .WillRepeatedly(), or "
  808. ".RetiresOnSaturation().");
  809. last_clause_ = kInSequence;
  810. s.AddExpectation(GetHandle());
  811. return *this;
  812. }
  813. TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
  814. return InSequence(s1).InSequence(s2);
  815. }
  816. TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
  817. const Sequence& s3) {
  818. return InSequence(s1, s2).InSequence(s3);
  819. }
  820. TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
  821. const Sequence& s3, const Sequence& s4) {
  822. return InSequence(s1, s2, s3).InSequence(s4);
  823. }
  824. TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
  825. const Sequence& s3, const Sequence& s4,
  826. const Sequence& s5) {
  827. return InSequence(s1, s2, s3, s4).InSequence(s5);
  828. }
  829. // Implements that .After() clause.
  830. TypedExpectation& After(const ExpectationSet& s) {
  831. ExpectSpecProperty(last_clause_ <= kAfter,
  832. ".After() cannot appear after .WillOnce(),"
  833. " .WillRepeatedly(), or "
  834. ".RetiresOnSaturation().");
  835. last_clause_ = kAfter;
  836. for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
  837. immediate_prerequisites_ += *it;
  838. }
  839. return *this;
  840. }
  841. TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
  842. return After(s1).After(s2);
  843. }
  844. TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
  845. const ExpectationSet& s3) {
  846. return After(s1, s2).After(s3);
  847. }
  848. TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
  849. const ExpectationSet& s3, const ExpectationSet& s4) {
  850. return After(s1, s2, s3).After(s4);
  851. }
  852. TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
  853. const ExpectationSet& s3, const ExpectationSet& s4,
  854. const ExpectationSet& s5) {
  855. return After(s1, s2, s3, s4).After(s5);
  856. }
  857. // Implements the .WillOnce() clause.
  858. TypedExpectation& WillOnce(const Action<F>& action) {
  859. ExpectSpecProperty(last_clause_ <= kWillOnce,
  860. ".WillOnce() cannot appear after "
  861. ".WillRepeatedly() or .RetiresOnSaturation().");
  862. last_clause_ = kWillOnce;
  863. untyped_actions_.push_back(new Action<F>(action));
  864. if (!cardinality_specified()) {
  865. set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
  866. }
  867. return *this;
  868. }
  869. // Implements the .WillRepeatedly() clause.
  870. TypedExpectation& WillRepeatedly(const Action<F>& action) {
  871. if (last_clause_ == kWillRepeatedly) {
  872. ExpectSpecProperty(false,
  873. ".WillRepeatedly() cannot appear "
  874. "more than once in an EXPECT_CALL().");
  875. } else {
  876. ExpectSpecProperty(last_clause_ < kWillRepeatedly,
  877. ".WillRepeatedly() cannot appear "
  878. "after .RetiresOnSaturation().");
  879. }
  880. last_clause_ = kWillRepeatedly;
  881. repeated_action_specified_ = true;
  882. repeated_action_ = action;
  883. if (!cardinality_specified()) {
  884. set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
  885. }
  886. // Now that no more action clauses can be specified, we check
  887. // whether their count makes sense.
  888. CheckActionCountIfNotDone();
  889. return *this;
  890. }
  891. // Implements the .RetiresOnSaturation() clause.
  892. TypedExpectation& RetiresOnSaturation() {
  893. ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
  894. ".RetiresOnSaturation() cannot appear "
  895. "more than once.");
  896. last_clause_ = kRetiresOnSaturation;
  897. retires_on_saturation_ = true;
  898. // Now that no more action clauses can be specified, we check
  899. // whether their count makes sense.
  900. CheckActionCountIfNotDone();
  901. return *this;
  902. }
  903. // Returns the matchers for the arguments as specified inside the
  904. // EXPECT_CALL() macro.
  905. const ArgumentMatcherTuple& matchers() const {
  906. return matchers_;
  907. }
  908. // Returns the matcher specified by the .With() clause.
  909. const Matcher<const ArgumentTuple&>& extra_matcher() const {
  910. return extra_matcher_;
  911. }
  912. // Returns the action specified by the .WillRepeatedly() clause.
  913. const Action<F>& repeated_action() const { return repeated_action_; }
  914. // If this mock method has an extra matcher (i.e. .With(matcher)),
  915. // describes it to the ostream.
  916. void MaybeDescribeExtraMatcherTo(::std::ostream* os) override {
  917. if (extra_matcher_specified_) {
  918. *os << " Expected args: ";
  919. extra_matcher_.DescribeTo(os);
  920. *os << "\n";
  921. }
  922. }
  923. private:
  924. template <typename Function>
  925. friend class FunctionMocker;
  926. // Returns an Expectation object that references and co-owns this
  927. // expectation.
  928. Expectation GetHandle() override { return owner_->GetHandleOf(this); }
  929. // The following methods will be called only after the EXPECT_CALL()
  930. // statement finishes and when the current thread holds
  931. // g_gmock_mutex.
  932. // Returns true if and only if this expectation matches the given arguments.
  933. bool Matches(const ArgumentTuple& args) const
  934. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  935. g_gmock_mutex.AssertHeld();
  936. return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
  937. }
  938. // Returns true if and only if this expectation should handle the given
  939. // arguments.
  940. bool ShouldHandleArguments(const ArgumentTuple& args) const
  941. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  942. g_gmock_mutex.AssertHeld();
  943. // In case the action count wasn't checked when the expectation
  944. // was defined (e.g. if this expectation has no WillRepeatedly()
  945. // or RetiresOnSaturation() clause), we check it when the
  946. // expectation is used for the first time.
  947. CheckActionCountIfNotDone();
  948. return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
  949. }
  950. // Describes the result of matching the arguments against this
  951. // expectation to the given ostream.
  952. void ExplainMatchResultTo(
  953. const ArgumentTuple& args,
  954. ::std::ostream* os) const
  955. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  956. g_gmock_mutex.AssertHeld();
  957. if (is_retired()) {
  958. *os << " Expected: the expectation is active\n"
  959. << " Actual: it is retired\n";
  960. } else if (!Matches(args)) {
  961. if (!TupleMatches(matchers_, args)) {
  962. ExplainMatchFailureTupleTo(matchers_, args, os);
  963. }
  964. StringMatchResultListener listener;
  965. if (!extra_matcher_.MatchAndExplain(args, &listener)) {
  966. *os << " Expected args: ";
  967. extra_matcher_.DescribeTo(os);
  968. *os << "\n Actual: don't match";
  969. internal::PrintIfNotEmpty(listener.str(), os);
  970. *os << "\n";
  971. }
  972. } else if (!AllPrerequisitesAreSatisfied()) {
  973. *os << " Expected: all pre-requisites are satisfied\n"
  974. << " Actual: the following immediate pre-requisites "
  975. << "are not satisfied:\n";
  976. ExpectationSet unsatisfied_prereqs;
  977. FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
  978. int i = 0;
  979. for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
  980. it != unsatisfied_prereqs.end(); ++it) {
  981. it->expectation_base()->DescribeLocationTo(os);
  982. *os << "pre-requisite #" << i++ << "\n";
  983. }
  984. *os << " (end of pre-requisites)\n";
  985. } else {
  986. // This line is here just for completeness' sake. It will never
  987. // be executed as currently the ExplainMatchResultTo() function
  988. // is called only when the mock function call does NOT match the
  989. // expectation.
  990. *os << "The call matches the expectation.\n";
  991. }
  992. }
  993. // Returns the action that should be taken for the current invocation.
  994. const Action<F>& GetCurrentAction(const FunctionMocker<F>* mocker,
  995. const ArgumentTuple& args) const
  996. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  997. g_gmock_mutex.AssertHeld();
  998. const int count = call_count();
  999. Assert(count >= 1, __FILE__, __LINE__,
  1000. "call_count() is <= 0 when GetCurrentAction() is "
  1001. "called - this should never happen.");
  1002. const int action_count = static_cast<int>(untyped_actions_.size());
  1003. if (action_count > 0 && !repeated_action_specified_ &&
  1004. count > action_count) {
  1005. // If there is at least one WillOnce() and no WillRepeatedly(),
  1006. // we warn the user when the WillOnce() clauses ran out.
  1007. ::std::stringstream ss;
  1008. DescribeLocationTo(&ss);
  1009. ss << "Actions ran out in " << source_text() << "...\n"
  1010. << "Called " << count << " times, but only "
  1011. << action_count << " WillOnce()"
  1012. << (action_count == 1 ? " is" : "s are") << " specified - ";
  1013. mocker->DescribeDefaultActionTo(args, &ss);
  1014. Log(kWarning, ss.str(), 1);
  1015. }
  1016. return count <= action_count
  1017. ? *static_cast<const Action<F>*>(
  1018. untyped_actions_[static_cast<size_t>(count - 1)])
  1019. : repeated_action();
  1020. }
  1021. // Given the arguments of a mock function call, if the call will
  1022. // over-saturate this expectation, returns the default action;
  1023. // otherwise, returns the next action in this expectation. Also
  1024. // describes *what* happened to 'what', and explains *why* Google
  1025. // Mock does it to 'why'. This method is not const as it calls
  1026. // IncrementCallCount(). A return value of NULL means the default
  1027. // action.
  1028. const Action<F>* GetActionForArguments(const FunctionMocker<F>* mocker,
  1029. const ArgumentTuple& args,
  1030. ::std::ostream* what,
  1031. ::std::ostream* why)
  1032. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  1033. g_gmock_mutex.AssertHeld();
  1034. if (IsSaturated()) {
  1035. // We have an excessive call.
  1036. IncrementCallCount();
  1037. *what << "Mock function called more times than expected - ";
  1038. mocker->DescribeDefaultActionTo(args, what);
  1039. DescribeCallCountTo(why);
  1040. return nullptr;
  1041. }
  1042. IncrementCallCount();
  1043. RetireAllPreRequisites();
  1044. if (retires_on_saturation_ && IsSaturated()) {
  1045. Retire();
  1046. }
  1047. // Must be done after IncrementCount()!
  1048. *what << "Mock function call matches " << source_text() <<"...\n";
  1049. return &(GetCurrentAction(mocker, args));
  1050. }
  1051. // All the fields below won't change once the EXPECT_CALL()
  1052. // statement finishes.
  1053. FunctionMocker<F>* const owner_;
  1054. ArgumentMatcherTuple matchers_;
  1055. Matcher<const ArgumentTuple&> extra_matcher_;
  1056. Action<F> repeated_action_;
  1057. GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
  1058. }; // class TypedExpectation
  1059. // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
  1060. // specifying the default behavior of, or expectation on, a mock
  1061. // function.
  1062. // Note: class MockSpec really belongs to the ::testing namespace.
  1063. // However if we define it in ::testing, MSVC will complain when
  1064. // classes in ::testing::internal declare it as a friend class
  1065. // template. To workaround this compiler bug, we define MockSpec in
  1066. // ::testing::internal and import it into ::testing.
  1067. // Logs a message including file and line number information.
  1068. GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
  1069. const char* file, int line,
  1070. const std::string& message);
  1071. template <typename F>
  1072. class MockSpec {
  1073. public:
  1074. typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
  1075. typedef typename internal::Function<F>::ArgumentMatcherTuple
  1076. ArgumentMatcherTuple;
  1077. // Constructs a MockSpec object, given the function mocker object
  1078. // that the spec is associated with.
  1079. MockSpec(internal::FunctionMocker<F>* function_mocker,
  1080. const ArgumentMatcherTuple& matchers)
  1081. : function_mocker_(function_mocker), matchers_(matchers) {}
  1082. // Adds a new default action spec to the function mocker and returns
  1083. // the newly created spec.
  1084. internal::OnCallSpec<F>& InternalDefaultActionSetAt(
  1085. const char* file, int line, const char* obj, const char* call) {
  1086. LogWithLocation(internal::kInfo, file, line,
  1087. std::string("ON_CALL(") + obj + ", " + call + ") invoked");
  1088. return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
  1089. }
  1090. // Adds a new expectation spec to the function mocker and returns
  1091. // the newly created spec.
  1092. internal::TypedExpectation<F>& InternalExpectedAt(
  1093. const char* file, int line, const char* obj, const char* call) {
  1094. const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
  1095. call + ")");
  1096. LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
  1097. return function_mocker_->AddNewExpectation(
  1098. file, line, source_text, matchers_);
  1099. }
  1100. // This operator overload is used to swallow the superfluous parameter list
  1101. // introduced by the ON/EXPECT_CALL macros. See the macro comments for more
  1102. // explanation.
  1103. MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {
  1104. return *this;
  1105. }
  1106. private:
  1107. template <typename Function>
  1108. friend class internal::FunctionMocker;
  1109. // The function mocker that owns this spec.
  1110. internal::FunctionMocker<F>* const function_mocker_;
  1111. // The argument matchers specified in the spec.
  1112. ArgumentMatcherTuple matchers_;
  1113. }; // class MockSpec
  1114. // Wrapper type for generically holding an ordinary value or lvalue reference.
  1115. // If T is not a reference type, it must be copyable or movable.
  1116. // ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
  1117. // T is a move-only value type (which means that it will always be copyable
  1118. // if the current platform does not support move semantics).
  1119. //
  1120. // The primary template defines handling for values, but function header
  1121. // comments describe the contract for the whole template (including
  1122. // specializations).
  1123. template <typename T>
  1124. class ReferenceOrValueWrapper {
  1125. public:
  1126. // Constructs a wrapper from the given value/reference.
  1127. explicit ReferenceOrValueWrapper(T value)
  1128. : value_(std::move(value)) {
  1129. }
  1130. // Unwraps and returns the underlying value/reference, exactly as
  1131. // originally passed. The behavior of calling this more than once on
  1132. // the same object is unspecified.
  1133. T Unwrap() { return std::move(value_); }
  1134. // Provides nondestructive access to the underlying value/reference.
  1135. // Always returns a const reference (more precisely,
  1136. // const std::add_lvalue_reference<T>::type). The behavior of calling this
  1137. // after calling Unwrap on the same object is unspecified.
  1138. const T& Peek() const {
  1139. return value_;
  1140. }
  1141. private:
  1142. T value_;
  1143. };
  1144. // Specialization for lvalue reference types. See primary template
  1145. // for documentation.
  1146. template <typename T>
  1147. class ReferenceOrValueWrapper<T&> {
  1148. public:
  1149. // Workaround for debatable pass-by-reference lint warning (c-library-team
  1150. // policy precludes NOLINT in this context)
  1151. typedef T& reference;
  1152. explicit ReferenceOrValueWrapper(reference ref)
  1153. : value_ptr_(&ref) {}
  1154. T& Unwrap() { return *value_ptr_; }
  1155. const T& Peek() const { return *value_ptr_; }
  1156. private:
  1157. T* value_ptr_;
  1158. };
  1159. // C++ treats the void type specially. For example, you cannot define
  1160. // a void-typed variable or pass a void value to a function.
  1161. // ActionResultHolder<T> holds a value of type T, where T must be a
  1162. // copyable type or void (T doesn't need to be default-constructable).
  1163. // It hides the syntactic difference between void and other types, and
  1164. // is used to unify the code for invoking both void-returning and
  1165. // non-void-returning mock functions.
  1166. // Untyped base class for ActionResultHolder<T>.
  1167. class UntypedActionResultHolderBase {
  1168. public:
  1169. virtual ~UntypedActionResultHolderBase() {}
  1170. // Prints the held value as an action's result to os.
  1171. virtual void PrintAsActionResult(::std::ostream* os) const = 0;
  1172. };
  1173. // This generic definition is used when T is not void.
  1174. template <typename T>
  1175. class ActionResultHolder : public UntypedActionResultHolderBase {
  1176. public:
  1177. // Returns the held value. Must not be called more than once.
  1178. T Unwrap() {
  1179. return result_.Unwrap();
  1180. }
  1181. // Prints the held value as an action's result to os.
  1182. void PrintAsActionResult(::std::ostream* os) const override {
  1183. *os << "\n Returns: ";
  1184. // T may be a reference type, so we don't use UniversalPrint().
  1185. UniversalPrinter<T>::Print(result_.Peek(), os);
  1186. }
  1187. // Performs the given mock function's default action and returns the
  1188. // result in a new-ed ActionResultHolder.
  1189. template <typename F>
  1190. static ActionResultHolder* PerformDefaultAction(
  1191. const FunctionMocker<F>* func_mocker,
  1192. typename Function<F>::ArgumentTuple&& args,
  1193. const std::string& call_description) {
  1194. return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(
  1195. std::move(args), call_description)));
  1196. }
  1197. // Performs the given action and returns the result in a new-ed
  1198. // ActionResultHolder.
  1199. template <typename F>
  1200. static ActionResultHolder* PerformAction(
  1201. const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
  1202. return new ActionResultHolder(
  1203. Wrapper(action.Perform(std::move(args))));
  1204. }
  1205. private:
  1206. typedef ReferenceOrValueWrapper<T> Wrapper;
  1207. explicit ActionResultHolder(Wrapper result)
  1208. : result_(std::move(result)) {
  1209. }
  1210. Wrapper result_;
  1211. GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
  1212. };
  1213. // Specialization for T = void.
  1214. template <>
  1215. class ActionResultHolder<void> : public UntypedActionResultHolderBase {
  1216. public:
  1217. void Unwrap() { }
  1218. void PrintAsActionResult(::std::ostream* /* os */) const override {}
  1219. // Performs the given mock function's default action and returns ownership
  1220. // of an empty ActionResultHolder*.
  1221. template <typename F>
  1222. static ActionResultHolder* PerformDefaultAction(
  1223. const FunctionMocker<F>* func_mocker,
  1224. typename Function<F>::ArgumentTuple&& args,
  1225. const std::string& call_description) {
  1226. func_mocker->PerformDefaultAction(std::move(args), call_description);
  1227. return new ActionResultHolder;
  1228. }
  1229. // Performs the given action and returns ownership of an empty
  1230. // ActionResultHolder*.
  1231. template <typename F>
  1232. static ActionResultHolder* PerformAction(
  1233. const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
  1234. action.Perform(std::move(args));
  1235. return new ActionResultHolder;
  1236. }
  1237. private:
  1238. ActionResultHolder() {}
  1239. GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
  1240. };
  1241. template <typename F>
  1242. class FunctionMocker;
  1243. template <typename R, typename... Args>
  1244. class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
  1245. using F = R(Args...);
  1246. public:
  1247. using Result = R;
  1248. using ArgumentTuple = std::tuple<Args...>;
  1249. using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
  1250. FunctionMocker() {}
  1251. // There is no generally useful and implementable semantics of
  1252. // copying a mock object, so copying a mock is usually a user error.
  1253. // Thus we disallow copying function mockers. If the user really
  1254. // wants to copy a mock object, they should implement their own copy
  1255. // operation, for example:
  1256. //
  1257. // class MockFoo : public Foo {
  1258. // public:
  1259. // // Defines a copy constructor explicitly.
  1260. // MockFoo(const MockFoo& src) {}
  1261. // ...
  1262. // };
  1263. FunctionMocker(const FunctionMocker&) = delete;
  1264. FunctionMocker& operator=(const FunctionMocker&) = delete;
  1265. // The destructor verifies that all expectations on this mock
  1266. // function have been satisfied. If not, it will report Google Test
  1267. // non-fatal failures for the violations.
  1268. ~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  1269. MutexLock l(&g_gmock_mutex);
  1270. VerifyAndClearExpectationsLocked();
  1271. Mock::UnregisterLocked(this);
  1272. ClearDefaultActionsLocked();
  1273. }
  1274. // Returns the ON_CALL spec that matches this mock function with the
  1275. // given arguments; returns NULL if no matching ON_CALL is found.
  1276. // L = *
  1277. const OnCallSpec<F>* FindOnCallSpec(
  1278. const ArgumentTuple& args) const {
  1279. for (UntypedOnCallSpecs::const_reverse_iterator it
  1280. = untyped_on_call_specs_.rbegin();
  1281. it != untyped_on_call_specs_.rend(); ++it) {
  1282. const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
  1283. if (spec->Matches(args))
  1284. return spec;
  1285. }
  1286. return nullptr;
  1287. }
  1288. // Performs the default action of this mock function on the given
  1289. // arguments and returns the result. Asserts (or throws if
  1290. // exceptions are enabled) with a helpful call descrption if there
  1291. // is no valid return value. This method doesn't depend on the
  1292. // mutable state of this object, and thus can be called concurrently
  1293. // without locking.
  1294. // L = *
  1295. Result PerformDefaultAction(ArgumentTuple&& args,
  1296. const std::string& call_description) const {
  1297. const OnCallSpec<F>* const spec =
  1298. this->FindOnCallSpec(args);
  1299. if (spec != nullptr) {
  1300. return spec->GetAction().Perform(std::move(args));
  1301. }
  1302. const std::string message =
  1303. call_description +
  1304. "\n The mock function has no default action "
  1305. "set, and its return type has no default value set.";
  1306. #if GTEST_HAS_EXCEPTIONS
  1307. if (!DefaultValue<Result>::Exists()) {
  1308. throw std::runtime_error(message);
  1309. }
  1310. #else
  1311. Assert(DefaultValue<Result>::Exists(), "", -1, message);
  1312. #endif
  1313. return DefaultValue<Result>::Get();
  1314. }
  1315. // Performs the default action with the given arguments and returns
  1316. // the action's result. The call description string will be used in
  1317. // the error message to describe the call in the case the default
  1318. // action fails. The caller is responsible for deleting the result.
  1319. // L = *
  1320. UntypedActionResultHolderBase* UntypedPerformDefaultAction(
  1321. void* untyped_args, // must point to an ArgumentTuple
  1322. const std::string& call_description) const override {
  1323. ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
  1324. return ResultHolder::PerformDefaultAction(this, std::move(*args),
  1325. call_description);
  1326. }
  1327. // Performs the given action with the given arguments and returns
  1328. // the action's result. The caller is responsible for deleting the
  1329. // result.
  1330. // L = *
  1331. UntypedActionResultHolderBase* UntypedPerformAction(
  1332. const void* untyped_action, void* untyped_args) const override {
  1333. // Make a copy of the action before performing it, in case the
  1334. // action deletes the mock object (and thus deletes itself).
  1335. const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
  1336. ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
  1337. return ResultHolder::PerformAction(action, std::move(*args));
  1338. }
  1339. // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
  1340. // clears the ON_CALL()s set on this mock function.
  1341. void ClearDefaultActionsLocked() override
  1342. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  1343. g_gmock_mutex.AssertHeld();
  1344. // Deleting our default actions may trigger other mock objects to be
  1345. // deleted, for example if an action contains a reference counted smart
  1346. // pointer to that mock object, and that is the last reference. So if we
  1347. // delete our actions within the context of the global mutex we may deadlock
  1348. // when this method is called again. Instead, make a copy of the set of
  1349. // actions to delete, clear our set within the mutex, and then delete the
  1350. // actions outside of the mutex.
  1351. UntypedOnCallSpecs specs_to_delete;
  1352. untyped_on_call_specs_.swap(specs_to_delete);
  1353. g_gmock_mutex.Unlock();
  1354. for (UntypedOnCallSpecs::const_iterator it =
  1355. specs_to_delete.begin();
  1356. it != specs_to_delete.end(); ++it) {
  1357. delete static_cast<const OnCallSpec<F>*>(*it);
  1358. }
  1359. // Lock the mutex again, since the caller expects it to be locked when we
  1360. // return.
  1361. g_gmock_mutex.Lock();
  1362. }
  1363. // Returns the result of invoking this mock function with the given
  1364. // arguments. This function can be safely called from multiple
  1365. // threads concurrently.
  1366. Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  1367. ArgumentTuple tuple(std::forward<Args>(args)...);
  1368. std::unique_ptr<ResultHolder> holder(DownCast_<ResultHolder*>(
  1369. this->UntypedInvokeWith(static_cast<void*>(&tuple))));
  1370. return holder->Unwrap();
  1371. }
  1372. MockSpec<F> With(Matcher<Args>... m) {
  1373. return MockSpec<F>(this, ::std::make_tuple(std::move(m)...));
  1374. }
  1375. protected:
  1376. template <typename Function>
  1377. friend class MockSpec;
  1378. typedef ActionResultHolder<Result> ResultHolder;
  1379. // Adds and returns a default action spec for this mock function.
  1380. OnCallSpec<F>& AddNewOnCallSpec(
  1381. const char* file, int line,
  1382. const ArgumentMatcherTuple& m)
  1383. GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  1384. Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
  1385. OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
  1386. untyped_on_call_specs_.push_back(on_call_spec);
  1387. return *on_call_spec;
  1388. }
  1389. // Adds and returns an expectation spec for this mock function.
  1390. TypedExpectation<F>& AddNewExpectation(const char* file, int line,
  1391. const std::string& source_text,
  1392. const ArgumentMatcherTuple& m)
  1393. GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  1394. Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
  1395. TypedExpectation<F>* const expectation =
  1396. new TypedExpectation<F>(this, file, line, source_text, m);
  1397. const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);
  1398. // See the definition of untyped_expectations_ for why access to
  1399. // it is unprotected here.
  1400. untyped_expectations_.push_back(untyped_expectation);
  1401. // Adds this expectation into the implicit sequence if there is one.
  1402. Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
  1403. if (implicit_sequence != nullptr) {
  1404. implicit_sequence->AddExpectation(Expectation(untyped_expectation));
  1405. }
  1406. return *expectation;
  1407. }
  1408. private:
  1409. template <typename Func> friend class TypedExpectation;
  1410. // Some utilities needed for implementing UntypedInvokeWith().
  1411. // Describes what default action will be performed for the given
  1412. // arguments.
  1413. // L = *
  1414. void DescribeDefaultActionTo(const ArgumentTuple& args,
  1415. ::std::ostream* os) const {
  1416. const OnCallSpec<F>* const spec = FindOnCallSpec(args);
  1417. if (spec == nullptr) {
  1418. *os << (std::is_void<Result>::value ? "returning directly.\n"
  1419. : "returning default value.\n");
  1420. } else {
  1421. *os << "taking default action specified at:\n"
  1422. << FormatFileLocation(spec->file(), spec->line()) << "\n";
  1423. }
  1424. }
  1425. // Writes a message that the call is uninteresting (i.e. neither
  1426. // explicitly expected nor explicitly unexpected) to the given
  1427. // ostream.
  1428. void UntypedDescribeUninterestingCall(const void* untyped_args,
  1429. ::std::ostream* os) const override
  1430. GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  1431. const ArgumentTuple& args =
  1432. *static_cast<const ArgumentTuple*>(untyped_args);
  1433. *os << "Uninteresting mock function call - ";
  1434. DescribeDefaultActionTo(args, os);
  1435. *os << " Function call: " << Name();
  1436. UniversalPrint(args, os);
  1437. }
  1438. // Returns the expectation that matches the given function arguments
  1439. // (or NULL is there's no match); when a match is found,
  1440. // untyped_action is set to point to the action that should be
  1441. // performed (or NULL if the action is "do default"), and
  1442. // is_excessive is modified to indicate whether the call exceeds the
  1443. // expected number.
  1444. //
  1445. // Critical section: We must find the matching expectation and the
  1446. // corresponding action that needs to be taken in an ATOMIC
  1447. // transaction. Otherwise another thread may call this mock
  1448. // method in the middle and mess up the state.
  1449. //
  1450. // However, performing the action has to be left out of the critical
  1451. // section. The reason is that we have no control on what the
  1452. // action does (it can invoke an arbitrary user function or even a
  1453. // mock function) and excessive locking could cause a dead lock.
  1454. const ExpectationBase* UntypedFindMatchingExpectation(
  1455. const void* untyped_args, const void** untyped_action, bool* is_excessive,
  1456. ::std::ostream* what, ::std::ostream* why) override
  1457. GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
  1458. const ArgumentTuple& args =
  1459. *static_cast<const ArgumentTuple*>(untyped_args);
  1460. MutexLock l(&g_gmock_mutex);
  1461. TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
  1462. if (exp == nullptr) { // A match wasn't found.
  1463. this->FormatUnexpectedCallMessageLocked(args, what, why);
  1464. return nullptr;
  1465. }
  1466. // This line must be done before calling GetActionForArguments(),
  1467. // which will increment the call count for *exp and thus affect
  1468. // its saturation status.
  1469. *is_excessive = exp->IsSaturated();
  1470. const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
  1471. if (action != nullptr && action->IsDoDefault())
  1472. action = nullptr; // Normalize "do default" to NULL.
  1473. *untyped_action = action;
  1474. return exp;
  1475. }
  1476. // Prints the given function arguments to the ostream.
  1477. void UntypedPrintArgs(const void* untyped_args,
  1478. ::std::ostream* os) const override {
  1479. const ArgumentTuple& args =
  1480. *static_cast<const ArgumentTuple*>(untyped_args);
  1481. UniversalPrint(args, os);
  1482. }
  1483. // Returns the expectation that matches the arguments, or NULL if no
  1484. // expectation matches them.
  1485. TypedExpectation<F>* FindMatchingExpectationLocked(
  1486. const ArgumentTuple& args) const
  1487. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  1488. g_gmock_mutex.AssertHeld();
  1489. // See the definition of untyped_expectations_ for why access to
  1490. // it is unprotected here.
  1491. for (typename UntypedExpectations::const_reverse_iterator it =
  1492. untyped_expectations_.rbegin();
  1493. it != untyped_expectations_.rend(); ++it) {
  1494. TypedExpectation<F>* const exp =
  1495. static_cast<TypedExpectation<F>*>(it->get());
  1496. if (exp->ShouldHandleArguments(args)) {
  1497. return exp;
  1498. }
  1499. }
  1500. return nullptr;
  1501. }
  1502. // Returns a message that the arguments don't match any expectation.
  1503. void FormatUnexpectedCallMessageLocked(
  1504. const ArgumentTuple& args,
  1505. ::std::ostream* os,
  1506. ::std::ostream* why) const
  1507. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  1508. g_gmock_mutex.AssertHeld();
  1509. *os << "\nUnexpected mock function call - ";
  1510. DescribeDefaultActionTo(args, os);
  1511. PrintTriedExpectationsLocked(args, why);
  1512. }
  1513. // Prints a list of expectations that have been tried against the
  1514. // current mock function call.
  1515. void PrintTriedExpectationsLocked(
  1516. const ArgumentTuple& args,
  1517. ::std::ostream* why) const
  1518. GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
  1519. g_gmock_mutex.AssertHeld();
  1520. const size_t count = untyped_expectations_.size();
  1521. *why << "Google Mock tried the following " << count << " "
  1522. << (count == 1 ? "expectation, but it didn't match" :
  1523. "expectations, but none matched")
  1524. << ":\n";
  1525. for (size_t i = 0; i < count; i++) {
  1526. TypedExpectation<F>* const expectation =
  1527. static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
  1528. *why << "\n";
  1529. expectation->DescribeLocationTo(why);
  1530. if (count > 1) {
  1531. *why << "tried expectation #" << i << ": ";
  1532. }
  1533. *why << expectation->source_text() << "...\n";
  1534. expectation->ExplainMatchResultTo(args, why);
  1535. expectation->DescribeCallCountTo(why);
  1536. }
  1537. }
  1538. }; // class FunctionMocker
  1539. // Reports an uninteresting call (whose description is in msg) in the
  1540. // manner specified by 'reaction'.
  1541. void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
  1542. } // namespace internal
  1543. namespace internal {
  1544. template <typename F>
  1545. class MockFunction;
  1546. template <typename R, typename... Args>
  1547. class MockFunction<R(Args...)> {
  1548. public:
  1549. MockFunction(const MockFunction&) = delete;
  1550. MockFunction& operator=(const MockFunction&) = delete;
  1551. std::function<R(Args...)> AsStdFunction() {
  1552. return [this](Args... args) -> R {
  1553. return this->Call(std::forward<Args>(args)...);
  1554. };
  1555. }
  1556. // Implementation detail: the expansion of the MOCK_METHOD macro.
  1557. R Call(Args... args) {
  1558. mock_.SetOwnerAndName(this, "Call");
  1559. return mock_.Invoke(std::forward<Args>(args)...);
  1560. }
  1561. MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
  1562. mock_.RegisterOwner(this);
  1563. return mock_.With(std::move(m)...);
  1564. }
  1565. MockSpec<R(Args...)> gmock_Call(const WithoutMatchers&, R (*)(Args...)) {
  1566. return this->gmock_Call(::testing::A<Args>()...);
  1567. }
  1568. protected:
  1569. MockFunction() = default;
  1570. ~MockFunction() = default;
  1571. private:
  1572. FunctionMocker<R(Args...)> mock_;
  1573. };
  1574. /*
  1575. The SignatureOf<F> struct is a meta-function returning function signature
  1576. corresponding to the provided F argument.
  1577. It makes use of MockFunction easier by allowing it to accept more F arguments
  1578. than just function signatures.
  1579. Specializations provided here cover a signature type itself and any template
  1580. that can be parameterized with a signature, including std::function and
  1581. boost::function.
  1582. */
  1583. template <typename F, typename = void>
  1584. struct SignatureOf;
  1585. template <typename R, typename... Args>
  1586. struct SignatureOf<R(Args...)> {
  1587. using type = R(Args...);
  1588. };
  1589. template <template <typename> class C, typename F>
  1590. struct SignatureOf<C<F>,
  1591. typename std::enable_if<std::is_function<F>::value>::type>
  1592. : SignatureOf<F> {};
  1593. template <typename F>
  1594. using SignatureOfT = typename SignatureOf<F>::type;
  1595. } // namespace internal
  1596. // A MockFunction<F> type has one mock method whose type is
  1597. // internal::SignatureOfT<F>. It is useful when you just want your
  1598. // test code to emit some messages and have Google Mock verify the
  1599. // right messages are sent (and perhaps at the right times). For
  1600. // example, if you are exercising code:
  1601. //
  1602. // Foo(1);
  1603. // Foo(2);
  1604. // Foo(3);
  1605. //
  1606. // and want to verify that Foo(1) and Foo(3) both invoke
  1607. // mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write:
  1608. //
  1609. // TEST(FooTest, InvokesBarCorrectly) {
  1610. // MyMock mock;
  1611. // MockFunction<void(string check_point_name)> check;
  1612. // {
  1613. // InSequence s;
  1614. //
  1615. // EXPECT_CALL(mock, Bar("a"));
  1616. // EXPECT_CALL(check, Call("1"));
  1617. // EXPECT_CALL(check, Call("2"));
  1618. // EXPECT_CALL(mock, Bar("a"));
  1619. // }
  1620. // Foo(1);
  1621. // check.Call("1");
  1622. // Foo(2);
  1623. // check.Call("2");
  1624. // Foo(3);
  1625. // }
  1626. //
  1627. // The expectation spec says that the first Bar("a") must happen
  1628. // before check point "1", the second Bar("a") must happen after check
  1629. // point "2", and nothing should happen between the two check
  1630. // points. The explicit check points make it easy to tell which
  1631. // Bar("a") is called by which call to Foo().
  1632. //
  1633. // MockFunction<F> can also be used to exercise code that accepts
  1634. // std::function<internal::SignatureOfT<F>> callbacks. To do so, use
  1635. // AsStdFunction() method to create std::function proxy forwarding to
  1636. // original object's Call. Example:
  1637. //
  1638. // TEST(FooTest, RunsCallbackWithBarArgument) {
  1639. // MockFunction<int(string)> callback;
  1640. // EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
  1641. // Foo(callback.AsStdFunction());
  1642. // }
  1643. //
  1644. // The internal::SignatureOfT<F> indirection allows to use other types
  1645. // than just function signature type. This is typically useful when
  1646. // providing a mock for a predefined std::function type. Example:
  1647. //
  1648. // using FilterPredicate = std::function<bool(string)>;
  1649. // void MyFilterAlgorithm(FilterPredicate predicate);
  1650. //
  1651. // TEST(FooTest, FilterPredicateAlwaysAccepts) {
  1652. // MockFunction<FilterPredicate> predicateMock;
  1653. // EXPECT_CALL(predicateMock, Call(_)).WillRepeatedly(Return(true));
  1654. // MyFilterAlgorithm(predicateMock.AsStdFunction());
  1655. // }
  1656. template <typename F>
  1657. class MockFunction : public internal::MockFunction<internal::SignatureOfT<F>> {
  1658. using Base = internal::MockFunction<internal::SignatureOfT<F>>;
  1659. public:
  1660. using Base::Base;
  1661. };
  1662. // The style guide prohibits "using" statements in a namespace scope
  1663. // inside a header file. However, the MockSpec class template is
  1664. // meant to be defined in the ::testing namespace. The following line
  1665. // is just a trick for working around a bug in MSVC 8.0, which cannot
  1666. // handle it if we define MockSpec in ::testing.
  1667. using internal::MockSpec;
  1668. // Const(x) is a convenient function for obtaining a const reference
  1669. // to x. This is useful for setting expectations on an overloaded
  1670. // const mock method, e.g.
  1671. //
  1672. // class MockFoo : public FooInterface {
  1673. // public:
  1674. // MOCK_METHOD0(Bar, int());
  1675. // MOCK_CONST_METHOD0(Bar, int&());
  1676. // };
  1677. //
  1678. // MockFoo foo;
  1679. // // Expects a call to non-const MockFoo::Bar().
  1680. // EXPECT_CALL(foo, Bar());
  1681. // // Expects a call to const MockFoo::Bar().
  1682. // EXPECT_CALL(Const(foo), Bar());
  1683. template <typename T>
  1684. inline const T& Const(const T& x) { return x; }
  1685. // Constructs an Expectation object that references and co-owns exp.
  1686. inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
  1687. : expectation_base_(exp.GetHandle().expectation_base()) {}
  1688. } // namespace testing
  1689. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
  1690. // Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is
  1691. // required to avoid compile errors when the name of the method used in call is
  1692. // a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro
  1693. // tests in internal/gmock-spec-builders_test.cc for more details.
  1694. //
  1695. // This macro supports statements both with and without parameter matchers. If
  1696. // the parameter list is omitted, gMock will accept any parameters, which allows
  1697. // tests to be written that don't need to encode the number of method
  1698. // parameter. This technique may only be used for non-overloaded methods.
  1699. //
  1700. // // These are the same:
  1701. // ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
  1702. // ON_CALL(mock, NoArgsMethod).WillByDefault(...);
  1703. //
  1704. // // As are these:
  1705. // ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
  1706. // ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
  1707. //
  1708. // // Can also specify args if you want, of course:
  1709. // ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
  1710. //
  1711. // // Overloads work as long as you specify parameters:
  1712. // ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
  1713. // ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
  1714. //
  1715. // // Oops! Which overload did you want?
  1716. // ON_CALL(mock, OverloadedMethod).WillByDefault(...);
  1717. // => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
  1718. //
  1719. // How this works: The mock class uses two overloads of the gmock_Method
  1720. // expectation setter method plus an operator() overload on the MockSpec object.
  1721. // In the matcher list form, the macro expands to:
  1722. //
  1723. // // This statement:
  1724. // ON_CALL(mock, TwoArgsMethod(_, 45))...
  1725. //
  1726. // // ...expands to:
  1727. // mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
  1728. // |-------------v---------------||------------v-------------|
  1729. // invokes first overload swallowed by operator()
  1730. //
  1731. // // ...which is essentially:
  1732. // mock.gmock_TwoArgsMethod(_, 45)...
  1733. //
  1734. // Whereas the form without a matcher list:
  1735. //
  1736. // // This statement:
  1737. // ON_CALL(mock, TwoArgsMethod)...
  1738. //
  1739. // // ...expands to:
  1740. // mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
  1741. // |-----------------------v--------------------------|
  1742. // invokes second overload
  1743. //
  1744. // // ...which is essentially:
  1745. // mock.gmock_TwoArgsMethod(_, _)...
  1746. //
  1747. // The WithoutMatchers() argument is used to disambiguate overloads and to
  1748. // block the caller from accidentally invoking the second overload directly. The
  1749. // second argument is an internal type derived from the method signature. The
  1750. // failure to disambiguate two overloads of this method in the ON_CALL statement
  1751. // is how we block callers from setting expectations on overloaded methods.
  1752. #define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
  1753. ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \
  1754. nullptr) \
  1755. .Setter(__FILE__, __LINE__, #mock_expr, #call)
  1756. #define ON_CALL(obj, call) \
  1757. GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
  1758. #define EXPECT_CALL(obj, call) \
  1759. GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
  1760. #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_