gmock-spec-builders.h 79 KB

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