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