blob: 00d16918a3465300e24cab3054aab4724ba98c01 [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// 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
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements the spec builder syntax (ON_CALL and
35// EXPECT_CALL).
36
37#include <gmock/gmock-spec-builders.h>
38
zhanyong.wandf35a762009-04-22 22:25:31 +000039#include <stdlib.h>
40#include <iostream> // NOLINT
41#include <map>
shiqiane35fdd92008-12-10 05:08:54 +000042#include <set>
zhanyong.wandf35a762009-04-22 22:25:31 +000043#include <gmock/gmock.h>
shiqiane35fdd92008-12-10 05:08:54 +000044#include <gtest/gtest.h>
45
zhanyong.wandf35a762009-04-22 22:25:31 +000046#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
47#include <unistd.h> // NOLINT
48#endif
49
shiqiane35fdd92008-12-10 05:08:54 +000050namespace testing {
51namespace internal {
52
53// Protects the mock object registry (in class Mock), all function
54// mockers, and all expectations.
55Mutex g_gmock_mutex(Mutex::NO_CONSTRUCTOR_NEEDED_FOR_STATIC_MUTEX);
56
57// Constructs an ExpectationBase object.
58ExpectationBase::ExpectationBase(const char* file, int line)
59 : file_(file),
60 line_(line),
61 cardinality_specified_(false),
62 cardinality_(Exactly(1)),
63 call_count_(0),
64 retired_(false) {
65}
66
67// Destructs an ExpectationBase object.
68ExpectationBase::~ExpectationBase() {}
69
70// Explicitly specifies the cardinality of this expectation. Used by
71// the subclasses to implement the .Times() clause.
72void ExpectationBase::SpecifyCardinality(const Cardinality& cardinality) {
73 cardinality_specified_ = true;
74 cardinality_ = cardinality;
75}
76
77// Retires all pre-requisites of this expectation.
78void ExpectationBase::RetireAllPreRequisites() {
79 if (is_retired()) {
80 // We can take this short-cut as we never retire an expectation
81 // until we have retired all its pre-requisites.
82 return;
83 }
84
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000085 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
86 it != immediate_prerequisites_.end(); ++it) {
87 ExpectationBase* const prerequisite = it->expectation_base().get();
shiqiane35fdd92008-12-10 05:08:54 +000088 if (!prerequisite->is_retired()) {
89 prerequisite->RetireAllPreRequisites();
90 prerequisite->Retire();
91 }
92 }
93}
94
95// Returns true iff all pre-requisites of this expectation have been
96// satisfied.
97// L >= g_gmock_mutex
98bool ExpectationBase::AllPrerequisitesAreSatisfied() const {
99 g_gmock_mutex.AssertHeld();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000100 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
shiqiane35fdd92008-12-10 05:08:54 +0000101 it != immediate_prerequisites_.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000102 if (!(it->expectation_base()->IsSatisfied()) ||
103 !(it->expectation_base()->AllPrerequisitesAreSatisfied()))
shiqiane35fdd92008-12-10 05:08:54 +0000104 return false;
105 }
106 return true;
107}
108
109// Adds unsatisfied pre-requisites of this expectation to 'result'.
110// L >= g_gmock_mutex
111void ExpectationBase::FindUnsatisfiedPrerequisites(
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000112 ExpectationSet* result) const {
shiqiane35fdd92008-12-10 05:08:54 +0000113 g_gmock_mutex.AssertHeld();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000114 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
shiqiane35fdd92008-12-10 05:08:54 +0000115 it != immediate_prerequisites_.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000116 if (it->expectation_base()->IsSatisfied()) {
shiqiane35fdd92008-12-10 05:08:54 +0000117 // If *it is satisfied and has a call count of 0, some of its
118 // pre-requisites may not be satisfied yet.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000119 if (it->expectation_base()->call_count_ == 0) {
120 it->expectation_base()->FindUnsatisfiedPrerequisites(result);
shiqiane35fdd92008-12-10 05:08:54 +0000121 }
122 } else {
123 // Now that we know *it is unsatisfied, we are not so interested
124 // in whether its pre-requisites are satisfied. Therefore we
125 // don't recursively call FindUnsatisfiedPrerequisites() here.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000126 *result += *it;
shiqiane35fdd92008-12-10 05:08:54 +0000127 }
128 }
129}
130
131// Points to the implicit sequence introduced by a living InSequence
132// object (if any) in the current thread or NULL.
133ThreadLocal<Sequence*> g_gmock_implicit_sequence;
134
135// Reports an uninteresting call (whose description is in msg) in the
136// manner specified by 'reaction'.
137void ReportUninterestingCall(CallReaction reaction, const string& msg) {
138 switch (reaction) {
139 case ALLOW:
zhanyong.wan9413f2f2009-05-29 19:50:06 +0000140 Log(INFO, msg, 3);
shiqiane35fdd92008-12-10 05:08:54 +0000141 break;
142 case WARN:
zhanyong.wan9413f2f2009-05-29 19:50:06 +0000143 Log(WARNING, msg, 3);
shiqiane35fdd92008-12-10 05:08:54 +0000144 break;
145 default: // FAIL
146 Expect(false, NULL, -1, msg);
147 }
148}
149
150} // namespace internal
151
152// Class Mock.
153
154namespace {
155
156typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
shiqiane35fdd92008-12-10 05:08:54 +0000157
zhanyong.wandf35a762009-04-22 22:25:31 +0000158// The current state of a mock object. Such information is needed for
159// detecting leaked mock objects and explicitly verifying a mock's
160// expectations.
161struct MockObjectState {
162 MockObjectState()
163 : first_used_file(NULL), first_used_line(-1), leakable(false) {}
164
165 // Where in the source file an ON_CALL or EXPECT_CALL is first
166 // invoked on this mock object.
167 const char* first_used_file;
168 int first_used_line;
zhanyong.wane7bb5ed2009-05-05 23:14:47 +0000169 ::std::string first_used_test_case;
170 ::std::string first_used_test;
zhanyong.wandf35a762009-04-22 22:25:31 +0000171 bool leakable; // true iff it's OK to leak the object.
172 FunctionMockers function_mockers; // All registered methods of the object.
173};
174
175// A global registry holding the state of all mock objects that are
176// alive. A mock object is added to this registry the first time
177// Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It
178// is removed from the registry in the mock object's destructor.
179class MockObjectRegistry {
180 public:
181 // Maps a mock object (identified by its address) to its state.
182 typedef std::map<const void*, MockObjectState> StateMap;
183
184 // This destructor will be called when a program exits, after all
185 // tests in it have been run. By then, there should be no mock
186 // object alive. Therefore we report any living object as test
187 // failure, unless the user explicitly asked us to ignore it.
188 ~MockObjectRegistry() {
189 using ::std::cout;
190
191 if (!GMOCK_FLAG(catch_leaked_mocks))
192 return;
193
194 int leaked_count = 0;
195 for (StateMap::const_iterator it = states_.begin(); it != states_.end();
196 ++it) {
197 if (it->second.leakable) // The user said it's fine to leak this object.
198 continue;
199
200 // TODO(wan@google.com): Print the type of the leaked object.
201 // This can help the user identify the leaked object.
202 cout << "\n";
203 const MockObjectState& state = it->second;
204 internal::FormatFileLocation(
205 state.first_used_file, state.first_used_line, &cout);
zhanyong.wane7bb5ed2009-05-05 23:14:47 +0000206 cout << " ERROR: this mock object";
207 if (state.first_used_test != "") {
208 cout << " (used in test " << state.first_used_test_case << "."
209 << state.first_used_test << ")";
210 }
211 cout << " should be deleted but never is. Its address is @"
212 << it->first << ".";
zhanyong.wandf35a762009-04-22 22:25:31 +0000213 leaked_count++;
214 }
215 if (leaked_count > 0) {
216 cout << "\nERROR: " << leaked_count
217 << " leaked mock " << (leaked_count == 1 ? "object" : "objects")
218 << " found at program exit.\n";
219 cout.flush();
220 ::std::cerr.flush();
221 // RUN_ALL_TESTS() has already returned when this destructor is
222 // called. Therefore we cannot use the normal Google Test
223 // failure reporting mechanism.
224 _exit(1); // We cannot call exit() as it is not reentrant and
225 // may already have been called.
226 }
227 }
228
229 StateMap& states() { return states_; }
230 private:
231 StateMap states_;
232};
233
234// Protected by g_gmock_mutex.
shiqiane35fdd92008-12-10 05:08:54 +0000235MockObjectRegistry g_mock_object_registry;
236
237// Maps a mock object to the reaction Google Mock should have when an
238// uninteresting method is called. Protected by g_gmock_mutex.
239std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
240
241// Sets the reaction Google Mock should have when an uninteresting
242// method of the given mock object is called.
243// L < g_gmock_mutex
244void SetReactionOnUninterestingCalls(const void* mock_obj,
245 internal::CallReaction reaction) {
246 internal::MutexLock l(&internal::g_gmock_mutex);
247 g_uninteresting_call_reaction[mock_obj] = reaction;
248}
249
250} // namespace
251
252// Tells Google Mock to allow uninteresting calls on the given mock
253// object.
254// L < g_gmock_mutex
255void Mock::AllowUninterestingCalls(const void* mock_obj) {
256 SetReactionOnUninterestingCalls(mock_obj, internal::ALLOW);
257}
258
259// Tells Google Mock to warn the user about uninteresting calls on the
260// given mock object.
261// L < g_gmock_mutex
262void Mock::WarnUninterestingCalls(const void* mock_obj) {
263 SetReactionOnUninterestingCalls(mock_obj, internal::WARN);
264}
265
266// Tells Google Mock to fail uninteresting calls on the given mock
267// object.
268// L < g_gmock_mutex
269void Mock::FailUninterestingCalls(const void* mock_obj) {
270 SetReactionOnUninterestingCalls(mock_obj, internal::FAIL);
271}
272
273// Tells Google Mock the given mock object is being destroyed and its
274// entry in the call-reaction table should be removed.
275// L < g_gmock_mutex
276void Mock::UnregisterCallReaction(const void* mock_obj) {
277 internal::MutexLock l(&internal::g_gmock_mutex);
278 g_uninteresting_call_reaction.erase(mock_obj);
279}
280
281// Returns the reaction Google Mock will have on uninteresting calls
282// made on the given mock object.
283// L < g_gmock_mutex
284internal::CallReaction Mock::GetReactionOnUninterestingCalls(
285 const void* mock_obj) {
286 internal::MutexLock l(&internal::g_gmock_mutex);
287 return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
288 internal::WARN : g_uninteresting_call_reaction[mock_obj];
289}
290
zhanyong.wandf35a762009-04-22 22:25:31 +0000291// Tells Google Mock to ignore mock_obj when checking for leaked mock
292// objects.
293// L < g_gmock_mutex
294void Mock::AllowLeak(const void* mock_obj) {
295 internal::MutexLock l(&internal::g_gmock_mutex);
296 g_mock_object_registry.states()[mock_obj].leakable = true;
297}
298
shiqiane35fdd92008-12-10 05:08:54 +0000299// Verifies and clears all expectations on the given mock object. If
300// the expectations aren't satisfied, generates one or more Google
301// Test non-fatal failures and returns false.
302// L < g_gmock_mutex
303bool Mock::VerifyAndClearExpectations(void* mock_obj) {
304 internal::MutexLock l(&internal::g_gmock_mutex);
305 return VerifyAndClearExpectationsLocked(mock_obj);
306}
307
308// Verifies all expectations on the given mock object and clears its
309// default actions and expectations. Returns true iff the
310// verification was successful.
311// L < g_gmock_mutex
312bool Mock::VerifyAndClear(void* mock_obj) {
313 internal::MutexLock l(&internal::g_gmock_mutex);
314 ClearDefaultActionsLocked(mock_obj);
315 return VerifyAndClearExpectationsLocked(mock_obj);
316}
317
318// Verifies and clears all expectations on the given mock object. If
319// the expectations aren't satisfied, generates one or more Google
320// Test non-fatal failures and returns false.
321// L >= g_gmock_mutex
322bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj) {
323 internal::g_gmock_mutex.AssertHeld();
zhanyong.wandf35a762009-04-22 22:25:31 +0000324 if (g_mock_object_registry.states().count(mock_obj) == 0) {
shiqiane35fdd92008-12-10 05:08:54 +0000325 // No EXPECT_CALL() was set on the given mock object.
326 return true;
327 }
328
329 // Verifies and clears the expectations on each mock method in the
330 // given mock object.
331 bool expectations_met = true;
zhanyong.wandf35a762009-04-22 22:25:31 +0000332 FunctionMockers& mockers =
333 g_mock_object_registry.states()[mock_obj].function_mockers;
shiqiane35fdd92008-12-10 05:08:54 +0000334 for (FunctionMockers::const_iterator it = mockers.begin();
335 it != mockers.end(); ++it) {
336 if (!(*it)->VerifyAndClearExpectationsLocked()) {
337 expectations_met = false;
338 }
339 }
340
341 // We don't clear the content of mockers, as they may still be
342 // needed by ClearDefaultActionsLocked().
343 return expectations_met;
344}
345
346// Registers a mock object and a mock method it owns.
347// L < g_gmock_mutex
348void Mock::Register(const void* mock_obj,
349 internal::UntypedFunctionMockerBase* mocker) {
350 internal::MutexLock l(&internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000351 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
352}
353
354// Tells Google Mock where in the source code mock_obj is used in an
355// ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
356// information helps the user identify which object it is.
357// L < g_gmock_mutex
358void Mock::RegisterUseByOnCallOrExpectCall(
359 const void* mock_obj, const char* file, int line) {
360 internal::MutexLock l(&internal::g_gmock_mutex);
361 MockObjectState& state = g_mock_object_registry.states()[mock_obj];
362 if (state.first_used_file == NULL) {
363 state.first_used_file = file;
364 state.first_used_line = line;
zhanyong.wane7bb5ed2009-05-05 23:14:47 +0000365 const TestInfo* const test_info =
366 UnitTest::GetInstance()->current_test_info();
367 if (test_info != NULL) {
368 // TODO(wan@google.com): record the test case name when the
369 // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or
370 // TearDownTestCase().
371 state.first_used_test_case = test_info->test_case_name();
372 state.first_used_test = test_info->name();
373 }
zhanyong.wandf35a762009-04-22 22:25:31 +0000374 }
shiqiane35fdd92008-12-10 05:08:54 +0000375}
376
377// Unregisters a mock method; removes the owning mock object from the
378// registry when the last mock method associated with it has been
379// unregistered. This is called only in the destructor of
380// FunctionMockerBase.
381// L >= g_gmock_mutex
382void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) {
383 internal::g_gmock_mutex.AssertHeld();
zhanyong.wandf35a762009-04-22 22:25:31 +0000384 for (MockObjectRegistry::StateMap::iterator it =
385 g_mock_object_registry.states().begin();
386 it != g_mock_object_registry.states().end(); ++it) {
387 FunctionMockers& mockers = it->second.function_mockers;
shiqiane35fdd92008-12-10 05:08:54 +0000388 if (mockers.erase(mocker) > 0) {
389 // mocker was in mockers and has been just removed.
390 if (mockers.empty()) {
zhanyong.wandf35a762009-04-22 22:25:31 +0000391 g_mock_object_registry.states().erase(it);
shiqiane35fdd92008-12-10 05:08:54 +0000392 }
393 return;
394 }
395 }
396}
397
398// Clears all ON_CALL()s set on the given mock object.
399// L >= g_gmock_mutex
400void Mock::ClearDefaultActionsLocked(void* mock_obj) {
401 internal::g_gmock_mutex.AssertHeld();
402
zhanyong.wandf35a762009-04-22 22:25:31 +0000403 if (g_mock_object_registry.states().count(mock_obj) == 0) {
shiqiane35fdd92008-12-10 05:08:54 +0000404 // No ON_CALL() was set on the given mock object.
405 return;
406 }
407
408 // Clears the default actions for each mock method in the given mock
409 // object.
zhanyong.wandf35a762009-04-22 22:25:31 +0000410 FunctionMockers& mockers =
411 g_mock_object_registry.states()[mock_obj].function_mockers;
shiqiane35fdd92008-12-10 05:08:54 +0000412 for (FunctionMockers::const_iterator it = mockers.begin();
413 it != mockers.end(); ++it) {
414 (*it)->ClearDefaultActionsLocked();
415 }
416
417 // We don't clear the content of mockers, as they may still be
418 // needed by VerifyAndClearExpectationsLocked().
419}
420
421// Adds an expectation to a sequence.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000422void Sequence::AddExpectation(const Expectation& expectation) const {
shiqiane35fdd92008-12-10 05:08:54 +0000423 if (*last_expectation_ != expectation) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000424 if (last_expectation_->expectation_base() != NULL) {
425 expectation.expectation_base()->immediate_prerequisites_
426 += *last_expectation_;
shiqiane35fdd92008-12-10 05:08:54 +0000427 }
428 *last_expectation_ = expectation;
429 }
430}
431
432// Creates the implicit sequence if there isn't one.
433InSequence::InSequence() {
434 if (internal::g_gmock_implicit_sequence.get() == NULL) {
435 internal::g_gmock_implicit_sequence.set(new Sequence);
436 sequence_created_ = true;
437 } else {
438 sequence_created_ = false;
439 }
440}
441
442// Deletes the implicit sequence if it was created by the constructor
443// of this object.
444InSequence::~InSequence() {
445 if (sequence_created_) {
446 delete internal::g_gmock_implicit_sequence.get();
447 internal::g_gmock_implicit_sequence.set(NULL);
448 }
449}
450
451} // namespace testing