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