• 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 // A unit test for Google Test itself.  This verifies that the basic
31 // constructs of Google Test work.
32 //
33 // Author: wan@google.com (Zhanyong Wan)
34 
35 #include <gtest/gtest-spi.h>
36 #include <gtest/gtest.h>
37 
38 // Indicates that this translation unit is part of Google Test's
39 // implementation.  It must come before gtest-internal-inl.h is
40 // included, or there will be a compiler error.  This trick is to
41 // prevent a user from accidentally including gtest-internal-inl.h in
42 // his code.
43 #define GTEST_IMPLEMENTATION_ 1
44 #include "src/gtest-internal-inl.h"
45 #undef GTEST_IMPLEMENTATION_
46 
47 #include <stdlib.h>
48 
49 #if GTEST_HAS_PTHREAD
50 #include <pthread.h>
51 #endif  // GTEST_HAS_PTHREAD
52 
53 using testing::ScopedFakeTestPartResultReporter;
54 using testing::TestPartResultArray;
55 
56 namespace posix = ::testing::internal::posix;
57 using testing::internal::String;
58 
59 // Tests catching fatal failures.
60 
61 // A subroutine used by the following test.
TestEq1(int x)62 void TestEq1(int x) {
63   ASSERT_EQ(1, x);
64 }
65 
66 // This function calls a test subroutine, catches the fatal failure it
67 // generates, and then returns early.
TryTestSubroutine()68 void TryTestSubroutine() {
69   // Calls a subrountine that yields a fatal failure.
70   TestEq1(2);
71 
72   // Catches the fatal failure and aborts the test.
73   //
74   // The testing::Test:: prefix is necessary when calling
75   // HasFatalFailure() outside of a TEST, TEST_F, or test fixture.
76   if (testing::Test::HasFatalFailure()) return;
77 
78   // If we get here, something is wrong.
79   FAIL() << "This should never be reached.";
80 }
81 
TEST(PassingTest,PassingTest1)82 TEST(PassingTest, PassingTest1) {
83 }
84 
TEST(PassingTest,PassingTest2)85 TEST(PassingTest, PassingTest2) {
86 }
87 
88 // Tests catching a fatal failure in a subroutine.
TEST(FatalFailureTest,FatalFailureInSubroutine)89 TEST(FatalFailureTest, FatalFailureInSubroutine) {
90   printf("(expecting a failure that x should be 1)\n");
91 
92   TryTestSubroutine();
93 }
94 
95 // Tests catching a fatal failure in a nested subroutine.
TEST(FatalFailureTest,FatalFailureInNestedSubroutine)96 TEST(FatalFailureTest, FatalFailureInNestedSubroutine) {
97   printf("(expecting a failure that x should be 1)\n");
98 
99   // Calls a subrountine that yields a fatal failure.
100   TryTestSubroutine();
101 
102   // Catches the fatal failure and aborts the test.
103   //
104   // When calling HasFatalFailure() inside a TEST, TEST_F, or test
105   // fixture, the testing::Test:: prefix is not needed.
106   if (HasFatalFailure()) return;
107 
108   // If we get here, something is wrong.
109   FAIL() << "This should never be reached.";
110 }
111 
112 // Tests HasFatalFailure() after a failed EXPECT check.
TEST(FatalFailureTest,NonfatalFailureInSubroutine)113 TEST(FatalFailureTest, NonfatalFailureInSubroutine) {
114   printf("(expecting a failure on false)\n");
115   EXPECT_TRUE(false);  // Generates a nonfatal failure
116   ASSERT_FALSE(HasFatalFailure());  // This should succeed.
117 }
118 
119 // Tests interleaving user logging and Google Test assertions.
TEST(LoggingTest,InterleavingLoggingAndAssertions)120 TEST(LoggingTest, InterleavingLoggingAndAssertions) {
121   static const int a[4] = {
122     3, 9, 2, 6
123   };
124 
125   printf("(expecting 2 failures on (3) >= (a[i]))\n");
126   for (int i = 0; i < static_cast<int>(sizeof(a)/sizeof(*a)); i++) {
127     printf("i == %d\n", i);
128     EXPECT_GE(3, a[i]);
129   }
130 }
131 
132 // Tests the SCOPED_TRACE macro.
133 
134 // A helper function for testing SCOPED_TRACE.
SubWithoutTrace(int n)135 void SubWithoutTrace(int n) {
136   EXPECT_EQ(1, n);
137   ASSERT_EQ(2, n);
138 }
139 
140 // Another helper function for testing SCOPED_TRACE.
SubWithTrace(int n)141 void SubWithTrace(int n) {
142   SCOPED_TRACE(testing::Message() << "n = " << n);
143 
144   SubWithoutTrace(n);
145 }
146 
147 // Tests that SCOPED_TRACE() obeys lexical scopes.
TEST(SCOPED_TRACETest,ObeysScopes)148 TEST(SCOPED_TRACETest, ObeysScopes) {
149   printf("(expected to fail)\n");
150 
151   // There should be no trace before SCOPED_TRACE() is invoked.
152   ADD_FAILURE() << "This failure is expected, and shouldn't have a trace.";
153 
154   {
155     SCOPED_TRACE("Expected trace");
156     // After SCOPED_TRACE(), a failure in the current scope should contain
157     // the trace.
158     ADD_FAILURE() << "This failure is expected, and should have a trace.";
159   }
160 
161   // Once the control leaves the scope of the SCOPED_TRACE(), there
162   // should be no trace again.
163   ADD_FAILURE() << "This failure is expected, and shouldn't have a trace.";
164 }
165 
166 // Tests that SCOPED_TRACE works inside a loop.
TEST(SCOPED_TRACETest,WorksInLoop)167 TEST(SCOPED_TRACETest, WorksInLoop) {
168   printf("(expected to fail)\n");
169 
170   for (int i = 1; i <= 2; i++) {
171     SCOPED_TRACE(testing::Message() << "i = " << i);
172 
173     SubWithoutTrace(i);
174   }
175 }
176 
177 // Tests that SCOPED_TRACE works in a subroutine.
TEST(SCOPED_TRACETest,WorksInSubroutine)178 TEST(SCOPED_TRACETest, WorksInSubroutine) {
179   printf("(expected to fail)\n");
180 
181   SubWithTrace(1);
182   SubWithTrace(2);
183 }
184 
185 // Tests that SCOPED_TRACE can be nested.
TEST(SCOPED_TRACETest,CanBeNested)186 TEST(SCOPED_TRACETest, CanBeNested) {
187   printf("(expected to fail)\n");
188 
189   SCOPED_TRACE("");  // A trace without a message.
190 
191   SubWithTrace(2);
192 }
193 
194 // Tests that multiple SCOPED_TRACEs can be used in the same scope.
TEST(SCOPED_TRACETest,CanBeRepeated)195 TEST(SCOPED_TRACETest, CanBeRepeated) {
196   printf("(expected to fail)\n");
197 
198   SCOPED_TRACE("A");
199   ADD_FAILURE()
200       << "This failure is expected, and should contain trace point A.";
201 
202   SCOPED_TRACE("B");
203   ADD_FAILURE()
204       << "This failure is expected, and should contain trace point A and B.";
205 
206   {
207     SCOPED_TRACE("C");
208     ADD_FAILURE() << "This failure is expected, and should contain "
209                   << "trace point A, B, and C.";
210   }
211 
212   SCOPED_TRACE("D");
213   ADD_FAILURE() << "This failure is expected, and should contain "
214                 << "trace point A, B, and D.";
215 }
216 
TEST(DisabledTestsWarningTest,DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning)217 TEST(DisabledTestsWarningTest,
218      DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning) {
219   // This test body is intentionally empty.  Its sole purpose is for
220   // verifying that the --gtest_also_run_disabled_tests flag
221   // suppresses the "YOU HAVE 12 DISABLED TESTS" warning at the end of
222   // the test output.
223 }
224 
225 // Tests using assertions outside of TEST and TEST_F.
226 //
227 // This function creates two failures intentionally.
AdHocTest()228 void AdHocTest() {
229   printf("The non-test part of the code is expected to have 2 failures.\n\n");
230   EXPECT_TRUE(false);
231   EXPECT_EQ(2, 3);
232 }
233 
234 // Runs all TESTs, all TEST_Fs, and the ad hoc test.
RunAllTests()235 int RunAllTests() {
236   AdHocTest();
237   return RUN_ALL_TESTS();
238 }
239 
240 // Tests non-fatal failures in the fixture constructor.
241 class NonFatalFailureInFixtureConstructorTest : public testing::Test {
242  protected:
NonFatalFailureInFixtureConstructorTest()243   NonFatalFailureInFixtureConstructorTest() {
244     printf("(expecting 5 failures)\n");
245     ADD_FAILURE() << "Expected failure #1, in the test fixture c'tor.";
246   }
247 
~NonFatalFailureInFixtureConstructorTest()248   ~NonFatalFailureInFixtureConstructorTest() {
249     ADD_FAILURE() << "Expected failure #5, in the test fixture d'tor.";
250   }
251 
SetUp()252   virtual void SetUp() {
253     ADD_FAILURE() << "Expected failure #2, in SetUp().";
254   }
255 
TearDown()256   virtual void TearDown() {
257     ADD_FAILURE() << "Expected failure #4, in TearDown.";
258   }
259 };
260 
TEST_F(NonFatalFailureInFixtureConstructorTest,FailureInConstructor)261 TEST_F(NonFatalFailureInFixtureConstructorTest, FailureInConstructor) {
262   ADD_FAILURE() << "Expected failure #3, in the test body.";
263 }
264 
265 // Tests fatal failures in the fixture constructor.
266 class FatalFailureInFixtureConstructorTest : public testing::Test {
267  protected:
FatalFailureInFixtureConstructorTest()268   FatalFailureInFixtureConstructorTest() {
269     printf("(expecting 2 failures)\n");
270     Init();
271   }
272 
~FatalFailureInFixtureConstructorTest()273   ~FatalFailureInFixtureConstructorTest() {
274     ADD_FAILURE() << "Expected failure #2, in the test fixture d'tor.";
275   }
276 
SetUp()277   virtual void SetUp() {
278     ADD_FAILURE() << "UNEXPECTED failure in SetUp().  "
279                   << "We should never get here, as the test fixture c'tor "
280                   << "had a fatal failure.";
281   }
282 
TearDown()283   virtual void TearDown() {
284     ADD_FAILURE() << "UNEXPECTED failure in TearDown().  "
285                   << "We should never get here, as the test fixture c'tor "
286                   << "had a fatal failure.";
287   }
288  private:
Init()289   void Init() {
290     FAIL() << "Expected failure #1, in the test fixture c'tor.";
291   }
292 };
293 
TEST_F(FatalFailureInFixtureConstructorTest,FailureInConstructor)294 TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) {
295   ADD_FAILURE() << "UNEXPECTED failure in the test body.  "
296                 << "We should never get here, as the test fixture c'tor "
297                 << "had a fatal failure.";
298 }
299 
300 // Tests non-fatal failures in SetUp().
301 class NonFatalFailureInSetUpTest : public testing::Test {
302  protected:
~NonFatalFailureInSetUpTest()303   virtual ~NonFatalFailureInSetUpTest() {
304     Deinit();
305   }
306 
SetUp()307   virtual void SetUp() {
308     printf("(expecting 4 failures)\n");
309     ADD_FAILURE() << "Expected failure #1, in SetUp().";
310   }
311 
TearDown()312   virtual void TearDown() {
313     FAIL() << "Expected failure #3, in TearDown().";
314   }
315  private:
Deinit()316   void Deinit() {
317     FAIL() << "Expected failure #4, in the test fixture d'tor.";
318   }
319 };
320 
TEST_F(NonFatalFailureInSetUpTest,FailureInSetUp)321 TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) {
322   FAIL() << "Expected failure #2, in the test function.";
323 }
324 
325 // Tests fatal failures in SetUp().
326 class FatalFailureInSetUpTest : public testing::Test {
327  protected:
~FatalFailureInSetUpTest()328   virtual ~FatalFailureInSetUpTest() {
329     Deinit();
330   }
331 
SetUp()332   virtual void SetUp() {
333     printf("(expecting 3 failures)\n");
334     FAIL() << "Expected failure #1, in SetUp().";
335   }
336 
TearDown()337   virtual void TearDown() {
338     FAIL() << "Expected failure #2, in TearDown().";
339   }
340  private:
Deinit()341   void Deinit() {
342     FAIL() << "Expected failure #3, in the test fixture d'tor.";
343   }
344 };
345 
TEST_F(FatalFailureInSetUpTest,FailureInSetUp)346 TEST_F(FatalFailureInSetUpTest, FailureInSetUp) {
347   FAIL() << "UNEXPECTED failure in the test function.  "
348          << "We should never get here, as SetUp() failed.";
349 }
350 
351 #if GTEST_OS_WINDOWS
352 
353 // This group of tests verifies that Google Test handles SEH and C++
354 // exceptions correctly.
355 
356 // A function that throws an SEH exception.
ThrowSEH()357 static void ThrowSEH() {
358   int* p = NULL;
359   *p = 0;  // Raises an access violation.
360 }
361 
362 // Tests exceptions thrown in the test fixture constructor.
363 class ExceptionInFixtureCtorTest : public testing::Test {
364  protected:
ExceptionInFixtureCtorTest()365   ExceptionInFixtureCtorTest() {
366     printf("(expecting a failure on thrown exception "
367            "in the test fixture's constructor)\n");
368 
369     ThrowSEH();
370   }
371 
~ExceptionInFixtureCtorTest()372   virtual ~ExceptionInFixtureCtorTest() {
373     Deinit();
374   }
375 
SetUp()376   virtual void SetUp() {
377     FAIL() << "UNEXPECTED failure in SetUp().  "
378            << "We should never get here, as the test fixture c'tor threw.";
379   }
380 
TearDown()381   virtual void TearDown() {
382     FAIL() << "UNEXPECTED failure in TearDown().  "
383            << "We should never get here, as the test fixture c'tor threw.";
384   }
385  private:
Deinit()386   void Deinit() {
387     FAIL() << "UNEXPECTED failure in the d'tor.  "
388            << "We should never get here, as the test fixture c'tor threw.";
389   }
390 };
391 
TEST_F(ExceptionInFixtureCtorTest,ExceptionInFixtureCtor)392 TEST_F(ExceptionInFixtureCtorTest, ExceptionInFixtureCtor) {
393   FAIL() << "UNEXPECTED failure in the test function.  "
394          << "We should never get here, as the test fixture c'tor threw.";
395 }
396 
397 // Tests exceptions thrown in SetUp().
398 class ExceptionInSetUpTest : public testing::Test {
399  protected:
~ExceptionInSetUpTest()400   virtual ~ExceptionInSetUpTest() {
401     Deinit();
402   }
403 
SetUp()404   virtual void SetUp() {
405     printf("(expecting 3 failures)\n");
406 
407     ThrowSEH();
408   }
409 
TearDown()410   virtual void TearDown() {
411     FAIL() << "Expected failure #2, in TearDown().";
412   }
413  private:
Deinit()414   void Deinit() {
415     FAIL() << "Expected failure #3, in the test fixture d'tor.";
416   }
417 };
418 
TEST_F(ExceptionInSetUpTest,ExceptionInSetUp)419 TEST_F(ExceptionInSetUpTest, ExceptionInSetUp) {
420   FAIL() << "UNEXPECTED failure in the test function.  "
421          << "We should never get here, as SetUp() threw.";
422 }
423 
424 // Tests that TearDown() and the test fixture d'tor are always called,
425 // even when the test function throws an exception.
426 class ExceptionInTestFunctionTest : public testing::Test {
427  protected:
~ExceptionInTestFunctionTest()428   virtual ~ExceptionInTestFunctionTest() {
429     Deinit();
430   }
431 
TearDown()432   virtual void TearDown() {
433     FAIL() << "Expected failure #2, in TearDown().";
434   }
435  private:
Deinit()436   void Deinit() {
437     FAIL() << "Expected failure #3, in the test fixture d'tor.";
438   }
439 };
440 
441 // Tests that the test fixture d'tor is always called, even when the
442 // test function throws an SEH exception.
TEST_F(ExceptionInTestFunctionTest,SEH)443 TEST_F(ExceptionInTestFunctionTest, SEH) {
444   printf("(expecting 3 failures)\n");
445 
446   ThrowSEH();
447 }
448 
449 #if GTEST_HAS_EXCEPTIONS
450 
451 // Tests that the test fixture d'tor is always called, even when the
452 // test function throws a C++ exception.  We do this only when
453 // GTEST_HAS_EXCEPTIONS is non-zero, i.e. C++ exceptions are enabled.
TEST_F(ExceptionInTestFunctionTest,CppException)454 TEST_F(ExceptionInTestFunctionTest, CppException) {
455   throw 1;
456 }
457 
458 // Tests exceptions thrown in TearDown().
459 class ExceptionInTearDownTest : public testing::Test {
460  protected:
~ExceptionInTearDownTest()461   virtual ~ExceptionInTearDownTest() {
462     Deinit();
463   }
464 
TearDown()465   virtual void TearDown() {
466     throw 1;
467   }
468  private:
Deinit()469   void Deinit() {
470     FAIL() << "Expected failure #2, in the test fixture d'tor.";
471   }
472 };
473 
TEST_F(ExceptionInTearDownTest,ExceptionInTearDown)474 TEST_F(ExceptionInTearDownTest, ExceptionInTearDown) {
475   printf("(expecting 2 failures)\n");
476 }
477 
478 #endif  // GTEST_HAS_EXCEPTIONS
479 
480 #endif  // GTEST_OS_WINDOWS
481 
482 // The MixedUpTestCaseTest test case verifies that Google Test will fail a
483 // test if it uses a different fixture class than what other tests in
484 // the same test case use.  It deliberately contains two fixture
485 // classes with the same name but defined in different namespaces.
486 
487 // The MixedUpTestCaseWithSameTestNameTest test case verifies that
488 // when the user defines two tests with the same test case name AND
489 // same test name (but in different namespaces), the second test will
490 // fail.
491 
492 namespace foo {
493 
494 class MixedUpTestCaseTest : public testing::Test {
495 };
496 
TEST_F(MixedUpTestCaseTest,FirstTestFromNamespaceFoo)497 TEST_F(MixedUpTestCaseTest, FirstTestFromNamespaceFoo) {}
TEST_F(MixedUpTestCaseTest,SecondTestFromNamespaceFoo)498 TEST_F(MixedUpTestCaseTest, SecondTestFromNamespaceFoo) {}
499 
500 class MixedUpTestCaseWithSameTestNameTest : public testing::Test {
501 };
502 
TEST_F(MixedUpTestCaseWithSameTestNameTest,TheSecondTestWithThisNameShouldFail)503 TEST_F(MixedUpTestCaseWithSameTestNameTest,
504        TheSecondTestWithThisNameShouldFail) {}
505 
506 }  // namespace foo
507 
508 namespace bar {
509 
510 class MixedUpTestCaseTest : public testing::Test {
511 };
512 
513 // The following two tests are expected to fail.  We rely on the
514 // golden file to check that Google Test generates the right error message.
TEST_F(MixedUpTestCaseTest,ThisShouldFail)515 TEST_F(MixedUpTestCaseTest, ThisShouldFail) {}
TEST_F(MixedUpTestCaseTest,ThisShouldFailToo)516 TEST_F(MixedUpTestCaseTest, ThisShouldFailToo) {}
517 
518 class MixedUpTestCaseWithSameTestNameTest : public testing::Test {
519 };
520 
521 // Expected to fail.  We rely on the golden file to check that Google Test
522 // generates the right error message.
TEST_F(MixedUpTestCaseWithSameTestNameTest,TheSecondTestWithThisNameShouldFail)523 TEST_F(MixedUpTestCaseWithSameTestNameTest,
524        TheSecondTestWithThisNameShouldFail) {}
525 
526 }  // namespace bar
527 
528 // The following two test cases verify that Google Test catches the user
529 // error of mixing TEST and TEST_F in the same test case.  The first
530 // test case checks the scenario where TEST_F appears before TEST, and
531 // the second one checks where TEST appears before TEST_F.
532 
533 class TEST_F_before_TEST_in_same_test_case : public testing::Test {
534 };
535 
TEST_F(TEST_F_before_TEST_in_same_test_case,DefinedUsingTEST_F)536 TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {}
537 
538 // Expected to fail.  We rely on the golden file to check that Google Test
539 // generates the right error message.
TEST(TEST_F_before_TEST_in_same_test_case,DefinedUsingTESTAndShouldFail)540 TEST(TEST_F_before_TEST_in_same_test_case, DefinedUsingTESTAndShouldFail) {}
541 
542 class TEST_before_TEST_F_in_same_test_case : public testing::Test {
543 };
544 
TEST(TEST_before_TEST_F_in_same_test_case,DefinedUsingTEST)545 TEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {}
546 
547 // Expected to fail.  We rely on the golden file to check that Google Test
548 // generates the right error message.
TEST_F(TEST_before_TEST_F_in_same_test_case,DefinedUsingTEST_FAndShouldFail)549 TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) {
550 }
551 
552 // Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE().
553 int global_integer = 0;
554 
555 // Tests that EXPECT_NONFATAL_FAILURE() can reference global variables.
TEST(ExpectNonfatalFailureTest,CanReferenceGlobalVariables)556 TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) {
557   global_integer = 0;
558   EXPECT_NONFATAL_FAILURE({
559     EXPECT_EQ(1, global_integer) << "Expected non-fatal failure.";
560   }, "Expected non-fatal failure.");
561 }
562 
563 // Tests that EXPECT_NONFATAL_FAILURE() can reference local variables
564 // (static or not).
TEST(ExpectNonfatalFailureTest,CanReferenceLocalVariables)565 TEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) {
566   int m = 0;
567   static int n;
568   n = 1;
569   EXPECT_NONFATAL_FAILURE({
570     EXPECT_EQ(m, n) << "Expected non-fatal failure.";
571   }, "Expected non-fatal failure.");
572 }
573 
574 // Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly
575 // one non-fatal failure and no fatal failure.
TEST(ExpectNonfatalFailureTest,SucceedsWhenThereIsOneNonfatalFailure)576 TEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) {
577   EXPECT_NONFATAL_FAILURE({
578     ADD_FAILURE() << "Expected non-fatal failure.";
579   }, "Expected non-fatal failure.");
580 }
581 
582 // Tests that EXPECT_NONFATAL_FAILURE() fails when there is no
583 // non-fatal failure.
TEST(ExpectNonfatalFailureTest,FailsWhenThereIsNoNonfatalFailure)584 TEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) {
585   printf("(expecting a failure)\n");
586   EXPECT_NONFATAL_FAILURE({
587   }, "");
588 }
589 
590 // Tests that EXPECT_NONFATAL_FAILURE() fails when there are two
591 // non-fatal failures.
TEST(ExpectNonfatalFailureTest,FailsWhenThereAreTwoNonfatalFailures)592 TEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) {
593   printf("(expecting a failure)\n");
594   EXPECT_NONFATAL_FAILURE({
595     ADD_FAILURE() << "Expected non-fatal failure 1.";
596     ADD_FAILURE() << "Expected non-fatal failure 2.";
597   }, "");
598 }
599 
600 // Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal
601 // failure.
TEST(ExpectNonfatalFailureTest,FailsWhenThereIsOneFatalFailure)602 TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) {
603   printf("(expecting a failure)\n");
604   EXPECT_NONFATAL_FAILURE({
605     FAIL() << "Expected fatal failure.";
606   }, "");
607 }
608 
609 // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
610 // tested returns.
TEST(ExpectNonfatalFailureTest,FailsWhenStatementReturns)611 TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) {
612   printf("(expecting a failure)\n");
613   EXPECT_NONFATAL_FAILURE({
614     return;
615   }, "");
616 }
617 
618 #if GTEST_HAS_EXCEPTIONS
619 
620 // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
621 // tested throws.
TEST(ExpectNonfatalFailureTest,FailsWhenStatementThrows)622 TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) {
623   printf("(expecting a failure)\n");
624   try {
625     EXPECT_NONFATAL_FAILURE({
626       throw 0;
627     }, "");
628   } catch(int) {  // NOLINT
629   }
630 }
631 
632 #endif  // GTEST_HAS_EXCEPTIONS
633 
634 // Tests that EXPECT_FATAL_FAILURE() can reference global variables.
TEST(ExpectFatalFailureTest,CanReferenceGlobalVariables)635 TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) {
636   global_integer = 0;
637   EXPECT_FATAL_FAILURE({
638     ASSERT_EQ(1, global_integer) << "Expected fatal failure.";
639   }, "Expected fatal failure.");
640 }
641 
642 // Tests that EXPECT_FATAL_FAILURE() can reference local static
643 // variables.
TEST(ExpectFatalFailureTest,CanReferenceLocalStaticVariables)644 TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) {
645   static int n;
646   n = 1;
647   EXPECT_FATAL_FAILURE({
648     ASSERT_EQ(0, n) << "Expected fatal failure.";
649   }, "Expected fatal failure.");
650 }
651 
652 // Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly
653 // one fatal failure and no non-fatal failure.
TEST(ExpectFatalFailureTest,SucceedsWhenThereIsOneFatalFailure)654 TEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) {
655   EXPECT_FATAL_FAILURE({
656     FAIL() << "Expected fatal failure.";
657   }, "Expected fatal failure.");
658 }
659 
660 // Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal
661 // failure.
TEST(ExpectFatalFailureTest,FailsWhenThereIsNoFatalFailure)662 TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) {
663   printf("(expecting a failure)\n");
664   EXPECT_FATAL_FAILURE({
665   }, "");
666 }
667 
668 // A helper for generating a fatal failure.
FatalFailure()669 void FatalFailure() {
670   FAIL() << "Expected fatal failure.";
671 }
672 
673 // Tests that EXPECT_FATAL_FAILURE() fails when there are two
674 // fatal failures.
TEST(ExpectFatalFailureTest,FailsWhenThereAreTwoFatalFailures)675 TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) {
676   printf("(expecting a failure)\n");
677   EXPECT_FATAL_FAILURE({
678     FatalFailure();
679     FatalFailure();
680   }, "");
681 }
682 
683 // Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal
684 // failure.
TEST(ExpectFatalFailureTest,FailsWhenThereIsOneNonfatalFailure)685 TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) {
686   printf("(expecting a failure)\n");
687   EXPECT_FATAL_FAILURE({
688     ADD_FAILURE() << "Expected non-fatal failure.";
689   }, "");
690 }
691 
692 // Tests that EXPECT_FATAL_FAILURE() fails when the statement being
693 // tested returns.
TEST(ExpectFatalFailureTest,FailsWhenStatementReturns)694 TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) {
695   printf("(expecting a failure)\n");
696   EXPECT_FATAL_FAILURE({
697     return;
698   }, "");
699 }
700 
701 #if GTEST_HAS_EXCEPTIONS
702 
703 // Tests that EXPECT_FATAL_FAILURE() fails when the statement being
704 // tested throws.
TEST(ExpectFatalFailureTest,FailsWhenStatementThrows)705 TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) {
706   printf("(expecting a failure)\n");
707   try {
708     EXPECT_FATAL_FAILURE({
709       throw 0;
710     }, "");
711   } catch(int) {  // NOLINT
712   }
713 }
714 
715 #endif  // GTEST_HAS_EXCEPTIONS
716 
717 // This #ifdef block tests the output of typed tests.
718 #if GTEST_HAS_TYPED_TEST
719 
720 template <typename T>
721 class TypedTest : public testing::Test {
722 };
723 
724 TYPED_TEST_CASE(TypedTest, testing::Types<int>);
725 
TYPED_TEST(TypedTest,Success)726 TYPED_TEST(TypedTest, Success) {
727   EXPECT_EQ(0, TypeParam());
728 }
729 
TYPED_TEST(TypedTest,Failure)730 TYPED_TEST(TypedTest, Failure) {
731   EXPECT_EQ(1, TypeParam()) << "Expected failure";
732 }
733 
734 #endif  // GTEST_HAS_TYPED_TEST
735 
736 // This #ifdef block tests the output of type-parameterized tests.
737 #if GTEST_HAS_TYPED_TEST_P
738 
739 template <typename T>
740 class TypedTestP : public testing::Test {
741 };
742 
743 TYPED_TEST_CASE_P(TypedTestP);
744 
TYPED_TEST_P(TypedTestP,Success)745 TYPED_TEST_P(TypedTestP, Success) {
746   EXPECT_EQ(0U, TypeParam());
747 }
748 
TYPED_TEST_P(TypedTestP,Failure)749 TYPED_TEST_P(TypedTestP, Failure) {
750   EXPECT_EQ(1U, TypeParam()) << "Expected failure";
751 }
752 
753 REGISTER_TYPED_TEST_CASE_P(TypedTestP, Success, Failure);
754 
755 typedef testing::Types<unsigned char, unsigned int> UnsignedTypes;
756 INSTANTIATE_TYPED_TEST_CASE_P(Unsigned, TypedTestP, UnsignedTypes);
757 
758 #endif  // GTEST_HAS_TYPED_TEST_P
759 
760 #if GTEST_HAS_DEATH_TEST
761 
762 // We rely on the golden file to verify that tests whose test case
763 // name ends with DeathTest are run first.
764 
TEST(ADeathTest,ShouldRunFirst)765 TEST(ADeathTest, ShouldRunFirst) {
766 }
767 
768 #if GTEST_HAS_TYPED_TEST
769 
770 // We rely on the golden file to verify that typed tests whose test
771 // case name ends with DeathTest are run first.
772 
773 template <typename T>
774 class ATypedDeathTest : public testing::Test {
775 };
776 
777 typedef testing::Types<int, double> NumericTypes;
778 TYPED_TEST_CASE(ATypedDeathTest, NumericTypes);
779 
TYPED_TEST(ATypedDeathTest,ShouldRunFirst)780 TYPED_TEST(ATypedDeathTest, ShouldRunFirst) {
781 }
782 
783 #endif  // GTEST_HAS_TYPED_TEST
784 
785 #if GTEST_HAS_TYPED_TEST_P
786 
787 
788 // We rely on the golden file to verify that type-parameterized tests
789 // whose test case name ends with DeathTest are run first.
790 
791 template <typename T>
792 class ATypeParamDeathTest : public testing::Test {
793 };
794 
795 TYPED_TEST_CASE_P(ATypeParamDeathTest);
796 
TYPED_TEST_P(ATypeParamDeathTest,ShouldRunFirst)797 TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) {
798 }
799 
800 REGISTER_TYPED_TEST_CASE_P(ATypeParamDeathTest, ShouldRunFirst);
801 
802 INSTANTIATE_TYPED_TEST_CASE_P(My, ATypeParamDeathTest, NumericTypes);
803 
804 #endif  // GTEST_HAS_TYPED_TEST_P
805 
806 #endif  // GTEST_HAS_DEATH_TEST
807 
808 // Tests various failure conditions of
809 // EXPECT_{,NON}FATAL_FAILURE{,_ON_ALL_THREADS}.
810 class ExpectFailureTest : public testing::Test {
811  public:  // Must be public and not protected due to a bug in g++ 3.4.2.
812   enum FailureMode {
813     FATAL_FAILURE,
814     NONFATAL_FAILURE
815   };
AddFailure(FailureMode failure)816   static void AddFailure(FailureMode failure) {
817     if (failure == FATAL_FAILURE) {
818       FAIL() << "Expected fatal failure.";
819     } else {
820       ADD_FAILURE() << "Expected non-fatal failure.";
821     }
822   }
823 };
824 
TEST_F(ExpectFailureTest,ExpectFatalFailure)825 TEST_F(ExpectFailureTest, ExpectFatalFailure) {
826   // Expected fatal failure, but succeeds.
827   printf("(expecting 1 failure)\n");
828   EXPECT_FATAL_FAILURE(SUCCEED(), "Expected fatal failure.");
829   // Expected fatal failure, but got a non-fatal failure.
830   printf("(expecting 1 failure)\n");
831   EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Expected non-fatal "
832                        "failure.");
833   // Wrong message.
834   printf("(expecting 1 failure)\n");
835   EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE), "Some other fatal failure "
836                        "expected.");
837 }
838 
TEST_F(ExpectFailureTest,ExpectNonFatalFailure)839 TEST_F(ExpectFailureTest, ExpectNonFatalFailure) {
840   // Expected non-fatal failure, but succeeds.
841   printf("(expecting 1 failure)\n");
842   EXPECT_NONFATAL_FAILURE(SUCCEED(), "Expected non-fatal failure.");
843   // Expected non-fatal failure, but got a fatal failure.
844   printf("(expecting 1 failure)\n");
845   EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure.");
846   // Wrong message.
847   printf("(expecting 1 failure)\n");
848   EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Some other non-fatal "
849                           "failure.");
850 }
851 
852 #if GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
853 
854 class ExpectFailureWithThreadsTest : public ExpectFailureTest {
855  protected:
AddFailureInOtherThread(FailureMode failure)856   static void AddFailureInOtherThread(FailureMode failure) {
857     pthread_t tid;
858     pthread_create(&tid,
859                    NULL,
860                    ExpectFailureWithThreadsTest::FailureThread,
861                    &failure);
862     pthread_join(tid, NULL);
863   }
864  private:
FailureThread(void * attr)865   static void* FailureThread(void* attr) {
866     FailureMode* failure = static_cast<FailureMode*>(attr);
867     AddFailure(*failure);
868     return NULL;
869   }
870 };
871 
TEST_F(ExpectFailureWithThreadsTest,ExpectFatalFailure)872 TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailure) {
873   // We only intercept the current thread.
874   printf("(expecting 2 failures)\n");
875   EXPECT_FATAL_FAILURE(AddFailureInOtherThread(FATAL_FAILURE),
876                        "Expected fatal failure.");
877 }
878 
TEST_F(ExpectFailureWithThreadsTest,ExpectNonFatalFailure)879 TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailure) {
880   // We only intercept the current thread.
881   printf("(expecting 2 failures)\n");
882   EXPECT_NONFATAL_FAILURE(AddFailureInOtherThread(NONFATAL_FAILURE),
883                           "Expected non-fatal failure.");
884 }
885 
886 typedef ExpectFailureWithThreadsTest ScopedFakeTestPartResultReporterTest;
887 
888 // Tests that the ScopedFakeTestPartResultReporter only catches failures from
889 // the current thread if it is instantiated with INTERCEPT_ONLY_CURRENT_THREAD.
TEST_F(ScopedFakeTestPartResultReporterTest,InterceptOnlyCurrentThread)890 TEST_F(ScopedFakeTestPartResultReporterTest, InterceptOnlyCurrentThread) {
891   printf("(expecting 2 failures)\n");
892   TestPartResultArray results;
893   {
894     ScopedFakeTestPartResultReporter reporter(
895         ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
896         &results);
897     AddFailureInOtherThread(FATAL_FAILURE);
898     AddFailureInOtherThread(NONFATAL_FAILURE);
899   }
900   // The two failures should not have been intercepted.
901   EXPECT_EQ(0, results.size()) << "This shouldn't fail.";
902 }
903 
904 #endif  // GTEST_IS_THREADSAFE && GTEST_HAS_PTHREAD
905 
TEST_F(ExpectFailureTest,ExpectFatalFailureOnAllThreads)906 TEST_F(ExpectFailureTest, ExpectFatalFailureOnAllThreads) {
907   // Expected fatal failure, but succeeds.
908   printf("(expecting 1 failure)\n");
909   EXPECT_FATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected fatal failure.");
910   // Expected fatal failure, but got a non-fatal failure.
911   printf("(expecting 1 failure)\n");
912   EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE),
913                                       "Expected non-fatal failure.");
914   // Wrong message.
915   printf("(expecting 1 failure)\n");
916   EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE),
917                                       "Some other fatal failure expected.");
918 }
919 
TEST_F(ExpectFailureTest,ExpectNonFatalFailureOnAllThreads)920 TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) {
921   // Expected non-fatal failure, but succeeds.
922   printf("(expecting 1 failure)\n");
923   EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected non-fatal "
924                                          "failure.");
925   // Expected non-fatal failure, but got a fatal failure.
926   printf("(expecting 1 failure)\n");
927   EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE),
928                                          "Expected fatal failure.");
929   // Wrong message.
930   printf("(expecting 1 failure)\n");
931   EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE),
932                                          "Some other non-fatal failure.");
933 }
934 
935 
936 // Two test environments for testing testing::AddGlobalTestEnvironment().
937 
938 class FooEnvironment : public testing::Environment {
939  public:
SetUp()940   virtual void SetUp() {
941     printf("%s", "FooEnvironment::SetUp() called.\n");
942   }
943 
TearDown()944   virtual void TearDown() {
945     printf("%s", "FooEnvironment::TearDown() called.\n");
946     FAIL() << "Expected fatal failure.";
947   }
948 };
949 
950 class BarEnvironment : public testing::Environment {
951  public:
SetUp()952   virtual void SetUp() {
953     printf("%s", "BarEnvironment::SetUp() called.\n");
954   }
955 
TearDown()956   virtual void TearDown() {
957     printf("%s", "BarEnvironment::TearDown() called.\n");
958     ADD_FAILURE() << "Expected non-fatal failure.";
959   }
960 };
961 
962 GTEST_DEFINE_bool_(internal_skip_environment_and_ad_hoc_tests, false,
963                    "This flag causes the program to skip test environment "
964                    "tests and ad hoc tests.");
965 
966 // The main function.
967 //
968 // The idea is to use Google Test to run all the tests we have defined (some
969 // of them are intended to fail), and then compare the test results
970 // with the "golden" file.
main(int argc,char ** argv)971 int main(int argc, char **argv) {
972   testing::GTEST_FLAG(print_time) = false;
973 
974   // We just run the tests, knowing some of them are intended to fail.
975   // We will use a separate Python script to compare the output of
976   // this program with the golden file.
977 
978   // It's hard to test InitGoogleTest() directly, as it has many
979   // global side effects.  The following line serves as a sanity test
980   // for it.
981   testing::InitGoogleTest(&argc, argv);
982   if (argc >= 2 &&
983       String(argv[1]) == "--gtest_internal_skip_environment_and_ad_hoc_tests")
984     GTEST_FLAG(internal_skip_environment_and_ad_hoc_tests) = true;
985 
986 #if GTEST_HAS_DEATH_TEST
987   if (testing::internal::GTEST_FLAG(internal_run_death_test) != "") {
988     // Skip the usual output capturing if we're running as the child
989     // process of an threadsafe-style death test.
990 #if GTEST_OS_WINDOWS
991     posix::FReopen("nul:", "w", stdout);
992 #else
993     posix::FReopen("/dev/null", "w", stdout);
994 #endif  // GTEST_OS_WINDOWS
995     return RUN_ALL_TESTS();
996   }
997 #endif  // GTEST_HAS_DEATH_TEST
998 
999   if (GTEST_FLAG(internal_skip_environment_and_ad_hoc_tests))
1000     return RUN_ALL_TESTS();
1001 
1002   // Registers two global test environments.
1003   // The golden file verifies that they are set up in the order they
1004   // are registered, and torn down in the reverse order.
1005   testing::AddGlobalTestEnvironment(new FooEnvironment);
1006   testing::AddGlobalTestEnvironment(new BarEnvironment);
1007 
1008   return RunAllTests();
1009 }
1010