You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1020 lines
31 KiB

  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. #include "gtest/gtest-spi.h"
  35. #include "gtest/gtest.h"
  36. // Indicates that this translation unit is part of Google Test's
  37. // implementation. It must come before gtest-internal-inl.h is
  38. // included, or there will be a compiler error. This trick is to
  39. // prevent a user from accidentally including gtest-internal-inl.h in
  40. // his code.
  41. #define GTEST_IMPLEMENTATION_ 1
  42. #include "src/gtest-internal-inl.h"
  43. #undef GTEST_IMPLEMENTATION_
  44. #include <stdlib.h>
  45. #if GTEST_IS_THREADSAFE
  46. using testing::ScopedFakeTestPartResultReporter;
  47. using testing::TestPartResultArray;
  48. using testing::internal::Notification;
  49. using testing::internal::ThreadWithParam;
  50. #endif
  51. namespace posix = ::testing::internal::posix;
  52. using testing::internal::String;
  53. using testing::internal::scoped_ptr;
  54. // Tests catching fatal failures.
  55. // A subroutine used by the following test.
  56. void TestEq1(int x) {
  57. ASSERT_EQ(1, x);
  58. }
  59. // This function calls a test subroutine, catches the fatal failure it
  60. // generates, and then returns early.
  61. void TryTestSubroutine() {
  62. // Calls a subrountine that yields a fatal failure.
  63. TestEq1(2);
  64. // Catches the fatal failure and aborts the test.
  65. //
  66. // The testing::Test:: prefix is necessary when calling
  67. // HasFatalFailure() outside of a TEST, TEST_F, or test fixture.
  68. if (testing::Test::HasFatalFailure()) return;
  69. // If we get here, something is wrong.
  70. FAIL() << "This should never be reached.";
  71. }
  72. TEST(PassingTest, PassingTest1) {
  73. }
  74. TEST(PassingTest, PassingTest2) {
  75. }
  76. // Tests that parameters of failing parameterized tests are printed in the
  77. // failing test summary.
  78. class FailingParamTest : public testing::TestWithParam<int> {};
  79. TEST_P(FailingParamTest, Fails) {
  80. EXPECT_EQ(1, GetParam());
  81. }
  82. // This generates a test which will fail. Google Test is expected to print
  83. // its parameter when it outputs the list of all failed tests.
  84. INSTANTIATE_TEST_CASE_P(PrintingFailingParams,
  85. FailingParamTest,
  86. testing::Values(2));
  87. // Tests catching a fatal failure in a subroutine.
  88. TEST(FatalFailureTest, FatalFailureInSubroutine) {
  89. printf("(expecting a failure that x should be 1)\n");
  90. TryTestSubroutine();
  91. }
  92. // Tests catching a fatal failure in a nested subroutine.
  93. TEST(FatalFailureTest, FatalFailureInNestedSubroutine) {
  94. printf("(expecting a failure that x should be 1)\n");
  95. // Calls a subrountine that yields a fatal failure.
  96. TryTestSubroutine();
  97. // Catches the fatal failure and aborts the test.
  98. //
  99. // When calling HasFatalFailure() inside a TEST, TEST_F, or test
  100. // fixture, the testing::Test:: prefix is not needed.
  101. if (HasFatalFailure()) return;
  102. // If we get here, something is wrong.
  103. FAIL() << "This should never be reached.";
  104. }
  105. // Tests HasFatalFailure() after a failed EXPECT check.
  106. TEST(FatalFailureTest, NonfatalFailureInSubroutine) {
  107. printf("(expecting a failure on false)\n");
  108. EXPECT_TRUE(false); // Generates a nonfatal failure
  109. ASSERT_FALSE(HasFatalFailure()); // This should succeed.
  110. }
  111. // Tests interleaving user logging and Google Test assertions.
  112. TEST(LoggingTest, InterleavingLoggingAndAssertions) {
  113. static const int a[4] = {
  114. 3, 9, 2, 6
  115. };
  116. printf("(expecting 2 failures on (3) >= (a[i]))\n");
  117. for (int i = 0; i < static_cast<int>(sizeof(a)/sizeof(*a)); i++) {
  118. printf("i == %d\n", i);
  119. EXPECT_GE(3, a[i]);
  120. }
  121. }
  122. // Tests the SCOPED_TRACE macro.
  123. // A helper function for testing SCOPED_TRACE.
  124. void SubWithoutTrace(int n) {
  125. EXPECT_EQ(1, n);
  126. ASSERT_EQ(2, n);
  127. }
  128. // Another helper function for testing SCOPED_TRACE.
  129. void SubWithTrace(int n) {
  130. SCOPED_TRACE(testing::Message() << "n = " << n);
  131. SubWithoutTrace(n);
  132. }
  133. // Tests that SCOPED_TRACE() obeys lexical scopes.
  134. TEST(SCOPED_TRACETest, ObeysScopes) {
  135. printf("(expected to fail)\n");
  136. // There should be no trace before SCOPED_TRACE() is invoked.
  137. ADD_FAILURE() << "This failure is expected, and shouldn't have a trace.";
  138. {
  139. SCOPED_TRACE("Expected trace");
  140. // After SCOPED_TRACE(), a failure in the current scope should contain
  141. // the trace.
  142. ADD_FAILURE() << "This failure is expected, and should have a trace.";
  143. }
  144. // Once the control leaves the scope of the SCOPED_TRACE(), there
  145. // should be no trace again.
  146. ADD_FAILURE() << "This failure is expected, and shouldn't have a trace.";
  147. }
  148. // Tests that SCOPED_TRACE works inside a loop.
  149. TEST(SCOPED_TRACETest, WorksInLoop) {
  150. printf("(expected to fail)\n");
  151. for (int i = 1; i <= 2; i++) {
  152. SCOPED_TRACE(testing::Message() << "i = " << i);
  153. SubWithoutTrace(i);
  154. }
  155. }
  156. // Tests that SCOPED_TRACE works in a subroutine.
  157. TEST(SCOPED_TRACETest, WorksInSubroutine) {
  158. printf("(expected to fail)\n");
  159. SubWithTrace(1);
  160. SubWithTrace(2);
  161. }
  162. // Tests that SCOPED_TRACE can be nested.
  163. TEST(SCOPED_TRACETest, CanBeNested) {
  164. printf("(expected to fail)\n");
  165. SCOPED_TRACE(""); // A trace without a message.
  166. SubWithTrace(2);
  167. }
  168. // Tests that multiple SCOPED_TRACEs can be used in the same scope.
  169. TEST(SCOPED_TRACETest, CanBeRepeated) {
  170. printf("(expected to fail)\n");
  171. SCOPED_TRACE("A");
  172. ADD_FAILURE()
  173. << "This failure is expected, and should contain trace point A.";
  174. SCOPED_TRACE("B");
  175. ADD_FAILURE()
  176. << "This failure is expected, and should contain trace point A and B.";
  177. {
  178. SCOPED_TRACE("C");
  179. ADD_FAILURE() << "This failure is expected, and should contain "
  180. << "trace point A, B, and C.";
  181. }
  182. SCOPED_TRACE("D");
  183. ADD_FAILURE() << "This failure is expected, and should contain "
  184. << "trace point A, B, and D.";
  185. }
  186. #if GTEST_IS_THREADSAFE
  187. // Tests that SCOPED_TRACE()s can be used concurrently from multiple
  188. // threads. Namely, an assertion should be affected by
  189. // SCOPED_TRACE()s in its own thread only.
  190. // Here's the sequence of actions that happen in the test:
  191. //
  192. // Thread A (main) | Thread B (spawned)
  193. // ===============================|================================
  194. // spawns thread B |
  195. // -------------------------------+--------------------------------
  196. // waits for n1 | SCOPED_TRACE("Trace B");
  197. // | generates failure #1
  198. // | notifies n1
  199. // -------------------------------+--------------------------------
  200. // SCOPED_TRACE("Trace A"); | waits for n2
  201. // generates failure #2 |
  202. // notifies n2 |
  203. // -------------------------------|--------------------------------
  204. // waits for n3 | generates failure #3
  205. // | trace B dies
  206. // | generates failure #4
  207. // | notifies n3
  208. // -------------------------------|--------------------------------
  209. // generates failure #5 | finishes
  210. // trace A dies |
  211. // generates failure #6 |
  212. // -------------------------------|--------------------------------
  213. // waits for thread B to finish |
  214. struct CheckPoints {
  215. Notification n1;
  216. Notification n2;
  217. Notification n3;
  218. };
  219. static void ThreadWithScopedTrace(CheckPoints* check_points) {
  220. {
  221. SCOPED_TRACE("Trace B");
  222. ADD_FAILURE()
  223. << "Expected failure #1 (in thread B, only trace B alive).";
  224. check_points->n1.Notify();
  225. check_points->n2.WaitForNotification();
  226. ADD_FAILURE()
  227. << "Expected failure #3 (in thread B, trace A & B both alive).";
  228. } // Trace B dies here.
  229. ADD_FAILURE()
  230. << "Expected failure #4 (in thread B, only trace A alive).";
  231. check_points->n3.Notify();
  232. }
  233. TEST(SCOPED_TRACETest, WorksConcurrently) {
  234. printf("(expecting 6 failures)\n");
  235. CheckPoints check_points;
  236. ThreadWithParam<CheckPoints*> thread(&ThreadWithScopedTrace,
  237. &check_points,
  238. NULL);
  239. check_points.n1.WaitForNotification();
  240. {
  241. SCOPED_TRACE("Trace A");
  242. ADD_FAILURE()
  243. << "Expected failure #2 (in thread A, trace A & B both alive).";
  244. check_points.n2.Notify();
  245. check_points.n3.WaitForNotification();
  246. ADD_FAILURE()
  247. << "Expected failure #5 (in thread A, only trace A alive).";
  248. } // Trace A dies here.
  249. ADD_FAILURE()
  250. << "Expected failure #6 (in thread A, no trace alive).";
  251. thread.Join();
  252. }
  253. #endif // GTEST_IS_THREADSAFE
  254. TEST(DisabledTestsWarningTest,
  255. DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning) {
  256. // This test body is intentionally empty. Its sole purpose is for
  257. // verifying that the --gtest_also_run_disabled_tests flag
  258. // suppresses the "YOU HAVE 12 DISABLED TESTS" warning at the end of
  259. // the test output.
  260. }
  261. // Tests using assertions outside of TEST and TEST_F.
  262. //
  263. // This function creates two failures intentionally.
  264. void AdHocTest() {
  265. printf("The non-test part of the code is expected to have 2 failures.\n\n");
  266. EXPECT_TRUE(false);
  267. EXPECT_EQ(2, 3);
  268. }
  269. // Runs all TESTs, all TEST_Fs, and the ad hoc test.
  270. int RunAllTests() {
  271. AdHocTest();
  272. return RUN_ALL_TESTS();
  273. }
  274. // Tests non-fatal failures in the fixture constructor.
  275. class NonFatalFailureInFixtureConstructorTest : public testing::Test {
  276. protected:
  277. NonFatalFailureInFixtureConstructorTest() {
  278. printf("(expecting 5 failures)\n");
  279. ADD_FAILURE() << "Expected failure #1, in the test fixture c'tor.";
  280. }
  281. ~NonFatalFailureInFixtureConstructorTest() {
  282. ADD_FAILURE() << "Expected failure #5, in the test fixture d'tor.";
  283. }
  284. virtual void SetUp() {
  285. ADD_FAILURE() << "Expected failure #2, in SetUp().";
  286. }
  287. virtual void TearDown() {
  288. ADD_FAILURE() << "Expected failure #4, in TearDown.";
  289. }
  290. };
  291. TEST_F(NonFatalFailureInFixtureConstructorTest, FailureInConstructor) {
  292. ADD_FAILURE() << "Expected failure #3, in the test body.";
  293. }
  294. // Tests fatal failures in the fixture constructor.
  295. class FatalFailureInFixtureConstructorTest : public testing::Test {
  296. protected:
  297. FatalFailureInFixtureConstructorTest() {
  298. printf("(expecting 2 failures)\n");
  299. Init();
  300. }
  301. ~FatalFailureInFixtureConstructorTest() {
  302. ADD_FAILURE() << "Expected failure #2, in the test fixture d'tor.";
  303. }
  304. virtual void SetUp() {
  305. ADD_FAILURE() << "UNEXPECTED failure in SetUp(). "
  306. << "We should never get here, as the test fixture c'tor "
  307. << "had a fatal failure.";
  308. }
  309. virtual void TearDown() {
  310. ADD_FAILURE() << "UNEXPECTED failure in TearDown(). "
  311. << "We should never get here, as the test fixture c'tor "
  312. << "had a fatal failure.";
  313. }
  314. private:
  315. void Init() {
  316. FAIL() << "Expected failure #1, in the test fixture c'tor.";
  317. }
  318. };
  319. TEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) {
  320. ADD_FAILURE() << "UNEXPECTED failure in the test body. "
  321. << "We should never get here, as the test fixture c'tor "
  322. << "had a fatal failure.";
  323. }
  324. // Tests non-fatal failures in SetUp().
  325. class NonFatalFailureInSetUpTest : public testing::Test {
  326. protected:
  327. virtual ~NonFatalFailureInSetUpTest() {
  328. Deinit();
  329. }
  330. virtual void SetUp() {
  331. printf("(expecting 4 failures)\n");
  332. ADD_FAILURE() << "Expected failure #1, in SetUp().";
  333. }
  334. virtual void TearDown() {
  335. FAIL() << "Expected failure #3, in TearDown().";
  336. }
  337. private:
  338. void Deinit() {
  339. FAIL() << "Expected failure #4, in the test fixture d'tor.";
  340. }
  341. };
  342. TEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) {
  343. FAIL() << "Expected failure #2, in the test function.";
  344. }
  345. // Tests fatal failures in SetUp().
  346. class FatalFailureInSetUpTest : public testing::Test {
  347. protected:
  348. virtual ~FatalFailureInSetUpTest() {
  349. Deinit();
  350. }
  351. virtual void SetUp() {
  352. printf("(expecting 3 failures)\n");
  353. FAIL() << "Expected failure #1, in SetUp().";
  354. }
  355. virtual void TearDown() {
  356. FAIL() << "Expected failure #2, in TearDown().";
  357. }
  358. private:
  359. void Deinit() {
  360. FAIL() << "Expected failure #3, in the test fixture d'tor.";
  361. }
  362. };
  363. TEST_F(FatalFailureInSetUpTest, FailureInSetUp) {
  364. FAIL() << "UNEXPECTED failure in the test function. "
  365. << "We should never get here, as SetUp() failed.";
  366. }
  367. TEST(AddFailureAtTest, MessageContainsSpecifiedFileAndLineNumber) {
  368. ADD_FAILURE_AT("foo.cc", 42) << "Expected failure in foo.cc";
  369. }
  370. #if GTEST_IS_THREADSAFE
  371. // A unary function that may die.
  372. void DieIf(bool should_die) {
  373. GTEST_CHECK_(!should_die) << " - death inside DieIf().";
  374. }
  375. // Tests running death tests in a multi-threaded context.
  376. // Used for coordination between the main and the spawn thread.
  377. struct SpawnThreadNotifications {
  378. SpawnThreadNotifications() {}
  379. Notification spawn_thread_started;
  380. Notification spawn_thread_ok_to_terminate;
  381. private:
  382. GTEST_DISALLOW_COPY_AND_ASSIGN_(SpawnThreadNotifications);
  383. };
  384. // The function to be executed in the thread spawn by the
  385. // MultipleThreads test (below).
  386. static void ThreadRoutine(SpawnThreadNotifications* notifications) {
  387. // Signals the main thread that this thread has started.
  388. notifications->spawn_thread_started.Notify();
  389. // Waits for permission to finish from the main thread.
  390. notifications->spawn_thread_ok_to_terminate.WaitForNotification();
  391. }
  392. // This is a death-test test, but it's not named with a DeathTest
  393. // suffix. It starts threads which might interfere with later
  394. // death tests, so it must run after all other death tests.
  395. class DeathTestAndMultiThreadsTest : public testing::Test {
  396. protected:
  397. // Starts a thread and waits for it to begin.
  398. virtual void SetUp() {
  399. thread_.reset(new ThreadWithParam<SpawnThreadNotifications*>(
  400. &ThreadRoutine, &notifications_, NULL));
  401. notifications_.spawn_thread_started.WaitForNotification();
  402. }
  403. // Tells the thread to finish, and reaps it.
  404. // Depending on the version of the thread library in use,
  405. // a manager thread might still be left running that will interfere
  406. // with later death tests. This is unfortunate, but this class
  407. // cleans up after itself as best it can.
  408. virtual void TearDown() {
  409. notifications_.spawn_thread_ok_to_terminate.Notify();
  410. }
  411. private:
  412. SpawnThreadNotifications notifications_;
  413. scoped_ptr<ThreadWithParam<SpawnThreadNotifications*> > thread_;
  414. };
  415. #endif // GTEST_IS_THREADSAFE
  416. // The MixedUpTestCaseTest test case verifies that Google Test will fail a
  417. // test if it uses a different fixture class than what other tests in
  418. // the same test case use. It deliberately contains two fixture
  419. // classes with the same name but defined in different namespaces.
  420. // The MixedUpTestCaseWithSameTestNameTest test case verifies that
  421. // when the user defines two tests with the same test case name AND
  422. // same test name (but in different namespaces), the second test will
  423. // fail.
  424. namespace foo {
  425. class MixedUpTestCaseTest : public testing::Test {
  426. };
  427. TEST_F(MixedUpTestCaseTest, FirstTestFromNamespaceFoo) {}
  428. TEST_F(MixedUpTestCaseTest, SecondTestFromNamespaceFoo) {}
  429. class MixedUpTestCaseWithSameTestNameTest : public testing::Test {
  430. };
  431. TEST_F(MixedUpTestCaseWithSameTestNameTest,
  432. TheSecondTestWithThisNameShouldFail) {}
  433. } // namespace foo
  434. namespace bar {
  435. class MixedUpTestCaseTest : public testing::Test {
  436. };
  437. // The following two tests are expected to fail. We rely on the
  438. // golden file to check that Google Test generates the right error message.
  439. TEST_F(MixedUpTestCaseTest, ThisShouldFail) {}
  440. TEST_F(MixedUpTestCaseTest, ThisShouldFailToo) {}
  441. class MixedUpTestCaseWithSameTestNameTest : public testing::Test {
  442. };
  443. // Expected to fail. We rely on the golden file to check that Google Test
  444. // generates the right error message.
  445. TEST_F(MixedUpTestCaseWithSameTestNameTest,
  446. TheSecondTestWithThisNameShouldFail) {}
  447. } // namespace bar
  448. // The following two test cases verify that Google Test catches the user
  449. // error of mixing TEST and TEST_F in the same test case. The first
  450. // test case checks the scenario where TEST_F appears before TEST, and
  451. // the second one checks where TEST appears before TEST_F.
  452. class TEST_F_before_TEST_in_same_test_case : public testing::Test {
  453. };
  454. TEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {}
  455. // Expected to fail. We rely on the golden file to check that Google Test
  456. // generates the right error message.
  457. TEST(TEST_F_before_TEST_in_same_test_case, DefinedUsingTESTAndShouldFail) {}
  458. class TEST_before_TEST_F_in_same_test_case : public testing::Test {
  459. };
  460. TEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {}
  461. // Expected to fail. We rely on the golden file to check that Google Test
  462. // generates the right error message.
  463. TEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) {
  464. }
  465. // Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE().
  466. int global_integer = 0;
  467. // Tests that EXPECT_NONFATAL_FAILURE() can reference global variables.
  468. TEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) {
  469. global_integer = 0;
  470. EXPECT_NONFATAL_FAILURE({
  471. EXPECT_EQ(1, global_integer) << "Expected non-fatal failure.";
  472. }, "Expected non-fatal failure.");
  473. }
  474. // Tests that EXPECT_NONFATAL_FAILURE() can reference local variables
  475. // (static or not).
  476. TEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) {
  477. int m = 0;
  478. static int n;
  479. n = 1;
  480. EXPECT_NONFATAL_FAILURE({
  481. EXPECT_EQ(m, n) << "Expected non-fatal failure.";
  482. }, "Expected non-fatal failure.");
  483. }
  484. // Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly
  485. // one non-fatal failure and no fatal failure.
  486. TEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) {
  487. EXPECT_NONFATAL_FAILURE({
  488. ADD_FAILURE() << "Expected non-fatal failure.";
  489. }, "Expected non-fatal failure.");
  490. }
  491. // Tests that EXPECT_NONFATAL_FAILURE() fails when there is no
  492. // non-fatal failure.
  493. TEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) {
  494. printf("(expecting a failure)\n");
  495. EXPECT_NONFATAL_FAILURE({
  496. }, "");
  497. }
  498. // Tests that EXPECT_NONFATAL_FAILURE() fails when there are two
  499. // non-fatal failures.
  500. TEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) {
  501. printf("(expecting a failure)\n");
  502. EXPECT_NONFATAL_FAILURE({
  503. ADD_FAILURE() << "Expected non-fatal failure 1.";
  504. ADD_FAILURE() << "Expected non-fatal failure 2.";
  505. }, "");
  506. }
  507. // Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal
  508. // failure.
  509. TEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) {
  510. printf("(expecting a failure)\n");
  511. EXPECT_NONFATAL_FAILURE({
  512. FAIL() << "Expected fatal failure.";
  513. }, "");
  514. }
  515. // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
  516. // tested returns.
  517. TEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) {
  518. printf("(expecting a failure)\n");
  519. EXPECT_NONFATAL_FAILURE({
  520. return;
  521. }, "");
  522. }
  523. #if GTEST_HAS_EXCEPTIONS
  524. // Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being
  525. // tested throws.
  526. TEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) {
  527. printf("(expecting a failure)\n");
  528. try {
  529. EXPECT_NONFATAL_FAILURE({
  530. throw 0;
  531. }, "");
  532. } catch(int) { // NOLINT
  533. }
  534. }
  535. #endif // GTEST_HAS_EXCEPTIONS
  536. // Tests that EXPECT_FATAL_FAILURE() can reference global variables.
  537. TEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) {
  538. global_integer = 0;
  539. EXPECT_FATAL_FAILURE({
  540. ASSERT_EQ(1, global_integer) << "Expected fatal failure.";
  541. }, "Expected fatal failure.");
  542. }
  543. // Tests that EXPECT_FATAL_FAILURE() can reference local static
  544. // variables.
  545. TEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) {
  546. static int n;
  547. n = 1;
  548. EXPECT_FATAL_FAILURE({
  549. ASSERT_EQ(0, n) << "Expected fatal failure.";
  550. }, "Expected fatal failure.");
  551. }
  552. // Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly
  553. // one fatal failure and no non-fatal failure.
  554. TEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) {
  555. EXPECT_FATAL_FAILURE({
  556. FAIL() << "Expected fatal failure.";
  557. }, "Expected fatal failure.");
  558. }
  559. // Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal
  560. // failure.
  561. TEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) {
  562. printf("(expecting a failure)\n");
  563. EXPECT_FATAL_FAILURE({
  564. }, "");
  565. }
  566. // A helper for generating a fatal failure.
  567. void FatalFailure() {
  568. FAIL() << "Expected fatal failure.";
  569. }
  570. // Tests that EXPECT_FATAL_FAILURE() fails when there are two
  571. // fatal failures.
  572. TEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) {
  573. printf("(expecting a failure)\n");
  574. EXPECT_FATAL_FAILURE({
  575. FatalFailure();
  576. FatalFailure();
  577. }, "");
  578. }
  579. // Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal
  580. // failure.
  581. TEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) {
  582. printf("(expecting a failure)\n");
  583. EXPECT_FATAL_FAILURE({
  584. ADD_FAILURE() << "Expected non-fatal failure.";
  585. }, "");
  586. }
  587. // Tests that EXPECT_FATAL_FAILURE() fails when the statement being
  588. // tested returns.
  589. TEST(ExpectFatalFailureTest, FailsWhenStatementReturns) {
  590. printf("(expecting a failure)\n");
  591. EXPECT_FATAL_FAILURE({
  592. return;
  593. }, "");
  594. }
  595. #if GTEST_HAS_EXCEPTIONS
  596. // Tests that EXPECT_FATAL_FAILURE() fails when the statement being
  597. // tested throws.
  598. TEST(ExpectFatalFailureTest, FailsWhenStatementThrows) {
  599. printf("(expecting a failure)\n");
  600. try {
  601. EXPECT_FATAL_FAILURE({
  602. throw 0;
  603. }, "");
  604. } catch(int) { // NOLINT
  605. }
  606. }
  607. #endif // GTEST_HAS_EXCEPTIONS
  608. // This #ifdef block tests the output of typed tests.
  609. #if GTEST_HAS_TYPED_TEST
  610. template <typename T>
  611. class TypedTest : public testing::Test {
  612. };
  613. TYPED_TEST_CASE(TypedTest, testing::Types<int>);
  614. TYPED_TEST(TypedTest, Success) {
  615. EXPECT_EQ(0, TypeParam());
  616. }
  617. TYPED_TEST(TypedTest, Failure) {
  618. EXPECT_EQ(1, TypeParam()) << "Expected failure";
  619. }
  620. #endif // GTEST_HAS_TYPED_TEST
  621. // This #ifdef block tests the output of type-parameterized tests.
  622. #if GTEST_HAS_TYPED_TEST_P
  623. template <typename T>
  624. class TypedTestP : public testing::Test {
  625. };
  626. TYPED_TEST_CASE_P(TypedTestP);
  627. TYPED_TEST_P(TypedTestP, Success) {
  628. EXPECT_EQ(0U, TypeParam());
  629. }
  630. TYPED_TEST_P(TypedTestP, Failure) {
  631. EXPECT_EQ(1U, TypeParam()) << "Expected failure";
  632. }
  633. REGISTER_TYPED_TEST_CASE_P(TypedTestP, Success, Failure);
  634. typedef testing::Types<unsigned char, unsigned int> UnsignedTypes;
  635. INSTANTIATE_TYPED_TEST_CASE_P(Unsigned, TypedTestP, UnsignedTypes);
  636. #endif // GTEST_HAS_TYPED_TEST_P
  637. #if GTEST_HAS_DEATH_TEST
  638. // We rely on the golden file to verify that tests whose test case
  639. // name ends with DeathTest are run first.
  640. TEST(ADeathTest, ShouldRunFirst) {
  641. }
  642. # if GTEST_HAS_TYPED_TEST
  643. // We rely on the golden file to verify that typed tests whose test
  644. // case name ends with DeathTest are run first.
  645. template <typename T>
  646. class ATypedDeathTest : public testing::Test {
  647. };
  648. typedef testing::Types<int, double> NumericTypes;
  649. TYPED_TEST_CASE(ATypedDeathTest, NumericTypes);
  650. TYPED_TEST(ATypedDeathTest, ShouldRunFirst) {
  651. }
  652. # endif // GTEST_HAS_TYPED_TEST
  653. # if GTEST_HAS_TYPED_TEST_P
  654. // We rely on the golden file to verify that type-parameterized tests
  655. // whose test case name ends with DeathTest are run first.
  656. template <typename T>
  657. class ATypeParamDeathTest : public testing::Test {
  658. };
  659. TYPED_TEST_CASE_P(ATypeParamDeathTest);
  660. TYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) {
  661. }
  662. REGISTER_TYPED_TEST_CASE_P(ATypeParamDeathTest, ShouldRunFirst);
  663. INSTANTIATE_TYPED_TEST_CASE_P(My, ATypeParamDeathTest, NumericTypes);
  664. # endif // GTEST_HAS_TYPED_TEST_P
  665. #endif // GTEST_HAS_DEATH_TEST
  666. // Tests various failure conditions of
  667. // EXPECT_{,NON}FATAL_FAILURE{,_ON_ALL_THREADS}.
  668. class ExpectFailureTest : public testing::Test {
  669. public: // Must be public and not protected due to a bug in g++ 3.4.2.
  670. enum FailureMode {
  671. FATAL_FAILURE,
  672. NONFATAL_FAILURE
  673. };
  674. static void AddFailure(FailureMode failure) {
  675. if (failure == FATAL_FAILURE) {
  676. FAIL() << "Expected fatal failure.";
  677. } else {
  678. ADD_FAILURE() << "Expected non-fatal failure.";
  679. }
  680. }
  681. };
  682. TEST_F(ExpectFailureTest, ExpectFatalFailure) {
  683. // Expected fatal failure, but succeeds.
  684. printf("(expecting 1 failure)\n");
  685. EXPECT_FATAL_FAILURE(SUCCEED(), "Expected fatal failure.");
  686. // Expected fatal failure, but got a non-fatal failure.
  687. printf("(expecting 1 failure)\n");
  688. EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Expected non-fatal "
  689. "failure.");
  690. // Wrong message.
  691. printf("(expecting 1 failure)\n");
  692. EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE), "Some other fatal failure "
  693. "expected.");
  694. }
  695. TEST_F(ExpectFailureTest, ExpectNonFatalFailure) {
  696. // Expected non-fatal failure, but succeeds.
  697. printf("(expecting 1 failure)\n");
  698. EXPECT_NONFATAL_FAILURE(SUCCEED(), "Expected non-fatal failure.");
  699. // Expected non-fatal failure, but got a fatal failure.
  700. printf("(expecting 1 failure)\n");
  701. EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE), "Expected fatal failure.");
  702. // Wrong message.
  703. printf("(expecting 1 failure)\n");
  704. EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE), "Some other non-fatal "
  705. "failure.");
  706. }
  707. #if GTEST_IS_THREADSAFE
  708. class ExpectFailureWithThreadsTest : public ExpectFailureTest {
  709. protected:
  710. static void AddFailureInOtherThread(FailureMode failure) {
  711. ThreadWithParam<FailureMode> thread(&AddFailure, failure, NULL);
  712. thread.Join();
  713. }
  714. };
  715. TEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailure) {
  716. // We only intercept the current thread.
  717. printf("(expecting 2 failures)\n");
  718. EXPECT_FATAL_FAILURE(AddFailureInOtherThread(FATAL_FAILURE),
  719. "Expected fatal failure.");
  720. }
  721. TEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailure) {
  722. // We only intercept the current thread.
  723. printf("(expecting 2 failures)\n");
  724. EXPECT_NONFATAL_FAILURE(AddFailureInOtherThread(NONFATAL_FAILURE),
  725. "Expected non-fatal failure.");
  726. }
  727. typedef ExpectFailureWithThreadsTest ScopedFakeTestPartResultReporterTest;
  728. // Tests that the ScopedFakeTestPartResultReporter only catches failures from
  729. // the current thread if it is instantiated with INTERCEPT_ONLY_CURRENT_THREAD.
  730. TEST_F(ScopedFakeTestPartResultReporterTest, InterceptOnlyCurrentThread) {
  731. printf("(expecting 2 failures)\n");
  732. TestPartResultArray results;
  733. {
  734. ScopedFakeTestPartResultReporter reporter(
  735. ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,
  736. &results);
  737. AddFailureInOtherThread(FATAL_FAILURE);
  738. AddFailureInOtherThread(NONFATAL_FAILURE);
  739. }
  740. // The two failures should not have been intercepted.
  741. EXPECT_EQ(0, results.size()) << "This shouldn't fail.";
  742. }
  743. #endif // GTEST_IS_THREADSAFE
  744. TEST_F(ExpectFailureTest, ExpectFatalFailureOnAllThreads) {
  745. // Expected fatal failure, but succeeds.
  746. printf("(expecting 1 failure)\n");
  747. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected fatal failure.");
  748. // Expected fatal failure, but got a non-fatal failure.
  749. printf("(expecting 1 failure)\n");
  750. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE),
  751. "Expected non-fatal failure.");
  752. // Wrong message.
  753. printf("(expecting 1 failure)\n");
  754. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE),
  755. "Some other fatal failure expected.");
  756. }
  757. TEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) {
  758. // Expected non-fatal failure, but succeeds.
  759. printf("(expecting 1 failure)\n");
  760. EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), "Expected non-fatal "
  761. "failure.");
  762. // Expected non-fatal failure, but got a fatal failure.
  763. printf("(expecting 1 failure)\n");
  764. EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE),
  765. "Expected fatal failure.");
  766. // Wrong message.
  767. printf("(expecting 1 failure)\n");
  768. EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE),
  769. "Some other non-fatal failure.");
  770. }
  771. // Two test environments for testing testing::AddGlobalTestEnvironment().
  772. class FooEnvironment : public testing::Environment {
  773. public:
  774. virtual void SetUp() {
  775. printf("%s", "FooEnvironment::SetUp() called.\n");
  776. }
  777. virtual void TearDown() {
  778. printf("%s", "FooEnvironment::TearDown() called.\n");
  779. FAIL() << "Expected fatal failure.";
  780. }
  781. };
  782. class BarEnvironment : public testing::Environment {
  783. public:
  784. virtual void SetUp() {
  785. printf("%s", "BarEnvironment::SetUp() called.\n");
  786. }
  787. virtual void TearDown() {
  788. printf("%s", "BarEnvironment::TearDown() called.\n");
  789. ADD_FAILURE() << "Expected non-fatal failure.";
  790. }
  791. };
  792. bool GTEST_FLAG(internal_skip_environment_and_ad_hoc_tests) = false;
  793. // The main function.
  794. //
  795. // The idea is to use Google Test to run all the tests we have defined (some
  796. // of them are intended to fail), and then compare the test results
  797. // with the "golden" file.
  798. int main(int argc, char **argv) {
  799. testing::GTEST_FLAG(print_time) = false;
  800. // We just run the tests, knowing some of them are intended to fail.
  801. // We will use a separate Python script to compare the output of
  802. // this program with the golden file.
  803. // It's hard to test InitGoogleTest() directly, as it has many
  804. // global side effects. The following line serves as a sanity test
  805. // for it.
  806. testing::InitGoogleTest(&argc, argv);
  807. if (argc >= 2 &&
  808. String(argv[1]) == "--gtest_internal_skip_environment_and_ad_hoc_tests")
  809. GTEST_FLAG(internal_skip_environment_and_ad_hoc_tests) = true;
  810. #if GTEST_HAS_DEATH_TEST
  811. if (testing::internal::GTEST_FLAG(internal_run_death_test) != "") {
  812. // Skip the usual output capturing if we're running as the child
  813. // process of an threadsafe-style death test.
  814. # if GTEST_OS_WINDOWS
  815. posix::FReopen("nul:", "w", stdout);
  816. # else
  817. posix::FReopen("/dev/null", "w", stdout);
  818. # endif // GTEST_OS_WINDOWS
  819. return RUN_ALL_TESTS();
  820. }
  821. #endif // GTEST_HAS_DEATH_TEST
  822. if (GTEST_FLAG(internal_skip_environment_and_ad_hoc_tests))
  823. return RUN_ALL_TESTS();
  824. // Registers two global test environments.
  825. // The golden file verifies that they are set up in the order they
  826. // are registered, and torn down in the reverse order.
  827. testing::AddGlobalTestEnvironment(new FooEnvironment);
  828. testing::AddGlobalTestEnvironment(new BarEnvironment);
  829. return RunAllTests();
  830. }