gmock-spec-builders.h 73 KB

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