| 1 |
// Copyright 2007, Google Inc. |
| 2 |
// All rights reserved. |
| 3 |
// |
| 4 |
// Redistribution and use in source and binary forms, with or without |
| 5 |
// modification, are permitted provided that the following conditions are |
| 6 |
// met: |
| 7 |
// |
| 8 |
// * Redistributions of source code must retain the above copyright |
| 9 |
// notice, this list of conditions and the following disclaimer. |
| 10 |
// * Redistributions in binary form must reproduce the above |
| 11 |
// copyright notice, this list of conditions and the following disclaimer |
| 12 |
// in the documentation and/or other materials provided with the |
| 13 |
// distribution. |
| 14 |
// * Neither the name of Google Inc. nor the names of its |
| 15 |
// contributors may be used to endorse or promote products derived from |
| 16 |
// this software without specific prior written permission. |
| 17 |
// |
| 18 |
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 19 |
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 20 |
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| 21 |
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
| 22 |
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 23 |
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
| 24 |
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| 25 |
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| 26 |
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 27 |
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 28 |
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 29 |
|
| 30 |
|
| 31 |
// Google Mock - a framework for writing C++ mock classes. |
| 32 |
// |
| 33 |
// This file implements the spec builder syntax (ON_CALL and |
| 34 |
// EXPECT_CALL). |
| 35 |
|
| 36 |
#include "gmock/gmock-spec-builders.h" |
| 37 |
|
| 38 |
#include <stdlib.h> |
| 39 |
#include <iostream> // NOLINT |
| 40 |
#include <map> |
| 41 |
#include <memory> |
| 42 |
#include <set> |
| 43 |
#include <string> |
| 44 |
#include <vector> |
| 45 |
#include "gmock/gmock.h" |
| 46 |
#include "gtest/gtest.h" |
| 47 |
|
| 48 |
#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC |
| 49 |
# include <unistd.h> // NOLINT |
| 50 |
#endif |
| 51 |
|
| 52 |
// Silence C4800 (C4800: 'int *const ': forcing value |
| 53 |
// to bool 'true' or 'false') for MSVC 15 |
| 54 |
#ifdef _MSC_VER |
| 55 |
#if _MSC_VER == 1900 |
| 56 |
# pragma warning(push) |
| 57 |
# pragma warning(disable:4800) |
| 58 |
#endif |
| 59 |
#endif |
| 60 |
|
| 61 |
namespace testing { |
| 62 |
namespace internal { |
| 63 |
|
| 64 |
// Protects the mock object registry (in class Mock), all function |
| 65 |
// mockers, and all expectations. |
| 66 |
GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex); |
| 67 |
|
| 68 |
// Logs a message including file and line number information. |
| 69 |
GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, |
| 70 |
const char* file, int line, |
| 71 |
const std::string& message) { |
| 72 |
::std::ostringstream s; |
| 73 |
s << file << ":" << line << ": " << message << ::std::endl; |
| 74 |
Log(severity, s.str(), 0); |
| 75 |
} |
| 76 |
|
| 77 |
// Constructs an ExpectationBase object. |
| 78 |
ExpectationBase::ExpectationBase(const char* a_file, int a_line, |
| 79 |
const std::string& a_source_text) |
| 80 |
: file_(a_file), |
| 81 |
line_(a_line), |
| 82 |
source_text_(a_source_text), |
| 83 |
cardinality_specified_(false), |
| 84 |
cardinality_(Exactly(1)), |
| 85 |
call_count_(0), |
| 86 |
retired_(false), |
| 87 |
extra_matcher_specified_(false), |
| 88 |
repeated_action_specified_(false), |
| 89 |
retires_on_saturation_(false), |
| 90 |
last_clause_(kNone), |
| 91 |
action_count_checked_(false) {} |
| 92 |
|
| 93 |
// Destructs an ExpectationBase object. |
| 94 |
ExpectationBase::~ExpectationBase() {} |
| 95 |
|
| 96 |
// Explicitly specifies the cardinality of this expectation. Used by |
| 97 |
// the subclasses to implement the .Times() clause. |
| 98 |
void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) { |
| 99 |
cardinality_specified_ = true; |
| 100 |
cardinality_ = a_cardinality; |
| 101 |
} |
| 102 |
|
| 103 |
// Retires all pre-requisites of this expectation. |
| 104 |
void ExpectationBase::RetireAllPreRequisites() |
| 105 |
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { |
| 106 |
if (is_retired()) { |
| 107 |
// We can take this short-cut as we never retire an expectation |
| 108 |
// until we have retired all its pre-requisites. |
| 109 |
return; |
| 110 |
} |
| 111 |
|
| 112 |
::std::vector<ExpectationBase*> expectations(1, this); |
| 113 |
while (!expectations.empty()) { |
| 114 |
ExpectationBase* exp = expectations.back(); |
| 115 |
expectations.pop_back(); |
| 116 |
|
| 117 |
for (ExpectationSet::const_iterator it = |
| 118 |
exp->immediate_prerequisites_.begin(); |
| 119 |
it != exp->immediate_prerequisites_.end(); ++it) { |
| 120 |
ExpectationBase* next = it->expectation_base().get(); |
| 121 |
if (!next->is_retired()) { |
| 122 |
next->Retire(); |
| 123 |
expectations.push_back(next); |
| 124 |
} |
| 125 |
} |
| 126 |
} |
| 127 |
} |
| 128 |
|
| 129 |
// Returns true if and only if all pre-requisites of this expectation |
| 130 |
// have been satisfied. |
| 131 |
bool ExpectationBase::AllPrerequisitesAreSatisfied() const |
| 132 |
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { |
| 133 |
g_gmock_mutex.AssertHeld(); |
| 134 |
::std::vector<const ExpectationBase*> expectations(1, this); |
| 135 |
while (!expectations.empty()) { |
| 136 |
const ExpectationBase* exp = expectations.back(); |
| 137 |
expectations.pop_back(); |
| 138 |
|
| 139 |
for (ExpectationSet::const_iterator it = |
| 140 |
exp->immediate_prerequisites_.begin(); |
| 141 |
it != exp->immediate_prerequisites_.end(); ++it) { |
| 142 |
const ExpectationBase* next = it->expectation_base().get(); |
| 143 |
if (!next->IsSatisfied()) return false; |
| 144 |
expectations.push_back(next); |
| 145 |
} |
| 146 |
} |
| 147 |
return true; |
| 148 |
} |
| 149 |
|
| 150 |
// Adds unsatisfied pre-requisites of this expectation to 'result'. |
| 151 |
void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const |
| 152 |
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { |
| 153 |
g_gmock_mutex.AssertHeld(); |
| 154 |
::std::vector<const ExpectationBase*> expectations(1, this); |
| 155 |
while (!expectations.empty()) { |
| 156 |
const ExpectationBase* exp = expectations.back(); |
| 157 |
expectations.pop_back(); |
| 158 |
|
| 159 |
for (ExpectationSet::const_iterator it = |
| 160 |
exp->immediate_prerequisites_.begin(); |
| 161 |
it != exp->immediate_prerequisites_.end(); ++it) { |
| 162 |
const ExpectationBase* next = it->expectation_base().get(); |
| 163 |
|
| 164 |
if (next->IsSatisfied()) { |
| 165 |
// If *it is satisfied and has a call count of 0, some of its |
| 166 |
// pre-requisites may not be satisfied yet. |
| 167 |
if (next->call_count_ == 0) { |
| 168 |
expectations.push_back(next); |
| 169 |
} |
| 170 |
} else { |
| 171 |
// Now that we know next is unsatisfied, we are not so interested |
| 172 |
// in whether its pre-requisites are satisfied. Therefore we |
| 173 |
// don't iterate into it here. |
| 174 |
*result += *it; |
| 175 |
} |
| 176 |
} |
| 177 |
} |
| 178 |
} |
| 179 |
|
| 180 |
// Describes how many times a function call matching this |
| 181 |
// expectation has occurred. |
| 182 |
void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const |
| 183 |
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { |
| 184 |
g_gmock_mutex.AssertHeld(); |
| 185 |
|
| 186 |
// Describes how many times the function is expected to be called. |
| 187 |
*os << " Expected: to be "; |
| 188 |
cardinality().DescribeTo(os); |
| 189 |
*os << "\n Actual: "; |
| 190 |
Cardinality::DescribeActualCallCountTo(call_count(), os); |
| 191 |
|
| 192 |
// Describes the state of the expectation (e.g. is it satisfied? |
| 193 |
// is it active?). |
| 194 |
*os << " - " << (IsOverSaturated() ? "over-saturated" : |
| 195 |
IsSaturated() ? "saturated" : |
| 196 |
IsSatisfied() ? "satisfied" : "unsatisfied") |
| 197 |
<< " and " |
| 198 |
<< (is_retired() ? "retired" : "active"); |
| 199 |
} |
| 200 |
|
| 201 |
// Checks the action count (i.e. the number of WillOnce() and |
| 202 |
// WillRepeatedly() clauses) against the cardinality if this hasn't |
| 203 |
// been done before. Prints a warning if there are too many or too |
| 204 |
// few actions. |
| 205 |
void ExpectationBase::CheckActionCountIfNotDone() const |
| 206 |
GTEST_LOCK_EXCLUDED_(mutex_) { |
| 207 |
bool should_check = false; |
| 208 |
{ |
| 209 |
MutexLock l(&mutex_); |
| 210 |
if (!action_count_checked_) { |
| 211 |
action_count_checked_ = true; |
| 212 |
should_check = true; |
| 213 |
} |
| 214 |
} |
| 215 |
|
| 216 |
if (should_check) { |
| 217 |
if (!cardinality_specified_) { |
| 218 |
// The cardinality was inferred - no need to check the action |
| 219 |
// count against it. |
| 220 |
return; |
| 221 |
} |
| 222 |
|
| 223 |
// The cardinality was explicitly specified. |
| 224 |
const int action_count = static_cast<int>(untyped_actions_.size()); |
| 225 |
const int upper_bound = cardinality().ConservativeUpperBound(); |
| 226 |
const int lower_bound = cardinality().ConservativeLowerBound(); |
| 227 |
bool too_many; // True if there are too many actions, or false |
| 228 |
// if there are too few. |
| 229 |
if (action_count > upper_bound || |
| 230 |
(action_count == upper_bound && repeated_action_specified_)) { |
| 231 |
too_many = true; |
| 232 |
} else if (0 < action_count && action_count < lower_bound && |
| 233 |
!repeated_action_specified_) { |
| 234 |
too_many = false; |
| 235 |
} else { |
| 236 |
return; |
| 237 |
} |
| 238 |
|
| 239 |
::std::stringstream ss; |
| 240 |
DescribeLocationTo(&ss); |
| 241 |
ss << "Too " << (too_many ? "many" : "few") |
| 242 |
<< " actions specified in " << source_text() << "...\n" |
| 243 |
<< "Expected to be "; |
| 244 |
cardinality().DescribeTo(&ss); |
| 245 |
ss << ", but has " << (too_many ? "" : "only ") |
| 246 |
<< action_count << " WillOnce()" |
| 247 |
<< (action_count == 1 ? "" : "s"); |
| 248 |
if (repeated_action_specified_) { |
| 249 |
ss << " and a WillRepeatedly()"; |
| 250 |
} |
| 251 |
ss << "."; |
| 252 |
Log(kWarning, ss.str(), -1); // -1 means "don't print stack trace". |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
// Implements the .Times() clause. |
| 257 |
void ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) { |
| 258 |
if (last_clause_ == kTimes) { |
| 259 |
ExpectSpecProperty(false, |
| 260 |
".Times() cannot appear " |
| 261 |
"more than once in an EXPECT_CALL()."); |
| 262 |
} else { |
| 263 |
ExpectSpecProperty(last_clause_ < kTimes, |
| 264 |
".Times() cannot appear after " |
| 265 |
".InSequence(), .WillOnce(), .WillRepeatedly(), " |
| 266 |
"or .RetiresOnSaturation()."); |
| 267 |
} |
| 268 |
last_clause_ = kTimes; |
| 269 |
|
| 270 |
SpecifyCardinality(a_cardinality); |
| 271 |
} |
| 272 |
|
| 273 |
// Points to the implicit sequence introduced by a living InSequence |
| 274 |
// object (if any) in the current thread or NULL. |
| 275 |
GTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence; |
| 276 |
|
| 277 |
// Reports an uninteresting call (whose description is in msg) in the |
| 278 |
// manner specified by 'reaction'. |
| 279 |
void ReportUninterestingCall(CallReaction reaction, const std::string& msg) { |
| 280 |
// Include a stack trace only if --gmock_verbose=info is specified. |
| 281 |
const int stack_frames_to_skip = |
| 282 |
GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1; |
| 283 |
switch (reaction) { |
| 284 |
case kAllow: |
| 285 |
Log(kInfo, msg, stack_frames_to_skip); |
| 286 |
break; |
| 287 |
case kWarn: |
| 288 |
Log(kWarning, |
| 289 |
msg + |
| 290 |
"\nNOTE: You can safely ignore the above warning unless this " |
| 291 |
"call should not happen. Do not suppress it by blindly adding " |
| 292 |
"an EXPECT_CALL() if you don't mean to enforce the call. " |
| 293 |
"See " |
| 294 |
"https://github.com/google/googletest/blob/master/googlemock/" |
| 295 |
"docs/cook_book.md#" |
| 296 |
"knowing-when-to-expect for details.\n", |
| 297 |
stack_frames_to_skip); |
| 298 |
break; |
| 299 |
default: // FAIL |
| 300 |
Expect(false, nullptr, -1, msg); |
| 301 |
} |
| 302 |
} |
| 303 |
|
| 304 |
UntypedFunctionMockerBase::UntypedFunctionMockerBase() |
| 305 |
: mock_obj_(nullptr), name_("") {} |
| 306 |
|
| 307 |
UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {} |
| 308 |
|
| 309 |
// Sets the mock object this mock method belongs to, and registers |
| 310 |
// this information in the global mock registry. Will be called |
| 311 |
// whenever an EXPECT_CALL() or ON_CALL() is executed on this mock |
| 312 |
// method. |
| 313 |
void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj) |
| 314 |
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { |
| 315 |
{ |
| 316 |
MutexLock l(&g_gmock_mutex); |
| 317 |
mock_obj_ = mock_obj; |
| 318 |
} |
| 319 |
Mock::Register(mock_obj, this); |
| 320 |
} |
| 321 |
|
| 322 |
// Sets the mock object this mock method belongs to, and sets the name |
| 323 |
// of the mock function. Will be called upon each invocation of this |
| 324 |
// mock function. |
| 325 |
void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj, |
| 326 |
const char* name) |
| 327 |
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { |
| 328 |
// We protect name_ under g_gmock_mutex in case this mock function |
| 329 |
// is called from two threads concurrently. |
| 330 |
MutexLock l(&g_gmock_mutex); |
| 331 |
mock_obj_ = mock_obj; |
| 332 |
name_ = name; |
| 333 |
} |
| 334 |
|
| 335 |
// Returns the name of the function being mocked. Must be called |
| 336 |
// after RegisterOwner() or SetOwnerAndName() has been called. |
| 337 |
const void* UntypedFunctionMockerBase::MockObject() const |
| 338 |
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { |
| 339 |
const void* mock_obj; |
| 340 |
{ |
| 341 |
// We protect mock_obj_ under g_gmock_mutex in case this mock |
| 342 |
// function is called from two threads concurrently. |
| 343 |
MutexLock l(&g_gmock_mutex); |
| 344 |
Assert(mock_obj_ != nullptr, __FILE__, __LINE__, |
| 345 |
"MockObject() must not be called before RegisterOwner() or " |
| 346 |
"SetOwnerAndName() has been called."); |
| 347 |
mock_obj = mock_obj_; |
| 348 |
} |
| 349 |
return mock_obj; |
| 350 |
} |
| 351 |
|
| 352 |
// Returns the name of this mock method. Must be called after |
| 353 |
// SetOwnerAndName() has been called. |
| 354 |
const char* UntypedFunctionMockerBase::Name() const |
| 355 |
GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { |
| 356 |
const char* name; |
| 357 |
{ |
| 358 |
// We protect name_ under g_gmock_mutex in case this mock |
| 359 |
// function is called from two threads concurrently. |
| 360 |
MutexLock l(&g_gmock_mutex); |
| 361 |
Assert(name_ != nullptr, __FILE__, __LINE__, |
| 362 |
"Name() must not be called before SetOwnerAndName() has " |
| 363 |
"been called."); |
| 364 |
name = name_; |
| 365 |
} |
| 366 |
return name; |
| 367 |
} |
| 368 |
|
| 369 |
// Calculates the result of invoking this mock function with the given |
| 370 |
// arguments, prints it, and returns it. The caller is responsible |
| 371 |
// for deleting the result. |
| 372 |
UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith( |
| 373 |
void* const untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { |
| 374 |
// See the definition of untyped_expectations_ for why access to it |
| 375 |
// is unprotected here. |
| 376 |
if (untyped_expectations_.size() == 0) { |
| 377 |
// No expectation is set on this mock method - we have an |
| 378 |
// uninteresting call. |
| 379 |
|
| 380 |
// We must get Google Mock's reaction on uninteresting calls |
| 381 |
// made on this mock object BEFORE performing the action, |
| 382 |
// because the action may DELETE the mock object and make the |
| 383 |
// following expression meaningless. |
| 384 |
const CallReaction reaction = |
| 385 |
Mock::GetReactionOnUninterestingCalls(MockObject()); |
| 386 |
|
| 387 |
// True if and only if we need to print this call's arguments and return |
| 388 |
// value. This definition must be kept in sync with |
| 389 |
// the behavior of ReportUninterestingCall(). |
| 390 |
const bool need_to_report_uninteresting_call = |
| 391 |
// If the user allows this uninteresting call, we print it |
| 392 |
// only when they want informational messages. |
| 393 |
reaction == kAllow ? LogIsVisible(kInfo) : |
| 394 |
// If the user wants this to be a warning, we print |
| 395 |
// it only when they want to see warnings. |
| 396 |
reaction == kWarn |
| 397 |
? LogIsVisible(kWarning) |
| 398 |
: |
| 399 |
// Otherwise, the user wants this to be an error, and we |
| 400 |
// should always print detailed information in the error. |
| 401 |
true; |
| 402 |
|
| 403 |
if (!need_to_report_uninteresting_call) { |
| 404 |
// Perform the action without printing the call information. |
| 405 |
return this->UntypedPerformDefaultAction( |
| 406 |
untyped_args, "Function call: " + std::string(Name())); |
| 407 |
} |
| 408 |
|
| 409 |
// Warns about the uninteresting call. |
| 410 |
::std::stringstream ss; |
| 411 |
this->UntypedDescribeUninterestingCall(untyped_args, &ss); |
| 412 |
|
| 413 |
// Calculates the function result. |
| 414 |
UntypedActionResultHolderBase* const result = |
| 415 |
this->UntypedPerformDefaultAction(untyped_args, ss.str()); |
| 416 |
|
| 417 |
// Prints the function result. |
| 418 |
if (result != nullptr) result->PrintAsActionResult(&ss); |
| 419 |
|
| 420 |
ReportUninterestingCall(reaction, ss.str()); |
| 421 |
return result; |
| 422 |
} |
| 423 |
|
| 424 |
bool is_excessive = false; |
| 425 |
::std::stringstream ss; |
| 426 |
::std::stringstream why; |
| 427 |
::std::stringstream loc; |
| 428 |
const void* untyped_action = nullptr; |
| 429 |
|
| 430 |
// The UntypedFindMatchingExpectation() function acquires and |
| 431 |
// releases g_gmock_mutex. |
| 432 |
const ExpectationBase* const untyped_expectation = |
| 433 |
this->UntypedFindMatchingExpectation( |
| 434 |
untyped_args, &untyped_action, &is_excessive, |
| 435 |
&ss, &why); |
| 436 |
const bool found = untyped_expectation != nullptr; |
| 437 |
|
| 438 |
// True if and only if we need to print the call's arguments |
| 439 |
// and return value. |
| 440 |
// This definition must be kept in sync with the uses of Expect() |
| 441 |
// and Log() in this function. |
| 442 |
const bool need_to_report_call = |
| 443 |
!found || is_excessive || LogIsVisible(kInfo); |
| 444 |
if (!need_to_report_call) { |
| 445 |
// Perform the action without printing the call information. |
| 446 |
return untyped_action == nullptr |
| 447 |
? this->UntypedPerformDefaultAction(untyped_args, "") |
| 448 |
: this->UntypedPerformAction(untyped_action, untyped_args); |
| 449 |
} |
| 450 |
|
| 451 |
ss << " Function call: " << Name(); |
| 452 |
this->UntypedPrintArgs(untyped_args, &ss); |
| 453 |
|
| 454 |
// In case the action deletes a piece of the expectation, we |
| 455 |
// generate the message beforehand. |
| 456 |
if (found && !is_excessive) { |
| 457 |
untyped_expectation->DescribeLocationTo(&loc); |
| 458 |
} |
| 459 |
|
| 460 |
UntypedActionResultHolderBase* const result = |
| 461 |
untyped_action == nullptr |
| 462 |
? this->UntypedPerformDefaultAction(untyped_args, ss.str()) |
| 463 |
: this->UntypedPerformAction(untyped_action, untyped_args); |
| 464 |
if (result != nullptr) result->PrintAsActionResult(&ss); |
| 465 |
ss << "\n" << why.str(); |
| 466 |
|
| 467 |
if (!found) { |
| 468 |
// No expectation matches this call - reports a failure. |
| 469 |
Expect(false, nullptr, -1, ss.str()); |
| 470 |
} else if (is_excessive) { |
| 471 |
// We had an upper-bound violation and the failure message is in ss. |
| 472 |
Expect(false, untyped_expectation->file(), |
| 473 |
untyped_expectation->line(), ss.str()); |
| 474 |
} else { |
| 475 |
// We had an expected call and the matching expectation is |
| 476 |
// described in ss. |
| 477 |
Log(kInfo, loc.str() + ss.str(), 2); |
| 478 |
} |
| 479 |
|
| 480 |
return result; |
| 481 |
} |
| 482 |
|
| 483 |
// Returns an Expectation object that references and co-owns exp, |
| 484 |
// which must be an expectation on this mock function. |
| 485 |
Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) { |
| 486 |
// See the definition of untyped_expectations_ for why access to it |
| 487 |
// is unprotected here. |
| 488 |
for (UntypedExpectations::const_iterator it = |
| 489 |
untyped_expectations_.begin(); |
| 490 |
it != untyped_expectations_.end(); ++it) { |
| 491 |
if (it->get() == exp) { |
| 492 |
return Expectation(*it); |
| 493 |
} |
| 494 |
} |
| 495 |
|
| 496 |
Assert(false, __FILE__, __LINE__, "Cannot find expectation."); |
| 497 |
return Expectation(); |
| 498 |
// The above statement is just to make the code compile, and will |
| 499 |
// never be executed. |
| 500 |
} |
| 501 |
|
| 502 |
// Verifies that all expectations on this mock function have been |
| 503 |
// satisfied. Reports one or more Google Test non-fatal failures |
| 504 |
// and returns false if not. |
| 505 |
bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked() |
| 506 |
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { |
| 507 |
g_gmock_mutex.AssertHeld(); |
| 508 |
bool expectations_met = true; |
| 509 |
for (UntypedExpectations::const_iterator it = |
| 510 |
untyped_expectations_.begin(); |
| 511 |
it != untyped_expectations_.end(); ++it) { |
| 512 |
ExpectationBase* const untyped_expectation = it->get(); |
| 513 |
if (untyped_expectation->IsOverSaturated()) { |
| 514 |
// There was an upper-bound violation. Since the error was |
| 515 |
// already reported when it occurred, there is no need to do |
| 516 |
// anything here. |
| 517 |
expectations_met = false; |
| 518 |
} else if (!untyped_expectation->IsSatisfied()) { |
| 519 |
expectations_met = false; |
| 520 |
::std::stringstream ss; |
| 521 |
ss << "Actual function call count doesn't match " |
| 522 |
<< untyped_expectation->source_text() << "...\n"; |
| 523 |
// No need to show the source file location of the expectation |
| 524 |
// in the description, as the Expect() call that follows already |
| 525 |
// takes care of it. |
| 526 |
untyped_expectation->MaybeDescribeExtraMatcherTo(&ss); |
| 527 |
untyped_expectation->DescribeCallCountTo(&ss); |
| 528 |
Expect(false, untyped_expectation->file(), |
| 529 |
untyped_expectation->line(), ss.str()); |
| 530 |
} |
| 531 |
} |
| 532 |
|
| 533 |
// Deleting our expectations may trigger other mock objects to be deleted, for |
| 534 |
// example if an action contains a reference counted smart pointer to that |
| 535 |
// mock object, and that is the last reference. So if we delete our |
| 536 |
// expectations within the context of the global mutex we may deadlock when |
| 537 |
// this method is called again. Instead, make a copy of the set of |
| 538 |
// expectations to delete, clear our set within the mutex, and then clear the |
| 539 |
// copied set outside of it. |
| 540 |
UntypedExpectations expectations_to_delete; |
| 541 |
untyped_expectations_.swap(expectations_to_delete); |
| 542 |
|
| 543 |
g_gmock_mutex.Unlock(); |
| 544 |
expectations_to_delete.clear(); |
| 545 |
g_gmock_mutex.Lock(); |
| 546 |
|
| 547 |
return expectations_met; |
| 548 |
} |
| 549 |
|
| 550 |
CallReaction intToCallReaction(int mock_behavior) { |
| 551 |
if (mock_behavior >= kAllow && mock_behavior <= kFail) { |
| 552 |
return static_cast<internal::CallReaction>(mock_behavior); |
| 553 |
} |
| 554 |
return kWarn; |
| 555 |
} |
| 556 |
|
| 557 |
} // namespace internal |
| 558 |
|
| 559 |
// Class Mock. |
| 560 |
|
| 561 |
namespace { |
| 562 |
|
| 563 |
typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers; |
| 564 |
|
| 565 |
// The current state of a mock object. Such information is needed for |
| 566 |
// detecting leaked mock objects and explicitly verifying a mock's |
| 567 |
// expectations. |
| 568 |
struct MockObjectState { |
| 569 |
MockObjectState() |
| 570 |
: first_used_file(nullptr), first_used_line(-1), leakable(false) {} |
| 571 |
|
| 572 |
// Where in the source file an ON_CALL or EXPECT_CALL is first |
| 573 |
// invoked on this mock object. |
| 574 |
const char* first_used_file; |
| 575 |
int first_used_line; |
| 576 |
::std::string first_used_test_suite; |
| 577 |
::std::string first_used_test; |
| 578 |
bool leakable; // true if and only if it's OK to leak the object. |
| 579 |
FunctionMockers function_mockers; // All registered methods of the object. |
| 580 |
}; |
| 581 |
|
| 582 |
// A global registry holding the state of all mock objects that are |
| 583 |
// alive. A mock object is added to this registry the first time |
| 584 |
// Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It |
| 585 |
// is removed from the registry in the mock object's destructor. |
| 586 |
class MockObjectRegistry { |
| 587 |
public: |
| 588 |
// Maps a mock object (identified by its address) to its state. |
| 589 |
typedef std::map<const void*, MockObjectState> StateMap; |
| 590 |
|
| 591 |
// This destructor will be called when a program exits, after all |
| 592 |
// tests in it have been run. By then, there should be no mock |
| 593 |
// object alive. Therefore we report any living object as test |
| 594 |
// failure, unless the user explicitly asked us to ignore it. |
| 595 |
~MockObjectRegistry() { |
| 596 |
if (!GMOCK_FLAG(catch_leaked_mocks)) |
| 597 |
return; |
| 598 |
|
| 599 |
int leaked_count = 0; |
| 600 |
for (StateMap::const_iterator it = states_.begin(); it != states_.end(); |
| 601 |
++it) { |
| 602 |
if (it->second.leakable) // The user said it's fine to leak this object. |
| 603 |
continue; |
| 604 |
|
| 605 |
// FIXME: Print the type of the leaked object. |
| 606 |
// This can help the user identify the leaked object. |
| 607 |
std::cout << "\n"; |
| 608 |
const MockObjectState& state = it->second; |
| 609 |
std::cout << internal::FormatFileLocation(state.first_used_file, |
| 610 |
state.first_used_line); |
| 611 |
std::cout << " ERROR: this mock object"; |
| 612 |
if (state.first_used_test != "") { |
| 613 |
std::cout << " (used in test " << state.first_used_test_suite << "." |
| 614 |
<< state.first_used_test << ")"; |
| 615 |
} |
| 616 |
std::cout << " should be deleted but never is. Its address is @" |
| 617 |
<< it->first << "."; |
| 618 |
leaked_count++; |
| 619 |
} |
| 620 |
if (leaked_count > 0) { |
| 621 |
std::cout << "\nERROR: " << leaked_count << " leaked mock " |
| 622 |
<< (leaked_count == 1 ? "object" : "objects") |
| 623 |
<< " found at program exit. Expectations on a mock object is " |
| 624 |
"verified when the object is destructed. Leaking a mock " |
| 625 |
"means that its expectations aren't verified, which is " |
| 626 |
"usually a test bug. If you really intend to leak a mock, " |
| 627 |
"you can suppress this error using " |
| 628 |
"testing::Mock::AllowLeak(mock_object), or you may use a " |
| 629 |
"fake or stub instead of a mock.\n"; |
| 630 |
std::cout.flush(); |
| 631 |
::std::cerr.flush(); |
| 632 |
// RUN_ALL_TESTS() has already returned when this destructor is |
| 633 |
// called. Therefore we cannot use the normal Google Test |
| 634 |
// failure reporting mechanism. |
| 635 |
_exit(1); // We cannot call exit() as it is not reentrant and |
| 636 |
// may already have been called. |
| 637 |
} |
| 638 |
} |
| 639 |
|
| 640 |
StateMap& states() { return states_; } |
| 641 |
|
| 642 |
private: |
| 643 |
StateMap states_; |
| 644 |
}; |
| 645 |
|
| 646 |
// Protected by g_gmock_mutex. |
| 647 |
MockObjectRegistry g_mock_object_registry; |
| 648 |
|
| 649 |
// Maps a mock object to the reaction Google Mock should have when an |
| 650 |
// uninteresting method is called. Protected by g_gmock_mutex. |
| 651 |
std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction; |
| 652 |
|
| 653 |
// Sets the reaction Google Mock should have when an uninteresting |
| 654 |
// method of the given mock object is called. |
| 655 |
void SetReactionOnUninterestingCalls(const void* mock_obj, |
| 656 |
internal::CallReaction reaction) |
| 657 |
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { |
| 658 |
internal::MutexLock l(&internal::g_gmock_mutex); |
| 659 |
g_uninteresting_call_reaction[mock_obj] = reaction; |
| 660 |
} |
| 661 |
|
| 662 |
} // namespace |
| 663 |
|
| 664 |
// Tells Google Mock to allow uninteresting calls on the given mock |
| 665 |
// object. |
| 666 |
void Mock::AllowUninterestingCalls(const void* mock_obj) |
| 667 |
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { |
| 668 |
SetReactionOnUninterestingCalls(mock_obj, internal::kAllow); |
| 669 |
} |
| 670 |
|
| 671 |
// Tells Google Mock to warn the user about uninteresting calls on the |
| 672 |
// given mock object. |
| 673 |
void Mock::WarnUninterestingCalls(const void* mock_obj) |
| 674 |
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { |
| 675 |
SetReactionOnUninterestingCalls(mock_obj, internal::kWarn); |
| 676 |
} |
| 677 |
|
| 678 |
// Tells Google Mock to fail uninteresting calls on the given mock |
| 679 |
// object. |
| 680 |
void Mock::FailUninterestingCalls(const void* mock_obj) |
| 681 |
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { |
| 682 |
SetReactionOnUninterestingCalls(mock_obj, internal::kFail); |
| 683 |
} |
| 684 |
|
| 685 |
// Tells Google Mock the given mock object is being destroyed and its |
| 686 |
// entry in the call-reaction table should be removed. |
| 687 |
void Mock::UnregisterCallReaction(const void* mock_obj) |
| 688 |
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { |
| 689 |
internal::MutexLock l(&internal::g_gmock_mutex); |
| 690 |
g_uninteresting_call_reaction.erase(mock_obj); |
| 691 |
} |
| 692 |
|
| 693 |
// Returns the reaction Google Mock will have on uninteresting calls |
| 694 |
// made on the given mock object. |
| 695 |
internal::CallReaction Mock::GetReactionOnUninterestingCalls( |
| 696 |
const void* mock_obj) |
| 697 |
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { |
| 698 |
internal::MutexLock l(&internal::g_gmock_mutex); |
| 699 |
return (g_uninteresting_call_reaction.count(mock_obj) == 0) ? |
| 700 |
internal::intToCallReaction(GMOCK_FLAG(default_mock_behavior)) : |
| 701 |
g_uninteresting_call_reaction[mock_obj]; |
| 702 |
} |
| 703 |
|
| 704 |
// Tells Google Mock to ignore mock_obj when checking for leaked mock |
| 705 |
// objects. |
| 706 |
void Mock::AllowLeak(const void* mock_obj) |
| 707 |
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { |
| 708 |
internal::MutexLock l(&internal::g_gmock_mutex); |
| 709 |
g_mock_object_registry.states()[mock_obj].leakable = true; |
| 710 |
} |
| 711 |
|
| 712 |
// Verifies and clears all expectations on the given mock object. If |
| 713 |
// the expectations aren't satisfied, generates one or more Google |
| 714 |
// Test non-fatal failures and returns false. |
| 715 |
bool Mock::VerifyAndClearExpectations(void* mock_obj) |
| 716 |
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { |
| 717 |
internal::MutexLock l(&internal::g_gmock_mutex); |
| 718 |
return VerifyAndClearExpectationsLocked(mock_obj); |
| 719 |
} |
| 720 |
|
| 721 |
// Verifies all expectations on the given mock object and clears its |
| 722 |
// default actions and expectations. Returns true if and only if the |
| 723 |
// verification was successful. |
| 724 |
bool Mock::VerifyAndClear(void* mock_obj) |
| 725 |
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { |
| 726 |
internal::MutexLock l(&internal::g_gmock_mutex); |
| 727 |
ClearDefaultActionsLocked(mock_obj); |
| 728 |
return VerifyAndClearExpectationsLocked(mock_obj); |
| 729 |
} |
| 730 |
|
| 731 |
// Verifies and clears all expectations on the given mock object. If |
| 732 |
// the expectations aren't satisfied, generates one or more Google |
| 733 |
// Test non-fatal failures and returns false. |
| 734 |
bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj) |
| 735 |
GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { |
| 736 |
internal::g_gmock_mutex.AssertHeld(); |
| 737 |
if (g_mock_object_registry.states().count(mock_obj) == 0) { |
| 738 |
// No EXPECT_CALL() was set on the given mock object. |
| 739 |
return true; |
| 740 |
} |
| 741 |
|
| 742 |
// Verifies and clears the expectations on each mock method in the |
| 743 |
// given mock object. |
| 744 |
bool expectations_met = true; |
| 745 |
FunctionMockers& mockers = |
| 746 |
g_mock_object_registry.states()[mock_obj].function_mockers; |
| 747 |
for (FunctionMockers::const_iterator it = mockers.begin(); |
| 748 |
it != mockers.end(); ++it) { |
| 749 |
if (!(*it)->VerifyAndClearExpectationsLocked()) { |
| 750 |
expectations_met = false; |
| 751 |
} |
| 752 |
} |
| 753 |
|
| 754 |
// We don't clear the content of mockers, as they may still be |
| 755 |
// needed by ClearDefaultActionsLocked(). |
| 756 |
return expectations_met; |
| 757 |
} |
| 758 |
|
| 759 |
bool Mock::IsNaggy(void* mock_obj) |
| 760 |
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { |
| 761 |
return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kWarn; |
| 762 |
} |
| 763 |
bool Mock::IsNice(void* mock_obj) |
| 764 |
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { |
| 765 |
return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kAllow; |
| 766 |
} |
| 767 |
bool Mock::IsStrict(void* mock_obj) |
| 768 |
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { |
| 769 |
return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kFail; |
| 770 |
} |
| 771 |
|
| 772 |
// Registers a mock object and a mock method it owns. |
| 773 |
void Mock::Register(const void* mock_obj, |
| 774 |
internal::UntypedFunctionMockerBase* mocker) |
| 775 |
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { |
| 776 |
internal::MutexLock l(&internal::g_gmock_mutex); |
| 777 |
g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker); |
| 778 |
} |
| 779 |
|
| 780 |
// Tells Google Mock where in the source code mock_obj is used in an |
| 781 |
// ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this |
| 782 |
// information helps the user identify which object it is. |
| 783 |
void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj, |
| 784 |
const char* file, int line) |
| 785 |
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { |
| 786 |
internal::MutexLock l(&internal::g_gmock_mutex); |
| 787 |
MockObjectState& state = g_mock_object_registry.states()[mock_obj]; |
| 788 |
if (state.first_used_file == nullptr) { |
| 789 |
state.first_used_file = file; |
| 790 |
state.first_used_line = line; |
| 791 |
const TestInfo* const test_info = |
| 792 |
UnitTest::GetInstance()->current_test_info(); |
| 793 |
if (test_info != nullptr) { |
| 794 |
state.first_used_test_suite = test_info->test_suite_name(); |
| 795 |
state.first_used_test = test_info->name(); |
| 796 |
} |
| 797 |
} |
| 798 |
} |
| 799 |
|
| 800 |
// Unregisters a mock method; removes the owning mock object from the |
| 801 |
// registry when the last mock method associated with it has been |
| 802 |
// unregistered. This is called only in the destructor of |
| 803 |
// FunctionMockerBase. |
| 804 |
void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) |
| 805 |
GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { |
| 806 |
internal::g_gmock_mutex.AssertHeld(); |
| 807 |
for (MockObjectRegistry::StateMap::iterator it = |
| 808 |
g_mock_object_registry.states().begin(); |
| 809 |
it != g_mock_object_registry.states().end(); ++it) { |
| 810 |
FunctionMockers& mockers = it->second.function_mockers; |
| 811 |
if (mockers.erase(mocker) > 0) { |
| 812 |
// mocker was in mockers and has been just removed. |
| 813 |
if (mockers.empty()) { |
| 814 |
g_mock_object_registry.states().erase(it); |
| 815 |
} |
| 816 |
return; |
| 817 |
} |
| 818 |
} |
| 819 |
} |
| 820 |
|
| 821 |
// Clears all ON_CALL()s set on the given mock object. |
| 822 |
void Mock::ClearDefaultActionsLocked(void* mock_obj) |
| 823 |
GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { |
| 824 |
internal::g_gmock_mutex.AssertHeld(); |
| 825 |
|
| 826 |
if (g_mock_object_registry.states().count(mock_obj) == 0) { |
| 827 |
// No ON_CALL() was set on the given mock object. |
| 828 |
return; |
| 829 |
} |
| 830 |
|
| 831 |
// Clears the default actions for each mock method in the given mock |
| 832 |
// object. |
| 833 |
FunctionMockers& mockers = |
| 834 |
g_mock_object_registry.states()[mock_obj].function_mockers; |
| 835 |
for (FunctionMockers::const_iterator it = mockers.begin(); |
| 836 |
it != mockers.end(); ++it) { |
| 837 |
(*it)->ClearDefaultActionsLocked(); |
| 838 |
} |
| 839 |
|
| 840 |
// We don't clear the content of mockers, as they may still be |
| 841 |
// needed by VerifyAndClearExpectationsLocked(). |
| 842 |
} |
| 843 |
|
| 844 |
Expectation::Expectation() {} |
| 845 |
|
| 846 |
Expectation::Expectation( |
| 847 |
const std::shared_ptr<internal::ExpectationBase>& an_expectation_base) |
| 848 |
: expectation_base_(an_expectation_base) {} |
| 849 |
|
| 850 |
Expectation::~Expectation() {} |
| 851 |
|
| 852 |
// Adds an expectation to a sequence. |
| 853 |
void Sequence::AddExpectation(const Expectation& expectation) const { |
| 854 |
if (*last_expectation_ != expectation) { |
| 855 |
if (last_expectation_->expectation_base() != nullptr) { |
| 856 |
expectation.expectation_base()->immediate_prerequisites_ |
| 857 |
+= *last_expectation_; |
| 858 |
} |
| 859 |
*last_expectation_ = expectation; |
| 860 |
} |
| 861 |
} |
| 862 |
|
| 863 |
// Creates the implicit sequence if there isn't one. |
| 864 |
InSequence::InSequence() { |
| 865 |
if (internal::g_gmock_implicit_sequence.get() == nullptr) { |
| 866 |
internal::g_gmock_implicit_sequence.set(new Sequence); |
| 867 |
sequence_created_ = true; |
| 868 |
} else { |
| 869 |
sequence_created_ = false; |
| 870 |
} |
| 871 |
} |
| 872 |
|
| 873 |
// Deletes the implicit sequence if it was created by the constructor |
| 874 |
// of this object. |
| 875 |
InSequence::~InSequence() { |
| 876 |
if (sequence_created_) { |
| 877 |
delete internal::g_gmock_implicit_sequence.get(); |
| 878 |
internal::g_gmock_implicit_sequence.set(nullptr); |
| 879 |
} |
| 880 |
} |
| 881 |
|
| 882 |
} // namespace testing |
| 883 |
|
| 884 |
#ifdef _MSC_VER |
| 885 |
#if _MSC_VER == 1900 |
| 886 |
# pragma warning(pop) |
| 887 |
#endif |
| 888 |
#endif |