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