51#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
60# pragma warning(disable:4800)
73 const char*
file,
int line,
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()
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
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
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
188 g_gmock_mutex.AssertHeld();
191 *os <<
" Expected: to be ";
192 cardinality().DescribeTo(os);
193 *os <<
"\n Actual: ";
194 Cardinality::DescribeActualCallCountTo(call_count(), os);
198 *os <<
" - " << (IsOverSaturated() ?
"over-saturated" :
199 IsSaturated() ?
"saturated" :
200 IsSatisfied() ?
"satisfied" :
"unsatisfied")
202 << (is_retired() ?
"retired" :
"active");
209void ExpectationBase::CheckActionCountIfNotDone()
const
211 bool should_check =
false;
214 if (!action_count_checked_) {
215 action_count_checked_ =
true;
221 if (!cardinality_specified_) {
228 const int action_count =
static_cast<int>(untyped_actions_.size());
229 const int upper_bound = cardinality().ConservativeUpperBound();
230 const int lower_bound = cardinality().ConservativeLowerBound();
233 if (action_count > upper_bound ||
234 (action_count == upper_bound && repeated_action_specified_)) {
236 }
else if (0 < action_count && action_count < lower_bound &&
237 !repeated_action_specified_) {
243 ::std::stringstream ss;
244 DescribeLocationTo(&ss);
245 ss <<
"Too " << (too_many ?
"many" :
"few")
246 <<
" actions specified in " << source_text() <<
"...\n"
247 <<
"Expected to be ";
248 cardinality().DescribeTo(&ss);
249 ss <<
", but has " << (too_many ?
"" :
"only ")
250 << action_count <<
" WillOnce()"
251 << (action_count == 1 ?
"" :
"s");
252 if (repeated_action_specified_) {
253 ss <<
" and a WillRepeatedly()";
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().");
267 ExpectSpecProperty(last_clause_ < kTimes,
268 ".Times() cannot appear after "
269 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
270 "or .RetiresOnSaturation().");
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)
321 mock_obj_ = mock_obj;
323 Mock::Register(mock_obj,
this);
329void UntypedFunctionMockerBase::SetOwnerAndName(
const void* mock_obj,
335 mock_obj_ = mock_obj;
341const void* UntypedFunctionMockerBase::MockObject()
const
343 const void* mock_obj;
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
365 Assert(name_ !=
nullptr, __FILE__, __LINE__,
366 "Name() must not be called before SetOwnerAndName() has "
376UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(
380 if (untyped_expectations_.size() == 0) {
388 const CallReaction reaction =
389 Mock::GetReactionOnUninterestingCalls(MockObject());
394 const bool need_to_report_uninteresting_call =
407 if (!need_to_report_uninteresting_call) {
409 return this->UntypedPerformDefaultAction(
410 untyped_args,
"Function call: " + std::string(Name()));
414 ::std::stringstream ss;
415 this->UntypedDescribeUninterestingCall(untyped_args, &ss);
418 UntypedActionResultHolderBase*
const result =
419 this->UntypedPerformDefaultAction(untyped_args, ss.str());
422 if (result !=
nullptr) result->PrintAsActionResult(&ss);
428 bool is_excessive =
false;
429 ::std::stringstream ss;
430 ::std::stringstream why;
431 ::std::stringstream loc;
432 const void* untyped_action =
nullptr;
437 const ExpectationBase*
const untyped_expectation =
438 this->UntypedFindMatchingExpectation(untyped_args, &untyped_action,
439 &is_excessive, &ss, &why);
440 const bool found = untyped_expectation !=
nullptr;
446 const bool need_to_report_call =
448 if (!need_to_report_call) {
450 return untyped_action ==
nullptr
451 ? this->UntypedPerformDefaultAction(untyped_args,
"")
452 : this->UntypedPerformAction(untyped_action, untyped_args);
455 ss <<
" Function call: " << Name();
456 this->UntypedPrintArgs(untyped_args, &ss);
460 if (found && !is_excessive) {
461 untyped_expectation->DescribeLocationTo(&loc);
464 UntypedActionResultHolderBase* result =
nullptr;
466 auto perform_action = [&] {
467 return untyped_action ==
nullptr
468 ? this->UntypedPerformDefaultAction(untyped_args, ss.str())
469 : this->UntypedPerformAction(untyped_action, untyped_args);
471 auto handle_failures = [&] {
472 ss <<
"\n" << why.str();
476 Expect(
false,
nullptr, -1, ss.str());
477 }
else if (is_excessive) {
479 Expect(
false, untyped_expectation->file(), untyped_expectation->line(),
484 Log(
kInfo, loc.str() + ss.str(), 2);
487#if GTEST_HAS_EXCEPTIONS
489 result = perform_action();
495 result = perform_action();
498 if (result !=
nullptr) result->PrintAsActionResult(&ss);
505Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
508 for (UntypedExpectations::const_iterator it =
509 untyped_expectations_.begin();
510 it != untyped_expectations_.end(); ++it) {
511 if (it->get() == exp) {
512 return Expectation(*it);
516 Assert(
false, __FILE__, __LINE__,
"Cannot find expectation.");
517 return Expectation();
525bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
527 g_gmock_mutex.AssertHeld();
528 bool expectations_met =
true;
529 for (UntypedExpectations::const_iterator it =
530 untyped_expectations_.begin();
531 it != untyped_expectations_.end(); ++it) {
532 ExpectationBase*
const untyped_expectation = it->get();
533 if (untyped_expectation->IsOverSaturated()) {
537 expectations_met =
false;
538 }
else if (!untyped_expectation->IsSatisfied()) {
539 expectations_met =
false;
540 ::std::stringstream ss;
541 ss <<
"Actual function call count doesn't match "
542 << untyped_expectation->source_text() <<
"...\n";
546 untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
547 untyped_expectation->DescribeCallCountTo(&ss);
548 Expect(
false, untyped_expectation->file(),
549 untyped_expectation->line(), ss.str());
560 UntypedExpectations expectations_to_delete;
561 untyped_expectations_.swap(expectations_to_delete);
563 g_gmock_mutex.Unlock();
564 expectations_to_delete.clear();
565 g_gmock_mutex.Lock();
567 return expectations_met;
571 if (mock_behavior >= kAllow && mock_behavior <= kFail) {
572 return static_cast<internal::CallReaction
>(mock_behavior);
583typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
588struct MockObjectState {
606class MockObjectRegistry {
609 typedef std::map<const void*, MockObjectState> StateMap;
615 ~MockObjectRegistry() {
619 int leaked_count = 0;
620 for (StateMap::const_iterator it = states_.begin(); it != states_.end();
622 if (it->second.leakable)
628 const MockObjectState& state = it->second;
630 state.first_used_line);
631 std::cout <<
" ERROR: this mock object";
632 if (state.first_used_test !=
"") {
633 std::cout <<
" (used in test " << state.first_used_test_suite <<
"."
634 << state.first_used_test <<
")";
636 std::cout <<
" should be deleted but never is. Its address is @"
640 if (leaked_count > 0) {
641 std::cout <<
"\nERROR: " << leaked_count <<
" leaked mock "
642 << (leaked_count == 1 ?
"object" :
"objects")
643 <<
" found at program exit. Expectations on a mock object are "
644 "verified when the object is destructed. Leaking a mock "
645 "means that its expectations aren't verified, which is "
646 "usually a test bug. If you really intend to leak a mock, "
647 "you can suppress this error using "
648 "testing::Mock::AllowLeak(mock_object), or you may use a "
649 "fake or stub instead of a mock.\n";
660 StateMap& states() {
return states_; }
667MockObjectRegistry g_mock_object_registry;
671std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
675void SetReactionOnUninterestingCalls(
const void* mock_obj,
676 internal::CallReaction reaction)
679 g_uninteresting_call_reaction[mock_obj] = reaction;
686void Mock::AllowUninterestingCalls(
const void* mock_obj)
688 SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
693void Mock::WarnUninterestingCalls(
const void* mock_obj)
695 SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
700void Mock::FailUninterestingCalls(
const void* mock_obj)
702 SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
707void Mock::UnregisterCallReaction(
const void* mock_obj)
710 g_uninteresting_call_reaction.erase(mock_obj);
715internal::CallReaction Mock::GetReactionOnUninterestingCalls(
716 const void* mock_obj)
719 return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
721 g_uninteresting_call_reaction[mock_obj];
726void Mock::AllowLeak(
const void* mock_obj)
729 g_mock_object_registry.states()[mock_obj].leakable =
true;
735bool Mock::VerifyAndClearExpectations(
void* mock_obj)
738 return VerifyAndClearExpectationsLocked(mock_obj);
744bool Mock::VerifyAndClear(
void* mock_obj)
747 ClearDefaultActionsLocked(mock_obj);
748 return VerifyAndClearExpectationsLocked(mock_obj);
754bool Mock::VerifyAndClearExpectationsLocked(
void* mock_obj)
756 internal::g_gmock_mutex.AssertHeld();
757 if (g_mock_object_registry.states().count(mock_obj) == 0) {
764 bool expectations_met =
true;
765 FunctionMockers& mockers =
766 g_mock_object_registry.states()[mock_obj].function_mockers;
767 for (FunctionMockers::const_iterator it = mockers.begin();
768 it != mockers.end(); ++it) {
769 if (!(*it)->VerifyAndClearExpectationsLocked()) {
770 expectations_met =
false;
776 return expectations_met;
779bool Mock::IsNaggy(
void* mock_obj)
781 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kWarn;
783bool Mock::IsNice(
void* mock_obj)
785 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kAllow;
787bool Mock::IsStrict(
void* mock_obj)
789 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kFail;
793void Mock::Register(
const void* mock_obj,
794 internal::UntypedFunctionMockerBase* mocker)
797 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
803void Mock::RegisterUseByOnCallOrExpectCall(
const void* mock_obj,
804 const char*
file,
int line)
807 MockObjectState& state = g_mock_object_registry.states()[mock_obj];
808 if (state.first_used_file ==
nullptr) {
809 state.first_used_file =
file;
810 state.first_used_line = line;
811 const TestInfo*
const test_info =
812 UnitTest::GetInstance()->current_test_info();
813 if (test_info !=
nullptr) {
814 state.first_used_test_suite = test_info->test_suite_name();
815 state.first_used_test = test_info->name();
824void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
826 internal::g_gmock_mutex.AssertHeld();
827 for (MockObjectRegistry::StateMap::iterator it =
828 g_mock_object_registry.states().begin();
829 it != g_mock_object_registry.states().end(); ++it) {
830 FunctionMockers& mockers = it->second.function_mockers;
831 if (mockers.erase(mocker) > 0) {
833 if (mockers.empty()) {
834 g_mock_object_registry.states().erase(it);
842void Mock::ClearDefaultActionsLocked(
void* mock_obj)
844 internal::g_gmock_mutex.AssertHeld();
846 if (g_mock_object_registry.states().count(mock_obj) == 0) {
853 FunctionMockers& mockers =
854 g_mock_object_registry.states()[mock_obj].function_mockers;
855 for (FunctionMockers::const_iterator it = mockers.begin();
856 it != mockers.end(); ++it) {
857 (*it)->ClearDefaultActionsLocked();
864Expectation::Expectation() {}
866Expectation::Expectation(
867 const std::shared_ptr<internal::ExpectationBase>& an_expectation_base)
868 : expectation_base_(an_expectation_base) {}
870Expectation::~Expectation() {}
873void Sequence::AddExpectation(
const Expectation& expectation)
const {
874 if (*last_expectation_ != expectation) {
875 if (last_expectation_->expectation_base() !=
nullptr) {
876 expectation.expectation_base()->immediate_prerequisites_
877 += *last_expectation_;
879 *last_expectation_ = expectation;
884InSequence::InSequence() {
887 sequence_created_ =
true;
889 sequence_created_ =
false;
895InSequence::~InSequence() {
896 if (sequence_created_) {
::std::string first_used_test_suite
const char * first_used_file
::std::string first_used_test
FunctionMockers function_mockers
#define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
#define GTEST_LOCK_EXCLUDED_(locks)
#define GTEST_DEFINE_STATIC_MUTEX_(mutex)
GTEST_API_ Cardinality Exactly(int n)
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)
GTEST_API_ bool LogIsVisible(LogSeverity severity)
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)