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