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