gmock_stress_test.cc 9.0 KB

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