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