44#include <unordered_map>
48#include "gtest/gtest.h"
49#include "gtest/internal/gtest-port.h"
51#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
60#pragma warning(disable : 4800)
73 const char* file,
int line,
74 const std::string& message) {
75 ::std::ostringstream s;
78 Log(severity, s.str(), 0);
82ExpectationBase::ExpectationBase(
const char* a_file,
int a_line,
83 const std::string& a_source_text)
86 source_text_(a_source_text),
87 cardinality_specified_(false),
91 extra_matcher_specified_(false),
92 repeated_action_specified_(false),
93 retires_on_saturation_(false),
95 action_count_checked_(false) {}
98ExpectationBase::~ExpectationBase() {}
102void ExpectationBase::SpecifyCardinality(
const Cardinality& a_cardinality) {
103 cardinality_specified_ =
true;
104 cardinality_ = a_cardinality;
108void ExpectationBase::RetireAllPreRequisites()
109 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
116 ::std::vector<ExpectationBase*> expectations(1,
this);
117 while (!expectations.empty()) {
118 ExpectationBase* exp = expectations.back();
119 expectations.pop_back();
121 for (ExpectationSet::const_iterator it =
122 exp->immediate_prerequisites_.begin();
123 it != exp->immediate_prerequisites_.end(); ++it) {
124 ExpectationBase* next = it->expectation_base().get();
125 if (!next->is_retired()) {
127 expectations.push_back(next);
135bool ExpectationBase::AllPrerequisitesAreSatisfied() const
136 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
137 g_gmock_mutex.AssertHeld();
138 ::std::vector<const ExpectationBase*> expectations(1,
this);
139 while (!expectations.empty()) {
140 const ExpectationBase* exp = expectations.back();
141 expectations.pop_back();
143 for (ExpectationSet::const_iterator it =
144 exp->immediate_prerequisites_.begin();
145 it != exp->immediate_prerequisites_.end(); ++it) {
146 const ExpectationBase* next = it->expectation_base().get();
147 if (!next->IsSatisfied())
return false;
148 expectations.push_back(next);
155void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result)
const
156 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
157 g_gmock_mutex.AssertHeld();
158 ::std::vector<const ExpectationBase*> expectations(1,
this);
159 while (!expectations.empty()) {
160 const ExpectationBase* exp = expectations.back();
161 expectations.pop_back();
163 for (ExpectationSet::const_iterator it =
164 exp->immediate_prerequisites_.begin();
165 it != exp->immediate_prerequisites_.end(); ++it) {
166 const ExpectationBase* next = it->expectation_base().get();
168 if (next->IsSatisfied()) {
171 if (next->call_count_ == 0) {
172 expectations.push_back(next);
186void ExpectationBase::DescribeCallCountTo(::std::ostream* os)
const
187 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
188 g_gmock_mutex.AssertHeld();
191 *os <<
" Expected: to be ";
192 cardinality().DescribeTo(os);
193 *os <<
"\n Actual: ";
194 Cardinality::DescribeActualCallCountTo(call_count(), os);
199 << (IsOverSaturated() ?
"over-saturated"
200 : IsSaturated() ?
"saturated"
201 : IsSatisfied() ?
"satisfied"
203 <<
" and " << (is_retired() ?
"retired" :
"active");
210void ExpectationBase::CheckActionCountIfNotDone() const
211 GTEST_LOCK_EXCLUDED_(mutex_) {
212 bool should_check =
false;
214 MutexLock l(&mutex_);
215 if (!action_count_checked_) {
216 action_count_checked_ =
true;
222 if (!cardinality_specified_) {
229 const int action_count =
static_cast<int>(untyped_actions_.size());
230 const int upper_bound = cardinality().ConservativeUpperBound();
231 const int lower_bound = cardinality().ConservativeLowerBound();
234 if (action_count > upper_bound ||
235 (action_count == upper_bound && repeated_action_specified_)) {
237 }
else if (0 < action_count && action_count < lower_bound &&
238 !repeated_action_specified_) {
244 ::std::stringstream ss;
245 DescribeLocationTo(&ss);
246 ss <<
"Too " << (too_many ?
"many" :
"few") <<
" actions specified in "
247 << source_text() <<
"...\n"
248 <<
"Expected to be ";
249 cardinality().DescribeTo(&ss);
250 ss <<
", but has " << (too_many ?
"" :
"only ") << action_count
251 <<
" WillOnce()" << (action_count == 1 ?
"" :
"s");
252 if (repeated_action_specified_) {
253 ss <<
" and a WillRepeatedly()";
256 Log(kWarning, ss.str(), -1);
261void ExpectationBase::UntypedTimes(
const Cardinality& a_cardinality) {
262 if (last_clause_ == kTimes) {
263 ExpectSpecProperty(
false,
264 ".Times() cannot appear "
265 "more than once in an EXPECT_CALL().");
268 last_clause_ < kTimes,
269 ".Times() may only appear *before* .InSequence(), .WillOnce(), "
270 ".WillRepeatedly(), or .RetiresOnSaturation(), not after.");
272 last_clause_ = kTimes;
274 SpecifyCardinality(a_cardinality);
285 const int stack_frames_to_skip =
289 Log(
kInfo, msg, stack_frames_to_skip);
294 "\nNOTE: You can safely ignore the above warning unless this "
295 "call should not happen. Do not suppress it by blindly adding "
296 "an EXPECT_CALL() if you don't mean to enforce the call. "
298 "https://github.com/google/googletest/blob/master/docs/"
299 "gmock_cook_book.md#"
300 "knowing-when-to-expect for details.\n",
301 stack_frames_to_skip);
304 Expect(
false,
nullptr, -1, msg);
308UntypedFunctionMockerBase::UntypedFunctionMockerBase()
309 : mock_obj_(nullptr), name_(
"") {}
311UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
317void UntypedFunctionMockerBase::RegisterOwner(
const void* mock_obj)
318 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
320 MutexLock l(&g_gmock_mutex);
321 mock_obj_ = mock_obj;
323 Mock::Register(mock_obj,
this);
329void UntypedFunctionMockerBase::SetOwnerAndName(
const void* mock_obj,
331 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
334 MutexLock l(&g_gmock_mutex);
335 mock_obj_ = mock_obj;
341const void* UntypedFunctionMockerBase::MockObject() const
342 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
343 const void* mock_obj;
347 MutexLock l(&g_gmock_mutex);
348 Assert(mock_obj_ !=
nullptr, __FILE__, __LINE__,
349 "MockObject() must not be called before RegisterOwner() or "
350 "SetOwnerAndName() has been called.");
351 mock_obj = mock_obj_;
358const char* UntypedFunctionMockerBase::Name() const
359 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
364 MutexLock l(&g_gmock_mutex);
365 Assert(name_ !=
nullptr, __FILE__, __LINE__,
366 "Name() must not be called before SetOwnerAndName() has "
375Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
378 for (UntypedExpectations::const_iterator it = untyped_expectations_.begin();
379 it != untyped_expectations_.end(); ++it) {
380 if (it->get() == exp) {
381 return Expectation(*it);
385 Assert(
false, __FILE__, __LINE__,
"Cannot find expectation.");
386 return Expectation();
394bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
395 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
396 g_gmock_mutex.AssertHeld();
397 bool expectations_met =
true;
398 for (UntypedExpectations::const_iterator it = untyped_expectations_.begin();
399 it != untyped_expectations_.end(); ++it) {
400 ExpectationBase*
const untyped_expectation = it->get();
401 if (untyped_expectation->IsOverSaturated()) {
405 expectations_met =
false;
406 }
else if (!untyped_expectation->IsSatisfied()) {
407 expectations_met =
false;
408 ::std::stringstream ss;
409 ss <<
"Actual function call count doesn't match "
410 << untyped_expectation->source_text() <<
"...\n";
414 untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
415 untyped_expectation->DescribeCallCountTo(&ss);
416 Expect(
false, untyped_expectation->file(), untyped_expectation->line(),
428 UntypedExpectations expectations_to_delete;
429 untyped_expectations_.swap(expectations_to_delete);
431 g_gmock_mutex.Unlock();
432 expectations_to_delete.clear();
433 g_gmock_mutex.Lock();
435 return expectations_met;
439 if (mock_behavior >= kAllow && mock_behavior <= kFail) {
440 return static_cast<internal::CallReaction
>(mock_behavior);
451typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
456struct MockObjectState {
474class MockObjectRegistry {
477 typedef std::map<const void*, MockObjectState> StateMap;
483 ~MockObjectRegistry() {
486 int leaked_count = 0;
487 for (StateMap::const_iterator it = states_.begin(); it != states_.end();
489 if (it->second.leakable)
495 const MockObjectState& state = it->second;
496 std::cout << internal::FormatFileLocation(state.first_used_file,
497 state.first_used_line);
498 std::cout <<
" ERROR: this mock object";
499 if (state.first_used_test !=
"") {
500 std::cout <<
" (used in test " << state.first_used_test_suite <<
"."
501 << state.first_used_test <<
")";
503 std::cout <<
" should be deleted but never is. Its address is @"
507 if (leaked_count > 0) {
508 std::cout <<
"\nERROR: " << leaked_count <<
" leaked mock "
509 << (leaked_count == 1 ?
"object" :
"objects")
510 <<
" found at program exit. Expectations on a mock object are "
511 "verified when the object is destructed. Leaking a mock "
512 "means that its expectations aren't verified, which is "
513 "usually a test bug. If you really intend to leak a mock, "
514 "you can suppress this error using "
515 "testing::Mock::AllowLeak(mock_object), or you may use a "
516 "fake or stub instead of a mock.\n";
527 StateMap& states() {
return states_; }
534MockObjectRegistry g_mock_object_registry;
538std::unordered_map<uintptr_t, internal::CallReaction>&
539UninterestingCallReactionMap() {
540 static auto* map =
new std::unordered_map<uintptr_t, internal::CallReaction>;
546void SetReactionOnUninterestingCalls(uintptr_t mock_obj,
547 internal::CallReaction reaction)
548 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
549 internal::MutexLock l(&internal::g_gmock_mutex);
550 UninterestingCallReactionMap()[mock_obj] = reaction;
557void Mock::AllowUninterestingCalls(uintptr_t mock_obj)
558 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
559 SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
564void Mock::WarnUninterestingCalls(uintptr_t mock_obj)
565 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
566 SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
571void Mock::FailUninterestingCalls(uintptr_t mock_obj)
572 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
573 SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
578void Mock::UnregisterCallReaction(uintptr_t mock_obj)
579 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
580 internal::MutexLock l(&internal::g_gmock_mutex);
581 UninterestingCallReactionMap().erase(
static_cast<uintptr_t
>(mock_obj));
586internal::CallReaction Mock::GetReactionOnUninterestingCalls(
587 const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
588 internal::MutexLock l(&internal::g_gmock_mutex);
589 return (UninterestingCallReactionMap().count(
590 reinterpret_cast<uintptr_t
>(mock_obj)) == 0)
591 ? internal::intToCallReaction(
593 : UninterestingCallReactionMap()[reinterpret_cast<uintptr_t>(
599void Mock::AllowLeak(
const void* mock_obj)
600 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
601 internal::MutexLock l(&internal::g_gmock_mutex);
602 g_mock_object_registry.states()[mock_obj].leakable =
true;
608bool Mock::VerifyAndClearExpectations(
void* mock_obj)
609 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
610 internal::MutexLock l(&internal::g_gmock_mutex);
611 return VerifyAndClearExpectationsLocked(mock_obj);
617bool Mock::VerifyAndClear(
void* mock_obj)
618 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
619 internal::MutexLock l(&internal::g_gmock_mutex);
620 ClearDefaultActionsLocked(mock_obj);
621 return VerifyAndClearExpectationsLocked(mock_obj);
627bool Mock::VerifyAndClearExpectationsLocked(
void* mock_obj)
628 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
629 internal::g_gmock_mutex.AssertHeld();
630 if (g_mock_object_registry.states().count(mock_obj) == 0) {
637 bool expectations_met =
true;
638 FunctionMockers& mockers =
639 g_mock_object_registry.states()[mock_obj].function_mockers;
640 for (FunctionMockers::const_iterator it = mockers.begin();
641 it != mockers.end(); ++it) {
642 if (!(*it)->VerifyAndClearExpectationsLocked()) {
643 expectations_met =
false;
649 return expectations_met;
652bool Mock::IsNaggy(
void* mock_obj)
653 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
654 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kWarn;
656bool Mock::IsNice(
void* mock_obj)
657 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
658 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kAllow;
660bool Mock::IsStrict(
void* mock_obj)
661 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
662 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kFail;
666void Mock::Register(
const void* mock_obj,
667 internal::UntypedFunctionMockerBase* mocker)
668 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
669 internal::MutexLock l(&internal::g_gmock_mutex);
670 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
676void Mock::RegisterUseByOnCallOrExpectCall(
const void* mock_obj,
677 const char* file,
int line)
678 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {
679 internal::MutexLock l(&internal::g_gmock_mutex);
680 MockObjectState& state = g_mock_object_registry.states()[mock_obj];
681 if (state.first_used_file ==
nullptr) {
682 state.first_used_file = file;
683 state.first_used_line = line;
684 const TestInfo*
const test_info =
685 UnitTest::GetInstance()->current_test_info();
686 if (test_info !=
nullptr) {
687 state.first_used_test_suite = test_info->test_suite_name();
688 state.first_used_test = test_info->name();
697void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
698 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
699 internal::g_gmock_mutex.AssertHeld();
700 for (MockObjectRegistry::StateMap::iterator it =
701 g_mock_object_registry.states().begin();
702 it != g_mock_object_registry.states().end(); ++it) {
703 FunctionMockers& mockers = it->second.function_mockers;
704 if (mockers.erase(mocker) > 0) {
706 if (mockers.empty()) {
707 g_mock_object_registry.states().erase(it);
715void Mock::ClearDefaultActionsLocked(
void* mock_obj)
716 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
717 internal::g_gmock_mutex.AssertHeld();
719 if (g_mock_object_registry.states().count(mock_obj) == 0) {
726 FunctionMockers& mockers =
727 g_mock_object_registry.states()[mock_obj].function_mockers;
728 for (FunctionMockers::const_iterator it = mockers.begin();
729 it != mockers.end(); ++it) {
730 (*it)->ClearDefaultActionsLocked();
737Expectation::Expectation() {}
739Expectation::Expectation(
740 const std::shared_ptr<internal::ExpectationBase>& an_expectation_base)
741 : expectation_base_(an_expectation_base) {}
743Expectation::~Expectation() {}
746void Sequence::AddExpectation(
const Expectation& expectation)
const {
747 if (*last_expectation_ != expectation) {
748 if (last_expectation_->expectation_base() !=
nullptr) {
749 expectation.expectation_base()->immediate_prerequisites_ +=
752 *last_expectation_ = expectation;
757InSequence::InSequence() {
758 if (internal::g_gmock_implicit_sequence.get() ==
nullptr) {
759 internal::g_gmock_implicit_sequence.set(
new Sequence);
760 sequence_created_ =
true;
762 sequence_created_ =
false;
768InSequence::~InSequence() {
769 if (sequence_created_) {
770 delete internal::g_gmock_implicit_sequence.get();
771 internal::g_gmock_implicit_sequence.set(
nullptr);
#define GMOCK_FLAG_GET(name)
::std::string first_used_test_suite
const char * first_used_file
::std::string first_used_test
FunctionMockers function_mockers
GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char *file, int line, const std::string &message)
GTEST_API_ ThreadLocal< Sequence * > g_gmock_implicit_sequence
GTEST_API_::std::string FormatFileLocation(const char *file, int line)
CallReaction intToCallReaction(int mock_behavior)
static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex)
GTEST_API_ void Log(LogSeverity severity, const std::string &message, int stack_frames_to_skip)
const char kInfoVerbosity[]
void Assert(bool condition, const char *file, int line, const std::string &msg)
void Expect(bool condition, const char *file, int line, const std::string &msg)
void ReportUninterestingCall(CallReaction reaction, const std::string &msg)
GTEST_API_ Cardinality Exactly(int n)