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.

257 lines
9.4 KiB

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