Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(4)

Side by Side Diff: testing/gmock/include/gmock/gmock-spec-builders.h

Issue 115846: Retry to checkin a version of gmock, modified to use our boost_tuple in VS2005. (Closed)
Patch Set: Created 11 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
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 // Author: wan@google.com (Zhanyong Wan)
31
32 // Google Mock - a framework for writing C++ mock classes.
33 //
34 // This file implements the ON_CALL() and EXPECT_CALL() macros.
35 //
36 // A user can use the ON_CALL() macro to specify the default action of
37 // a mock method. The syntax is:
38 //
39 // ON_CALL(mock_object, Method(argument-matchers))
40 // .WithArguments(multi-argument-matcher)
41 // .WillByDefault(action);
42 //
43 // where the .WithArguments() clause is optional.
44 //
45 // A user can use the EXPECT_CALL() macro to specify an expectation on
46 // a mock method. The syntax is:
47 //
48 // EXPECT_CALL(mock_object, Method(argument-matchers))
49 // .WithArguments(multi-argument-matchers)
50 // .Times(cardinality)
51 // .InSequence(sequences)
52 // .WillOnce(action)
53 // .WillRepeatedly(action)
54 // .RetiresOnSaturation();
55 //
56 // where all clauses are optional, .InSequence() and .WillOnce() can
57 // appear any number of times, and .Times() can be omitted only if
58 // .WillOnce() or .WillRepeatedly() is present.
59
60 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
61 #define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
62
63 #include <map>
64 #include <set>
65 #include <sstream>
66 #include <string>
67 #include <vector>
68
69 #include <gmock/gmock-actions.h>
70 #include <gmock/gmock-cardinalities.h>
71 #include <gmock/gmock-matchers.h>
72 #include <gmock/gmock-printers.h>
73 #include <gmock/internal/gmock-internal-utils.h>
74 #include <gmock/internal/gmock-port.h>
75 #include <gtest/gtest.h>
76
77 namespace testing {
78
79 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
80 // and MUST NOT BE USED IN USER CODE!!!
81 namespace internal {
82
83 template <typename F>
84 class FunctionMocker;
85
86 // Base class for expectations.
87 class ExpectationBase;
88
89 // Helper class for testing the Expectation class template.
90 class ExpectationTester;
91
92 // Base class for function mockers.
93 template <typename F>
94 class FunctionMockerBase;
95
96 // Helper class for implementing FunctionMockerBase<F>::InvokeWith().
97 template <typename Result, typename F>
98 class InvokeWithHelper;
99
100 // Protects the mock object registry (in class Mock), all function
101 // mockers, and all expectations.
102 //
103 // The reason we don't use more fine-grained protection is: when a
104 // mock function Foo() is called, it needs to consult its expectations
105 // to see which one should be picked. If another thread is allowed to
106 // call a mock function (either Foo() or a different one) at the same
107 // time, it could affect the "retired" attributes of Foo()'s
108 // expectations when InSequence() is used, and thus affect which
109 // expectation gets picked. Therefore, we sequence all mock function
110 // calls to ensure the integrity of the mock objects' states.
111 extern Mutex g_gmock_mutex;
112
113 // Abstract base class of FunctionMockerBase. This is the
114 // type-agnostic part of the function mocker interface. Its pure
115 // virtual methods are implemented by FunctionMockerBase.
116 class UntypedFunctionMockerBase {
117 public:
118 virtual ~UntypedFunctionMockerBase() {}
119
120 // Verifies that all expectations on this mock function have been
121 // satisfied. Reports one or more Google Test non-fatal failures
122 // and returns false if not.
123 // L >= g_gmock_mutex
124 virtual bool VerifyAndClearExpectationsLocked() = 0;
125
126 // Clears the ON_CALL()s set on this mock function.
127 // L >= g_gmock_mutex
128 virtual void ClearDefaultActionsLocked() = 0;
129 }; // class UntypedFunctionMockerBase
130
131 // This template class implements a default action spec (i.e. an
132 // ON_CALL() statement).
133 template <typename F>
134 class DefaultActionSpec {
135 public:
136 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
137 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
138
139 // Constructs a DefaultActionSpec object from the information inside
140 // the parenthesis of an ON_CALL() statement.
141 DefaultActionSpec(const char* file, int line,
142 const ArgumentMatcherTuple& matchers)
143 : file_(file),
144 line_(line),
145 matchers_(matchers),
146 // By default, extra_matcher_ should match anything. However,
147 // we cannot initialize it with _ as that triggers a compiler
148 // bug in Symbian's C++ compiler (cannot decide between two
149 // overloaded constructors of Matcher<const ArgumentTuple&>).
150 extra_matcher_(A<const ArgumentTuple&>()),
151 last_clause_(NONE) {
152 }
153
154 // Where in the source file was the default action spec defined?
155 const char* file() const { return file_; }
156 int line() const { return line_; }
157
158 // Implements the .WithArguments() clause.
159 DefaultActionSpec& WithArguments(const Matcher<const ArgumentTuple&>& m) {
160 // Makes sure this is called at most once.
161 ExpectSpecProperty(last_clause_ < WITH_ARGUMENTS,
162 ".WithArguments() cannot appear "
163 "more than once in an ON_CALL().");
164 last_clause_ = WITH_ARGUMENTS;
165
166 extra_matcher_ = m;
167 return *this;
168 }
169
170 // Implements the .WillByDefault() clause.
171 DefaultActionSpec& WillByDefault(const Action<F>& action) {
172 ExpectSpecProperty(last_clause_ < WILL_BY_DEFAULT,
173 ".WillByDefault() must appear "
174 "exactly once in an ON_CALL().");
175 last_clause_ = WILL_BY_DEFAULT;
176
177 ExpectSpecProperty(!action.IsDoDefault(),
178 "DoDefault() cannot be used in ON_CALL().");
179 action_ = action;
180 return *this;
181 }
182
183 // Returns true iff the given arguments match the matchers.
184 bool Matches(const ArgumentTuple& args) const {
185 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
186 }
187
188 // Returns the action specified by the user.
189 const Action<F>& GetAction() const {
190 AssertSpecProperty(last_clause_ == WILL_BY_DEFAULT,
191 ".WillByDefault() must appear exactly "
192 "once in an ON_CALL().");
193 return action_;
194 }
195 private:
196 // Gives each clause in the ON_CALL() statement a name.
197 enum Clause {
198 // Do not change the order of the enum members! The run-time
199 // syntax checking relies on it.
200 NONE,
201 WITH_ARGUMENTS,
202 WILL_BY_DEFAULT,
203 };
204
205 // Asserts that the ON_CALL() statement has a certain property.
206 void AssertSpecProperty(bool property, const string& failure_message) const {
207 Assert(property, file_, line_, failure_message);
208 }
209
210 // Expects that the ON_CALL() statement has a certain property.
211 void ExpectSpecProperty(bool property, const string& failure_message) const {
212 Expect(property, file_, line_, failure_message);
213 }
214
215 // The information in statement
216 //
217 // ON_CALL(mock_object, Method(matchers))
218 // .WithArguments(multi-argument-matcher)
219 // .WillByDefault(action);
220 //
221 // is recorded in the data members like this:
222 //
223 // source file that contains the statement => file_
224 // line number of the statement => line_
225 // matchers => matchers_
226 // multi-argument-matcher => extra_matcher_
227 // action => action_
228 const char* file_;
229 int line_;
230 ArgumentMatcherTuple matchers_;
231 Matcher<const ArgumentTuple&> extra_matcher_;
232 Action<F> action_;
233
234 // The last clause in the ON_CALL() statement as seen so far.
235 // Initially NONE and changes as the statement is parsed.
236 Clause last_clause_;
237 }; // class DefaultActionSpec
238
239 // Possible reactions on uninteresting calls.
240 enum CallReaction {
241 ALLOW,
242 WARN,
243 FAIL,
244 };
245
246 } // namespace internal
247
248 // Utilities for manipulating mock objects.
249 class Mock {
250 public:
251 // The following public methods can be called concurrently.
252
253 // Tells Google Mock to ignore mock_obj when checking for leaked
254 // mock objects.
255 static void AllowLeak(const void* mock_obj);
256
257 // Verifies and clears all expectations on the given mock object.
258 // If the expectations aren't satisfied, generates one or more
259 // Google Test non-fatal failures and returns false.
260 static bool VerifyAndClearExpectations(void* mock_obj);
261
262 // Verifies all expectations on the given mock object and clears its
263 // default actions and expectations. Returns true iff the
264 // verification was successful.
265 static bool VerifyAndClear(void* mock_obj);
266 private:
267 // Needed for a function mocker to register itself (so that we know
268 // how to clear a mock object).
269 template <typename F>
270 friend class internal::FunctionMockerBase;
271
272 template <typename R, typename Args>
273 friend class internal::InvokeWithHelper;
274
275 template <typename M>
276 friend class NiceMock;
277
278 template <typename M>
279 friend class StrictMock;
280
281 // Tells Google Mock to allow uninteresting calls on the given mock
282 // object.
283 // L < g_gmock_mutex
284 static void AllowUninterestingCalls(const void* mock_obj);
285
286 // Tells Google Mock to warn the user about uninteresting calls on
287 // the given mock object.
288 // L < g_gmock_mutex
289 static void WarnUninterestingCalls(const void* mock_obj);
290
291 // Tells Google Mock to fail uninteresting calls on the given mock
292 // object.
293 // L < g_gmock_mutex
294 static void FailUninterestingCalls(const void* mock_obj);
295
296 // Tells Google Mock the given mock object is being destroyed and
297 // its entry in the call-reaction table should be removed.
298 // L < g_gmock_mutex
299 static void UnregisterCallReaction(const void* mock_obj);
300
301 // Returns the reaction Google Mock will have on uninteresting calls
302 // made on the given mock object.
303 // L < g_gmock_mutex
304 static internal::CallReaction GetReactionOnUninterestingCalls(
305 const void* mock_obj);
306
307 // Verifies that all expectations on the given mock object have been
308 // satisfied. Reports one or more Google Test non-fatal failures
309 // and returns false if not.
310 // L >= g_gmock_mutex
311 static bool VerifyAndClearExpectationsLocked(void* mock_obj);
312
313 // Clears all ON_CALL()s set on the given mock object.
314 // L >= g_gmock_mutex
315 static void ClearDefaultActionsLocked(void* mock_obj);
316
317 // Registers a mock object and a mock method it owns.
318 // L < g_gmock_mutex
319 static void Register(const void* mock_obj,
320 internal::UntypedFunctionMockerBase* mocker);
321
322 // Tells Google Mock where in the source code mock_obj is used in an
323 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
324 // information helps the user identify which object it is.
325 // L < g_gmock_mutex
326 static void RegisterUseByOnCallOrExpectCall(
327 const void* mock_obj, const char* file, int line);
328
329 // Unregisters a mock method; removes the owning mock object from
330 // the registry when the last mock method associated with it has
331 // been unregistered. This is called only in the destructor of
332 // FunctionMockerBase.
333 // L >= g_gmock_mutex
334 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker);
335 }; // class Mock
336
337 // Sequence objects are used by a user to specify the relative order
338 // in which the expectations should match. They are copyable (we rely
339 // on the compiler-defined copy constructor and assignment operator).
340 class Sequence {
341 public:
342 // Constructs an empty sequence.
343 Sequence()
344 : last_expectation_(
345 new internal::linked_ptr<internal::ExpectationBase>(NULL)) {}
346
347 // Adds an expectation to this sequence. The caller must ensure
348 // that no other thread is accessing this Sequence object.
349 void AddExpectation(
350 const internal::linked_ptr<internal::ExpectationBase>& expectation) const;
351 private:
352 // The last expectation in this sequence. We use a nested
353 // linked_ptr here because:
354 // - Sequence objects are copyable, and we want the copies to act
355 // as aliases. The outer linked_ptr allows the copies to co-own
356 // and share the same state.
357 // - An Expectation object is co-owned (via linked_ptr) by its
358 // FunctionMocker and its successors (other Expectation objects).
359 // Hence the inner linked_ptr.
360 internal::linked_ptr<internal::linked_ptr<internal::ExpectationBase> >
361 last_expectation_;
362 }; // class Sequence
363
364 // An object of this type causes all EXPECT_CALL() statements
365 // encountered in its scope to be put in an anonymous sequence. The
366 // work is done in the constructor and destructor. You should only
367 // create an InSequence object on the stack.
368 //
369 // The sole purpose for this class is to support easy definition of
370 // sequential expectations, e.g.
371 //
372 // {
373 // InSequence dummy; // The name of the object doesn't matter.
374 //
375 // // The following expectations must match in the order they appear.
376 // EXPECT_CALL(a, Bar())...;
377 // EXPECT_CALL(a, Baz())...;
378 // ...
379 // EXPECT_CALL(b, Xyz())...;
380 // }
381 //
382 // You can create InSequence objects in multiple threads, as long as
383 // they are used to affect different mock objects. The idea is that
384 // each thread can create and set up its own mocks as if it's the only
385 // thread. However, for clarity of your tests we recommend you to set
386 // up mocks in the main thread unless you have a good reason not to do
387 // so.
388 class InSequence {
389 public:
390 InSequence();
391 ~InSequence();
392 private:
393 bool sequence_created_;
394
395 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
396 } GMOCK_ATTRIBUTE_UNUSED_;
397
398 namespace internal {
399
400 // Points to the implicit sequence introduced by a living InSequence
401 // object (if any) in the current thread or NULL.
402 extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
403
404 // Base class for implementing expectations.
405 //
406 // There are two reasons for having a type-agnostic base class for
407 // Expectation:
408 //
409 // 1. We need to store collections of expectations of different
410 // types (e.g. all pre-requisites of a particular expectation, all
411 // expectations in a sequence). Therefore these expectation objects
412 // must share a common base class.
413 //
414 // 2. We can avoid binary code bloat by moving methods not depending
415 // on the template argument of Expectation to the base class.
416 //
417 // This class is internal and mustn't be used by user code directly.
418 class ExpectationBase {
419 public:
420 ExpectationBase(const char* file, int line);
421
422 virtual ~ExpectationBase();
423
424 // Where in the source file was the expectation spec defined?
425 const char* file() const { return file_; }
426 int line() const { return line_; }
427
428 // Returns the cardinality specified in the expectation spec.
429 const Cardinality& cardinality() const { return cardinality_; }
430
431 // Describes the source file location of this expectation.
432 void DescribeLocationTo(::std::ostream* os) const {
433 *os << file() << ":" << line() << ": ";
434 }
435
436 // Describes how many times a function call matching this
437 // expectation has occurred.
438 // L >= g_gmock_mutex
439 virtual void DescribeCallCountTo(::std::ostream* os) const = 0;
440 protected:
441 typedef std::set<linked_ptr<ExpectationBase>,
442 LinkedPtrLessThan<ExpectationBase> >
443 ExpectationBaseSet;
444
445 enum Clause {
446 // Don't change the order of the enum members!
447 NONE,
448 WITH_ARGUMENTS,
449 TIMES,
450 IN_SEQUENCE,
451 WILL_ONCE,
452 WILL_REPEATEDLY,
453 RETIRES_ON_SATURATION,
454 };
455
456 // Asserts that the EXPECT_CALL() statement has the given property.
457 void AssertSpecProperty(bool property, const string& failure_message) const {
458 Assert(property, file_, line_, failure_message);
459 }
460
461 // Expects that the EXPECT_CALL() statement has the given property.
462 void ExpectSpecProperty(bool property, const string& failure_message) const {
463 Expect(property, file_, line_, failure_message);
464 }
465
466 // Explicitly specifies the cardinality of this expectation. Used
467 // by the subclasses to implement the .Times() clause.
468 void SpecifyCardinality(const Cardinality& cardinality);
469
470 // Returns true iff the user specified the cardinality explicitly
471 // using a .Times().
472 bool cardinality_specified() const { return cardinality_specified_; }
473
474 // Sets the cardinality of this expectation spec.
475 void set_cardinality(const Cardinality& cardinality) {
476 cardinality_ = cardinality;
477 }
478
479 // The following group of methods should only be called after the
480 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
481 // the current thread.
482
483 // Retires all pre-requisites of this expectation.
484 // L >= g_gmock_mutex
485 void RetireAllPreRequisites();
486
487 // Returns true iff this expectation is retired.
488 // L >= g_gmock_mutex
489 bool is_retired() const {
490 g_gmock_mutex.AssertHeld();
491 return retired_;
492 }
493
494 // Retires this expectation.
495 // L >= g_gmock_mutex
496 void Retire() {
497 g_gmock_mutex.AssertHeld();
498 retired_ = true;
499 }
500
501 // Returns true iff this expectation is satisfied.
502 // L >= g_gmock_mutex
503 bool IsSatisfied() const {
504 g_gmock_mutex.AssertHeld();
505 return cardinality().IsSatisfiedByCallCount(call_count_);
506 }
507
508 // Returns true iff this expectation is saturated.
509 // L >= g_gmock_mutex
510 bool IsSaturated() const {
511 g_gmock_mutex.AssertHeld();
512 return cardinality().IsSaturatedByCallCount(call_count_);
513 }
514
515 // Returns true iff this expectation is over-saturated.
516 // L >= g_gmock_mutex
517 bool IsOverSaturated() const {
518 g_gmock_mutex.AssertHeld();
519 return cardinality().IsOverSaturatedByCallCount(call_count_);
520 }
521
522 // Returns true iff all pre-requisites of this expectation are satisfied.
523 // L >= g_gmock_mutex
524 bool AllPrerequisitesAreSatisfied() const;
525
526 // Adds unsatisfied pre-requisites of this expectation to 'result'.
527 // L >= g_gmock_mutex
528 void FindUnsatisfiedPrerequisites(ExpectationBaseSet* result) const;
529
530 // Returns the number this expectation has been invoked.
531 // L >= g_gmock_mutex
532 int call_count() const {
533 g_gmock_mutex.AssertHeld();
534 return call_count_;
535 }
536
537 // Increments the number this expectation has been invoked.
538 // L >= g_gmock_mutex
539 void IncrementCallCount() {
540 g_gmock_mutex.AssertHeld();
541 call_count_++;
542 }
543
544 private:
545 friend class ::testing::Sequence;
546 friend class ::testing::internal::ExpectationTester;
547
548 template <typename Function>
549 friend class Expectation;
550
551 // This group of fields are part of the spec and won't change after
552 // an EXPECT_CALL() statement finishes.
553 const char* file_; // The file that contains the expectation.
554 int line_; // The line number of the expectation.
555 // True iff the cardinality is specified explicitly.
556 bool cardinality_specified_;
557 Cardinality cardinality_; // The cardinality of the expectation.
558 // The immediate pre-requisites of this expectation. We use
559 // linked_ptr in the set because we want an Expectation object to be
560 // co-owned by its FunctionMocker and its successors. This allows
561 // multiple mock objects to be deleted at different times.
562 ExpectationBaseSet immediate_prerequisites_;
563
564 // This group of fields are the current state of the expectation,
565 // and can change as the mock function is called.
566 int call_count_; // How many times this expectation has been invoked.
567 bool retired_; // True iff this expectation has retired.
568 }; // class ExpectationBase
569
570 // Impements an expectation for the given function type.
571 template <typename F>
572 class Expectation : public ExpectationBase {
573 public:
574 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
575 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
576 typedef typename Function<F>::Result Result;
577
578 Expectation(FunctionMockerBase<F>* owner, const char* file, int line,
579 const ArgumentMatcherTuple& m)
580 : ExpectationBase(file, line),
581 owner_(owner),
582 matchers_(m),
583 // By default, extra_matcher_ should match anything. However,
584 // we cannot initialize it with _ as that triggers a compiler
585 // bug in Symbian's C++ compiler (cannot decide between two
586 // overloaded constructors of Matcher<const ArgumentTuple&>).
587 extra_matcher_(A<const ArgumentTuple&>()),
588 repeated_action_specified_(false),
589 repeated_action_(DoDefault()),
590 retires_on_saturation_(false),
591 last_clause_(NONE),
592 action_count_checked_(false) {}
593
594 virtual ~Expectation() {
595 // Check the validity of the action count if it hasn't been done
596 // yet (for example, if the expectation was never used).
597 CheckActionCountIfNotDone();
598 }
599
600 // Implements the .WithArguments() clause.
601 Expectation& WithArguments(const Matcher<const ArgumentTuple&>& m) {
602 if (last_clause_ == WITH_ARGUMENTS) {
603 ExpectSpecProperty(false,
604 ".WithArguments() cannot appear "
605 "more than once in an EXPECT_CALL().");
606 } else {
607 ExpectSpecProperty(last_clause_ < WITH_ARGUMENTS,
608 ".WithArguments() must be the first "
609 "clause in an EXPECT_CALL().");
610 }
611 last_clause_ = WITH_ARGUMENTS;
612
613 extra_matcher_ = m;
614 return *this;
615 }
616
617 // Implements the .Times() clause.
618 Expectation& Times(const Cardinality& cardinality) {
619 if (last_clause_ ==TIMES) {
620 ExpectSpecProperty(false,
621 ".Times() cannot appear "
622 "more than once in an EXPECT_CALL().");
623 } else {
624 ExpectSpecProperty(last_clause_ < TIMES,
625 ".Times() cannot appear after "
626 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
627 "or .RetiresOnSaturation().");
628 }
629 last_clause_ = TIMES;
630
631 ExpectationBase::SpecifyCardinality(cardinality);
632 return *this;
633 }
634
635 // Implements the .Times() clause.
636 Expectation& Times(int n) {
637 return Times(Exactly(n));
638 }
639
640 // Implements the .InSequence() clause.
641 Expectation& InSequence(const Sequence& s) {
642 ExpectSpecProperty(last_clause_ <= IN_SEQUENCE,
643 ".InSequence() cannot appear after .WillOnce(),"
644 " .WillRepeatedly(), or "
645 ".RetiresOnSaturation().");
646 last_clause_ = IN_SEQUENCE;
647
648 s.AddExpectation(owner_->GetLinkedExpectationBase(this));
649 return *this;
650 }
651 Expectation& InSequence(const Sequence& s1, const Sequence& s2) {
652 return InSequence(s1).InSequence(s2);
653 }
654 Expectation& InSequence(const Sequence& s1, const Sequence& s2,
655 const Sequence& s3) {
656 return InSequence(s1, s2).InSequence(s3);
657 }
658 Expectation& InSequence(const Sequence& s1, const Sequence& s2,
659 const Sequence& s3, const Sequence& s4) {
660 return InSequence(s1, s2, s3).InSequence(s4);
661 }
662 Expectation& InSequence(const Sequence& s1, const Sequence& s2,
663 const Sequence& s3, const Sequence& s4,
664 const Sequence& s5) {
665 return InSequence(s1, s2, s3, s4).InSequence(s5);
666 }
667
668 // Implements the .WillOnce() clause.
669 Expectation& WillOnce(const Action<F>& action) {
670 ExpectSpecProperty(last_clause_ <= WILL_ONCE,
671 ".WillOnce() cannot appear after "
672 ".WillRepeatedly() or .RetiresOnSaturation().");
673 last_clause_ = WILL_ONCE;
674
675 actions_.push_back(action);
676 if (!cardinality_specified()) {
677 set_cardinality(Exactly(static_cast<int>(actions_.size())));
678 }
679 return *this;
680 }
681
682 // Implements the .WillRepeatedly() clause.
683 Expectation& WillRepeatedly(const Action<F>& action) {
684 if (last_clause_ == WILL_REPEATEDLY) {
685 ExpectSpecProperty(false,
686 ".WillRepeatedly() cannot appear "
687 "more than once in an EXPECT_CALL().");
688 } else {
689 ExpectSpecProperty(last_clause_ < WILL_REPEATEDLY,
690 ".WillRepeatedly() cannot appear "
691 "after .RetiresOnSaturation().");
692 }
693 last_clause_ = WILL_REPEATEDLY;
694 repeated_action_specified_ = true;
695
696 repeated_action_ = action;
697 if (!cardinality_specified()) {
698 set_cardinality(AtLeast(static_cast<int>(actions_.size())));
699 }
700
701 // Now that no more action clauses can be specified, we check
702 // whether their count makes sense.
703 CheckActionCountIfNotDone();
704 return *this;
705 }
706
707 // Implements the .RetiresOnSaturation() clause.
708 Expectation& RetiresOnSaturation() {
709 ExpectSpecProperty(last_clause_ < RETIRES_ON_SATURATION,
710 ".RetiresOnSaturation() cannot appear "
711 "more than once.");
712 last_clause_ = RETIRES_ON_SATURATION;
713 retires_on_saturation_ = true;
714
715 // Now that no more action clauses can be specified, we check
716 // whether their count makes sense.
717 CheckActionCountIfNotDone();
718 return *this;
719 }
720
721 // Returns the matchers for the arguments as specified inside the
722 // EXPECT_CALL() macro.
723 const ArgumentMatcherTuple& matchers() const {
724 return matchers_;
725 }
726
727 // Returns the matcher specified by the .WithArguments() clause.
728 const Matcher<const ArgumentTuple&>& extra_matcher() const {
729 return extra_matcher_;
730 }
731
732 // Returns the sequence of actions specified by the .WillOnce() clause.
733 const std::vector<Action<F> >& actions() const { return actions_; }
734
735 // Returns the action specified by the .WillRepeatedly() clause.
736 const Action<F>& repeated_action() const { return repeated_action_; }
737
738 // Returns true iff the .RetiresOnSaturation() clause was specified.
739 bool retires_on_saturation() const { return retires_on_saturation_; }
740
741 // Describes how many times a function call matching this
742 // expectation has occurred (implements
743 // ExpectationBase::DescribeCallCountTo()).
744 // L >= g_gmock_mutex
745 virtual void DescribeCallCountTo(::std::ostream* os) const {
746 g_gmock_mutex.AssertHeld();
747
748 // Describes how many times the function is expected to be called.
749 *os << " Expected: to be ";
750 cardinality().DescribeTo(os);
751 *os << "\n Actual: ";
752 Cardinality::DescribeActualCallCountTo(call_count(), os);
753
754 // Describes the state of the expectation (e.g. is it satisfied?
755 // is it active?).
756 *os << " - " << (IsOverSaturated() ? "over-saturated" :
757 IsSaturated() ? "saturated" :
758 IsSatisfied() ? "satisfied" : "unsatisfied")
759 << " and "
760 << (is_retired() ? "retired" : "active");
761 }
762 private:
763 template <typename Function>
764 friend class FunctionMockerBase;
765
766 template <typename R, typename Function>
767 friend class InvokeWithHelper;
768
769 // The following methods will be called only after the EXPECT_CALL()
770 // statement finishes and when the current thread holds
771 // g_gmock_mutex.
772
773 // Returns true iff this expectation matches the given arguments.
774 // L >= g_gmock_mutex
775 bool Matches(const ArgumentTuple& args) const {
776 g_gmock_mutex.AssertHeld();
777 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
778 }
779
780 // Returns true iff this expectation should handle the given arguments.
781 // L >= g_gmock_mutex
782 bool ShouldHandleArguments(const ArgumentTuple& args) const {
783 g_gmock_mutex.AssertHeld();
784
785 // In case the action count wasn't checked when the expectation
786 // was defined (e.g. if this expectation has no WillRepeatedly()
787 // or RetiresOnSaturation() clause), we check it when the
788 // expectation is used for the first time.
789 CheckActionCountIfNotDone();
790 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
791 }
792
793 // Describes the result of matching the arguments against this
794 // expectation to the given ostream.
795 // L >= g_gmock_mutex
796 void DescribeMatchResultTo(const ArgumentTuple& args,
797 ::std::ostream* os) const {
798 g_gmock_mutex.AssertHeld();
799
800 if (is_retired()) {
801 *os << " Expected: the expectation is active\n"
802 << " Actual: it is retired\n";
803 } else if (!Matches(args)) {
804 if (!TupleMatches(matchers_, args)) {
805 DescribeMatchFailureTupleTo(matchers_, args, os);
806 }
807 if (!extra_matcher_.Matches(args)) {
808 *os << " Expected: ";
809 extra_matcher_.DescribeTo(os);
810 *os << "\n Actual: false";
811
812 internal::ExplainMatchResultAsNeededTo<const ArgumentTuple&>(
813 extra_matcher_, args, os);
814 *os << "\n";
815 }
816 } else if (!AllPrerequisitesAreSatisfied()) {
817 *os << " Expected: all pre-requisites are satisfied\n"
818 << " Actual: the following immediate pre-requisites "
819 << "are not satisfied:\n";
820 ExpectationBaseSet unsatisfied_prereqs;
821 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
822 int i = 0;
823 for (ExpectationBaseSet::const_iterator it = unsatisfied_prereqs.begin();
824 it != unsatisfied_prereqs.end(); ++it) {
825 (*it)->DescribeLocationTo(os);
826 *os << "pre-requisite #" << i++ << "\n";
827 }
828 *os << " (end of pre-requisites)\n";
829 } else {
830 // This line is here just for completeness' sake. It will never
831 // be executed as currently the DescribeMatchResultTo() function
832 // is called only when the mock function call does NOT match the
833 // expectation.
834 *os << "The call matches the expectation.\n";
835 }
836 }
837
838 // Returns the action that should be taken for the current invocation.
839 // L >= g_gmock_mutex
840 const Action<F>& GetCurrentAction(const FunctionMockerBase<F>* mocker,
841 const ArgumentTuple& args) const {
842 g_gmock_mutex.AssertHeld();
843 const int count = call_count();
844 Assert(count >= 1, __FILE__, __LINE__,
845 "call_count() is <= 0 when GetCurrentAction() is "
846 "called - this should never happen.");
847
848 const int action_count = static_cast<int>(actions().size());
849 if (action_count > 0 && !repeated_action_specified_ &&
850 count > action_count) {
851 // If there is at least one WillOnce() and no WillRepeatedly(),
852 // we warn the user when the WillOnce() clauses ran out.
853 ::std::stringstream ss;
854 DescribeLocationTo(&ss);
855 ss << "Actions ran out.\n"
856 << "Called " << count << " times, but only "
857 << action_count << " WillOnce()"
858 << (action_count == 1 ? " is" : "s are") << " specified - ";
859 mocker->DescribeDefaultActionTo(args, &ss);
860 Log(WARNING, ss.str(), 1);
861 }
862
863 return count <= action_count ? actions()[count - 1] : repeated_action();
864 }
865
866 // Given the arguments of a mock function call, if the call will
867 // over-saturate this expectation, returns the default action;
868 // otherwise, returns the next action in this expectation. Also
869 // describes *what* happened to 'what', and explains *why* Google
870 // Mock does it to 'why'. This method is not const as it calls
871 // IncrementCallCount().
872 // L >= g_gmock_mutex
873 Action<F> GetActionForArguments(const FunctionMockerBase<F>* mocker,
874 const ArgumentTuple& args,
875 ::std::ostream* what,
876 ::std::ostream* why) {
877 g_gmock_mutex.AssertHeld();
878 if (IsSaturated()) {
879 // We have an excessive call.
880 IncrementCallCount();
881 *what << "Mock function called more times than expected - ";
882 mocker->DescribeDefaultActionTo(args, what);
883 DescribeCallCountTo(why);
884
885 // TODO(wan): allow the user to control whether unexpected calls
886 // should fail immediately or continue using a flag
887 // --gmock_unexpected_calls_are_fatal.
888 return DoDefault();
889 }
890
891 IncrementCallCount();
892 RetireAllPreRequisites();
893
894 if (retires_on_saturation() && IsSaturated()) {
895 Retire();
896 }
897
898 // Must be done after IncrementCount()!
899 *what << "Expected mock function call.\n";
900 return GetCurrentAction(mocker, args);
901 }
902
903 // Checks the action count (i.e. the number of WillOnce() and
904 // WillRepeatedly() clauses) against the cardinality if this hasn't
905 // been done before. Prints a warning if there are too many or too
906 // few actions.
907 // L < mutex_
908 void CheckActionCountIfNotDone() const {
909 bool should_check = false;
910 {
911 MutexLock l(&mutex_);
912 if (!action_count_checked_) {
913 action_count_checked_ = true;
914 should_check = true;
915 }
916 }
917
918 if (should_check) {
919 if (!cardinality_specified_) {
920 // The cardinality was inferred - no need to check the action
921 // count against it.
922 return;
923 }
924
925 // The cardinality was explicitly specified.
926 const int action_count = static_cast<int>(actions_.size());
927 const int upper_bound = cardinality().ConservativeUpperBound();
928 const int lower_bound = cardinality().ConservativeLowerBound();
929 bool too_many; // True if there are too many actions, or false
930 // if there are too few.
931 if (action_count > upper_bound ||
932 (action_count == upper_bound && repeated_action_specified_)) {
933 too_many = true;
934 } else if (0 < action_count && action_count < lower_bound &&
935 !repeated_action_specified_) {
936 too_many = false;
937 } else {
938 return;
939 }
940
941 ::std::stringstream ss;
942 DescribeLocationTo(&ss);
943 ss << "Too " << (too_many ? "many" : "few")
944 << " actions specified.\n"
945 << "Expected to be ";
946 cardinality().DescribeTo(&ss);
947 ss << ", but has " << (too_many ? "" : "only ")
948 << action_count << " WillOnce()"
949 << (action_count == 1 ? "" : "s");
950 if (repeated_action_specified_) {
951 ss << " and a WillRepeatedly()";
952 }
953 ss << ".";
954 Log(WARNING, ss.str(), -1); // -1 means "don't print stack trace".
955 }
956 }
957
958 // All the fields below won't change once the EXPECT_CALL()
959 // statement finishes.
960 FunctionMockerBase<F>* const owner_;
961 ArgumentMatcherTuple matchers_;
962 Matcher<const ArgumentTuple&> extra_matcher_;
963 std::vector<Action<F> > actions_;
964 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
965 Action<F> repeated_action_;
966 bool retires_on_saturation_;
967 Clause last_clause_;
968 mutable bool action_count_checked_; // Under mutex_.
969 mutable Mutex mutex_; // Protects action_count_checked_.
970 }; // class Expectation
971
972 // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
973 // specifying the default behavior of, or expectation on, a mock
974 // function.
975
976 // Note: class MockSpec really belongs to the ::testing namespace.
977 // However if we define it in ::testing, MSVC will complain when
978 // classes in ::testing::internal declare it as a friend class
979 // template. To workaround this compiler bug, we define MockSpec in
980 // ::testing::internal and import it into ::testing.
981
982 template <typename F>
983 class MockSpec {
984 public:
985 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
986 typedef typename internal::Function<F>::ArgumentMatcherTuple
987 ArgumentMatcherTuple;
988
989 // Constructs a MockSpec object, given the function mocker object
990 // that the spec is associated with.
991 explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker)
992 : function_mocker_(function_mocker) {}
993
994 // Adds a new default action spec to the function mocker and returns
995 // the newly created spec.
996 internal::DefaultActionSpec<F>& InternalDefaultActionSetAt(
997 const char* file, int line, const char* obj, const char* call) {
998 LogWithLocation(internal::INFO, file, line,
999 string("ON_CALL(") + obj + ", " + call + ") invoked");
1000 return function_mocker_->AddNewDefaultActionSpec(file, line, matchers_);
1001 }
1002
1003 // Adds a new expectation spec to the function mocker and returns
1004 // the newly created spec.
1005 internal::Expectation<F>& InternalExpectedAt(
1006 const char* file, int line, const char* obj, const char* call) {
1007 LogWithLocation(internal::INFO, file, line,
1008 string("EXPECT_CALL(") + obj + ", " + call + ") invoked");
1009 return function_mocker_->AddNewExpectation(file, line, matchers_);
1010 }
1011
1012 private:
1013 template <typename Function>
1014 friend class internal::FunctionMocker;
1015
1016 void SetMatchers(const ArgumentMatcherTuple& matchers) {
1017 matchers_ = matchers;
1018 }
1019
1020 // Logs a message including file and line number information.
1021 void LogWithLocation(testing::internal::LogSeverity severity,
1022 const char* file, int line,
1023 const string& message) {
1024 ::std::ostringstream s;
1025 s << file << ":" << line << ": " << message << ::std::endl;
1026 Log(severity, s.str(), 0);
1027 }
1028
1029 // The function mocker that owns this spec.
1030 internal::FunctionMockerBase<F>* const function_mocker_;
1031 // The argument matchers specified in the spec.
1032 ArgumentMatcherTuple matchers_;
1033 }; // class MockSpec
1034
1035 // MSVC warns about using 'this' in base member initializer list, so
1036 // we need to temporarily disable the warning. We have to do it for
1037 // the entire class to suppress the warning, even though it's about
1038 // the constructor only.
1039
1040 #ifdef _MSC_VER
1041 #pragma warning(push) // Saves the current warning state.
1042 #pragma warning(disable:4355) // Temporarily disables warning 4355.
1043 #endif // _MSV_VER
1044
1045 // The base of the function mocker class for the given function type.
1046 // We put the methods in this class instead of its child to avoid code
1047 // bloat.
1048 template <typename F>
1049 class FunctionMockerBase : public UntypedFunctionMockerBase {
1050 public:
1051 typedef typename Function<F>::Result Result;
1052 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1053 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1054
1055 FunctionMockerBase() : mock_obj_(NULL), name_(""), current_spec_(this) {}
1056
1057 // The destructor verifies that all expectations on this mock
1058 // function have been satisfied. If not, it will report Google Test
1059 // non-fatal failures for the violations.
1060 // L < g_gmock_mutex
1061 virtual ~FunctionMockerBase() {
1062 MutexLock l(&g_gmock_mutex);
1063 VerifyAndClearExpectationsLocked();
1064 Mock::UnregisterLocked(this);
1065 }
1066
1067 // Returns the ON_CALL spec that matches this mock function with the
1068 // given arguments; returns NULL if no matching ON_CALL is found.
1069 // L = *
1070 const DefaultActionSpec<F>* FindDefaultActionSpec(
1071 const ArgumentTuple& args) const {
1072 for (typename std::vector<DefaultActionSpec<F> >::const_reverse_iterator it
1073 = default_actions_.rbegin();
1074 it != default_actions_.rend(); ++it) {
1075 const DefaultActionSpec<F>& spec = *it;
1076 if (spec.Matches(args))
1077 return &spec;
1078 }
1079
1080 return NULL;
1081 }
1082
1083 // Performs the default action of this mock function on the given arguments
1084 // and returns the result. Asserts with a helpful call descrption if there is
1085 // no valid return value. This method doesn't depend on the mutable state of
1086 // this object, and thus can be called concurrently without locking.
1087 // L = *
1088 Result PerformDefaultAction(const ArgumentTuple& args,
1089 const string& call_description) const {
1090 const DefaultActionSpec<F>* const spec = FindDefaultActionSpec(args);
1091 if (spec != NULL) {
1092 return spec->GetAction().Perform(args);
1093 }
1094 Assert(DefaultValue<Result>::Exists(), "", -1,
1095 call_description + "\n The mock function has no default action "
1096 "set, and its return type has no default value set.");
1097 return DefaultValue<Result>::Get();
1098 }
1099
1100 // Registers this function mocker and the mock object owning it;
1101 // returns a reference to the function mocker object. This is only
1102 // called by the ON_CALL() and EXPECT_CALL() macros.
1103 // L < g_gmock_mutex
1104 FunctionMocker<F>& RegisterOwner(const void* mock_obj) {
1105 {
1106 MutexLock l(&g_gmock_mutex);
1107 mock_obj_ = mock_obj;
1108 }
1109 Mock::Register(mock_obj, this);
1110 return *::testing::internal::down_cast<FunctionMocker<F>*>(this);
1111 }
1112
1113 // The following two functions are from UntypedFunctionMockerBase.
1114
1115 // Verifies that all expectations on this mock function have been
1116 // satisfied. Reports one or more Google Test non-fatal failures
1117 // and returns false if not.
1118 // L >= g_gmock_mutex
1119 virtual bool VerifyAndClearExpectationsLocked();
1120
1121 // Clears the ON_CALL()s set on this mock function.
1122 // L >= g_gmock_mutex
1123 virtual void ClearDefaultActionsLocked() {
1124 g_gmock_mutex.AssertHeld();
1125 default_actions_.clear();
1126 }
1127
1128 // Sets the name of the function being mocked. Will be called upon
1129 // each invocation of this mock function.
1130 // L < g_gmock_mutex
1131 void SetOwnerAndName(const void* mock_obj, const char* name) {
1132 // We protect name_ under g_gmock_mutex in case this mock function
1133 // is called from two threads concurrently.
1134 MutexLock l(&g_gmock_mutex);
1135 mock_obj_ = mock_obj;
1136 name_ = name;
1137 }
1138
1139 // Returns the address of the mock object this method belongs to.
1140 // Must be called after SetOwnerAndName() has been called.
1141 // L < g_gmock_mutex
1142 const void* MockObject() const {
1143 const void* mock_obj;
1144 {
1145 // We protect mock_obj_ under g_gmock_mutex in case this mock
1146 // function is called from two threads concurrently.
1147 MutexLock l(&g_gmock_mutex);
1148 mock_obj = mock_obj_;
1149 }
1150 return mock_obj;
1151 }
1152
1153 // Returns the name of the function being mocked. Must be called
1154 // after SetOwnerAndName() has been called.
1155 // L < g_gmock_mutex
1156 const char* Name() const {
1157 const char* name;
1158 {
1159 // We protect name_ under g_gmock_mutex in case this mock
1160 // function is called from two threads concurrently.
1161 MutexLock l(&g_gmock_mutex);
1162 name = name_;
1163 }
1164 return name;
1165 }
1166 protected:
1167 template <typename Function>
1168 friend class MockSpec;
1169
1170 template <typename R, typename Function>
1171 friend class InvokeWithHelper;
1172
1173 // Returns the result of invoking this mock function with the given
1174 // arguments. This function can be safely called from multiple
1175 // threads concurrently.
1176 // L < g_gmock_mutex
1177 Result InvokeWith(const ArgumentTuple& args) {
1178 return InvokeWithHelper<Result, F>::InvokeAndPrintResult(this, args);
1179 }
1180
1181 // Adds and returns a default action spec for this mock function.
1182 // L < g_gmock_mutex
1183 DefaultActionSpec<F>& AddNewDefaultActionSpec(
1184 const char* file, int line,
1185 const ArgumentMatcherTuple& m) {
1186 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1187 default_actions_.push_back(DefaultActionSpec<F>(file, line, m));
1188 return default_actions_.back();
1189 }
1190
1191 // Adds and returns an expectation spec for this mock function.
1192 // L < g_gmock_mutex
1193 Expectation<F>& AddNewExpectation(
1194 const char* file, int line,
1195 const ArgumentMatcherTuple& m) {
1196 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1197 const linked_ptr<Expectation<F> > expectation(
1198 new Expectation<F>(this, file, line, m));
1199 expectations_.push_back(expectation);
1200
1201 // Adds this expectation into the implicit sequence if there is one.
1202 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1203 if (implicit_sequence != NULL) {
1204 implicit_sequence->AddExpectation(expectation);
1205 }
1206
1207 return *expectation;
1208 }
1209
1210 // The current spec (either default action spec or expectation spec)
1211 // being described on this function mocker.
1212 MockSpec<F>& current_spec() { return current_spec_; }
1213 private:
1214 template <typename Func> friend class Expectation;
1215
1216 typedef std::vector<internal::linked_ptr<Expectation<F> > > Expectations;
1217
1218 // Gets the internal::linked_ptr<ExpectationBase> object that co-owns 'exp'.
1219 internal::linked_ptr<ExpectationBase> GetLinkedExpectationBase(
1220 Expectation<F>* exp) {
1221 for (typename Expectations::const_iterator it = expectations_.begin();
1222 it != expectations_.end(); ++it) {
1223 if (it->get() == exp) {
1224 return *it;
1225 }
1226 }
1227
1228 Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
1229 return internal::linked_ptr<ExpectationBase>(NULL);
1230 // The above statement is just to make the code compile, and will
1231 // never be executed.
1232 }
1233
1234 // Some utilities needed for implementing InvokeWith().
1235
1236 // Describes what default action will be performed for the given
1237 // arguments.
1238 // L = *
1239 void DescribeDefaultActionTo(const ArgumentTuple& args,
1240 ::std::ostream* os) const {
1241 const DefaultActionSpec<F>* const spec = FindDefaultActionSpec(args);
1242
1243 if (spec == NULL) {
1244 *os << (internal::type_equals<Result, void>::value ?
1245 "returning directly.\n" :
1246 "returning default value.\n");
1247 } else {
1248 *os << "taking default action specified at:\n"
1249 << spec->file() << ":" << spec->line() << ":\n";
1250 }
1251 }
1252
1253 // Writes a message that the call is uninteresting (i.e. neither
1254 // explicitly expected nor explicitly unexpected) to the given
1255 // ostream.
1256 // L < g_gmock_mutex
1257 void DescribeUninterestingCall(const ArgumentTuple& args,
1258 ::std::ostream* os) const {
1259 *os << "Uninteresting mock function call - ";
1260 DescribeDefaultActionTo(args, os);
1261 *os << " Function call: " << Name();
1262 UniversalPrinter<ArgumentTuple>::Print(args, os);
1263 }
1264
1265 // Critical section: We must find the matching expectation and the
1266 // corresponding action that needs to be taken in an ATOMIC
1267 // transaction. Otherwise another thread may call this mock
1268 // method in the middle and mess up the state.
1269 //
1270 // However, performing the action has to be left out of the critical
1271 // section. The reason is that we have no control on what the
1272 // action does (it can invoke an arbitrary user function or even a
1273 // mock function) and excessive locking could cause a dead lock.
1274 // L < g_gmock_mutex
1275 bool FindMatchingExpectationAndAction(
1276 const ArgumentTuple& args, Expectation<F>** exp, Action<F>* action,
1277 bool* is_excessive, ::std::ostream* what, ::std::ostream* why) {
1278 MutexLock l(&g_gmock_mutex);
1279 *exp = this->FindMatchingExpectationLocked(args);
1280 if (*exp == NULL) { // A match wasn't found.
1281 *action = DoDefault();
1282 this->FormatUnexpectedCallMessageLocked(args, what, why);
1283 return false;
1284 }
1285
1286 // This line must be done before calling GetActionForArguments(),
1287 // which will increment the call count for *exp and thus affect
1288 // its saturation status.
1289 *is_excessive = (*exp)->IsSaturated();
1290 *action = (*exp)->GetActionForArguments(this, args, what, why);
1291 return true;
1292 }
1293
1294 // Returns the expectation that matches the arguments, or NULL if no
1295 // expectation matches them.
1296 // L >= g_gmock_mutex
1297 Expectation<F>* FindMatchingExpectationLocked(
1298 const ArgumentTuple& args) const {
1299 g_gmock_mutex.AssertHeld();
1300 for (typename Expectations::const_reverse_iterator it =
1301 expectations_.rbegin();
1302 it != expectations_.rend(); ++it) {
1303 Expectation<F>* const exp = it->get();
1304 if (exp->ShouldHandleArguments(args)) {
1305 return exp;
1306 }
1307 }
1308 return NULL;
1309 }
1310
1311 // Returns a message that the arguments don't match any expectation.
1312 // L >= g_gmock_mutex
1313 void FormatUnexpectedCallMessageLocked(const ArgumentTuple& args,
1314 ::std::ostream* os,
1315 ::std::ostream* why) const {
1316 g_gmock_mutex.AssertHeld();
1317 *os << "\nUnexpected mock function call - ";
1318 DescribeDefaultActionTo(args, os);
1319 PrintTriedExpectationsLocked(args, why);
1320 }
1321
1322 // Prints a list of expectations that have been tried against the
1323 // current mock function call.
1324 // L >= g_gmock_mutex
1325 void PrintTriedExpectationsLocked(const ArgumentTuple& args,
1326 ::std::ostream* why) const {
1327 g_gmock_mutex.AssertHeld();
1328 const int count = static_cast<int>(expectations_.size());
1329 *why << "Google Mock tried the following " << count << " "
1330 << (count == 1 ? "expectation, but it didn't match" :
1331 "expectations, but none matched")
1332 << ":\n";
1333 for (int i = 0; i < count; i++) {
1334 *why << "\n";
1335 expectations_[i]->DescribeLocationTo(why);
1336 if (count > 1) {
1337 *why << "tried expectation #" << i;
1338 }
1339 *why << "\n";
1340 expectations_[i]->DescribeMatchResultTo(args, why);
1341 expectations_[i]->DescribeCallCountTo(why);
1342 }
1343 }
1344
1345 // Address of the mock object this mock method belongs to. Only
1346 // valid after this mock method has been called or
1347 // ON_CALL/EXPECT_CALL has been invoked on it.
1348 const void* mock_obj_; // Protected by g_gmock_mutex.
1349
1350 // Name of the function being mocked. Only valid after this mock
1351 // method has been called.
1352 const char* name_; // Protected by g_gmock_mutex.
1353
1354 // The current spec (either default action spec or expectation spec)
1355 // being described on this function mocker.
1356 MockSpec<F> current_spec_;
1357
1358 // All default action specs for this function mocker.
1359 std::vector<DefaultActionSpec<F> > default_actions_;
1360 // All expectations for this function mocker.
1361 Expectations expectations_;
1362
1363 // There is no generally useful and implementable semantics of
1364 // copying a mock object, so copying a mock is usually a user error.
1365 // Thus we disallow copying function mockers. If the user really
1366 // wants to copy a mock object, he should implement his own copy
1367 // operation, for example:
1368 //
1369 // class MockFoo : public Foo {
1370 // public:
1371 // // Defines a copy constructor explicitly.
1372 // MockFoo(const MockFoo& src) {}
1373 // ...
1374 // };
1375 GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
1376 }; // class FunctionMockerBase
1377
1378 #ifdef _MSC_VER
1379 #pragma warning(pop) // Restores the warning state.
1380 #endif // _MSV_VER
1381
1382 // Implements methods of FunctionMockerBase.
1383
1384 // Verifies that all expectations on this mock function have been
1385 // satisfied. Reports one or more Google Test non-fatal failures and
1386 // returns false if not.
1387 // L >= g_gmock_mutex
1388 template <typename F>
1389 bool FunctionMockerBase<F>::VerifyAndClearExpectationsLocked() {
1390 g_gmock_mutex.AssertHeld();
1391 bool expectations_met = true;
1392 for (typename Expectations::const_iterator it = expectations_.begin();
1393 it != expectations_.end(); ++it) {
1394 Expectation<F>* const exp = it->get();
1395
1396 if (exp->IsOverSaturated()) {
1397 // There was an upper-bound violation. Since the error was
1398 // already reported when it occurred, there is no need to do
1399 // anything here.
1400 expectations_met = false;
1401 } else if (!exp->IsSatisfied()) {
1402 expectations_met = false;
1403 ::std::stringstream ss;
1404 ss << "Actual function call count doesn't match this expectation.\n";
1405 // No need to show the source file location of the expectation
1406 // in the description, as the Expect() call that follows already
1407 // takes care of it.
1408 exp->DescribeCallCountTo(&ss);
1409 Expect(false, exp->file(), exp->line(), ss.str());
1410 }
1411 }
1412 expectations_.clear();
1413 return expectations_met;
1414 }
1415
1416 // Reports an uninteresting call (whose description is in msg) in the
1417 // manner specified by 'reaction'.
1418 void ReportUninterestingCall(CallReaction reaction, const string& msg);
1419
1420 // When an uninteresting or unexpected mock function is called, we
1421 // want to print its return value to assist the user debugging. Since
1422 // there's nothing to print when the function returns void, we need to
1423 // specialize the logic of FunctionMockerBase<F>::InvokeWith() for
1424 // void return values.
1425 //
1426 // C++ doesn't allow us to specialize a member function template
1427 // unless we also specialize its enclosing class, so we had to let
1428 // InvokeWith() delegate its work to a helper class InvokeWithHelper,
1429 // which can then be specialized.
1430 //
1431 // Note that InvokeWithHelper must be a class template (as opposed to
1432 // a function template), as only class templates can be partially
1433 // specialized.
1434 template <typename Result, typename F>
1435 class InvokeWithHelper {
1436 public:
1437 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1438
1439 // Calculates the result of invoking the function mocked by mocker
1440 // with the given arguments, prints it, and returns it.
1441 // L < g_gmock_mutex
1442 static Result InvokeAndPrintResult(
1443 FunctionMockerBase<F>* mocker,
1444 const ArgumentTuple& args) {
1445 if (mocker->expectations_.size() == 0) {
1446 // No expectation is set on this mock method - we have an
1447 // uninteresting call.
1448
1449 // Warns about the uninteresting call.
1450 ::std::stringstream ss;
1451 mocker->DescribeUninterestingCall(args, &ss);
1452
1453 // We must get Google Mock's reaction on uninteresting calls
1454 // made on this mock object BEFORE performing the action,
1455 // because the action may DELETE the mock object and make the
1456 // following expression meaningless.
1457 const CallReaction reaction =
1458 Mock::GetReactionOnUninterestingCalls(mocker->MockObject());
1459
1460 // Calculates the function result.
1461 Result result = mocker->PerformDefaultAction(args, ss.str());
1462
1463 // Prints the function result.
1464 ss << "\n Returns: ";
1465 UniversalPrinter<Result>::Print(result, &ss);
1466 ReportUninterestingCall(reaction, ss.str());
1467
1468 return result;
1469 }
1470
1471 bool is_excessive = false;
1472 ::std::stringstream ss;
1473 ::std::stringstream why;
1474 ::std::stringstream loc;
1475 Action<F> action;
1476 Expectation<F>* exp;
1477
1478 // The FindMatchingExpectationAndAction() function acquires and
1479 // releases g_gmock_mutex.
1480 const bool found = mocker->FindMatchingExpectationAndAction(
1481 args, &exp, &action, &is_excessive, &ss, &why);
1482 ss << " Function call: " << mocker->Name();
1483 UniversalPrinter<ArgumentTuple>::Print(args, &ss);
1484 // In case the action deletes a piece of the expectation, we
1485 // generate the message beforehand.
1486 if (found && !is_excessive) {
1487 exp->DescribeLocationTo(&loc);
1488 }
1489 Result result = action.IsDoDefault() ?
1490 mocker->PerformDefaultAction(args, ss.str())
1491 : action.Perform(args);
1492 ss << "\n Returns: ";
1493 UniversalPrinter<Result>::Print(result, &ss);
1494 ss << "\n" << why.str();
1495
1496 if (found) {
1497 if (is_excessive) {
1498 // We had an upper-bound violation and the failure message is in ss.
1499 Expect(false, exp->file(), exp->line(), ss.str());
1500 } else {
1501 // We had an expected call and the matching expectation is
1502 // described in ss.
1503 Log(INFO, loc.str() + ss.str(), 3);
1504 }
1505 } else {
1506 // No expectation matches this call - reports a failure.
1507 Expect(false, NULL, -1, ss.str());
1508 }
1509 return result;
1510 }
1511 }; // class InvokeWithHelper
1512
1513 // This specialization helps to implement
1514 // FunctionMockerBase<F>::InvokeWith() for void-returning functions.
1515 template <typename F>
1516 class InvokeWithHelper<void, F> {
1517 public:
1518 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1519
1520 // Invokes the function mocked by mocker with the given arguments.
1521 // L < g_gmock_mutex
1522 static void InvokeAndPrintResult(FunctionMockerBase<F>* mocker,
1523 const ArgumentTuple& args) {
1524 const int count = static_cast<int>(mocker->expectations_.size());
1525 if (count == 0) {
1526 // No expectation is set on this mock method - we have an
1527 // uninteresting call.
1528 ::std::stringstream ss;
1529 mocker->DescribeUninterestingCall(args, &ss);
1530
1531 // We must get Google Mock's reaction on uninteresting calls
1532 // made on this mock object BEFORE performing the action,
1533 // because the action may DELETE the mock object and make the
1534 // following expression meaningless.
1535 const CallReaction reaction =
1536 Mock::GetReactionOnUninterestingCalls(mocker->MockObject());
1537
1538 mocker->PerformDefaultAction(args, ss.str());
1539 ReportUninterestingCall(reaction, ss.str());
1540 return;
1541 }
1542
1543 bool is_excessive = false;
1544 ::std::stringstream ss;
1545 ::std::stringstream why;
1546 ::std::stringstream loc;
1547 Action<F> action;
1548 Expectation<F>* exp;
1549
1550 // The FindMatchingExpectationAndAction() function acquires and
1551 // releases g_gmock_mutex.
1552 const bool found = mocker->FindMatchingExpectationAndAction(
1553 args, &exp, &action, &is_excessive, &ss, &why);
1554 ss << " Function call: " << mocker->Name();
1555 UniversalPrinter<ArgumentTuple>::Print(args, &ss);
1556 ss << "\n" << why.str();
1557 // In case the action deletes a piece of the expectation, we
1558 // generate the message beforehand.
1559 if (found && !is_excessive) {
1560 exp->DescribeLocationTo(&loc);
1561 }
1562 if (action.IsDoDefault()) {
1563 mocker->PerformDefaultAction(args, ss.str());
1564 } else {
1565 action.Perform(args);
1566 }
1567
1568 if (found) {
1569 // A matching expectation and corresponding action were found.
1570 if (is_excessive) {
1571 // We had an upper-bound violation and the failure message is in ss.
1572 Expect(false, exp->file(), exp->line(), ss.str());
1573 } else {
1574 // We had an expected call and the matching expectation is
1575 // described in ss.
1576 Log(INFO, loc.str() + ss.str(), 3);
1577 }
1578 } else {
1579 // No matching expectation was found - reports an error.
1580 Expect(false, NULL, -1, ss.str());
1581 }
1582 }
1583 }; // class InvokeWithHelper<void, F>
1584
1585 } // namespace internal
1586
1587 // The style guide prohibits "using" statements in a namespace scope
1588 // inside a header file. However, the MockSpec class template is
1589 // meant to be defined in the ::testing namespace. The following line
1590 // is just a trick for working around a bug in MSVC 8.0, which cannot
1591 // handle it if we define MockSpec in ::testing.
1592 using internal::MockSpec;
1593
1594 // Const(x) is a convenient function for obtaining a const reference
1595 // to x. This is useful for setting expectations on an overloaded
1596 // const mock method, e.g.
1597 //
1598 // class MockFoo : public FooInterface {
1599 // public:
1600 // MOCK_METHOD0(Bar, int());
1601 // MOCK_CONST_METHOD0(Bar, int&());
1602 // };
1603 //
1604 // MockFoo foo;
1605 // // Expects a call to non-const MockFoo::Bar().
1606 // EXPECT_CALL(foo, Bar());
1607 // // Expects a call to const MockFoo::Bar().
1608 // EXPECT_CALL(Const(foo), Bar());
1609 template <typename T>
1610 inline const T& Const(const T& x) { return x; }
1611
1612 } // namespace testing
1613
1614 // A separate macro is required to avoid compile errors when the name
1615 // of the method used in call is a result of macro expansion.
1616 // See CompilesWithMethodNameExpandedFromMacro tests in
1617 // internal/gmock-spec-builders_test.cc for more details.
1618 #define GMOCK_ON_CALL_IMPL_(obj, call) \
1619 ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \
1620 #obj, #call)
1621 #define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call)
1622
1623 #define GMOCK_EXPECT_CALL_IMPL_(obj, call) \
1624 ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
1625 #define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call)
1626
1627 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
OLDNEW
« no previous file with comments | « testing/gmock/include/gmock/gmock-printers.h ('k') | testing/gmock/include/gmock/internal/gmock-generated-internal-utils.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698