gmock-spec-builders.h 80 KB

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