37 #include "gmock/gmock-spec-builders.h" 44 #include "gmock/gmock.h" 45 #include "gtest/gtest.h" 47 #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC 60 const char* file,
int line,
62 ::std::ostringstream
s;
63 s << file <<
":" << line <<
": " << message << ::std::endl;
64 Log(severity, s.str(), 0);
70 const string& a_source_text)
73 source_text_(a_source_text),
74 cardinality_specified_(false),
78 extra_matcher_specified_(false),
79 repeated_action_specified_(false),
80 retires_on_saturation_(false),
82 action_count_checked_(false) {}
85 ExpectationBase::~ExpectationBase() {}
89 void ExpectationBase::SpecifyCardinality(
const Cardinality& a_cardinality) {
90 cardinality_specified_ =
true;
91 cardinality_ = a_cardinality;
95 void ExpectationBase::RetireAllPreRequisites()
104 it != immediate_prerequisites_.end(); ++it) {
105 ExpectationBase*
const prerequisite = it->expectation_base().get();
106 if (!prerequisite->is_retired()) {
107 prerequisite->RetireAllPreRequisites();
108 prerequisite->Retire();
115 bool ExpectationBase::AllPrerequisitesAreSatisfied()
const 117 g_gmock_mutex.AssertHeld();
119 it != immediate_prerequisites_.end(); ++it) {
120 if (!(it->expectation_base()->IsSatisfied()) ||
121 !(it->expectation_base()->AllPrerequisitesAreSatisfied()))
128 void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result)
const 130 g_gmock_mutex.AssertHeld();
132 it != immediate_prerequisites_.end(); ++it) {
133 if (it->expectation_base()->IsSatisfied()) {
136 if (it->expectation_base()->call_count_ == 0) {
137 it->expectation_base()->FindUnsatisfiedPrerequisites(result);
150 void ExpectationBase::DescribeCallCountTo(::std::ostream* os)
const 152 g_gmock_mutex.AssertHeld();
155 *os <<
" Expected: to be ";
156 cardinality().DescribeTo(os);
157 *os <<
"\n Actual: ";
162 *os <<
" - " << (IsOverSaturated() ?
"over-saturated" :
163 IsSaturated() ?
"saturated" :
164 IsSatisfied() ?
"satisfied" :
"unsatisfied")
166 << (is_retired() ?
"retired" :
"active");
173 void ExpectationBase::CheckActionCountIfNotDone()
const 175 bool should_check =
false;
178 if (!action_count_checked_) {
179 action_count_checked_ =
true;
185 if (!cardinality_specified_) {
192 const int action_count =
static_cast<int>(untyped_actions_.size());
193 const int upper_bound = cardinality().ConservativeUpperBound();
194 const int lower_bound = cardinality().ConservativeLowerBound();
197 if (action_count > upper_bound ||
198 (action_count == upper_bound && repeated_action_specified_)) {
200 }
else if (0 < action_count && action_count < lower_bound &&
201 !repeated_action_specified_) {
207 ::std::stringstream ss;
208 DescribeLocationTo(&ss);
209 ss <<
"Too " << (too_many ?
"many" :
"few")
210 <<
" actions specified in " << source_text() <<
"...\n" 211 <<
"Expected to be ";
212 cardinality().DescribeTo(&ss);
213 ss <<
", but has " << (too_many ?
"" :
"only ")
214 << action_count <<
" WillOnce()" 215 << (action_count == 1 ?
"" :
"s");
216 if (repeated_action_specified_) {
217 ss <<
" and a WillRepeatedly()";
225 void ExpectationBase::UntypedTimes(
const Cardinality& a_cardinality) {
226 if (last_clause_ == kTimes) {
227 ExpectSpecProperty(
false,
228 ".Times() cannot appear " 229 "more than once in an EXPECT_CALL().");
231 ExpectSpecProperty(last_clause_ < kTimes,
232 ".Times() cannot appear after " 233 ".InSequence(), .WillOnce(), .WillRepeatedly(), " 234 "or .RetiresOnSaturation().");
236 last_clause_ = kTimes;
238 SpecifyCardinality(a_cardinality);
249 const int stack_frames_to_skip =
253 Log(
kInfo, msg, stack_frames_to_skip);
258 "\nNOTE: You can safely ignore the above warning unless this " 259 "call should not happen. Do not suppress it by blindly adding " 260 "an EXPECT_CALL() if you don't mean to enforce the call. " 261 "See https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#" 262 "knowing-when-to-expect for details.\n",
263 stack_frames_to_skip);
266 Expect(
false, NULL, -1, msg);
270 UntypedFunctionMockerBase::UntypedFunctionMockerBase()
271 : mock_obj_(NULL),
name_(
"") {}
273 UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
279 void UntypedFunctionMockerBase::RegisterOwner(
const void* mock_obj)
283 mock_obj_ = mock_obj;
285 Mock::Register(mock_obj,
this);
291 void UntypedFunctionMockerBase::SetOwnerAndName(
const void* mock_obj,
297 mock_obj_ = mock_obj;
303 const void* UntypedFunctionMockerBase::MockObject()
const 305 const void* mock_obj;
310 Assert(mock_obj_ != NULL, __FILE__, __LINE__,
311 "MockObject() must not be called before RegisterOwner() or " 312 "SetOwnerAndName() has been called.");
313 mock_obj = mock_obj_;
320 const char* UntypedFunctionMockerBase::Name()
const 328 "Name() must not be called before SetOwnerAndName() has " 338 UntypedActionResultHolderBase*
339 UntypedFunctionMockerBase::UntypedInvokeWith(
const void*
const untyped_args)
341 if (untyped_expectations_.size() == 0) {
350 Mock::GetReactionOnUninterestingCalls(MockObject());
355 const bool need_to_report_uninteresting_call =
366 if (!need_to_report_uninteresting_call) {
368 return this->UntypedPerformDefaultAction(untyped_args,
"");
372 ::std::stringstream ss;
373 this->UntypedDescribeUninterestingCall(untyped_args, &ss);
376 UntypedActionResultHolderBase*
const result =
377 this->UntypedPerformDefaultAction(untyped_args, ss.str());
381 result->PrintAsActionResult(&ss);
387 bool is_excessive =
false;
388 ::std::stringstream ss;
389 ::std::stringstream why;
390 ::std::stringstream loc;
391 const void* untyped_action = NULL;
395 const ExpectationBase*
const untyped_expectation =
396 this->UntypedFindMatchingExpectation(
397 untyped_args, &untyped_action, &is_excessive,
399 const bool found = untyped_expectation != NULL;
404 const bool need_to_report_call =
406 if (!need_to_report_call) {
409 untyped_action == NULL ?
410 this->UntypedPerformDefaultAction(untyped_args,
"") :
411 this->UntypedPerformAction(untyped_action, untyped_args);
414 ss <<
" Function call: " << Name();
415 this->UntypedPrintArgs(untyped_args, &ss);
419 if (found && !is_excessive) {
420 untyped_expectation->DescribeLocationTo(&loc);
423 UntypedActionResultHolderBase*
const result =
424 untyped_action == NULL ?
425 this->UntypedPerformDefaultAction(untyped_args, ss.str()) :
426 this->UntypedPerformAction(untyped_action, untyped_args);
428 result->PrintAsActionResult(&ss);
429 ss <<
"\n" << why.str();
433 Expect(
false, NULL, -1, ss.str());
434 }
else if (is_excessive) {
436 Expect(
false, untyped_expectation->file(),
437 untyped_expectation->line(), ss.str());
441 Log(
kInfo, loc.str() + ss.str(), 2);
449 Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
450 for (UntypedExpectations::const_iterator it =
451 untyped_expectations_.begin();
452 it != untyped_expectations_.end(); ++it) {
453 if (it->get() == exp) {
454 return Expectation(*it);
458 Assert(
false, __FILE__, __LINE__,
"Cannot find expectation.");
459 return Expectation();
467 bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
469 g_gmock_mutex.AssertHeld();
470 bool expectations_met =
true;
471 for (UntypedExpectations::const_iterator it =
472 untyped_expectations_.begin();
473 it != untyped_expectations_.end(); ++it) {
474 ExpectationBase*
const untyped_expectation = it->get();
475 if (untyped_expectation->IsOverSaturated()) {
479 expectations_met =
false;
480 }
else if (!untyped_expectation->IsSatisfied()) {
481 expectations_met =
false;
482 ::std::stringstream ss;
483 ss <<
"Actual function call count doesn't match " 484 << untyped_expectation->source_text() <<
"...\n";
488 untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
489 untyped_expectation->DescribeCallCountTo(&ss);
490 Expect(
false, untyped_expectation->file(),
491 untyped_expectation->line(), ss.str());
502 UntypedExpectations expectations_to_delete;
503 untyped_expectations_.swap(expectations_to_delete);
505 g_gmock_mutex.Unlock();
506 expectations_to_delete.clear();
507 g_gmock_mutex.Lock();
509 return expectations_met;
518 typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
523 struct MockObjectState {
541 class MockObjectRegistry {
544 typedef std::map<const void*, MockObjectState> StateMap;
550 ~MockObjectRegistry() {
557 int leaked_count = 0;
558 for (StateMap::const_iterator it =
states_.begin(); it !=
states_.end();
560 if (it->second.leakable)
566 const MockObjectState&
state = it->second;
568 state.first_used_line);
569 std::cout <<
" ERROR: this mock object";
570 if (state.first_used_test !=
"") {
571 std::cout <<
" (used in test " << state.first_used_test_case <<
"." 572 << state.first_used_test <<
")";
574 std::cout <<
" should be deleted but never is. Its address is @" 578 if (leaked_count > 0) {
579 std::cout <<
"\nERROR: " << leaked_count
580 <<
" leaked mock " << (leaked_count == 1 ?
"object" :
"objects")
581 <<
" found at program exit.\n";
592 StateMap& states() {
return states_; }
599 MockObjectRegistry g_mock_object_registry;
603 std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
607 void SetReactionOnUninterestingCalls(
const void* mock_obj,
611 g_uninteresting_call_reaction[mock_obj] = reaction;
618 void Mock::AllowUninterestingCalls(
const void* mock_obj)
625 void Mock::WarnUninterestingCalls(
const void* mock_obj)
632 void Mock::FailUninterestingCalls(
const void* mock_obj)
639 void Mock::UnregisterCallReaction(
const void* mock_obj)
642 g_uninteresting_call_reaction.erase(mock_obj);
648 const void* mock_obj)
651 return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
657 void Mock::AllowLeak(
const void* mock_obj)
660 g_mock_object_registry.states()[mock_obj].leakable =
true;
666 bool Mock::VerifyAndClearExpectations(
void* mock_obj)
669 return VerifyAndClearExpectationsLocked(mock_obj);
675 bool Mock::VerifyAndClear(
void* mock_obj)
678 ClearDefaultActionsLocked(mock_obj);
679 return VerifyAndClearExpectationsLocked(mock_obj);
685 bool Mock::VerifyAndClearExpectationsLocked(
void* mock_obj)
687 internal::g_gmock_mutex.AssertHeld();
688 if (g_mock_object_registry.states().count(mock_obj) == 0) {
695 bool expectations_met =
true;
696 FunctionMockers& mockers =
697 g_mock_object_registry.states()[mock_obj].function_mockers;
698 for (FunctionMockers::const_iterator it = mockers.begin();
699 it != mockers.end(); ++it) {
700 if (!(*it)->VerifyAndClearExpectationsLocked()) {
701 expectations_met =
false;
707 return expectations_met;
711 void Mock::Register(
const void* mock_obj,
712 internal::UntypedFunctionMockerBase* mocker)
715 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
721 void Mock::RegisterUseByOnCallOrExpectCall(
const void* mock_obj,
722 const char* file,
int line)
725 MockObjectState&
state = g_mock_object_registry.states()[mock_obj];
726 if (state.first_used_file == NULL) {
727 state.first_used_file = file;
728 state.first_used_line = line;
729 const TestInfo*
const test_info =
731 if (test_info != NULL) {
735 state.first_used_test_case = test_info->test_case_name();
736 state.first_used_test = test_info->name();
745 void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
747 internal::g_gmock_mutex.AssertHeld();
748 for (MockObjectRegistry::StateMap::iterator it =
749 g_mock_object_registry.states().begin();
750 it != g_mock_object_registry.states().end(); ++it) {
751 FunctionMockers& mockers = it->second.function_mockers;
752 if (mockers.erase(mocker) > 0) {
754 if (mockers.empty()) {
755 g_mock_object_registry.states().erase(it);
763 void Mock::ClearDefaultActionsLocked(
void* mock_obj)
765 internal::g_gmock_mutex.AssertHeld();
767 if (g_mock_object_registry.states().count(mock_obj) == 0) {
774 FunctionMockers& mockers =
775 g_mock_object_registry.states()[mock_obj].function_mockers;
776 for (FunctionMockers::const_iterator it = mockers.begin();
777 it != mockers.end(); ++it) {
778 (*it)->ClearDefaultActionsLocked();
788 const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base)
789 : expectation_base_(an_expectation_base) {}
795 if (*last_expectation_ != expectation) {
796 if (last_expectation_->expectation_base() != NULL) {
797 expectation.expectation_base()->immediate_prerequisites_
798 += *last_expectation_;
800 *last_expectation_ = expectation;
const char * first_used_file
GTEST_API_ ThreadLocal< Sequence * > g_gmock_implicit_sequence
FunctionMockers function_mockers
static void DescribeActualCallCountTo(int actual_call_count,::std::ostream *os)
::std::string FormatFileLocation(const char *file, int line)
::std::string first_used_test
ExpectationBase(const char *file, int line, const string &source_text)
const char kInfoVerbosity[]
::std::string first_used_test_case
Expectation::Set::const_iterator const_iterator
void ReportUninterestingCall(CallReaction reaction, const string &msg)
void Expect(bool condition, const char *file, int line, const string &msg)
void AddExpectation(const Expectation &expectation) const
GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char *file, int line, const string &message)
GTEST_API_ void Log(LogSeverity severity, const string &message, int stack_frames_to_skip)
static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex)
const TestInfo * current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_)
GTEST_API_ bool LogIsVisible(LogSeverity severity)
GTEST_API_ Cardinality Exactly(int n)
#define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
void Assert(bool condition, const char *file, int line)
#define GTEST_LOCK_EXCLUDED_(locks)
static UnitTest * GetInstance()