51 #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
59 # pragma warning(push)
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);
82 ExpectationBase::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) {}
98 ExpectationBase::~ExpectationBase() {}
102 void ExpectationBase::SpecifyCardinality(
const Cardinality& a_cardinality) {
103 cardinality_specified_ =
true;
104 cardinality_ = a_cardinality;
108 void 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);
135 bool 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);
155 void 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);
186 void 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");
209 void 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()";
261 void 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/googlemock/"
300 "knowing-when-to-expect for details.\n",
301 stack_frames_to_skip);
304 Expect(
false,
nullptr, -1, msg);
308 UntypedFunctionMockerBase::UntypedFunctionMockerBase()
309 : mock_obj_(nullptr),
name_(
"") {}
311 UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
317 void UntypedFunctionMockerBase::RegisterOwner(
const void* mock_obj)
321 mock_obj_ = mock_obj;
323 Mock::Register(mock_obj,
this);
329 void UntypedFunctionMockerBase::SetOwnerAndName(
const void* mock_obj,
335 mock_obj_ = mock_obj;
341 const 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_;
358 const char* UntypedFunctionMockerBase::Name() const
366 "Name() must not be called before SetOwnerAndName() has "
376 UntypedActionResultHolderBase* 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;
436 const ExpectationBase*
const untyped_expectation =
437 this->UntypedFindMatchingExpectation(
438 untyped_args, &untyped_action, &is_excessive,
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*
const result =
465 untyped_action ==
nullptr
466 ? this->UntypedPerformDefaultAction(untyped_args, ss.str())
467 : this->UntypedPerformAction(untyped_action, untyped_args);
468 if (result !=
nullptr) result->PrintAsActionResult(&ss);
469 ss <<
"\n" << why.str();
473 Expect(
false,
nullptr, -1, ss.str());
474 }
else if (is_excessive) {
476 Expect(
false, untyped_expectation->file(),
477 untyped_expectation->line(), ss.str());
481 Log(
kInfo, loc.str() + ss.str(), 2);
489 Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
492 for (UntypedExpectations::const_iterator it =
493 untyped_expectations_.begin();
494 it != untyped_expectations_.end(); ++it) {
495 if (it->get() ==
exp) {
496 return Expectation(*it);
500 Assert(
false, __FILE__, __LINE__,
"Cannot find expectation.");
501 return Expectation();
509 bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
511 g_gmock_mutex.AssertHeld();
512 bool expectations_met =
true;
513 for (UntypedExpectations::const_iterator it =
514 untyped_expectations_.begin();
515 it != untyped_expectations_.end(); ++it) {
516 ExpectationBase*
const untyped_expectation = it->get();
517 if (untyped_expectation->IsOverSaturated()) {
521 expectations_met =
false;
522 }
else if (!untyped_expectation->IsSatisfied()) {
523 expectations_met =
false;
524 ::std::stringstream ss;
525 ss <<
"Actual function call count doesn't match "
526 << untyped_expectation->source_text() <<
"...\n";
530 untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
531 untyped_expectation->DescribeCallCountTo(&ss);
532 Expect(
false, untyped_expectation->file(),
533 untyped_expectation->line(), ss.str());
544 UntypedExpectations expectations_to_delete;
545 untyped_expectations_.swap(expectations_to_delete);
547 g_gmock_mutex.Unlock();
548 expectations_to_delete.clear();
549 g_gmock_mutex.Lock();
551 return expectations_met;
555 if (mock_behavior >= kAllow && mock_behavior <= kFail) {
556 return static_cast<internal::CallReaction
>(mock_behavior);
567 typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
572 struct MockObjectState {
590 class MockObjectRegistry {
593 typedef std::map<const void*, MockObjectState> StateMap;
599 ~MockObjectRegistry() {
603 int leaked_count = 0;
604 for (StateMap::const_iterator it =
states_.begin(); it !=
states_.end();
606 if (it->second.leakable)
612 const MockObjectState& state = it->second;
614 state.first_used_line);
615 std::cout <<
" ERROR: this mock object";
616 if (state.first_used_test !=
"") {
617 std::cout <<
" (used in test " << state.first_used_test_suite <<
"."
618 << state.first_used_test <<
")";
620 std::cout <<
" should be deleted but never is. Its address is @"
624 if (leaked_count > 0) {
625 std::cout <<
"\nERROR: " << leaked_count <<
" leaked mock "
626 << (leaked_count == 1 ?
"object" :
"objects")
627 <<
" found at program exit. Expectations on a mock object are "
628 "verified when the object is destructed. Leaking a mock "
629 "means that its expectations aren't verified, which is "
630 "usually a test bug. If you really intend to leak a mock, "
631 "you can suppress this error using "
632 "testing::Mock::AllowLeak(mock_object), or you may use a "
633 "fake or stub instead of a mock.\n";
644 StateMap& states() {
return states_; }
651 MockObjectRegistry g_mock_object_registry;
655 std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
659 void SetReactionOnUninterestingCalls(
const void* mock_obj,
660 internal::CallReaction reaction)
663 g_uninteresting_call_reaction[mock_obj] = reaction;
670 void Mock::AllowUninterestingCalls(
const void* mock_obj)
672 SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);
677 void Mock::WarnUninterestingCalls(
const void* mock_obj)
679 SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);
684 void Mock::FailUninterestingCalls(
const void* mock_obj)
686 SetReactionOnUninterestingCalls(mock_obj, internal::kFail);
691 void Mock::UnregisterCallReaction(
const void* mock_obj)
694 g_uninteresting_call_reaction.erase(mock_obj);
699 internal::CallReaction Mock::GetReactionOnUninterestingCalls(
700 const void* mock_obj)
703 return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
705 g_uninteresting_call_reaction[mock_obj];
710 void Mock::AllowLeak(
const void* mock_obj)
713 g_mock_object_registry.states()[mock_obj].leakable =
true;
719 bool Mock::VerifyAndClearExpectations(
void* mock_obj)
722 return VerifyAndClearExpectationsLocked(mock_obj);
728 bool Mock::VerifyAndClear(
void* mock_obj)
731 ClearDefaultActionsLocked(mock_obj);
732 return VerifyAndClearExpectationsLocked(mock_obj);
738 bool Mock::VerifyAndClearExpectationsLocked(
void* mock_obj)
740 internal::g_gmock_mutex.AssertHeld();
741 if (g_mock_object_registry.states().count(mock_obj) == 0) {
748 bool expectations_met =
true;
749 FunctionMockers& mockers =
750 g_mock_object_registry.states()[mock_obj].function_mockers;
751 for (FunctionMockers::const_iterator it = mockers.begin();
752 it != mockers.end(); ++it) {
753 if (!(*it)->VerifyAndClearExpectationsLocked()) {
754 expectations_met =
false;
760 return expectations_met;
763 bool Mock::IsNaggy(
void* mock_obj)
765 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kWarn;
767 bool Mock::IsNice(
void* mock_obj)
769 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kAllow;
771 bool Mock::IsStrict(
void* mock_obj)
773 return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kFail;
777 void Mock::Register(
const void* mock_obj,
778 internal::UntypedFunctionMockerBase* mocker)
781 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
787 void Mock::RegisterUseByOnCallOrExpectCall(
const void* mock_obj,
788 const char* file,
int line)
791 MockObjectState& state = g_mock_object_registry.states()[mock_obj];
792 if (state.first_used_file ==
nullptr) {
793 state.first_used_file = file;
794 state.first_used_line = line;
795 const TestInfo*
const test_info =
796 UnitTest::GetInstance()->current_test_info();
797 if (test_info !=
nullptr) {
798 state.first_used_test_suite = test_info->test_suite_name();
799 state.first_used_test = test_info->name();
808 void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
810 internal::g_gmock_mutex.AssertHeld();
811 for (MockObjectRegistry::StateMap::iterator it =
812 g_mock_object_registry.states().begin();
813 it != g_mock_object_registry.states().end(); ++it) {
814 FunctionMockers& mockers = it->second.function_mockers;
815 if (mockers.erase(mocker) > 0) {
817 if (mockers.empty()) {
818 g_mock_object_registry.states().erase(it);
826 void Mock::ClearDefaultActionsLocked(
void* mock_obj)
828 internal::g_gmock_mutex.AssertHeld();
830 if (g_mock_object_registry.states().count(mock_obj) == 0) {
837 FunctionMockers& mockers =
838 g_mock_object_registry.states()[mock_obj].function_mockers;
839 for (FunctionMockers::const_iterator it = mockers.begin();
840 it != mockers.end(); ++it) {
841 (*it)->ClearDefaultActionsLocked();
848 Expectation::Expectation() {}
850 Expectation::Expectation(
851 const std::shared_ptr<internal::ExpectationBase>& an_expectation_base)
852 : expectation_base_(an_expectation_base) {}
854 Expectation::~Expectation() {}
857 void Sequence::AddExpectation(
const Expectation& expectation)
const {
858 if (*last_expectation_ != expectation) {
859 if (last_expectation_->expectation_base() !=
nullptr) {
860 expectation.expectation_base()->immediate_prerequisites_
861 += *last_expectation_;
863 *last_expectation_ = expectation;
868 InSequence::InSequence() {
871 sequence_created_ =
true;
873 sequence_created_ =
false;
879 InSequence::~InSequence() {
880 if (sequence_created_) {
890 # pragma warning(pop)
CallReaction intToCallReaction(int mock_behavior)
void ReportUninterestingCall(CallReaction reaction, const std::string &msg)
GTEST_API_::std::string FormatFileLocation(const char *file, int line)
const char kInfoVerbosity[]
#define GTEST_LOCK_EXCLUDED_(locks)
::std::string first_used_test
GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char *file, int line, const std::string &message)
static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex)
GTEST_API_ bool LogIsVisible(LogSeverity severity)
GTEST_API_ Cardinality Exactly(int n)
void Assert(bool condition, const char *file, int line, const std::string &msg)
#define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
const char * first_used_file
FunctionMockers function_mockers
GTEST_API_ ThreadLocal< Sequence * > g_gmock_implicit_sequence
::std::string first_used_test_suite
void Expect(bool condition, const char *file, int line, const std::string &msg)
GTEST_API_ void Log(LogSeverity severity, const std::string &message, int stack_frames_to_skip)