blob: fc4968baab9677d29e277d8eb0b062ff8f781d0c [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,
Nico Weber09fd5b32017-05-15 17:07:03 -040061 const std::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.
Nico Weber09fd5b32017-05-15 17:07:03 -040068ExpectationBase::ExpectationBase(const char* a_file, int a_line,
69 const std::string& a_source_text)
zhanyong.wan32de5f52009-12-23 00:13:23 +000070 : file_(a_file),
71 line_(a_line),
72 source_text_(a_source_text),
shiqiane35fdd92008-12-10 05:08:54 +000073 cardinality_specified_(false),
74 cardinality_(Exactly(1)),
75 call_count_(0),
zhanyong.waned6c9272011-02-23 19:39:27 +000076 retired_(false),
77 extra_matcher_specified_(false),
78 repeated_action_specified_(false),
79 retires_on_saturation_(false),
80 last_clause_(kNone),
81 action_count_checked_(false) {}
shiqiane35fdd92008-12-10 05:08:54 +000082
83// Destructs an ExpectationBase object.
84ExpectationBase::~ExpectationBase() {}
85
86// Explicitly specifies the cardinality of this expectation. Used by
87// the subclasses to implement the .Times() clause.
zhanyong.wan32de5f52009-12-23 00:13:23 +000088void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {
shiqiane35fdd92008-12-10 05:08:54 +000089 cardinality_specified_ = true;
zhanyong.wan32de5f52009-12-23 00:13:23 +000090 cardinality_ = a_cardinality;
shiqiane35fdd92008-12-10 05:08:54 +000091}
92
93// Retires all pre-requisites of this expectation.
vladlosev4d60a592011-10-24 21:16:22 +000094void ExpectationBase::RetireAllPreRequisites()
95 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +000096 if (is_retired()) {
97 // We can take this short-cut as we never retire an expectation
98 // until we have retired all its pre-requisites.
99 return;
100 }
101
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000102 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
103 it != immediate_prerequisites_.end(); ++it) {
104 ExpectationBase* const prerequisite = it->expectation_base().get();
shiqiane35fdd92008-12-10 05:08:54 +0000105 if (!prerequisite->is_retired()) {
106 prerequisite->RetireAllPreRequisites();
107 prerequisite->Retire();
108 }
109 }
110}
111
112// Returns true iff all pre-requisites of this expectation have been
113// satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000114bool ExpectationBase::AllPrerequisitesAreSatisfied() const
115 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000116 g_gmock_mutex.AssertHeld();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000117 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
shiqiane35fdd92008-12-10 05:08:54 +0000118 it != immediate_prerequisites_.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000119 if (!(it->expectation_base()->IsSatisfied()) ||
120 !(it->expectation_base()->AllPrerequisitesAreSatisfied()))
shiqiane35fdd92008-12-10 05:08:54 +0000121 return false;
122 }
123 return true;
124}
125
126// Adds unsatisfied pre-requisites of this expectation to 'result'.
vladlosev4d60a592011-10-24 21:16:22 +0000127void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const
128 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000129 g_gmock_mutex.AssertHeld();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000130 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
shiqiane35fdd92008-12-10 05:08:54 +0000131 it != immediate_prerequisites_.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000132 if (it->expectation_base()->IsSatisfied()) {
shiqiane35fdd92008-12-10 05:08:54 +0000133 // If *it is satisfied and has a call count of 0, some of its
134 // pre-requisites may not be satisfied yet.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000135 if (it->expectation_base()->call_count_ == 0) {
136 it->expectation_base()->FindUnsatisfiedPrerequisites(result);
shiqiane35fdd92008-12-10 05:08:54 +0000137 }
138 } else {
139 // Now that we know *it is unsatisfied, we are not so interested
140 // in whether its pre-requisites are satisfied. Therefore we
141 // don't recursively call FindUnsatisfiedPrerequisites() here.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000142 *result += *it;
shiqiane35fdd92008-12-10 05:08:54 +0000143 }
144 }
145}
146
zhanyong.waned6c9272011-02-23 19:39:27 +0000147// Describes how many times a function call matching this
148// expectation has occurred.
vladlosev4d60a592011-10-24 21:16:22 +0000149void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
150 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000151 g_gmock_mutex.AssertHeld();
152
153 // Describes how many times the function is expected to be called.
154 *os << " Expected: to be ";
155 cardinality().DescribeTo(os);
156 *os << "\n Actual: ";
157 Cardinality::DescribeActualCallCountTo(call_count(), os);
158
159 // Describes the state of the expectation (e.g. is it satisfied?
160 // is it active?).
161 *os << " - " << (IsOverSaturated() ? "over-saturated" :
162 IsSaturated() ? "saturated" :
163 IsSatisfied() ? "satisfied" : "unsatisfied")
164 << " and "
165 << (is_retired() ? "retired" : "active");
166}
167
168// Checks the action count (i.e. the number of WillOnce() and
169// WillRepeatedly() clauses) against the cardinality if this hasn't
170// been done before. Prints a warning if there are too many or too
171// few actions.
vladlosev4d60a592011-10-24 21:16:22 +0000172void ExpectationBase::CheckActionCountIfNotDone() const
173 GTEST_LOCK_EXCLUDED_(mutex_) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000174 bool should_check = false;
175 {
176 MutexLock l(&mutex_);
177 if (!action_count_checked_) {
178 action_count_checked_ = true;
179 should_check = true;
180 }
181 }
182
183 if (should_check) {
184 if (!cardinality_specified_) {
185 // The cardinality was inferred - no need to check the action
186 // count against it.
187 return;
188 }
189
190 // The cardinality was explicitly specified.
191 const int action_count = static_cast<int>(untyped_actions_.size());
192 const int upper_bound = cardinality().ConservativeUpperBound();
193 const int lower_bound = cardinality().ConservativeLowerBound();
194 bool too_many; // True if there are too many actions, or false
195 // if there are too few.
196 if (action_count > upper_bound ||
197 (action_count == upper_bound && repeated_action_specified_)) {
198 too_many = true;
199 } else if (0 < action_count && action_count < lower_bound &&
200 !repeated_action_specified_) {
201 too_many = false;
202 } else {
203 return;
204 }
205
206 ::std::stringstream ss;
207 DescribeLocationTo(&ss);
208 ss << "Too " << (too_many ? "many" : "few")
209 << " actions specified in " << source_text() << "...\n"
210 << "Expected to be ";
211 cardinality().DescribeTo(&ss);
212 ss << ", but has " << (too_many ? "" : "only ")
213 << action_count << " WillOnce()"
214 << (action_count == 1 ? "" : "s");
215 if (repeated_action_specified_) {
216 ss << " and a WillRepeatedly()";
217 }
218 ss << ".";
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000219 Log(kWarning, ss.str(), -1); // -1 means "don't print stack trace".
zhanyong.waned6c9272011-02-23 19:39:27 +0000220 }
221}
222
223// Implements the .Times() clause.
224void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
225 if (last_clause_ == kTimes) {
226 ExpectSpecProperty(false,
227 ".Times() cannot appear "
228 "more than once in an EXPECT_CALL().");
229 } else {
230 ExpectSpecProperty(last_clause_ < kTimes,
231 ".Times() cannot appear after "
232 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
233 "or .RetiresOnSaturation().");
234 }
235 last_clause_ = kTimes;
236
237 SpecifyCardinality(a_cardinality);
238}
239
shiqiane35fdd92008-12-10 05:08:54 +0000240// Points to the implicit sequence introduced by a living InSequence
241// object (if any) in the current thread or NULL.
vladlosev587c1b32011-05-20 00:42:22 +0000242GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
shiqiane35fdd92008-12-10 05:08:54 +0000243
244// Reports an uninteresting call (whose description is in msg) in the
245// manner specified by 'reaction'.
Nico Weber09fd5b32017-05-15 17:07:03 -0400246void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
kosak5625dd32015-02-14 22:05:58 +0000247 // Include a stack trace only if --gmock_verbose=info is specified.
248 const int stack_frames_to_skip =
249 GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1;
shiqiane35fdd92008-12-10 05:08:54 +0000250 switch (reaction) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000251 case kAllow:
kosak5625dd32015-02-14 22:05:58 +0000252 Log(kInfo, msg, stack_frames_to_skip);
shiqiane35fdd92008-12-10 05:08:54 +0000253 break;
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000254 case kWarn:
kosak04ce8522014-01-12 23:42:34 +0000255 Log(kWarning,
256 msg +
257 "\nNOTE: You can safely ignore the above warning unless this "
258 "call should not happen. Do not suppress it by blindly adding "
259 "an EXPECT_CALL() if you don't mean to enforce the call. "
Jacob Meachamd4aa34b2016-02-16 17:45:11 -0800260 "See https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#"
261 "knowing-when-to-expect for details.\n",
kosak5625dd32015-02-14 22:05:58 +0000262 stack_frames_to_skip);
shiqiane35fdd92008-12-10 05:08:54 +0000263 break;
264 default: // FAIL
265 Expect(false, NULL, -1, msg);
266 }
267}
268
zhanyong.waned6c9272011-02-23 19:39:27 +0000269UntypedFunctionMockerBase::UntypedFunctionMockerBase()
270 : mock_obj_(NULL), name_("") {}
271
272UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
273
274// Sets the mock object this mock method belongs to, and registers
275// this information in the global mock registry. Will be called
276// whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
277// method.
vladlosev4d60a592011-10-24 21:16:22 +0000278void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
279 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000280 {
281 MutexLock l(&g_gmock_mutex);
282 mock_obj_ = mock_obj;
283 }
284 Mock::Register(mock_obj, this);
285}
286
287// Sets the mock object this mock method belongs to, and sets the name
288// of the mock function. Will be called upon each invocation of this
289// mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000290void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
291 const char* name)
292 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000293 // We protect name_ under g_gmock_mutex in case this mock function
294 // is called from two threads concurrently.
295 MutexLock l(&g_gmock_mutex);
296 mock_obj_ = mock_obj;
297 name_ = name;
298}
299
300// Returns the name of the function being mocked. Must be called
301// after RegisterOwner() or SetOwnerAndName() has been called.
vladlosev4d60a592011-10-24 21:16:22 +0000302const void* UntypedFunctionMockerBase::MockObject() const
303 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000304 const void* mock_obj;
305 {
306 // We protect mock_obj_ under g_gmock_mutex in case this mock
307 // function is called from two threads concurrently.
308 MutexLock l(&g_gmock_mutex);
309 Assert(mock_obj_ != NULL, __FILE__, __LINE__,
310 "MockObject() must not be called before RegisterOwner() or "
311 "SetOwnerAndName() has been called.");
312 mock_obj = mock_obj_;
313 }
314 return mock_obj;
315}
316
317// Returns the name of this mock method. Must be called after
318// SetOwnerAndName() has been called.
vladlosev4d60a592011-10-24 21:16:22 +0000319const char* UntypedFunctionMockerBase::Name() const
320 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000321 const char* name;
322 {
323 // We protect name_ under g_gmock_mutex in case this mock
324 // function is called from two threads concurrently.
325 MutexLock l(&g_gmock_mutex);
326 Assert(name_ != NULL, __FILE__, __LINE__,
327 "Name() must not be called before SetOwnerAndName() has "
328 "been called.");
329 name = name_;
330 }
331 return name;
332}
333
334// Calculates the result of invoking this mock function with the given
335// arguments, prints it, and returns it. The caller is responsible
336// for deleting the result.
kosakb5c81092014-01-29 06:41:44 +0000337UntypedActionResultHolderBase*
vladlosev4d60a592011-10-24 21:16:22 +0000338UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args)
339 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000340 if (untyped_expectations_.size() == 0) {
341 // No expectation is set on this mock method - we have an
342 // uninteresting call.
343
344 // We must get Google Mock's reaction on uninteresting calls
345 // made on this mock object BEFORE performing the action,
346 // because the action may DELETE the mock object and make the
347 // following expression meaningless.
348 const CallReaction reaction =
349 Mock::GetReactionOnUninterestingCalls(MockObject());
350
351 // True iff we need to print this call's arguments and return
352 // value. This definition must be kept in sync with
353 // the behavior of ReportUninterestingCall().
354 const bool need_to_report_uninteresting_call =
355 // If the user allows this uninteresting call, we print it
Jonathan Wakelyb70cf1a2017-09-27 13:31:13 +0100356 // only when they want informational messages.
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000357 reaction == kAllow ? LogIsVisible(kInfo) :
zhanyong.waned6c9272011-02-23 19:39:27 +0000358 // If the user wants this to be a warning, we print it only
Jonathan Wakelyb70cf1a2017-09-27 13:31:13 +0100359 // when they want to see warnings.
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000360 reaction == kWarn ? LogIsVisible(kWarning) :
zhanyong.waned6c9272011-02-23 19:39:27 +0000361 // Otherwise, the user wants this to be an error, and we
362 // should always print detailed information in the error.
363 true;
364
365 if (!need_to_report_uninteresting_call) {
366 // Perform the action without printing the call information.
Maurice Gilden5b4166f2017-07-27 11:12:12 +0200367 return this->UntypedPerformDefaultAction(untyped_args, "Function call: " + std::string(Name()));
zhanyong.waned6c9272011-02-23 19:39:27 +0000368 }
369
370 // Warns about the uninteresting call.
371 ::std::stringstream ss;
372 this->UntypedDescribeUninterestingCall(untyped_args, &ss);
373
374 // Calculates the function result.
kosakb5c81092014-01-29 06:41:44 +0000375 UntypedActionResultHolderBase* const result =
zhanyong.waned6c9272011-02-23 19:39:27 +0000376 this->UntypedPerformDefaultAction(untyped_args, ss.str());
377
378 // Prints the function result.
379 if (result != NULL)
380 result->PrintAsActionResult(&ss);
381
382 ReportUninterestingCall(reaction, ss.str());
383 return result;
384 }
385
386 bool is_excessive = false;
387 ::std::stringstream ss;
388 ::std::stringstream why;
389 ::std::stringstream loc;
390 const void* untyped_action = NULL;
391
392 // The UntypedFindMatchingExpectation() function acquires and
393 // releases g_gmock_mutex.
394 const ExpectationBase* const untyped_expectation =
395 this->UntypedFindMatchingExpectation(
396 untyped_args, &untyped_action, &is_excessive,
397 &ss, &why);
398 const bool found = untyped_expectation != NULL;
399
400 // True iff we need to print the call's arguments and return value.
401 // This definition must be kept in sync with the uses of Expect()
402 // and Log() in this function.
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000403 const bool need_to_report_call =
404 !found || is_excessive || LogIsVisible(kInfo);
zhanyong.waned6c9272011-02-23 19:39:27 +0000405 if (!need_to_report_call) {
406 // Perform the action without printing the call information.
407 return
408 untyped_action == NULL ?
409 this->UntypedPerformDefaultAction(untyped_args, "") :
410 this->UntypedPerformAction(untyped_action, untyped_args);
411 }
412
413 ss << " Function call: " << Name();
414 this->UntypedPrintArgs(untyped_args, &ss);
415
416 // In case the action deletes a piece of the expectation, we
417 // generate the message beforehand.
418 if (found && !is_excessive) {
419 untyped_expectation->DescribeLocationTo(&loc);
420 }
421
kosakb5c81092014-01-29 06:41:44 +0000422 UntypedActionResultHolderBase* const result =
zhanyong.waned6c9272011-02-23 19:39:27 +0000423 untyped_action == NULL ?
424 this->UntypedPerformDefaultAction(untyped_args, ss.str()) :
425 this->UntypedPerformAction(untyped_action, untyped_args);
426 if (result != NULL)
427 result->PrintAsActionResult(&ss);
428 ss << "\n" << why.str();
429
430 if (!found) {
431 // No expectation matches this call - reports a failure.
432 Expect(false, NULL, -1, ss.str());
433 } else if (is_excessive) {
434 // We had an upper-bound violation and the failure message is in ss.
435 Expect(false, untyped_expectation->file(),
436 untyped_expectation->line(), ss.str());
437 } else {
438 // We had an expected call and the matching expectation is
439 // described in ss.
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000440 Log(kInfo, loc.str() + ss.str(), 2);
zhanyong.waned6c9272011-02-23 19:39:27 +0000441 }
442
443 return result;
444}
445
446// Returns an Expectation object that references and co-owns exp,
447// which must be an expectation on this mock function.
448Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
449 for (UntypedExpectations::const_iterator it =
450 untyped_expectations_.begin();
451 it != untyped_expectations_.end(); ++it) {
452 if (it->get() == exp) {
453 return Expectation(*it);
454 }
455 }
456
457 Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
458 return Expectation();
459 // The above statement is just to make the code compile, and will
460 // never be executed.
461}
462
463// Verifies that all expectations on this mock function have been
464// satisfied. Reports one or more Google Test non-fatal failures
465// and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000466bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
467 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000468 g_gmock_mutex.AssertHeld();
469 bool expectations_met = true;
470 for (UntypedExpectations::const_iterator it =
471 untyped_expectations_.begin();
472 it != untyped_expectations_.end(); ++it) {
473 ExpectationBase* const untyped_expectation = it->get();
474 if (untyped_expectation->IsOverSaturated()) {
475 // There was an upper-bound violation. Since the error was
476 // already reported when it occurred, there is no need to do
477 // anything here.
478 expectations_met = false;
479 } else if (!untyped_expectation->IsSatisfied()) {
480 expectations_met = false;
481 ::std::stringstream ss;
482 ss << "Actual function call count doesn't match "
483 << untyped_expectation->source_text() << "...\n";
484 // No need to show the source file location of the expectation
485 // in the description, as the Expect() call that follows already
486 // takes care of it.
487 untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
488 untyped_expectation->DescribeCallCountTo(&ss);
489 Expect(false, untyped_expectation->file(),
490 untyped_expectation->line(), ss.str());
491 }
492 }
vladlosev9bcb5f92011-10-24 23:41:07 +0000493
494 // Deleting our expectations may trigger other mock objects to be deleted, for
495 // example if an action contains a reference counted smart pointer to that
496 // mock object, and that is the last reference. So if we delete our
497 // expectations within the context of the global mutex we may deadlock when
498 // this method is called again. Instead, make a copy of the set of
499 // expectations to delete, clear our set within the mutex, and then clear the
500 // copied set outside of it.
501 UntypedExpectations expectations_to_delete;
502 untyped_expectations_.swap(expectations_to_delete);
503
504 g_gmock_mutex.Unlock();
505 expectations_to_delete.clear();
506 g_gmock_mutex.Lock();
507
zhanyong.waned6c9272011-02-23 19:39:27 +0000508 return expectations_met;
509}
510
Alyssa Wilka2803bc2017-08-16 12:43:26 -0400511CallReaction intToCallReaction(int mock_behavior) {
512 if (mock_behavior >= kAllow && mock_behavior <= kFail) {
513 return static_cast<internal::CallReaction>(mock_behavior);
514 }
515 return kWarn;
516}
517
shiqiane35fdd92008-12-10 05:08:54 +0000518} // namespace internal
519
520// Class Mock.
521
522namespace {
523
524typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
shiqiane35fdd92008-12-10 05:08:54 +0000525
zhanyong.wandf35a762009-04-22 22:25:31 +0000526// The current state of a mock object. Such information is needed for
527// detecting leaked mock objects and explicitly verifying a mock's
528// expectations.
529struct MockObjectState {
530 MockObjectState()
531 : first_used_file(NULL), first_used_line(-1), leakable(false) {}
532
533 // Where in the source file an ON_CALL or EXPECT_CALL is first
534 // invoked on this mock object.
535 const char* first_used_file;
536 int first_used_line;
zhanyong.wane7bb5ed2009-05-05 23:14:47 +0000537 ::std::string first_used_test_case;
538 ::std::string first_used_test;
zhanyong.wandf35a762009-04-22 22:25:31 +0000539 bool leakable; // true iff it's OK to leak the object.
540 FunctionMockers function_mockers; // All registered methods of the object.
541};
542
543// A global registry holding the state of all mock objects that are
544// alive. A mock object is added to this registry the first time
545// Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It
546// is removed from the registry in the mock object's destructor.
547class MockObjectRegistry {
548 public:
549 // Maps a mock object (identified by its address) to its state.
550 typedef std::map<const void*, MockObjectState> StateMap;
551
552 // This destructor will be called when a program exits, after all
553 // tests in it have been run. By then, there should be no mock
554 // object alive. Therefore we report any living object as test
555 // failure, unless the user explicitly asked us to ignore it.
556 ~MockObjectRegistry() {
zhanyong.wan9571b282009-08-07 07:15:56 +0000557 // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is
558 // a macro.
zhanyong.wandf35a762009-04-22 22:25:31 +0000559
560 if (!GMOCK_FLAG(catch_leaked_mocks))
561 return;
562
563 int leaked_count = 0;
564 for (StateMap::const_iterator it = states_.begin(); it != states_.end();
565 ++it) {
566 if (it->second.leakable) // The user said it's fine to leak this object.
567 continue;
568
569 // TODO(wan@google.com): Print the type of the leaked object.
570 // This can help the user identify the leaked object.
zhanyong.wan9571b282009-08-07 07:15:56 +0000571 std::cout << "\n";
zhanyong.wandf35a762009-04-22 22:25:31 +0000572 const MockObjectState& state = it->second;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000573 std::cout << internal::FormatFileLocation(state.first_used_file,
574 state.first_used_line);
zhanyong.wan9571b282009-08-07 07:15:56 +0000575 std::cout << " ERROR: this mock object";
zhanyong.wane7bb5ed2009-05-05 23:14:47 +0000576 if (state.first_used_test != "") {
zhanyong.wan9571b282009-08-07 07:15:56 +0000577 std::cout << " (used in test " << state.first_used_test_case << "."
zhanyong.wane7bb5ed2009-05-05 23:14:47 +0000578 << state.first_used_test << ")";
579 }
zhanyong.wan9571b282009-08-07 07:15:56 +0000580 std::cout << " should be deleted but never is. Its address is @"
zhanyong.wane7bb5ed2009-05-05 23:14:47 +0000581 << it->first << ".";
zhanyong.wandf35a762009-04-22 22:25:31 +0000582 leaked_count++;
583 }
584 if (leaked_count > 0) {
zhanyong.wan9571b282009-08-07 07:15:56 +0000585 std::cout << "\nERROR: " << leaked_count
zhanyong.wandf35a762009-04-22 22:25:31 +0000586 << " leaked mock " << (leaked_count == 1 ? "object" : "objects")
587 << " found at program exit.\n";
zhanyong.wan9571b282009-08-07 07:15:56 +0000588 std::cout.flush();
zhanyong.wandf35a762009-04-22 22:25:31 +0000589 ::std::cerr.flush();
590 // RUN_ALL_TESTS() has already returned when this destructor is
591 // called. Therefore we cannot use the normal Google Test
592 // failure reporting mechanism.
593 _exit(1); // We cannot call exit() as it is not reentrant and
594 // may already have been called.
595 }
596 }
597
598 StateMap& states() { return states_; }
jgm79a367e2012-04-10 16:02:11 +0000599
zhanyong.wandf35a762009-04-22 22:25:31 +0000600 private:
601 StateMap states_;
602};
603
604// Protected by g_gmock_mutex.
shiqiane35fdd92008-12-10 05:08:54 +0000605MockObjectRegistry g_mock_object_registry;
606
607// Maps a mock object to the reaction Google Mock should have when an
608// uninteresting method is called. Protected by g_gmock_mutex.
609std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
610
611// Sets the reaction Google Mock should have when an uninteresting
612// method of the given mock object is called.
shiqiane35fdd92008-12-10 05:08:54 +0000613void SetReactionOnUninterestingCalls(const void* mock_obj,
vladlosev4d60a592011-10-24 21:16:22 +0000614 internal::CallReaction reaction)
615 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000616 internal::MutexLock l(&internal::g_gmock_mutex);
617 g_uninteresting_call_reaction[mock_obj] = reaction;
618}
619
620} // namespace
621
622// Tells Google Mock to allow uninteresting calls on the given mock
623// object.
vladlosev4d60a592011-10-24 21:16:22 +0000624void Mock::AllowUninterestingCalls(const void* mock_obj)
625 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000626 SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
shiqiane35fdd92008-12-10 05:08:54 +0000627}
628
629// Tells Google Mock to warn the user about uninteresting calls on the
630// given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000631void Mock::WarnUninterestingCalls(const void* mock_obj)
632 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000633 SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
shiqiane35fdd92008-12-10 05:08:54 +0000634}
635
636// Tells Google Mock to fail uninteresting calls on the given mock
637// object.
vladlosev4d60a592011-10-24 21:16:22 +0000638void Mock::FailUninterestingCalls(const void* mock_obj)
639 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000640 SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
shiqiane35fdd92008-12-10 05:08:54 +0000641}
642
643// Tells Google Mock the given mock object is being destroyed and its
644// entry in the call-reaction table should be removed.
vladlosev4d60a592011-10-24 21:16:22 +0000645void Mock::UnregisterCallReaction(const void* mock_obj)
646 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000647 internal::MutexLock l(&internal::g_gmock_mutex);
648 g_uninteresting_call_reaction.erase(mock_obj);
649}
650
651// Returns the reaction Google Mock will have on uninteresting calls
652// made on the given mock object.
shiqiane35fdd92008-12-10 05:08:54 +0000653internal::CallReaction Mock::GetReactionOnUninterestingCalls(
vladlosev4d60a592011-10-24 21:16:22 +0000654 const void* mock_obj)
655 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000656 internal::MutexLock l(&internal::g_gmock_mutex);
657 return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
Alyssa Wilka2803bc2017-08-16 12:43:26 -0400658 internal::intToCallReaction(GMOCK_FLAG(default_mock_behavior)) :
Alyssa Wilk6e1970e2017-08-10 09:41:09 -0400659 g_uninteresting_call_reaction[mock_obj];
shiqiane35fdd92008-12-10 05:08:54 +0000660}
661
zhanyong.wandf35a762009-04-22 22:25:31 +0000662// Tells Google Mock to ignore mock_obj when checking for leaked mock
663// objects.
vladlosev4d60a592011-10-24 21:16:22 +0000664void Mock::AllowLeak(const void* mock_obj)
665 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +0000666 internal::MutexLock l(&internal::g_gmock_mutex);
667 g_mock_object_registry.states()[mock_obj].leakable = true;
668}
669
shiqiane35fdd92008-12-10 05:08:54 +0000670// Verifies and clears all expectations on the given mock object. If
671// the expectations aren't satisfied, generates one or more Google
672// Test non-fatal failures and returns false.
vladlosev4d60a592011-10-24 21:16:22 +0000673bool Mock::VerifyAndClearExpectations(void* mock_obj)
674 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000675 internal::MutexLock l(&internal::g_gmock_mutex);
676 return VerifyAndClearExpectationsLocked(mock_obj);
677}
678
679// Verifies all expectations on the given mock object and clears its
680// default actions and expectations. Returns true iff the
681// verification was successful.
vladlosev4d60a592011-10-24 21:16:22 +0000682bool Mock::VerifyAndClear(void* mock_obj)
683 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000684 internal::MutexLock l(&internal::g_gmock_mutex);
685 ClearDefaultActionsLocked(mock_obj);
686 return VerifyAndClearExpectationsLocked(mock_obj);
687}
688
689// Verifies and clears all expectations on the given mock object. If
690// the expectations aren't satisfied, generates one or more Google
691// Test non-fatal failures and returns false.
vladlosev4d60a592011-10-24 21:16:22 +0000692bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
693 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000694 internal::g_gmock_mutex.AssertHeld();
zhanyong.wandf35a762009-04-22 22:25:31 +0000695 if (g_mock_object_registry.states().count(mock_obj) == 0) {
shiqiane35fdd92008-12-10 05:08:54 +0000696 // No EXPECT_CALL() was set on the given mock object.
697 return true;
698 }
699
700 // Verifies and clears the expectations on each mock method in the
701 // given mock object.
702 bool expectations_met = true;
zhanyong.wandf35a762009-04-22 22:25:31 +0000703 FunctionMockers& mockers =
704 g_mock_object_registry.states()[mock_obj].function_mockers;
shiqiane35fdd92008-12-10 05:08:54 +0000705 for (FunctionMockers::const_iterator it = mockers.begin();
706 it != mockers.end(); ++it) {
707 if (!(*it)->VerifyAndClearExpectationsLocked()) {
708 expectations_met = false;
709 }
710 }
711
712 // We don't clear the content of mockers, as they may still be
713 // needed by ClearDefaultActionsLocked().
714 return expectations_met;
715}
716
717// Registers a mock object and a mock method it owns.
shiqiane35fdd92008-12-10 05:08:54 +0000718void Mock::Register(const void* mock_obj,
vladlosev4d60a592011-10-24 21:16:22 +0000719 internal::UntypedFunctionMockerBase* mocker)
720 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000721 internal::MutexLock l(&internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000722 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
723}
724
725// Tells Google Mock where in the source code mock_obj is used in an
726// ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
727// information helps the user identify which object it is.
vladlosev4d60a592011-10-24 21:16:22 +0000728void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
729 const char* file, int line)
730 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +0000731 internal::MutexLock l(&internal::g_gmock_mutex);
732 MockObjectState& state = g_mock_object_registry.states()[mock_obj];
733 if (state.first_used_file == NULL) {
734 state.first_used_file = file;
735 state.first_used_line = line;
zhanyong.wane7bb5ed2009-05-05 23:14:47 +0000736 const TestInfo* const test_info =
737 UnitTest::GetInstance()->current_test_info();
738 if (test_info != NULL) {
739 // TODO(wan@google.com): record the test case name when the
740 // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or
741 // TearDownTestCase().
742 state.first_used_test_case = test_info->test_case_name();
743 state.first_used_test = test_info->name();
744 }
zhanyong.wandf35a762009-04-22 22:25:31 +0000745 }
shiqiane35fdd92008-12-10 05:08:54 +0000746}
747
748// Unregisters a mock method; removes the owning mock object from the
749// registry when the last mock method associated with it has been
750// unregistered. This is called only in the destructor of
751// FunctionMockerBase.
vladlosev4d60a592011-10-24 21:16:22 +0000752void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
753 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000754 internal::g_gmock_mutex.AssertHeld();
zhanyong.wandf35a762009-04-22 22:25:31 +0000755 for (MockObjectRegistry::StateMap::iterator it =
756 g_mock_object_registry.states().begin();
757 it != g_mock_object_registry.states().end(); ++it) {
758 FunctionMockers& mockers = it->second.function_mockers;
shiqiane35fdd92008-12-10 05:08:54 +0000759 if (mockers.erase(mocker) > 0) {
760 // mocker was in mockers and has been just removed.
761 if (mockers.empty()) {
zhanyong.wandf35a762009-04-22 22:25:31 +0000762 g_mock_object_registry.states().erase(it);
shiqiane35fdd92008-12-10 05:08:54 +0000763 }
764 return;
765 }
766 }
767}
768
769// Clears all ON_CALL()s set on the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000770void Mock::ClearDefaultActionsLocked(void* mock_obj)
771 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000772 internal::g_gmock_mutex.AssertHeld();
773
zhanyong.wandf35a762009-04-22 22:25:31 +0000774 if (g_mock_object_registry.states().count(mock_obj) == 0) {
shiqiane35fdd92008-12-10 05:08:54 +0000775 // No ON_CALL() was set on the given mock object.
776 return;
777 }
778
779 // Clears the default actions for each mock method in the given mock
780 // object.
zhanyong.wandf35a762009-04-22 22:25:31 +0000781 FunctionMockers& mockers =
782 g_mock_object_registry.states()[mock_obj].function_mockers;
shiqiane35fdd92008-12-10 05:08:54 +0000783 for (FunctionMockers::const_iterator it = mockers.begin();
784 it != mockers.end(); ++it) {
785 (*it)->ClearDefaultActionsLocked();
786 }
787
788 // We don't clear the content of mockers, as they may still be
789 // needed by VerifyAndClearExpectationsLocked().
790}
791
zhanyong.wan7c95d832009-10-01 21:56:16 +0000792Expectation::Expectation() {}
793
794Expectation::Expectation(
zhanyong.wan32de5f52009-12-23 00:13:23 +0000795 const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base)
796 : expectation_base_(an_expectation_base) {}
zhanyong.wan7c95d832009-10-01 21:56:16 +0000797
798Expectation::~Expectation() {}
799
shiqiane35fdd92008-12-10 05:08:54 +0000800// Adds an expectation to a sequence.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000801void Sequence::AddExpectation(const Expectation& expectation) const {
shiqiane35fdd92008-12-10 05:08:54 +0000802 if (*last_expectation_ != expectation) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000803 if (last_expectation_->expectation_base() != NULL) {
804 expectation.expectation_base()->immediate_prerequisites_
805 += *last_expectation_;
shiqiane35fdd92008-12-10 05:08:54 +0000806 }
807 *last_expectation_ = expectation;
808 }
809}
810
811// Creates the implicit sequence if there isn't one.
812InSequence::InSequence() {
813 if (internal::g_gmock_implicit_sequence.get() == NULL) {
814 internal::g_gmock_implicit_sequence.set(new Sequence);
815 sequence_created_ = true;
816 } else {
817 sequence_created_ = false;
818 }
819}
820
821// Deletes the implicit sequence if it was created by the constructor
822// of this object.
823InSequence::~InSequence() {
824 if (sequence_created_) {
825 delete internal::g_gmock_implicit_sequence.get();
826 internal::g_gmock_implicit_sequence.set(NULL);
827 }
828}
829
830} // namespace testing