36 #include "gmock/gmock-spec-builders.h"
47 #include "gmock/gmock.h"
48 #include "gtest/gtest.h"
49 #include "gtest/internal/gtest-port.h"
51 #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
59 # pragma warning(push)
60 # pragma warning(disable:4800)
75 ::std::ostringstream
s;
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().");
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 =
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);
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) {
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(),
487 #if GTEST_HAS_EXCEPTIONS
489 result = perform_action();
495 result = perform_action();
498 if (
result !=
nullptr)
result->PrintAsActionResult(&ss);
505 Expectation 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) {
516 Assert(
false, __FILE__, __LINE__,
"Cannot find expectation.");
525 bool 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) {
583 typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
588 struct MockObjectState {
606 class MockObjectRegistry {
609 typedef std::map<const void*, MockObjectState> StateMap;
615 ~MockObjectRegistry() {
618 int leaked_count = 0;
621 if (
it->second.leakable)
627 const MockObjectState&
state =
it->second;
629 state.first_used_line);
630 std::cout <<
" ERROR: this mock object";
631 if (
state.first_used_test !=
"") {
632 std::cout <<
" (used in test " <<
state.first_used_test_suite <<
"."
633 <<
state.first_used_test <<
")";
635 std::cout <<
" should be deleted but never is. Its address is @"
639 if (leaked_count > 0) {
640 std::cout <<
"\nERROR: " << leaked_count <<
" leaked mock "
641 << (leaked_count == 1 ?
"object" :
"objects")
642 <<
" found at program exit. Expectations on a mock object are "
643 "verified when the object is destructed. Leaking a mock "
644 "means that its expectations aren't verified, which is "
645 "usually a test bug. If you really intend to leak a mock, "
646 "you can suppress this error using "
647 "testing::Mock::AllowLeak(mock_object), or you may use a "
648 "fake or stub instead of a mock.\n";
659 StateMap& states() {
return states_; }
666 MockObjectRegistry g_mock_object_registry;
670 std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
674 void SetReactionOnUninterestingCalls(
const void* mock_obj,
678 g_uninteresting_call_reaction[mock_obj] = reaction;
685 void Mock::AllowUninterestingCalls(
const void* mock_obj)
692 void Mock::WarnUninterestingCalls(
const void* mock_obj)
699 void Mock::FailUninterestingCalls(
const void* mock_obj)
706 void Mock::UnregisterCallReaction(
const void* mock_obj)
709 g_uninteresting_call_reaction.erase(mock_obj);
715 const void* mock_obj)
718 return (g_uninteresting_call_reaction.count(mock_obj) == 0)
721 : g_uninteresting_call_reaction[mock_obj];
726 void Mock::AllowLeak(
const void* mock_obj)
729 g_mock_object_registry.states()[mock_obj].leakable =
true;
735 bool Mock::VerifyAndClearExpectations(
void* mock_obj)
738 return VerifyAndClearExpectationsLocked(mock_obj);
744 bool Mock::VerifyAndClear(
void* mock_obj)
747 ClearDefaultActionsLocked(mock_obj);
748 return VerifyAndClearExpectationsLocked(mock_obj);
754 bool 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;
779 bool Mock::IsNaggy(
void* mock_obj)
781 return Mock::GetReactionOnUninterestingCalls(mock_obj) ==
internal::kWarn;
783 bool Mock::IsNice(
void* mock_obj)
787 bool Mock::IsStrict(
void* mock_obj)
789 return Mock::GetReactionOnUninterestingCalls(mock_obj) ==
internal::kFail;
793 void Mock::Register(
const void* mock_obj,
794 internal::UntypedFunctionMockerBase* mocker)
797 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
803 void Mock::RegisterUseByOnCallOrExpectCall(
const void* mock_obj,
807 MockObjectState&
state = g_mock_object_registry.states()[mock_obj];
808 if (
state.first_used_file ==
nullptr) {
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();
824 void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
826 internal::g_gmock_mutex.AssertHeld();
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);
842 void 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();
867 const std::shared_ptr<internal::ExpectationBase>& an_expectation_base)
868 : expectation_base_(an_expectation_base) {}
870 Expectation::~Expectation() {}
875 if (last_expectation_->expectation_base() !=
nullptr) {
876 expectation.expectation_base()->immediate_prerequisites_
877 += *last_expectation_;
884 InSequence::InSequence() {
887 sequence_created_ =
true;
889 sequence_created_ =
false;
895 InSequence::~InSequence() {
896 if (sequence_created_) {
906 # pragma warning(pop)