gmock-spec-builders.h 71 KB

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