gtest_stress_test.cc 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. // Copyright 2007, 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. // Tests that SCOPED_TRACE() and various Google Test assertions can be
  30. // used in a large number of threads concurrently.
  31. #include "gtest/gtest.h"
  32. #include <vector>
  33. #include "src/gtest-internal-inl.h"
  34. #if GTEST_IS_THREADSAFE
  35. namespace testing {
  36. namespace {
  37. using internal::Notification;
  38. using internal::TestPropertyKeyIs;
  39. using internal::ThreadWithParam;
  40. // In order to run tests in this file, for platforms where Google Test is
  41. // thread safe, implement ThreadWithParam. See the description of its API
  42. // in gtest-port.h, where it is defined for already supported platforms.
  43. // How many threads to create?
  44. const int kThreadCount = 50;
  45. std::string IdToKey(int id, const char* suffix) {
  46. Message key;
  47. key << "key_" << id << "_" << suffix;
  48. return key.GetString();
  49. }
  50. std::string IdToString(int id) {
  51. Message id_message;
  52. id_message << id;
  53. return id_message.GetString();
  54. }
  55. void ExpectKeyAndValueWereRecordedForId(
  56. const std::vector<TestProperty>& properties,
  57. int id, const char* suffix) {
  58. TestPropertyKeyIs matches_key(IdToKey(id, suffix).c_str());
  59. const std::vector<TestProperty>::const_iterator property =
  60. std::find_if(properties.begin(), properties.end(), matches_key);
  61. ASSERT_TRUE(property != properties.end())
  62. << "expecting " << suffix << " value for id " << id;
  63. EXPECT_STREQ(IdToString(id).c_str(), property->value());
  64. }
  65. // Calls a large number of Google Test assertions, where exactly one of them
  66. // will fail.
  67. void ManyAsserts(int id) {
  68. GTEST_LOG_(INFO) << "Thread #" << id << " running...";
  69. SCOPED_TRACE(Message() << "Thread #" << id);
  70. for (int i = 0; i < kThreadCount; i++) {
  71. SCOPED_TRACE(Message() << "Iteration #" << i);
  72. // A bunch of assertions that should succeed.
  73. EXPECT_TRUE(true);
  74. ASSERT_FALSE(false) << "This shouldn't fail.";
  75. EXPECT_STREQ("a", "a");
  76. ASSERT_LE(5, 6);
  77. EXPECT_EQ(i, i) << "This shouldn't fail.";
  78. // RecordProperty() should interact safely with other threads as well.
  79. // The shared_key forces property updates.
  80. Test::RecordProperty(IdToKey(id, "string").c_str(), IdToString(id).c_str());
  81. Test::RecordProperty(IdToKey(id, "int").c_str(), id);
  82. Test::RecordProperty("shared_key", IdToString(id).c_str());
  83. // This assertion should fail kThreadCount times per thread. It
  84. // is for testing whether Google Test can handle failed assertions in a
  85. // multi-threaded context.
  86. EXPECT_LT(i, 0) << "This should always fail.";
  87. }
  88. }
  89. void CheckTestFailureCount(int expected_failures) {
  90. const TestInfo* const info = UnitTest::GetInstance()->current_test_info();
  91. const TestResult* const result = info->result();
  92. GTEST_CHECK_(expected_failures == result->total_part_count())
  93. << "Logged " << result->total_part_count() << " failures "
  94. << " vs. " << expected_failures << " expected";
  95. }
  96. // Tests using SCOPED_TRACE() and Google Test assertions in many threads
  97. // concurrently.
  98. TEST(StressTest, CanUseScopedTraceAndAssertionsInManyThreads) {
  99. {
  100. std::unique_ptr<ThreadWithParam<int> > threads[kThreadCount];
  101. Notification threads_can_start;
  102. for (int i = 0; i != kThreadCount; i++)
  103. threads[i].reset(new ThreadWithParam<int>(&ManyAsserts,
  104. i,
  105. &threads_can_start));
  106. threads_can_start.Notify();
  107. // Blocks until all the threads are done.
  108. for (int i = 0; i != kThreadCount; i++)
  109. threads[i]->Join();
  110. }
  111. // Ensures that kThreadCount*kThreadCount failures have been reported.
  112. const TestInfo* const info = UnitTest::GetInstance()->current_test_info();
  113. const TestResult* const result = info->result();
  114. std::vector<TestProperty> properties;
  115. // We have no access to the TestResult's list of properties but we can
  116. // copy them one by one.
  117. for (int i = 0; i < result->test_property_count(); ++i)
  118. properties.push_back(result->GetTestProperty(i));
  119. EXPECT_EQ(kThreadCount * 2 + 1, result->test_property_count())
  120. << "String and int values recorded on each thread, "
  121. << "as well as one shared_key";
  122. for (int i = 0; i < kThreadCount; ++i) {
  123. ExpectKeyAndValueWereRecordedForId(properties, i, "string");
  124. ExpectKeyAndValueWereRecordedForId(properties, i, "int");
  125. }
  126. CheckTestFailureCount(kThreadCount*kThreadCount);
  127. }
  128. void FailingThread(bool is_fatal) {
  129. if (is_fatal)
  130. FAIL() << "Fatal failure in some other thread. "
  131. << "(This failure is expected.)";
  132. else
  133. ADD_FAILURE() << "Non-fatal failure in some other thread. "
  134. << "(This failure is expected.)";
  135. }
  136. void GenerateFatalFailureInAnotherThread(bool is_fatal) {
  137. ThreadWithParam<bool> thread(&FailingThread, is_fatal, nullptr);
  138. thread.Join();
  139. }
  140. TEST(NoFatalFailureTest, ExpectNoFatalFailureIgnoresFailuresInOtherThreads) {
  141. EXPECT_NO_FATAL_FAILURE(GenerateFatalFailureInAnotherThread(true));
  142. // We should only have one failure (the one from
  143. // GenerateFatalFailureInAnotherThread()), since the EXPECT_NO_FATAL_FAILURE
  144. // should succeed.
  145. CheckTestFailureCount(1);
  146. }
  147. void AssertNoFatalFailureIgnoresFailuresInOtherThreads() {
  148. ASSERT_NO_FATAL_FAILURE(GenerateFatalFailureInAnotherThread(true));
  149. }
  150. TEST(NoFatalFailureTest, AssertNoFatalFailureIgnoresFailuresInOtherThreads) {
  151. // Using a subroutine, to make sure, that the test continues.
  152. AssertNoFatalFailureIgnoresFailuresInOtherThreads();
  153. // We should only have one failure (the one from
  154. // GenerateFatalFailureInAnotherThread()), since the EXPECT_NO_FATAL_FAILURE
  155. // should succeed.
  156. CheckTestFailureCount(1);
  157. }
  158. TEST(FatalFailureTest, ExpectFatalFailureIgnoresFailuresInOtherThreads) {
  159. // This statement should fail, since the current thread doesn't generate a
  160. // fatal failure, only another one does.
  161. EXPECT_FATAL_FAILURE(GenerateFatalFailureInAnotherThread(true), "expected");
  162. CheckTestFailureCount(2);
  163. }
  164. TEST(FatalFailureOnAllThreadsTest, ExpectFatalFailureOnAllThreads) {
  165. // This statement should succeed, because failures in all threads are
  166. // considered.
  167. EXPECT_FATAL_FAILURE_ON_ALL_THREADS(
  168. GenerateFatalFailureInAnotherThread(true), "expected");
  169. CheckTestFailureCount(0);
  170. // We need to add a failure, because main() checks that there are failures.
  171. // But when only this test is run, we shouldn't have any failures.
  172. ADD_FAILURE() << "This is an expected non-fatal failure.";
  173. }
  174. TEST(NonFatalFailureTest, ExpectNonFatalFailureIgnoresFailuresInOtherThreads) {
  175. // This statement should fail, since the current thread doesn't generate a
  176. // fatal failure, only another one does.
  177. EXPECT_NONFATAL_FAILURE(GenerateFatalFailureInAnotherThread(false),
  178. "expected");
  179. CheckTestFailureCount(2);
  180. }
  181. TEST(NonFatalFailureOnAllThreadsTest, ExpectNonFatalFailureOnAllThreads) {
  182. // This statement should succeed, because failures in all threads are
  183. // considered.
  184. EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(
  185. GenerateFatalFailureInAnotherThread(false), "expected");
  186. CheckTestFailureCount(0);
  187. // We need to add a failure, because main() checks that there are failures,
  188. // But when only this test is run, we shouldn't have any failures.
  189. ADD_FAILURE() << "This is an expected non-fatal failure.";
  190. }
  191. } // namespace
  192. } // namespace testing
  193. int main(int argc, char **argv) {
  194. testing::InitGoogleTest(&argc, argv);
  195. const int result = RUN_ALL_TESTS(); // Expected to fail.
  196. GTEST_CHECK_(result == 1) << "RUN_ALL_TESTS() did not fail as expected";
  197. printf("\nPASS\n");
  198. return 0;
  199. }
  200. #else
  201. TEST(StressTest,
  202. DISABLED_ThreadSafetyTestsAreSkippedWhenGoogleTestIsNotThreadSafe) {
  203. }
  204. int main(int argc, char **argv) {
  205. testing::InitGoogleTest(&argc, argv);
  206. return RUN_ALL_TESTS();
  207. }
  208. #endif // GTEST_IS_THREADSAFE