1 // Copyright 2005, 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 // The purpose of this file is to generate Google Test output under
31 // various conditions.  The output will then be verified by
32 // googletest-output-test.py to ensure that Google Test generates the
33 // desired messages.  Therefore, most tests in this file are MEANT TO
34 // FAIL.
35 
36 #include "gtest/gtest-spi.h"
37 #include "gtest/gtest.h"
38 #include "src/gtest-internal-inl.h"
39 
40 #include <stdlib.h>
41 
42 #if _MSC_VER
43 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */)
44 #endif  //  _MSC_VER
45 
46 #if GTEST_IS_THREADSAFE
47 using testing::ScopedFakeTestPartResultReporter;
48 using testing::TestPartResultArray;
49 
50 using testing::internal::Notification;
51 using testing::internal::ThreadWithParam;
52 #endif
53 
54 namespace posix = ::testing::internal::posix;
55 
56 // Tests catching fatal failures.
57 
58 // A subroutine used by the following test.
TestEq1(int x)59 void TestEq1(int x) { ASSERT_EQ(1, x); }
60 
61 // This function calls a test subroutine, catches the fatal failure it
62 // generates, and then returns early.
TryTestSubroutine()63 void TryTestSubroutine() {
64   // Calls a subrountine that yields a fatal failure.
65   TestEq1(2);
66 
67   // Catches the fatal failure and aborts the test.
68   //
69   // The testing::Test:: prefix is necessary when calling
70   // HasFatalFailure() outside of a TEST, TEST_F, or test fixture.
71   if (testing::Test::HasFatalFailure()) return;
72 
73   // If we get here, something is wrong.
74   FAIL() << "This should never be reached.";
75 }
76 
TEST(PassingTest,PassingTest1)77 TEST(PassingTest, PassingTest1) {}
78 
TEST(PassingTest,PassingTest2)79 TEST(PassingTest, PassingTest2) {}
80 
81 // Tests that parameters of failing parameterized tests are printed in the
82 // failing test summary.
83 class FailingParamTest : public testing::TestWithParam<int> {};
84 
TEST_P(FailingParamTest,Fails)85 TEST_P(FailingParamTest, Fails) { EXPECT_EQ(1, GetParam()); }
86 
87 // This generates a test which will fail. Google Test is expected to print
88 // its parameter when it outputs the list of all failed tests.
89 INSTANTIATE_TEST_SUITE_P(PrintingFailingParams, FailingParamTest,
90                          testing::Values(2));
91 
92 // Tests that an empty value for the test suite basename yields just
93 // the test name without any prior /
94 class EmptyBasenameParamInst : public testing::TestWithParam<int> {};
95 
TEST_P(EmptyBasenameParamInst,Passes)96 TEST_P(EmptyBasenameParamInst, Passes) { EXPECT_EQ(1, GetParam()); }
97 
98 INSTANTIATE_TEST_SUITE_P(, EmptyBasenameParamInst, testing::Values(1));
99 
100 static const char kGoldenString[] = "\"Line\0 1\"\nLine 2";
101 
TEST(NonfatalFailureTest,EscapesStringOperands)102 TEST(NonfatalFailureTest, EscapesStringOperands) {
103   std::string actual = "actual \"string\"";
104   EXPECT_EQ(kGoldenString, actual);
105 
106   const char* golden = kGoldenString;
107   EXPECT_EQ(golden, actual);
108 }
109 
TEST(NonfatalFailureTest,DiffForLongStrings)110 TEST(NonfatalFailureTest, DiffForLongStrings) {
111   std::string golden_str(kGoldenString, sizeof(kGoldenString) - 1);
112   EXPECT_EQ(golden_str, "Line 2");
113 }
114 
115 // Tests catching a fatal failure in a subroutine.
TEST(FatalFailureTest,FatalFailureInSubroutine)116 TEST(FatalFailureTest, FatalFailureInSubroutine) {
117   printf("(expecting a failure that x should be 1)\n");
118 
119   TryTestSubroutine();
120 }
121 
122 // Tests catching a fatal failure in a nested subroutine.
TEST(FatalFailureTest,FatalFailureInNestedSubroutine)123 TEST(FatalFailureTest, FatalFailureInNestedSubroutine) {
124   printf("(expecting a failure that x should be 1)\n");
125 
126   // Calls a subrountine that yields a fatal failure.
127   TryTestSubroutine();
128 
129   // Catches the fatal failure and aborts the test.
130   //
131   // When calling HasFatalFailure() inside a TEST, TEST_F, or test
132   // fixture, the testing::Test:: prefix is not needed.
133   if (HasFatalFailure()) return;
134 
135   // If we get here, something is wrong.
136   FAIL() << "This should never be reached.";
137 }
138 
139 // Tests HasFatalFailure() after a failed EXPECT check.
TEST(FatalFailureTest,NonfatalFailureInSubroutine)140 TEST(FatalFailureTest, NonfatalFailureInSubroutine) {
141   printf("(expecting a failure on false)\n");
142   EXPECT_TRUE(false);               // Generates a nonfatal failure
143   ASSERT_FALSE(HasFatalFailure());  // This should succeed.
144 }
145 
146 // Tests interleaving user logging and Google Test assertions.
TEST(LoggingTest,InterleavingLoggingAndAssertions)147 TEST(LoggingTest, InterleavingLoggingAndAssertions) {
148   static const int a[4] = {3, 9, 2, 6};
149 
150   printf("(expecting 2 failures on (3) >= (a[i]))\n");
151   for (int i = 0; i < static_cast<int>(sizeof(a) / sizeof(*a)); i++) {
152     printf("i == %d\n", i);
153     EXPECT_GE(3, a[i]);
154   }
155 }
156 
157 // Tests the SCOPED_TRACE macro.
158 
159 // A helper function for testing SCOPED_TRACE.
SubWithoutTrace(int n)160 void SubWithoutTrace(int n) {
161   EXPECT_EQ(1, n);
162   ASSERT_EQ(2, n);
163 }
164 
165 // Another helper function for testing SCOPED_TRACE.
SubWithTrace(int n)166 void SubWithTrace(int n) {
167   SCOPED_TRACE(testing::Message() << "n = " << n);
168 
169   SubWithoutTrace(n);
170 }
171 
TEST(SCOPED_TRACETest,AcceptedValues)172 TEST(SCOPED_TRACETest, AcceptedValues) {
173   SCOPED_TRACE("literal string");
174   SCOPED_TRACE(std::string("std::string"));
175   SCOPED_TRACE(1337);  // streamable type
176   const char* null_value = nullptr;
177   SCOPED_TRACE(null_value);
178 
179   ADD_FAILURE() << "Just checking that all these values work fine.";
180 }
181 
182 // Tests that SCOPED_TRACE() obeys lexical scopes.
TEST(SCOPED_TRACETest,ObeysScopes)183 TEST(SCOPED_TRACETest, ObeysScopes) {
184   printf("(expected to fail)\n");
185 
186   // There should be no trace before SCOPED_TRACE() is invoked.
187   ADD_FAILURE() << "This failure is expected, and shouldn't have a trace.";
188 
189   {
190     SCOPED_TRACE("Expected trace");
191     // After SCOPED_TRACE(), a failure in the current scope should contain
192     // the trace.
193     ADD_FAILURE() << "This failure is expected, and should have a trace.";
194   }
195 
196   // Once the control leaves the scope of the SCOPED_TRACE(), there
197   // should be no trace again.
198   ADD_FAILURE() << "This failure is expected, and shouldn't have a trace.";
199 }
200 
201 // Tests that SCOPED_TRACE works inside a loop.
TEST(SCOPED_TRACETest,WorksInLoop)202 TEST(SCOPED_TRACETest, WorksInLoop) {
203   printf("(expected to fail)\n");
204 
205   for (int i = 1; i <= 2; i++) {
206     SCOPED_TRACE(testing::Message() << "i = " << i);
207 
208     SubWithoutTrace(i);
209   }
210 }
211 
212 // Tests that SCOPED_TRACE works in a subroutine.
TEST(SCOPED_TRACETest,WorksInSubroutine)213 TEST(SCOPED_TRACETest, WorksInSubroutine) {
214   printf("(expected to fail)\n");
215 
216   SubWithTrace(1);
217   SubWithTrace(2);
218 }
219 
220 // Tests that SCOPED_TRACE can be nested.
TEST(SCOPED_TRACETest,CanBeNested)221 TEST(SCOPED_TRACETest, CanBeNested) {
222   printf("(expected to fail)\n");
223 
224   SCOPED_TRACE("");  // A trace without a message.
225 
226   SubWithTrace(2);
227 }
228 
229 // Tests that multiple SCOPED_TRACEs can be used in the same scope.
TEST(SCOPED_TRACETest,CanBeRepeated)230 TEST(SCOPED_TRACETest, CanBeRepeated) {
231   printf("(expected to fail)\n");
232 
233   SCOPED_TRACE("A");
234   ADD_FAILURE()
235       << "This failure is expected, and should contain trace point A.";
236 
237   SCOPED_TRACE("B");
238   ADD_FAILURE()
239       << "This failure is expected, and should contain trace point A and B.";
240 
241   {
242     SCOPED_TRACE("C");
243     ADD_FAILURE() << "This failure is expected, and should "
244                   << "contain trace point A, B, and C.";
245   }
246 
247   SCOPED_TRACE("D");
248   ADD_FAILURE() << "This failure is expected, and should "
249                 << "contain trace point A, B, and D.";
250 }
251 
252 #if GTEST_IS_THREADSAFE
253 // Tests that SCOPED_TRACE()s can be used concurrently from multiple
254 // threads.  Namely, an assertion should be affected by
255 // SCOPED_TRACE()s in its own thread only.
256 
257 // Here's the sequence of actions that happen in the test:
258 //
259 //   Thread A (main)                | Thread B (spawned)
260 //   ===============================|================================
261 //   spawns thread B                |
262 //   -------------------------------+--------------------------------
263 //   waits for n1                   | SCOPED_TRACE("Trace B");
264 //                                  | generates failure #1
265 //                                  | notifies n1
266 //   -------------------------------+--------------------------------
267 //   SCOPED_TRACE("Trace A");       | waits for n2
268 //   generates failure #2           |
269 //   notifies n2                    |
270 //   -------------------------------|--------------------------------
271 //   waits for n3                   | generates failure #3
272 //                                  | trace B dies
273 //                                  | generates failure #4
274 //                                  | notifies n3
275 //   -------------------------------|--------------------------------
276 //   generates failure #5           | finishes
277 //   trace A dies                   |
278 //   generates failure #6           |
279 //   -------------------------------|--------------------------------
280 //   waits for thread B to finish   |
281 
282 struct CheckPoints {
283   Notification n1;
284   Notification n2;
285   Notification n3;
286 };
287 
ThreadWithScopedTrace(CheckPoints * check_points)288 static void ThreadWithScopedTrace(CheckPoints* check_points) {
289   {
290     SCOPED_TRACE("Trace B");
291     ADD_FAILURE() << "Expected failure #1 (in thread B, only trace B alive).";
292     check_points->n1.Notify();
293     check_points->n2.WaitForNotification();
294 
295     ADD_FAILURE()
296         << "Expected failure #3 (in thread B, trace A & B both alive).";
297   }  // Trace B dies here.
298   ADD_FAILURE() << "Expected failure #4 (in thread B, only trace A alive).";
299   check_points->n3.Notify();
300 }
301 
TEST(SCOPED_TRACETest,WorksConcurrently)302 TEST(SCOPED_TRACETest, WorksConcurrently) {
303   printf("(expecting 6 failures)\n");
304 
305   CheckPoints check_points;
306   ThreadWithParam<CheckPoints*> thread(&ThreadWithScopedTrace, &check_points,
307                                        nullptr);
308   check_points.n1.WaitForNotification();
309 
310   {
311     SCOPED_TRACE("Trace A");
312     ADD_FAILURE()
313         << "Expected failure #2 (in thread A, trace A & B both alive).";
314     check_points.n2.Notify();
315     check_points.n3.WaitForNotification();
316 
317     ADD_FAILURE() << "Expected failure #5 (in thread A, only trace A alive).";
318   }  // Trace A dies here.
319   ADD_FAILURE() << "Expected failure #6 (in thread A, no trace alive).";
320   thread.Join();
321 }
322 #endif  // GTEST_IS_THREADSAFE
323 
324 // Tests basic functionality of the ScopedTrace utility (most of its features
325 // are already tested in SCOPED_TRACETest).
TEST(ScopedTraceTest,WithExplicitFileAndLine)326 TEST(ScopedTraceTest, WithExplicitFileAndLine) {
327   testing::ScopedTrace trace("explicit_file.cc", 123, "expected trace message");
328   ADD_FAILURE() << "Check that the trace is attached to a particular location.";
329 }
330 
TEST(DisabledTestsWarningTest,DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning)331 TEST(DisabledTestsWarningTest,
332      DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning) {
333   // This test body is intentionally empty.  Its sole purpose is for
334   // verifying that the --gtest_also_run_disabled_tests flag
335   // suppresses the "YOU HAVE 12 DISABLED TESTS" warning at the end of
336   // the test output.
337 }
338 
339 // Tests using assertions outside of TEST and TEST_F.
340 //
341 // This function creates two failures intentionally.
AdHocTest()342 void AdHocTest() {
343   printf("The non-test part of the code is expected to have 2 failures.\n\n");
344   EXPECT_TRUE(false);
345   EXPECT_EQ(2, 3);
346 }
347 
348 // Runs all TESTs, all TEST_Fs, and the ad hoc test.
RunAllTests()349 int RunAllTests() {
350   AdHocTest();
351   return RUN_ALL_TESTS();
352 }
353 
354 // Tests non-fatal failures in the fixture constructor.
355 class NonFatalFailureInFixtureConstructorTest : public testing::Test {
356  protected:
NonFatalFailureInFixtureConstructorTest()357   NonFatalFailureInFixtureConstructorTest() {
358     printf("(expecting 5 failures)\n");
359     ADD_FAILURE() << "Expected failure #1, in the test fixture c'tor.";
360   }
361 
~NonFatalFailureInFixtureConstructorTest()362   ~NonFatalFailureInFixtureConstructorTest() override {
363     ADD_FAILURE() << "Expected failure #5, in the test fixture d'tor.";
364   }
365 
SetUp()366   void SetUp() override { ADD_FAILURE() << "Expected failure #2, in SetUp()."; }
367 
TearDown()368   void TearDown() override {
369     ADD_FAILURE() << "Expected failure #4, in TearDown.";
370   }
371 };
372 
TEST_F(NonFatalFailureInFixtureConstructorTest,FailureInConstructor)373 TEST_F(NonFatalFailureInFixtureConstructorTest, FailureInConstructor) {
374   ADD_FAILURE() << "Expected failure #3, in the test body.";
375 }
376 
377 // Tests fatal failures in the fixture constructor.
378 class FatalFailureInFixtureConstructorTest : public testing::Test {
379  protected:
FatalFailureInFixtureConstructorTest()380   FatalFailureInFixtureConstructorTest() {
381     printf("(expecting 2 failures)\n");
382     Init();
383   }
384 
~FatalFailureInFixtureConstructorTest()385   ~FatalFailureInFixtureConstructorTest() override {
386     ADD_FAILURE() << "Expected failure #2, in the test fixture d'tor.";
387   }
388 
SetUp()389   void SetUp() override {
390     ADD_FAILURE() << "UNEXPECTED failure in SetUp().  "
391                   << "We should never get here, as the test fixture c'tor "
392                   << "had a fatal failure.";
393   }
394 
TearDown()395   void TearDown() override {
396     ADD_FAILURE() << "UNEXPECTED failure in TearDown().  "
397                   << "We should never get here, as the test fixture c'tor "
398                   << "had a fatal failure.";
399   }
400 
401  private:
Init()402   void Init() { FAIL() << "Expected failure #1, in the test fixture c'tor."; }
403 };
404 
TEST_F(FatalFailureInFixtureConstructorTest,FailureInConstructor)405 TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) {
406   ADD_FAILURE() << "UNEXPECTED failure in the test body.  "
407                 << "We should never get here, as the test fixture c'tor "
408                 << "had a fatal failure.";
409 }
410 
411 // Tests non-fatal failures in SetUp().
412 class NonFatalFailureInSetUpTest : public testing::Test {
413  protected:
~NonFatalFailureInSetUpTest()414   ~NonFatalFailureInSetUpTest() override { Deinit(); }
415 
SetUp()416   void SetUp() override {
417     printf("(expecting 4 failures)\n");
418     ADD_FAILURE() << "Expected failure #1, in SetUp().";
419   }
420 
TearDown()421   void TearDown() override { FAIL() << "Expected failure #3, in TearDown()."; }
422 
423  private:
Deinit()424   void Deinit() { FAIL() << "Expected failure #4, in the test fixture d'tor."; }
425 };
426 
TEST_F(NonFatalFailureInSetUpTest,FailureInSetUp)427 TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) {
428   FAIL() << "Expected failure #2, in the test function.";
429 }
430 
431 // Tests fatal failures in SetUp().
432 class FatalFailureInSetUpTest : public testing::Test {
433  protected:
~FatalFailureInSetUpTest()434   ~FatalFailureInSetUpTest() override { Deinit(); }
435 
SetUp()436   void SetUp() override {
437     printf("(expecting 3 failures)\n");
438     FAIL() << "Expected failure #1, in SetUp().";
439   }
440 
TearDown()441   void TearDown() override { FAIL() << "Expected failure #2, in TearDown()."; }
442 
443  private:
Deinit()444   void Deinit() { FAIL() << "Expected failure #3, in the test fixture d'tor."; }
445 };
446 
TEST_F(FatalFailureInSetUpTest,FailureInSetUp)447 TEST_F(FatalFailureInSetUpTest, FailureInSetUp) {
448   FAIL() << "UNEXPECTED failure in the test function.  "
449          << "We should never get here, as SetUp() failed.";
450 }
451 
TEST(AddFailureAtTest,MessageContainsSpecifiedFileAndLineNumber)452 TEST(AddFailureAtTest, MessageContainsSpecifiedFileAndLineNumber) {
453   ADD_FAILURE_AT("foo.cc", 42) << "Expected nonfatal failure in foo.cc";
454 }
455 
TEST(GtestFailAtTest,MessageContainsSpecifiedFileAndLineNumber)456 TEST(GtestFailAtTest, MessageContainsSpecifiedFileAndLineNumber) {
457   GTEST_FAIL_AT("foo.cc", 42) << "Expected fatal failure in foo.cc";
458 }
459 
460 #if GTEST_IS_THREADSAFE
461 
462 // A unary function that may die.
DieIf(bool should_die)463 void DieIf(bool should_die) {
464   GTEST_CHECK_(!should_die) << " - death inside DieIf().";
465 }
466 
467 // Tests running death tests in a multi-threaded context.
468 
469 // Used for coordination between the main and the spawn thread.
470 struct SpawnThreadNotifications {
SpawnThreadNotificationsSpawnThreadNotifications471   SpawnThreadNotifications() {}
472 
473   Notification spawn_thread_started;
474   Notification spawn_thread_ok_to_terminate;
475 
476  private:
477   GTEST_DISALLOW_COPY_AND_ASSIGN_(SpawnThreadNotifications);
478 };
479 
480 // The function to be executed in the thread spawn by the
481 // MultipleThreads test (below).
ThreadRoutine(SpawnThreadNotifications * notifications)482 static void ThreadRoutine(SpawnThreadNotifications* notifications) {
483   // Signals the main thread that this thread has started.
484   notifications->spawn_thread_started.Notify();
485 
486   // Waits for permission to finish from the main thread.
487   notifications->spawn_thread_ok_to_terminate.WaitForNotification();
488 }
489 
490 // This is a death-test test, but it's not named with a DeathTest
491 // suffix.  It starts threads which might interfere with later
492 // death tests, so it must run after all other death tests.
493 class DeathTestAndMultiThreadsTest : public testing::Test {
494  protected:
495   // Starts a thread and waits for it to begin.
SetUp()496   void SetUp() override {
497     thread_.reset(new ThreadWithParam<SpawnThreadNotifications*>(
498         &ThreadRoutine, &notifications_, nullptr));
499     notifications_.spawn_thread_started.WaitForNotification();
500   }
501   // Tells the thread to finish, and reaps it.
502   // Depending on the version of the thread library in use,
503   // a manager thread might still be left running that will interfere
504   // with later death tests.  This is unfortunate, but this class
505   // cleans up after itself as best it can.
TearDown()506   void TearDown() override {
507     notifications_.spawn_thread_ok_to_terminate.Notify();
508   }
509 
510  private:
511   SpawnThreadNotifications notifications_;
512   std::unique_ptr<ThreadWithParam<SpawnThreadNotifications*> > thread_;
513 };
514 
515 #endif  // GTEST_IS_THREADSAFE
516 
517 // The MixedUpTestSuiteTest test case verifies that Google Test will fail a
518 // test if it uses a different fixture class than what other tests in
519 // the same test case use.  It deliberately contains two fixture
520 // classes with the same name but defined in different namespaces.
521 
522 // The MixedUpTestSuiteWithSameTestNameTest test case verifies that
523 // when the user defines two tests with the same test case name AND
524 // same test name (but in different namespaces), the second test will
525 // fail.
526 
527 namespace foo {
528 
529 class MixedUpTestSuiteTest : public testing::Test {};
530 
TEST_F(MixedUpTestSuiteTest,FirstTestFromNamespaceFoo)531 TEST_F(MixedUpTestSuiteTest, FirstTestFromNamespaceFoo) {}
TEST_F(MixedUpTestSuiteTest,SecondTestFromNamespaceFoo)532 TEST_F(MixedUpTestSuiteTest, SecondTestFromNamespaceFoo) {}
533 
534 class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {};
535 
TEST_F(MixedUpTestSuiteWithSameTestNameTest,TheSecondTestWithThisNameShouldFail)536 TEST_F(MixedUpTestSuiteWithSameTestNameTest,
537        TheSecondTestWithThisNameShouldFail) {}
538 
539 }  // namespace foo
540 
541 namespace bar {
542 
543 class MixedUpTestSuiteTest : public testing::Test {};
544 
545 // The following two tests are expected to fail.  We rely on the
546 // golden file to check that Google Test generates the right error message.
TEST_F(MixedUpTestSuiteTest,ThisShouldFail)547 TEST_F(MixedUpTestSuiteTest, ThisShouldFail) {}
TEST_F(MixedUpTestSuiteTest,ThisShouldFailToo)548 TEST_F(MixedUpTestSuiteTest, ThisShouldFailToo) {}
549 
550 class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {};
551 
552 // Expected to fail.  We rely on the golden file to check that Google Test
553 // generates the right error message.
TEST_F(MixedUpTestSuiteWithSameTestNameTest,TheSecondTestWithThisNameShouldFail)554 TEST_F(MixedUpTestSuiteWithSameTestNameTest,
555        TheSecondTestWithThisNameShouldFail) {}
556 
557 }  // namespace bar
558 
559 // The following two test cases verify that Google Test catches the user
560 // error of mixing TEST and TEST_F in the same test case.  The first
561 // test case checks the scenario where TEST_F appears before TEST, and
562 // the second one checks where TEST appears before TEST_F.
563 
564 class TEST_F_before_TEST_in_same_test_case : public testing::Test {};
565 
TEST_F(TEST_F_before_TEST_in_same_test_case,DefinedUsingTEST_F)566 TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {}
567 
568 // Expected to fail.  We rely on the golden file to check that Google Test
569 // generates the right error message.
TEST(TEST_F_before_TEST_in_same_test_case,DefinedUsingTESTAndShouldFail)570 TEST(TEST_F_before_TEST_in_same_test_case, DefinedUsingTESTAndShouldFail) {}
571 
572 class TEST_before_TEST_F_in_same_test_case : public testing::Test {};
573 
TEST(TEST_before_TEST_F_in_same_test_case,DefinedUsingTEST)574 TEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {}
575 
576 // Expected to fail.  We rely on the golden file to check that Google Test
577 // generates the right error message.
TEST_F(TEST_before_TEST_F_in_same_test_case,DefinedUsingTEST_FAndShouldFail)578 TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) {}
579 
580 // Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE().
581 int global_integer = 0;
582 
583 // Tests that EXPECT_NONFATAL_FAILURE() can reference global variables.
TEST(ExpectNonfatalFailureTest,CanReferenceGlobalVariables)584 TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) {
585   global_integer = 0;
586   EXPECT_NONFATAL_FAILURE(
587       { EXPECT_EQ(1, global_integer) << "Expected non-fatal failure."; },
588       "Expected non-fatal failure.");
589 }
590 
591 // Tests that EXPECT_NONFATAL_FAILURE() can reference local variables
592 // (static or not).
TEST(ExpectNonfatalFailureTest,CanReferenceLocalVariables)593 TEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) {
594   int m = 0;
595   static int n;
596   n = 1;
597   EXPECT_NONFATAL_FAILURE({ EXPECT_EQ(m, n) << "Expected non-fatal failure."; },
598                           "Expected non-fatal failure.");
599 }
600 
601 // Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly
602 // one non-fatal failure and no fatal failure.
TEST(ExpectNonfatalFailureTest,SucceedsWhenThereIsOneNonfatalFailure)603 TEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) {
604   EXPECT_NONFATAL_FAILURE({ ADD_FAILURE() << "Expected non-fatal failure."; },
605                           "Expected non-fatal failure.");
606 }
607 
608 // Tests that EXPECT_NONFATAL_FAILURE() fails when there is no
609 // non-fatal failure.
TEST(ExpectNonfatalFailureTest,FailsWhenThereIsNoNonfatalFailure)610 TEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) {
611   printf("(expecting a failure)\n");
612   EXPECT_NONFATAL_FAILURE({}, "");
613 }
614 
615 // Tests that EXPECT_NONFATAL_FAILURE() fails when there are two
616 // non-fatal failures.
TEST(ExpectNonfatalFailureTest,FailsWhenThereAreTwoNonfatalFailures)617 TEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) {
618   printf("(expecting a failure)\n");
619   EXPECT_NONFATAL_FAILURE(
620       {
621         ADD_FAILURE() << "Expected non-fatal failure 1.";
622         ADD_FAILURE() << "Expected non-fatal failure 2.";
623       },
624       "");
625 }
626 
627 // Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal
628 // failure.
TEST(ExpectNonfatalFailureTest,FailsWhenThereIsOneFatalFailure)629 TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) {
630   printf("(expecting a failure)\n");
631   EXPECT_NONFATAL_FAILURE({ FAIL() << "Expected fatal failure."; }, "");
632 }
633 
634 // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
635 // tested returns.
TEST(ExpectNonfatalFailureTest,FailsWhenStatementReturns)636 TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) {
637   printf("(expecting a failure)\n");
638   EXPECT_NONFATAL_FAILURE({ return; }, "");
639 }
640 
641 #if GTEST_HAS_EXCEPTIONS
642 
643 // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
644 // tested throws.
TEST(ExpectNonfatalFailureTest,FailsWhenStatementThrows)645 TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) {
646   printf("(expecting a failure)\n");
647   try {
648     EXPECT_NONFATAL_FAILURE({ throw 0; }, "");
649   } catch (int) {  // NOLINT
650   }
651 }
652 
653 #endif  // GTEST_HAS_EXCEPTIONS
654 
655 // Tests that EXPECT_FATAL_FAILURE() can reference global variables.
TEST(ExpectFatalFailureTest,CanReferenceGlobalVariables)656 TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) {
657   global_integer = 0;
658   EXPECT_FATAL_FAILURE(
659       { ASSERT_EQ(1, global_integer) << "Expected fatal failure."; },
660       "Expected fatal failure.");
661 }
662 
663 // Tests that EXPECT_FATAL_FAILURE() can reference local static
664 // variables.
TEST(ExpectFatalFailureTest,CanReferenceLocalStaticVariables)665 TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) {
666   static int n;
667   n = 1;
668   EXPECT_FATAL_FAILURE({ ASSERT_EQ(0, n) << "Expected fatal failure."; },
669                        "Expected fatal failure.");
670 }
671 
672 // Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly
673 // one fatal failure and no non-fatal failure.
TEST(ExpectFatalFailureTest,SucceedsWhenThereIsOneFatalFailure)674 TEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) {
675   EXPECT_FATAL_FAILURE({ FAIL() << "Expected fatal failure."; },
676                        "Expected fatal failure.");
677 }
678 
679 // Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal
680 // failure.
TEST(ExpectFatalFailureTest,FailsWhenThereIsNoFatalFailure)681 TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) {
682   printf("(expecting a failure)\n");
683   EXPECT_FATAL_FAILURE({}, "");
684 }
685 
686 // A helper for generating a fatal failure.
FatalFailure()687 void FatalFailure() { FAIL() << "Expected fatal failure."; }
688 
689 // Tests that EXPECT_FATAL_FAILURE() fails when there are two
690 // fatal failures.
TEST(ExpectFatalFailureTest,FailsWhenThereAreTwoFatalFailures)691 TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) {
692   printf("(expecting a failure)\n");
693   EXPECT_FATAL_FAILURE(
694       {
695         FatalFailure();
696         FatalFailure();
697       },
698       "");
699 }
700 
701 // Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal
702 // failure.
TEST(ExpectFatalFailureTest,FailsWhenThereIsOneNonfatalFailure)703 TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) {
704   printf("(expecting a failure)\n");
705   EXPECT_FATAL_FAILURE({ ADD_FAILURE() << "Expected non-fatal failure."; }, "");
706 }
707 
708 // Tests that EXPECT_FATAL_FAILURE() fails when the statement being
709 // tested returns.
TEST(ExpectFatalFailureTest,FailsWhenStatementReturns)710 TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) {
711   printf("(expecting a failure)\n");
712   EXPECT_FATAL_FAILURE({ return; }, "");
713 }
714 
715 #if GTEST_HAS_EXCEPTIONS
716 
717 // Tests that EXPECT_FATAL_FAILURE() fails when the statement being
718 // tested throws.
TEST(ExpectFatalFailureTest,FailsWhenStatementThrows)719 TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) {
720   printf("(expecting a failure)\n");
721   try {
722     EXPECT_FATAL_FAILURE({ throw 0; }, "");
723   } catch (int) {  // NOLINT
724   }
725 }
726 
727 #endif  // GTEST_HAS_EXCEPTIONS
728 
729 // This #ifdef block tests the output of value-parameterized tests.
730 
ParamNameFunc(const testing::TestParamInfo<std::string> & info)731 std::string ParamNameFunc(const testing::TestParamInfo<std::string>& info) {
732   return info.param;
733 }
734 
735 class ParamTest : public testing::TestWithParam<std::string> {};
736 
TEST_P(ParamTest,Success)737 TEST_P(ParamTest, Success) { EXPECT_EQ("a", GetParam()); }
738 
TEST_P(ParamTest,Failure)739 TEST_P(ParamTest, Failure) { EXPECT_EQ("b", GetParam()) << "Expected failure"; }
740 
741 INSTANTIATE_TEST_SUITE_P(PrintingStrings, ParamTest,
742                          testing::Values(std::string("a")), ParamNameFunc);
743 
744 // This #ifdef block tests the output of typed tests.
745 #if GTEST_HAS_TYPED_TEST
746 
747 template <typename T>
748 class TypedTest : public testing::Test {};
749 
750 TYPED_TEST_SUITE(TypedTest, testing::Types<int>);
751 
TYPED_TEST(TypedTest,Success)752 TYPED_TEST(TypedTest, Success) { EXPECT_EQ(0, TypeParam()); }
753 
TYPED_TEST(TypedTest,Failure)754 TYPED_TEST(TypedTest, Failure) {
755   EXPECT_EQ(1, TypeParam()) << "Expected failure";
756 }
757 
758 typedef testing::Types<char, int> TypesForTestWithNames;
759 
760 template <typename T>
761 class TypedTestWithNames : public testing::Test {};
762 
763 class TypedTestNames {
764  public:
765   template <typename T>
GetName(int i)766   static std::string GetName(int i) {
767     if (std::is_same<T, char>::value)
768       return std::string("char") + ::testing::PrintToString(i);
769     if (std::is_same<T, int>::value)
770       return std::string("int") + ::testing::PrintToString(i);
771   }
772 };
773 
774 TYPED_TEST_SUITE(TypedTestWithNames, TypesForTestWithNames, TypedTestNames);
775 
TYPED_TEST(TypedTestWithNames,Success)776 TYPED_TEST(TypedTestWithNames, Success) {}
777 
TYPED_TEST(TypedTestWithNames,Failure)778 TYPED_TEST(TypedTestWithNames, Failure) { FAIL(); }
779 
780 #endif  // GTEST_HAS_TYPED_TEST
781 
782 // This #ifdef block tests the output of type-parameterized tests.
783 #if GTEST_HAS_TYPED_TEST_P
784 
785 template <typename T>
786 class TypedTestP : public testing::Test {};
787 
788 TYPED_TEST_SUITE_P(TypedTestP);
789 
TYPED_TEST_P(TypedTestP,Success)790 TYPED_TEST_P(TypedTestP, Success) { EXPECT_EQ(0U, TypeParam()); }
791 
TYPED_TEST_P(TypedTestP,Failure)792 TYPED_TEST_P(TypedTestP, Failure) {
793   EXPECT_EQ(1U, TypeParam()) << "Expected failure";
794 }
795 
796 REGISTER_TYPED_TEST_SUITE_P(TypedTestP, Success, Failure);
797 
798 typedef testing::Types<unsigned char, unsigned int> UnsignedTypes;
799 INSTANTIATE_TYPED_TEST_SUITE_P(Unsigned, TypedTestP, UnsignedTypes);
800 
801 class TypedTestPNames {
802  public:
803   template <typename T>
GetName(int i)804   static std::string GetName(int i) {
805     if (std::is_same<T, unsigned char>::value) {
806       return std::string("unsignedChar") + ::testing::PrintToString(i);
807     }
808     if (std::is_same<T, unsigned int>::value) {
809       return std::string("unsignedInt") + ::testing::PrintToString(i);
810     }
811   }
812 };
813 
814 INSTANTIATE_TYPED_TEST_SUITE_P(UnsignedCustomName, TypedTestP, UnsignedTypes,
815                                TypedTestPNames);
816 
817 #endif  // GTEST_HAS_TYPED_TEST_P
818 
819 #if GTEST_HAS_DEATH_TEST
820 
821 // We rely on the golden file to verify that tests whose test case
822 // name ends with DeathTest are run first.
823 
TEST(ADeathTest,ShouldRunFirst)824 TEST(ADeathTest, ShouldRunFirst) {}
825 
826 #if GTEST_HAS_TYPED_TEST
827 
828 // We rely on the golden file to verify that typed tests whose test
829 // case name ends with DeathTest are run first.
830 
831 template <typename T>
832 class ATypedDeathTest : public testing::Test {};
833 
834 typedef testing::Types<int, double> NumericTypes;
835 TYPED_TEST_SUITE(ATypedDeathTest, NumericTypes);
836 
TYPED_TEST(ATypedDeathTest,ShouldRunFirst)837 TYPED_TEST(ATypedDeathTest, ShouldRunFirst) {}
838 
839 #endif  // GTEST_HAS_TYPED_TEST
840 
841 #if GTEST_HAS_TYPED_TEST_P
842 
843 // We rely on the golden file to verify that type-parameterized tests
844 // whose test case name ends with DeathTest are run first.
845 
846 template <typename T>
847 class ATypeParamDeathTest : public testing::Test {};
848 
849 TYPED_TEST_SUITE_P(ATypeParamDeathTest);
850 
TYPED_TEST_P(ATypeParamDeathTest,ShouldRunFirst)851 TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) {}
852 
853 REGISTER_TYPED_TEST_SUITE_P(ATypeParamDeathTest, ShouldRunFirst);
854 
855 INSTANTIATE_TYPED_TEST_SUITE_P(My, ATypeParamDeathTest, NumericTypes);
856 
857 #endif  // GTEST_HAS_TYPED_TEST_P
858 
859 #endif  // GTEST_HAS_DEATH_TEST
860 
861 // Tests various failure conditions of
862 // EXPECT_{,NON}FATAL_FAILURE{,_ON_ALL_THREADS}.
863 class ExpectFailureTest : public testing::Test {
864  public:  // Must be public and not protected due to a bug in g++ 3.4.2.
865   enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE };
AddFailure(FailureMode failure)866   static void AddFailure(FailureMode failure) {
867     if (failure == FATAL_FAILURE) {
868       FAIL() << "Expected fatal failure.";
869     } else {
870       ADD_FAILURE() << "Expected non-fatal failure.";
871     }
872   }
873 };
874 
TEST_F(ExpectFailureTest,ExpectFatalFailure)875 TEST_F(ExpectFailureTest, ExpectFatalFailure) {
876   // Expected fatal failure, but succeeds.
877   printf("(expecting 1 failure)\n");
878   EXPECT_FATAL_FAILURE(SUCCEED(), "Expected fatal failure.");
879   // Expected fatal failure, but got a non-fatal failure.
880   printf("(expecting 1 failure)\n");
881   EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE),
882                        "Expected non-fatal "
883                        "failure.");
884   // Wrong message.
885   printf("(expecting 1 failure)\n");
886   EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE),
887                        "Some other fatal failure "
888                        "expected.");
889 }
890 
TEST_F(ExpectFailureTest,ExpectNonFatalFailure)891 TEST_F(ExpectFailureTest, ExpectNonFatalFailure) {
892   // Expected non-fatal failure, but succeeds.
893   printf("(expecting 1 failure)\n");
894   EXPECT_NONFATAL_FAILURE(SUCCEED(), "Expected non-fatal failure.");
895   // Expected non-fatal failure, but got a fatal failure.
896   printf("(expecting 1 failure)\n");
897   EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure.");
898   // Wrong message.
899   printf("(expecting 1 failure)\n");
900   EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE),
901                           "Some other non-fatal "
902                           "failure.");
903 }
904 
905 #if GTEST_IS_THREADSAFE
906 
907 class ExpectFailureWithThreadsTest : public ExpectFailureTest {
908  protected:
AddFailureInOtherThread(FailureMode failure)909   static void AddFailureInOtherThread(FailureMode failure) {
910     ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr);
911     thread.Join();
912   }
913 };
914 
TEST_F(ExpectFailureWithThreadsTest,ExpectFatalFailure)915 TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailure) {
916   // We only intercept the current thread.
917   printf("(expecting 2 failures)\n");
918   EXPECT_FATAL_FAILURE(AddFailureInOtherThread(FATAL_FAILURE),
919                        "Expected fatal failure.");
920 }
921 
TEST_F(ExpectFailureWithThreadsTest,ExpectNonFatalFailure)922 TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailure) {
923   // We only intercept the current thread.
924   printf("(expecting 2 failures)\n");
925   EXPECT_NONFATAL_FAILURE(AddFailureInOtherThread(NONFATAL_FAILURE),
926                           "Expected non-fatal failure.");
927 }
928 
929 typedef ExpectFailureWithThreadsTest ScopedFakeTestPartResultReporterTest;
930 
931 // Tests that the ScopedFakeTestPartResultReporter only catches failures from
932 // the current thread if it is instantiated with INTERCEPT_ONLY_CURRENT_THREAD.
TEST_F(ScopedFakeTestPartResultReporterTest,InterceptOnlyCurrentThread)933 TEST_F(ScopedFakeTestPartResultReporterTest, InterceptOnlyCurrentThread) {
934   printf("(expecting 2 failures)\n");
935   TestPartResultArray results;
936   {
937     ScopedFakeTestPartResultReporter reporter(
938         ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
939         &results);
940     AddFailureInOtherThread(FATAL_FAILURE);
941     AddFailureInOtherThread(NONFATAL_FAILURE);
942   }
943   // The two failures should not have been intercepted.
944   EXPECT_EQ(0, results.size()) << "This shouldn't fail.";
945 }
946 
947 #endif  // GTEST_IS_THREADSAFE
948 
TEST_F(ExpectFailureTest,ExpectFatalFailureOnAllThreads)949 TEST_F(ExpectFailureTest, ExpectFatalFailureOnAllThreads) {
950   // Expected fatal failure, but succeeds.
951   printf("(expecting 1 failure)\n");
952   EXPECT_FATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected fatal failure.");
953   // Expected fatal failure, but got a non-fatal failure.
954   printf("(expecting 1 failure)\n");
955   EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE),
956                                       "Expected non-fatal failure.");
957   // Wrong message.
958   printf("(expecting 1 failure)\n");
959   EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE),
960                                       "Some other fatal failure expected.");
961 }
962 
TEST_F(ExpectFailureTest,ExpectNonFatalFailureOnAllThreads)963 TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) {
964   // Expected non-fatal failure, but succeeds.
965   printf("(expecting 1 failure)\n");
966   EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(),
967                                          "Expected non-fatal "
968                                          "failure.");
969   // Expected non-fatal failure, but got a fatal failure.
970   printf("(expecting 1 failure)\n");
971   EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE),
972                                          "Expected fatal failure.");
973   // Wrong message.
974   printf("(expecting 1 failure)\n");
975   EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE),
976                                          "Some other non-fatal failure.");
977 }
978 
979 class DynamicFixture : public testing::Test {
980  protected:
DynamicFixture()981   DynamicFixture() { printf("DynamicFixture()\n"); }
~DynamicFixture()982   ~DynamicFixture() override { printf("~DynamicFixture()\n"); }
SetUp()983   void SetUp() override { printf("DynamicFixture::SetUp\n"); }
TearDown()984   void TearDown() override { printf("DynamicFixture::TearDown\n"); }
985 
SetUpTestSuite()986   static void SetUpTestSuite() { printf("DynamicFixture::SetUpTestSuite\n"); }
TearDownTestSuite()987   static void TearDownTestSuite() {
988     printf("DynamicFixture::TearDownTestSuite\n");
989   }
990 };
991 
992 template <bool Pass>
993 class DynamicTest : public DynamicFixture {
994  public:
TestBody()995   void TestBody() override { EXPECT_TRUE(Pass); }
996 };
997 
998 auto dynamic_test = (
999     // Register two tests with the same fixture correctly.
1000     testing::RegisterTest(
1001         "DynamicFixture", "DynamicTestPass", nullptr, nullptr, __FILE__,
__anonef1893c80102() 1002         __LINE__, []() -> DynamicFixture* { return new DynamicTest<true>; }),
1003     testing::RegisterTest(
1004         "DynamicFixture", "DynamicTestFail", nullptr, nullptr, __FILE__,
__anonef1893c80202() 1005         __LINE__, []() -> DynamicFixture* { return new DynamicTest<false>; }),
1006 
1007     // Register the same fixture with another name. That's fine.
1008     testing::RegisterTest(
1009         "DynamicFixtureAnotherName", "DynamicTestPass", nullptr, nullptr,
1010         __FILE__, __LINE__,
__anonef1893c80302() 1011         []() -> DynamicFixture* { return new DynamicTest<true>; }),
1012 
1013     // Register two tests with the same fixture incorrectly.
1014     testing::RegisterTest(
1015         "BadDynamicFixture1", "FixtureBase", nullptr, nullptr, __FILE__,
__anonef1893c80402() 1016         __LINE__, []() -> DynamicFixture* { return new DynamicTest<true>; }),
1017     testing::RegisterTest(
1018         "BadDynamicFixture1", "TestBase", nullptr, nullptr, __FILE__, __LINE__,
__anonef1893c80502() 1019         []() -> testing::Test* { return new DynamicTest<true>; }),
1020 
1021     // Register two tests with the same fixture incorrectly by ommiting the
1022     // return type.
1023     testing::RegisterTest(
1024         "BadDynamicFixture2", "FixtureBase", nullptr, nullptr, __FILE__,
__anonef1893c80602() 1025         __LINE__, []() -> DynamicFixture* { return new DynamicTest<true>; }),
1026     testing::RegisterTest("BadDynamicFixture2", "Derived", nullptr, nullptr,
1027                           __FILE__, __LINE__,
__anonef1893c80702() 1028                           []() { return new DynamicTest<true>; }));
1029 
1030 // Two test environments for testing testing::AddGlobalTestEnvironment().
1031 
1032 class FooEnvironment : public testing::Environment {
1033  public:
SetUp()1034   void SetUp() override { printf("%s", "FooEnvironment::SetUp() called.\n"); }
1035 
TearDown()1036   void TearDown() override {
1037     printf("%s", "FooEnvironment::TearDown() called.\n");
1038     FAIL() << "Expected fatal failure.";
1039   }
1040 };
1041 
1042 class BarEnvironment : public testing::Environment {
1043  public:
SetUp()1044   void SetUp() override { printf("%s", "BarEnvironment::SetUp() called.\n"); }
1045 
TearDown()1046   void TearDown() override {
1047     printf("%s", "BarEnvironment::TearDown() called.\n");
1048     ADD_FAILURE() << "Expected non-fatal failure.";
1049   }
1050 };
1051 
1052 // The main function.
1053 //
1054 // The idea is to use Google Test to run all the tests we have defined (some
1055 // of them are intended to fail), and then compare the test results
1056 // with the "golden" file.
main(int argc,char ** argv)1057 int main(int argc, char** argv) {
1058   testing::GTEST_FLAG(print_time) = false;
1059 
1060   // We just run the tests, knowing some of them are intended to fail.
1061   // We will use a separate Python script to compare the output of
1062   // this program with the golden file.
1063 
1064   // It's hard to test InitGoogleTest() directly, as it has many
1065   // global side effects.  The following line serves as a sanity test
1066   // for it.
1067   testing::InitGoogleTest(&argc, argv);
1068   bool internal_skip_environment_and_ad_hoc_tests =
1069       std::count(argv, argv + argc,
1070                  std::string("internal_skip_environment_and_ad_hoc_tests")) > 0;
1071 
1072 #if GTEST_HAS_DEATH_TEST
1073   if (testing::internal::GTEST_FLAG(internal_run_death_test) != "") {
1074 // Skip the usual output capturing if we're running as the child
1075 // process of an threadsafe-style death test.
1076 #if GTEST_OS_WINDOWS
1077     posix::FReopen("nul:", "w", stdout);
1078 #else
1079     posix::FReopen("/dev/null", "w", stdout);
1080 #endif  // GTEST_OS_WINDOWS
1081     return RUN_ALL_TESTS();
1082   }
1083 #endif  // GTEST_HAS_DEATH_TEST
1084 
1085   if (internal_skip_environment_and_ad_hoc_tests) return RUN_ALL_TESTS();
1086 
1087   // Registers two global test environments.
1088   // The golden file verifies that they are set up in the order they
1089   // are registered, and torn down in the reverse order.
1090   testing::AddGlobalTestEnvironment(new FooEnvironment);
1091   testing::AddGlobalTestEnvironment(new BarEnvironment);
1092 #if _MSC_VER
1093   GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4127
1094 #endif                               //  _MSC_VER
1095   return RunAllTests();
1096 }
1097