]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/googletest/googlemock/test/gmock-spec-builders_test.cc
MFC r345203,r345205,r345353,r345645,r345708,r345709,r345735,r345770,r346081,r346270...
[FreeBSD/FreeBSD.git] / contrib / googletest / googlemock / test / gmock-spec-builders_test.cc
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
31 // Google Mock - a framework for writing C++ mock classes.
32 //
33 // This file tests the spec builder syntax.
34
35 #include "gmock/gmock-spec-builders.h"
36
37 #include <ostream>  // NOLINT
38 #include <sstream>
39 #include <string>
40
41 #include "gmock/gmock.h"
42 #include "gmock/internal/gmock-port.h"
43 #include "gtest/gtest.h"
44 #include "gtest/gtest-spi.h"
45 #include "gtest/internal/gtest-port.h"
46
47 namespace testing {
48 namespace internal {
49
50 // Helper class for testing the Expectation class template.
51 class ExpectationTester {
52  public:
53   // Sets the call count of the given expectation to the given number.
54   void SetCallCount(int n, ExpectationBase* exp) {
55     exp->call_count_ = n;
56   }
57 };
58
59 }  // namespace internal
60 }  // namespace testing
61
62 namespace {
63
64 using testing::_;
65 using testing::AnyNumber;
66 using testing::AtLeast;
67 using testing::AtMost;
68 using testing::Between;
69 using testing::Cardinality;
70 using testing::CardinalityInterface;
71 using testing::ContainsRegex;
72 using testing::Const;
73 using testing::DoAll;
74 using testing::DoDefault;
75 using testing::Eq;
76 using testing::Expectation;
77 using testing::ExpectationSet;
78 using testing::GMOCK_FLAG(verbose);
79 using testing::Gt;
80 using testing::InSequence;
81 using testing::Invoke;
82 using testing::InvokeWithoutArgs;
83 using testing::IsNotSubstring;
84 using testing::IsSubstring;
85 using testing::Lt;
86 using testing::Message;
87 using testing::Mock;
88 using testing::NaggyMock;
89 using testing::Ne;
90 using testing::Return;
91 using testing::SaveArg;
92 using testing::Sequence;
93 using testing::SetArgPointee;
94 using testing::internal::ExpectationTester;
95 using testing::internal::FormatFileLocation;
96 using testing::internal::kAllow;
97 using testing::internal::kErrorVerbosity;
98 using testing::internal::kFail;
99 using testing::internal::kInfoVerbosity;
100 using testing::internal::kWarn;
101 using testing::internal::kWarningVerbosity;
102 using testing::internal::linked_ptr;
103
104 #if GTEST_HAS_STREAM_REDIRECTION
105 using testing::HasSubstr;
106 using testing::internal::CaptureStdout;
107 using testing::internal::GetCapturedStdout;
108 #endif
109
110 class Incomplete;
111
112 class MockIncomplete {
113  public:
114   // This line verifies that a mock method can take a by-reference
115   // argument of an incomplete type.
116   MOCK_METHOD1(ByRefFunc, void(const Incomplete& x));
117 };
118
119 // Tells Google Mock how to print a value of type Incomplete.
120 void PrintTo(const Incomplete& x, ::std::ostream* os);
121
122 TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) {
123   // Even though this mock class contains a mock method that takes
124   // by-reference an argument whose type is incomplete, we can still
125   // use the mock, as long as Google Mock knows how to print the
126   // argument.
127   MockIncomplete incomplete;
128   EXPECT_CALL(incomplete, ByRefFunc(_))
129       .Times(AnyNumber());
130 }
131
132 // The definition of the printer for the argument type doesn't have to
133 // be visible where the mock is used.
134 void PrintTo(const Incomplete& /* x */, ::std::ostream* os) {
135   *os << "incomplete";
136 }
137
138 class Result {};
139
140 // A type that's not default constructible.
141 class NonDefaultConstructible {
142  public:
143   explicit NonDefaultConstructible(int /* dummy */) {}
144 };
145
146 class MockA {
147  public:
148   MockA() {}
149
150   MOCK_METHOD1(DoA, void(int n));
151   MOCK_METHOD1(ReturnResult, Result(int n));
152   MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible());
153   MOCK_METHOD2(Binary, bool(int x, int y));
154   MOCK_METHOD2(ReturnInt, int(int x, int y));
155
156  private:
157   GTEST_DISALLOW_COPY_AND_ASSIGN_(MockA);
158 };
159
160 class MockB {
161  public:
162   MockB() {}
163
164   MOCK_CONST_METHOD0(DoB, int());  // NOLINT
165   MOCK_METHOD1(DoB, int(int n));  // NOLINT
166
167  private:
168   GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
169 };
170
171 class ReferenceHoldingMock {
172  public:
173   ReferenceHoldingMock() {}
174
175   MOCK_METHOD1(AcceptReference, void(linked_ptr<MockA>*));
176
177  private:
178   GTEST_DISALLOW_COPY_AND_ASSIGN_(ReferenceHoldingMock);
179 };
180
181 // Tests that EXPECT_CALL and ON_CALL compile in a presence of macro
182 // redefining a mock method name. This could happen, for example, when
183 // the tested code #includes Win32 API headers which define many APIs
184 // as macros, e.g. #define TextOut TextOutW.
185
186 #define Method MethodW
187
188 class CC {
189  public:
190   virtual ~CC() {}
191   virtual int Method() = 0;
192 };
193 class MockCC : public CC {
194  public:
195   MockCC() {}
196
197   MOCK_METHOD0(Method, int());
198
199  private:
200   GTEST_DISALLOW_COPY_AND_ASSIGN_(MockCC);
201 };
202
203 // Tests that a method with expanded name compiles.
204 TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
205   MockCC cc;
206   ON_CALL(cc, Method());
207 }
208
209 // Tests that the method with expanded name not only compiles but runs
210 // and returns a correct value, too.
211 TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
212   MockCC cc;
213   ON_CALL(cc, Method()).WillByDefault(Return(42));
214   EXPECT_EQ(42, cc.Method());
215 }
216
217 // Tests that a method with expanded name compiles.
218 TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
219   MockCC cc;
220   EXPECT_CALL(cc, Method());
221   cc.Method();
222 }
223
224 // Tests that it works, too.
225 TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
226   MockCC cc;
227   EXPECT_CALL(cc, Method()).WillOnce(Return(42));
228   EXPECT_EQ(42, cc.Method());
229 }
230
231 #undef Method  // Done with macro redefinition tests.
232
233 // Tests that ON_CALL evaluates its arguments exactly once as promised
234 // by Google Mock.
235 TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
236   MockA a;
237   MockA* pa = &a;
238
239   ON_CALL(*pa++, DoA(_));
240   EXPECT_EQ(&a + 1, pa);
241 }
242
243 TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
244   MockA a;
245   int n = 0;
246
247   ON_CALL(a, DoA(n++));
248   EXPECT_EQ(1, n);
249 }
250
251 // Tests that the syntax of ON_CALL() is enforced at run time.
252
253 TEST(OnCallSyntaxTest, WithIsOptional) {
254   MockA a;
255
256   ON_CALL(a, DoA(5))
257       .WillByDefault(Return());
258   ON_CALL(a, DoA(_))
259       .With(_)
260       .WillByDefault(Return());
261 }
262
263 TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) {
264   MockA a;
265
266   EXPECT_NONFATAL_FAILURE({  // NOLINT
267     ON_CALL(a, ReturnResult(_))
268         .With(_)
269         .With(_)
270         .WillByDefault(Return(Result()));
271   }, ".With() cannot appear more than once in an ON_CALL()");
272 }
273
274 TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
275   MockA a;
276
277   EXPECT_DEATH_IF_SUPPORTED({
278     ON_CALL(a, DoA(5));
279     a.DoA(5);
280   }, "");
281 }
282
283 TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {
284   MockA a;
285
286   EXPECT_NONFATAL_FAILURE({  // NOLINT
287     ON_CALL(a, DoA(5))
288         .WillByDefault(Return())
289         .WillByDefault(Return());
290   }, ".WillByDefault() must appear exactly once in an ON_CALL()");
291 }
292
293 // Tests that EXPECT_CALL evaluates its arguments exactly once as
294 // promised by Google Mock.
295 TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) {
296   MockA a;
297   MockA* pa = &a;
298
299   EXPECT_CALL(*pa++, DoA(_));
300   a.DoA(0);
301   EXPECT_EQ(&a + 1, pa);
302 }
303
304 TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) {
305   MockA a;
306   int n = 0;
307
308   EXPECT_CALL(a, DoA(n++));
309   a.DoA(0);
310   EXPECT_EQ(1, n);
311 }
312
313 // Tests that the syntax of EXPECT_CALL() is enforced at run time.
314
315 TEST(ExpectCallSyntaxTest, WithIsOptional) {
316   MockA a;
317
318   EXPECT_CALL(a, DoA(5))
319       .Times(0);
320   EXPECT_CALL(a, DoA(6))
321       .With(_)
322       .Times(0);
323 }
324
325 TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {
326   MockA a;
327
328   EXPECT_NONFATAL_FAILURE({  // NOLINT
329     EXPECT_CALL(a, DoA(6))
330         .With(_)
331         .With(_);
332   }, ".With() cannot appear more than once in an EXPECT_CALL()");
333
334   a.DoA(6);
335 }
336
337 TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {
338   MockA a;
339
340   EXPECT_NONFATAL_FAILURE({  // NOLINT
341     EXPECT_CALL(a, DoA(1))
342         .Times(1)
343         .With(_);
344   }, ".With() must be the first clause in an EXPECT_CALL()");
345
346   a.DoA(1);
347
348   EXPECT_NONFATAL_FAILURE({  // NOLINT
349     EXPECT_CALL(a, DoA(2))
350         .WillOnce(Return())
351         .With(_);
352   }, ".With() must be the first clause in an EXPECT_CALL()");
353
354   a.DoA(2);
355 }
356
357 TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {
358   MockA a;
359
360   EXPECT_CALL(a, DoA(1))
361       .WillOnce(Return());
362
363   EXPECT_CALL(a, DoA(2))
364       .WillOnce(Return())
365       .WillRepeatedly(Return());
366
367   a.DoA(1);
368   a.DoA(2);
369   a.DoA(2);
370 }
371
372 TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {
373   MockA a;
374
375   EXPECT_NONFATAL_FAILURE({  // NOLINT
376     EXPECT_CALL(a, DoA(1))
377         .Times(1)
378         .Times(2);
379   }, ".Times() cannot appear more than once in an EXPECT_CALL()");
380
381   a.DoA(1);
382   a.DoA(1);
383 }
384
385 TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {
386   MockA a;
387   Sequence s;
388
389   EXPECT_NONFATAL_FAILURE({  // NOLINT
390     EXPECT_CALL(a, DoA(1))
391         .InSequence(s)
392         .Times(1);
393   }, ".Times() cannot appear after ");
394
395   a.DoA(1);
396 }
397
398 TEST(ExpectCallSyntaxTest, InSequenceIsOptional) {
399   MockA a;
400   Sequence s;
401
402   EXPECT_CALL(a, DoA(1));
403   EXPECT_CALL(a, DoA(2))
404       .InSequence(s);
405
406   a.DoA(1);
407   a.DoA(2);
408 }
409
410 TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {
411   MockA a;
412   Sequence s1, s2;
413
414   EXPECT_CALL(a, DoA(1))
415       .InSequence(s1, s2)
416       .InSequence(s1);
417
418   a.DoA(1);
419 }
420
421 TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) {
422   MockA a;
423   Sequence s;
424
425   Expectation e = EXPECT_CALL(a, DoA(1))
426       .Times(AnyNumber());
427   EXPECT_NONFATAL_FAILURE({  // NOLINT
428     EXPECT_CALL(a, DoA(2))
429         .After(e)
430         .InSequence(s);
431   }, ".InSequence() cannot appear after ");
432
433   a.DoA(2);
434 }
435
436 TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) {
437   MockA a;
438   Sequence s;
439
440   EXPECT_NONFATAL_FAILURE({  // NOLINT
441     EXPECT_CALL(a, DoA(1))
442         .WillOnce(Return())
443         .InSequence(s);
444   }, ".InSequence() cannot appear after ");
445
446   a.DoA(1);
447 }
448
449 TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) {
450   MockA a;
451
452   Expectation e = EXPECT_CALL(a, DoA(1));
453   EXPECT_NONFATAL_FAILURE({
454     EXPECT_CALL(a, DoA(2))
455         .WillOnce(Return())
456         .After(e);
457   }, ".After() cannot appear after ");
458
459   a.DoA(1);
460   a.DoA(2);
461 }
462
463 TEST(ExpectCallSyntaxTest, WillIsOptional) {
464   MockA a;
465
466   EXPECT_CALL(a, DoA(1));
467   EXPECT_CALL(a, DoA(2))
468       .WillOnce(Return());
469
470   a.DoA(1);
471   a.DoA(2);
472 }
473
474 TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {
475   MockA a;
476
477   EXPECT_CALL(a, DoA(1))
478       .Times(AnyNumber())
479       .WillOnce(Return())
480       .WillOnce(Return())
481       .WillOnce(Return());
482 }
483
484 TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {
485   MockA a;
486
487   EXPECT_NONFATAL_FAILURE({  // NOLINT
488     EXPECT_CALL(a, DoA(1))
489         .WillRepeatedly(Return())
490         .WillOnce(Return());
491   }, ".WillOnce() cannot appear after ");
492
493   a.DoA(1);
494 }
495
496 TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {
497   MockA a;
498
499   EXPECT_CALL(a, DoA(1))
500       .WillOnce(Return());
501   EXPECT_CALL(a, DoA(2))
502       .WillOnce(Return())
503       .WillRepeatedly(Return());
504
505   a.DoA(1);
506   a.DoA(2);
507   a.DoA(2);
508 }
509
510 TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {
511   MockA a;
512
513   EXPECT_NONFATAL_FAILURE({  // NOLINT
514     EXPECT_CALL(a, DoA(1))
515         .WillRepeatedly(Return())
516         .WillRepeatedly(Return());
517   }, ".WillRepeatedly() cannot appear more than once in an "
518      "EXPECT_CALL()");
519 }
520
521 TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {
522   MockA a;
523
524   EXPECT_NONFATAL_FAILURE({  // NOLINT
525     EXPECT_CALL(a, DoA(1))
526         .RetiresOnSaturation()
527         .WillRepeatedly(Return());
528   }, ".WillRepeatedly() cannot appear after ");
529 }
530
531 TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {
532   MockA a;
533
534   EXPECT_CALL(a, DoA(1));
535   EXPECT_CALL(a, DoA(1))
536       .RetiresOnSaturation();
537
538   a.DoA(1);
539   a.DoA(1);
540 }
541
542 TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {
543   MockA a;
544
545   EXPECT_NONFATAL_FAILURE({  // NOLINT
546     EXPECT_CALL(a, DoA(1))
547         .RetiresOnSaturation()
548         .RetiresOnSaturation();
549   }, ".RetiresOnSaturation() cannot appear more than once");
550
551   a.DoA(1);
552 }
553
554 TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {
555   {
556     MockA a;
557     EXPECT_CALL(a, DoA(1));
558     a.DoA(1);
559   }
560   EXPECT_NONFATAL_FAILURE({  // NOLINT
561     MockA a;
562     EXPECT_CALL(a, DoA(1));
563   }, "to be called once");
564   EXPECT_NONFATAL_FAILURE({  // NOLINT
565     MockA a;
566     EXPECT_CALL(a, DoA(1));
567     a.DoA(1);
568     a.DoA(1);
569   }, "to be called once");
570 }
571
572 #if GTEST_HAS_STREAM_REDIRECTION
573
574 // Tests that Google Mock doesn't print a warning when the number of
575 // WillOnce() is adequate.
576 TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {
577   CaptureStdout();
578   {
579     MockB b;
580
581     // It's always fine to omit WillOnce() entirely.
582     EXPECT_CALL(b, DoB())
583         .Times(0);
584     EXPECT_CALL(b, DoB(1))
585         .Times(AtMost(1));
586     EXPECT_CALL(b, DoB(2))
587         .Times(1)
588         .WillRepeatedly(Return(1));
589
590     // It's fine for the number of WillOnce()s to equal the upper bound.
591     EXPECT_CALL(b, DoB(3))
592         .Times(Between(1, 2))
593         .WillOnce(Return(1))
594         .WillOnce(Return(2));
595
596     // It's fine for the number of WillOnce()s to be smaller than the
597     // upper bound when there is a WillRepeatedly().
598     EXPECT_CALL(b, DoB(4))
599         .Times(AtMost(3))
600         .WillOnce(Return(1))
601         .WillRepeatedly(Return(2));
602
603     // Satisfies the above expectations.
604     b.DoB(2);
605     b.DoB(3);
606   }
607   EXPECT_STREQ("", GetCapturedStdout().c_str());
608 }
609
610 // Tests that Google Mock warns on having too many actions in an
611 // expectation compared to its cardinality.
612 TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
613   CaptureStdout();
614   {
615     MockB b;
616
617     // Warns when the number of WillOnce()s is larger than the upper bound.
618     EXPECT_CALL(b, DoB())
619         .Times(0)
620         .WillOnce(Return(1));  // #1
621     EXPECT_CALL(b, DoB())
622         .Times(AtMost(1))
623         .WillOnce(Return(1))
624         .WillOnce(Return(2));  // #2
625     EXPECT_CALL(b, DoB(1))
626         .Times(1)
627         .WillOnce(Return(1))
628         .WillOnce(Return(2))
629         .RetiresOnSaturation();  // #3
630
631     // Warns when the number of WillOnce()s equals the upper bound and
632     // there is a WillRepeatedly().
633     EXPECT_CALL(b, DoB())
634         .Times(0)
635         .WillRepeatedly(Return(1));  // #4
636     EXPECT_CALL(b, DoB(2))
637         .Times(1)
638         .WillOnce(Return(1))
639         .WillRepeatedly(Return(2));  // #5
640
641     // Satisfies the above expectations.
642     b.DoB(1);
643     b.DoB(2);
644   }
645   const std::string output = GetCapturedStdout();
646   EXPECT_PRED_FORMAT2(
647       IsSubstring,
648       "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
649       "Expected to be never called, but has 1 WillOnce().",
650       output);  // #1
651   EXPECT_PRED_FORMAT2(
652       IsSubstring,
653       "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
654       "Expected to be called at most once, "
655       "but has 2 WillOnce()s.",
656       output);  // #2
657   EXPECT_PRED_FORMAT2(
658       IsSubstring,
659       "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n"
660       "Expected to be called once, but has 2 WillOnce()s.",
661       output);  // #3
662   EXPECT_PRED_FORMAT2(
663       IsSubstring,
664       "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
665       "Expected to be never called, but has 0 WillOnce()s "
666       "and a WillRepeatedly().",
667       output);  // #4
668   EXPECT_PRED_FORMAT2(
669       IsSubstring,
670       "Too many actions specified in EXPECT_CALL(b, DoB(2))...\n"
671       "Expected to be called once, but has 1 WillOnce() "
672       "and a WillRepeatedly().",
673       output);  // #5
674 }
675
676 // Tests that Google Mock warns on having too few actions in an
677 // expectation compared to its cardinality.
678 TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
679   MockB b;
680
681   EXPECT_CALL(b, DoB())
682       .Times(Between(2, 3))
683       .WillOnce(Return(1));
684
685   CaptureStdout();
686   b.DoB();
687   const std::string output = GetCapturedStdout();
688   EXPECT_PRED_FORMAT2(
689       IsSubstring,
690       "Too few actions specified in EXPECT_CALL(b, DoB())...\n"
691       "Expected to be called between 2 and 3 times, "
692       "but has only 1 WillOnce().",
693       output);
694   b.DoB();
695 }
696
697 TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) {
698   int original_behavior = testing::GMOCK_FLAG(default_mock_behavior);
699
700   testing::GMOCK_FLAG(default_mock_behavior) = kAllow;
701   CaptureStdout();
702   {
703     MockA a;
704     a.DoA(0);
705   }
706   std::string output = GetCapturedStdout();
707   EXPECT_TRUE(output.empty()) << output;
708
709   testing::GMOCK_FLAG(default_mock_behavior) = kWarn;
710   CaptureStdout();
711   {
712     MockA a;
713     a.DoA(0);
714   }
715   std::string warning_output = GetCapturedStdout();
716   EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
717   EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
718                       warning_output);
719
720   testing::GMOCK_FLAG(default_mock_behavior) = kFail;
721   EXPECT_NONFATAL_FAILURE({
722     MockA a;
723     a.DoA(0);
724   }, "Uninteresting mock function call");
725
726   // Out of bounds values are converted to kWarn
727   testing::GMOCK_FLAG(default_mock_behavior) = -1;
728   CaptureStdout();
729   {
730     MockA a;
731     a.DoA(0);
732   }
733   warning_output = GetCapturedStdout();
734   EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
735   EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
736                       warning_output);
737   testing::GMOCK_FLAG(default_mock_behavior) = 3;
738   CaptureStdout();
739   {
740     MockA a;
741     a.DoA(0);
742   }
743   warning_output = GetCapturedStdout();
744   EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
745   EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
746                       warning_output);
747
748   testing::GMOCK_FLAG(default_mock_behavior) = original_behavior;
749 }
750
751 #endif  // GTEST_HAS_STREAM_REDIRECTION
752
753 // Tests the semantics of ON_CALL().
754
755 // Tests that the built-in default action is taken when no ON_CALL()
756 // is specified.
757 TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {
758   MockB b;
759   EXPECT_CALL(b, DoB());
760
761   EXPECT_EQ(0, b.DoB());
762 }
763
764 // Tests that the built-in default action is taken when no ON_CALL()
765 // matches the invocation.
766 TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {
767   MockB b;
768   ON_CALL(b, DoB(1))
769       .WillByDefault(Return(1));
770   EXPECT_CALL(b, DoB(_));
771
772   EXPECT_EQ(0, b.DoB(2));
773 }
774
775 // Tests that the last matching ON_CALL() action is taken.
776 TEST(OnCallTest, PicksLastMatchingOnCall) {
777   MockB b;
778   ON_CALL(b, DoB(_))
779       .WillByDefault(Return(3));
780   ON_CALL(b, DoB(2))
781       .WillByDefault(Return(2));
782   ON_CALL(b, DoB(1))
783       .WillByDefault(Return(1));
784   EXPECT_CALL(b, DoB(_));
785
786   EXPECT_EQ(2, b.DoB(2));
787 }
788
789 // Tests the semantics of EXPECT_CALL().
790
791 // Tests that any call is allowed when no EXPECT_CALL() is specified.
792 TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {
793   MockB b;
794   EXPECT_CALL(b, DoB());
795   // There is no expectation on DoB(int).
796
797   b.DoB();
798
799   // DoB(int) can be called any number of times.
800   b.DoB(1);
801   b.DoB(2);
802 }
803
804 // Tests that the last matching EXPECT_CALL() fires.
805 TEST(ExpectCallTest, PicksLastMatchingExpectCall) {
806   MockB b;
807   EXPECT_CALL(b, DoB(_))
808       .WillRepeatedly(Return(2));
809   EXPECT_CALL(b, DoB(1))
810       .WillRepeatedly(Return(1));
811
812   EXPECT_EQ(1, b.DoB(1));
813 }
814
815 // Tests lower-bound violation.
816 TEST(ExpectCallTest, CatchesTooFewCalls) {
817   EXPECT_NONFATAL_FAILURE({  // NOLINT
818     MockB b;
819     EXPECT_CALL(b, DoB(5))
820         .Times(AtLeast(2));
821
822     b.DoB(5);
823   }, "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n"
824      "         Expected: to be called at least twice\n"
825      "           Actual: called once - unsatisfied and active");
826 }
827
828 // Tests that the cardinality can be inferred when no Times(...) is
829 // specified.
830 TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {
831   {
832     MockB b;
833     EXPECT_CALL(b, DoB())
834         .WillOnce(Return(1))
835         .WillOnce(Return(2));
836
837     EXPECT_EQ(1, b.DoB());
838     EXPECT_EQ(2, b.DoB());
839   }
840
841   EXPECT_NONFATAL_FAILURE({  // NOLINT
842     MockB b;
843     EXPECT_CALL(b, DoB())
844         .WillOnce(Return(1))
845         .WillOnce(Return(2));
846
847     EXPECT_EQ(1, b.DoB());
848   }, "to be called twice");
849
850   {  // NOLINT
851     MockB b;
852     EXPECT_CALL(b, DoB())
853         .WillOnce(Return(1))
854         .WillOnce(Return(2));
855
856     EXPECT_EQ(1, b.DoB());
857     EXPECT_EQ(2, b.DoB());
858     EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice");
859   }
860 }
861
862 TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
863   {
864     MockB b;
865     EXPECT_CALL(b, DoB())
866         .WillOnce(Return(1))
867         .WillRepeatedly(Return(2));
868
869     EXPECT_EQ(1, b.DoB());
870   }
871
872   {  // NOLINT
873     MockB b;
874     EXPECT_CALL(b, DoB())
875         .WillOnce(Return(1))
876         .WillRepeatedly(Return(2));
877
878     EXPECT_EQ(1, b.DoB());
879     EXPECT_EQ(2, b.DoB());
880     EXPECT_EQ(2, b.DoB());
881   }
882
883   EXPECT_NONFATAL_FAILURE({  // NOLINT
884     MockB b;
885     EXPECT_CALL(b, DoB())
886         .WillOnce(Return(1))
887         .WillRepeatedly(Return(2));
888   }, "to be called at least once");
889 }
890
891 // Tests that the n-th action is taken for the n-th matching
892 // invocation.
893 TEST(ExpectCallTest, NthMatchTakesNthAction) {
894   MockB b;
895   EXPECT_CALL(b, DoB())
896       .WillOnce(Return(1))
897       .WillOnce(Return(2))
898       .WillOnce(Return(3));
899
900   EXPECT_EQ(1, b.DoB());
901   EXPECT_EQ(2, b.DoB());
902   EXPECT_EQ(3, b.DoB());
903 }
904
905 // Tests that the WillRepeatedly() action is taken when the WillOnce(...)
906 // list is exhausted.
907 TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
908   MockB b;
909   EXPECT_CALL(b, DoB())
910       .WillOnce(Return(1))
911       .WillRepeatedly(Return(2));
912
913   EXPECT_EQ(1, b.DoB());
914   EXPECT_EQ(2, b.DoB());
915   EXPECT_EQ(2, b.DoB());
916 }
917
918 #if GTEST_HAS_STREAM_REDIRECTION
919
920 // Tests that the default action is taken when the WillOnce(...) list is
921 // exhausted and there is no WillRepeatedly().
922 TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
923   MockB b;
924   EXPECT_CALL(b, DoB(_))
925       .Times(1);
926   EXPECT_CALL(b, DoB())
927       .Times(AnyNumber())
928       .WillOnce(Return(1))
929       .WillOnce(Return(2));
930
931   CaptureStdout();
932   EXPECT_EQ(0, b.DoB(1));  // Shouldn't generate a warning as the
933                            // expectation has no action clause at all.
934   EXPECT_EQ(1, b.DoB());
935   EXPECT_EQ(2, b.DoB());
936   const std::string output1 = GetCapturedStdout();
937   EXPECT_STREQ("", output1.c_str());
938
939   CaptureStdout();
940   EXPECT_EQ(0, b.DoB());
941   EXPECT_EQ(0, b.DoB());
942   const std::string output2 = GetCapturedStdout();
943   EXPECT_THAT(output2.c_str(),
944               HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
945                         "Called 3 times, but only 2 WillOnce()s are specified"
946                         " - returning default value."));
947   EXPECT_THAT(output2.c_str(),
948               HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
949                         "Called 4 times, but only 2 WillOnce()s are specified"
950                         " - returning default value."));
951 }
952
953 TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhausedActions) {
954   MockB b;
955   std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
956   EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));
957
958   EXPECT_EQ(1, b.DoB());
959
960   CaptureStdout();
961   EXPECT_EQ(0, b.DoB());
962   const std::string output = GetCapturedStdout();
963   // The warning message should contain the call location.
964   EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output);
965 }
966
967 TEST(FunctionMockerMessageTest,
968      ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) {
969   std::string on_call_location;
970   CaptureStdout();
971   {
972     NaggyMock<MockB> b;
973     on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
974     ON_CALL(b, DoB(_)).WillByDefault(Return(0));
975     b.DoB(0);
976   }
977   EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout());
978 }
979
980 #endif  // GTEST_HAS_STREAM_REDIRECTION
981
982 // Tests that an uninteresting call performs the default action.
983 TEST(UninterestingCallTest, DoesDefaultAction) {
984   // When there is an ON_CALL() statement, the action specified by it
985   // should be taken.
986   MockA a;
987   ON_CALL(a, Binary(_, _))
988       .WillByDefault(Return(true));
989   EXPECT_TRUE(a.Binary(1, 2));
990
991   // When there is no ON_CALL(), the default value for the return type
992   // should be returned.
993   MockB b;
994   EXPECT_EQ(0, b.DoB());
995 }
996
997 // Tests that an unexpected call performs the default action.
998 TEST(UnexpectedCallTest, DoesDefaultAction) {
999   // When there is an ON_CALL() statement, the action specified by it
1000   // should be taken.
1001   MockA a;
1002   ON_CALL(a, Binary(_, _))
1003       .WillByDefault(Return(true));
1004   EXPECT_CALL(a, Binary(0, 0));
1005   a.Binary(0, 0);
1006   bool result = false;
1007   EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),
1008                           "Unexpected mock function call");
1009   EXPECT_TRUE(result);
1010
1011   // When there is no ON_CALL(), the default value for the return type
1012   // should be returned.
1013   MockB b;
1014   EXPECT_CALL(b, DoB(0))
1015       .Times(0);
1016   int n = -1;
1017   EXPECT_NONFATAL_FAILURE(n = b.DoB(1),
1018                           "Unexpected mock function call");
1019   EXPECT_EQ(0, n);
1020 }
1021
1022 // Tests that when an unexpected void function generates the right
1023 // failure message.
1024 TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {
1025   // First, tests the message when there is only one EXPECT_CALL().
1026   MockA a1;
1027   EXPECT_CALL(a1, DoA(1));
1028   a1.DoA(1);
1029   // Ideally we should match the failure message against a regex, but
1030   // EXPECT_NONFATAL_FAILURE doesn't support that, so we test for
1031   // multiple sub-strings instead.
1032   EXPECT_NONFATAL_FAILURE(
1033       a1.DoA(9),
1034       "Unexpected mock function call - returning directly.\n"
1035       "    Function call: DoA(9)\n"
1036       "Google Mock tried the following 1 expectation, but it didn't match:");
1037   EXPECT_NONFATAL_FAILURE(
1038       a1.DoA(9),
1039       "  Expected arg #0: is equal to 1\n"
1040       "           Actual: 9\n"
1041       "         Expected: to be called once\n"
1042       "           Actual: called once - saturated and active");
1043
1044   // Next, tests the message when there are more than one EXPECT_CALL().
1045   MockA a2;
1046   EXPECT_CALL(a2, DoA(1));
1047   EXPECT_CALL(a2, DoA(3));
1048   a2.DoA(1);
1049   EXPECT_NONFATAL_FAILURE(
1050       a2.DoA(2),
1051       "Unexpected mock function call - returning directly.\n"
1052       "    Function call: DoA(2)\n"
1053       "Google Mock tried the following 2 expectations, but none matched:");
1054   EXPECT_NONFATAL_FAILURE(
1055       a2.DoA(2),
1056       "tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n"
1057       "  Expected arg #0: is equal to 1\n"
1058       "           Actual: 2\n"
1059       "         Expected: to be called once\n"
1060       "           Actual: called once - saturated and active");
1061   EXPECT_NONFATAL_FAILURE(
1062       a2.DoA(2),
1063       "tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n"
1064       "  Expected arg #0: is equal to 3\n"
1065       "           Actual: 2\n"
1066       "         Expected: to be called once\n"
1067       "           Actual: never called - unsatisfied and active");
1068   a2.DoA(3);
1069 }
1070
1071 // Tests that an unexpected non-void function generates the right
1072 // failure message.
1073 TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {
1074   MockB b1;
1075   EXPECT_CALL(b1, DoB(1));
1076   b1.DoB(1);
1077   EXPECT_NONFATAL_FAILURE(
1078       b1.DoB(2),
1079       "Unexpected mock function call - returning default value.\n"
1080       "    Function call: DoB(2)\n"
1081       "          Returns: 0\n"
1082       "Google Mock tried the following 1 expectation, but it didn't match:");
1083   EXPECT_NONFATAL_FAILURE(
1084       b1.DoB(2),
1085       "  Expected arg #0: is equal to 1\n"
1086       "           Actual: 2\n"
1087       "         Expected: to be called once\n"
1088       "           Actual: called once - saturated and active");
1089 }
1090
1091 // Tests that Google Mock explains that an retired expectation doesn't
1092 // match the call.
1093 TEST(UnexpectedCallTest, RetiredExpectation) {
1094   MockB b;
1095   EXPECT_CALL(b, DoB(1))
1096       .RetiresOnSaturation();
1097
1098   b.DoB(1);
1099   EXPECT_NONFATAL_FAILURE(
1100       b.DoB(1),
1101       "         Expected: the expectation is active\n"
1102       "           Actual: it is retired");
1103 }
1104
1105 // Tests that Google Mock explains that an expectation that doesn't
1106 // match the arguments doesn't match the call.
1107 TEST(UnexpectedCallTest, UnmatchedArguments) {
1108   MockB b;
1109   EXPECT_CALL(b, DoB(1));
1110
1111   EXPECT_NONFATAL_FAILURE(
1112       b.DoB(2),
1113       "  Expected arg #0: is equal to 1\n"
1114       "           Actual: 2\n");
1115   b.DoB(1);
1116 }
1117
1118 // Tests that Google Mock explains that an expectation with
1119 // unsatisfied pre-requisites doesn't match the call.
1120 TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
1121   Sequence s1, s2;
1122   MockB b;
1123   EXPECT_CALL(b, DoB(1))
1124       .InSequence(s1);
1125   EXPECT_CALL(b, DoB(2))
1126       .Times(AnyNumber())
1127       .InSequence(s1);
1128   EXPECT_CALL(b, DoB(3))
1129       .InSequence(s2);
1130   EXPECT_CALL(b, DoB(4))
1131       .InSequence(s1, s2);
1132
1133   ::testing::TestPartResultArray failures;
1134   {
1135     ::testing::ScopedFakeTestPartResultReporter reporter(&failures);
1136     b.DoB(4);
1137     // Now 'failures' contains the Google Test failures generated by
1138     // the above statement.
1139   }
1140
1141   // There should be one non-fatal failure.
1142   ASSERT_EQ(1, failures.size());
1143   const ::testing::TestPartResult& r = failures.GetTestPartResult(0);
1144   EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type());
1145
1146   // Verifies that the failure message contains the two unsatisfied
1147   // pre-requisites but not the satisfied one.
1148 #if GTEST_USES_PCRE
1149   EXPECT_THAT(r.message(), ContainsRegex(
1150       // PCRE has trouble using (.|\n) to match any character, but
1151       // supports the (?s) prefix for using . to match any character.
1152       "(?s)the following immediate pre-requisites are not satisfied:\n"
1153       ".*: pre-requisite #0\n"
1154       ".*: pre-requisite #1"));
1155 #elif GTEST_USES_POSIX_RE
1156   EXPECT_THAT(r.message(), ContainsRegex(
1157       // POSIX RE doesn't understand the (?s) prefix, but has no trouble
1158       // with (.|\n).
1159       "the following immediate pre-requisites are not satisfied:\n"
1160       "(.|\n)*: pre-requisite #0\n"
1161       "(.|\n)*: pre-requisite #1"));
1162 #else
1163   // We can only use Google Test's own simple regex.
1164   EXPECT_THAT(r.message(), ContainsRegex(
1165       "the following immediate pre-requisites are not satisfied:"));
1166   EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));
1167   EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));
1168 #endif  // GTEST_USES_PCRE
1169
1170   b.DoB(1);
1171   b.DoB(3);
1172   b.DoB(4);
1173 }
1174
1175 TEST(UndefinedReturnValueTest,
1176      ReturnValueIsMandatoryWhenNotDefaultConstructible) {
1177   MockA a;
1178   // FIXME: We should really verify the output message,
1179   // but we cannot yet due to that EXPECT_DEATH only captures stderr
1180   // while Google Mock logs to stdout.
1181 #if GTEST_HAS_EXCEPTIONS
1182   EXPECT_ANY_THROW(a.ReturnNonDefaultConstructible());
1183 #else
1184   EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), "");
1185 #endif
1186 }
1187
1188 // Tests that an excessive call (one whose arguments match the
1189 // matchers but is called too many times) performs the default action.
1190 TEST(ExcessiveCallTest, DoesDefaultAction) {
1191   // When there is an ON_CALL() statement, the action specified by it
1192   // should be taken.
1193   MockA a;
1194   ON_CALL(a, Binary(_, _))
1195       .WillByDefault(Return(true));
1196   EXPECT_CALL(a, Binary(0, 0));
1197   a.Binary(0, 0);
1198   bool result = false;
1199   EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),
1200                           "Mock function called more times than expected");
1201   EXPECT_TRUE(result);
1202
1203   // When there is no ON_CALL(), the default value for the return type
1204   // should be returned.
1205   MockB b;
1206   EXPECT_CALL(b, DoB(0))
1207       .Times(0);
1208   int n = -1;
1209   EXPECT_NONFATAL_FAILURE(n = b.DoB(0),
1210                           "Mock function called more times than expected");
1211   EXPECT_EQ(0, n);
1212 }
1213
1214 // Tests that when a void function is called too many times,
1215 // the failure message contains the argument values.
1216 TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
1217   MockA a;
1218   EXPECT_CALL(a, DoA(_))
1219       .Times(0);
1220   EXPECT_NONFATAL_FAILURE(
1221       a.DoA(9),
1222       "Mock function called more times than expected - returning directly.\n"
1223       "    Function call: DoA(9)\n"
1224       "         Expected: to be never called\n"
1225       "           Actual: called once - over-saturated and active");
1226 }
1227
1228 // Tests that when a non-void function is called too many times, the
1229 // failure message contains the argument values and the return value.
1230 TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {
1231   MockB b;
1232   EXPECT_CALL(b, DoB(_));
1233   b.DoB(1);
1234   EXPECT_NONFATAL_FAILURE(
1235       b.DoB(2),
1236       "Mock function called more times than expected - "
1237       "returning default value.\n"
1238       "    Function call: DoB(2)\n"
1239       "          Returns: 0\n"
1240       "         Expected: to be called once\n"
1241       "           Actual: called twice - over-saturated and active");
1242 }
1243
1244 // Tests using sequences.
1245
1246 TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {
1247   MockA a;
1248   {
1249     InSequence dummy;
1250
1251     EXPECT_CALL(a, DoA(1));
1252     EXPECT_CALL(a, DoA(2));
1253   }
1254
1255   EXPECT_NONFATAL_FAILURE({  // NOLINT
1256     a.DoA(2);
1257   }, "Unexpected mock function call");
1258
1259   a.DoA(1);
1260   a.DoA(2);
1261 }
1262
1263 TEST(InSequenceTest, NestedInSequence) {
1264   MockA a;
1265   {
1266     InSequence dummy;
1267
1268     EXPECT_CALL(a, DoA(1));
1269     {
1270       InSequence dummy2;
1271
1272       EXPECT_CALL(a, DoA(2));
1273       EXPECT_CALL(a, DoA(3));
1274     }
1275   }
1276
1277   EXPECT_NONFATAL_FAILURE({  // NOLINT
1278     a.DoA(1);
1279     a.DoA(3);
1280   }, "Unexpected mock function call");
1281
1282   a.DoA(2);
1283   a.DoA(3);
1284 }
1285
1286 TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {
1287   MockA a;
1288   {
1289     InSequence dummy;
1290
1291     EXPECT_CALL(a, DoA(1));
1292     EXPECT_CALL(a, DoA(2));
1293   }
1294   EXPECT_CALL(a, DoA(3));
1295
1296   EXPECT_NONFATAL_FAILURE({  // NOLINT
1297     a.DoA(2);
1298   }, "Unexpected mock function call");
1299
1300   a.DoA(3);
1301   a.DoA(1);
1302   a.DoA(2);
1303 }
1304
1305 // Tests that any order is allowed when no sequence is used.
1306 TEST(SequenceTest, AnyOrderIsOkByDefault) {
1307   {
1308     MockA a;
1309     MockB b;
1310
1311     EXPECT_CALL(a, DoA(1));
1312     EXPECT_CALL(b, DoB())
1313         .Times(AnyNumber());
1314
1315     a.DoA(1);
1316     b.DoB();
1317   }
1318
1319   {  // NOLINT
1320     MockA a;
1321     MockB b;
1322
1323     EXPECT_CALL(a, DoA(1));
1324     EXPECT_CALL(b, DoB())
1325         .Times(AnyNumber());
1326
1327     b.DoB();
1328     a.DoA(1);
1329   }
1330 }
1331
1332 // Tests that the calls must be in strict order when a complete order
1333 // is specified.
1334 TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) {
1335   MockA a;
1336   ON_CALL(a, ReturnResult(_))
1337       .WillByDefault(Return(Result()));
1338
1339   Sequence s;
1340   EXPECT_CALL(a, ReturnResult(1))
1341       .InSequence(s);
1342   EXPECT_CALL(a, ReturnResult(2))
1343       .InSequence(s);
1344   EXPECT_CALL(a, ReturnResult(3))
1345       .InSequence(s);
1346
1347   a.ReturnResult(1);
1348
1349   // May only be called after a.ReturnResult(2).
1350   EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1351
1352   a.ReturnResult(2);
1353   a.ReturnResult(3);
1354 }
1355
1356 // Tests that the calls must be in strict order when a complete order
1357 // is specified.
1358 TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) {
1359   MockA a;
1360   ON_CALL(a, ReturnResult(_))
1361       .WillByDefault(Return(Result()));
1362
1363   Sequence s;
1364   EXPECT_CALL(a, ReturnResult(1))
1365       .InSequence(s);
1366   EXPECT_CALL(a, ReturnResult(2))
1367       .InSequence(s);
1368
1369   // May only be called after a.ReturnResult(1).
1370   EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call");
1371
1372   a.ReturnResult(1);
1373   a.ReturnResult(2);
1374 }
1375
1376 // Tests specifying a DAG using multiple sequences.
1377 class PartialOrderTest : public testing::Test {
1378  protected:
1379   PartialOrderTest() {
1380     ON_CALL(a_, ReturnResult(_))
1381         .WillByDefault(Return(Result()));
1382
1383     // Specifies this partial ordering:
1384     //
1385     // a.ReturnResult(1) ==>
1386     //                       a.ReturnResult(2) * n  ==>  a.ReturnResult(3)
1387     // b.DoB() * 2       ==>
1388     Sequence x, y;
1389     EXPECT_CALL(a_, ReturnResult(1))
1390         .InSequence(x);
1391     EXPECT_CALL(b_, DoB())
1392         .Times(2)
1393         .InSequence(y);
1394     EXPECT_CALL(a_, ReturnResult(2))
1395         .Times(AnyNumber())
1396         .InSequence(x, y);
1397     EXPECT_CALL(a_, ReturnResult(3))
1398         .InSequence(x);
1399   }
1400
1401   MockA a_;
1402   MockB b_;
1403 };
1404
1405 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) {
1406   a_.ReturnResult(1);
1407   b_.DoB();
1408
1409   // May only be called after the second DoB().
1410   EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1411
1412   b_.DoB();
1413   a_.ReturnResult(3);
1414 }
1415
1416 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag2) {
1417   // May only be called after ReturnResult(1).
1418   EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1419
1420   a_.ReturnResult(1);
1421   b_.DoB();
1422   b_.DoB();
1423   a_.ReturnResult(3);
1424 }
1425
1426 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag3) {
1427   // May only be called last.
1428   EXPECT_NONFATAL_FAILURE(a_.ReturnResult(3), "Unexpected mock function call");
1429
1430   a_.ReturnResult(1);
1431   b_.DoB();
1432   b_.DoB();
1433   a_.ReturnResult(3);
1434 }
1435
1436 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag4) {
1437   a_.ReturnResult(1);
1438   b_.DoB();
1439   b_.DoB();
1440   a_.ReturnResult(3);
1441
1442   // May only be called before ReturnResult(3).
1443   EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1444 }
1445
1446 TEST(SequenceTest, Retirement) {
1447   MockA a;
1448   Sequence s;
1449
1450   EXPECT_CALL(a, DoA(1))
1451       .InSequence(s);
1452   EXPECT_CALL(a, DoA(_))
1453       .InSequence(s)
1454       .RetiresOnSaturation();
1455   EXPECT_CALL(a, DoA(1))
1456       .InSequence(s);
1457
1458   a.DoA(1);
1459   a.DoA(2);
1460   a.DoA(1);
1461 }
1462
1463 // Tests Expectation.
1464
1465 TEST(ExpectationTest, ConstrutorsWork) {
1466   MockA a;
1467   Expectation e1;  // Default ctor.
1468
1469   // Ctor from various forms of EXPECT_CALL.
1470   Expectation e2 = EXPECT_CALL(a, DoA(2));
1471   Expectation e3 = EXPECT_CALL(a, DoA(3)).With(_);
1472   {
1473     Sequence s;
1474     Expectation e4 = EXPECT_CALL(a, DoA(4)).Times(1);
1475     Expectation e5 = EXPECT_CALL(a, DoA(5)).InSequence(s);
1476   }
1477   Expectation e6 = EXPECT_CALL(a, DoA(6)).After(e2);
1478   Expectation e7 = EXPECT_CALL(a, DoA(7)).WillOnce(Return());
1479   Expectation e8 = EXPECT_CALL(a, DoA(8)).WillRepeatedly(Return());
1480   Expectation e9 = EXPECT_CALL(a, DoA(9)).RetiresOnSaturation();
1481
1482   Expectation e10 = e2;  // Copy ctor.
1483
1484   EXPECT_THAT(e1, Ne(e2));
1485   EXPECT_THAT(e2, Eq(e10));
1486
1487   a.DoA(2);
1488   a.DoA(3);
1489   a.DoA(4);
1490   a.DoA(5);
1491   a.DoA(6);
1492   a.DoA(7);
1493   a.DoA(8);
1494   a.DoA(9);
1495 }
1496
1497 TEST(ExpectationTest, AssignmentWorks) {
1498   MockA a;
1499   Expectation e1;
1500   Expectation e2 = EXPECT_CALL(a, DoA(1));
1501
1502   EXPECT_THAT(e1, Ne(e2));
1503
1504   e1 = e2;
1505   EXPECT_THAT(e1, Eq(e2));
1506
1507   a.DoA(1);
1508 }
1509
1510 // Tests ExpectationSet.
1511
1512 TEST(ExpectationSetTest, MemberTypesAreCorrect) {
1513   ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();
1514 }
1515
1516 TEST(ExpectationSetTest, ConstructorsWork) {
1517   MockA a;
1518
1519   Expectation e1;
1520   const Expectation e2;
1521   ExpectationSet es1;  // Default ctor.
1522   ExpectationSet es2 = EXPECT_CALL(a, DoA(1));  // Ctor from EXPECT_CALL.
1523   ExpectationSet es3 = e1;  // Ctor from Expectation.
1524   ExpectationSet es4(e1);   // Ctor from Expectation; alternative syntax.
1525   ExpectationSet es5 = e2;  // Ctor from const Expectation.
1526   ExpectationSet es6(e2);   // Ctor from const Expectation; alternative syntax.
1527   ExpectationSet es7 = es2;  // Copy ctor.
1528
1529   EXPECT_EQ(0, es1.size());
1530   EXPECT_EQ(1, es2.size());
1531   EXPECT_EQ(1, es3.size());
1532   EXPECT_EQ(1, es4.size());
1533   EXPECT_EQ(1, es5.size());
1534   EXPECT_EQ(1, es6.size());
1535   EXPECT_EQ(1, es7.size());
1536
1537   EXPECT_THAT(es3, Ne(es2));
1538   EXPECT_THAT(es4, Eq(es3));
1539   EXPECT_THAT(es5, Eq(es4));
1540   EXPECT_THAT(es6, Eq(es5));
1541   EXPECT_THAT(es7, Eq(es2));
1542   a.DoA(1);
1543 }
1544
1545 TEST(ExpectationSetTest, AssignmentWorks) {
1546   ExpectationSet es1;
1547   ExpectationSet es2 = Expectation();
1548
1549   es1 = es2;
1550   EXPECT_EQ(1, es1.size());
1551   EXPECT_THAT(*(es1.begin()), Eq(Expectation()));
1552   EXPECT_THAT(es1, Eq(es2));
1553 }
1554
1555 TEST(ExpectationSetTest, InsertionWorks) {
1556   ExpectationSet es1;
1557   Expectation e1;
1558   es1 += e1;
1559   EXPECT_EQ(1, es1.size());
1560   EXPECT_THAT(*(es1.begin()), Eq(e1));
1561
1562   MockA a;
1563   Expectation e2 = EXPECT_CALL(a, DoA(1));
1564   es1 += e2;
1565   EXPECT_EQ(2, es1.size());
1566
1567   ExpectationSet::const_iterator it1 = es1.begin();
1568   ExpectationSet::const_iterator it2 = it1;
1569   ++it2;
1570   EXPECT_TRUE(*it1 == e1 || *it2 == e1);  // e1 must be in the set.
1571   EXPECT_TRUE(*it1 == e2 || *it2 == e2);  // e2 must be in the set too.
1572   a.DoA(1);
1573 }
1574
1575 TEST(ExpectationSetTest, SizeWorks) {
1576   ExpectationSet es;
1577   EXPECT_EQ(0, es.size());
1578
1579   es += Expectation();
1580   EXPECT_EQ(1, es.size());
1581
1582   MockA a;
1583   es += EXPECT_CALL(a, DoA(1));
1584   EXPECT_EQ(2, es.size());
1585
1586   a.DoA(1);
1587 }
1588
1589 TEST(ExpectationSetTest, IsEnumerable) {
1590   ExpectationSet es;
1591   EXPECT_TRUE(es.begin() == es.end());
1592
1593   es += Expectation();
1594   ExpectationSet::const_iterator it = es.begin();
1595   EXPECT_TRUE(it != es.end());
1596   EXPECT_THAT(*it, Eq(Expectation()));
1597   ++it;
1598   EXPECT_TRUE(it== es.end());
1599 }
1600
1601 // Tests the .After() clause.
1602
1603 TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {
1604   MockA a;
1605   ExpectationSet es;
1606   es += EXPECT_CALL(a, DoA(1));
1607   es += EXPECT_CALL(a, DoA(2));
1608   EXPECT_CALL(a, DoA(3))
1609       .After(es);
1610
1611   a.DoA(1);
1612   a.DoA(2);
1613   a.DoA(3);
1614 }
1615
1616 TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {
1617   MockA a;
1618   MockB b;
1619   // The following also verifies that const Expectation objects work
1620   // too.  Do not remove the const modifiers.
1621   const Expectation e1 = EXPECT_CALL(a, DoA(1));
1622   const Expectation e2 = EXPECT_CALL(b, DoB())
1623       .Times(2)
1624       .After(e1);
1625   EXPECT_CALL(a, DoA(2)).After(e2);
1626
1627   a.DoA(1);
1628   b.DoB();
1629   b.DoB();
1630   a.DoA(2);
1631 }
1632
1633 // Calls must be in strict order when specified so using .After().
1634 TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) {
1635   MockA a;
1636   MockB b;
1637
1638   // Define ordering:
1639   //   a.DoA(1) ==> b.DoB() ==> a.DoA(2)
1640   Expectation e1 = EXPECT_CALL(a, DoA(1));
1641   Expectation e2 = EXPECT_CALL(b, DoB())
1642       .After(e1);
1643   EXPECT_CALL(a, DoA(2))
1644       .After(e2);
1645
1646   a.DoA(1);
1647
1648   // May only be called after DoB().
1649   EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
1650
1651   b.DoB();
1652   a.DoA(2);
1653 }
1654
1655 // Calls must be in strict order when specified so using .After().
1656 TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) {
1657   MockA a;
1658   MockB b;
1659
1660   // Define ordering:
1661   //   a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2)
1662   Expectation e1 = EXPECT_CALL(a, DoA(1));
1663   Expectation e2 = EXPECT_CALL(b, DoB())
1664       .Times(2)
1665       .After(e1);
1666   EXPECT_CALL(a, DoA(2))
1667       .After(e2);
1668
1669   a.DoA(1);
1670   b.DoB();
1671
1672   // May only be called after the second DoB().
1673   EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
1674
1675   b.DoB();
1676   a.DoA(2);
1677 }
1678
1679 // Calls must satisfy the partial order when specified so.
1680 TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {
1681   MockA a;
1682   ON_CALL(a, ReturnResult(_))
1683       .WillByDefault(Return(Result()));
1684
1685   // Define ordering:
1686   //   a.DoA(1) ==>
1687   //   a.DoA(2) ==> a.ReturnResult(3)
1688   Expectation e = EXPECT_CALL(a, DoA(1));
1689   const ExpectationSet es = EXPECT_CALL(a, DoA(2));
1690   EXPECT_CALL(a, ReturnResult(3))
1691       .After(e, es);
1692
1693   // May only be called last.
1694   EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1695
1696   a.DoA(2);
1697   a.DoA(1);
1698   a.ReturnResult(3);
1699 }
1700
1701 // Calls must satisfy the partial order when specified so.
1702 TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) {
1703   MockA a;
1704
1705   // Define ordering:
1706   //   a.DoA(1) ==>
1707   //   a.DoA(2) ==> a.DoA(3)
1708   Expectation e = EXPECT_CALL(a, DoA(1));
1709   const ExpectationSet es = EXPECT_CALL(a, DoA(2));
1710   EXPECT_CALL(a, DoA(3))
1711       .After(e, es);
1712
1713   a.DoA(2);
1714
1715   // May only be called last.
1716   EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
1717
1718   a.DoA(1);
1719   a.DoA(3);
1720 }
1721
1722 // .After() can be combined with .InSequence().
1723 TEST(AfterTest, CanBeUsedWithInSequence) {
1724   MockA a;
1725   Sequence s;
1726   Expectation e = EXPECT_CALL(a, DoA(1));
1727   EXPECT_CALL(a, DoA(2)).InSequence(s);
1728   EXPECT_CALL(a, DoA(3))
1729       .InSequence(s)
1730       .After(e);
1731
1732   a.DoA(1);
1733
1734   // May only be after DoA(2).
1735   EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
1736
1737   a.DoA(2);
1738   a.DoA(3);
1739 }
1740
1741 // .After() can be called multiple times.
1742 TEST(AfterTest, CanBeCalledManyTimes) {
1743   MockA a;
1744   Expectation e1 = EXPECT_CALL(a, DoA(1));
1745   Expectation e2 = EXPECT_CALL(a, DoA(2));
1746   Expectation e3 = EXPECT_CALL(a, DoA(3));
1747   EXPECT_CALL(a, DoA(4))
1748       .After(e1)
1749       .After(e2)
1750       .After(e3);
1751
1752   a.DoA(3);
1753   a.DoA(1);
1754   a.DoA(2);
1755   a.DoA(4);
1756 }
1757
1758 // .After() accepts up to 5 arguments.
1759 TEST(AfterTest, AcceptsUpToFiveArguments) {
1760   MockA a;
1761   Expectation e1 = EXPECT_CALL(a, DoA(1));
1762   Expectation e2 = EXPECT_CALL(a, DoA(2));
1763   Expectation e3 = EXPECT_CALL(a, DoA(3));
1764   ExpectationSet es1 = EXPECT_CALL(a, DoA(4));
1765   ExpectationSet es2 = EXPECT_CALL(a, DoA(5));
1766   EXPECT_CALL(a, DoA(6))
1767       .After(e1, e2, e3, es1, es2);
1768
1769   a.DoA(5);
1770   a.DoA(2);
1771   a.DoA(4);
1772   a.DoA(1);
1773   a.DoA(3);
1774   a.DoA(6);
1775 }
1776
1777 // .After() allows input to contain duplicated Expectations.
1778 TEST(AfterTest, AcceptsDuplicatedInput) {
1779   MockA a;
1780   ON_CALL(a, ReturnResult(_))
1781       .WillByDefault(Return(Result()));
1782
1783   // Define ordering:
1784   //   DoA(1) ==>
1785   //   DoA(2) ==> ReturnResult(3)
1786   Expectation e1 = EXPECT_CALL(a, DoA(1));
1787   Expectation e2 = EXPECT_CALL(a, DoA(2));
1788   ExpectationSet es;
1789   es += e1;
1790   es += e2;
1791   EXPECT_CALL(a, ReturnResult(3))
1792       .After(e1, e2, es, e1);
1793
1794   a.DoA(1);
1795
1796   // May only be after DoA(2).
1797   EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1798
1799   a.DoA(2);
1800   a.ReturnResult(3);
1801 }
1802
1803 // An Expectation added to an ExpectationSet after it has been used in
1804 // an .After() has no effect.
1805 TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {
1806   MockA a;
1807   ExpectationSet es1 = EXPECT_CALL(a, DoA(1));
1808   Expectation e2 = EXPECT_CALL(a, DoA(2));
1809   EXPECT_CALL(a, DoA(3))
1810       .After(es1);
1811   es1 += e2;
1812
1813   a.DoA(1);
1814   a.DoA(3);
1815   a.DoA(2);
1816 }
1817
1818 // Tests that Google Mock correctly handles calls to mock functions
1819 // after a mock object owning one of their pre-requisites has died.
1820
1821 // Tests that calls that satisfy the original spec are successful.
1822 TEST(DeletingMockEarlyTest, Success1) {
1823   MockB* const b1 = new MockB;
1824   MockA* const a = new MockA;
1825   MockB* const b2 = new MockB;
1826
1827   {
1828     InSequence dummy;
1829     EXPECT_CALL(*b1, DoB(_))
1830         .WillOnce(Return(1));
1831     EXPECT_CALL(*a, Binary(_, _))
1832         .Times(AnyNumber())
1833         .WillRepeatedly(Return(true));
1834     EXPECT_CALL(*b2, DoB(_))
1835         .Times(AnyNumber())
1836         .WillRepeatedly(Return(2));
1837   }
1838
1839   EXPECT_EQ(1, b1->DoB(1));
1840   delete b1;
1841   // a's pre-requisite has died.
1842   EXPECT_TRUE(a->Binary(0, 1));
1843   delete b2;
1844   // a's successor has died.
1845   EXPECT_TRUE(a->Binary(1, 2));
1846   delete a;
1847 }
1848
1849 // Tests that calls that satisfy the original spec are successful.
1850 TEST(DeletingMockEarlyTest, Success2) {
1851   MockB* const b1 = new MockB;
1852   MockA* const a = new MockA;
1853   MockB* const b2 = new MockB;
1854
1855   {
1856     InSequence dummy;
1857     EXPECT_CALL(*b1, DoB(_))
1858         .WillOnce(Return(1));
1859     EXPECT_CALL(*a, Binary(_, _))
1860         .Times(AnyNumber());
1861     EXPECT_CALL(*b2, DoB(_))
1862         .Times(AnyNumber())
1863         .WillRepeatedly(Return(2));
1864   }
1865
1866   delete a;  // a is trivially satisfied.
1867   EXPECT_EQ(1, b1->DoB(1));
1868   EXPECT_EQ(2, b2->DoB(2));
1869   delete b1;
1870   delete b2;
1871 }
1872
1873 // Tests that it's OK to delete a mock object itself in its action.
1874
1875 // Suppresses warning on unreferenced formal parameter in MSVC with
1876 // -W4.
1877 #ifdef _MSC_VER
1878 # pragma warning(push)
1879 # pragma warning(disable:4100)
1880 #endif
1881
1882 ACTION_P(Delete, ptr) { delete ptr; }
1883
1884 #ifdef _MSC_VER
1885 # pragma warning(pop)
1886 #endif
1887
1888 TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
1889   MockA* const a = new MockA;
1890   EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a));
1891   a->DoA(42);  // This will cause a to be deleted.
1892 }
1893
1894 TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {
1895   MockA* const a = new MockA;
1896   EXPECT_CALL(*a, ReturnResult(_))
1897       .WillOnce(DoAll(Delete(a), Return(Result())));
1898   a->ReturnResult(42);  // This will cause a to be deleted.
1899 }
1900
1901 // Tests that calls that violate the original spec yield failures.
1902 TEST(DeletingMockEarlyTest, Failure1) {
1903   MockB* const b1 = new MockB;
1904   MockA* const a = new MockA;
1905   MockB* const b2 = new MockB;
1906
1907   {
1908     InSequence dummy;
1909     EXPECT_CALL(*b1, DoB(_))
1910         .WillOnce(Return(1));
1911     EXPECT_CALL(*a, Binary(_, _))
1912         .Times(AnyNumber());
1913     EXPECT_CALL(*b2, DoB(_))
1914         .Times(AnyNumber())
1915         .WillRepeatedly(Return(2));
1916   }
1917
1918   delete a;  // a is trivially satisfied.
1919   EXPECT_NONFATAL_FAILURE({
1920     b2->DoB(2);
1921   }, "Unexpected mock function call");
1922   EXPECT_EQ(1, b1->DoB(1));
1923   delete b1;
1924   delete b2;
1925 }
1926
1927 // Tests that calls that violate the original spec yield failures.
1928 TEST(DeletingMockEarlyTest, Failure2) {
1929   MockB* const b1 = new MockB;
1930   MockA* const a = new MockA;
1931   MockB* const b2 = new MockB;
1932
1933   {
1934     InSequence dummy;
1935     EXPECT_CALL(*b1, DoB(_));
1936     EXPECT_CALL(*a, Binary(_, _))
1937         .Times(AnyNumber());
1938     EXPECT_CALL(*b2, DoB(_))
1939         .Times(AnyNumber());
1940   }
1941
1942   EXPECT_NONFATAL_FAILURE(delete b1,
1943                           "Actual: never called");
1944   EXPECT_NONFATAL_FAILURE(a->Binary(0, 1),
1945                           "Unexpected mock function call");
1946   EXPECT_NONFATAL_FAILURE(b2->DoB(1),
1947                           "Unexpected mock function call");
1948   delete a;
1949   delete b2;
1950 }
1951
1952 class EvenNumberCardinality : public CardinalityInterface {
1953  public:
1954   // Returns true iff call_count calls will satisfy this cardinality.
1955   virtual bool IsSatisfiedByCallCount(int call_count) const {
1956     return call_count % 2 == 0;
1957   }
1958
1959   // Returns true iff call_count calls will saturate this cardinality.
1960   virtual bool IsSaturatedByCallCount(int /* call_count */) const {
1961     return false;
1962   }
1963
1964   // Describes self to an ostream.
1965   virtual void DescribeTo(::std::ostream* os) const {
1966     *os << "called even number of times";
1967   }
1968 };
1969
1970 Cardinality EvenNumber() {
1971   return Cardinality(new EvenNumberCardinality);
1972 }
1973
1974 TEST(ExpectationBaseTest,
1975      AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
1976   MockA* a = new MockA;
1977   Sequence s;
1978
1979   EXPECT_CALL(*a, DoA(1))
1980       .Times(EvenNumber())
1981       .InSequence(s);
1982   EXPECT_CALL(*a, DoA(2))
1983       .Times(AnyNumber())
1984       .InSequence(s);
1985   EXPECT_CALL(*a, DoA(3))
1986       .Times(AnyNumber());
1987
1988   a->DoA(3);
1989   a->DoA(1);
1990   EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");
1991   EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");
1992 }
1993
1994 // The following tests verify the message generated when a mock
1995 // function is called.
1996
1997 struct Printable {
1998 };
1999
2000 inline void operator<<(::std::ostream& os, const Printable&) {
2001   os << "Printable";
2002 }
2003
2004 struct Unprintable {
2005   Unprintable() : value(0) {}
2006   int value;
2007 };
2008
2009 class MockC {
2010  public:
2011   MockC() {}
2012
2013   MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p,
2014                                 const Printable& x, Unprintable y));
2015   MOCK_METHOD0(NonVoidMethod, int());  // NOLINT
2016
2017  private:
2018   GTEST_DISALLOW_COPY_AND_ASSIGN_(MockC);
2019 };
2020
2021 class VerboseFlagPreservingFixture : public testing::Test {
2022  protected:
2023   VerboseFlagPreservingFixture()
2024       : saved_verbose_flag_(GMOCK_FLAG(verbose)) {}
2025
2026   ~VerboseFlagPreservingFixture() { GMOCK_FLAG(verbose) = saved_verbose_flag_; }
2027
2028  private:
2029   const std::string saved_verbose_flag_;
2030
2031   GTEST_DISALLOW_COPY_AND_ASSIGN_(VerboseFlagPreservingFixture);
2032 };
2033
2034 #if GTEST_HAS_STREAM_REDIRECTION
2035
2036 // Tests that an uninteresting mock function call on a naggy mock
2037 // generates a warning without the stack trace when
2038 // --gmock_verbose=warning is specified.
2039 TEST(FunctionCallMessageTest,
2040      UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) {
2041   GMOCK_FLAG(verbose) = kWarningVerbosity;
2042   NaggyMock<MockC> c;
2043   CaptureStdout();
2044   c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
2045   const std::string output = GetCapturedStdout();
2046   EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
2047   EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output);
2048 }
2049
2050 // Tests that an uninteresting mock function call on a naggy mock
2051 // generates a warning containing the stack trace when
2052 // --gmock_verbose=info is specified.
2053 TEST(FunctionCallMessageTest,
2054      UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) {
2055   GMOCK_FLAG(verbose) = kInfoVerbosity;
2056   NaggyMock<MockC> c;
2057   CaptureStdout();
2058   c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
2059   const std::string output = GetCapturedStdout();
2060   EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
2061   EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);
2062
2063 # ifndef NDEBUG
2064
2065   // We check the stack trace content in dbg-mode only, as opt-mode
2066   // may inline the call we are interested in seeing.
2067
2068   // Verifies that a void mock function's name appears in the stack
2069   // trace.
2070   EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output);
2071
2072   // Verifies that a non-void mock function's name appears in the
2073   // stack trace.
2074   CaptureStdout();
2075   c.NonVoidMethod();
2076   const std::string output2 = GetCapturedStdout();
2077   EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);
2078
2079 # endif  // NDEBUG
2080 }
2081
2082 // Tests that an uninteresting mock function call on a naggy mock
2083 // causes the function arguments and return value to be printed.
2084 TEST(FunctionCallMessageTest,
2085      UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) {
2086   // A non-void mock function.
2087   NaggyMock<MockB> b;
2088   CaptureStdout();
2089   b.DoB();
2090   const std::string output1 = GetCapturedStdout();
2091   EXPECT_PRED_FORMAT2(
2092       IsSubstring,
2093       "Uninteresting mock function call - returning default value.\n"
2094       "    Function call: DoB()\n"
2095       "          Returns: 0\n", output1.c_str());
2096   // Makes sure the return value is printed.
2097
2098   // A void mock function.
2099   NaggyMock<MockC> c;
2100   CaptureStdout();
2101   c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
2102   const std::string output2 = GetCapturedStdout();
2103   EXPECT_THAT(output2.c_str(),
2104               ContainsRegex(
2105                   "Uninteresting mock function call - returning directly\\.\n"
2106                   "    Function call: VoidMethod"
2107                   "\\(false, 5, \"Hi\", NULL, @.+ "
2108                   "Printable, 4-byte object <00-00 00-00>\\)"));
2109   // A void function has no return value to print.
2110 }
2111
2112 // Tests how the --gmock_verbose flag affects Google Mock's output.
2113
2114 class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
2115  public:
2116   // Verifies that the given Google Mock output is correct.  (When
2117   // should_print is true, the output should match the given regex and
2118   // contain the given function name in the stack trace.  When it's
2119   // false, the output should be empty.)
2120   void VerifyOutput(const std::string& output, bool should_print,
2121                     const std::string& expected_substring,
2122                     const std::string& function_name) {
2123     if (should_print) {
2124       EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));
2125 # ifndef NDEBUG
2126       // We check the stack trace content in dbg-mode only, as opt-mode
2127       // may inline the call we are interested in seeing.
2128       EXPECT_THAT(output.c_str(), HasSubstr(function_name));
2129 # else
2130       // Suppresses 'unused function parameter' warnings.
2131       static_cast<void>(function_name);
2132 # endif  // NDEBUG
2133     } else {
2134       EXPECT_STREQ("", output.c_str());
2135     }
2136   }
2137
2138   // Tests how the flag affects expected calls.
2139   void TestExpectedCall(bool should_print) {
2140     MockA a;
2141     EXPECT_CALL(a, DoA(5));
2142     EXPECT_CALL(a, Binary(_, 1))
2143         .WillOnce(Return(true));
2144
2145     // A void-returning function.
2146     CaptureStdout();
2147     a.DoA(5);
2148     VerifyOutput(
2149         GetCapturedStdout(),
2150         should_print,
2151         "Mock function call matches EXPECT_CALL(a, DoA(5))...\n"
2152         "    Function call: DoA(5)\n"
2153         "Stack trace:\n",
2154         "DoA");
2155
2156     // A non-void-returning function.
2157     CaptureStdout();
2158     a.Binary(2, 1);
2159     VerifyOutput(
2160         GetCapturedStdout(),
2161         should_print,
2162         "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"
2163         "    Function call: Binary(2, 1)\n"
2164         "          Returns: true\n"
2165         "Stack trace:\n",
2166         "Binary");
2167   }
2168
2169   // Tests how the flag affects uninteresting calls on a naggy mock.
2170   void TestUninterestingCallOnNaggyMock(bool should_print) {
2171     NaggyMock<MockA> a;
2172     const std::string note =
2173         "NOTE: You can safely ignore the above warning unless this "
2174         "call should not happen.  Do not suppress it by blindly adding "
2175         "an EXPECT_CALL() if you don't mean to enforce the call.  "
2176         "See "
2177         "https://github.com/google/googletest/blob/master/googlemock/docs/"
2178         "CookBook.md#"
2179         "knowing-when-to-expect for details.";
2180
2181     // A void-returning function.
2182     CaptureStdout();
2183     a.DoA(5);
2184     VerifyOutput(
2185         GetCapturedStdout(),
2186         should_print,
2187         "\nGMOCK WARNING:\n"
2188         "Uninteresting mock function call - returning directly.\n"
2189         "    Function call: DoA(5)\n" +
2190         note,
2191         "DoA");
2192
2193     // A non-void-returning function.
2194     CaptureStdout();
2195     a.Binary(2, 1);
2196     VerifyOutput(
2197         GetCapturedStdout(),
2198         should_print,
2199         "\nGMOCK WARNING:\n"
2200         "Uninteresting mock function call - returning default value.\n"
2201         "    Function call: Binary(2, 1)\n"
2202         "          Returns: false\n" +
2203         note,
2204         "Binary");
2205   }
2206 };
2207
2208 // Tests that --gmock_verbose=info causes both expected and
2209 // uninteresting calls to be reported.
2210 TEST_F(GMockVerboseFlagTest, Info) {
2211   GMOCK_FLAG(verbose) = kInfoVerbosity;
2212   TestExpectedCall(true);
2213   TestUninterestingCallOnNaggyMock(true);
2214 }
2215
2216 // Tests that --gmock_verbose=warning causes uninteresting calls to be
2217 // reported.
2218 TEST_F(GMockVerboseFlagTest, Warning) {
2219   GMOCK_FLAG(verbose) = kWarningVerbosity;
2220   TestExpectedCall(false);
2221   TestUninterestingCallOnNaggyMock(true);
2222 }
2223
2224 // Tests that --gmock_verbose=warning causes neither expected nor
2225 // uninteresting calls to be reported.
2226 TEST_F(GMockVerboseFlagTest, Error) {
2227   GMOCK_FLAG(verbose) = kErrorVerbosity;
2228   TestExpectedCall(false);
2229   TestUninterestingCallOnNaggyMock(false);
2230 }
2231
2232 // Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
2233 // as --gmock_verbose=warning.
2234 TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
2235   GMOCK_FLAG(verbose) = "invalid";  // Treated as "warning".
2236   TestExpectedCall(false);
2237   TestUninterestingCallOnNaggyMock(true);
2238 }
2239
2240 #endif  // GTEST_HAS_STREAM_REDIRECTION
2241
2242 // A helper class that generates a failure when printed.  We use it to
2243 // ensure that Google Mock doesn't print a value (even to an internal
2244 // buffer) when it is not supposed to do so.
2245 class PrintMeNot {};
2246
2247 void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {
2248   ADD_FAILURE() << "Google Mock is printing a value that shouldn't be "
2249                 << "printed even to an internal buffer.";
2250 }
2251
2252 class LogTestHelper {
2253  public:
2254   LogTestHelper() {}
2255
2256   MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
2257
2258  private:
2259   GTEST_DISALLOW_COPY_AND_ASSIGN_(LogTestHelper);
2260 };
2261
2262 class GMockLogTest : public VerboseFlagPreservingFixture {
2263  protected:
2264   LogTestHelper helper_;
2265 };
2266
2267 TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {
2268   GMOCK_FLAG(verbose) = kWarningVerbosity;
2269   EXPECT_CALL(helper_, Foo(_))
2270       .WillOnce(Return(PrintMeNot()));
2271   helper_.Foo(PrintMeNot());  // This is an expected call.
2272 }
2273
2274 TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {
2275   GMOCK_FLAG(verbose) = kErrorVerbosity;
2276   EXPECT_CALL(helper_, Foo(_))
2277       .WillOnce(Return(PrintMeNot()));
2278   helper_.Foo(PrintMeNot());  // This is an expected call.
2279 }
2280
2281 TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {
2282   GMOCK_FLAG(verbose) = kErrorVerbosity;
2283   ON_CALL(helper_, Foo(_))
2284       .WillByDefault(Return(PrintMeNot()));
2285   helper_.Foo(PrintMeNot());  // This should generate a warning.
2286 }
2287
2288 // Tests Mock::AllowLeak().
2289
2290 TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {
2291   MockA* a = new MockA;
2292   Mock::AllowLeak(a);
2293 }
2294
2295 TEST(AllowLeakTest, CanBeCalledBeforeOnCall) {
2296   MockA* a = new MockA;
2297   Mock::AllowLeak(a);
2298   ON_CALL(*a, DoA(_)).WillByDefault(Return());
2299   a->DoA(0);
2300 }
2301
2302 TEST(AllowLeakTest, CanBeCalledAfterOnCall) {
2303   MockA* a = new MockA;
2304   ON_CALL(*a, DoA(_)).WillByDefault(Return());
2305   Mock::AllowLeak(a);
2306 }
2307
2308 TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) {
2309   MockA* a = new MockA;
2310   Mock::AllowLeak(a);
2311   EXPECT_CALL(*a, DoA(_));
2312   a->DoA(0);
2313 }
2314
2315 TEST(AllowLeakTest, CanBeCalledAfterExpectCall) {
2316   MockA* a = new MockA;
2317   EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2318   Mock::AllowLeak(a);
2319 }
2320
2321 TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) {
2322   MockA* a = new MockA;
2323   ON_CALL(*a, DoA(_)).WillByDefault(Return());
2324   EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2325   Mock::AllowLeak(a);
2326 }
2327
2328 // Tests that we can verify and clear a mock object's expectations
2329 // when none of its methods has expectations.
2330 TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {
2331   MockB b;
2332   ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2333
2334   // There should be no expectations on the methods now, so we can
2335   // freely call them.
2336   EXPECT_EQ(0, b.DoB());
2337   EXPECT_EQ(0, b.DoB(1));
2338 }
2339
2340 // Tests that we can verify and clear a mock object's expectations
2341 // when some, but not all, of its methods have expectations *and* the
2342 // verification succeeds.
2343 TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
2344   MockB b;
2345   EXPECT_CALL(b, DoB())
2346       .WillOnce(Return(1));
2347   b.DoB();
2348   ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2349
2350   // There should be no expectations on the methods now, so we can
2351   // freely call them.
2352   EXPECT_EQ(0, b.DoB());
2353   EXPECT_EQ(0, b.DoB(1));
2354 }
2355
2356 // Tests that we can verify and clear a mock object's expectations
2357 // when some, but not all, of its methods have expectations *and* the
2358 // verification fails.
2359 TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
2360   MockB b;
2361   EXPECT_CALL(b, DoB())
2362       .WillOnce(Return(1));
2363   bool result = true;
2364   EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2365                           "Actual: never called");
2366   ASSERT_FALSE(result);
2367
2368   // There should be no expectations on the methods now, so we can
2369   // freely call them.
2370   EXPECT_EQ(0, b.DoB());
2371   EXPECT_EQ(0, b.DoB(1));
2372 }
2373
2374 // Tests that we can verify and clear a mock object's expectations
2375 // when all of its methods have expectations.
2376 TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
2377   MockB b;
2378   EXPECT_CALL(b, DoB())
2379       .WillOnce(Return(1));
2380   EXPECT_CALL(b, DoB(_))
2381       .WillOnce(Return(2));
2382   b.DoB();
2383   b.DoB(1);
2384   ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2385
2386   // There should be no expectations on the methods now, so we can
2387   // freely call them.
2388   EXPECT_EQ(0, b.DoB());
2389   EXPECT_EQ(0, b.DoB(1));
2390 }
2391
2392 // Tests that we can verify and clear a mock object's expectations
2393 // when a method has more than one expectation.
2394 TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
2395   MockB b;
2396   EXPECT_CALL(b, DoB(0))
2397       .WillOnce(Return(1));
2398   EXPECT_CALL(b, DoB(_))
2399       .WillOnce(Return(2));
2400   b.DoB(1);
2401   bool result = true;
2402   EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2403                           "Actual: never called");
2404   ASSERT_FALSE(result);
2405
2406   // There should be no expectations on the methods now, so we can
2407   // freely call them.
2408   EXPECT_EQ(0, b.DoB());
2409   EXPECT_EQ(0, b.DoB(1));
2410 }
2411
2412 // Tests that we can call VerifyAndClearExpectations() on the same
2413 // mock object multiple times.
2414 TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
2415   MockB b;
2416   EXPECT_CALL(b, DoB());
2417   b.DoB();
2418   Mock::VerifyAndClearExpectations(&b);
2419
2420   EXPECT_CALL(b, DoB(_))
2421       .WillOnce(Return(1));
2422   b.DoB(1);
2423   Mock::VerifyAndClearExpectations(&b);
2424   Mock::VerifyAndClearExpectations(&b);
2425
2426   // There should be no expectations on the methods now, so we can
2427   // freely call them.
2428   EXPECT_EQ(0, b.DoB());
2429   EXPECT_EQ(0, b.DoB(1));
2430 }
2431
2432 // Tests that we can clear a mock object's default actions when none
2433 // of its methods has default actions.
2434 TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {
2435   MockB b;
2436   // If this crashes or generates a failure, the test will catch it.
2437   Mock::VerifyAndClear(&b);
2438   EXPECT_EQ(0, b.DoB());
2439 }
2440
2441 // Tests that we can clear a mock object's default actions when some,
2442 // but not all of its methods have default actions.
2443 TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
2444   MockB b;
2445   ON_CALL(b, DoB())
2446       .WillByDefault(Return(1));
2447
2448   Mock::VerifyAndClear(&b);
2449
2450   // Verifies that the default action of int DoB() was removed.
2451   EXPECT_EQ(0, b.DoB());
2452 }
2453
2454 // Tests that we can clear a mock object's default actions when all of
2455 // its methods have default actions.
2456 TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
2457   MockB b;
2458   ON_CALL(b, DoB())
2459       .WillByDefault(Return(1));
2460   ON_CALL(b, DoB(_))
2461       .WillByDefault(Return(2));
2462
2463   Mock::VerifyAndClear(&b);
2464
2465   // Verifies that the default action of int DoB() was removed.
2466   EXPECT_EQ(0, b.DoB());
2467
2468   // Verifies that the default action of int DoB(int) was removed.
2469   EXPECT_EQ(0, b.DoB(0));
2470 }
2471
2472 // Tests that we can clear a mock object's default actions when a
2473 // method has more than one ON_CALL() set on it.
2474 TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
2475   MockB b;
2476   ON_CALL(b, DoB(0))
2477       .WillByDefault(Return(1));
2478   ON_CALL(b, DoB(_))
2479       .WillByDefault(Return(2));
2480
2481   Mock::VerifyAndClear(&b);
2482
2483   // Verifies that the default actions (there are two) of int DoB(int)
2484   // were removed.
2485   EXPECT_EQ(0, b.DoB(0));
2486   EXPECT_EQ(0, b.DoB(1));
2487 }
2488
2489 // Tests that we can call VerifyAndClear() on a mock object multiple
2490 // times.
2491 TEST(VerifyAndClearTest, CanCallManyTimes) {
2492   MockB b;
2493   ON_CALL(b, DoB())
2494       .WillByDefault(Return(1));
2495   Mock::VerifyAndClear(&b);
2496   Mock::VerifyAndClear(&b);
2497
2498   ON_CALL(b, DoB(_))
2499       .WillByDefault(Return(1));
2500   Mock::VerifyAndClear(&b);
2501
2502   EXPECT_EQ(0, b.DoB());
2503   EXPECT_EQ(0, b.DoB(1));
2504 }
2505
2506 // Tests that VerifyAndClear() works when the verification succeeds.
2507 TEST(VerifyAndClearTest, Success) {
2508   MockB b;
2509   ON_CALL(b, DoB())
2510       .WillByDefault(Return(1));
2511   EXPECT_CALL(b, DoB(1))
2512       .WillOnce(Return(2));
2513
2514   b.DoB();
2515   b.DoB(1);
2516   ASSERT_TRUE(Mock::VerifyAndClear(&b));
2517
2518   // There should be no expectations on the methods now, so we can
2519   // freely call them.
2520   EXPECT_EQ(0, b.DoB());
2521   EXPECT_EQ(0, b.DoB(1));
2522 }
2523
2524 // Tests that VerifyAndClear() works when the verification fails.
2525 TEST(VerifyAndClearTest, Failure) {
2526   MockB b;
2527   ON_CALL(b, DoB(_))
2528       .WillByDefault(Return(1));
2529   EXPECT_CALL(b, DoB())
2530       .WillOnce(Return(2));
2531
2532   b.DoB(1);
2533   bool result = true;
2534   EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),
2535                           "Actual: never called");
2536   ASSERT_FALSE(result);
2537
2538   // There should be no expectations on the methods now, so we can
2539   // freely call them.
2540   EXPECT_EQ(0, b.DoB());
2541   EXPECT_EQ(0, b.DoB(1));
2542 }
2543
2544 // Tests that VerifyAndClear() works when the default actions and
2545 // expectations are set on a const mock object.
2546 TEST(VerifyAndClearTest, Const) {
2547   MockB b;
2548   ON_CALL(Const(b), DoB())
2549       .WillByDefault(Return(1));
2550
2551   EXPECT_CALL(Const(b), DoB())
2552       .WillOnce(DoDefault())
2553       .WillOnce(Return(2));
2554
2555   b.DoB();
2556   b.DoB();
2557   ASSERT_TRUE(Mock::VerifyAndClear(&b));
2558
2559   // There should be no expectations on the methods now, so we can
2560   // freely call them.
2561   EXPECT_EQ(0, b.DoB());
2562   EXPECT_EQ(0, b.DoB(1));
2563 }
2564
2565 // Tests that we can set default actions and expectations on a mock
2566 // object after VerifyAndClear() has been called on it.
2567 TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
2568   MockB b;
2569   ON_CALL(b, DoB())
2570       .WillByDefault(Return(1));
2571   EXPECT_CALL(b, DoB(_))
2572       .WillOnce(Return(2));
2573   b.DoB(1);
2574
2575   Mock::VerifyAndClear(&b);
2576
2577   EXPECT_CALL(b, DoB())
2578       .WillOnce(Return(3));
2579   ON_CALL(b, DoB(_))
2580       .WillByDefault(Return(4));
2581
2582   EXPECT_EQ(3, b.DoB());
2583   EXPECT_EQ(4, b.DoB(1));
2584 }
2585
2586 // Tests that calling VerifyAndClear() on one mock object does not
2587 // affect other mock objects (either of the same type or not).
2588 TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
2589   MockA a;
2590   MockB b1;
2591   MockB b2;
2592
2593   ON_CALL(a, Binary(_, _))
2594       .WillByDefault(Return(true));
2595   EXPECT_CALL(a, Binary(_, _))
2596       .WillOnce(DoDefault())
2597       .WillOnce(Return(false));
2598
2599   ON_CALL(b1, DoB())
2600       .WillByDefault(Return(1));
2601   EXPECT_CALL(b1, DoB(_))
2602       .WillOnce(Return(2));
2603
2604   ON_CALL(b2, DoB())
2605       .WillByDefault(Return(3));
2606   EXPECT_CALL(b2, DoB(_));
2607
2608   b2.DoB(0);
2609   Mock::VerifyAndClear(&b2);
2610
2611   // Verifies that the default actions and expectations of a and b1
2612   // are still in effect.
2613   EXPECT_TRUE(a.Binary(0, 0));
2614   EXPECT_FALSE(a.Binary(0, 0));
2615
2616   EXPECT_EQ(1, b1.DoB());
2617   EXPECT_EQ(2, b1.DoB(0));
2618 }
2619
2620 TEST(VerifyAndClearTest,
2621      DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {
2622   linked_ptr<MockA> a(new MockA);
2623   ReferenceHoldingMock test_mock;
2624
2625   // EXPECT_CALL stores a reference to a inside test_mock.
2626   EXPECT_CALL(test_mock, AcceptReference(_))
2627       .WillRepeatedly(SetArgPointee<0>(a));
2628
2629   // Throw away the reference to the mock that we have in a. After this, the
2630   // only reference to it is stored by test_mock.
2631   a.reset();
2632
2633   // When test_mock goes out of scope, it destroys the last remaining reference
2634   // to the mock object originally pointed to by a. This will cause the MockA
2635   // destructor to be called from inside the ReferenceHoldingMock destructor.
2636   // The state of all mocks is protected by a single global lock, but there
2637   // should be no deadlock.
2638 }
2639
2640 TEST(VerifyAndClearTest,
2641      DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {
2642   linked_ptr<MockA> a(new MockA);
2643   ReferenceHoldingMock test_mock;
2644
2645   // ON_CALL stores a reference to a inside test_mock.
2646   ON_CALL(test_mock, AcceptReference(_))
2647       .WillByDefault(SetArgPointee<0>(a));
2648
2649   // Throw away the reference to the mock that we have in a. After this, the
2650   // only reference to it is stored by test_mock.
2651   a.reset();
2652
2653   // When test_mock goes out of scope, it destroys the last remaining reference
2654   // to the mock object originally pointed to by a. This will cause the MockA
2655   // destructor to be called from inside the ReferenceHoldingMock destructor.
2656   // The state of all mocks is protected by a single global lock, but there
2657   // should be no deadlock.
2658 }
2659
2660 // Tests that a mock function's action can call a mock function
2661 // (either the same function or a different one) either as an explicit
2662 // action or as a default action without causing a dead lock.  It
2663 // verifies that the action is not performed inside the critical
2664 // section.
2665 TEST(SynchronizationTest, CanCallMockMethodInAction) {
2666   MockA a;
2667   MockC c;
2668   ON_CALL(a, DoA(_))
2669       .WillByDefault(IgnoreResult(InvokeWithoutArgs(&c,
2670                                                     &MockC::NonVoidMethod)));
2671   EXPECT_CALL(a, DoA(1));
2672   EXPECT_CALL(a, DoA(1))
2673       .WillOnce(Invoke(&a, &MockA::DoA))
2674       .RetiresOnSaturation();
2675   EXPECT_CALL(c, NonVoidMethod());
2676
2677   a.DoA(1);
2678   // This will match the second EXPECT_CALL() and trigger another a.DoA(1),
2679   // which will in turn match the first EXPECT_CALL() and trigger a call to
2680   // c.NonVoidMethod() that was specified by the ON_CALL() since the first
2681   // EXPECT_CALL() did not specify an action.
2682 }
2683
2684 TEST(ParameterlessExpectationsTest, CanSetExpectationsWithoutMatchers) {
2685   MockA a;
2686   int do_a_arg0 = 0;
2687   ON_CALL(a, DoA).WillByDefault(SaveArg<0>(&do_a_arg0));
2688   int do_a_47_arg0 = 0;
2689   ON_CALL(a, DoA(47)).WillByDefault(SaveArg<0>(&do_a_47_arg0));
2690
2691   a.DoA(17);
2692   EXPECT_THAT(do_a_arg0, 17);
2693   EXPECT_THAT(do_a_47_arg0, 0);
2694   a.DoA(47);
2695   EXPECT_THAT(do_a_arg0, 17);
2696   EXPECT_THAT(do_a_47_arg0, 47);
2697
2698   ON_CALL(a, Binary).WillByDefault(Return(true));
2699   ON_CALL(a, Binary(_, 14)).WillByDefault(Return(false));
2700   EXPECT_THAT(a.Binary(14, 17), true);
2701   EXPECT_THAT(a.Binary(17, 14), false);
2702 }
2703
2704 TEST(ParameterlessExpectationsTest, CanSetExpectationsForOverloadedMethods) {
2705   MockB b;
2706   ON_CALL(b, DoB()).WillByDefault(Return(9));
2707   ON_CALL(b, DoB(5)).WillByDefault(Return(11));
2708
2709   EXPECT_THAT(b.DoB(), 9);
2710   EXPECT_THAT(b.DoB(1), 0);  // default value
2711   EXPECT_THAT(b.DoB(5), 11);
2712 }
2713
2714 struct MockWithConstMethods {
2715  public:
2716   MOCK_CONST_METHOD1(Foo, int(int));
2717   MOCK_CONST_METHOD2(Bar, int(int, const char*));
2718 };
2719
2720 TEST(ParameterlessExpectationsTest, CanSetExpectationsForConstMethods) {
2721   MockWithConstMethods mock;
2722   ON_CALL(mock, Foo).WillByDefault(Return(7));
2723   ON_CALL(mock, Bar).WillByDefault(Return(33));
2724
2725   EXPECT_THAT(mock.Foo(17), 7);
2726   EXPECT_THAT(mock.Bar(27, "purple"), 33);
2727 }
2728
2729 class MockConstOverload {
2730  public:
2731   MOCK_METHOD1(Overloaded, int(int));
2732   MOCK_CONST_METHOD1(Overloaded, int(int));
2733 };
2734
2735 TEST(ParameterlessExpectationsTest,
2736      CanSetExpectationsForConstOverloadedMethods) {
2737   MockConstOverload mock;
2738   ON_CALL(mock, Overloaded(_)).WillByDefault(Return(7));
2739   ON_CALL(mock, Overloaded(5)).WillByDefault(Return(9));
2740   ON_CALL(Const(mock), Overloaded(5)).WillByDefault(Return(11));
2741   ON_CALL(Const(mock), Overloaded(7)).WillByDefault(Return(13));
2742
2743   EXPECT_THAT(mock.Overloaded(1), 7);
2744   EXPECT_THAT(mock.Overloaded(5), 9);
2745   EXPECT_THAT(mock.Overloaded(7), 7);
2746
2747   const MockConstOverload& const_mock = mock;
2748   EXPECT_THAT(const_mock.Overloaded(1), 0);
2749   EXPECT_THAT(const_mock.Overloaded(5), 11);
2750   EXPECT_THAT(const_mock.Overloaded(7), 13);
2751 }
2752
2753 }  // namespace
2754
2755 // Allows the user to define their own main and then invoke gmock_main
2756 // from it. This might be necessary on some platforms which require
2757 // specific setup and teardown.
2758 #if GMOCK_RENAME_MAIN
2759 int gmock_main(int argc, char **argv) {
2760 #else
2761 int main(int argc, char **argv) {
2762 #endif  // GMOCK_RENAME_MAIN
2763   testing::InitGoogleMock(&argc, argv);
2764   // Ensures that the tests pass no matter what value of
2765   // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
2766   testing::GMOCK_FLAG(catch_leaked_mocks) = true;
2767   testing::GMOCK_FLAG(verbose) = testing::internal::kWarningVerbosity;
2768
2769   return RUN_ALL_TESTS();
2770 }