1 // 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
31 // Google Mock - a framework for writing C++ mock classes.
32 //
33 // This file implements the spec builder syntax (ON_CALL and
34 // EXPECT_CALL).
35
36 #include "gmock/gmock-spec-builders.h"
37
38 #include <stdlib.h>
39 #include <iostream> // NOLINT
40 #include <map>
41 #include <memory>
42 #include <set>
43 #include <string>
44 #include <vector>
45 #include "gmock/gmock.h"
46 #include "gtest/gtest.h"
47
48 #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
49 # include <unistd.h> // NOLINT
50 #endif
51
52 // Silence C4800 (C4800: 'int *const ': forcing value
53 // to bool 'true' or 'false') for MSVC 15
54 #ifdef _MSC_VER
55 #if _MSC_VER == 1900
56 # pragma warning(push)
57 # pragma warning(disable:4800)
58 #endif
59 #endif
60
61 namespace testing {
62 namespace internal {
63
64 // Protects the mock object registry (in class Mock), all function
65 // mockers, and all expectations.
66 GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
67
68 // Logs a message including file and line number information.
LogWithLocation(testing::internal::LogSeverity severity,const char * file,int line,const std::string & message)69 GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
70 const char* file, int line,
71 const std::string& message) {
72 ::std::ostringstream s;
73 s << file << ":" << line << ": " << message << ::std::endl;
74 Log(severity, s.str(), 0);
75 }
76
77 // Constructs an ExpectationBase object.
ExpectationBase(const char * a_file,int a_line,const std::string & a_source_text)78 ExpectationBase::ExpectationBase(const char* a_file, int a_line,
79 const std::string& a_source_text)
80 : file_(a_file),
81 line_(a_line),
82 source_text_(a_source_text),
83 cardinality_specified_(false),
84 cardinality_(Exactly(1)),
85 call_count_(0),
86 retired_(false),
87 extra_matcher_specified_(false),
88 repeated_action_specified_(false),
89 retires_on_saturation_(false),
90 last_clause_(kNone),
91 action_count_checked_(false) {}
92
93 // Destructs an ExpectationBase object.
~ExpectationBase()94 ExpectationBase::~ExpectationBase() {}
95
96 // Explicitly specifies the cardinality of this expectation. Used by
97 // the subclasses to implement the .Times() clause.
SpecifyCardinality(const Cardinality & a_cardinality)98 void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {
99 cardinality_specified_ = true;
100 cardinality_ = a_cardinality;
101 }
102
103 // Retires all pre-requisites of this expectation.
RetireAllPreRequisites()104 void ExpectationBase::RetireAllPreRequisites()
105 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
106 if (is_retired()) {
107 // We can take this short-cut as we never retire an expectation
108 // until we have retired all its pre-requisites.
109 return;
110 }
111
112 ::std::vector<ExpectationBase*> expectations(1, this);
113 while (!expectations.empty()) {
114 ExpectationBase* exp = expectations.back();
115 expectations.pop_back();
116
117 for (ExpectationSet::const_iterator it =
118 exp->immediate_prerequisites_.begin();
119 it != exp->immediate_prerequisites_.end(); ++it) {
120 ExpectationBase* next = it->expectation_base().get();
121 if (!next->is_retired()) {
122 next->Retire();
123 expectations.push_back(next);
124 }
125 }
126 }
127 }
128
129 // Returns true iff all pre-requisites of this expectation have been
130 // satisfied.
AllPrerequisitesAreSatisfied() const131 bool ExpectationBase::AllPrerequisitesAreSatisfied() const
132 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
133 g_gmock_mutex.AssertHeld();
134 ::std::vector<const ExpectationBase*> expectations(1, this);
135 while (!expectations.empty()) {
136 const ExpectationBase* exp = expectations.back();
137 expectations.pop_back();
138
139 for (ExpectationSet::const_iterator it =
140 exp->immediate_prerequisites_.begin();
141 it != exp->immediate_prerequisites_.end(); ++it) {
142 const ExpectationBase* next = it->expectation_base().get();
143 if (!next->IsSatisfied()) return false;
144 expectations.push_back(next);
145 }
146 }
147 return true;
148 }
149
150 // Adds unsatisfied pre-requisites of this expectation to 'result'.
FindUnsatisfiedPrerequisites(ExpectationSet * result) const151 void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const
152 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
153 g_gmock_mutex.AssertHeld();
154 ::std::vector<const ExpectationBase*> expectations(1, this);
155 while (!expectations.empty()) {
156 const ExpectationBase* exp = expectations.back();
157 expectations.pop_back();
158
159 for (ExpectationSet::const_iterator it =
160 exp->immediate_prerequisites_.begin();
161 it != exp->immediate_prerequisites_.end(); ++it) {
162 const ExpectationBase* next = it->expectation_base().get();
163
164 if (next->IsSatisfied()) {
165 // If *it is satisfied and has a call count of 0, some of its
166 // pre-requisites may not be satisfied yet.
167 if (next->call_count_ == 0) {
168 expectations.push_back(next);
169 }
170 } else {
171 // Now that we know next is unsatisfied, we are not so interested
172 // in whether its pre-requisites are satisfied. Therefore we
173 // don't iterate into it here.
174 *result += *it;
175 }
176 }
177 }
178 }
179
180 // Describes how many times a function call matching this
181 // expectation has occurred.
DescribeCallCountTo(::std::ostream * os) const182 void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const
183 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
184 g_gmock_mutex.AssertHeld();
185
186 // Describes how many times the function is expected to be called.
187 *os << " Expected: to be ";
188 cardinality().DescribeTo(os);
189 *os << "\n Actual: ";
190 Cardinality::DescribeActualCallCountTo(call_count(), os);
191
192 // Describes the state of the expectation (e.g. is it satisfied?
193 // is it active?).
194 *os << " - " << (IsOverSaturated() ? "over-saturated" :
195 IsSaturated() ? "saturated" :
196 IsSatisfied() ? "satisfied" : "unsatisfied")
197 << " and "
198 << (is_retired() ? "retired" : "active");
199 }
200
201 // Checks the action count (i.e. the number of WillOnce() and
202 // WillRepeatedly() clauses) against the cardinality if this hasn't
203 // been done before. Prints a warning if there are too many or too
204 // few actions.
CheckActionCountIfNotDone() const205 void ExpectationBase::CheckActionCountIfNotDone() const
206 GTEST_LOCK_EXCLUDED_(mutex_) {
207 bool should_check = false;
208 {
209 MutexLock l(&mutex_);
210 if (!action_count_checked_) {
211 action_count_checked_ = true;
212 should_check = true;
213 }
214 }
215
216 if (should_check) {
217 if (!cardinality_specified_) {
218 // The cardinality was inferred - no need to check the action
219 // count against it.
220 return;
221 }
222
223 // The cardinality was explicitly specified.
224 const int action_count = static_cast<int>(untyped_actions_.size());
225 const int upper_bound = cardinality().ConservativeUpperBound();
226 const int lower_bound = cardinality().ConservativeLowerBound();
227 bool too_many; // True if there are too many actions, or false
228 // if there are too few.
229 if (action_count > upper_bound ||
230 (action_count == upper_bound && repeated_action_specified_)) {
231 too_many = true;
232 } else if (0 < action_count && action_count < lower_bound &&
233 !repeated_action_specified_) {
234 too_many = false;
235 } else {
236 return;
237 }
238
239 ::std::stringstream ss;
240 DescribeLocationTo(&ss);
241 ss << "Too " << (too_many ? "many" : "few")
242 << " actions specified in " << source_text() << "...\n"
243 << "Expected to be ";
244 cardinality().DescribeTo(&ss);
245 ss << ", but has " << (too_many ? "" : "only ")
246 << action_count << " WillOnce()"
247 << (action_count == 1 ? "" : "s");
248 if (repeated_action_specified_) {
249 ss << " and a WillRepeatedly()";
250 }
251 ss << ".";
252 Log(kWarning, ss.str(), -1); // -1 means "don't print stack trace".
253 }
254 }
255
256 // Implements the .Times() clause.
UntypedTimes(const Cardinality & a_cardinality)257 void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {
258 if (last_clause_ == kTimes) {
259 ExpectSpecProperty(false,
260 ".Times() cannot appear "
261 "more than once in an EXPECT_CALL().");
262 } else {
263 ExpectSpecProperty(last_clause_ < kTimes,
264 ".Times() cannot appear after "
265 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
266 "or .RetiresOnSaturation().");
267 }
268 last_clause_ = kTimes;
269
270 SpecifyCardinality(a_cardinality);
271 }
272
273 // Points to the implicit sequence introduced by a living InSequence
274 // object (if any) in the current thread or NULL.
275 GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;
276
277 // Reports an uninteresting call (whose description is in msg) in the
278 // manner specified by 'reaction'.
ReportUninterestingCall(CallReaction reaction,const std::string & msg)279 void ReportUninterestingCall(CallReaction reaction, const std::string& msg) {
280 // Include a stack trace only if --gmock_verbose=info is specified.
281 const int stack_frames_to_skip =
282 GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1;
283 switch (reaction) {
284 case kAllow:
285 Log(kInfo, msg, stack_frames_to_skip);
286 break;
287 case kWarn:
288 Log(kWarning,
289 msg +
290 "\nNOTE: You can safely ignore the above warning unless this "
291 "call should not happen. Do not suppress it by blindly adding "
292 "an EXPECT_CALL() if you don't mean to enforce the call. "
293 "See "
294 "https://github.com/google/googletest/blob/master/googlemock/"
295 "docs/CookBook.md#"
296 "knowing-when-to-expect for details.\n",
297 stack_frames_to_skip);
298 break;
299 default: // FAIL
300 Expect(false, nullptr, -1, msg);
301 }
302 }
303
UntypedFunctionMockerBase()304 UntypedFunctionMockerBase::UntypedFunctionMockerBase()
305 : mock_obj_(nullptr), name_("") {}
306
~UntypedFunctionMockerBase()307 UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
308
309 // Sets the mock object this mock method belongs to, and registers
310 // this information in the global mock registry. Will be called
311 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
312 // method.
RegisterOwner(const void * mock_obj)313 void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
314 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
315 {
316 MutexLock l(&g_gmock_mutex);
317 mock_obj_ = mock_obj;
318 }
319 Mock::Register(mock_obj, this);
320 }
321
322 // Sets the mock object this mock method belongs to, and sets the name
323 // of the mock function. Will be called upon each invocation of this
324 // mock function.
SetOwnerAndName(const void * mock_obj,const char * name)325 void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,
326 const char* name)
327 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
328 // We protect name_ under g_gmock_mutex in case this mock function
329 // is called from two threads concurrently.
330 MutexLock l(&g_gmock_mutex);
331 mock_obj_ = mock_obj;
332 name_ = name;
333 }
334
335 // Returns the name of the function being mocked. Must be called
336 // after RegisterOwner() or SetOwnerAndName() has been called.
MockObject() const337 const void* UntypedFunctionMockerBase::MockObject() const
338 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
339 const void* mock_obj;
340 {
341 // We protect mock_obj_ under g_gmock_mutex in case this mock
342 // function is called from two threads concurrently.
343 MutexLock l(&g_gmock_mutex);
344 Assert(mock_obj_ != nullptr, __FILE__, __LINE__,
345 "MockObject() must not be called before RegisterOwner() or "
346 "SetOwnerAndName() has been called.");
347 mock_obj = mock_obj_;
348 }
349 return mock_obj;
350 }
351
352 // Returns the name of this mock method. Must be called after
353 // SetOwnerAndName() has been called.
Name() const354 const char* UntypedFunctionMockerBase::Name() const
355 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
356 const char* name;
357 {
358 // We protect name_ under g_gmock_mutex in case this mock
359 // function is called from two threads concurrently.
360 MutexLock l(&g_gmock_mutex);
361 Assert(name_ != nullptr, __FILE__, __LINE__,
362 "Name() must not be called before SetOwnerAndName() has "
363 "been called.");
364 name = name_;
365 }
366 return name;
367 }
368
369 // Calculates the result of invoking this mock function with the given
370 // arguments, prints it, and returns it. The caller is responsible
371 // for deleting the result.
UntypedInvokeWith(void * const untyped_args)372 UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
373 void* const untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
374 // See the definition of untyped_expectations_ for why access to it
375 // is unprotected here.
376 if (untyped_expectations_.size() == 0) {
377 // No expectation is set on this mock method - we have an
378 // uninteresting call.
379
380 // We must get Google Mock's reaction on uninteresting calls
381 // made on this mock object BEFORE performing the action,
382 // because the action may DELETE the mock object and make the
383 // following expression meaningless.
384 const CallReaction reaction =
385 Mock::GetReactionOnUninterestingCalls(MockObject());
386
387 // True iff we need to print this call's arguments and return
388 // value. This definition must be kept in sync with
389 // the behavior of ReportUninterestingCall().
390 const bool need_to_report_uninteresting_call =
391 // If the user allows this uninteresting call, we print it
392 // only when they want informational messages.
393 reaction == kAllow ? LogIsVisible(kInfo) :
394 // If the user wants this to be a warning, we print
395 // it only when they want to see warnings.
396 reaction == kWarn
397 ? LogIsVisible(kWarning)
398 :
399 // Otherwise, the user wants this to be an error, and we
400 // should always print detailed information in the error.
401 true;
402
403 if (!need_to_report_uninteresting_call) {
404 // Perform the action without printing the call information.
405 return this->UntypedPerformDefaultAction(
406 untyped_args, "Function call: " + std::string(Name()));
407 }
408
409 // Warns about the uninteresting call.
410 ::std::stringstream ss;
411 this->UntypedDescribeUninterestingCall(untyped_args, &ss);
412
413 // Calculates the function result.
414 UntypedActionResultHolderBase* const result =
415 this->UntypedPerformDefaultAction(untyped_args, ss.str());
416
417 // Prints the function result.
418 if (result != nullptr) result->PrintAsActionResult(&ss);
419
420 ReportUninterestingCall(reaction, ss.str());
421 return result;
422 }
423
424 bool is_excessive = false;
425 ::std::stringstream ss;
426 ::std::stringstream why;
427 ::std::stringstream loc;
428 const void* untyped_action = nullptr;
429
430 // The UntypedFindMatchingExpectation() function acquires and
431 // releases g_gmock_mutex.
432 const ExpectationBase* const untyped_expectation =
433 this->UntypedFindMatchingExpectation(
434 untyped_args, &untyped_action, &is_excessive,
435 &ss, &why);
436 const bool found = untyped_expectation != nullptr;
437
438 // True iff we need to print the call's arguments and return value.
439 // This definition must be kept in sync with the uses of Expect()
440 // and Log() in this function.
441 const bool need_to_report_call =
442 !found || is_excessive || LogIsVisible(kInfo);
443 if (!need_to_report_call) {
444 // Perform the action without printing the call information.
445 return untyped_action == nullptr
446 ? this->UntypedPerformDefaultAction(untyped_args, "")
447 : this->UntypedPerformAction(untyped_action, untyped_args);
448 }
449
450 ss << " Function call: " << Name();
451 this->UntypedPrintArgs(untyped_args, &ss);
452
453 // In case the action deletes a piece of the expectation, we
454 // generate the message beforehand.
455 if (found && !is_excessive) {
456 untyped_expectation->DescribeLocationTo(&loc);
457 }
458
459 UntypedActionResultHolderBase* const result =
460 untyped_action == nullptr
461 ? this->UntypedPerformDefaultAction(untyped_args, ss.str())
462 : this->UntypedPerformAction(untyped_action, untyped_args);
463 if (result != nullptr) result->PrintAsActionResult(&ss);
464 ss << "\n" << why.str();
465
466 if (!found) {
467 // No expectation matches this call - reports a failure.
468 Expect(false, nullptr, -1, ss.str());
469 } else if (is_excessive) {
470 // We had an upper-bound violation and the failure message is in ss.
471 Expect(false, untyped_expectation->file(),
472 untyped_expectation->line(), ss.str());
473 } else {
474 // We had an expected call and the matching expectation is
475 // described in ss.
476 Log(kInfo, loc.str() + ss.str(), 2);
477 }
478
479 return result;
480 }
481
482 // Returns an Expectation object that references and co-owns exp,
483 // which must be an expectation on this mock function.
GetHandleOf(ExpectationBase * exp)484 Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
485 // See the definition of untyped_expectations_ for why access to it
486 // is unprotected here.
487 for (UntypedExpectations::const_iterator it =
488 untyped_expectations_.begin();
489 it != untyped_expectations_.end(); ++it) {
490 if (it->get() == exp) {
491 return Expectation(*it);
492 }
493 }
494
495 Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
496 return Expectation();
497 // The above statement is just to make the code compile, and will
498 // never be executed.
499 }
500
501 // Verifies that all expectations on this mock function have been
502 // satisfied. Reports one or more Google Test non-fatal failures
503 // and returns false if not.
VerifyAndClearExpectationsLocked()504 bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
505 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
506 g_gmock_mutex.AssertHeld();
507 bool expectations_met = true;
508 for (UntypedExpectations::const_iterator it =
509 untyped_expectations_.begin();
510 it != untyped_expectations_.end(); ++it) {
511 ExpectationBase* const untyped_expectation = it->get();
512 if (untyped_expectation->IsOverSaturated()) {
513 // There was an upper-bound violation. Since the error was
514 // already reported when it occurred, there is no need to do
515 // anything here.
516 expectations_met = false;
517 } else if (!untyped_expectation->IsSatisfied()) {
518 expectations_met = false;
519 ::std::stringstream ss;
520 ss << "Actual function call count doesn't match "
521 << untyped_expectation->source_text() << "...\n";
522 // No need to show the source file location of the expectation
523 // in the description, as the Expect() call that follows already
524 // takes care of it.
525 untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
526 untyped_expectation->DescribeCallCountTo(&ss);
527 Expect(false, untyped_expectation->file(),
528 untyped_expectation->line(), ss.str());
529 }
530 }
531
532 // Deleting our expectations may trigger other mock objects to be deleted, for
533 // example if an action contains a reference counted smart pointer to that
534 // mock object, and that is the last reference. So if we delete our
535 // expectations within the context of the global mutex we may deadlock when
536 // this method is called again. Instead, make a copy of the set of
537 // expectations to delete, clear our set within the mutex, and then clear the
538 // copied set outside of it.
539 UntypedExpectations expectations_to_delete;
540 untyped_expectations_.swap(expectations_to_delete);
541
542 g_gmock_mutex.Unlock();
543 expectations_to_delete.clear();
544 g_gmock_mutex.Lock();
545
546 return expectations_met;
547 }
548
intToCallReaction(int mock_behavior)549 CallReaction intToCallReaction(int mock_behavior) {
550 if (mock_behavior >= kAllow && mock_behavior <= kFail) {
551 return static_cast<internal::CallReaction>(mock_behavior);
552 }
553 return kWarn;
554 }
555
556 } // namespace internal
557
558 // Class Mock.
559
560 namespace {
561
562 typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
563
564 // The current state of a mock object. Such information is needed for
565 // detecting leaked mock objects and explicitly verifying a mock's
566 // expectations.
567 struct MockObjectState {
MockObjectStatetesting::__anoncbefcb4e0111::MockObjectState568 MockObjectState()
569 : first_used_file(nullptr), first_used_line(-1), leakable(false) {}
570
571 // Where in the source file an ON_CALL or EXPECT_CALL is first
572 // invoked on this mock object.
573 const char* first_used_file;
574 int first_used_line;
575 ::std::string first_used_test_suite;
576 ::std::string first_used_test;
577 bool leakable; // true iff it's OK to leak the object.
578 FunctionMockers function_mockers; // All registered methods of the object.
579 };
580
581 // A global registry holding the state of all mock objects that are
582 // alive. A mock object is added to this registry the first time
583 // Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It
584 // is removed from the registry in the mock object's destructor.
585 class MockObjectRegistry {
586 public:
587 // Maps a mock object (identified by its address) to its state.
588 typedef std::map<const void*, MockObjectState> StateMap;
589
590 // This destructor will be called when a program exits, after all
591 // tests in it have been run. By then, there should be no mock
592 // object alive. Therefore we report any living object as test
593 // failure, unless the user explicitly asked us to ignore it.
~MockObjectRegistry()594 ~MockObjectRegistry() {
595 if (!GMOCK_FLAG(catch_leaked_mocks))
596 return;
597
598 int leaked_count = 0;
599 for (StateMap::const_iterator it = states_.begin(); it != states_.end();
600 ++it) {
601 if (it->second.leakable) // The user said it's fine to leak this object.
602 continue;
603
604 // FIXME: Print the type of the leaked object.
605 // This can help the user identify the leaked object.
606 std::cout << "\n";
607 const MockObjectState& state = it->second;
608 std::cout << internal::FormatFileLocation(state.first_used_file,
609 state.first_used_line);
610 std::cout << " ERROR: this mock object";
611 if (state.first_used_test != "") {
612 std::cout << " (used in test " << state.first_used_test_suite << "."
613 << state.first_used_test << ")";
614 }
615 std::cout << " should be deleted but never is. Its address is @"
616 << it->first << ".";
617 leaked_count++;
618 }
619 if (leaked_count > 0) {
620 std::cout << "\nERROR: " << leaked_count << " leaked mock "
621 << (leaked_count == 1 ? "object" : "objects")
622 << " found at program exit. Expectations on a mock object is "
623 "verified when the object is destructed. Leaking a mock "
624 "means that its expectations aren't verified, which is "
625 "usually a test bug. If you really intend to leak a mock, "
626 "you can suppress this error using "
627 "testing::Mock::AllowLeak(mock_object), or you may use a "
628 "fake or stub instead of a mock.\n";
629 std::cout.flush();
630 ::std::cerr.flush();
631 // RUN_ALL_TESTS() has already returned when this destructor is
632 // called. Therefore we cannot use the normal Google Test
633 // failure reporting mechanism.
634 _exit(1); // We cannot call exit() as it is not reentrant and
635 // may already have been called.
636 }
637 }
638
states()639 StateMap& states() { return states_; }
640
641 private:
642 StateMap states_;
643 };
644
645 // Protected by g_gmock_mutex.
646 MockObjectRegistry g_mock_object_registry;
647
648 // Maps a mock object to the reaction Google Mock should have when an
649 // uninteresting method is called. Protected by g_gmock_mutex.
650 std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
651
652 // Sets the reaction Google Mock should have when an uninteresting
653 // method of the given mock object is called.
SetReactionOnUninterestingCalls(const void * mock_obj,internal::CallReaction reaction)654 void SetReactionOnUninterestingCalls(const void* mock_obj,
655 internal::CallReaction reaction)
656 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
657 internal::MutexLock l(&internal::g_gmock_mutex);
658 g_uninteresting_call_reaction[mock_obj] = reaction;
659 }
660
661 } // namespace
662
663 // Tells Google Mock to allow uninteresting calls on the given mock
664 // object.
AllowUninterestingCalls(const void * mock_obj)665 void Mock::AllowUninterestingCalls(const void* mock_obj)
666 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
667 SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
668 }
669
670 // Tells Google Mock to warn the user about uninteresting calls on the
671 // given mock object.
WarnUninterestingCalls(const void * mock_obj)672 void Mock::WarnUninterestingCalls(const void* mock_obj)
673 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
674 SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
675 }
676
677 // Tells Google Mock to fail uninteresting calls on the given mock
678 // object.
FailUninterestingCalls(const void * mock_obj)679 void Mock::FailUninterestingCalls(const void* mock_obj)
680 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
681 SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
682 }
683
684 // Tells Google Mock the given mock object is being destroyed and its
685 // entry in the call-reaction table should be removed.
UnregisterCallReaction(const void * mock_obj)686 void Mock::UnregisterCallReaction(const void* mock_obj)
687 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
688 internal::MutexLock l(&internal::g_gmock_mutex);
689 g_uninteresting_call_reaction.erase(mock_obj);
690 }
691
692 // Returns the reaction Google Mock will have on uninteresting calls
693 // made on the given mock object.
GetReactionOnUninterestingCalls(const void * mock_obj)694 internal::CallReaction Mock::GetReactionOnUninterestingCalls(
695 const void* mock_obj)
696 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
697 internal::MutexLock l(&internal::g_gmock_mutex);
698 return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
699 internal::intToCallReaction(GMOCK_FLAG(default_mock_behavior)) :
700 g_uninteresting_call_reaction[mock_obj];
701 }
702
703 // Tells Google Mock to ignore mock_obj when checking for leaked mock
704 // objects.
AllowLeak(const void * mock_obj)705 void Mock::AllowLeak(const void* mock_obj)
706 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
707 internal::MutexLock l(&internal::g_gmock_mutex);
708 g_mock_object_registry.states()[mock_obj].leakable = true;
709 }
710
711 // Verifies and clears all expectations on the given mock object. If
712 // the expectations aren't satisfied, generates one or more Google
713 // Test non-fatal failures and returns false.
VerifyAndClearExpectations(void * mock_obj)714 bool Mock::VerifyAndClearExpectations(void* mock_obj)
715 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
716 internal::MutexLock l(&internal::g_gmock_mutex);
717 return VerifyAndClearExpectationsLocked(mock_obj);
718 }
719
720 // Verifies all expectations on the given mock object and clears its
721 // default actions and expectations. Returns true iff the
722 // verification was successful.
VerifyAndClear(void * mock_obj)723 bool Mock::VerifyAndClear(void* mock_obj)
724 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
725 internal::MutexLock l(&internal::g_gmock_mutex);
726 ClearDefaultActionsLocked(mock_obj);
727 return VerifyAndClearExpectationsLocked(mock_obj);
728 }
729
730 // Verifies and clears all expectations on the given mock object. If
731 // the expectations aren't satisfied, generates one or more Google
732 // Test non-fatal failures and returns false.
VerifyAndClearExpectationsLocked(void * mock_obj)733 bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
734 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
735 internal::g_gmock_mutex.AssertHeld();
736 if (g_mock_object_registry.states().count(mock_obj) == 0) {
737 // No EXPECT_CALL() was set on the given mock object.
738 return true;
739 }
740
741 // Verifies and clears the expectations on each mock method in the
742 // given mock object.
743 bool expectations_met = true;
744 FunctionMockers& mockers =
745 g_mock_object_registry.states()[mock_obj].function_mockers;
746 for (FunctionMockers::const_iterator it = mockers.begin();
747 it != mockers.end(); ++it) {
748 if (!(*it)->VerifyAndClearExpectationsLocked()) {
749 expectations_met = false;
750 }
751 }
752
753 // We don't clear the content of mockers, as they may still be
754 // needed by ClearDefaultActionsLocked().
755 return expectations_met;
756 }
757
IsNaggy(void * mock_obj)758 bool Mock::IsNaggy(void* mock_obj)
759 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
760 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kWarn;
761 }
IsNice(void * mock_obj)762 bool Mock::IsNice(void* mock_obj)
763 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
764 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kAllow;
765 }
IsStrict(void * mock_obj)766 bool Mock::IsStrict(void* mock_obj)
767 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
768 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kFail;
769 }
770
771 // Registers a mock object and a mock method it owns.
Register(const void * mock_obj,internal::UntypedFunctionMockerBase * mocker)772 void Mock::Register(const void* mock_obj,
773 internal::UntypedFunctionMockerBase* mocker)
774 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
775 internal::MutexLock l(&internal::g_gmock_mutex);
776 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
777 }
778
779 // Tells Google Mock where in the source code mock_obj is used in an
780 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
781 // information helps the user identify which object it is.
RegisterUseByOnCallOrExpectCall(const void * mock_obj,const char * file,int line)782 void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,
783 const char* file, int line)
784 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
785 internal::MutexLock l(&internal::g_gmock_mutex);
786 MockObjectState& state = g_mock_object_registry.states()[mock_obj];
787 if (state.first_used_file == nullptr) {
788 state.first_used_file = file;
789 state.first_used_line = line;
790 const TestInfo* const test_info =
791 UnitTest::GetInstance()->current_test_info();
792 if (test_info != nullptr) {
793 state.first_used_test_suite = test_info->test_suite_name();
794 state.first_used_test = test_info->name();
795 }
796 }
797 }
798
799 // Unregisters a mock method; removes the owning mock object from the
800 // registry when the last mock method associated with it has been
801 // unregistered. This is called only in the destructor of
802 // FunctionMockerBase.
UnregisterLocked(internal::UntypedFunctionMockerBase * mocker)803 void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
804 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
805 internal::g_gmock_mutex.AssertHeld();
806 for (MockObjectRegistry::StateMap::iterator it =
807 g_mock_object_registry.states().begin();
808 it != g_mock_object_registry.states().end(); ++it) {
809 FunctionMockers& mockers = it->second.function_mockers;
810 if (mockers.erase(mocker) > 0) {
811 // mocker was in mockers and has been just removed.
812 if (mockers.empty()) {
813 g_mock_object_registry.states().erase(it);
814 }
815 return;
816 }
817 }
818 }
819
820 // Clears all ON_CALL()s set on the given mock object.
ClearDefaultActionsLocked(void * mock_obj)821 void Mock::ClearDefaultActionsLocked(void* mock_obj)
822 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
823 internal::g_gmock_mutex.AssertHeld();
824
825 if (g_mock_object_registry.states().count(mock_obj) == 0) {
826 // No ON_CALL() was set on the given mock object.
827 return;
828 }
829
830 // Clears the default actions for each mock method in the given mock
831 // object.
832 FunctionMockers& mockers =
833 g_mock_object_registry.states()[mock_obj].function_mockers;
834 for (FunctionMockers::const_iterator it = mockers.begin();
835 it != mockers.end(); ++it) {
836 (*it)->ClearDefaultActionsLocked();
837 }
838
839 // We don't clear the content of mockers, as they may still be
840 // needed by VerifyAndClearExpectationsLocked().
841 }
842
Expectation()843 Expectation::Expectation() {}
844
Expectation(const std::shared_ptr<internal::ExpectationBase> & an_expectation_base)845 Expectation::Expectation(
846 const std::shared_ptr<internal::ExpectationBase>& an_expectation_base)
847 : expectation_base_(an_expectation_base) {}
848
~Expectation()849 Expectation::~Expectation() {}
850
851 // Adds an expectation to a sequence.
AddExpectation(const Expectation & expectation) const852 void Sequence::AddExpectation(const Expectation& expectation) const {
853 if (*last_expectation_ != expectation) {
854 if (last_expectation_->expectation_base() != nullptr) {
855 expectation.expectation_base()->immediate_prerequisites_
856 += *last_expectation_;
857 }
858 *last_expectation_ = expectation;
859 }
860 }
861
862 // Creates the implicit sequence if there isn't one.
InSequence()863 InSequence::InSequence() {
864 if (internal::g_gmock_implicit_sequence.get() == nullptr) {
865 internal::g_gmock_implicit_sequence.set(new Sequence);
866 sequence_created_ = true;
867 } else {
868 sequence_created_ = false;
869 }
870 }
871
872 // Deletes the implicit sequence if it was created by the constructor
873 // of this object.
~InSequence()874 InSequence::~InSequence() {
875 if (sequence_created_) {
876 delete internal::g_gmock_implicit_sequence.get();
877 internal::g_gmock_implicit_sequence.set(nullptr);
878 }
879 }
880
881 } // namespace testing
882
883 #ifdef _MSC_VER
884 #if _MSC_VER == 1900
885 # pragma warning(pop)
886 #endif
887 #endif
888