blob: 9fcb61ea6c78eaa4efe012cb0d901740f26188da [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
zhanyong.wan53e08c42010-09-14 05:38:21 +000037#include "gmock/gmock-spec-builders.h"
shiqiane35fdd92008-12-10 05:08:54 +000038
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>
vladlosev6c54a5e2009-10-21 06:15:34 +000043#include <string>
zhanyong.wan53e08c42010-09-14 05:38:21 +000044#include "gmock/gmock.h"
45#include "gtest/gtest.h"
shiqiane35fdd92008-12-10 05:08:54 +000046
zhanyong.wandf35a762009-04-22 22:25:31 +000047#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
zhanyong.wan658ac0b2011-02-24 07:29:13 +000048# include <unistd.h> // NOLINT
zhanyong.wandf35a762009-04-22 22:25:31 +000049#endif
50
shiqiane35fdd92008-12-10 05:08:54 +000051namespace testing {
52namespace internal {
53
54// Protects the mock object registry (in class Mock), all function
55// mockers, and all expectations.
vladlosev587c1b32011-05-20 00:42:22 +000056GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +000057
zhanyong.waned6c9272011-02-23 19:39:27 +000058// Logs a message including file and line number information.
vladlosev587c1b32011-05-20 00:42:22 +000059GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
60 const char* file, int line,
61 const string& message) {
zhanyong.waned6c9272011-02-23 19:39:27 +000062 ::std::ostringstream s;
63 s << file << ":" << line << ": " << message << ::std::endl;
64 Log(severity, s.str(), 0);
65}
66
shiqiane35fdd92008-12-10 05:08:54 +000067// Constructs an ExpectationBase object.
zhanyong.wan32de5f52009-12-23 00:13:23 +000068ExpectationBase::ExpectationBase(const char* a_file,
69 int a_line,
70 const string& a_source_text)
71 : file_(a_file),
72 line_(a_line),
73 source_text_(a_source_text),
shiqiane35fdd92008-12-10 05:08:54 +000074 cardinality_specified_(false),
75 cardinality_(Exactly(1)),
76 call_count_(0),
zhanyong.waned6c9272011-02-23 19:39:27 +000077 retired_(false),
78 extra_matcher_specified_(false),
79 repeated_action_specified_(false),
80 retires_on_saturation_(false),
81 last_clause_(kNone),
82 action_count_checked_(false) {}
shiqiane35fdd92008-12-10 05:08:54 +000083
84// Destructs an ExpectationBase object.
85ExpectationBase::~ExpectationBase() {}
86
87// Explicitly specifies the cardinality of this expectation. Used by
88// the subclasses to implement the .Times() clause.
zhanyong.wan32de5f52009-12-23 00:13:23 +000089void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {
shiqiane35fdd92008-12-10 05:08:54 +000090 cardinality_specified_ = true;
zhanyong.wan32de5f52009-12-23 00:13:23 +000091 cardinality_ = a_cardinality;
shiqiane35fdd92008-12-10 05:08:54 +000092}
93
94// Retires all pre-requisites of this expectation.
vladlosev4d60a592011-10-24 21:16:22 +000095void ExpectationBase::RetireAllPreRequisites()
96 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +000097 if (is_retired()) {
98 // We can take this short-cut as we never retire an expectation
99 // until we have retired all its pre-requisites.
100 return;
101 }
102
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000103 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
104 it != immediate_prerequisites_.end(); ++it) {
105 ExpectationBase* const prerequisite = it->expectation_base().get();
shiqiane35fdd92008-12-10 05:08:54 +0000106 if (!prerequisite->is_retired()) {
107 prerequisite->RetireAllPreRequisites();
108 prerequisite->Retire();
109 }
110 }
111}
112
113// Returns true iff all pre-requisites of this expectation have been
114// satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000115bool ExpectationBase::AllPrerequisitesAreSatisfied() const
116 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000117 g_gmock_mutex.AssertHeld();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000118 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
shiqiane35fdd92008-12-10 05:08:54 +0000119 it != immediate_prerequisites_.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000120 if (!(it->expectation_base()->IsSatisfied()) ||
121 !(it->expectation_base()->AllPrerequisitesAreSatisfied()))
shiqiane35fdd92008-12-10 05:08:54 +0000122 return false;
123 }
124 return true;
125}
126
127// Adds unsatisfied pre-requisites of this expectation to 'result'.
vladlosev4d60a592011-10-24 21:16:22 +0000128void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const
129 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000130 g_gmock_mutex.AssertHeld();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000131 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
shiqiane35fdd92008-12-10 05:08:54 +0000132 it != immediate_prerequisites_.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000133 if (it->expectation_base()->IsSatisfied()) {
shiqiane35fdd92008-12-10 05:08:54 +0000134 // If *it is satisfied and has a call count of 0, some of its
135 // pre-requisites may not be satisfied yet.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000136 if (it->expectation_base()->call_count_ == 0) {
137 it->expectation_base()->FindUnsatisfiedPrerequisites(result);
shiqiane35fdd92008-12-10 05:08:54 +0000138 }
139 } else {
140 // Now that we know *it is unsatisfied, we are not so interested
141 // in whether its pre-requisites are satisfied. Therefore we
142 // don't recursively call FindUnsatisfiedPrerequisites() here.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000143 *result += *it;
shiqiane35fdd92008-12-10 05:08:54 +0000144 }
145 }
146}
147
zhanyong.waned6c9272011-02-23 19:39:27 +0000148// Describes how many times a function call matching this
149// expectation has occurred.
vladlosev4d60a592011-10-24 21:16:22 +0000150void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
151 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000152 g_gmock_mutex.AssertHeld();
153
154 // Describes how many times the function is expected to be called.
155 *os << " Expected: to be ";
156 cardinality().DescribeTo(os);
157 *os << "\n Actual: ";
158 Cardinality::DescribeActualCallCountTo(call_count(), os);
159
160 // Describes the state of the expectation (e.g. is it satisfied?
161 // is it active?).
162 *os << " - " << (IsOverSaturated() ? "over-saturated" :
163 IsSaturated() ? "saturated" :
164 IsSatisfied() ? "satisfied" : "unsatisfied")
165 << " and "
166 << (is_retired() ? "retired" : "active");
167}
168
169// Checks the action count (i.e. the number of WillOnce() and
170// WillRepeatedly() clauses) against the cardinality if this hasn't
171// been done before. Prints a warning if there are too many or too
172// few actions.
vladlosev4d60a592011-10-24 21:16:22 +0000173void ExpectationBase::CheckActionCountIfNotDone() const
174 GTEST_LOCK_EXCLUDED_(mutex_) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000175 bool should_check = false;
176 {
177 MutexLock l(&mutex_);
178 if (!action_count_checked_) {
179 action_count_checked_ = true;
180 should_check = true;
181 }
182 }
183
184 if (should_check) {
185 if (!cardinality_specified_) {
186 // The cardinality was inferred - no need to check the action
187 // count against it.
188 return;
189 }
190
191 // The cardinality was explicitly specified.
192 const int action_count = static_cast<int>(untyped_actions_.size());
193 const int upper_bound = cardinality().ConservativeUpperBound();
194 const int lower_bound = cardinality().ConservativeLowerBound();
195 bool too_many; // True if there are too many actions, or false
196 // if there are too few.
197 if (action_count > upper_bound ||
198 (action_count == upper_bound && repeated_action_specified_)) {
199 too_many = true;
200 } else if (0 < action_count && action_count < lower_bound &&
201 !repeated_action_specified_) {
202 too_many = false;
203 } else {
204 return;
205 }
206
207 ::std::stringstream ss;
208 DescribeLocationTo(&ss);
209 ss << "Too " << (too_many ? "many" : "few")
210 << " actions specified in " << source_text() << "...\n"
211 << "Expected to be ";
212 cardinality().DescribeTo(&ss);
213 ss << ", but has " << (too_many ? "" : "only ")
214 << action_count << " WillOnce()"
215 << (action_count == 1 ? "" : "s");
216 if (repeated_action_specified_) {
217 ss << " and a WillRepeatedly()";
218 }
219 ss << ".";
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000220 Log(kWarning, ss.str(), -1); // -1 means "don't print stack trace".
zhanyong.waned6c9272011-02-23 19:39:27 +0000221 }
222}
223
224// Implements the .Times() clause.
225void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
226 if (last_clause_ == kTimes) {
227 ExpectSpecProperty(false,
228 ".Times() cannot appear "
229 "more than once in an EXPECT_CALL().");
230 } else {
231 ExpectSpecProperty(last_clause_ < kTimes,
232 ".Times() cannot appear after "
233 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
234 "or .RetiresOnSaturation().");
235 }
236 last_clause_ = kTimes;
237
238 SpecifyCardinality(a_cardinality);
239}
240
shiqiane35fdd92008-12-10 05:08:54 +0000241// Points to the implicit sequence introduced by a living InSequence
242// object (if any) in the current thread or NULL.
vladlosev587c1b32011-05-20 00:42:22 +0000243GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
shiqiane35fdd92008-12-10 05:08:54 +0000244
245// Reports an uninteresting call (whose description is in msg) in the
246// manner specified by 'reaction'.
247void ReportUninterestingCall(CallReaction reaction, const string& msg) {
248 switch (reaction) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000249 case kAllow:
250 Log(kInfo, msg, 3);
shiqiane35fdd92008-12-10 05:08:54 +0000251 break;
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000252 case kWarn:
253 Log(kWarning, msg, 3);
shiqiane35fdd92008-12-10 05:08:54 +0000254 break;
255 default: // FAIL
256 Expect(false, NULL, -1, msg);
257 }
258}
259
zhanyong.waned6c9272011-02-23 19:39:27 +0000260UntypedFunctionMockerBase::UntypedFunctionMockerBase()
261 : mock_obj_(NULL), name_("") {}
262
263UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
264
265// Sets the mock object this mock method belongs to, and registers
266// this information in the global mock registry. Will be called
267// whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
268// method.
vladlosev4d60a592011-10-24 21:16:22 +0000269void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
270 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000271 {
272 MutexLock l(&g_gmock_mutex);
273 mock_obj_ = mock_obj;
274 }
275 Mock::Register(mock_obj, this);
276}
277
278// Sets the mock object this mock method belongs to, and sets the name
279// of the mock function. Will be called upon each invocation of this
280// mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000281void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
282 const char* name)
283 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000284 // We protect name_ under g_gmock_mutex in case this mock function
285 // is called from two threads concurrently.
286 MutexLock l(&g_gmock_mutex);
287 mock_obj_ = mock_obj;
288 name_ = name;
289}
290
291// Returns the name of the function being mocked. Must be called
292// after RegisterOwner() or SetOwnerAndName() has been called.
vladlosev4d60a592011-10-24 21:16:22 +0000293const void* UntypedFunctionMockerBase::MockObject() const
294 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000295 const void* mock_obj;
296 {
297 // We protect mock_obj_ under g_gmock_mutex in case this mock
298 // function is called from two threads concurrently.
299 MutexLock l(&g_gmock_mutex);
300 Assert(mock_obj_ != NULL, __FILE__, __LINE__,
301 "MockObject() must not be called before RegisterOwner() or "
302 "SetOwnerAndName() has been called.");
303 mock_obj = mock_obj_;
304 }
305 return mock_obj;
306}
307
308// Returns the name of this mock method. Must be called after
309// SetOwnerAndName() has been called.
vladlosev4d60a592011-10-24 21:16:22 +0000310const char* UntypedFunctionMockerBase::Name() const
311 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000312 const char* name;
313 {
314 // We protect name_ under g_gmock_mutex in case this mock
315 // function is called from two threads concurrently.
316 MutexLock l(&g_gmock_mutex);
317 Assert(name_ != NULL, __FILE__, __LINE__,
318 "Name() must not be called before SetOwnerAndName() has "
319 "been called.");
320 name = name_;
321 }
322 return name;
323}
324
325// Calculates the result of invoking this mock function with the given
326// arguments, prints it, and returns it. The caller is responsible
327// for deleting the result.
zhanyong.waned6c9272011-02-23 19:39:27 +0000328const UntypedActionResultHolderBase*
vladlosev4d60a592011-10-24 21:16:22 +0000329UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args)
330 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000331 if (untyped_expectations_.size() == 0) {
332 // No expectation is set on this mock method - we have an
333 // uninteresting call.
334
335 // We must get Google Mock's reaction on uninteresting calls
336 // made on this mock object BEFORE performing the action,
337 // because the action may DELETE the mock object and make the
338 // following expression meaningless.
339 const CallReaction reaction =
340 Mock::GetReactionOnUninterestingCalls(MockObject());
341
342 // True iff we need to print this call's arguments and return
343 // value. This definition must be kept in sync with
344 // the behavior of ReportUninterestingCall().
345 const bool need_to_report_uninteresting_call =
346 // If the user allows this uninteresting call, we print it
347 // only when he wants informational messages.
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000348 reaction == kAllow ? LogIsVisible(kInfo) :
zhanyong.waned6c9272011-02-23 19:39:27 +0000349 // If the user wants this to be a warning, we print it only
350 // when he wants to see warnings.
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000351 reaction == kWarn ? LogIsVisible(kWarning) :
zhanyong.waned6c9272011-02-23 19:39:27 +0000352 // Otherwise, the user wants this to be an error, and we
353 // should always print detailed information in the error.
354 true;
355
356 if (!need_to_report_uninteresting_call) {
357 // Perform the action without printing the call information.
358 return this->UntypedPerformDefaultAction(untyped_args, "");
359 }
360
361 // Warns about the uninteresting call.
362 ::std::stringstream ss;
363 this->UntypedDescribeUninterestingCall(untyped_args, &ss);
364
365 // Calculates the function result.
366 const UntypedActionResultHolderBase* const result =
367 this->UntypedPerformDefaultAction(untyped_args, ss.str());
368
369 // Prints the function result.
370 if (result != NULL)
371 result->PrintAsActionResult(&ss);
372
373 ReportUninterestingCall(reaction, ss.str());
374 return result;
375 }
376
377 bool is_excessive = false;
378 ::std::stringstream ss;
379 ::std::stringstream why;
380 ::std::stringstream loc;
381 const void* untyped_action = NULL;
382
383 // The UntypedFindMatchingExpectation() function acquires and
384 // releases g_gmock_mutex.
385 const ExpectationBase* const untyped_expectation =
386 this->UntypedFindMatchingExpectation(
387 untyped_args, &untyped_action, &is_excessive,
388 &ss, &why);
389 const bool found = untyped_expectation != NULL;
390
391 // True iff we need to print the call's arguments and return value.
392 // This definition must be kept in sync with the uses of Expect()
393 // and Log() in this function.
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000394 const bool need_to_report_call =
395 !found || is_excessive || LogIsVisible(kInfo);
zhanyong.waned6c9272011-02-23 19:39:27 +0000396 if (!need_to_report_call) {
397 // Perform the action without printing the call information.
398 return
399 untyped_action == NULL ?
400 this->UntypedPerformDefaultAction(untyped_args, "") :
401 this->UntypedPerformAction(untyped_action, untyped_args);
402 }
403
404 ss << " Function call: " << Name();
405 this->UntypedPrintArgs(untyped_args, &ss);
406
407 // In case the action deletes a piece of the expectation, we
408 // generate the message beforehand.
409 if (found && !is_excessive) {
410 untyped_expectation->DescribeLocationTo(&loc);
411 }
412
413 const UntypedActionResultHolderBase* const result =
414 untyped_action == NULL ?
415 this->UntypedPerformDefaultAction(untyped_args, ss.str()) :
416 this->UntypedPerformAction(untyped_action, untyped_args);
417 if (result != NULL)
418 result->PrintAsActionResult(&ss);
419 ss << "\n" << why.str();
420
421 if (!found) {
422 // No expectation matches this call - reports a failure.
423 Expect(false, NULL, -1, ss.str());
424 } else if (is_excessive) {
425 // We had an upper-bound violation and the failure message is in ss.
426 Expect(false, untyped_expectation->file(),
427 untyped_expectation->line(), ss.str());
428 } else {
429 // We had an expected call and the matching expectation is
430 // described in ss.
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000431 Log(kInfo, loc.str() + ss.str(), 2);
zhanyong.waned6c9272011-02-23 19:39:27 +0000432 }
433
434 return result;
435}
436
437// Returns an Expectation object that references and co-owns exp,
438// which must be an expectation on this mock function.
439Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
440 for (UntypedExpectations::const_iterator it =
441 untyped_expectations_.begin();
442 it != untyped_expectations_.end(); ++it) {
443 if (it->get() == exp) {
444 return Expectation(*it);
445 }
446 }
447
448 Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
449 return Expectation();
450 // The above statement is just to make the code compile, and will
451 // never be executed.
452}
453
454// Verifies that all expectations on this mock function have been
455// satisfied. Reports one or more Google Test non-fatal failures
456// and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000457bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
458 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000459 g_gmock_mutex.AssertHeld();
460 bool expectations_met = true;
461 for (UntypedExpectations::const_iterator it =
462 untyped_expectations_.begin();
463 it != untyped_expectations_.end(); ++it) {
464 ExpectationBase* const untyped_expectation = it->get();
465 if (untyped_expectation->IsOverSaturated()) {
466 // There was an upper-bound violation. Since the error was
467 // already reported when it occurred, there is no need to do
468 // anything here.
469 expectations_met = false;
470 } else if (!untyped_expectation->IsSatisfied()) {
471 expectations_met = false;
472 ::std::stringstream ss;
473 ss << "Actual function call count doesn't match "
474 << untyped_expectation->source_text() << "...\n";
475 // No need to show the source file location of the expectation
476 // in the description, as the Expect() call that follows already
477 // takes care of it.
478 untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
479 untyped_expectation->DescribeCallCountTo(&ss);
480 Expect(false, untyped_expectation->file(),
481 untyped_expectation->line(), ss.str());
482 }
483 }
vladlosev9bcb5f92011-10-24 23:41:07 +0000484
485 // Deleting our expectations may trigger other mock objects to be deleted, for
486 // example if an action contains a reference counted smart pointer to that
487 // mock object, and that is the last reference. So if we delete our
488 // expectations within the context of the global mutex we may deadlock when
489 // this method is called again. Instead, make a copy of the set of
490 // expectations to delete, clear our set within the mutex, and then clear the
491 // copied set outside of it.
492 UntypedExpectations expectations_to_delete;
493 untyped_expectations_.swap(expectations_to_delete);
494
495 g_gmock_mutex.Unlock();
496 expectations_to_delete.clear();
497 g_gmock_mutex.Lock();
498
zhanyong.waned6c9272011-02-23 19:39:27 +0000499 return expectations_met;
500}
501
shiqiane35fdd92008-12-10 05:08:54 +0000502} // namespace internal
503
504// Class Mock.
505
506namespace {
507
508typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
shiqiane35fdd92008-12-10 05:08:54 +0000509
zhanyong.wandf35a762009-04-22 22:25:31 +0000510// The current state of a mock object. Such information is needed for
511// detecting leaked mock objects and explicitly verifying a mock's
512// expectations.
513struct MockObjectState {
514 MockObjectState()
515 : first_used_file(NULL), first_used_line(-1), leakable(false) {}
516
517 // Where in the source file an ON_CALL or EXPECT_CALL is first
518 // invoked on this mock object.
519 const char* first_used_file;
520 int first_used_line;
zhanyong.wane7bb5ed2009-05-05 23:14:47 +0000521 ::std::string first_used_test_case;
522 ::std::string first_used_test;
zhanyong.wandf35a762009-04-22 22:25:31 +0000523 bool leakable; // true iff it's OK to leak the object.
524 FunctionMockers function_mockers; // All registered methods of the object.
525};
526
527// A global registry holding the state of all mock objects that are
528// alive. A mock object is added to this registry the first time
529// Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It
530// is removed from the registry in the mock object's destructor.
531class MockObjectRegistry {
532 public:
533 // Maps a mock object (identified by its address) to its state.
534 typedef std::map<const void*, MockObjectState> StateMap;
535
536 // This destructor will be called when a program exits, after all
537 // tests in it have been run. By then, there should be no mock
538 // object alive. Therefore we report any living object as test
539 // failure, unless the user explicitly asked us to ignore it.
540 ~MockObjectRegistry() {
zhanyong.wan9571b282009-08-07 07:15:56 +0000541 // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is
542 // a macro.
zhanyong.wandf35a762009-04-22 22:25:31 +0000543
544 if (!GMOCK_FLAG(catch_leaked_mocks))
545 return;
546
547 int leaked_count = 0;
548 for (StateMap::const_iterator it = states_.begin(); it != states_.end();
549 ++it) {
550 if (it->second.leakable) // The user said it's fine to leak this object.
551 continue;
552
553 // TODO(wan@google.com): Print the type of the leaked object.
554 // This can help the user identify the leaked object.
zhanyong.wan9571b282009-08-07 07:15:56 +0000555 std::cout << "\n";
zhanyong.wandf35a762009-04-22 22:25:31 +0000556 const MockObjectState& state = it->second;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000557 std::cout << internal::FormatFileLocation(state.first_used_file,
558 state.first_used_line);
zhanyong.wan9571b282009-08-07 07:15:56 +0000559 std::cout << " ERROR: this mock object";
zhanyong.wane7bb5ed2009-05-05 23:14:47 +0000560 if (state.first_used_test != "") {
zhanyong.wan9571b282009-08-07 07:15:56 +0000561 std::cout << " (used in test " << state.first_used_test_case << "."
zhanyong.wane7bb5ed2009-05-05 23:14:47 +0000562 << state.first_used_test << ")";
563 }
zhanyong.wan9571b282009-08-07 07:15:56 +0000564 std::cout << " should be deleted but never is. Its address is @"
zhanyong.wane7bb5ed2009-05-05 23:14:47 +0000565 << it->first << ".";
zhanyong.wandf35a762009-04-22 22:25:31 +0000566 leaked_count++;
567 }
568 if (leaked_count > 0) {
zhanyong.wan9571b282009-08-07 07:15:56 +0000569 std::cout << "\nERROR: " << leaked_count
zhanyong.wandf35a762009-04-22 22:25:31 +0000570 << " leaked mock " << (leaked_count == 1 ? "object" : "objects")
571 << " found at program exit.\n";
zhanyong.wan9571b282009-08-07 07:15:56 +0000572 std::cout.flush();
zhanyong.wandf35a762009-04-22 22:25:31 +0000573 ::std::cerr.flush();
574 // RUN_ALL_TESTS() has already returned when this destructor is
575 // called. Therefore we cannot use the normal Google Test
576 // failure reporting mechanism.
577 _exit(1); // We cannot call exit() as it is not reentrant and
578 // may already have been called.
579 }
580 }
581
582 StateMap& states() { return states_; }
jgm79a367e2012-04-10 16:02:11 +0000583
zhanyong.wandf35a762009-04-22 22:25:31 +0000584 private:
585 StateMap states_;
586};
587
588// Protected by g_gmock_mutex.
shiqiane35fdd92008-12-10 05:08:54 +0000589MockObjectRegistry g_mock_object_registry;
590
591// Maps a mock object to the reaction Google Mock should have when an
592// uninteresting method is called. Protected by g_gmock_mutex.
593std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
594
595// Sets the reaction Google Mock should have when an uninteresting
596// method of the given mock object is called.
shiqiane35fdd92008-12-10 05:08:54 +0000597void SetReactionOnUninterestingCalls(const void* mock_obj,
vladlosev4d60a592011-10-24 21:16:22 +0000598 internal::CallReaction reaction)
599 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000600 internal::MutexLock l(&internal::g_gmock_mutex);
601 g_uninteresting_call_reaction[mock_obj] = reaction;
602}
603
604} // namespace
605
606// Tells Google Mock to allow uninteresting calls on the given mock
607// object.
vladlosev4d60a592011-10-24 21:16:22 +0000608void Mock::AllowUninterestingCalls(const void* mock_obj)
609 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000610 SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
shiqiane35fdd92008-12-10 05:08:54 +0000611}
612
613// Tells Google Mock to warn the user about uninteresting calls on the
614// given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000615void Mock::WarnUninterestingCalls(const void* mock_obj)
616 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000617 SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
shiqiane35fdd92008-12-10 05:08:54 +0000618}
619
620// Tells Google Mock to fail uninteresting calls on the given mock
621// object.
vladlosev4d60a592011-10-24 21:16:22 +0000622void Mock::FailUninterestingCalls(const void* mock_obj)
623 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000624 SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
shiqiane35fdd92008-12-10 05:08:54 +0000625}
626
627// Tells Google Mock the given mock object is being destroyed and its
628// entry in the call-reaction table should be removed.
vladlosev4d60a592011-10-24 21:16:22 +0000629void Mock::UnregisterCallReaction(const void* mock_obj)
630 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000631 internal::MutexLock l(&internal::g_gmock_mutex);
632 g_uninteresting_call_reaction.erase(mock_obj);
633}
634
635// Returns the reaction Google Mock will have on uninteresting calls
636// made on the given mock object.
shiqiane35fdd92008-12-10 05:08:54 +0000637internal::CallReaction Mock::GetReactionOnUninterestingCalls(
vladlosev4d60a592011-10-24 21:16:22 +0000638 const void* mock_obj)
639 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000640 internal::MutexLock l(&internal::g_gmock_mutex);
641 return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000642 internal::kWarn : g_uninteresting_call_reaction[mock_obj];
shiqiane35fdd92008-12-10 05:08:54 +0000643}
644
zhanyong.wandf35a762009-04-22 22:25:31 +0000645// Tells Google Mock to ignore mock_obj when checking for leaked mock
646// objects.
vladlosev4d60a592011-10-24 21:16:22 +0000647void Mock::AllowLeak(const void* mock_obj)
648 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +0000649 internal::MutexLock l(&internal::g_gmock_mutex);
650 g_mock_object_registry.states()[mock_obj].leakable = true;
651}
652
shiqiane35fdd92008-12-10 05:08:54 +0000653// Verifies and clears all expectations on the given mock object. If
654// the expectations aren't satisfied, generates one or more Google
655// Test non-fatal failures and returns false.
vladlosev4d60a592011-10-24 21:16:22 +0000656bool Mock::VerifyAndClearExpectations(void* mock_obj)
657 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000658 internal::MutexLock l(&internal::g_gmock_mutex);
659 return VerifyAndClearExpectationsLocked(mock_obj);
660}
661
662// Verifies all expectations on the given mock object and clears its
663// default actions and expectations. Returns true iff the
664// verification was successful.
vladlosev4d60a592011-10-24 21:16:22 +0000665bool Mock::VerifyAndClear(void* mock_obj)
666 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000667 internal::MutexLock l(&internal::g_gmock_mutex);
668 ClearDefaultActionsLocked(mock_obj);
669 return VerifyAndClearExpectationsLocked(mock_obj);
670}
671
672// Verifies and clears all expectations on the given mock object. If
673// the expectations aren't satisfied, generates one or more Google
674// Test non-fatal failures and returns false.
vladlosev4d60a592011-10-24 21:16:22 +0000675bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
676 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000677 internal::g_gmock_mutex.AssertHeld();
zhanyong.wandf35a762009-04-22 22:25:31 +0000678 if (g_mock_object_registry.states().count(mock_obj) == 0) {
shiqiane35fdd92008-12-10 05:08:54 +0000679 // No EXPECT_CALL() was set on the given mock object.
680 return true;
681 }
682
683 // Verifies and clears the expectations on each mock method in the
684 // given mock object.
685 bool expectations_met = true;
zhanyong.wandf35a762009-04-22 22:25:31 +0000686 FunctionMockers& mockers =
687 g_mock_object_registry.states()[mock_obj].function_mockers;
shiqiane35fdd92008-12-10 05:08:54 +0000688 for (FunctionMockers::const_iterator it = mockers.begin();
689 it != mockers.end(); ++it) {
690 if (!(*it)->VerifyAndClearExpectationsLocked()) {
691 expectations_met = false;
692 }
693 }
694
695 // We don't clear the content of mockers, as they may still be
696 // needed by ClearDefaultActionsLocked().
697 return expectations_met;
698}
699
700// Registers a mock object and a mock method it owns.
shiqiane35fdd92008-12-10 05:08:54 +0000701void Mock::Register(const void* mock_obj,
vladlosev4d60a592011-10-24 21:16:22 +0000702 internal::UntypedFunctionMockerBase* mocker)
703 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000704 internal::MutexLock l(&internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000705 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
706}
707
708// Tells Google Mock where in the source code mock_obj is used in an
709// ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
710// information helps the user identify which object it is.
vladlosev4d60a592011-10-24 21:16:22 +0000711void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
712 const char* file, int line)
713 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +0000714 internal::MutexLock l(&internal::g_gmock_mutex);
715 MockObjectState& state = g_mock_object_registry.states()[mock_obj];
716 if (state.first_used_file == NULL) {
717 state.first_used_file = file;
718 state.first_used_line = line;
zhanyong.wane7bb5ed2009-05-05 23:14:47 +0000719 const TestInfo* const test_info =
720 UnitTest::GetInstance()->current_test_info();
721 if (test_info != NULL) {
722 // TODO(wan@google.com): record the test case name when the
723 // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or
724 // TearDownTestCase().
725 state.first_used_test_case = test_info->test_case_name();
726 state.first_used_test = test_info->name();
727 }
zhanyong.wandf35a762009-04-22 22:25:31 +0000728 }
shiqiane35fdd92008-12-10 05:08:54 +0000729}
730
731// Unregisters a mock method; removes the owning mock object from the
732// registry when the last mock method associated with it has been
733// unregistered. This is called only in the destructor of
734// FunctionMockerBase.
vladlosev4d60a592011-10-24 21:16:22 +0000735void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
736 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000737 internal::g_gmock_mutex.AssertHeld();
zhanyong.wandf35a762009-04-22 22:25:31 +0000738 for (MockObjectRegistry::StateMap::iterator it =
739 g_mock_object_registry.states().begin();
740 it != g_mock_object_registry.states().end(); ++it) {
741 FunctionMockers& mockers = it->second.function_mockers;
shiqiane35fdd92008-12-10 05:08:54 +0000742 if (mockers.erase(mocker) > 0) {
743 // mocker was in mockers and has been just removed.
744 if (mockers.empty()) {
zhanyong.wandf35a762009-04-22 22:25:31 +0000745 g_mock_object_registry.states().erase(it);
shiqiane35fdd92008-12-10 05:08:54 +0000746 }
747 return;
748 }
749 }
750}
751
752// Clears all ON_CALL()s set on the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000753void Mock::ClearDefaultActionsLocked(void* mock_obj)
754 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000755 internal::g_gmock_mutex.AssertHeld();
756
zhanyong.wandf35a762009-04-22 22:25:31 +0000757 if (g_mock_object_registry.states().count(mock_obj) == 0) {
shiqiane35fdd92008-12-10 05:08:54 +0000758 // No ON_CALL() was set on the given mock object.
759 return;
760 }
761
762 // Clears the default actions for each mock method in the given mock
763 // object.
zhanyong.wandf35a762009-04-22 22:25:31 +0000764 FunctionMockers& mockers =
765 g_mock_object_registry.states()[mock_obj].function_mockers;
shiqiane35fdd92008-12-10 05:08:54 +0000766 for (FunctionMockers::const_iterator it = mockers.begin();
767 it != mockers.end(); ++it) {
768 (*it)->ClearDefaultActionsLocked();
769 }
770
771 // We don't clear the content of mockers, as they may still be
772 // needed by VerifyAndClearExpectationsLocked().
773}
774
zhanyong.wan7c95d832009-10-01 21:56:16 +0000775Expectation::Expectation() {}
776
777Expectation::Expectation(
zhanyong.wan32de5f52009-12-23 00:13:23 +0000778 const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base)
779 : expectation_base_(an_expectation_base) {}
zhanyong.wan7c95d832009-10-01 21:56:16 +0000780
781Expectation::~Expectation() {}
782
shiqiane35fdd92008-12-10 05:08:54 +0000783// Adds an expectation to a sequence.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000784void Sequence::AddExpectation(const Expectation& expectation) const {
shiqiane35fdd92008-12-10 05:08:54 +0000785 if (*last_expectation_ != expectation) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000786 if (last_expectation_->expectation_base() != NULL) {
787 expectation.expectation_base()->immediate_prerequisites_
788 += *last_expectation_;
shiqiane35fdd92008-12-10 05:08:54 +0000789 }
790 *last_expectation_ = expectation;
791 }
792}
793
794// Creates the implicit sequence if there isn't one.
795InSequence::InSequence() {
796 if (internal::g_gmock_implicit_sequence.get() == NULL) {
797 internal::g_gmock_implicit_sequence.set(new Sequence);
798 sequence_created_ = true;
799 } else {
800 sequence_created_ = false;
801 }
802}
803
804// Deletes the implicit sequence if it was created by the constructor
805// of this object.
806InSequence::~InSequence() {
807 if (sequence_created_) {
808 delete internal::g_gmock_implicit_sequence.get();
809 internal::g_gmock_implicit_sequence.set(NULL);
810 }
811}
812
813} // namespace testing