1 // Copyright 2005, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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.
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.
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
38 #include "gtest/gtest-spi.h"
39 #include "gtest/gtest.h"
40 #include "src/gtest-internal-inl.h"
43 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */)
46 #if GTEST_IS_THREADSAFE
47 using testing::ScopedFakeTestPartResultReporter;
48 using testing::TestPartResultArray;
50 using testing::internal::Notification;
51 using testing::internal::ThreadWithParam;
54 namespace posix = ::testing::internal::posix;
56 // Tests catching fatal failures.
58 // A subroutine used by the following test.
59 void TestEq1(int x) { ASSERT_EQ(1, x); }
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.
67 // Catches the fatal failure and aborts the test.
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;
73 // If we get here, something is wrong.
74 FAIL() << "This should never be reached.";
77 TEST(PassingTest, PassingTest1) {}
79 TEST(PassingTest, PassingTest2) {}
81 // Tests that parameters of failing parameterized tests are printed in the
82 // failing test summary.
83 class FailingParamTest : public testing::TestWithParam<int> {};
85 TEST_P(FailingParamTest, Fails) { EXPECT_EQ(1, GetParam()); }
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,
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> {};
96 TEST_P(EmptyBasenameParamInst, Passes) { EXPECT_EQ(1, GetParam()); }
98 INSTANTIATE_TEST_SUITE_P(, EmptyBasenameParamInst, testing::Values(1));
100 static const char kGoldenString[] = "\"Line\0 1\"\nLine 2";
102 TEST(NonfatalFailureTest, EscapesStringOperands) {
103 std::string actual = "actual \"string\"";
104 EXPECT_EQ(kGoldenString, actual);
106 const char* golden = kGoldenString;
107 EXPECT_EQ(golden, actual);
110 TEST(NonfatalFailureTest, DiffForLongStrings) {
111 std::string golden_str(kGoldenString, sizeof(kGoldenString) - 1);
112 EXPECT_EQ(golden_str, "Line 2");
115 // Tests catching a fatal failure in a subroutine.
116 TEST(FatalFailureTest, FatalFailureInSubroutine) {
117 printf("(expecting a failure that x should be 1)\n");
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");
126 // Calls a subrountine that yields a fatal failure.
129 // Catches the fatal failure and aborts the test.
131 // When calling HasFatalFailure() inside a TEST, TEST_F, or test
132 // fixture, the testing::Test:: prefix is not needed.
133 if (HasFatalFailure()) return;
135 // If we get here, something is wrong.
136 FAIL() << "This should never be reached.";
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.
146 // Tests interleaving user logging and Google Test assertions.
147 TEST(LoggingTest, InterleavingLoggingAndAssertions) {
148 static const int a[4] = {3, 9, 2, 6};
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);
157 // Tests the SCOPED_TRACE macro.
159 // A helper function for testing SCOPED_TRACE.
160 void SubWithoutTrace(int n) {
165 // Another helper function for testing SCOPED_TRACE.
166 void SubWithTrace(int n) {
167 SCOPED_TRACE(testing::Message() << "n = " << n);
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);
179 ADD_FAILURE() << "Just checking that all these values work fine.";
182 // Tests that SCOPED_TRACE() obeys lexical scopes.
183 TEST(SCOPED_TRACETest, ObeysScopes) {
184 printf("(expected to fail)\n");
186 // There should be no trace before SCOPED_TRACE() is invoked.
187 ADD_FAILURE() << "This failure is expected, and shouldn't have a trace.";
190 SCOPED_TRACE("Expected trace");
191 // After SCOPED_TRACE(), a failure in the current scope should contain
193 ADD_FAILURE() << "This failure is expected, and should have a trace.";
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.";
201 // Tests that SCOPED_TRACE works inside a loop.
202 TEST(SCOPED_TRACETest, WorksInLoop) {
203 printf("(expected to fail)\n");
205 for (int i = 1; i <= 2; i++) {
206 SCOPED_TRACE(testing::Message() << "i = " << i);
212 // Tests that SCOPED_TRACE works in a subroutine.
213 TEST(SCOPED_TRACETest, WorksInSubroutine) {
214 printf("(expected to fail)\n");
220 // Tests that SCOPED_TRACE can be nested.
221 TEST(SCOPED_TRACETest, CanBeNested) {
222 printf("(expected to fail)\n");
224 SCOPED_TRACE(""); // A trace without a message.
229 // Tests that multiple SCOPED_TRACEs can be used in the same scope.
230 TEST(SCOPED_TRACETest, CanBeRepeated) {
231 printf("(expected to fail)\n");
235 << "This failure is expected, and should contain trace point A.";
239 << "This failure is expected, and should contain trace point A and B.";
243 ADD_FAILURE() << "This failure is expected, and should "
244 << "contain trace point A, B, and C.";
248 ADD_FAILURE() << "This failure is expected, and should "
249 << "contain trace point A, B, and D.";
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.
257 // Here's the sequence of actions that happen in the test:
259 // Thread A (main) | Thread B (spawned)
260 // ===============================|================================
262 // -------------------------------+--------------------------------
263 // waits for n1 | SCOPED_TRACE("Trace B");
264 // | generates failure #1
266 // -------------------------------+--------------------------------
267 // SCOPED_TRACE("Trace A"); | waits for n2
268 // generates failure #2 |
270 // -------------------------------|--------------------------------
271 // waits for n3 | generates failure #3
273 // | generates failure #4
275 // -------------------------------|--------------------------------
276 // generates failure #5 | finishes
278 // generates failure #6 |
279 // -------------------------------|--------------------------------
280 // waits for thread B to finish |
288 static void ThreadWithScopedTrace(CheckPoints* check_points) {
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();
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();
302 TEST(SCOPED_TRACETest, WorksConcurrently) {
303 printf("(expecting 6 failures)\n");
305 CheckPoints check_points;
306 ThreadWithParam<CheckPoints*> thread(&ThreadWithScopedTrace, &check_points,
308 check_points.n1.WaitForNotification();
311 SCOPED_TRACE("Trace A");
313 << "Expected failure #2 (in thread A, trace A & B both alive).";
314 check_points.n2.Notify();
315 check_points.n3.WaitForNotification();
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).";
322 #endif // GTEST_IS_THREADSAFE
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.";
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
339 // Tests using assertions outside of TEST and TEST_F.
341 // This function creates two failures intentionally.
343 printf("The non-test part of the code is expected to have 2 failures.\n\n");
348 // Runs all TESTs, all TEST_Fs, and the ad hoc test.
351 return RUN_ALL_TESTS();
354 // Tests non-fatal failures in the fixture constructor.
355 class NonFatalFailureInFixtureConstructorTest : public testing::Test {
357 NonFatalFailureInFixtureConstructorTest() {
358 printf("(expecting 5 failures)\n");
359 ADD_FAILURE() << "Expected failure #1, in the test fixture c'tor.";
362 ~NonFatalFailureInFixtureConstructorTest() override {
363 ADD_FAILURE() << "Expected failure #5, in the test fixture d'tor.";
366 void SetUp() override { ADD_FAILURE() << "Expected failure #2, in SetUp()."; }
368 void TearDown() override {
369 ADD_FAILURE() << "Expected failure #4, in TearDown.";
373 TEST_F(NonFatalFailureInFixtureConstructorTest, FailureInConstructor) {
374 ADD_FAILURE() << "Expected failure #3, in the test body.";
377 // Tests fatal failures in the fixture constructor.
378 class FatalFailureInFixtureConstructorTest : public testing::Test {
380 FatalFailureInFixtureConstructorTest() {
381 printf("(expecting 2 failures)\n");
385 ~FatalFailureInFixtureConstructorTest() override {
386 ADD_FAILURE() << "Expected failure #2, in the test fixture d'tor.";
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.";
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.";
402 void Init() { FAIL() << "Expected failure #1, in the test fixture c'tor."; }
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.";
411 // Tests non-fatal failures in SetUp().
412 class NonFatalFailureInSetUpTest : public testing::Test {
414 ~NonFatalFailureInSetUpTest() override { Deinit(); }
416 void SetUp() override {
417 printf("(expecting 4 failures)\n");
418 ADD_FAILURE() << "Expected failure #1, in SetUp().";
421 void TearDown() override { FAIL() << "Expected failure #3, in TearDown()."; }
424 void Deinit() { FAIL() << "Expected failure #4, in the test fixture d'tor."; }
427 TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) {
428 FAIL() << "Expected failure #2, in the test function.";
431 // Tests fatal failures in SetUp().
432 class FatalFailureInSetUpTest : public testing::Test {
434 ~FatalFailureInSetUpTest() override { Deinit(); }
436 void SetUp() override {
437 printf("(expecting 3 failures)\n");
438 FAIL() << "Expected failure #1, in SetUp().";
441 void TearDown() override { FAIL() << "Expected failure #2, in TearDown()."; }
444 void Deinit() { FAIL() << "Expected failure #3, in the test fixture d'tor."; }
447 TEST_F(FatalFailureInSetUpTest, FailureInSetUp) {
448 FAIL() << "UNEXPECTED failure in the test function. "
449 << "We should never get here, as SetUp() failed.";
452 TEST(AddFailureAtTest, MessageContainsSpecifiedFileAndLineNumber) {
453 ADD_FAILURE_AT("foo.cc", 42) << "Expected nonfatal failure in foo.cc";
456 TEST(GtestFailAtTest, MessageContainsSpecifiedFileAndLineNumber) {
457 GTEST_FAIL_AT("foo.cc", 42) << "Expected fatal failure in foo.cc";
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.
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
472 class MixedUpTestSuiteTest : public testing::Test {};
474 TEST_F(MixedUpTestSuiteTest, FirstTestFromNamespaceFoo) {}
475 TEST_F(MixedUpTestSuiteTest, SecondTestFromNamespaceFoo) {}
477 class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {};
479 TEST_F(MixedUpTestSuiteWithSameTestNameTest,
480 TheSecondTestWithThisNameShouldFail) {}
486 class MixedUpTestSuiteTest : public testing::Test {};
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) {}
493 class MixedUpTestSuiteWithSameTestNameTest : public testing::Test {};
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) {}
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.
507 class TEST_F_before_TEST_in_same_test_case : public testing::Test {};
509 TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {}
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) {}
515 class TEST_before_TEST_F_in_same_test_case : public testing::Test {};
517 TEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {}
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) {}
523 // Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE().
524 int global_integer = 0;
526 // Tests that EXPECT_NONFATAL_FAILURE() can reference global variables.
527 TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) {
529 EXPECT_NONFATAL_FAILURE(
530 { EXPECT_EQ(1, global_integer) << "Expected non-fatal failure."; },
531 "Expected non-fatal failure.");
534 // Tests that EXPECT_NONFATAL_FAILURE() can reference local variables
536 TEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) {
540 EXPECT_NONFATAL_FAILURE({ EXPECT_EQ(m, n) << "Expected non-fatal failure."; },
541 "Expected non-fatal failure.");
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.");
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({}, "");
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(
564 ADD_FAILURE() << "Expected non-fatal failure 1.";
565 ADD_FAILURE() << "Expected non-fatal failure 2.";
570 // Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal
572 TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) {
573 printf("(expecting a failure)\n");
574 EXPECT_NONFATAL_FAILURE({ FAIL() << "Expected fatal failure."; }, "");
577 // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
579 TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) {
580 printf("(expecting a failure)\n");
581 EXPECT_NONFATAL_FAILURE({ return; }, "");
584 #if GTEST_HAS_EXCEPTIONS
586 // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
588 TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) {
589 printf("(expecting a failure)\n");
591 EXPECT_NONFATAL_FAILURE({ throw 0; }, "");
592 } catch (int) { // NOLINT
596 #endif // GTEST_HAS_EXCEPTIONS
598 // Tests that EXPECT_FATAL_FAILURE() can reference global variables.
599 TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) {
601 EXPECT_FATAL_FAILURE(
602 { ASSERT_EQ(1, global_integer) << "Expected fatal failure."; },
603 "Expected fatal failure.");
606 // Tests that EXPECT_FATAL_FAILURE() can reference local static
608 TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) {
611 EXPECT_FATAL_FAILURE({ ASSERT_EQ(0, n) << "Expected fatal failure."; },
612 "Expected fatal failure.");
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.");
622 // Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal
624 TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) {
625 printf("(expecting a failure)\n");
626 EXPECT_FATAL_FAILURE({}, "");
629 // A helper for generating a fatal failure.
630 void FatalFailure() { FAIL() << "Expected fatal failure."; }
632 // Tests that EXPECT_FATAL_FAILURE() fails when there are two
634 TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) {
635 printf("(expecting a failure)\n");
636 EXPECT_FATAL_FAILURE(
644 // Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal
646 TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) {
647 printf("(expecting a failure)\n");
648 EXPECT_FATAL_FAILURE({ ADD_FAILURE() << "Expected non-fatal failure."; }, "");
651 // Tests that EXPECT_FATAL_FAILURE() fails when the statement being
653 TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) {
654 printf("(expecting a failure)\n");
655 EXPECT_FATAL_FAILURE({ return; }, "");
658 #if GTEST_HAS_EXCEPTIONS
660 // Tests that EXPECT_FATAL_FAILURE() fails when the statement being
662 TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) {
663 printf("(expecting a failure)\n");
665 EXPECT_FATAL_FAILURE({ throw 0; }, "");
666 } catch (int) { // NOLINT
670 #endif // GTEST_HAS_EXCEPTIONS
672 // This #ifdef block tests the output of value-parameterized tests.
674 std::string ParamNameFunc(const testing::TestParamInfo<std::string>& info) {
678 class ParamTest : public testing::TestWithParam<std::string> {};
680 TEST_P(ParamTest, Success) { EXPECT_EQ("a", GetParam()); }
682 TEST_P(ParamTest, Failure) { EXPECT_EQ("b", GetParam()) << "Expected failure"; }
684 INSTANTIATE_TEST_SUITE_P(PrintingStrings, ParamTest,
685 testing::Values(std::string("a")), ParamNameFunc);
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"));
691 // fails under kErrorOnUninstantiatedParameterizedTest=true
692 class DetectNotInstantiatedTest : public testing::TestWithParam<int> {};
693 TEST_P(DetectNotInstantiatedTest, Used) {}
695 // This would make the test failure from the above go away.
696 // INSTANTIATE_TEST_SUITE_P(Fix, DetectNotInstantiatedTest, testing::Values(1));
698 template <typename T>
699 class TypedTest : public testing::Test {};
701 TYPED_TEST_SUITE(TypedTest, testing::Types<int>);
703 TYPED_TEST(TypedTest, Success) { EXPECT_EQ(0, TypeParam()); }
705 TYPED_TEST(TypedTest, Failure) {
706 EXPECT_EQ(1, TypeParam()) << "Expected failure";
709 typedef testing::Types<char, int> TypesForTestWithNames;
711 template <typename T>
712 class TypedTestWithNames : public testing::Test {};
714 class TypedTestNames {
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);
725 TYPED_TEST_SUITE(TypedTestWithNames, TypesForTestWithNames, TypedTestNames);
727 TYPED_TEST(TypedTestWithNames, Success) {}
729 TYPED_TEST(TypedTestWithNames, Failure) { FAIL(); }
731 template <typename T>
732 class TypedTestP : public testing::Test {};
734 TYPED_TEST_SUITE_P(TypedTestP);
736 TYPED_TEST_P(TypedTestP, Success) { EXPECT_EQ(0U, TypeParam()); }
738 TYPED_TEST_P(TypedTestP, Failure) {
739 EXPECT_EQ(1U, TypeParam()) << "Expected failure";
742 REGISTER_TYPED_TEST_SUITE_P(TypedTestP, Success, Failure);
744 typedef testing::Types<unsigned char, unsigned int> UnsignedTypes;
745 INSTANTIATE_TYPED_TEST_SUITE_P(Unsigned, TypedTestP, UnsignedTypes);
747 class TypedTestPNames {
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);
754 if (std::is_same<T, unsigned int>::value) {
755 return std::string("unsignedInt") + ::testing::PrintToString(i);
760 INSTANTIATE_TYPED_TEST_SUITE_P(UnsignedCustomName, TypedTestP, UnsignedTypes,
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;
770 REGISTER_TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest, Used);
772 // kErrorOnUninstantiatedTypeParameterizedTest=true would make the above fail.
773 // Adding the following would make that test failure go away.
775 // typedef ::testing::Types<char, int, unsigned int> MyTypes;
776 // INSTANTIATE_TYPED_TEST_SUITE_P(All, DetectNotInstantiatedTypesTest, MyTypes);
778 #if GTEST_HAS_DEATH_TEST
780 // We rely on the golden file to verify that tests whose test case
781 // name ends with DeathTest are run first.
783 TEST(ADeathTest, ShouldRunFirst) {}
785 // We rely on the golden file to verify that typed tests whose test
786 // case name ends with DeathTest are run first.
788 template <typename T>
789 class ATypedDeathTest : public testing::Test {};
791 typedef testing::Types<int, double> NumericTypes;
792 TYPED_TEST_SUITE(ATypedDeathTest, NumericTypes);
794 TYPED_TEST(ATypedDeathTest, ShouldRunFirst) {}
796 // We rely on the golden file to verify that type-parameterized tests
797 // whose test case name ends with DeathTest are run first.
799 template <typename T>
800 class ATypeParamDeathTest : public testing::Test {};
802 TYPED_TEST_SUITE_P(ATypeParamDeathTest);
804 TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) {}
806 REGISTER_TYPED_TEST_SUITE_P(ATypeParamDeathTest, ShouldRunFirst);
808 INSTANTIATE_TYPED_TEST_SUITE_P(My, ATypeParamDeathTest, NumericTypes);
810 #endif // GTEST_HAS_DEATH_TEST
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.";
821 ADD_FAILURE() << "Expected non-fatal failure.";
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 "
836 printf("(expecting 1 failure)\n");
837 EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE),
838 "Some other fatal failure "
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.");
850 printf("(expecting 1 failure)\n");
851 EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE),
852 "Some other non-fatal "
856 #if GTEST_IS_THREADSAFE
858 class ExpectFailureWithThreadsTest : public ExpectFailureTest {
860 static void AddFailureInOtherThread(FailureMode failure) {
861 ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr);
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.");
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.");
880 typedef ExpectFailureWithThreadsTest ScopedFakeTestPartResultReporterTest;
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;
888 ScopedFakeTestPartResultReporter reporter(
889 ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
891 AddFailureInOtherThread(FATAL_FAILURE);
892 AddFailureInOtherThread(NONFATAL_FAILURE);
894 // The two failures should not have been intercepted.
895 EXPECT_EQ(0, results.size()) << "This shouldn't fail.";
898 #endif // GTEST_IS_THREADSAFE
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.");
909 printf("(expecting 1 failure)\n");
910 EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE),
911 "Some other fatal failure expected.");
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 "
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.");
925 printf("(expecting 1 failure)\n");
926 EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE),
927 "Some other non-fatal failure.");
930 class DynamicFixture : public testing::Test {
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"); }
937 static void SetUpTestSuite() { printf("DynamicFixture::SetUpTestSuite\n"); }
938 static void TearDownTestSuite() {
939 printf("DynamicFixture::TearDownTestSuite\n");
944 class DynamicTest : public DynamicFixture {
946 void TestBody() override { EXPECT_TRUE(Pass); }
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>; }),
958 // Register the same fixture with another name. That's fine.
959 testing::RegisterTest(
960 "DynamicFixtureAnotherName", "DynamicTestPass", nullptr, nullptr,
962 []() -> DynamicFixture* { return new DynamicTest<true>; }),
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>; }),
972 // Register two tests with the same fixture incorrectly by omitting the
974 testing::RegisterTest(
975 "BadDynamicFixture2", "FixtureBase", nullptr, nullptr, __FILE__,
976 __LINE__, []() -> DynamicFixture* { return new DynamicTest<true>; }),
977 testing::RegisterTest("BadDynamicFixture2", "Derived", nullptr, nullptr,
979 []() { return new DynamicTest<true>; }));
981 // Two test environments for testing testing::AddGlobalTestEnvironment().
983 class FooEnvironment : public testing::Environment {
985 void SetUp() override { printf("%s", "FooEnvironment::SetUp() called.\n"); }
987 void TearDown() override {
988 printf("%s", "FooEnvironment::TearDown() called.\n");
989 FAIL() << "Expected fatal failure.";
993 class BarEnvironment : public testing::Environment {
995 void SetUp() override { printf("%s", "BarEnvironment::SetUp() called.\n"); }
997 void TearDown() override {
998 printf("%s", "BarEnvironment::TearDown() called.\n");
999 ADD_FAILURE() << "Expected non-fatal failure.";
1003 class TestSuiteThatFailsToSetUp : public testing::Test {
1005 static void SetUpTestSuite() { EXPECT_TRUE(false); }
1007 TEST_F(TestSuiteThatFailsToSetUp, ShouldNotRun) { std::abort(); }
1009 // The main function.
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);
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.
1021 // It's hard to test InitGoogleTest() directly, as it has many
1022 // global side effects. The following line serves as a test
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;
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);
1036 posix::FReopen("/dev/null", "w", stdout);
1037 #endif // GTEST_OS_WINDOWS
1038 return RUN_ALL_TESTS();
1040 #endif // GTEST_HAS_DEATH_TEST
1042 if (internal_skip_environment_and_ad_hoc_tests) return RUN_ALL_TESTS();
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);
1050 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4127
1052 return RunAllTests();