blob: b97bad030bba9d4ac11b3be5f5346fca3e3fe001 [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>
Gennadiy Civilfe402c22018-04-05 16:09:17 -040044#include <vector>
zhanyong.wan53e08c42010-09-14 05:38:21 +000045#include "gmock/gmock.h"
46#include "gtest/gtest.h"
shiqiane35fdd92008-12-10 05:08:54 +000047
zhanyong.wandf35a762009-04-22 22:25:31 +000048#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
zhanyong.wan658ac0b2011-02-24 07:29:13 +000049# include <unistd.h> // NOLINT
zhanyong.wandf35a762009-04-22 22:25:31 +000050#endif
51
shiqiane35fdd92008-12-10 05:08:54 +000052namespace testing {
53namespace internal {
54
55// Protects the mock object registry (in class Mock), all function
56// mockers, and all expectations.
vladlosev587c1b32011-05-20 00:42:22 +000057GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +000058
zhanyong.waned6c9272011-02-23 19:39:27 +000059// Logs a message including file and line number information.
vladlosev587c1b32011-05-20 00:42:22 +000060GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
61 const char* file, int line,
Nico Weber09fd5b32017-05-15 17:07:03 -040062 const std::string& message) {
zhanyong.waned6c9272011-02-23 19:39:27 +000063 ::std::ostringstream s;
64 s << file << ":" << line << ": " << message << ::std::endl;
65 Log(severity, s.str(), 0);
66}
67
shiqiane35fdd92008-12-10 05:08:54 +000068// Constructs an ExpectationBase object.
Nico Weber09fd5b32017-05-15 17:07:03 -040069ExpectationBase::ExpectationBase(const char* a_file, int a_line,
70 const std::string& a_source_text)
zhanyong.wan32de5f52009-12-23 00:13:23 +000071 : 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
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400103 ::std::vector<ExpectationBase*> expectations(1, this);
104 while (!expectations.empty()) {
105 ExpectationBase* exp = expectations.back();
106 expectations.pop_back();
107
108 for (ExpectationSet::const_iterator it =
109 exp->immediate_prerequisites_.begin();
110 it != exp->immediate_prerequisites_.end(); ++it) {
111 ExpectationBase* next = it->expectation_base().get();
112 if (!next->is_retired()) {
113 next->Retire();
114 expectations.push_back(next);
115 }
shiqiane35fdd92008-12-10 05:08:54 +0000116 }
117 }
118}
119
120// Returns true iff all pre-requisites of this expectation have been
121// satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000122bool ExpectationBase::AllPrerequisitesAreSatisfied() const
123 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000124 g_gmock_mutex.AssertHeld();
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400125 ::std::vector<const ExpectationBase*> expectations(1, this);
126 while (!expectations.empty()) {
127 const ExpectationBase* exp = expectations.back();
128 expectations.pop_back();
129
130 for (ExpectationSet::const_iterator it =
131 exp->immediate_prerequisites_.begin();
132 it != exp->immediate_prerequisites_.end(); ++it) {
133 const ExpectationBase* next = it->expectation_base().get();
134 if (!next->IsSatisfied()) return false;
135 expectations.push_back(next);
136 }
shiqiane35fdd92008-12-10 05:08:54 +0000137 }
138 return true;
139}
140
141// Adds unsatisfied pre-requisites of this expectation to 'result'.
vladlosev4d60a592011-10-24 21:16:22 +0000142void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const
143 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000144 g_gmock_mutex.AssertHeld();
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400145 ::std::vector<const ExpectationBase*> expectations(1, this);
146 while (!expectations.empty()) {
147 const ExpectationBase* exp = expectations.back();
148 expectations.pop_back();
149
150 for (ExpectationSet::const_iterator it =
151 exp->immediate_prerequisites_.begin();
152 it != exp->immediate_prerequisites_.end(); ++it) {
153 const ExpectationBase* next = it->expectation_base().get();
154
155 if (next->IsSatisfied()) {
156 // If *it is satisfied and has a call count of 0, some of its
157 // pre-requisites may not be satisfied yet.
158 if (next->call_count_ == 0) {
159 expectations.push_back(next);
160 }
161 } else {
162 // Now that we know next is unsatisfied, we are not so interested
163 // in whether its pre-requisites are satisfied. Therefore we
164 // don't iterate into it here.
165 *result += *it;
shiqiane35fdd92008-12-10 05:08:54 +0000166 }
shiqiane35fdd92008-12-10 05:08:54 +0000167 }
168 }
169}
170
zhanyong.waned6c9272011-02-23 19:39:27 +0000171// Describes how many times a function call matching this
172// expectation has occurred.
vladlosev4d60a592011-10-24 21:16:22 +0000173void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
174 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000175 g_gmock_mutex.AssertHeld();
176
177 // Describes how many times the function is expected to be called.
178 *os << " Expected: to be ";
179 cardinality().DescribeTo(os);
180 *os << "\n Actual: ";
181 Cardinality::DescribeActualCallCountTo(call_count(), os);
182
183 // Describes the state of the expectation (e.g. is it satisfied?
184 // is it active?).
185 *os << " - " << (IsOverSaturated() ? "over-saturated" :
186 IsSaturated() ? "saturated" :
187 IsSatisfied() ? "satisfied" : "unsatisfied")
188 << " and "
189 << (is_retired() ? "retired" : "active");
190}
191
192// Checks the action count (i.e. the number of WillOnce() and
193// WillRepeatedly() clauses) against the cardinality if this hasn't
194// been done before. Prints a warning if there are too many or too
195// few actions.
vladlosev4d60a592011-10-24 21:16:22 +0000196void ExpectationBase::CheckActionCountIfNotDone() const
197 GTEST_LOCK_EXCLUDED_(mutex_) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000198 bool should_check = false;
199 {
200 MutexLock l(&mutex_);
201 if (!action_count_checked_) {
202 action_count_checked_ = true;
203 should_check = true;
204 }
205 }
206
207 if (should_check) {
208 if (!cardinality_specified_) {
209 // The cardinality was inferred - no need to check the action
210 // count against it.
211 return;
212 }
213
214 // The cardinality was explicitly specified.
215 const int action_count = static_cast<int>(untyped_actions_.size());
216 const int upper_bound = cardinality().ConservativeUpperBound();
217 const int lower_bound = cardinality().ConservativeLowerBound();
218 bool too_many; // True if there are too many actions, or false
219 // if there are too few.
220 if (action_count > upper_bound ||
221 (action_count == upper_bound && repeated_action_specified_)) {
222 too_many = true;
223 } else if (0 < action_count && action_count < lower_bound &&
224 !repeated_action_specified_) {
225 too_many = false;
226 } else {
227 return;
228 }
229
230 ::std::stringstream ss;
231 DescribeLocationTo(&ss);
232 ss << "Too " << (too_many ? "many" : "few")
233 << " actions specified in " << source_text() << "...\n"
234 << "Expected to be ";
235 cardinality().DescribeTo(&ss);
236 ss << ", but has " << (too_many ? "" : "only ")
237 << action_count << " WillOnce()"
238 << (action_count == 1 ? "" : "s");
239 if (repeated_action_specified_) {
240 ss << " and a WillRepeatedly()";
241 }
242 ss << ".";
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000243 Log(kWarning, ss.str(), -1); // -1 means "don't print stack trace".
zhanyong.waned6c9272011-02-23 19:39:27 +0000244 }
245}
246
247// Implements the .Times() clause.
248void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
249 if (last_clause_ == kTimes) {
250 ExpectSpecProperty(false,
251 ".Times() cannot appear "
252 "more than once in an EXPECT_CALL().");
253 } else {
254 ExpectSpecProperty(last_clause_ < kTimes,
255 ".Times() cannot appear after "
256 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
257 "or .RetiresOnSaturation().");
258 }
259 last_clause_ = kTimes;
260
261 SpecifyCardinality(a_cardinality);
262}
263
shiqiane35fdd92008-12-10 05:08:54 +0000264// Points to the implicit sequence introduced by a living InSequence
265// object (if any) in the current thread or NULL.
vladlosev587c1b32011-05-20 00:42:22 +0000266GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
shiqiane35fdd92008-12-10 05:08:54 +0000267
268// Reports an uninteresting call (whose description is in msg) in the
269// manner specified by 'reaction'.
Nico Weber09fd5b32017-05-15 17:07:03 -0400270void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
kosak5625dd32015-02-14 22:05:58 +0000271 // Include a stack trace only if --gmock_verbose=info is specified.
272 const int stack_frames_to_skip =
273 GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1;
shiqiane35fdd92008-12-10 05:08:54 +0000274 switch (reaction) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000275 case kAllow:
kosak5625dd32015-02-14 22:05:58 +0000276 Log(kInfo, msg, stack_frames_to_skip);
shiqiane35fdd92008-12-10 05:08:54 +0000277 break;
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000278 case kWarn:
kosak04ce8522014-01-12 23:42:34 +0000279 Log(kWarning,
280 msg +
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400281 "\nNOTE: You can safely ignore the above warning unless this "
282 "call should not happen. Do not suppress it by blindly adding "
283 "an EXPECT_CALL() if you don't mean to enforce the call. "
284 "See "
285 "https://github.com/google/googletest/blob/master/googlemock/"
286 "docs/CookBook.md#"
287 "knowing-when-to-expect for details.\n",
kosak5625dd32015-02-14 22:05:58 +0000288 stack_frames_to_skip);
shiqiane35fdd92008-12-10 05:08:54 +0000289 break;
290 default: // FAIL
291 Expect(false, NULL, -1, msg);
292 }
293}
294
zhanyong.waned6c9272011-02-23 19:39:27 +0000295UntypedFunctionMockerBase::UntypedFunctionMockerBase()
296 : mock_obj_(NULL), name_("") {}
297
298UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
299
300// Sets the mock object this mock method belongs to, and registers
301// this information in the global mock registry. Will be called
302// whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
303// method.
vladlosev4d60a592011-10-24 21:16:22 +0000304void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
305 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000306 {
307 MutexLock l(&g_gmock_mutex);
308 mock_obj_ = mock_obj;
309 }
310 Mock::Register(mock_obj, this);
311}
312
313// Sets the mock object this mock method belongs to, and sets the name
314// of the mock function. Will be called upon each invocation of this
315// mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000316void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
317 const char* name)
318 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000319 // We protect name_ under g_gmock_mutex in case this mock function
320 // is called from two threads concurrently.
321 MutexLock l(&g_gmock_mutex);
322 mock_obj_ = mock_obj;
323 name_ = name;
324}
325
326// Returns the name of the function being mocked. Must be called
327// after RegisterOwner() or SetOwnerAndName() has been called.
vladlosev4d60a592011-10-24 21:16:22 +0000328const void* UntypedFunctionMockerBase::MockObject() const
329 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000330 const void* mock_obj;
331 {
332 // We protect mock_obj_ under g_gmock_mutex in case this mock
333 // function is called from two threads concurrently.
334 MutexLock l(&g_gmock_mutex);
335 Assert(mock_obj_ != NULL, __FILE__, __LINE__,
336 "MockObject() must not be called before RegisterOwner() or "
337 "SetOwnerAndName() has been called.");
338 mock_obj = mock_obj_;
339 }
340 return mock_obj;
341}
342
343// Returns the name of this mock method. Must be called after
344// SetOwnerAndName() has been called.
vladlosev4d60a592011-10-24 21:16:22 +0000345const char* UntypedFunctionMockerBase::Name() const
346 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000347 const char* name;
348 {
349 // We protect name_ under g_gmock_mutex in case this mock
350 // function is called from two threads concurrently.
351 MutexLock l(&g_gmock_mutex);
352 Assert(name_ != NULL, __FILE__, __LINE__,
353 "Name() must not be called before SetOwnerAndName() has "
354 "been called.");
355 name = name_;
356 }
357 return name;
358}
359
360// Calculates the result of invoking this mock function with the given
361// arguments, prints it, and returns it. The caller is responsible
362// for deleting the result.
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400363UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
364 void* const untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
365 // See the definition of untyped_expectations_ for why access to it
366 // is unprotected here.
zhanyong.waned6c9272011-02-23 19:39:27 +0000367 if (untyped_expectations_.size() == 0) {
368 // No expectation is set on this mock method - we have an
369 // uninteresting call.
370
371 // We must get Google Mock's reaction on uninteresting calls
372 // made on this mock object BEFORE performing the action,
373 // because the action may DELETE the mock object and make the
374 // following expression meaningless.
375 const CallReaction reaction =
376 Mock::GetReactionOnUninterestingCalls(MockObject());
377
378 // True iff we need to print this call's arguments and return
379 // value. This definition must be kept in sync with
380 // the behavior of ReportUninterestingCall().
381 const bool need_to_report_uninteresting_call =
382 // If the user allows this uninteresting call, we print it
Jonathan Wakelyb70cf1a2017-09-27 13:31:13 +0100383 // only when they want informational messages.
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000384 reaction == kAllow ? LogIsVisible(kInfo) :
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400385 // If the user wants this to be a warning, we print
386 // it only when they want to see warnings.
387 reaction == kWarn
388 ? LogIsVisible(kWarning)
389 :
390 // Otherwise, the user wants this to be an error, and we
391 // should always print detailed information in the error.
392 true;
zhanyong.waned6c9272011-02-23 19:39:27 +0000393
394 if (!need_to_report_uninteresting_call) {
395 // Perform the action without printing the call information.
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400396 return this->UntypedPerformDefaultAction(
397 untyped_args, "Function call: " + std::string(Name()));
zhanyong.waned6c9272011-02-23 19:39:27 +0000398 }
399
400 // Warns about the uninteresting call.
401 ::std::stringstream ss;
402 this->UntypedDescribeUninterestingCall(untyped_args, &ss);
403
404 // Calculates the function result.
kosakb5c81092014-01-29 06:41:44 +0000405 UntypedActionResultHolderBase* const result =
zhanyong.waned6c9272011-02-23 19:39:27 +0000406 this->UntypedPerformDefaultAction(untyped_args, ss.str());
407
408 // Prints the function result.
409 if (result != NULL)
410 result->PrintAsActionResult(&ss);
411
412 ReportUninterestingCall(reaction, ss.str());
413 return result;
414 }
415
416 bool is_excessive = false;
417 ::std::stringstream ss;
418 ::std::stringstream why;
419 ::std::stringstream loc;
420 const void* untyped_action = NULL;
421
422 // The UntypedFindMatchingExpectation() function acquires and
423 // releases g_gmock_mutex.
424 const ExpectationBase* const untyped_expectation =
425 this->UntypedFindMatchingExpectation(
426 untyped_args, &untyped_action, &is_excessive,
427 &ss, &why);
428 const bool found = untyped_expectation != NULL;
429
430 // True iff we need to print the call's arguments and return value.
431 // This definition must be kept in sync with the uses of Expect()
432 // and Log() in this function.
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000433 const bool need_to_report_call =
434 !found || is_excessive || LogIsVisible(kInfo);
zhanyong.waned6c9272011-02-23 19:39:27 +0000435 if (!need_to_report_call) {
436 // Perform the action without printing the call information.
437 return
438 untyped_action == NULL ?
439 this->UntypedPerformDefaultAction(untyped_args, "") :
440 this->UntypedPerformAction(untyped_action, untyped_args);
441 }
442
443 ss << " Function call: " << Name();
444 this->UntypedPrintArgs(untyped_args, &ss);
445
446 // In case the action deletes a piece of the expectation, we
447 // generate the message beforehand.
448 if (found && !is_excessive) {
449 untyped_expectation->DescribeLocationTo(&loc);
450 }
451
kosakb5c81092014-01-29 06:41:44 +0000452 UntypedActionResultHolderBase* const result =
zhanyong.waned6c9272011-02-23 19:39:27 +0000453 untyped_action == NULL ?
454 this->UntypedPerformDefaultAction(untyped_args, ss.str()) :
455 this->UntypedPerformAction(untyped_action, untyped_args);
456 if (result != NULL)
457 result->PrintAsActionResult(&ss);
458 ss << "\n" << why.str();
459
460 if (!found) {
461 // No expectation matches this call - reports a failure.
462 Expect(false, NULL, -1, ss.str());
463 } else if (is_excessive) {
464 // We had an upper-bound violation and the failure message is in ss.
465 Expect(false, untyped_expectation->file(),
466 untyped_expectation->line(), ss.str());
467 } else {
468 // We had an expected call and the matching expectation is
469 // described in ss.
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000470 Log(kInfo, loc.str() + ss.str(), 2);
zhanyong.waned6c9272011-02-23 19:39:27 +0000471 }
472
473 return result;
474}
475
476// Returns an Expectation object that references and co-owns exp,
477// which must be an expectation on this mock function.
478Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400479 // See the definition of untyped_expectations_ for why access to it
480 // is unprotected here.
zhanyong.waned6c9272011-02-23 19:39:27 +0000481 for (UntypedExpectations::const_iterator it =
482 untyped_expectations_.begin();
483 it != untyped_expectations_.end(); ++it) {
484 if (it->get() == exp) {
485 return Expectation(*it);
486 }
487 }
488
489 Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
490 return Expectation();
491 // The above statement is just to make the code compile, and will
492 // never be executed.
493}
494
495// Verifies that all expectations on this mock function have been
496// satisfied. Reports one or more Google Test non-fatal failures
497// and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000498bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
499 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000500 g_gmock_mutex.AssertHeld();
501 bool expectations_met = true;
502 for (UntypedExpectations::const_iterator it =
503 untyped_expectations_.begin();
504 it != untyped_expectations_.end(); ++it) {
505 ExpectationBase* const untyped_expectation = it->get();
506 if (untyped_expectation->IsOverSaturated()) {
507 // There was an upper-bound violation. Since the error was
508 // already reported when it occurred, there is no need to do
509 // anything here.
510 expectations_met = false;
511 } else if (!untyped_expectation->IsSatisfied()) {
512 expectations_met = false;
513 ::std::stringstream ss;
514 ss << "Actual function call count doesn't match "
515 << untyped_expectation->source_text() << "...\n";
516 // No need to show the source file location of the expectation
517 // in the description, as the Expect() call that follows already
518 // takes care of it.
519 untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
520 untyped_expectation->DescribeCallCountTo(&ss);
521 Expect(false, untyped_expectation->file(),
522 untyped_expectation->line(), ss.str());
523 }
524 }
vladlosev9bcb5f92011-10-24 23:41:07 +0000525
526 // Deleting our expectations may trigger other mock objects to be deleted, for
527 // example if an action contains a reference counted smart pointer to that
528 // mock object, and that is the last reference. So if we delete our
529 // expectations within the context of the global mutex we may deadlock when
530 // this method is called again. Instead, make a copy of the set of
531 // expectations to delete, clear our set within the mutex, and then clear the
532 // copied set outside of it.
533 UntypedExpectations expectations_to_delete;
534 untyped_expectations_.swap(expectations_to_delete);
535
536 g_gmock_mutex.Unlock();
537 expectations_to_delete.clear();
538 g_gmock_mutex.Lock();
539
zhanyong.waned6c9272011-02-23 19:39:27 +0000540 return expectations_met;
541}
542
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400543CallReaction intToCallReaction(int mock_behavior) {
Alyssa Wilka2803bc2017-08-16 12:43:26 -0400544 if (mock_behavior >= kAllow && mock_behavior <= kFail) {
545 return static_cast<internal::CallReaction>(mock_behavior);
546 }
547 return kWarn;
548}
549
shiqiane35fdd92008-12-10 05:08:54 +0000550} // namespace internal
551
552// Class Mock.
553
554namespace {
555
556typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
shiqiane35fdd92008-12-10 05:08:54 +0000557
zhanyong.wandf35a762009-04-22 22:25:31 +0000558// The current state of a mock object. Such information is needed for
559// detecting leaked mock objects and explicitly verifying a mock's
560// expectations.
561struct MockObjectState {
562 MockObjectState()
563 : first_used_file(NULL), first_used_line(-1), leakable(false) {}
564
565 // Where in the source file an ON_CALL or EXPECT_CALL is first
566 // invoked on this mock object.
567 const char* first_used_file;
568 int first_used_line;
zhanyong.wane7bb5ed2009-05-05 23:14:47 +0000569 ::std::string first_used_test_case;
570 ::std::string first_used_test;
zhanyong.wandf35a762009-04-22 22:25:31 +0000571 bool leakable; // true iff it's OK to leak the object.
572 FunctionMockers function_mockers; // All registered methods of the object.
573};
574
575// A global registry holding the state of all mock objects that are
576// alive. A mock object is added to this registry the first time
577// Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It
578// is removed from the registry in the mock object's destructor.
579class MockObjectRegistry {
580 public:
581 // Maps a mock object (identified by its address) to its state.
582 typedef std::map<const void*, MockObjectState> StateMap;
583
584 // This destructor will be called when a program exits, after all
585 // tests in it have been run. By then, there should be no mock
586 // object alive. Therefore we report any living object as test
587 // failure, unless the user explicitly asked us to ignore it.
588 ~MockObjectRegistry() {
zhanyong.wan9571b282009-08-07 07:15:56 +0000589 // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is
590 // a macro.
zhanyong.wandf35a762009-04-22 22:25:31 +0000591
592 if (!GMOCK_FLAG(catch_leaked_mocks))
593 return;
594
595 int leaked_count = 0;
596 for (StateMap::const_iterator it = states_.begin(); it != states_.end();
597 ++it) {
598 if (it->second.leakable) // The user said it's fine to leak this object.
599 continue;
600
601 // TODO(wan@google.com): Print the type of the leaked object.
602 // This can help the user identify the leaked object.
zhanyong.wan9571b282009-08-07 07:15:56 +0000603 std::cout << "\n";
zhanyong.wandf35a762009-04-22 22:25:31 +0000604 const MockObjectState& state = it->second;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000605 std::cout << internal::FormatFileLocation(state.first_used_file,
606 state.first_used_line);
zhanyong.wan9571b282009-08-07 07:15:56 +0000607 std::cout << " ERROR: this mock object";
zhanyong.wane7bb5ed2009-05-05 23:14:47 +0000608 if (state.first_used_test != "") {
zhanyong.wan9571b282009-08-07 07:15:56 +0000609 std::cout << " (used in test " << state.first_used_test_case << "."
zhanyong.wane7bb5ed2009-05-05 23:14:47 +0000610 << state.first_used_test << ")";
611 }
zhanyong.wan9571b282009-08-07 07:15:56 +0000612 std::cout << " should be deleted but never is. Its address is @"
zhanyong.wane7bb5ed2009-05-05 23:14:47 +0000613 << it->first << ".";
zhanyong.wandf35a762009-04-22 22:25:31 +0000614 leaked_count++;
615 }
616 if (leaked_count > 0) {
Gennadiy Civilfe402c22018-04-05 16:09:17 -0400617 std::cout << "\nERROR: " << leaked_count << " leaked mock "
618 << (leaked_count == 1 ? "object" : "objects")
619 << " found at program exit. Expectations on a mock object is "
620 "verified when the object is destructed. Leaking a mock "
621 "means that its expectations aren't verified, which is "
622 "usually a test bug. If you really intend to leak a mock, "
623 "you can suppress this error using "
624 "testing::Mock::AllowLeak(mock_object), or you may use a "
625 "fake or stub instead of a mock.\n";
zhanyong.wan9571b282009-08-07 07:15:56 +0000626 std::cout.flush();
zhanyong.wandf35a762009-04-22 22:25:31 +0000627 ::std::cerr.flush();
628 // RUN_ALL_TESTS() has already returned when this destructor is
629 // called. Therefore we cannot use the normal Google Test
630 // failure reporting mechanism.
631 _exit(1); // We cannot call exit() as it is not reentrant and
632 // may already have been called.
633 }
634 }
635
636 StateMap& states() { return states_; }
jgm79a367e2012-04-10 16:02:11 +0000637
zhanyong.wandf35a762009-04-22 22:25:31 +0000638 private:
639 StateMap states_;
640};
641
642// Protected by g_gmock_mutex.
shiqiane35fdd92008-12-10 05:08:54 +0000643MockObjectRegistry g_mock_object_registry;
644
645// Maps a mock object to the reaction Google Mock should have when an
646// uninteresting method is called. Protected by g_gmock_mutex.
647std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
648
649// Sets the reaction Google Mock should have when an uninteresting
650// method of the given mock object is called.
shiqiane35fdd92008-12-10 05:08:54 +0000651void SetReactionOnUninterestingCalls(const void* mock_obj,
vladlosev4d60a592011-10-24 21:16:22 +0000652 internal::CallReaction reaction)
653 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000654 internal::MutexLock l(&internal::g_gmock_mutex);
655 g_uninteresting_call_reaction[mock_obj] = reaction;
656}
657
658} // namespace
659
660// Tells Google Mock to allow uninteresting calls on the given mock
661// object.
vladlosev4d60a592011-10-24 21:16:22 +0000662void Mock::AllowUninterestingCalls(const void* mock_obj)
663 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000664 SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
shiqiane35fdd92008-12-10 05:08:54 +0000665}
666
667// Tells Google Mock to warn the user about uninteresting calls on the
668// given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000669void Mock::WarnUninterestingCalls(const void* mock_obj)
670 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000671 SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
shiqiane35fdd92008-12-10 05:08:54 +0000672}
673
674// Tells Google Mock to fail uninteresting calls on the given mock
675// object.
vladlosev4d60a592011-10-24 21:16:22 +0000676void Mock::FailUninterestingCalls(const void* mock_obj)
677 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000678 SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
shiqiane35fdd92008-12-10 05:08:54 +0000679}
680
681// Tells Google Mock the given mock object is being destroyed and its
682// entry in the call-reaction table should be removed.
vladlosev4d60a592011-10-24 21:16:22 +0000683void Mock::UnregisterCallReaction(const void* mock_obj)
684 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000685 internal::MutexLock l(&internal::g_gmock_mutex);
686 g_uninteresting_call_reaction.erase(mock_obj);
687}
688
689// Returns the reaction Google Mock will have on uninteresting calls
690// made on the given mock object.
shiqiane35fdd92008-12-10 05:08:54 +0000691internal::CallReaction Mock::GetReactionOnUninterestingCalls(
vladlosev4d60a592011-10-24 21:16:22 +0000692 const void* mock_obj)
693 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000694 internal::MutexLock l(&internal::g_gmock_mutex);
695 return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
Alyssa Wilka2803bc2017-08-16 12:43:26 -0400696 internal::intToCallReaction(GMOCK_FLAG(default_mock_behavior)) :
Alyssa Wilk6e1970e2017-08-10 09:41:09 -0400697 g_uninteresting_call_reaction[mock_obj];
shiqiane35fdd92008-12-10 05:08:54 +0000698}
699
zhanyong.wandf35a762009-04-22 22:25:31 +0000700// Tells Google Mock to ignore mock_obj when checking for leaked mock
701// objects.
vladlosev4d60a592011-10-24 21:16:22 +0000702void Mock::AllowLeak(const void* mock_obj)
703 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +0000704 internal::MutexLock l(&internal::g_gmock_mutex);
705 g_mock_object_registry.states()[mock_obj].leakable = true;
706}
707
shiqiane35fdd92008-12-10 05:08:54 +0000708// Verifies and clears all expectations on the given mock object. If
709// the expectations aren't satisfied, generates one or more Google
710// Test non-fatal failures and returns false.
vladlosev4d60a592011-10-24 21:16:22 +0000711bool Mock::VerifyAndClearExpectations(void* mock_obj)
712 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000713 internal::MutexLock l(&internal::g_gmock_mutex);
714 return VerifyAndClearExpectationsLocked(mock_obj);
715}
716
717// Verifies all expectations on the given mock object and clears its
718// default actions and expectations. Returns true iff the
719// verification was successful.
vladlosev4d60a592011-10-24 21:16:22 +0000720bool Mock::VerifyAndClear(void* mock_obj)
721 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000722 internal::MutexLock l(&internal::g_gmock_mutex);
723 ClearDefaultActionsLocked(mock_obj);
724 return VerifyAndClearExpectationsLocked(mock_obj);
725}
726
727// Verifies and clears all expectations on the given mock object. If
728// the expectations aren't satisfied, generates one or more Google
729// Test non-fatal failures and returns false.
vladlosev4d60a592011-10-24 21:16:22 +0000730bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
731 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000732 internal::g_gmock_mutex.AssertHeld();
zhanyong.wandf35a762009-04-22 22:25:31 +0000733 if (g_mock_object_registry.states().count(mock_obj) == 0) {
shiqiane35fdd92008-12-10 05:08:54 +0000734 // No EXPECT_CALL() was set on the given mock object.
735 return true;
736 }
737
738 // Verifies and clears the expectations on each mock method in the
739 // given mock object.
740 bool expectations_met = true;
zhanyong.wandf35a762009-04-22 22:25:31 +0000741 FunctionMockers& mockers =
742 g_mock_object_registry.states()[mock_obj].function_mockers;
shiqiane35fdd92008-12-10 05:08:54 +0000743 for (FunctionMockers::const_iterator it = mockers.begin();
744 it != mockers.end(); ++it) {
745 if (!(*it)->VerifyAndClearExpectationsLocked()) {
746 expectations_met = false;
747 }
748 }
749
750 // We don't clear the content of mockers, as they may still be
751 // needed by ClearDefaultActionsLocked().
752 return expectations_met;
753}
754
755// Registers a mock object and a mock method it owns.
shiqiane35fdd92008-12-10 05:08:54 +0000756void Mock::Register(const void* mock_obj,
vladlosev4d60a592011-10-24 21:16:22 +0000757 internal::UntypedFunctionMockerBase* mocker)
758 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000759 internal::MutexLock l(&internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000760 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
761}
762
763// Tells Google Mock where in the source code mock_obj is used in an
764// ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
765// information helps the user identify which object it is.
vladlosev4d60a592011-10-24 21:16:22 +0000766void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
767 const char* file, int line)
768 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +0000769 internal::MutexLock l(&internal::g_gmock_mutex);
770 MockObjectState& state = g_mock_object_registry.states()[mock_obj];
771 if (state.first_used_file == NULL) {
772 state.first_used_file = file;
773 state.first_used_line = line;
zhanyong.wane7bb5ed2009-05-05 23:14:47 +0000774 const TestInfo* const test_info =
775 UnitTest::GetInstance()->current_test_info();
776 if (test_info != NULL) {
777 // TODO(wan@google.com): record the test case name when the
778 // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or
779 // TearDownTestCase().
780 state.first_used_test_case = test_info->test_case_name();
781 state.first_used_test = test_info->name();
782 }
zhanyong.wandf35a762009-04-22 22:25:31 +0000783 }
shiqiane35fdd92008-12-10 05:08:54 +0000784}
785
786// Unregisters a mock method; removes the owning mock object from the
787// registry when the last mock method associated with it has been
788// unregistered. This is called only in the destructor of
789// FunctionMockerBase.
vladlosev4d60a592011-10-24 21:16:22 +0000790void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
791 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000792 internal::g_gmock_mutex.AssertHeld();
zhanyong.wandf35a762009-04-22 22:25:31 +0000793 for (MockObjectRegistry::StateMap::iterator it =
794 g_mock_object_registry.states().begin();
795 it != g_mock_object_registry.states().end(); ++it) {
796 FunctionMockers& mockers = it->second.function_mockers;
shiqiane35fdd92008-12-10 05:08:54 +0000797 if (mockers.erase(mocker) > 0) {
798 // mocker was in mockers and has been just removed.
799 if (mockers.empty()) {
zhanyong.wandf35a762009-04-22 22:25:31 +0000800 g_mock_object_registry.states().erase(it);
shiqiane35fdd92008-12-10 05:08:54 +0000801 }
802 return;
803 }
804 }
805}
806
807// Clears all ON_CALL()s set on the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000808void Mock::ClearDefaultActionsLocked(void* mock_obj)
809 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000810 internal::g_gmock_mutex.AssertHeld();
811
zhanyong.wandf35a762009-04-22 22:25:31 +0000812 if (g_mock_object_registry.states().count(mock_obj) == 0) {
shiqiane35fdd92008-12-10 05:08:54 +0000813 // No ON_CALL() was set on the given mock object.
814 return;
815 }
816
817 // Clears the default actions for each mock method in the given mock
818 // object.
zhanyong.wandf35a762009-04-22 22:25:31 +0000819 FunctionMockers& mockers =
820 g_mock_object_registry.states()[mock_obj].function_mockers;
shiqiane35fdd92008-12-10 05:08:54 +0000821 for (FunctionMockers::const_iterator it = mockers.begin();
822 it != mockers.end(); ++it) {
823 (*it)->ClearDefaultActionsLocked();
824 }
825
826 // We don't clear the content of mockers, as they may still be
827 // needed by VerifyAndClearExpectationsLocked().
828}
829
zhanyong.wan7c95d832009-10-01 21:56:16 +0000830Expectation::Expectation() {}
831
832Expectation::Expectation(
zhanyong.wan32de5f52009-12-23 00:13:23 +0000833 const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base)
834 : expectation_base_(an_expectation_base) {}
zhanyong.wan7c95d832009-10-01 21:56:16 +0000835
836Expectation::~Expectation() {}
837
shiqiane35fdd92008-12-10 05:08:54 +0000838// Adds an expectation to a sequence.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000839void Sequence::AddExpectation(const Expectation& expectation) const {
shiqiane35fdd92008-12-10 05:08:54 +0000840 if (*last_expectation_ != expectation) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000841 if (last_expectation_->expectation_base() != NULL) {
842 expectation.expectation_base()->immediate_prerequisites_
843 += *last_expectation_;
shiqiane35fdd92008-12-10 05:08:54 +0000844 }
845 *last_expectation_ = expectation;
846 }
847}
848
849// Creates the implicit sequence if there isn't one.
850InSequence::InSequence() {
851 if (internal::g_gmock_implicit_sequence.get() == NULL) {
852 internal::g_gmock_implicit_sequence.set(new Sequence);
853 sequence_created_ = true;
854 } else {
855 sequence_created_ = false;
856 }
857}
858
859// Deletes the implicit sequence if it was created by the constructor
860// of this object.
861InSequence::~InSequence() {
862 if (sequence_created_) {
863 delete internal::g_gmock_implicit_sequence.get();
864 internal::g_gmock_implicit_sequence.set(NULL);
865 }
866}
867
868} // namespace testing