gmock_stress_test.cc 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 Google Mock constructs can be used in a large number of
  32. // threads concurrently.
  33. #include "gmock/gmock.h"
  34. #include "gtest/gtest.h"
  35. namespace testing {
  36. namespace {
  37. // From <gtest/internal/gtest-port.h>.
  38. using ::testing::internal::ThreadWithParam;
  39. // The maximum number of test threads (not including helper threads)
  40. // to create.
  41. const int kMaxTestThreads = 50;
  42. // How many times to repeat a task in a test thread.
  43. const int kRepeat = 50;
  44. class MockFoo {
  45. public:
  46. MOCK_METHOD1(Bar, int(int n)); // NOLINT
  47. MOCK_METHOD2(Baz, char(const char* s1, const internal::string& s2)); // NOLINT
  48. };
  49. // Helper for waiting for the given thread to finish and then deleting it.
  50. template <typename T>
  51. void JoinAndDelete(ThreadWithParam<T>* t) {
  52. t->Join();
  53. delete t;
  54. }
  55. using internal::linked_ptr;
  56. // Helper classes for testing using linked_ptr concurrently.
  57. class Base {
  58. public:
  59. explicit Base(int a_x) : x_(a_x) {}
  60. virtual ~Base() {}
  61. int x() const { return x_; }
  62. private:
  63. int x_;
  64. };
  65. class Derived1 : public Base {
  66. public:
  67. Derived1(int a_x, int a_y) : Base(a_x), y_(a_y) {}
  68. int y() const { return y_; }
  69. private:
  70. int y_;
  71. };
  72. class Derived2 : public Base {
  73. public:
  74. Derived2(int a_x, int a_z) : Base(a_x), z_(a_z) {}
  75. int z() const { return z_; }
  76. private:
  77. int z_;
  78. };
  79. linked_ptr<Derived1> pointer1(new Derived1(1, 2));
  80. linked_ptr<Derived2> pointer2(new Derived2(3, 4));
  81. struct Dummy {};
  82. // Tests that we can copy from a linked_ptr and read it concurrently.
  83. void TestConcurrentCopyAndReadLinkedPtr(Dummy /* dummy */) {
  84. // Reads pointer1 and pointer2 while they are being copied from in
  85. // another thread.
  86. EXPECT_EQ(1, pointer1->x());
  87. EXPECT_EQ(2, pointer1->y());
  88. EXPECT_EQ(3, pointer2->x());
  89. EXPECT_EQ(4, pointer2->z());
  90. // Copies from pointer1.
  91. linked_ptr<Derived1> p1(pointer1);
  92. EXPECT_EQ(1, p1->x());
  93. EXPECT_EQ(2, p1->y());
  94. // Assigns from pointer2 where the LHS was empty.
  95. linked_ptr<Base> p2;
  96. p2 = pointer1;
  97. EXPECT_EQ(1, p2->x());
  98. // Assigns from pointer2 where the LHS was not empty.
  99. p2 = pointer2;
  100. EXPECT_EQ(3, p2->x());
  101. }
  102. const linked_ptr<Derived1> p0(new Derived1(1, 2));
  103. // Tests that we can concurrently modify two linked_ptrs that point to
  104. // the same object.
  105. void TestConcurrentWriteToEqualLinkedPtr(Dummy /* dummy */) {
  106. // p1 and p2 point to the same, shared thing. One thread resets p1.
  107. // Another thread assigns to p2. This will cause the same
  108. // underlying "ring" to be updated concurrently.
  109. linked_ptr<Derived1> p1(p0);
  110. linked_ptr<Derived1> p2(p0);
  111. EXPECT_EQ(1, p1->x());
  112. EXPECT_EQ(2, p1->y());
  113. EXPECT_EQ(1, p2->x());
  114. EXPECT_EQ(2, p2->y());
  115. p1.reset();
  116. p2 = p0;
  117. EXPECT_EQ(1, p2->x());
  118. EXPECT_EQ(2, p2->y());
  119. }
  120. // Tests that different mock objects can be used in their respective
  121. // threads. This should generate no Google Test failure.
  122. void TestConcurrentMockObjects(Dummy /* dummy */) {
  123. // Creates a mock and does some typical operations on it.
  124. MockFoo foo;
  125. ON_CALL(foo, Bar(_))
  126. .WillByDefault(Return(1));
  127. ON_CALL(foo, Baz(_, _))
  128. .WillByDefault(Return('b'));
  129. ON_CALL(foo, Baz(_, "you"))
  130. .WillByDefault(Return('a'));
  131. EXPECT_CALL(foo, Bar(0))
  132. .Times(AtMost(3));
  133. EXPECT_CALL(foo, Baz(_, _));
  134. EXPECT_CALL(foo, Baz("hi", "you"))
  135. .WillOnce(Return('z'))
  136. .WillRepeatedly(DoDefault());
  137. EXPECT_EQ(1, foo.Bar(0));
  138. EXPECT_EQ(1, foo.Bar(0));
  139. EXPECT_EQ('z', foo.Baz("hi", "you"));
  140. EXPECT_EQ('a', foo.Baz("hi", "you"));
  141. EXPECT_EQ('b', foo.Baz("hi", "me"));
  142. }
  143. // Tests invoking methods of the same mock object in multiple threads.
  144. struct Helper1Param {
  145. MockFoo* mock_foo;
  146. int* count;
  147. };
  148. void Helper1(Helper1Param param) {
  149. for (int i = 0; i < kRepeat; i++) {
  150. const char ch = param.mock_foo->Baz("a", "b");
  151. if (ch == 'a') {
  152. // It was an expected call.
  153. (*param.count)++;
  154. } else {
  155. // It was an excessive call.
  156. EXPECT_EQ('\0', ch);
  157. }
  158. // An unexpected call.
  159. EXPECT_EQ('\0', param.mock_foo->Baz("x", "y")) << "Expected failure.";
  160. // An uninteresting call.
  161. EXPECT_EQ(1, param.mock_foo->Bar(5));
  162. }
  163. }
  164. // This should generate 3*kRepeat + 1 failures in total.
  165. void TestConcurrentCallsOnSameObject(Dummy /* dummy */) {
  166. MockFoo foo;
  167. ON_CALL(foo, Bar(_))
  168. .WillByDefault(Return(1));
  169. EXPECT_CALL(foo, Baz(_, "b"))
  170. .Times(kRepeat)
  171. .WillRepeatedly(Return('a'));
  172. EXPECT_CALL(foo, Baz(_, "c")); // Expected to be unsatisfied.
  173. // This chunk of code should generate kRepeat failures about
  174. // excessive calls, and 2*kRepeat failures about unexpected calls.
  175. int count1 = 0;
  176. const Helper1Param param = { &foo, &count1 };
  177. ThreadWithParam<Helper1Param>* const t =
  178. new ThreadWithParam<Helper1Param>(Helper1, param, NULL);
  179. int count2 = 0;
  180. const Helper1Param param2 = { &foo, &count2 };
  181. Helper1(param2);
  182. JoinAndDelete(t);
  183. EXPECT_EQ(kRepeat, count1 + count2);
  184. // foo's destructor should generate one failure about unsatisfied
  185. // expectation.
  186. }
  187. // Tests using the same mock object in multiple threads when the
  188. // expectations are partially ordered.
  189. void Helper2(MockFoo* foo) {
  190. for (int i = 0; i < kRepeat; i++) {
  191. foo->Bar(2);
  192. foo->Bar(3);
  193. }
  194. }
  195. // This should generate no Google Test failures.
  196. void TestPartiallyOrderedExpectationsWithThreads(Dummy /* dummy */) {
  197. MockFoo foo;
  198. Sequence s1, s2;
  199. {
  200. InSequence dummy;
  201. EXPECT_CALL(foo, Bar(0));
  202. EXPECT_CALL(foo, Bar(1))
  203. .InSequence(s1, s2);
  204. }
  205. EXPECT_CALL(foo, Bar(2))
  206. .Times(2*kRepeat)
  207. .InSequence(s1)
  208. .RetiresOnSaturation();
  209. EXPECT_CALL(foo, Bar(3))
  210. .Times(2*kRepeat)
  211. .InSequence(s2);
  212. {
  213. InSequence dummy;
  214. EXPECT_CALL(foo, Bar(2))
  215. .InSequence(s1, s2);
  216. EXPECT_CALL(foo, Bar(4));
  217. }
  218. foo.Bar(0);
  219. foo.Bar(1);
  220. ThreadWithParam<MockFoo*>* const t =
  221. new ThreadWithParam<MockFoo*>(Helper2, &foo, NULL);
  222. Helper2(&foo);
  223. JoinAndDelete(t);
  224. foo.Bar(2);
  225. foo.Bar(4);
  226. }
  227. // Tests using Google Mock constructs in many threads concurrently.
  228. TEST(StressTest, CanUseGMockWithThreads) {
  229. void (*test_routines[])(Dummy dummy) = {
  230. &TestConcurrentCopyAndReadLinkedPtr,
  231. &TestConcurrentWriteToEqualLinkedPtr,
  232. &TestConcurrentMockObjects,
  233. &TestConcurrentCallsOnSameObject,
  234. &TestPartiallyOrderedExpectationsWithThreads,
  235. };
  236. const int kRoutines = sizeof(test_routines)/sizeof(test_routines[0]);
  237. const int kCopiesOfEachRoutine = kMaxTestThreads / kRoutines;
  238. const int kTestThreads = kCopiesOfEachRoutine * kRoutines;
  239. ThreadWithParam<Dummy>* threads[kTestThreads] = {};
  240. for (int i = 0; i < kTestThreads; i++) {
  241. // Creates a thread to run the test function.
  242. threads[i] =
  243. new ThreadWithParam<Dummy>(test_routines[i % kRoutines], Dummy(), NULL);
  244. GTEST_LOG_(INFO) << "Thread #" << i << " running . . .";
  245. }
  246. // At this point, we have many threads running.
  247. for (int i = 0; i < kTestThreads; i++) {
  248. JoinAndDelete(threads[i]);
  249. }
  250. // Ensures that the correct number of failures have been reported.
  251. const TestInfo* const info = UnitTest::GetInstance()->current_test_info();
  252. const TestResult& result = *info->result();
  253. const int kExpectedFailures = (3*kRepeat + 1)*kCopiesOfEachRoutine;
  254. GTEST_CHECK_(kExpectedFailures == result.total_part_count())
  255. << "Expected " << kExpectedFailures << " failures, but got "
  256. << result.total_part_count();
  257. }
  258. } // namespace
  259. } // namespace testing
  260. int main(int argc, char **argv) {
  261. testing::InitGoogleMock(&argc, argv);
  262. const int exit_code = RUN_ALL_TESTS(); // Expected to fail.
  263. GTEST_CHECK_(exit_code != 0) << "RUN_ALL_TESTS() did not fail as expected";
  264. printf("\nPASS\n");
  265. return 0;
  266. }