c2f96d980d263646dba9ee45037e3ed87eaacbe3
[platform/upstream/gtest.git] / googletest / test / googletest-output-test_.cc
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 <stdlib.h>
37
38 #include "gtest/gtest-spi.h"
39 #include "gtest/gtest.h"
40 #include "src/gtest-internal-inl.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.
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.
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
77 TEST(PassingTest, PassingTest1) {}
78
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
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
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
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
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.
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.
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.
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.
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.
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.
166 void SubWithTrace(int n) {
167   SCOPED_TRACE(testing::Message() << "n = " << n);
168
169   SubWithoutTrace(n);
170 }
171
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.
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.
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.
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.
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.
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
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
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).
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
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.
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.
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:
357   NonFatalFailureInFixtureConstructorTest() {
358     printf("(expecting 5 failures)\n");
359     ADD_FAILURE() << "Expected failure #1, in the test fixture c'tor.";
360   }
361
362   ~NonFatalFailureInFixtureConstructorTest() override {
363     ADD_FAILURE() << "Expected failure #5, in the test fixture d'tor.";
364   }
365
366   void SetUp() override { ADD_FAILURE() << "Expected failure #2, in SetUp()."; }
367
368   void TearDown() override {
369     ADD_FAILURE() << "Expected failure #4, in TearDown.";
370   }
371 };
372
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:
380   FatalFailureInFixtureConstructorTest() {
381     printf("(expecting 2 failures)\n");
382     Init();
383   }
384
385   ~FatalFailureInFixtureConstructorTest() override {
386     ADD_FAILURE() << "Expected failure #2, in the test fixture d'tor.";
387   }
388
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
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:
402   void Init() { FAIL() << "Expected failure #1, in the test fixture c'tor."; }
403 };
404
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:
414   ~NonFatalFailureInSetUpTest() override { Deinit(); }
415
416   void SetUp() override {
417     printf("(expecting 4 failures)\n");
418     ADD_FAILURE() << "Expected failure #1, in SetUp().";
419   }
420
421   void TearDown() override { FAIL() << "Expected failure #3, in TearDown()."; }
422
423  private:
424   void Deinit() { FAIL() << "Expected failure #4, in the test fixture d'tor."; }
425 };
426
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:
434   ~FatalFailureInSetUpTest() override { Deinit(); }
435
436   void SetUp() override {
437     printf("(expecting 3 failures)\n");
438     FAIL() << "Expected failure #1, in SetUp().";
439   }
440
441   void TearDown() override { FAIL() << "Expected failure #2, in TearDown()."; }
442
443  private:
444   void Deinit() { FAIL() << "Expected failure #3, in the test fixture d'tor."; }
445 };
446
447 TEST_F(FatalFailureInSetUpTest, FailureInSetUp) {
448   FAIL() << "UNEXPECTED failure in the test function.  "
449          << "We should never get here, as SetUp() failed.";
450 }
451
452 TEST(AddFailureAtTest, MessageContainsSpecifiedFileAndLineNumber) {
453   ADD_FAILURE_AT("foo.cc", 42) << "Expected nonfatal failure in foo.cc";
454 }
455
456 TEST(GtestFailAtTest, MessageContainsSpecifiedFileAndLineNumber) {
457   GTEST_FAIL_AT("foo.cc", 42) << "Expected fatal failure in foo.cc";
458 }
459
460 // The MixedUpTestSuiteTest test case verifies that Google Test will fail a
461 // test if it uses a different fixture class than what other tests in
462 // the same test case use.  It deliberately contains two fixture
463 // classes with the same name but defined in different namespaces.
464
465 // The MixedUpTestSuiteWithSameTestNameTest test case verifies that
466 // when the user defines two tests with the same test case name AND
467 // same test name (but in different namespaces), the second test will
468 // fail.
469
470 namespace foo {
471
472 class MixedUpTestSuiteTest : public testing::Test {};
473
474 TEST_F(MixedUpTestSuiteTest, FirstTestFromNamespaceFoo) {}
475 TEST_F(MixedUpTestSuiteTest, SecondTestFromNamespaceFoo) {}
476
477 class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {};
478
479 TEST_F(MixedUpTestSuiteWithSameTestNameTest,
480        TheSecondTestWithThisNameShouldFail) {}
481
482 }  // namespace foo
483
484 namespace bar {
485
486 class MixedUpTestSuiteTest : public testing::Test {};
487
488 // The following two tests are expected to fail.  We rely on the
489 // golden file to check that Google Test generates the right error message.
490 TEST_F(MixedUpTestSuiteTest, ThisShouldFail) {}
491 TEST_F(MixedUpTestSuiteTest, ThisShouldFailToo) {}
492
493 class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {};
494
495 // Expected to fail.  We rely on the golden file to check that Google Test
496 // generates the right error message.
497 TEST_F(MixedUpTestSuiteWithSameTestNameTest,
498        TheSecondTestWithThisNameShouldFail) {}
499
500 }  // namespace bar
501
502 // The following two test cases verify that Google Test catches the user
503 // error of mixing TEST and TEST_F in the same test case.  The first
504 // test case checks the scenario where TEST_F appears before TEST, and
505 // the second one checks where TEST appears before TEST_F.
506
507 class TEST_F_before_TEST_in_same_test_case : public testing::Test {};
508
509 TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {}
510
511 // Expected to fail.  We rely on the golden file to check that Google Test
512 // generates the right error message.
513 TEST(TEST_F_before_TEST_in_same_test_case, DefinedUsingTESTAndShouldFail) {}
514
515 class TEST_before_TEST_F_in_same_test_case : public testing::Test {};
516
517 TEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {}
518
519 // Expected to fail.  We rely on the golden file to check that Google Test
520 // generates the right error message.
521 TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) {}
522
523 // Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE().
524 int global_integer = 0;
525
526 // Tests that EXPECT_NONFATAL_FAILURE() can reference global variables.
527 TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) {
528   global_integer = 0;
529   EXPECT_NONFATAL_FAILURE(
530       { EXPECT_EQ(1, global_integer) << "Expected non-fatal failure."; },
531       "Expected non-fatal failure.");
532 }
533
534 // Tests that EXPECT_NONFATAL_FAILURE() can reference local variables
535 // (static or not).
536 TEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) {
537   int m = 0;
538   static int n;
539   n = 1;
540   EXPECT_NONFATAL_FAILURE({ EXPECT_EQ(m, n) << "Expected non-fatal failure."; },
541                           "Expected non-fatal failure.");
542 }
543
544 // Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly
545 // one non-fatal failure and no fatal failure.
546 TEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) {
547   EXPECT_NONFATAL_FAILURE({ ADD_FAILURE() << "Expected non-fatal failure."; },
548                           "Expected non-fatal failure.");
549 }
550
551 // Tests that EXPECT_NONFATAL_FAILURE() fails when there is no
552 // non-fatal failure.
553 TEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) {
554   printf("(expecting a failure)\n");
555   EXPECT_NONFATAL_FAILURE({}, "");
556 }
557
558 // Tests that EXPECT_NONFATAL_FAILURE() fails when there are two
559 // non-fatal failures.
560 TEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) {
561   printf("(expecting a failure)\n");
562   EXPECT_NONFATAL_FAILURE(
563       {
564         ADD_FAILURE() << "Expected non-fatal failure 1.";
565         ADD_FAILURE() << "Expected non-fatal failure 2.";
566       },
567       "");
568 }
569
570 // Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal
571 // failure.
572 TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) {
573   printf("(expecting a failure)\n");
574   EXPECT_NONFATAL_FAILURE({ FAIL() << "Expected fatal failure."; }, "");
575 }
576
577 // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
578 // tested returns.
579 TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) {
580   printf("(expecting a failure)\n");
581   EXPECT_NONFATAL_FAILURE({ return; }, "");
582 }
583
584 #if GTEST_HAS_EXCEPTIONS
585
586 // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
587 // tested throws.
588 TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) {
589   printf("(expecting a failure)\n");
590   try {
591     EXPECT_NONFATAL_FAILURE({ throw 0; }, "");
592   } catch (int) {  // NOLINT
593   }
594 }
595
596 #endif  // GTEST_HAS_EXCEPTIONS
597
598 // Tests that EXPECT_FATAL_FAILURE() can reference global variables.
599 TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) {
600   global_integer = 0;
601   EXPECT_FATAL_FAILURE(
602       { ASSERT_EQ(1, global_integer) << "Expected fatal failure."; },
603       "Expected fatal failure.");
604 }
605
606 // Tests that EXPECT_FATAL_FAILURE() can reference local static
607 // variables.
608 TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) {
609   static int n;
610   n = 1;
611   EXPECT_FATAL_FAILURE({ ASSERT_EQ(0, n) << "Expected fatal failure."; },
612                        "Expected fatal failure.");
613 }
614
615 // Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly
616 // one fatal failure and no non-fatal failure.
617 TEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) {
618   EXPECT_FATAL_FAILURE({ FAIL() << "Expected fatal failure."; },
619                        "Expected fatal failure.");
620 }
621
622 // Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal
623 // failure.
624 TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) {
625   printf("(expecting a failure)\n");
626   EXPECT_FATAL_FAILURE({}, "");
627 }
628
629 // A helper for generating a fatal failure.
630 void FatalFailure() { FAIL() << "Expected fatal failure."; }
631
632 // Tests that EXPECT_FATAL_FAILURE() fails when there are two
633 // fatal failures.
634 TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) {
635   printf("(expecting a failure)\n");
636   EXPECT_FATAL_FAILURE(
637       {
638         FatalFailure();
639         FatalFailure();
640       },
641       "");
642 }
643
644 // Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal
645 // failure.
646 TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) {
647   printf("(expecting a failure)\n");
648   EXPECT_FATAL_FAILURE({ ADD_FAILURE() << "Expected non-fatal failure."; }, "");
649 }
650
651 // Tests that EXPECT_FATAL_FAILURE() fails when the statement being
652 // tested returns.
653 TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) {
654   printf("(expecting a failure)\n");
655   EXPECT_FATAL_FAILURE({ return; }, "");
656 }
657
658 #if GTEST_HAS_EXCEPTIONS
659
660 // Tests that EXPECT_FATAL_FAILURE() fails when the statement being
661 // tested throws.
662 TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) {
663   printf("(expecting a failure)\n");
664   try {
665     EXPECT_FATAL_FAILURE({ throw 0; }, "");
666   } catch (int) {  // NOLINT
667   }
668 }
669
670 #endif  // GTEST_HAS_EXCEPTIONS
671
672 // This #ifdef block tests the output of value-parameterized tests.
673
674 std::string ParamNameFunc(const testing::TestParamInfo<std::string>& info) {
675   return info.param;
676 }
677
678 class ParamTest : public testing::TestWithParam<std::string> {};
679
680 TEST_P(ParamTest, Success) { EXPECT_EQ("a", GetParam()); }
681
682 TEST_P(ParamTest, Failure) { EXPECT_EQ("b", GetParam()) << "Expected failure"; }
683
684 INSTANTIATE_TEST_SUITE_P(PrintingStrings, ParamTest,
685                          testing::Values(std::string("a")), ParamNameFunc);
686
687 // The case where a suite has INSTANTIATE_TEST_SUITE_P but not TEST_P.
688 using NoTests = ParamTest;
689 INSTANTIATE_TEST_SUITE_P(ThisIsOdd, NoTests, ::testing::Values("Hello"));
690
691 // fails under kErrorOnUninstantiatedParameterizedTest=true
692 class DetectNotInstantiatedTest : public testing::TestWithParam<int> {};
693 TEST_P(DetectNotInstantiatedTest, Used) {}
694
695 // This would make the test failure from the above go away.
696 // INSTANTIATE_TEST_SUITE_P(Fix, DetectNotInstantiatedTest, testing::Values(1));
697
698 template <typename T>
699 class TypedTest : public testing::Test {};
700
701 TYPED_TEST_SUITE(TypedTest, testing::Types<int>);
702
703 TYPED_TEST(TypedTest, Success) { EXPECT_EQ(0, TypeParam()); }
704
705 TYPED_TEST(TypedTest, Failure) {
706   EXPECT_EQ(1, TypeParam()) << "Expected failure";
707 }
708
709 typedef testing::Types<char, int> TypesForTestWithNames;
710
711 template <typename T>
712 class TypedTestWithNames : public testing::Test {};
713
714 class TypedTestNames {
715  public:
716   template <typename T>
717   static std::string GetName(int i) {
718     if (std::is_same<T, char>::value)
719       return std::string("char") + ::testing::PrintToString(i);
720     if (std::is_same<T, int>::value)
721       return std::string("int") + ::testing::PrintToString(i);
722   }
723 };
724
725 TYPED_TEST_SUITE(TypedTestWithNames, TypesForTestWithNames, TypedTestNames);
726
727 TYPED_TEST(TypedTestWithNames, Success) {}
728
729 TYPED_TEST(TypedTestWithNames, Failure) { FAIL(); }
730
731 template <typename T>
732 class TypedTestP : public testing::Test {};
733
734 TYPED_TEST_SUITE_P(TypedTestP);
735
736 TYPED_TEST_P(TypedTestP, Success) { EXPECT_EQ(0U, TypeParam()); }
737
738 TYPED_TEST_P(TypedTestP, Failure) {
739   EXPECT_EQ(1U, TypeParam()) << "Expected failure";
740 }
741
742 REGISTER_TYPED_TEST_SUITE_P(TypedTestP, Success, Failure);
743
744 typedef testing::Types<unsigned char, unsigned int> UnsignedTypes;
745 INSTANTIATE_TYPED_TEST_SUITE_P(Unsigned, TypedTestP, UnsignedTypes);
746
747 class TypedTestPNames {
748  public:
749   template <typename T>
750   static std::string GetName(int i) {
751     if (std::is_same<T, unsigned char>::value) {
752       return std::string("unsignedChar") + ::testing::PrintToString(i);
753     }
754     if (std::is_same<T, unsigned int>::value) {
755       return std::string("unsignedInt") + ::testing::PrintToString(i);
756     }
757   }
758 };
759
760 INSTANTIATE_TYPED_TEST_SUITE_P(UnsignedCustomName, TypedTestP, UnsignedTypes,
761                                TypedTestPNames);
762
763 template <typename T>
764 class DetectNotInstantiatedTypesTest : public testing::Test {};
765 TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest);
766 TYPED_TEST_P(DetectNotInstantiatedTypesTest, Used) {
767   TypeParam instantiate;
768   (void)instantiate;
769 }
770 REGISTER_TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest, Used);
771
772 // kErrorOnUninstantiatedTypeParameterizedTest=true would make the above fail.
773 // Adding the following would make that test failure go away.
774 //
775 // typedef ::testing::Types<char, int, unsigned int> MyTypes;
776 // INSTANTIATE_TYPED_TEST_SUITE_P(All, DetectNotInstantiatedTypesTest, MyTypes);
777
778 #if GTEST_HAS_DEATH_TEST
779
780 // We rely on the golden file to verify that tests whose test case
781 // name ends with DeathTest are run first.
782
783 TEST(ADeathTest, ShouldRunFirst) {}
784
785 // We rely on the golden file to verify that typed tests whose test
786 // case name ends with DeathTest are run first.
787
788 template <typename T>
789 class ATypedDeathTest : public testing::Test {};
790
791 typedef testing::Types<int, double> NumericTypes;
792 TYPED_TEST_SUITE(ATypedDeathTest, NumericTypes);
793
794 TYPED_TEST(ATypedDeathTest, ShouldRunFirst) {}
795
796 // We rely on the golden file to verify that type-parameterized tests
797 // whose test case name ends with DeathTest are run first.
798
799 template <typename T>
800 class ATypeParamDeathTest : public testing::Test {};
801
802 TYPED_TEST_SUITE_P(ATypeParamDeathTest);
803
804 TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) {}
805
806 REGISTER_TYPED_TEST_SUITE_P(ATypeParamDeathTest, ShouldRunFirst);
807
808 INSTANTIATE_TYPED_TEST_SUITE_P(My, ATypeParamDeathTest, NumericTypes);
809
810 #endif  // GTEST_HAS_DEATH_TEST
811
812 // Tests various failure conditions of
813 // EXPECT_{,NON}FATAL_FAILURE{,_ON_ALL_THREADS}.
814 class ExpectFailureTest : public testing::Test {
815  public:  // Must be public and not protected due to a bug in g++ 3.4.2.
816   enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE };
817   static void AddFailure(FailureMode failure) {
818     if (failure == FATAL_FAILURE) {
819       FAIL() << "Expected fatal failure.";
820     } else {
821       ADD_FAILURE() << "Expected non-fatal failure.";
822     }
823   }
824 };
825
826 TEST_F(ExpectFailureTest, ExpectFatalFailure) {
827   // Expected fatal failure, but succeeds.
828   printf("(expecting 1 failure)\n");
829   EXPECT_FATAL_FAILURE(SUCCEED(), "Expected fatal failure.");
830   // Expected fatal failure, but got a non-fatal failure.
831   printf("(expecting 1 failure)\n");
832   EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE),
833                        "Expected non-fatal "
834                        "failure.");
835   // Wrong message.
836   printf("(expecting 1 failure)\n");
837   EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE),
838                        "Some other fatal failure "
839                        "expected.");
840 }
841
842 TEST_F(ExpectFailureTest, ExpectNonFatalFailure) {
843   // Expected non-fatal failure, but succeeds.
844   printf("(expecting 1 failure)\n");
845   EXPECT_NONFATAL_FAILURE(SUCCEED(), "Expected non-fatal failure.");
846   // Expected non-fatal failure, but got a fatal failure.
847   printf("(expecting 1 failure)\n");
848   EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure.");
849   // Wrong message.
850   printf("(expecting 1 failure)\n");
851   EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE),
852                           "Some other non-fatal "
853                           "failure.");
854 }
855
856 #if GTEST_IS_THREADSAFE
857
858 class ExpectFailureWithThreadsTest : public ExpectFailureTest {
859  protected:
860   static void AddFailureInOtherThread(FailureMode failure) {
861     ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr);
862     thread.Join();
863   }
864 };
865
866 TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailure) {
867   // We only intercept the current thread.
868   printf("(expecting 2 failures)\n");
869   EXPECT_FATAL_FAILURE(AddFailureInOtherThread(FATAL_FAILURE),
870                        "Expected fatal failure.");
871 }
872
873 TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailure) {
874   // We only intercept the current thread.
875   printf("(expecting 2 failures)\n");
876   EXPECT_NONFATAL_FAILURE(AddFailureInOtherThread(NONFATAL_FAILURE),
877                           "Expected non-fatal failure.");
878 }
879
880 typedef ExpectFailureWithThreadsTest ScopedFakeTestPartResultReporterTest;
881
882 // Tests that the ScopedFakeTestPartResultReporter only catches failures from
883 // the current thread if it is instantiated with INTERCEPT_ONLY_CURRENT_THREAD.
884 TEST_F(ScopedFakeTestPartResultReporterTest, InterceptOnlyCurrentThread) {
885   printf("(expecting 2 failures)\n");
886   TestPartResultArray results;
887   {
888     ScopedFakeTestPartResultReporter reporter(
889         ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
890         &results);
891     AddFailureInOtherThread(FATAL_FAILURE);
892     AddFailureInOtherThread(NONFATAL_FAILURE);
893   }
894   // The two failures should not have been intercepted.
895   EXPECT_EQ(0, results.size()) << "This shouldn't fail.";
896 }
897
898 #endif  // GTEST_IS_THREADSAFE
899
900 TEST_F(ExpectFailureTest, ExpectFatalFailureOnAllThreads) {
901   // Expected fatal failure, but succeeds.
902   printf("(expecting 1 failure)\n");
903   EXPECT_FATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected fatal failure.");
904   // Expected fatal failure, but got a non-fatal failure.
905   printf("(expecting 1 failure)\n");
906   EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE),
907                                       "Expected non-fatal failure.");
908   // Wrong message.
909   printf("(expecting 1 failure)\n");
910   EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE),
911                                       "Some other fatal failure expected.");
912 }
913
914 TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) {
915   // Expected non-fatal failure, but succeeds.
916   printf("(expecting 1 failure)\n");
917   EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(),
918                                          "Expected non-fatal "
919                                          "failure.");
920   // Expected non-fatal failure, but got a fatal failure.
921   printf("(expecting 1 failure)\n");
922   EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE),
923                                          "Expected fatal failure.");
924   // Wrong message.
925   printf("(expecting 1 failure)\n");
926   EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE),
927                                          "Some other non-fatal failure.");
928 }
929
930 class DynamicFixture : public testing::Test {
931  protected:
932   DynamicFixture() { printf("DynamicFixture()\n"); }
933   ~DynamicFixture() override { printf("~DynamicFixture()\n"); }
934   void SetUp() override { printf("DynamicFixture::SetUp\n"); }
935   void TearDown() override { printf("DynamicFixture::TearDown\n"); }
936
937   static void SetUpTestSuite() { printf("DynamicFixture::SetUpTestSuite\n"); }
938   static void TearDownTestSuite() {
939     printf("DynamicFixture::TearDownTestSuite\n");
940   }
941 };
942
943 template <bool Pass>
944 class DynamicTest : public DynamicFixture {
945  public:
946   void TestBody() override { EXPECT_TRUE(Pass); }
947 };
948
949 auto dynamic_test = (
950     // Register two tests with the same fixture correctly.
951     testing::RegisterTest(
952         "DynamicFixture", "DynamicTestPass", nullptr, nullptr, __FILE__,
953         __LINE__, []() -> DynamicFixture* { return new DynamicTest<true>; }),
954     testing::RegisterTest(
955         "DynamicFixture", "DynamicTestFail", nullptr, nullptr, __FILE__,
956         __LINE__, []() -> DynamicFixture* { return new DynamicTest<false>; }),
957
958     // Register the same fixture with another name. That's fine.
959     testing::RegisterTest(
960         "DynamicFixtureAnotherName", "DynamicTestPass", nullptr, nullptr,
961         __FILE__, __LINE__,
962         []() -> DynamicFixture* { return new DynamicTest<true>; }),
963
964     // Register two tests with the same fixture incorrectly.
965     testing::RegisterTest(
966         "BadDynamicFixture1", "FixtureBase", nullptr, nullptr, __FILE__,
967         __LINE__, []() -> DynamicFixture* { return new DynamicTest<true>; }),
968     testing::RegisterTest(
969         "BadDynamicFixture1", "TestBase", nullptr, nullptr, __FILE__, __LINE__,
970         []() -> testing::Test* { return new DynamicTest<true>; }),
971
972     // Register two tests with the same fixture incorrectly by omitting the
973     // return type.
974     testing::RegisterTest(
975         "BadDynamicFixture2", "FixtureBase", nullptr, nullptr, __FILE__,
976         __LINE__, []() -> DynamicFixture* { return new DynamicTest<true>; }),
977     testing::RegisterTest("BadDynamicFixture2", "Derived", nullptr, nullptr,
978                           __FILE__, __LINE__,
979                           []() { return new DynamicTest<true>; }));
980
981 // Two test environments for testing testing::AddGlobalTestEnvironment().
982
983 class FooEnvironment : public testing::Environment {
984  public:
985   void SetUp() override { printf("%s", "FooEnvironment::SetUp() called.\n"); }
986
987   void TearDown() override {
988     printf("%s", "FooEnvironment::TearDown() called.\n");
989     FAIL() << "Expected fatal failure.";
990   }
991 };
992
993 class BarEnvironment : public testing::Environment {
994  public:
995   void SetUp() override { printf("%s", "BarEnvironment::SetUp() called.\n"); }
996
997   void TearDown() override {
998     printf("%s", "BarEnvironment::TearDown() called.\n");
999     ADD_FAILURE() << "Expected non-fatal failure.";
1000   }
1001 };
1002
1003 class TestSuiteThatFailsToSetUp : public testing::Test {
1004  public:
1005   static void SetUpTestSuite() { EXPECT_TRUE(false); }
1006 };
1007 TEST_F(TestSuiteThatFailsToSetUp, ShouldNotRun) { std::abort(); }
1008
1009 // The main function.
1010 //
1011 // The idea is to use Google Test to run all the tests we have defined (some
1012 // of them are intended to fail), and then compare the test results
1013 // with the "golden" file.
1014 int main(int argc, char** argv) {
1015   GTEST_FLAG_SET(print_time, false);
1016
1017   // We just run the tests, knowing some of them are intended to fail.
1018   // We will use a separate Python script to compare the output of
1019   // this program with the golden file.
1020
1021   // It's hard to test InitGoogleTest() directly, as it has many
1022   // global side effects.  The following line serves as a test
1023   // for it.
1024   testing::InitGoogleTest(&argc, argv);
1025   bool internal_skip_environment_and_ad_hoc_tests =
1026       std::count(argv, argv + argc,
1027                  std::string("internal_skip_environment_and_ad_hoc_tests")) > 0;
1028
1029 #if GTEST_HAS_DEATH_TEST
1030   if (GTEST_FLAG_GET(internal_run_death_test) != "") {
1031     // Skip the usual output capturing if we're running as the child
1032     // process of an threadsafe-style death test.
1033 #if GTEST_OS_WINDOWS
1034     posix::FReopen("nul:", "w", stdout);
1035 #else
1036     posix::FReopen("/dev/null", "w", stdout);
1037 #endif  // GTEST_OS_WINDOWS
1038     return RUN_ALL_TESTS();
1039   }
1040 #endif  // GTEST_HAS_DEATH_TEST
1041
1042   if (internal_skip_environment_and_ad_hoc_tests) return RUN_ALL_TESTS();
1043
1044   // Registers two global test environments.
1045   // The golden file verifies that they are set up in the order they
1046   // are registered, and torn down in the reverse order.
1047   testing::AddGlobalTestEnvironment(new FooEnvironment);
1048   testing::AddGlobalTestEnvironment(new BarEnvironment);
1049 #if _MSC_VER
1050   GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4127
1051 #endif                               //  _MSC_VER
1052   return RunAllTests();
1053 }