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