Back to home page

sPhenix code displayed by LXR

 
 

    


File indexing completed on 2025-08-06 08:19:58

0001 // Copyright 2007, Google Inc.
0002 // All rights reserved.
0003 //
0004 // Redistribution and use in source and binary forms, with or without
0005 // modification, are permitted provided that the following conditions are
0006 // met:
0007 //
0008 //     * Redistributions of source code must retain the above copyright
0009 // notice, this list of conditions and the following disclaimer.
0010 //     * Redistributions in binary form must reproduce the above
0011 // copyright notice, this list of conditions and the following disclaimer
0012 // in the documentation and/or other materials provided with the
0013 // distribution.
0014 //     * Neither the name of Google Inc. nor the names of its
0015 // contributors may be used to endorse or promote products derived from
0016 // this software without specific prior written permission.
0017 //
0018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
0019 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
0020 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
0021 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
0022 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
0023 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
0024 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
0025 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
0026 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
0027 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
0028 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
0029 //
0030 // Author: wan@google.com (Zhanyong Wan)
0031 
0032 // Google Mock - a framework for writing C++ mock classes.
0033 //
0034 // This file tests the spec builder syntax.
0035 
0036 #include "gmock/gmock-spec-builders.h"
0037 
0038 #include <ostream>  // NOLINT
0039 #include <sstream>
0040 #include <string>
0041 
0042 #include "gmock/gmock.h"
0043 #include "gmock/internal/gmock-port.h"
0044 #include "gtest/gtest.h"
0045 #include "gtest/gtest-spi.h"
0046 #include "gtest/internal/gtest-port.h"
0047 
0048 namespace testing {
0049 namespace internal {
0050 
0051 // Helper class for testing the Expectation class template.
0052 class ExpectationTester {
0053  public:
0054   // Sets the call count of the given expectation to the given number.
0055   void SetCallCount(int n, ExpectationBase* exp) {
0056     exp->call_count_ = n;
0057   }
0058 };
0059 
0060 }  // namespace internal
0061 }  // namespace testing
0062 
0063 namespace {
0064 
0065 using testing::_;
0066 using testing::AnyNumber;
0067 using testing::AtLeast;
0068 using testing::AtMost;
0069 using testing::Between;
0070 using testing::Cardinality;
0071 using testing::CardinalityInterface;
0072 using testing::ContainsRegex;
0073 using testing::Const;
0074 using testing::DoAll;
0075 using testing::DoDefault;
0076 using testing::Eq;
0077 using testing::Expectation;
0078 using testing::ExpectationSet;
0079 using testing::GMOCK_FLAG(verbose);
0080 using testing::Gt;
0081 using testing::InSequence;
0082 using testing::Invoke;
0083 using testing::InvokeWithoutArgs;
0084 using testing::IsNotSubstring;
0085 using testing::IsSubstring;
0086 using testing::Lt;
0087 using testing::Message;
0088 using testing::Mock;
0089 using testing::NaggyMock;
0090 using testing::Ne;
0091 using testing::Return;
0092 using testing::Sequence;
0093 using testing::SetArgPointee;
0094 using testing::internal::ExpectationTester;
0095 using testing::internal::FormatFileLocation;
0096 using testing::internal::kErrorVerbosity;
0097 using testing::internal::kInfoVerbosity;
0098 using testing::internal::kWarningVerbosity;
0099 using testing::internal::linked_ptr;
0100 using testing::internal::string;
0101 
0102 #if GTEST_HAS_STREAM_REDIRECTION
0103 using testing::HasSubstr;
0104 using testing::internal::CaptureStdout;
0105 using testing::internal::GetCapturedStdout;
0106 #endif
0107 
0108 class Incomplete;
0109 
0110 class MockIncomplete {
0111  public:
0112   // This line verifies that a mock method can take a by-reference
0113   // argument of an incomplete type.
0114   MOCK_METHOD1(ByRefFunc, void(const Incomplete& x));
0115 };
0116 
0117 // Tells Google Mock how to print a value of type Incomplete.
0118 void PrintTo(const Incomplete& x, ::std::ostream* os);
0119 
0120 TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) {
0121   // Even though this mock class contains a mock method that takes
0122   // by-reference an argument whose type is incomplete, we can still
0123   // use the mock, as long as Google Mock knows how to print the
0124   // argument.
0125   MockIncomplete incomplete;
0126   EXPECT_CALL(incomplete, ByRefFunc(_))
0127       .Times(AnyNumber());
0128 }
0129 
0130 // The definition of the printer for the argument type doesn't have to
0131 // be visible where the mock is used.
0132 void PrintTo(const Incomplete& /* x */, ::std::ostream* os) {
0133   *os << "incomplete";
0134 }
0135 
0136 class Result {};
0137 
0138 // A type that's not default constructible.
0139 class NonDefaultConstructible {
0140  public:
0141   explicit NonDefaultConstructible(int /* dummy */) {}
0142 };
0143 
0144 class MockA {
0145  public:
0146   MockA() {}
0147 
0148   MOCK_METHOD1(DoA, void(int n));
0149   MOCK_METHOD1(ReturnResult, Result(int n));
0150   MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible());
0151   MOCK_METHOD2(Binary, bool(int x, int y));
0152   MOCK_METHOD2(ReturnInt, int(int x, int y));
0153 
0154  private:
0155   GTEST_DISALLOW_COPY_AND_ASSIGN_(MockA);
0156 };
0157 
0158 class MockB {
0159  public:
0160   MockB() {}
0161 
0162   MOCK_CONST_METHOD0(DoB, int());  // NOLINT
0163   MOCK_METHOD1(DoB, int(int n));  // NOLINT
0164 
0165  private:
0166   GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
0167 };
0168 
0169 class ReferenceHoldingMock {
0170  public:
0171   ReferenceHoldingMock() {}
0172 
0173   MOCK_METHOD1(AcceptReference, void(linked_ptr<MockA>*));
0174 
0175  private:
0176   GTEST_DISALLOW_COPY_AND_ASSIGN_(ReferenceHoldingMock);
0177 };
0178 
0179 // Tests that EXPECT_CALL and ON_CALL compile in a presence of macro
0180 // redefining a mock method name. This could happen, for example, when
0181 // the tested code #includes Win32 API headers which define many APIs
0182 // as macros, e.g. #define TextOut TextOutW.
0183 
0184 #define Method MethodW
0185 
0186 class CC {
0187  public:
0188   virtual ~CC() {}
0189   virtual int Method() = 0;
0190 };
0191 class MockCC : public CC {
0192  public:
0193   MockCC() {}
0194 
0195   MOCK_METHOD0(Method, int());
0196 
0197  private:
0198   GTEST_DISALLOW_COPY_AND_ASSIGN_(MockCC);
0199 };
0200 
0201 // Tests that a method with expanded name compiles.
0202 TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
0203   MockCC cc;
0204   ON_CALL(cc, Method());
0205 }
0206 
0207 // Tests that the method with expanded name not only compiles but runs
0208 // and returns a correct value, too.
0209 TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
0210   MockCC cc;
0211   ON_CALL(cc, Method()).WillByDefault(Return(42));
0212   EXPECT_EQ(42, cc.Method());
0213 }
0214 
0215 // Tests that a method with expanded name compiles.
0216 TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
0217   MockCC cc;
0218   EXPECT_CALL(cc, Method());
0219   cc.Method();
0220 }
0221 
0222 // Tests that it works, too.
0223 TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
0224   MockCC cc;
0225   EXPECT_CALL(cc, Method()).WillOnce(Return(42));
0226   EXPECT_EQ(42, cc.Method());
0227 }
0228 
0229 #undef Method  // Done with macro redefinition tests.
0230 
0231 // Tests that ON_CALL evaluates its arguments exactly once as promised
0232 // by Google Mock.
0233 TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
0234   MockA a;
0235   MockA* pa = &a;
0236 
0237   ON_CALL(*pa++, DoA(_));
0238   EXPECT_EQ(&a + 1, pa);
0239 }
0240 
0241 TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
0242   MockA a;
0243   int n = 0;
0244 
0245   ON_CALL(a, DoA(n++));
0246   EXPECT_EQ(1, n);
0247 }
0248 
0249 // Tests that the syntax of ON_CALL() is enforced at run time.
0250 
0251 TEST(OnCallSyntaxTest, WithIsOptional) {
0252   MockA a;
0253 
0254   ON_CALL(a, DoA(5))
0255       .WillByDefault(Return());
0256   ON_CALL(a, DoA(_))
0257       .With(_)
0258       .WillByDefault(Return());
0259 }
0260 
0261 TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) {
0262   MockA a;
0263 
0264   EXPECT_NONFATAL_FAILURE({  // NOLINT
0265     ON_CALL(a, ReturnResult(_))
0266         .With(_)
0267         .With(_)
0268         .WillByDefault(Return(Result()));
0269   }, ".With() cannot appear more than once in an ON_CALL()");
0270 }
0271 
0272 TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
0273   MockA a;
0274 
0275   EXPECT_DEATH_IF_SUPPORTED({
0276     ON_CALL(a, DoA(5));
0277     a.DoA(5);
0278   }, "");
0279 }
0280 
0281 TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {
0282   MockA a;
0283 
0284   EXPECT_NONFATAL_FAILURE({  // NOLINT
0285     ON_CALL(a, DoA(5))
0286         .WillByDefault(Return())
0287         .WillByDefault(Return());
0288   }, ".WillByDefault() must appear exactly once in an ON_CALL()");
0289 }
0290 
0291 // Tests that EXPECT_CALL evaluates its arguments exactly once as
0292 // promised by Google Mock.
0293 TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) {
0294   MockA a;
0295   MockA* pa = &a;
0296 
0297   EXPECT_CALL(*pa++, DoA(_));
0298   a.DoA(0);
0299   EXPECT_EQ(&a + 1, pa);
0300 }
0301 
0302 TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) {
0303   MockA a;
0304   int n = 0;
0305 
0306   EXPECT_CALL(a, DoA(n++));
0307   a.DoA(0);
0308   EXPECT_EQ(1, n);
0309 }
0310 
0311 // Tests that the syntax of EXPECT_CALL() is enforced at run time.
0312 
0313 TEST(ExpectCallSyntaxTest, WithIsOptional) {
0314   MockA a;
0315 
0316   EXPECT_CALL(a, DoA(5))
0317       .Times(0);
0318   EXPECT_CALL(a, DoA(6))
0319       .With(_)
0320       .Times(0);
0321 }
0322 
0323 TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {
0324   MockA a;
0325 
0326   EXPECT_NONFATAL_FAILURE({  // NOLINT
0327     EXPECT_CALL(a, DoA(6))
0328         .With(_)
0329         .With(_);
0330   }, ".With() cannot appear more than once in an EXPECT_CALL()");
0331 
0332   a.DoA(6);
0333 }
0334 
0335 TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {
0336   MockA a;
0337 
0338   EXPECT_NONFATAL_FAILURE({  // NOLINT
0339     EXPECT_CALL(a, DoA(1))
0340         .Times(1)
0341         .With(_);
0342   }, ".With() must be the first clause in an EXPECT_CALL()");
0343 
0344   a.DoA(1);
0345 
0346   EXPECT_NONFATAL_FAILURE({  // NOLINT
0347     EXPECT_CALL(a, DoA(2))
0348         .WillOnce(Return())
0349         .With(_);
0350   }, ".With() must be the first clause in an EXPECT_CALL()");
0351 
0352   a.DoA(2);
0353 }
0354 
0355 TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {
0356   MockA a;
0357 
0358   EXPECT_CALL(a, DoA(1))
0359       .WillOnce(Return());
0360 
0361   EXPECT_CALL(a, DoA(2))
0362       .WillOnce(Return())
0363       .WillRepeatedly(Return());
0364 
0365   a.DoA(1);
0366   a.DoA(2);
0367   a.DoA(2);
0368 }
0369 
0370 TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {
0371   MockA a;
0372 
0373   EXPECT_NONFATAL_FAILURE({  // NOLINT
0374     EXPECT_CALL(a, DoA(1))
0375         .Times(1)
0376         .Times(2);
0377   }, ".Times() cannot appear more than once in an EXPECT_CALL()");
0378 
0379   a.DoA(1);
0380   a.DoA(1);
0381 }
0382 
0383 TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {
0384   MockA a;
0385   Sequence s;
0386 
0387   EXPECT_NONFATAL_FAILURE({  // NOLINT
0388     EXPECT_CALL(a, DoA(1))
0389         .InSequence(s)
0390         .Times(1);
0391   }, ".Times() cannot appear after ");
0392 
0393   a.DoA(1);
0394 }
0395 
0396 TEST(ExpectCallSyntaxTest, InSequenceIsOptional) {
0397   MockA a;
0398   Sequence s;
0399 
0400   EXPECT_CALL(a, DoA(1));
0401   EXPECT_CALL(a, DoA(2))
0402       .InSequence(s);
0403 
0404   a.DoA(1);
0405   a.DoA(2);
0406 }
0407 
0408 TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {
0409   MockA a;
0410   Sequence s1, s2;
0411 
0412   EXPECT_CALL(a, DoA(1))
0413       .InSequence(s1, s2)
0414       .InSequence(s1);
0415 
0416   a.DoA(1);
0417 }
0418 
0419 TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) {
0420   MockA a;
0421   Sequence s;
0422 
0423   Expectation e = EXPECT_CALL(a, DoA(1))
0424       .Times(AnyNumber());
0425   EXPECT_NONFATAL_FAILURE({  // NOLINT
0426     EXPECT_CALL(a, DoA(2))
0427         .After(e)
0428         .InSequence(s);
0429   }, ".InSequence() cannot appear after ");
0430 
0431   a.DoA(2);
0432 }
0433 
0434 TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) {
0435   MockA a;
0436   Sequence s;
0437 
0438   EXPECT_NONFATAL_FAILURE({  // NOLINT
0439     EXPECT_CALL(a, DoA(1))
0440         .WillOnce(Return())
0441         .InSequence(s);
0442   }, ".InSequence() cannot appear after ");
0443 
0444   a.DoA(1);
0445 }
0446 
0447 TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) {
0448   MockA a;
0449 
0450   Expectation e = EXPECT_CALL(a, DoA(1));
0451   EXPECT_NONFATAL_FAILURE({
0452     EXPECT_CALL(a, DoA(2))
0453         .WillOnce(Return())
0454         .After(e);
0455   }, ".After() cannot appear after ");
0456 
0457   a.DoA(1);
0458   a.DoA(2);
0459 }
0460 
0461 TEST(ExpectCallSyntaxTest, WillIsOptional) {
0462   MockA a;
0463 
0464   EXPECT_CALL(a, DoA(1));
0465   EXPECT_CALL(a, DoA(2))
0466       .WillOnce(Return());
0467 
0468   a.DoA(1);
0469   a.DoA(2);
0470 }
0471 
0472 TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {
0473   MockA a;
0474 
0475   EXPECT_CALL(a, DoA(1))
0476       .Times(AnyNumber())
0477       .WillOnce(Return())
0478       .WillOnce(Return())
0479       .WillOnce(Return());
0480 }
0481 
0482 TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {
0483   MockA a;
0484 
0485   EXPECT_NONFATAL_FAILURE({  // NOLINT
0486     EXPECT_CALL(a, DoA(1))
0487         .WillRepeatedly(Return())
0488         .WillOnce(Return());
0489   }, ".WillOnce() cannot appear after ");
0490 
0491   a.DoA(1);
0492 }
0493 
0494 TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {
0495   MockA a;
0496 
0497   EXPECT_CALL(a, DoA(1))
0498       .WillOnce(Return());
0499   EXPECT_CALL(a, DoA(2))
0500       .WillOnce(Return())
0501       .WillRepeatedly(Return());
0502 
0503   a.DoA(1);
0504   a.DoA(2);
0505   a.DoA(2);
0506 }
0507 
0508 TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {
0509   MockA a;
0510 
0511   EXPECT_NONFATAL_FAILURE({  // NOLINT
0512     EXPECT_CALL(a, DoA(1))
0513         .WillRepeatedly(Return())
0514         .WillRepeatedly(Return());
0515   }, ".WillRepeatedly() cannot appear more than once in an "
0516      "EXPECT_CALL()");
0517 }
0518 
0519 TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {
0520   MockA a;
0521 
0522   EXPECT_NONFATAL_FAILURE({  // NOLINT
0523     EXPECT_CALL(a, DoA(1))
0524         .RetiresOnSaturation()
0525         .WillRepeatedly(Return());
0526   }, ".WillRepeatedly() cannot appear after ");
0527 }
0528 
0529 TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {
0530   MockA a;
0531 
0532   EXPECT_CALL(a, DoA(1));
0533   EXPECT_CALL(a, DoA(1))
0534       .RetiresOnSaturation();
0535 
0536   a.DoA(1);
0537   a.DoA(1);
0538 }
0539 
0540 TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {
0541   MockA a;
0542 
0543   EXPECT_NONFATAL_FAILURE({  // NOLINT
0544     EXPECT_CALL(a, DoA(1))
0545         .RetiresOnSaturation()
0546         .RetiresOnSaturation();
0547   }, ".RetiresOnSaturation() cannot appear more than once");
0548 
0549   a.DoA(1);
0550 }
0551 
0552 TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {
0553   {
0554     MockA a;
0555     EXPECT_CALL(a, DoA(1));
0556     a.DoA(1);
0557   }
0558   EXPECT_NONFATAL_FAILURE({  // NOLINT
0559     MockA a;
0560     EXPECT_CALL(a, DoA(1));
0561   }, "to be called once");
0562   EXPECT_NONFATAL_FAILURE({  // NOLINT
0563     MockA a;
0564     EXPECT_CALL(a, DoA(1));
0565     a.DoA(1);
0566     a.DoA(1);
0567   }, "to be called once");
0568 }
0569 
0570 #if GTEST_HAS_STREAM_REDIRECTION
0571 
0572 // Tests that Google Mock doesn't print a warning when the number of
0573 // WillOnce() is adequate.
0574 TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {
0575   CaptureStdout();
0576   {
0577     MockB b;
0578 
0579     // It's always fine to omit WillOnce() entirely.
0580     EXPECT_CALL(b, DoB())
0581         .Times(0);
0582     EXPECT_CALL(b, DoB(1))
0583         .Times(AtMost(1));
0584     EXPECT_CALL(b, DoB(2))
0585         .Times(1)
0586         .WillRepeatedly(Return(1));
0587 
0588     // It's fine for the number of WillOnce()s to equal the upper bound.
0589     EXPECT_CALL(b, DoB(3))
0590         .Times(Between(1, 2))
0591         .WillOnce(Return(1))
0592         .WillOnce(Return(2));
0593 
0594     // It's fine for the number of WillOnce()s to be smaller than the
0595     // upper bound when there is a WillRepeatedly().
0596     EXPECT_CALL(b, DoB(4))
0597         .Times(AtMost(3))
0598         .WillOnce(Return(1))
0599         .WillRepeatedly(Return(2));
0600 
0601     // Satisfies the above expectations.
0602     b.DoB(2);
0603     b.DoB(3);
0604   }
0605   EXPECT_STREQ("", GetCapturedStdout().c_str());
0606 }
0607 
0608 // Tests that Google Mock warns on having too many actions in an
0609 // expectation compared to its cardinality.
0610 TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
0611   CaptureStdout();
0612   {
0613     MockB b;
0614 
0615     // Warns when the number of WillOnce()s is larger than the upper bound.
0616     EXPECT_CALL(b, DoB())
0617         .Times(0)
0618         .WillOnce(Return(1));  // #1
0619     EXPECT_CALL(b, DoB())
0620         .Times(AtMost(1))
0621         .WillOnce(Return(1))
0622         .WillOnce(Return(2));  // #2
0623     EXPECT_CALL(b, DoB(1))
0624         .Times(1)
0625         .WillOnce(Return(1))
0626         .WillOnce(Return(2))
0627         .RetiresOnSaturation();  // #3
0628 
0629     // Warns when the number of WillOnce()s equals the upper bound and
0630     // there is a WillRepeatedly().
0631     EXPECT_CALL(b, DoB())
0632         .Times(0)
0633         .WillRepeatedly(Return(1));  // #4
0634     EXPECT_CALL(b, DoB(2))
0635         .Times(1)
0636         .WillOnce(Return(1))
0637         .WillRepeatedly(Return(2));  // #5
0638 
0639     // Satisfies the above expectations.
0640     b.DoB(1);
0641     b.DoB(2);
0642   }
0643   const std::string output = GetCapturedStdout();
0644   EXPECT_PRED_FORMAT2(
0645       IsSubstring,
0646       "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
0647       "Expected to be never called, but has 1 WillOnce().",
0648       output);  // #1
0649   EXPECT_PRED_FORMAT2(
0650       IsSubstring,
0651       "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
0652       "Expected to be called at most once, "
0653       "but has 2 WillOnce()s.",
0654       output);  // #2
0655   EXPECT_PRED_FORMAT2(
0656       IsSubstring,
0657       "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n"
0658       "Expected to be called once, but has 2 WillOnce()s.",
0659       output);  // #3
0660   EXPECT_PRED_FORMAT2(
0661       IsSubstring,
0662       "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
0663       "Expected to be never called, but has 0 WillOnce()s "
0664       "and a WillRepeatedly().",
0665       output);  // #4
0666   EXPECT_PRED_FORMAT2(
0667       IsSubstring,
0668       "Too many actions specified in EXPECT_CALL(b, DoB(2))...\n"
0669       "Expected to be called once, but has 1 WillOnce() "
0670       "and a WillRepeatedly().",
0671       output);  // #5
0672 }
0673 
0674 // Tests that Google Mock warns on having too few actions in an
0675 // expectation compared to its cardinality.
0676 TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
0677   MockB b;
0678 
0679   EXPECT_CALL(b, DoB())
0680       .Times(Between(2, 3))
0681       .WillOnce(Return(1));
0682 
0683   CaptureStdout();
0684   b.DoB();
0685   const std::string output = GetCapturedStdout();
0686   EXPECT_PRED_FORMAT2(
0687       IsSubstring,
0688       "Too few actions specified in EXPECT_CALL(b, DoB())...\n"
0689       "Expected to be called between 2 and 3 times, "
0690       "but has only 1 WillOnce().",
0691       output);
0692   b.DoB();
0693 }
0694 
0695 #endif  // GTEST_HAS_STREAM_REDIRECTION
0696 
0697 // Tests the semantics of ON_CALL().
0698 
0699 // Tests that the built-in default action is taken when no ON_CALL()
0700 // is specified.
0701 TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {
0702   MockB b;
0703   EXPECT_CALL(b, DoB());
0704 
0705   EXPECT_EQ(0, b.DoB());
0706 }
0707 
0708 // Tests that the built-in default action is taken when no ON_CALL()
0709 // matches the invocation.
0710 TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {
0711   MockB b;
0712   ON_CALL(b, DoB(1))
0713       .WillByDefault(Return(1));
0714   EXPECT_CALL(b, DoB(_));
0715 
0716   EXPECT_EQ(0, b.DoB(2));
0717 }
0718 
0719 // Tests that the last matching ON_CALL() action is taken.
0720 TEST(OnCallTest, PicksLastMatchingOnCall) {
0721   MockB b;
0722   ON_CALL(b, DoB(_))
0723       .WillByDefault(Return(3));
0724   ON_CALL(b, DoB(2))
0725       .WillByDefault(Return(2));
0726   ON_CALL(b, DoB(1))
0727       .WillByDefault(Return(1));
0728   EXPECT_CALL(b, DoB(_));
0729 
0730   EXPECT_EQ(2, b.DoB(2));
0731 }
0732 
0733 // Tests the semantics of EXPECT_CALL().
0734 
0735 // Tests that any call is allowed when no EXPECT_CALL() is specified.
0736 TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {
0737   MockB b;
0738   EXPECT_CALL(b, DoB());
0739   // There is no expectation on DoB(int).
0740 
0741   b.DoB();
0742 
0743   // DoB(int) can be called any number of times.
0744   b.DoB(1);
0745   b.DoB(2);
0746 }
0747 
0748 // Tests that the last matching EXPECT_CALL() fires.
0749 TEST(ExpectCallTest, PicksLastMatchingExpectCall) {
0750   MockB b;
0751   EXPECT_CALL(b, DoB(_))
0752       .WillRepeatedly(Return(2));
0753   EXPECT_CALL(b, DoB(1))
0754       .WillRepeatedly(Return(1));
0755 
0756   EXPECT_EQ(1, b.DoB(1));
0757 }
0758 
0759 // Tests lower-bound violation.
0760 TEST(ExpectCallTest, CatchesTooFewCalls) {
0761   EXPECT_NONFATAL_FAILURE({  // NOLINT
0762     MockB b;
0763     EXPECT_CALL(b, DoB(5))
0764         .Times(AtLeast(2));
0765 
0766     b.DoB(5);
0767   }, "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n"
0768      "         Expected: to be called at least twice\n"
0769      "           Actual: called once - unsatisfied and active");
0770 }
0771 
0772 // Tests that the cardinality can be inferred when no Times(...) is
0773 // specified.
0774 TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {
0775   {
0776     MockB b;
0777     EXPECT_CALL(b, DoB())
0778         .WillOnce(Return(1))
0779         .WillOnce(Return(2));
0780 
0781     EXPECT_EQ(1, b.DoB());
0782     EXPECT_EQ(2, b.DoB());
0783   }
0784 
0785   EXPECT_NONFATAL_FAILURE({  // NOLINT
0786     MockB b;
0787     EXPECT_CALL(b, DoB())
0788         .WillOnce(Return(1))
0789         .WillOnce(Return(2));
0790 
0791     EXPECT_EQ(1, b.DoB());
0792   }, "to be called twice");
0793 
0794   {  // NOLINT
0795     MockB b;
0796     EXPECT_CALL(b, DoB())
0797         .WillOnce(Return(1))
0798         .WillOnce(Return(2));
0799 
0800     EXPECT_EQ(1, b.DoB());
0801     EXPECT_EQ(2, b.DoB());
0802     EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice");
0803   }
0804 }
0805 
0806 TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
0807   {
0808     MockB b;
0809     EXPECT_CALL(b, DoB())
0810         .WillOnce(Return(1))
0811         .WillRepeatedly(Return(2));
0812 
0813     EXPECT_EQ(1, b.DoB());
0814   }
0815 
0816   {  // NOLINT
0817     MockB b;
0818     EXPECT_CALL(b, DoB())
0819         .WillOnce(Return(1))
0820         .WillRepeatedly(Return(2));
0821 
0822     EXPECT_EQ(1, b.DoB());
0823     EXPECT_EQ(2, b.DoB());
0824     EXPECT_EQ(2, b.DoB());
0825   }
0826 
0827   EXPECT_NONFATAL_FAILURE({  // NOLINT
0828     MockB b;
0829     EXPECT_CALL(b, DoB())
0830         .WillOnce(Return(1))
0831         .WillRepeatedly(Return(2));
0832   }, "to be called at least once");
0833 }
0834 
0835 // Tests that the n-th action is taken for the n-th matching
0836 // invocation.
0837 TEST(ExpectCallTest, NthMatchTakesNthAction) {
0838   MockB b;
0839   EXPECT_CALL(b, DoB())
0840       .WillOnce(Return(1))
0841       .WillOnce(Return(2))
0842       .WillOnce(Return(3));
0843 
0844   EXPECT_EQ(1, b.DoB());
0845   EXPECT_EQ(2, b.DoB());
0846   EXPECT_EQ(3, b.DoB());
0847 }
0848 
0849 // Tests that the WillRepeatedly() action is taken when the WillOnce(...)
0850 // list is exhausted.
0851 TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
0852   MockB b;
0853   EXPECT_CALL(b, DoB())
0854       .WillOnce(Return(1))
0855       .WillRepeatedly(Return(2));
0856 
0857   EXPECT_EQ(1, b.DoB());
0858   EXPECT_EQ(2, b.DoB());
0859   EXPECT_EQ(2, b.DoB());
0860 }
0861 
0862 #if GTEST_HAS_STREAM_REDIRECTION
0863 
0864 // Tests that the default action is taken when the WillOnce(...) list is
0865 // exhausted and there is no WillRepeatedly().
0866 TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
0867   MockB b;
0868   EXPECT_CALL(b, DoB(_))
0869       .Times(1);
0870   EXPECT_CALL(b, DoB())
0871       .Times(AnyNumber())
0872       .WillOnce(Return(1))
0873       .WillOnce(Return(2));
0874 
0875   CaptureStdout();
0876   EXPECT_EQ(0, b.DoB(1));  // Shouldn't generate a warning as the
0877                            // expectation has no action clause at all.
0878   EXPECT_EQ(1, b.DoB());
0879   EXPECT_EQ(2, b.DoB());
0880   const std::string output1 = GetCapturedStdout();
0881   EXPECT_STREQ("", output1.c_str());
0882 
0883   CaptureStdout();
0884   EXPECT_EQ(0, b.DoB());
0885   EXPECT_EQ(0, b.DoB());
0886   const std::string output2 = GetCapturedStdout();
0887   EXPECT_THAT(output2.c_str(),
0888               HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
0889                         "Called 3 times, but only 2 WillOnce()s are specified"
0890                         " - returning default value."));
0891   EXPECT_THAT(output2.c_str(),
0892               HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
0893                         "Called 4 times, but only 2 WillOnce()s are specified"
0894                         " - returning default value."));
0895 }
0896 
0897 TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhausedActions) {
0898   MockB b;
0899   std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
0900   EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));
0901 
0902   EXPECT_EQ(1, b.DoB());
0903 
0904   CaptureStdout();
0905   EXPECT_EQ(0, b.DoB());
0906   const std::string output = GetCapturedStdout();
0907   // The warning message should contain the call location.
0908   EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output);
0909 }
0910 
0911 TEST(FunctionMockerMessageTest,
0912      ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) {
0913   std::string on_call_location;
0914   CaptureStdout();
0915   {
0916     NaggyMock<MockB> b;
0917     on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
0918     ON_CALL(b, DoB(_)).WillByDefault(Return(0));
0919     b.DoB(0);
0920   }
0921   EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout());
0922 }
0923 
0924 #endif  // GTEST_HAS_STREAM_REDIRECTION
0925 
0926 // Tests that an uninteresting call performs the default action.
0927 TEST(UninterestingCallTest, DoesDefaultAction) {
0928   // When there is an ON_CALL() statement, the action specified by it
0929   // should be taken.
0930   MockA a;
0931   ON_CALL(a, Binary(_, _))
0932       .WillByDefault(Return(true));
0933   EXPECT_TRUE(a.Binary(1, 2));
0934 
0935   // When there is no ON_CALL(), the default value for the return type
0936   // should be returned.
0937   MockB b;
0938   EXPECT_EQ(0, b.DoB());
0939 }
0940 
0941 // Tests that an unexpected call performs the default action.
0942 TEST(UnexpectedCallTest, DoesDefaultAction) {
0943   // When there is an ON_CALL() statement, the action specified by it
0944   // should be taken.
0945   MockA a;
0946   ON_CALL(a, Binary(_, _))
0947       .WillByDefault(Return(true));
0948   EXPECT_CALL(a, Binary(0, 0));
0949   a.Binary(0, 0);
0950   bool result = false;
0951   EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),
0952                           "Unexpected mock function call");
0953   EXPECT_TRUE(result);
0954 
0955   // When there is no ON_CALL(), the default value for the return type
0956   // should be returned.
0957   MockB b;
0958   EXPECT_CALL(b, DoB(0))
0959       .Times(0);
0960   int n = -1;
0961   EXPECT_NONFATAL_FAILURE(n = b.DoB(1),
0962                           "Unexpected mock function call");
0963   EXPECT_EQ(0, n);
0964 }
0965 
0966 // Tests that when an unexpected void function generates the right
0967 // failure message.
0968 TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {
0969   // First, tests the message when there is only one EXPECT_CALL().
0970   MockA a1;
0971   EXPECT_CALL(a1, DoA(1));
0972   a1.DoA(1);
0973   // Ideally we should match the failure message against a regex, but
0974   // EXPECT_NONFATAL_FAILURE doesn't support that, so we test for
0975   // multiple sub-strings instead.
0976   EXPECT_NONFATAL_FAILURE(
0977       a1.DoA(9),
0978       "Unexpected mock function call - returning directly.\n"
0979       "    Function call: DoA(9)\n"
0980       "Google Mock tried the following 1 expectation, but it didn't match:");
0981   EXPECT_NONFATAL_FAILURE(
0982       a1.DoA(9),
0983       "  Expected arg #0: is equal to 1\n"
0984       "           Actual: 9\n"
0985       "         Expected: to be called once\n"
0986       "           Actual: called once - saturated and active");
0987 
0988   // Next, tests the message when there are more than one EXPECT_CALL().
0989   MockA a2;
0990   EXPECT_CALL(a2, DoA(1));
0991   EXPECT_CALL(a2, DoA(3));
0992   a2.DoA(1);
0993   EXPECT_NONFATAL_FAILURE(
0994       a2.DoA(2),
0995       "Unexpected mock function call - returning directly.\n"
0996       "    Function call: DoA(2)\n"
0997       "Google Mock tried the following 2 expectations, but none matched:");
0998   EXPECT_NONFATAL_FAILURE(
0999       a2.DoA(2),
1000       "tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n"
1001       "  Expected arg #0: is equal to 1\n"
1002       "           Actual: 2\n"
1003       "         Expected: to be called once\n"
1004       "           Actual: called once - saturated and active");
1005   EXPECT_NONFATAL_FAILURE(
1006       a2.DoA(2),
1007       "tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n"
1008       "  Expected arg #0: is equal to 3\n"
1009       "           Actual: 2\n"
1010       "         Expected: to be called once\n"
1011       "           Actual: never called - unsatisfied and active");
1012   a2.DoA(3);
1013 }
1014 
1015 // Tests that an unexpected non-void function generates the right
1016 // failure message.
1017 TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {
1018   MockB b1;
1019   EXPECT_CALL(b1, DoB(1));
1020   b1.DoB(1);
1021   EXPECT_NONFATAL_FAILURE(
1022       b1.DoB(2),
1023       "Unexpected mock function call - returning default value.\n"
1024       "    Function call: DoB(2)\n"
1025       "          Returns: 0\n"
1026       "Google Mock tried the following 1 expectation, but it didn't match:");
1027   EXPECT_NONFATAL_FAILURE(
1028       b1.DoB(2),
1029       "  Expected arg #0: is equal to 1\n"
1030       "           Actual: 2\n"
1031       "         Expected: to be called once\n"
1032       "           Actual: called once - saturated and active");
1033 }
1034 
1035 // Tests that Google Mock explains that an retired expectation doesn't
1036 // match the call.
1037 TEST(UnexpectedCallTest, RetiredExpectation) {
1038   MockB b;
1039   EXPECT_CALL(b, DoB(1))
1040       .RetiresOnSaturation();
1041 
1042   b.DoB(1);
1043   EXPECT_NONFATAL_FAILURE(
1044       b.DoB(1),
1045       "         Expected: the expectation is active\n"
1046       "           Actual: it is retired");
1047 }
1048 
1049 // Tests that Google Mock explains that an expectation that doesn't
1050 // match the arguments doesn't match the call.
1051 TEST(UnexpectedCallTest, UnmatchedArguments) {
1052   MockB b;
1053   EXPECT_CALL(b, DoB(1));
1054 
1055   EXPECT_NONFATAL_FAILURE(
1056       b.DoB(2),
1057       "  Expected arg #0: is equal to 1\n"
1058       "           Actual: 2\n");
1059   b.DoB(1);
1060 }
1061 
1062 // Tests that Google Mock explains that an expectation with
1063 // unsatisfied pre-requisites doesn't match the call.
1064 TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
1065   Sequence s1, s2;
1066   MockB b;
1067   EXPECT_CALL(b, DoB(1))
1068       .InSequence(s1);
1069   EXPECT_CALL(b, DoB(2))
1070       .Times(AnyNumber())
1071       .InSequence(s1);
1072   EXPECT_CALL(b, DoB(3))
1073       .InSequence(s2);
1074   EXPECT_CALL(b, DoB(4))
1075       .InSequence(s1, s2);
1076 
1077   ::testing::TestPartResultArray failures;
1078   {
1079     ::testing::ScopedFakeTestPartResultReporter reporter(&failures);
1080     b.DoB(4);
1081     // Now 'failures' contains the Google Test failures generated by
1082     // the above statement.
1083   }
1084 
1085   // There should be one non-fatal failure.
1086   ASSERT_EQ(1, failures.size());
1087   const ::testing::TestPartResult& r = failures.GetTestPartResult(0);
1088   EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type());
1089 
1090   // Verifies that the failure message contains the two unsatisfied
1091   // pre-requisites but not the satisfied one.
1092 #if GTEST_USES_PCRE
1093   EXPECT_THAT(r.message(), ContainsRegex(
1094       // PCRE has trouble using (.|\n) to match any character, but
1095       // supports the (?s) prefix for using . to match any character.
1096       "(?s)the following immediate pre-requisites are not satisfied:\n"
1097       ".*: pre-requisite #0\n"
1098       ".*: pre-requisite #1"));
1099 #elif GTEST_USES_POSIX_RE
1100   EXPECT_THAT(r.message(), ContainsRegex(
1101       // POSIX RE doesn't understand the (?s) prefix, but has no trouble
1102       // with (.|\n).
1103       "the following immediate pre-requisites are not satisfied:\n"
1104       "(.|\n)*: pre-requisite #0\n"
1105       "(.|\n)*: pre-requisite #1"));
1106 #else
1107   // We can only use Google Test's own simple regex.
1108   EXPECT_THAT(r.message(), ContainsRegex(
1109       "the following immediate pre-requisites are not satisfied:"));
1110   EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));
1111   EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));
1112 #endif  // GTEST_USES_PCRE
1113 
1114   b.DoB(1);
1115   b.DoB(3);
1116   b.DoB(4);
1117 }
1118 
1119 TEST(UndefinedReturnValueTest,
1120      ReturnValueIsMandatoryWhenNotDefaultConstructible) {
1121   MockA a;
1122   // TODO(wan@google.com): We should really verify the output message,
1123   // but we cannot yet due to that EXPECT_DEATH only captures stderr
1124   // while Google Mock logs to stdout.
1125 #if GTEST_HAS_EXCEPTIONS
1126   EXPECT_ANY_THROW(a.ReturnNonDefaultConstructible());
1127 #else
1128   EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), "");
1129 #endif
1130 }
1131 
1132 // Tests that an excessive call (one whose arguments match the
1133 // matchers but is called too many times) performs the default action.
1134 TEST(ExcessiveCallTest, DoesDefaultAction) {
1135   // When there is an ON_CALL() statement, the action specified by it
1136   // should be taken.
1137   MockA a;
1138   ON_CALL(a, Binary(_, _))
1139       .WillByDefault(Return(true));
1140   EXPECT_CALL(a, Binary(0, 0));
1141   a.Binary(0, 0);
1142   bool result = false;
1143   EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),
1144                           "Mock function called more times than expected");
1145   EXPECT_TRUE(result);
1146 
1147   // When there is no ON_CALL(), the default value for the return type
1148   // should be returned.
1149   MockB b;
1150   EXPECT_CALL(b, DoB(0))
1151       .Times(0);
1152   int n = -1;
1153   EXPECT_NONFATAL_FAILURE(n = b.DoB(0),
1154                           "Mock function called more times than expected");
1155   EXPECT_EQ(0, n);
1156 }
1157 
1158 // Tests that when a void function is called too many times,
1159 // the failure message contains the argument values.
1160 TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
1161   MockA a;
1162   EXPECT_CALL(a, DoA(_))
1163       .Times(0);
1164   EXPECT_NONFATAL_FAILURE(
1165       a.DoA(9),
1166       "Mock function called more times than expected - returning directly.\n"
1167       "    Function call: DoA(9)\n"
1168       "         Expected: to be never called\n"
1169       "           Actual: called once - over-saturated and active");
1170 }
1171 
1172 // Tests that when a non-void function is called too many times, the
1173 // failure message contains the argument values and the return value.
1174 TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {
1175   MockB b;
1176   EXPECT_CALL(b, DoB(_));
1177   b.DoB(1);
1178   EXPECT_NONFATAL_FAILURE(
1179       b.DoB(2),
1180       "Mock function called more times than expected - "
1181       "returning default value.\n"
1182       "    Function call: DoB(2)\n"
1183       "          Returns: 0\n"
1184       "         Expected: to be called once\n"
1185       "           Actual: called twice - over-saturated and active");
1186 }
1187 
1188 // Tests using sequences.
1189 
1190 TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {
1191   MockA a;
1192   {
1193     InSequence dummy;
1194 
1195     EXPECT_CALL(a, DoA(1));
1196     EXPECT_CALL(a, DoA(2));
1197   }
1198 
1199   EXPECT_NONFATAL_FAILURE({  // NOLINT
1200     a.DoA(2);
1201   }, "Unexpected mock function call");
1202 
1203   a.DoA(1);
1204   a.DoA(2);
1205 }
1206 
1207 TEST(InSequenceTest, NestedInSequence) {
1208   MockA a;
1209   {
1210     InSequence dummy;
1211 
1212     EXPECT_CALL(a, DoA(1));
1213     {
1214       InSequence dummy2;
1215 
1216       EXPECT_CALL(a, DoA(2));
1217       EXPECT_CALL(a, DoA(3));
1218     }
1219   }
1220 
1221   EXPECT_NONFATAL_FAILURE({  // NOLINT
1222     a.DoA(1);
1223     a.DoA(3);
1224   }, "Unexpected mock function call");
1225 
1226   a.DoA(2);
1227   a.DoA(3);
1228 }
1229 
1230 TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {
1231   MockA a;
1232   {
1233     InSequence dummy;
1234 
1235     EXPECT_CALL(a, DoA(1));
1236     EXPECT_CALL(a, DoA(2));
1237   }
1238   EXPECT_CALL(a, DoA(3));
1239 
1240   EXPECT_NONFATAL_FAILURE({  // NOLINT
1241     a.DoA(2);
1242   }, "Unexpected mock function call");
1243 
1244   a.DoA(3);
1245   a.DoA(1);
1246   a.DoA(2);
1247 }
1248 
1249 // Tests that any order is allowed when no sequence is used.
1250 TEST(SequenceTest, AnyOrderIsOkByDefault) {
1251   {
1252     MockA a;
1253     MockB b;
1254 
1255     EXPECT_CALL(a, DoA(1));
1256     EXPECT_CALL(b, DoB())
1257         .Times(AnyNumber());
1258 
1259     a.DoA(1);
1260     b.DoB();
1261   }
1262 
1263   {  // NOLINT
1264     MockA a;
1265     MockB b;
1266 
1267     EXPECT_CALL(a, DoA(1));
1268     EXPECT_CALL(b, DoB())
1269         .Times(AnyNumber());
1270 
1271     b.DoB();
1272     a.DoA(1);
1273   }
1274 }
1275 
1276 // Tests that the calls must be in strict order when a complete order
1277 // is specified.
1278 TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) {
1279   MockA a;
1280   ON_CALL(a, ReturnResult(_))
1281       .WillByDefault(Return(Result()));
1282 
1283   Sequence s;
1284   EXPECT_CALL(a, ReturnResult(1))
1285       .InSequence(s);
1286   EXPECT_CALL(a, ReturnResult(2))
1287       .InSequence(s);
1288   EXPECT_CALL(a, ReturnResult(3))
1289       .InSequence(s);
1290 
1291   a.ReturnResult(1);
1292 
1293   // May only be called after a.ReturnResult(2).
1294   EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1295 
1296   a.ReturnResult(2);
1297   a.ReturnResult(3);
1298 }
1299 
1300 // Tests that the calls must be in strict order when a complete order
1301 // is specified.
1302 TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) {
1303   MockA a;
1304   ON_CALL(a, ReturnResult(_))
1305       .WillByDefault(Return(Result()));
1306 
1307   Sequence s;
1308   EXPECT_CALL(a, ReturnResult(1))
1309       .InSequence(s);
1310   EXPECT_CALL(a, ReturnResult(2))
1311       .InSequence(s);
1312 
1313   // May only be called after a.ReturnResult(1).
1314   EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call");
1315 
1316   a.ReturnResult(1);
1317   a.ReturnResult(2);
1318 }
1319 
1320 // Tests specifying a DAG using multiple sequences.
1321 class PartialOrderTest : public testing::Test {
1322  protected:
1323   PartialOrderTest() {
1324     ON_CALL(a_, ReturnResult(_))
1325         .WillByDefault(Return(Result()));
1326 
1327     // Specifies this partial ordering:
1328     //
1329     // a.ReturnResult(1) ==>
1330     //                       a.ReturnResult(2) * n  ==>  a.ReturnResult(3)
1331     // b.DoB() * 2       ==>
1332     Sequence x, y;
1333     EXPECT_CALL(a_, ReturnResult(1))
1334         .InSequence(x);
1335     EXPECT_CALL(b_, DoB())
1336         .Times(2)
1337         .InSequence(y);
1338     EXPECT_CALL(a_, ReturnResult(2))
1339         .Times(AnyNumber())
1340         .InSequence(x, y);
1341     EXPECT_CALL(a_, ReturnResult(3))
1342         .InSequence(x);
1343   }
1344 
1345   MockA a_;
1346   MockB b_;
1347 };
1348 
1349 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) {
1350   a_.ReturnResult(1);
1351   b_.DoB();
1352 
1353   // May only be called after the second DoB().
1354   EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1355 
1356   b_.DoB();
1357   a_.ReturnResult(3);
1358 }
1359 
1360 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag2) {
1361   // May only be called after ReturnResult(1).
1362   EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1363 
1364   a_.ReturnResult(1);
1365   b_.DoB();
1366   b_.DoB();
1367   a_.ReturnResult(3);
1368 }
1369 
1370 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag3) {
1371   // May only be called last.
1372   EXPECT_NONFATAL_FAILURE(a_.ReturnResult(3), "Unexpected mock function call");
1373 
1374   a_.ReturnResult(1);
1375   b_.DoB();
1376   b_.DoB();
1377   a_.ReturnResult(3);
1378 }
1379 
1380 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag4) {
1381   a_.ReturnResult(1);
1382   b_.DoB();
1383   b_.DoB();
1384   a_.ReturnResult(3);
1385 
1386   // May only be called before ReturnResult(3).
1387   EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1388 }
1389 
1390 TEST(SequenceTest, Retirement) {
1391   MockA a;
1392   Sequence s;
1393 
1394   EXPECT_CALL(a, DoA(1))
1395       .InSequence(s);
1396   EXPECT_CALL(a, DoA(_))
1397       .InSequence(s)
1398       .RetiresOnSaturation();
1399   EXPECT_CALL(a, DoA(1))
1400       .InSequence(s);
1401 
1402   a.DoA(1);
1403   a.DoA(2);
1404   a.DoA(1);
1405 }
1406 
1407 // Tests Expectation.
1408 
1409 TEST(ExpectationTest, ConstrutorsWork) {
1410   MockA a;
1411   Expectation e1;  // Default ctor.
1412 
1413   // Ctor from various forms of EXPECT_CALL.
1414   Expectation e2 = EXPECT_CALL(a, DoA(2));
1415   Expectation e3 = EXPECT_CALL(a, DoA(3)).With(_);
1416   {
1417     Sequence s;
1418     Expectation e4 = EXPECT_CALL(a, DoA(4)).Times(1);
1419     Expectation e5 = EXPECT_CALL(a, DoA(5)).InSequence(s);
1420   }
1421   Expectation e6 = EXPECT_CALL(a, DoA(6)).After(e2);
1422   Expectation e7 = EXPECT_CALL(a, DoA(7)).WillOnce(Return());
1423   Expectation e8 = EXPECT_CALL(a, DoA(8)).WillRepeatedly(Return());
1424   Expectation e9 = EXPECT_CALL(a, DoA(9)).RetiresOnSaturation();
1425 
1426   Expectation e10 = e2;  // Copy ctor.
1427 
1428   EXPECT_THAT(e1, Ne(e2));
1429   EXPECT_THAT(e2, Eq(e10));
1430 
1431   a.DoA(2);
1432   a.DoA(3);
1433   a.DoA(4);
1434   a.DoA(5);
1435   a.DoA(6);
1436   a.DoA(7);
1437   a.DoA(8);
1438   a.DoA(9);
1439 }
1440 
1441 TEST(ExpectationTest, AssignmentWorks) {
1442   MockA a;
1443   Expectation e1;
1444   Expectation e2 = EXPECT_CALL(a, DoA(1));
1445 
1446   EXPECT_THAT(e1, Ne(e2));
1447 
1448   e1 = e2;
1449   EXPECT_THAT(e1, Eq(e2));
1450 
1451   a.DoA(1);
1452 }
1453 
1454 // Tests ExpectationSet.
1455 
1456 TEST(ExpectationSetTest, MemberTypesAreCorrect) {
1457   ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();
1458 }
1459 
1460 TEST(ExpectationSetTest, ConstructorsWork) {
1461   MockA a;
1462 
1463   Expectation e1;
1464   const Expectation e2;
1465   ExpectationSet es1;  // Default ctor.
1466   ExpectationSet es2 = EXPECT_CALL(a, DoA(1));  // Ctor from EXPECT_CALL.
1467   ExpectationSet es3 = e1;  // Ctor from Expectation.
1468   ExpectationSet es4(e1);   // Ctor from Expectation; alternative syntax.
1469   ExpectationSet es5 = e2;  // Ctor from const Expectation.
1470   ExpectationSet es6(e2);   // Ctor from const Expectation; alternative syntax.
1471   ExpectationSet es7 = es2;  // Copy ctor.
1472 
1473   EXPECT_EQ(0, es1.size());
1474   EXPECT_EQ(1, es2.size());
1475   EXPECT_EQ(1, es3.size());
1476   EXPECT_EQ(1, es4.size());
1477   EXPECT_EQ(1, es5.size());
1478   EXPECT_EQ(1, es6.size());
1479   EXPECT_EQ(1, es7.size());
1480 
1481   EXPECT_THAT(es3, Ne(es2));
1482   EXPECT_THAT(es4, Eq(es3));
1483   EXPECT_THAT(es5, Eq(es4));
1484   EXPECT_THAT(es6, Eq(es5));
1485   EXPECT_THAT(es7, Eq(es2));
1486   a.DoA(1);
1487 }
1488 
1489 TEST(ExpectationSetTest, AssignmentWorks) {
1490   ExpectationSet es1;
1491   ExpectationSet es2 = Expectation();
1492 
1493   es1 = es2;
1494   EXPECT_EQ(1, es1.size());
1495   EXPECT_THAT(*(es1.begin()), Eq(Expectation()));
1496   EXPECT_THAT(es1, Eq(es2));
1497 }
1498 
1499 TEST(ExpectationSetTest, InsertionWorks) {
1500   ExpectationSet es1;
1501   Expectation e1;
1502   es1 += e1;
1503   EXPECT_EQ(1, es1.size());
1504   EXPECT_THAT(*(es1.begin()), Eq(e1));
1505 
1506   MockA a;
1507   Expectation e2 = EXPECT_CALL(a, DoA(1));
1508   es1 += e2;
1509   EXPECT_EQ(2, es1.size());
1510 
1511   ExpectationSet::const_iterator it1 = es1.begin();
1512   ExpectationSet::const_iterator it2 = it1;
1513   ++it2;
1514   EXPECT_TRUE(*it1 == e1 || *it2 == e1);  // e1 must be in the set.
1515   EXPECT_TRUE(*it1 == e2 || *it2 == e2);  // e2 must be in the set too.
1516   a.DoA(1);
1517 }
1518 
1519 TEST(ExpectationSetTest, SizeWorks) {
1520   ExpectationSet es;
1521   EXPECT_EQ(0, es.size());
1522 
1523   es += Expectation();
1524   EXPECT_EQ(1, es.size());
1525 
1526   MockA a;
1527   es += EXPECT_CALL(a, DoA(1));
1528   EXPECT_EQ(2, es.size());
1529 
1530   a.DoA(1);
1531 }
1532 
1533 TEST(ExpectationSetTest, IsEnumerable) {
1534   ExpectationSet es;
1535   EXPECT_TRUE(es.begin() == es.end());
1536 
1537   es += Expectation();
1538   ExpectationSet::const_iterator it = es.begin();
1539   EXPECT_TRUE(it != es.end());
1540   EXPECT_THAT(*it, Eq(Expectation()));
1541   ++it;
1542   EXPECT_TRUE(it== es.end());
1543 }
1544 
1545 // Tests the .After() clause.
1546 
1547 TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {
1548   MockA a;
1549   ExpectationSet es;
1550   es += EXPECT_CALL(a, DoA(1));
1551   es += EXPECT_CALL(a, DoA(2));
1552   EXPECT_CALL(a, DoA(3))
1553       .After(es);
1554 
1555   a.DoA(1);
1556   a.DoA(2);
1557   a.DoA(3);
1558 }
1559 
1560 TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {
1561   MockA a;
1562   MockB b;
1563   // The following also verifies that const Expectation objects work
1564   // too.  Do not remove the const modifiers.
1565   const Expectation e1 = EXPECT_CALL(a, DoA(1));
1566   const Expectation e2 = EXPECT_CALL(b, DoB())
1567       .Times(2)
1568       .After(e1);
1569   EXPECT_CALL(a, DoA(2)).After(e2);
1570 
1571   a.DoA(1);
1572   b.DoB();
1573   b.DoB();
1574   a.DoA(2);
1575 }
1576 
1577 // Calls must be in strict order when specified so using .After().
1578 TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) {
1579   MockA a;
1580   MockB b;
1581 
1582   // Define ordering:
1583   //   a.DoA(1) ==> b.DoB() ==> a.DoA(2)
1584   Expectation e1 = EXPECT_CALL(a, DoA(1));
1585   Expectation e2 = EXPECT_CALL(b, DoB())
1586       .After(e1);
1587   EXPECT_CALL(a, DoA(2))
1588       .After(e2);
1589 
1590   a.DoA(1);
1591 
1592   // May only be called after DoB().
1593   EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
1594 
1595   b.DoB();
1596   a.DoA(2);
1597 }
1598 
1599 // Calls must be in strict order when specified so using .After().
1600 TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) {
1601   MockA a;
1602   MockB b;
1603 
1604   // Define ordering:
1605   //   a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2)
1606   Expectation e1 = EXPECT_CALL(a, DoA(1));
1607   Expectation e2 = EXPECT_CALL(b, DoB())
1608       .Times(2)
1609       .After(e1);
1610   EXPECT_CALL(a, DoA(2))
1611       .After(e2);
1612 
1613   a.DoA(1);
1614   b.DoB();
1615 
1616   // May only be called after the second DoB().
1617   EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
1618 
1619   b.DoB();
1620   a.DoA(2);
1621 }
1622 
1623 // Calls must satisfy the partial order when specified so.
1624 TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {
1625   MockA a;
1626   ON_CALL(a, ReturnResult(_))
1627       .WillByDefault(Return(Result()));
1628 
1629   // Define ordering:
1630   //   a.DoA(1) ==>
1631   //   a.DoA(2) ==> a.ReturnResult(3)
1632   Expectation e = EXPECT_CALL(a, DoA(1));
1633   const ExpectationSet es = EXPECT_CALL(a, DoA(2));
1634   EXPECT_CALL(a, ReturnResult(3))
1635       .After(e, es);
1636 
1637   // May only be called last.
1638   EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1639 
1640   a.DoA(2);
1641   a.DoA(1);
1642   a.ReturnResult(3);
1643 }
1644 
1645 // Calls must satisfy the partial order when specified so.
1646 TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) {
1647   MockA a;
1648 
1649   // Define ordering:
1650   //   a.DoA(1) ==>
1651   //   a.DoA(2) ==> a.DoA(3)
1652   Expectation e = EXPECT_CALL(a, DoA(1));
1653   const ExpectationSet es = EXPECT_CALL(a, DoA(2));
1654   EXPECT_CALL(a, DoA(3))
1655       .After(e, es);
1656 
1657   a.DoA(2);
1658 
1659   // May only be called last.
1660   EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
1661 
1662   a.DoA(1);
1663   a.DoA(3);
1664 }
1665 
1666 // .After() can be combined with .InSequence().
1667 TEST(AfterTest, CanBeUsedWithInSequence) {
1668   MockA a;
1669   Sequence s;
1670   Expectation e = EXPECT_CALL(a, DoA(1));
1671   EXPECT_CALL(a, DoA(2)).InSequence(s);
1672   EXPECT_CALL(a, DoA(3))
1673       .InSequence(s)
1674       .After(e);
1675 
1676   a.DoA(1);
1677 
1678   // May only be after DoA(2).
1679   EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
1680 
1681   a.DoA(2);
1682   a.DoA(3);
1683 }
1684 
1685 // .After() can be called multiple times.
1686 TEST(AfterTest, CanBeCalledManyTimes) {
1687   MockA a;
1688   Expectation e1 = EXPECT_CALL(a, DoA(1));
1689   Expectation e2 = EXPECT_CALL(a, DoA(2));
1690   Expectation e3 = EXPECT_CALL(a, DoA(3));
1691   EXPECT_CALL(a, DoA(4))
1692       .After(e1)
1693       .After(e2)
1694       .After(e3);
1695 
1696   a.DoA(3);
1697   a.DoA(1);
1698   a.DoA(2);
1699   a.DoA(4);
1700 }
1701 
1702 // .After() accepts up to 5 arguments.
1703 TEST(AfterTest, AcceptsUpToFiveArguments) {
1704   MockA a;
1705   Expectation e1 = EXPECT_CALL(a, DoA(1));
1706   Expectation e2 = EXPECT_CALL(a, DoA(2));
1707   Expectation e3 = EXPECT_CALL(a, DoA(3));
1708   ExpectationSet es1 = EXPECT_CALL(a, DoA(4));
1709   ExpectationSet es2 = EXPECT_CALL(a, DoA(5));
1710   EXPECT_CALL(a, DoA(6))
1711       .After(e1, e2, e3, es1, es2);
1712 
1713   a.DoA(5);
1714   a.DoA(2);
1715   a.DoA(4);
1716   a.DoA(1);
1717   a.DoA(3);
1718   a.DoA(6);
1719 }
1720 
1721 // .After() allows input to contain duplicated Expectations.
1722 TEST(AfterTest, AcceptsDuplicatedInput) {
1723   MockA a;
1724   ON_CALL(a, ReturnResult(_))
1725       .WillByDefault(Return(Result()));
1726 
1727   // Define ordering:
1728   //   DoA(1) ==>
1729   //   DoA(2) ==> ReturnResult(3)
1730   Expectation e1 = EXPECT_CALL(a, DoA(1));
1731   Expectation e2 = EXPECT_CALL(a, DoA(2));
1732   ExpectationSet es;
1733   es += e1;
1734   es += e2;
1735   EXPECT_CALL(a, ReturnResult(3))
1736       .After(e1, e2, es, e1);
1737 
1738   a.DoA(1);
1739 
1740   // May only be after DoA(2).
1741   EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1742 
1743   a.DoA(2);
1744   a.ReturnResult(3);
1745 }
1746 
1747 // An Expectation added to an ExpectationSet after it has been used in
1748 // an .After() has no effect.
1749 TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {
1750   MockA a;
1751   ExpectationSet es1 = EXPECT_CALL(a, DoA(1));
1752   Expectation e2 = EXPECT_CALL(a, DoA(2));
1753   EXPECT_CALL(a, DoA(3))
1754       .After(es1);
1755   es1 += e2;
1756 
1757   a.DoA(1);
1758   a.DoA(3);
1759   a.DoA(2);
1760 }
1761 
1762 // Tests that Google Mock correctly handles calls to mock functions
1763 // after a mock object owning one of their pre-requisites has died.
1764 
1765 // Tests that calls that satisfy the original spec are successful.
1766 TEST(DeletingMockEarlyTest, Success1) {
1767   MockB* const b1 = new MockB;
1768   MockA* const a = new MockA;
1769   MockB* const b2 = new MockB;
1770 
1771   {
1772     InSequence dummy;
1773     EXPECT_CALL(*b1, DoB(_))
1774         .WillOnce(Return(1));
1775     EXPECT_CALL(*a, Binary(_, _))
1776         .Times(AnyNumber())
1777         .WillRepeatedly(Return(true));
1778     EXPECT_CALL(*b2, DoB(_))
1779         .Times(AnyNumber())
1780         .WillRepeatedly(Return(2));
1781   }
1782 
1783   EXPECT_EQ(1, b1->DoB(1));
1784   delete b1;
1785   // a's pre-requisite has died.
1786   EXPECT_TRUE(a->Binary(0, 1));
1787   delete b2;
1788   // a's successor has died.
1789   EXPECT_TRUE(a->Binary(1, 2));
1790   delete a;
1791 }
1792 
1793 // Tests that calls that satisfy the original spec are successful.
1794 TEST(DeletingMockEarlyTest, Success2) {
1795   MockB* const b1 = new MockB;
1796   MockA* const a = new MockA;
1797   MockB* const b2 = new MockB;
1798 
1799   {
1800     InSequence dummy;
1801     EXPECT_CALL(*b1, DoB(_))
1802         .WillOnce(Return(1));
1803     EXPECT_CALL(*a, Binary(_, _))
1804         .Times(AnyNumber());
1805     EXPECT_CALL(*b2, DoB(_))
1806         .Times(AnyNumber())
1807         .WillRepeatedly(Return(2));
1808   }
1809 
1810   delete a;  // a is trivially satisfied.
1811   EXPECT_EQ(1, b1->DoB(1));
1812   EXPECT_EQ(2, b2->DoB(2));
1813   delete b1;
1814   delete b2;
1815 }
1816 
1817 // Tests that it's OK to delete a mock object itself in its action.
1818 
1819 // Suppresses warning on unreferenced formal parameter in MSVC with
1820 // -W4.
1821 #ifdef _MSC_VER
1822 # pragma warning(push)
1823 # pragma warning(disable:4100)
1824 #endif
1825 
1826 ACTION_P(Delete, ptr) { delete ptr; }
1827 
1828 #ifdef _MSC_VER
1829 # pragma warning(pop)
1830 #endif
1831 
1832 TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
1833   MockA* const a = new MockA;
1834   EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a));
1835   a->DoA(42);  // This will cause a to be deleted.
1836 }
1837 
1838 TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {
1839   MockA* const a = new MockA;
1840   EXPECT_CALL(*a, ReturnResult(_))
1841       .WillOnce(DoAll(Delete(a), Return(Result())));
1842   a->ReturnResult(42);  // This will cause a to be deleted.
1843 }
1844 
1845 // Tests that calls that violate the original spec yield failures.
1846 TEST(DeletingMockEarlyTest, Failure1) {
1847   MockB* const b1 = new MockB;
1848   MockA* const a = new MockA;
1849   MockB* const b2 = new MockB;
1850 
1851   {
1852     InSequence dummy;
1853     EXPECT_CALL(*b1, DoB(_))
1854         .WillOnce(Return(1));
1855     EXPECT_CALL(*a, Binary(_, _))
1856         .Times(AnyNumber());
1857     EXPECT_CALL(*b2, DoB(_))
1858         .Times(AnyNumber())
1859         .WillRepeatedly(Return(2));
1860   }
1861 
1862   delete a;  // a is trivially satisfied.
1863   EXPECT_NONFATAL_FAILURE({
1864     b2->DoB(2);
1865   }, "Unexpected mock function call");
1866   EXPECT_EQ(1, b1->DoB(1));
1867   delete b1;
1868   delete b2;
1869 }
1870 
1871 // Tests that calls that violate the original spec yield failures.
1872 TEST(DeletingMockEarlyTest, Failure2) {
1873   MockB* const b1 = new MockB;
1874   MockA* const a = new MockA;
1875   MockB* const b2 = new MockB;
1876 
1877   {
1878     InSequence dummy;
1879     EXPECT_CALL(*b1, DoB(_));
1880     EXPECT_CALL(*a, Binary(_, _))
1881         .Times(AnyNumber());
1882     EXPECT_CALL(*b2, DoB(_))
1883         .Times(AnyNumber());
1884   }
1885 
1886   EXPECT_NONFATAL_FAILURE(delete b1,
1887                           "Actual: never called");
1888   EXPECT_NONFATAL_FAILURE(a->Binary(0, 1),
1889                           "Unexpected mock function call");
1890   EXPECT_NONFATAL_FAILURE(b2->DoB(1),
1891                           "Unexpected mock function call");
1892   delete a;
1893   delete b2;
1894 }
1895 
1896 class EvenNumberCardinality : public CardinalityInterface {
1897  public:
1898   // Returns true iff call_count calls will satisfy this cardinality.
1899   virtual bool IsSatisfiedByCallCount(int call_count) const {
1900     return call_count % 2 == 0;
1901   }
1902 
1903   // Returns true iff call_count calls will saturate this cardinality.
1904   virtual bool IsSaturatedByCallCount(int /* call_count */) const {
1905     return false;
1906   }
1907 
1908   // Describes self to an ostream.
1909   virtual void DescribeTo(::std::ostream* os) const {
1910     *os << "called even number of times";
1911   }
1912 };
1913 
1914 Cardinality EvenNumber() {
1915   return Cardinality(new EvenNumberCardinality);
1916 }
1917 
1918 TEST(ExpectationBaseTest,
1919      AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
1920   MockA* a = new MockA;
1921   Sequence s;
1922 
1923   EXPECT_CALL(*a, DoA(1))
1924       .Times(EvenNumber())
1925       .InSequence(s);
1926   EXPECT_CALL(*a, DoA(2))
1927       .Times(AnyNumber())
1928       .InSequence(s);
1929   EXPECT_CALL(*a, DoA(3))
1930       .Times(AnyNumber());
1931 
1932   a->DoA(3);
1933   a->DoA(1);
1934   EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");
1935   EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");
1936 }
1937 
1938 // The following tests verify the message generated when a mock
1939 // function is called.
1940 
1941 struct Printable {
1942 };
1943 
1944 inline void operator<<(::std::ostream& os, const Printable&) {
1945   os << "Printable";
1946 }
1947 
1948 struct Unprintable {
1949   Unprintable() : value(0) {}
1950   int value;
1951 };
1952 
1953 class MockC {
1954  public:
1955   MockC() {}
1956 
1957   MOCK_METHOD6(VoidMethod, void(bool cond, int n, string s, void* p,
1958                                 const Printable& x, Unprintable y));
1959   MOCK_METHOD0(NonVoidMethod, int());  // NOLINT
1960 
1961  private:
1962   GTEST_DISALLOW_COPY_AND_ASSIGN_(MockC);
1963 };
1964 
1965 class VerboseFlagPreservingFixture : public testing::Test {
1966  protected:
1967   VerboseFlagPreservingFixture()
1968       : saved_verbose_flag_(GMOCK_FLAG(verbose)) {}
1969 
1970   ~VerboseFlagPreservingFixture() { GMOCK_FLAG(verbose) = saved_verbose_flag_; }
1971 
1972  private:
1973   const string saved_verbose_flag_;
1974 
1975   GTEST_DISALLOW_COPY_AND_ASSIGN_(VerboseFlagPreservingFixture);
1976 };
1977 
1978 #if GTEST_HAS_STREAM_REDIRECTION
1979 
1980 // Tests that an uninteresting mock function call on a naggy mock
1981 // generates a warning without the stack trace when
1982 // --gmock_verbose=warning is specified.
1983 TEST(FunctionCallMessageTest,
1984      UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) {
1985   GMOCK_FLAG(verbose) = kWarningVerbosity;
1986   NaggyMock<MockC> c;
1987   CaptureStdout();
1988   c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
1989   const std::string output = GetCapturedStdout();
1990   EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
1991   EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output);
1992 }
1993 
1994 // Tests that an uninteresting mock function call on a naggy mock
1995 // generates a warning containing the stack trace when
1996 // --gmock_verbose=info is specified.
1997 TEST(FunctionCallMessageTest,
1998      UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) {
1999   GMOCK_FLAG(verbose) = kInfoVerbosity;
2000   NaggyMock<MockC> c;
2001   CaptureStdout();
2002   c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
2003   const std::string output = GetCapturedStdout();
2004   EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
2005   EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);
2006 
2007 # ifndef NDEBUG
2008 
2009   // We check the stack trace content in dbg-mode only, as opt-mode
2010   // may inline the call we are interested in seeing.
2011 
2012   // Verifies that a void mock function's name appears in the stack
2013   // trace.
2014   EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output);
2015 
2016   // Verifies that a non-void mock function's name appears in the
2017   // stack trace.
2018   CaptureStdout();
2019   c.NonVoidMethod();
2020   const std::string output2 = GetCapturedStdout();
2021   EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);
2022 
2023 # endif  // NDEBUG
2024 }
2025 
2026 // Tests that an uninteresting mock function call on a naggy mock
2027 // causes the function arguments and return value to be printed.
2028 TEST(FunctionCallMessageTest,
2029      UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) {
2030   // A non-void mock function.
2031   NaggyMock<MockB> b;
2032   CaptureStdout();
2033   b.DoB();
2034   const std::string output1 = GetCapturedStdout();
2035   EXPECT_PRED_FORMAT2(
2036       IsSubstring,
2037       "Uninteresting mock function call - returning default value.\n"
2038       "    Function call: DoB()\n"
2039       "          Returns: 0\n", output1.c_str());
2040   // Makes sure the return value is printed.
2041 
2042   // A void mock function.
2043   NaggyMock<MockC> c;
2044   CaptureStdout();
2045   c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
2046   const std::string output2 = GetCapturedStdout();
2047   EXPECT_THAT(output2.c_str(),
2048               ContainsRegex(
2049                   "Uninteresting mock function call - returning directly\\.\n"
2050                   "    Function call: VoidMethod"
2051                   "\\(false, 5, \"Hi\", NULL, @.+ "
2052                   "Printable, 4-byte object <00-00 00-00>\\)"));
2053   // A void function has no return value to print.
2054 }
2055 
2056 // Tests how the --gmock_verbose flag affects Google Mock's output.
2057 
2058 class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
2059  public:
2060   // Verifies that the given Google Mock output is correct.  (When
2061   // should_print is true, the output should match the given regex and
2062   // contain the given function name in the stack trace.  When it's
2063   // false, the output should be empty.)
2064   void VerifyOutput(const std::string& output, bool should_print,
2065                     const string& expected_substring,
2066                     const string& function_name) {
2067     if (should_print) {
2068       EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));
2069 # ifndef NDEBUG
2070       // We check the stack trace content in dbg-mode only, as opt-mode
2071       // may inline the call we are interested in seeing.
2072       EXPECT_THAT(output.c_str(), HasSubstr(function_name));
2073 # else
2074       // Suppresses 'unused function parameter' warnings.
2075       static_cast<void>(function_name);
2076 # endif  // NDEBUG
2077     } else {
2078       EXPECT_STREQ("", output.c_str());
2079     }
2080   }
2081 
2082   // Tests how the flag affects expected calls.
2083   void TestExpectedCall(bool should_print) {
2084     MockA a;
2085     EXPECT_CALL(a, DoA(5));
2086     EXPECT_CALL(a, Binary(_, 1))
2087         .WillOnce(Return(true));
2088 
2089     // A void-returning function.
2090     CaptureStdout();
2091     a.DoA(5);
2092     VerifyOutput(
2093         GetCapturedStdout(),
2094         should_print,
2095         "Mock function call matches EXPECT_CALL(a, DoA(5))...\n"
2096         "    Function call: DoA(5)\n"
2097         "Stack trace:\n",
2098         "DoA");
2099 
2100     // A non-void-returning function.
2101     CaptureStdout();
2102     a.Binary(2, 1);
2103     VerifyOutput(
2104         GetCapturedStdout(),
2105         should_print,
2106         "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"
2107         "    Function call: Binary(2, 1)\n"
2108         "          Returns: true\n"
2109         "Stack trace:\n",
2110         "Binary");
2111   }
2112 
2113   // Tests how the flag affects uninteresting calls on a naggy mock.
2114   void TestUninterestingCallOnNaggyMock(bool should_print) {
2115     NaggyMock<MockA> a;
2116     const string note =
2117         "NOTE: You can safely ignore the above warning unless this "
2118         "call should not happen.  Do not suppress it by blindly adding "
2119         "an EXPECT_CALL() if you don't mean to enforce the call.  "
2120         "See https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#"
2121         "knowing-when-to-expect for details.";
2122 
2123     // A void-returning function.
2124     CaptureStdout();
2125     a.DoA(5);
2126     VerifyOutput(
2127         GetCapturedStdout(),
2128         should_print,
2129         "\nGMOCK WARNING:\n"
2130         "Uninteresting mock function call - returning directly.\n"
2131         "    Function call: DoA(5)\n" +
2132         note,
2133         "DoA");
2134 
2135     // A non-void-returning function.
2136     CaptureStdout();
2137     a.Binary(2, 1);
2138     VerifyOutput(
2139         GetCapturedStdout(),
2140         should_print,
2141         "\nGMOCK WARNING:\n"
2142         "Uninteresting mock function call - returning default value.\n"
2143         "    Function call: Binary(2, 1)\n"
2144         "          Returns: false\n" +
2145         note,
2146         "Binary");
2147   }
2148 };
2149 
2150 // Tests that --gmock_verbose=info causes both expected and
2151 // uninteresting calls to be reported.
2152 TEST_F(GMockVerboseFlagTest, Info) {
2153   GMOCK_FLAG(verbose) = kInfoVerbosity;
2154   TestExpectedCall(true);
2155   TestUninterestingCallOnNaggyMock(true);
2156 }
2157 
2158 // Tests that --gmock_verbose=warning causes uninteresting calls to be
2159 // reported.
2160 TEST_F(GMockVerboseFlagTest, Warning) {
2161   GMOCK_FLAG(verbose) = kWarningVerbosity;
2162   TestExpectedCall(false);
2163   TestUninterestingCallOnNaggyMock(true);
2164 }
2165 
2166 // Tests that --gmock_verbose=warning causes neither expected nor
2167 // uninteresting calls to be reported.
2168 TEST_F(GMockVerboseFlagTest, Error) {
2169   GMOCK_FLAG(verbose) = kErrorVerbosity;
2170   TestExpectedCall(false);
2171   TestUninterestingCallOnNaggyMock(false);
2172 }
2173 
2174 // Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
2175 // as --gmock_verbose=warning.
2176 TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
2177   GMOCK_FLAG(verbose) = "invalid";  // Treated as "warning".
2178   TestExpectedCall(false);
2179   TestUninterestingCallOnNaggyMock(true);
2180 }
2181 
2182 #endif  // GTEST_HAS_STREAM_REDIRECTION
2183 
2184 // A helper class that generates a failure when printed.  We use it to
2185 // ensure that Google Mock doesn't print a value (even to an internal
2186 // buffer) when it is not supposed to do so.
2187 class PrintMeNot {};
2188 
2189 void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {
2190   ADD_FAILURE() << "Google Mock is printing a value that shouldn't be "
2191                 << "printed even to an internal buffer.";
2192 }
2193 
2194 class LogTestHelper {
2195  public:
2196   LogTestHelper() {}
2197 
2198   MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
2199 
2200  private:
2201   GTEST_DISALLOW_COPY_AND_ASSIGN_(LogTestHelper);
2202 };
2203 
2204 class GMockLogTest : public VerboseFlagPreservingFixture {
2205  protected:
2206   LogTestHelper helper_;
2207 };
2208 
2209 TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {
2210   GMOCK_FLAG(verbose) = kWarningVerbosity;
2211   EXPECT_CALL(helper_, Foo(_))
2212       .WillOnce(Return(PrintMeNot()));
2213   helper_.Foo(PrintMeNot());  // This is an expected call.
2214 }
2215 
2216 TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {
2217   GMOCK_FLAG(verbose) = kErrorVerbosity;
2218   EXPECT_CALL(helper_, Foo(_))
2219       .WillOnce(Return(PrintMeNot()));
2220   helper_.Foo(PrintMeNot());  // This is an expected call.
2221 }
2222 
2223 TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {
2224   GMOCK_FLAG(verbose) = kErrorVerbosity;
2225   ON_CALL(helper_, Foo(_))
2226       .WillByDefault(Return(PrintMeNot()));
2227   helper_.Foo(PrintMeNot());  // This should generate a warning.
2228 }
2229 
2230 // Tests Mock::AllowLeak().
2231 
2232 TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {
2233   MockA* a = new MockA;
2234   Mock::AllowLeak(a);
2235 }
2236 
2237 TEST(AllowLeakTest, CanBeCalledBeforeOnCall) {
2238   MockA* a = new MockA;
2239   Mock::AllowLeak(a);
2240   ON_CALL(*a, DoA(_)).WillByDefault(Return());
2241   a->DoA(0);
2242 }
2243 
2244 TEST(AllowLeakTest, CanBeCalledAfterOnCall) {
2245   MockA* a = new MockA;
2246   ON_CALL(*a, DoA(_)).WillByDefault(Return());
2247   Mock::AllowLeak(a);
2248 }
2249 
2250 TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) {
2251   MockA* a = new MockA;
2252   Mock::AllowLeak(a);
2253   EXPECT_CALL(*a, DoA(_));
2254   a->DoA(0);
2255 }
2256 
2257 TEST(AllowLeakTest, CanBeCalledAfterExpectCall) {
2258   MockA* a = new MockA;
2259   EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2260   Mock::AllowLeak(a);
2261 }
2262 
2263 TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) {
2264   MockA* a = new MockA;
2265   ON_CALL(*a, DoA(_)).WillByDefault(Return());
2266   EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2267   Mock::AllowLeak(a);
2268 }
2269 
2270 // Tests that we can verify and clear a mock object's expectations
2271 // when none of its methods has expectations.
2272 TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {
2273   MockB b;
2274   ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2275 
2276   // There should be no expectations on the methods now, so we can
2277   // freely call them.
2278   EXPECT_EQ(0, b.DoB());
2279   EXPECT_EQ(0, b.DoB(1));
2280 }
2281 
2282 // Tests that we can verify and clear a mock object's expectations
2283 // when some, but not all, of its methods have expectations *and* the
2284 // verification succeeds.
2285 TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
2286   MockB b;
2287   EXPECT_CALL(b, DoB())
2288       .WillOnce(Return(1));
2289   b.DoB();
2290   ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2291 
2292   // There should be no expectations on the methods now, so we can
2293   // freely call them.
2294   EXPECT_EQ(0, b.DoB());
2295   EXPECT_EQ(0, b.DoB(1));
2296 }
2297 
2298 // Tests that we can verify and clear a mock object's expectations
2299 // when some, but not all, of its methods have expectations *and* the
2300 // verification fails.
2301 TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
2302   MockB b;
2303   EXPECT_CALL(b, DoB())
2304       .WillOnce(Return(1));
2305   bool result = true;
2306   EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2307                           "Actual: never called");
2308   ASSERT_FALSE(result);
2309 
2310   // There should be no expectations on the methods now, so we can
2311   // freely call them.
2312   EXPECT_EQ(0, b.DoB());
2313   EXPECT_EQ(0, b.DoB(1));
2314 }
2315 
2316 // Tests that we can verify and clear a mock object's expectations
2317 // when all of its methods have expectations.
2318 TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
2319   MockB b;
2320   EXPECT_CALL(b, DoB())
2321       .WillOnce(Return(1));
2322   EXPECT_CALL(b, DoB(_))
2323       .WillOnce(Return(2));
2324   b.DoB();
2325   b.DoB(1);
2326   ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2327 
2328   // There should be no expectations on the methods now, so we can
2329   // freely call them.
2330   EXPECT_EQ(0, b.DoB());
2331   EXPECT_EQ(0, b.DoB(1));
2332 }
2333 
2334 // Tests that we can verify and clear a mock object's expectations
2335 // when a method has more than one expectation.
2336 TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
2337   MockB b;
2338   EXPECT_CALL(b, DoB(0))
2339       .WillOnce(Return(1));
2340   EXPECT_CALL(b, DoB(_))
2341       .WillOnce(Return(2));
2342   b.DoB(1);
2343   bool result = true;
2344   EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2345                           "Actual: never called");
2346   ASSERT_FALSE(result);
2347 
2348   // There should be no expectations on the methods now, so we can
2349   // freely call them.
2350   EXPECT_EQ(0, b.DoB());
2351   EXPECT_EQ(0, b.DoB(1));
2352 }
2353 
2354 // Tests that we can call VerifyAndClearExpectations() on the same
2355 // mock object multiple times.
2356 TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
2357   MockB b;
2358   EXPECT_CALL(b, DoB());
2359   b.DoB();
2360   Mock::VerifyAndClearExpectations(&b);
2361 
2362   EXPECT_CALL(b, DoB(_))
2363       .WillOnce(Return(1));
2364   b.DoB(1);
2365   Mock::VerifyAndClearExpectations(&b);
2366   Mock::VerifyAndClearExpectations(&b);
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 clear a mock object's default actions when none
2375 // of its methods has default actions.
2376 TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {
2377   MockB b;
2378   // If this crashes or generates a failure, the test will catch it.
2379   Mock::VerifyAndClear(&b);
2380   EXPECT_EQ(0, b.DoB());
2381 }
2382 
2383 // Tests that we can clear a mock object's default actions when some,
2384 // but not all of its methods have default actions.
2385 TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
2386   MockB b;
2387   ON_CALL(b, DoB())
2388       .WillByDefault(Return(1));
2389 
2390   Mock::VerifyAndClear(&b);
2391 
2392   // Verifies that the default action of int DoB() was removed.
2393   EXPECT_EQ(0, b.DoB());
2394 }
2395 
2396 // Tests that we can clear a mock object's default actions when all of
2397 // its methods have default actions.
2398 TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
2399   MockB b;
2400   ON_CALL(b, DoB())
2401       .WillByDefault(Return(1));
2402   ON_CALL(b, DoB(_))
2403       .WillByDefault(Return(2));
2404 
2405   Mock::VerifyAndClear(&b);
2406 
2407   // Verifies that the default action of int DoB() was removed.
2408   EXPECT_EQ(0, b.DoB());
2409 
2410   // Verifies that the default action of int DoB(int) was removed.
2411   EXPECT_EQ(0, b.DoB(0));
2412 }
2413 
2414 // Tests that we can clear a mock object's default actions when a
2415 // method has more than one ON_CALL() set on it.
2416 TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
2417   MockB b;
2418   ON_CALL(b, DoB(0))
2419       .WillByDefault(Return(1));
2420   ON_CALL(b, DoB(_))
2421       .WillByDefault(Return(2));
2422 
2423   Mock::VerifyAndClear(&b);
2424 
2425   // Verifies that the default actions (there are two) of int DoB(int)
2426   // were removed.
2427   EXPECT_EQ(0, b.DoB(0));
2428   EXPECT_EQ(0, b.DoB(1));
2429 }
2430 
2431 // Tests that we can call VerifyAndClear() on a mock object multiple
2432 // times.
2433 TEST(VerifyAndClearTest, CanCallManyTimes) {
2434   MockB b;
2435   ON_CALL(b, DoB())
2436       .WillByDefault(Return(1));
2437   Mock::VerifyAndClear(&b);
2438   Mock::VerifyAndClear(&b);
2439 
2440   ON_CALL(b, DoB(_))
2441       .WillByDefault(Return(1));
2442   Mock::VerifyAndClear(&b);
2443 
2444   EXPECT_EQ(0, b.DoB());
2445   EXPECT_EQ(0, b.DoB(1));
2446 }
2447 
2448 // Tests that VerifyAndClear() works when the verification succeeds.
2449 TEST(VerifyAndClearTest, Success) {
2450   MockB b;
2451   ON_CALL(b, DoB())
2452       .WillByDefault(Return(1));
2453   EXPECT_CALL(b, DoB(1))
2454       .WillOnce(Return(2));
2455 
2456   b.DoB();
2457   b.DoB(1);
2458   ASSERT_TRUE(Mock::VerifyAndClear(&b));
2459 
2460   // There should be no expectations on the methods now, so we can
2461   // freely call them.
2462   EXPECT_EQ(0, b.DoB());
2463   EXPECT_EQ(0, b.DoB(1));
2464 }
2465 
2466 // Tests that VerifyAndClear() works when the verification fails.
2467 TEST(VerifyAndClearTest, Failure) {
2468   MockB b;
2469   ON_CALL(b, DoB(_))
2470       .WillByDefault(Return(1));
2471   EXPECT_CALL(b, DoB())
2472       .WillOnce(Return(2));
2473 
2474   b.DoB(1);
2475   bool result = true;
2476   EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),
2477                           "Actual: never called");
2478   ASSERT_FALSE(result);
2479 
2480   // There should be no expectations on the methods now, so we can
2481   // freely call them.
2482   EXPECT_EQ(0, b.DoB());
2483   EXPECT_EQ(0, b.DoB(1));
2484 }
2485 
2486 // Tests that VerifyAndClear() works when the default actions and
2487 // expectations are set on a const mock object.
2488 TEST(VerifyAndClearTest, Const) {
2489   MockB b;
2490   ON_CALL(Const(b), DoB())
2491       .WillByDefault(Return(1));
2492 
2493   EXPECT_CALL(Const(b), DoB())
2494       .WillOnce(DoDefault())
2495       .WillOnce(Return(2));
2496 
2497   b.DoB();
2498   b.DoB();
2499   ASSERT_TRUE(Mock::VerifyAndClear(&b));
2500 
2501   // There should be no expectations on the methods now, so we can
2502   // freely call them.
2503   EXPECT_EQ(0, b.DoB());
2504   EXPECT_EQ(0, b.DoB(1));
2505 }
2506 
2507 // Tests that we can set default actions and expectations on a mock
2508 // object after VerifyAndClear() has been called on it.
2509 TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
2510   MockB b;
2511   ON_CALL(b, DoB())
2512       .WillByDefault(Return(1));
2513   EXPECT_CALL(b, DoB(_))
2514       .WillOnce(Return(2));
2515   b.DoB(1);
2516 
2517   Mock::VerifyAndClear(&b);
2518 
2519   EXPECT_CALL(b, DoB())
2520       .WillOnce(Return(3));
2521   ON_CALL(b, DoB(_))
2522       .WillByDefault(Return(4));
2523 
2524   EXPECT_EQ(3, b.DoB());
2525   EXPECT_EQ(4, b.DoB(1));
2526 }
2527 
2528 // Tests that calling VerifyAndClear() on one mock object does not
2529 // affect other mock objects (either of the same type or not).
2530 TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
2531   MockA a;
2532   MockB b1;
2533   MockB b2;
2534 
2535   ON_CALL(a, Binary(_, _))
2536       .WillByDefault(Return(true));
2537   EXPECT_CALL(a, Binary(_, _))
2538       .WillOnce(DoDefault())
2539       .WillOnce(Return(false));
2540 
2541   ON_CALL(b1, DoB())
2542       .WillByDefault(Return(1));
2543   EXPECT_CALL(b1, DoB(_))
2544       .WillOnce(Return(2));
2545 
2546   ON_CALL(b2, DoB())
2547       .WillByDefault(Return(3));
2548   EXPECT_CALL(b2, DoB(_));
2549 
2550   b2.DoB(0);
2551   Mock::VerifyAndClear(&b2);
2552 
2553   // Verifies that the default actions and expectations of a and b1
2554   // are still in effect.
2555   EXPECT_TRUE(a.Binary(0, 0));
2556   EXPECT_FALSE(a.Binary(0, 0));
2557 
2558   EXPECT_EQ(1, b1.DoB());
2559   EXPECT_EQ(2, b1.DoB(0));
2560 }
2561 
2562 TEST(VerifyAndClearTest,
2563      DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {
2564   linked_ptr<MockA> a(new MockA);
2565   ReferenceHoldingMock test_mock;
2566 
2567   // EXPECT_CALL stores a reference to a inside test_mock.
2568   EXPECT_CALL(test_mock, AcceptReference(_))
2569       .WillRepeatedly(SetArgPointee<0>(a));
2570 
2571   // Throw away the reference to the mock that we have in a. After this, the
2572   // only reference to it is stored by test_mock.
2573   a.reset();
2574 
2575   // When test_mock goes out of scope, it destroys the last remaining reference
2576   // to the mock object originally pointed to by a. This will cause the MockA
2577   // destructor to be called from inside the ReferenceHoldingMock destructor.
2578   // The state of all mocks is protected by a single global lock, but there
2579   // should be no deadlock.
2580 }
2581 
2582 TEST(VerifyAndClearTest,
2583      DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {
2584   linked_ptr<MockA> a(new MockA);
2585   ReferenceHoldingMock test_mock;
2586 
2587   // ON_CALL stores a reference to a inside test_mock.
2588   ON_CALL(test_mock, AcceptReference(_))
2589       .WillByDefault(SetArgPointee<0>(a));
2590 
2591   // Throw away the reference to the mock that we have in a. After this, the
2592   // only reference to it is stored by test_mock.
2593   a.reset();
2594 
2595   // When test_mock goes out of scope, it destroys the last remaining reference
2596   // to the mock object originally pointed to by a. This will cause the MockA
2597   // destructor to be called from inside the ReferenceHoldingMock destructor.
2598   // The state of all mocks is protected by a single global lock, but there
2599   // should be no deadlock.
2600 }
2601 
2602 // Tests that a mock function's action can call a mock function
2603 // (either the same function or a different one) either as an explicit
2604 // action or as a default action without causing a dead lock.  It
2605 // verifies that the action is not performed inside the critical
2606 // section.
2607 TEST(SynchronizationTest, CanCallMockMethodInAction) {
2608   MockA a;
2609   MockC c;
2610   ON_CALL(a, DoA(_))
2611       .WillByDefault(IgnoreResult(InvokeWithoutArgs(&c,
2612                                                     &MockC::NonVoidMethod)));
2613   EXPECT_CALL(a, DoA(1));
2614   EXPECT_CALL(a, DoA(1))
2615       .WillOnce(Invoke(&a, &MockA::DoA))
2616       .RetiresOnSaturation();
2617   EXPECT_CALL(c, NonVoidMethod());
2618 
2619   a.DoA(1);
2620   // This will match the second EXPECT_CALL() and trigger another a.DoA(1),
2621   // which will in turn match the first EXPECT_CALL() and trigger a call to
2622   // c.NonVoidMethod() that was specified by the ON_CALL() since the first
2623   // EXPECT_CALL() did not specify an action.
2624 }
2625 
2626 }  // namespace
2627 
2628 // Allows the user to define his own main and then invoke gmock_main
2629 // from it. This might be necessary on some platforms which require
2630 // specific setup and teardown.
2631 #if GMOCK_RENAME_MAIN
2632 int gmock_main(int argc, char **argv) {
2633 #else
2634 int main(int argc, char **argv) {
2635 #endif  // GMOCK_RENAME_MAIN
2636   testing::InitGoogleMock(&argc, argv);
2637 
2638   // Ensures that the tests pass no matter what value of
2639   // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
2640   testing::GMOCK_FLAG(catch_leaked_mocks) = true;
2641   testing::GMOCK_FLAG(verbose) = testing::internal::kWarningVerbosity;
2642 
2643   return RUN_ALL_TESTS();
2644 }