gtest_stress_test.cc 9.4 KB

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