blob: 2bb729547ecdb5897e6563a755a86e0ce8932144 [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
85 for (ExpectationBaseSet::const_iterator it =
86 immediate_prerequisites_.begin();
87 it != immediate_prerequisites_.end();
88 ++it) {
89 ExpectationBase* const prerequisite = (*it).get();
90 if (!prerequisite->is_retired()) {
91 prerequisite->RetireAllPreRequisites();
92 prerequisite->Retire();
93 }
94 }
95}
96
97// Returns true iff all pre-requisites of this expectation have been
98// satisfied.
99// L >= g_gmock_mutex
100bool ExpectationBase::AllPrerequisitesAreSatisfied() const {
101 g_gmock_mutex.AssertHeld();
102 for (ExpectationBaseSet::const_iterator it = immediate_prerequisites_.begin();
103 it != immediate_prerequisites_.end(); ++it) {
104 if (!(*it)->IsSatisfied() ||
105 !(*it)->AllPrerequisitesAreSatisfied())
106 return false;
107 }
108 return true;
109}
110
111// Adds unsatisfied pre-requisites of this expectation to 'result'.
112// L >= g_gmock_mutex
113void ExpectationBase::FindUnsatisfiedPrerequisites(
114 ExpectationBaseSet* result) const {
115 g_gmock_mutex.AssertHeld();
116 for (ExpectationBaseSet::const_iterator it = immediate_prerequisites_.begin();
117 it != immediate_prerequisites_.end(); ++it) {
118 if ((*it)->IsSatisfied()) {
119 // If *it is satisfied and has a call count of 0, some of its
120 // pre-requisites may not be satisfied yet.
121 if ((*it)->call_count_ == 0) {
122 (*it)->FindUnsatisfiedPrerequisites(result);
123 }
124 } else {
125 // Now that we know *it is unsatisfied, we are not so interested
126 // in whether its pre-requisites are satisfied. Therefore we
127 // don't recursively call FindUnsatisfiedPrerequisites() here.
128 result->insert(*it);
129 }
130 }
131}
132
133// Points to the implicit sequence introduced by a living InSequence
134// object (if any) in the current thread or NULL.
135ThreadLocal<Sequence*> g_gmock_implicit_sequence;
136
137// Reports an uninteresting call (whose description is in msg) in the
138// manner specified by 'reaction'.
139void ReportUninterestingCall(CallReaction reaction, const string& msg) {
140 switch (reaction) {
141 case ALLOW:
142 Log(INFO, msg, 4);
143 break;
144 case WARN:
145 Log(WARNING, msg, 4);
146 break;
147 default: // FAIL
148 Expect(false, NULL, -1, msg);
149 }
150}
151
152} // namespace internal
153
154// Class Mock.
155
156namespace {
157
158typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
shiqiane35fdd92008-12-10 05:08:54 +0000159
zhanyong.wandf35a762009-04-22 22:25:31 +0000160// The current state of a mock object. Such information is needed for
161// detecting leaked mock objects and explicitly verifying a mock's
162// expectations.
163struct MockObjectState {
164 MockObjectState()
165 : first_used_file(NULL), first_used_line(-1), leakable(false) {}
166
167 // Where in the source file an ON_CALL or EXPECT_CALL is first
168 // invoked on this mock object.
169 const char* first_used_file;
170 int first_used_line;
171 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);
206 cout << " ERROR: this mock object should be deleted but never is. "
207 << "Its address is @" << it->first << ".";
208 leaked_count++;
209 }
210 if (leaked_count > 0) {
211 cout << "\nERROR: " << leaked_count
212 << " leaked mock " << (leaked_count == 1 ? "object" : "objects")
213 << " found at program exit.\n";
214 cout.flush();
215 ::std::cerr.flush();
216 // RUN_ALL_TESTS() has already returned when this destructor is
217 // called. Therefore we cannot use the normal Google Test
218 // failure reporting mechanism.
219 _exit(1); // We cannot call exit() as it is not reentrant and
220 // may already have been called.
221 }
222 }
223
224 StateMap& states() { return states_; }
225 private:
226 StateMap states_;
227};
228
229// Protected by g_gmock_mutex.
shiqiane35fdd92008-12-10 05:08:54 +0000230MockObjectRegistry g_mock_object_registry;
231
232// Maps a mock object to the reaction Google Mock should have when an
233// uninteresting method is called. Protected by g_gmock_mutex.
234std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
235
236// Sets the reaction Google Mock should have when an uninteresting
237// method of the given mock object is called.
238// L < g_gmock_mutex
239void SetReactionOnUninterestingCalls(const void* mock_obj,
240 internal::CallReaction reaction) {
241 internal::MutexLock l(&internal::g_gmock_mutex);
242 g_uninteresting_call_reaction[mock_obj] = reaction;
243}
244
245} // namespace
246
247// Tells Google Mock to allow uninteresting calls on the given mock
248// object.
249// L < g_gmock_mutex
250void Mock::AllowUninterestingCalls(const void* mock_obj) {
251 SetReactionOnUninterestingCalls(mock_obj, internal::ALLOW);
252}
253
254// Tells Google Mock to warn the user about uninteresting calls on the
255// given mock object.
256// L < g_gmock_mutex
257void Mock::WarnUninterestingCalls(const void* mock_obj) {
258 SetReactionOnUninterestingCalls(mock_obj, internal::WARN);
259}
260
261// Tells Google Mock to fail uninteresting calls on the given mock
262// object.
263// L < g_gmock_mutex
264void Mock::FailUninterestingCalls(const void* mock_obj) {
265 SetReactionOnUninterestingCalls(mock_obj, internal::FAIL);
266}
267
268// Tells Google Mock the given mock object is being destroyed and its
269// entry in the call-reaction table should be removed.
270// L < g_gmock_mutex
271void Mock::UnregisterCallReaction(const void* mock_obj) {
272 internal::MutexLock l(&internal::g_gmock_mutex);
273 g_uninteresting_call_reaction.erase(mock_obj);
274}
275
276// Returns the reaction Google Mock will have on uninteresting calls
277// made on the given mock object.
278// L < g_gmock_mutex
279internal::CallReaction Mock::GetReactionOnUninterestingCalls(
280 const void* mock_obj) {
281 internal::MutexLock l(&internal::g_gmock_mutex);
282 return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
283 internal::WARN : g_uninteresting_call_reaction[mock_obj];
284}
285
zhanyong.wandf35a762009-04-22 22:25:31 +0000286// Tells Google Mock to ignore mock_obj when checking for leaked mock
287// objects.
288// L < g_gmock_mutex
289void Mock::AllowLeak(const void* mock_obj) {
290 internal::MutexLock l(&internal::g_gmock_mutex);
291 g_mock_object_registry.states()[mock_obj].leakable = true;
292}
293
shiqiane35fdd92008-12-10 05:08:54 +0000294// Verifies and clears all expectations on the given mock object. If
295// the expectations aren't satisfied, generates one or more Google
296// Test non-fatal failures and returns false.
297// L < g_gmock_mutex
298bool Mock::VerifyAndClearExpectations(void* mock_obj) {
299 internal::MutexLock l(&internal::g_gmock_mutex);
300 return VerifyAndClearExpectationsLocked(mock_obj);
301}
302
303// Verifies all expectations on the given mock object and clears its
304// default actions and expectations. Returns true iff the
305// verification was successful.
306// L < g_gmock_mutex
307bool Mock::VerifyAndClear(void* mock_obj) {
308 internal::MutexLock l(&internal::g_gmock_mutex);
309 ClearDefaultActionsLocked(mock_obj);
310 return VerifyAndClearExpectationsLocked(mock_obj);
311}
312
313// Verifies and clears all expectations on the given mock object. If
314// the expectations aren't satisfied, generates one or more Google
315// Test non-fatal failures and returns false.
316// L >= g_gmock_mutex
317bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj) {
318 internal::g_gmock_mutex.AssertHeld();
zhanyong.wandf35a762009-04-22 22:25:31 +0000319 if (g_mock_object_registry.states().count(mock_obj) == 0) {
shiqiane35fdd92008-12-10 05:08:54 +0000320 // No EXPECT_CALL() was set on the given mock object.
321 return true;
322 }
323
324 // Verifies and clears the expectations on each mock method in the
325 // given mock object.
326 bool expectations_met = true;
zhanyong.wandf35a762009-04-22 22:25:31 +0000327 FunctionMockers& mockers =
328 g_mock_object_registry.states()[mock_obj].function_mockers;
shiqiane35fdd92008-12-10 05:08:54 +0000329 for (FunctionMockers::const_iterator it = mockers.begin();
330 it != mockers.end(); ++it) {
331 if (!(*it)->VerifyAndClearExpectationsLocked()) {
332 expectations_met = false;
333 }
334 }
335
336 // We don't clear the content of mockers, as they may still be
337 // needed by ClearDefaultActionsLocked().
338 return expectations_met;
339}
340
341// Registers a mock object and a mock method it owns.
342// L < g_gmock_mutex
343void Mock::Register(const void* mock_obj,
344 internal::UntypedFunctionMockerBase* mocker) {
345 internal::MutexLock l(&internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000346 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
347}
348
349// Tells Google Mock where in the source code mock_obj is used in an
350// ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
351// information helps the user identify which object it is.
352// L < g_gmock_mutex
353void Mock::RegisterUseByOnCallOrExpectCall(
354 const void* mock_obj, const char* file, int line) {
355 internal::MutexLock l(&internal::g_gmock_mutex);
356 MockObjectState& state = g_mock_object_registry.states()[mock_obj];
357 if (state.first_used_file == NULL) {
358 state.first_used_file = file;
359 state.first_used_line = line;
360 }
shiqiane35fdd92008-12-10 05:08:54 +0000361}
362
363// Unregisters a mock method; removes the owning mock object from the
364// registry when the last mock method associated with it has been
365// unregistered. This is called only in the destructor of
366// FunctionMockerBase.
367// L >= g_gmock_mutex
368void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) {
369 internal::g_gmock_mutex.AssertHeld();
zhanyong.wandf35a762009-04-22 22:25:31 +0000370 for (MockObjectRegistry::StateMap::iterator it =
371 g_mock_object_registry.states().begin();
372 it != g_mock_object_registry.states().end(); ++it) {
373 FunctionMockers& mockers = it->second.function_mockers;
shiqiane35fdd92008-12-10 05:08:54 +0000374 if (mockers.erase(mocker) > 0) {
375 // mocker was in mockers and has been just removed.
376 if (mockers.empty()) {
zhanyong.wandf35a762009-04-22 22:25:31 +0000377 g_mock_object_registry.states().erase(it);
shiqiane35fdd92008-12-10 05:08:54 +0000378 }
379 return;
380 }
381 }
382}
383
384// Clears all ON_CALL()s set on the given mock object.
385// L >= g_gmock_mutex
386void Mock::ClearDefaultActionsLocked(void* mock_obj) {
387 internal::g_gmock_mutex.AssertHeld();
388
zhanyong.wandf35a762009-04-22 22:25:31 +0000389 if (g_mock_object_registry.states().count(mock_obj) == 0) {
shiqiane35fdd92008-12-10 05:08:54 +0000390 // No ON_CALL() was set on the given mock object.
391 return;
392 }
393
394 // Clears the default actions for each mock method in the given mock
395 // object.
zhanyong.wandf35a762009-04-22 22:25:31 +0000396 FunctionMockers& mockers =
397 g_mock_object_registry.states()[mock_obj].function_mockers;
shiqiane35fdd92008-12-10 05:08:54 +0000398 for (FunctionMockers::const_iterator it = mockers.begin();
399 it != mockers.end(); ++it) {
400 (*it)->ClearDefaultActionsLocked();
401 }
402
403 // We don't clear the content of mockers, as they may still be
404 // needed by VerifyAndClearExpectationsLocked().
405}
406
407// Adds an expectation to a sequence.
408void Sequence::AddExpectation(
409 const internal::linked_ptr<internal::ExpectationBase>& expectation) const {
410 if (*last_expectation_ != expectation) {
411 if (*last_expectation_ != NULL) {
412 expectation->immediate_prerequisites_.insert(*last_expectation_);
413 }
414 *last_expectation_ = expectation;
415 }
416}
417
418// Creates the implicit sequence if there isn't one.
419InSequence::InSequence() {
420 if (internal::g_gmock_implicit_sequence.get() == NULL) {
421 internal::g_gmock_implicit_sequence.set(new Sequence);
422 sequence_created_ = true;
423 } else {
424 sequence_created_ = false;
425 }
426}
427
428// Deletes the implicit sequence if it was created by the constructor
429// of this object.
430InSequence::~InSequence() {
431 if (sequence_created_) {
432 delete internal::g_gmock_implicit_sequence.get();
433 internal::g_gmock_implicit_sequence.set(NULL);
434 }
435}
436
437} // namespace testing