gmock-spec-builders.h 78 KB

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