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 // Author: wan@google.com (Zhanyong Wan)
31
32 // Google Mock - a framework for writing C++ mock classes.
33 //
34 // This file implements the spec builder syntax (ON_CALL and
35 // EXPECT_CALL).
36
37 #include "gmock/gmock-spec-builders.h"
38
39 #include <stdlib.h>
40 #include <iostream> // NOLINT
41 #include <map>
42 #include <set>
43 #include <string>
44 #include "gmock/gmock.h"
45 #include "gtest/gtest.h"
46
47 #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
48 # include <unistd.h> // NOLINT
49 #endif
50
51 namespace testing {
52 namespace internal {
53
54 // Protects the mock object registry (in class Mock), all function
55 // mockers, and all expectations.
56 GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);
57
58 // Logs a message including file and line number information.
LogWithLocation(testing::internal::LogSeverity severity,const char * file,int line,const string & message)59 void LogWithLocation(testing::internal::LogSeverity severity,
60 const char* file, int line,
61 const string& message) {
62 ::std::ostringstream s;
63 s << file << ":" << line << ": " << message << ::std::endl;
64 Log(severity, s.str(), 0);
65 }
66
67 // Constructs an ExpectationBase object.
ExpectationBase(const char * a_file,int a_line,const string & a_source_text)68 ExpectationBase::ExpectationBase(const char* a_file,
69 int a_line,
70 const string& a_source_text)
71 : file_(a_file),
72 line_(a_line),
73 source_text_(a_source_text),
74 cardinality_specified_(false),
75 cardinality_(Exactly(1)),
76 call_count_(0),
77 retired_(false),
78 extra_matcher_specified_(false),
79 repeated_action_specified_(false),
80 retires_on_saturation_(false),
81 last_clause_(kNone),
82 action_count_checked_(false) {}
83
84 // Destructs an ExpectationBase object.
~ExpectationBase()85 ExpectationBase::~ExpectationBase() {}
86
87 // Explicitly specifies the cardinality of this expectation. Used by
88 // the subclasses to implement the .Times() clause.
SpecifyCardinality(const Cardinality & a_cardinality)89 void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {
90 cardinality_specified_ = true;
91 cardinality_ = a_cardinality;
92 }
93
94 // Retires all pre-requisites of this expectation.
RetireAllPreRequisites()95 void ExpectationBase::RetireAllPreRequisites() {
96 if (is_retired()) {
97 // We can take this short-cut as we never retire an expectation
98 // until we have retired all its pre-requisites.
99 return;
100 }
101
102 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
103 it != immediate_prerequisites_.end(); ++it) {
104 ExpectationBase* const prerequisite = it->expectation_base().get();
105 if (!prerequisite->is_retired()) {
106 prerequisite->RetireAllPreRequisites();
107 prerequisite->Retire();
108 }
109 }
110 }
111
112 // Returns true iff all pre-requisites of this expectation have been
113 // satisfied.
114 // L >= g_gmock_mutex
AllPrerequisitesAreSatisfied() const115 bool ExpectationBase::AllPrerequisitesAreSatisfied() const {
116 g_gmock_mutex.AssertHeld();
117 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
118 it != immediate_prerequisites_.end(); ++it) {
119 if (!(it->expectation_base()->IsSatisfied()) ||
120 !(it->expectation_base()->AllPrerequisitesAreSatisfied()))
121 return false;
122 }
123 return true;
124 }
125
126 // Adds unsatisfied pre-requisites of this expectation to 'result'.
127 // L >= g_gmock_mutex
FindUnsatisfiedPrerequisites(ExpectationSet * result) const128 void ExpectationBase::FindUnsatisfiedPrerequisites(
129 ExpectationSet* result) const {
130 g_gmock_mutex.AssertHeld();
131 for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin();
132 it != immediate_prerequisites_.end(); ++it) {
133 if (it->expectation_base()->IsSatisfied()) {
134 // If *it is satisfied and has a call count of 0, some of its
135 // pre-requisites may not be satisfied yet.
136 if (it->expectation_base()->call_count_ == 0) {
137 it->expectation_base()->FindUnsatisfiedPrerequisites(result);
138 }
139 } else {
140 // Now that we know *it is unsatisfied, we are not so interested
141 // in whether its pre-requisites are satisfied. Therefore we
142 // don't recursively call FindUnsatisfiedPrerequisites() here.
143 *result += *it;
144 }
145 }
146 }
147
148 // Describes how many times a function call matching this
149 // expectation has occurred.
150 // L >= g_gmock_mutex
DescribeCallCountTo(::std::ostream * os) const151 void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const {
152 g_gmock_mutex.AssertHeld();
153
154 // Describes how many times the function is expected to be called.
155 *os << " Expected: to be ";
156 cardinality().DescribeTo(os);
157 *os << "\n Actual: ";
158 Cardinality::DescribeActualCallCountTo(call_count(), os);
159
160 // Describes the state of the expectation (e.g. is it satisfied?
161 // is it active?).
162 *os << " - " << (IsOverSaturated() ? "over-saturated" :
163 IsSaturated() ? "saturated" :
164 IsSatisfied() ? "satisfied" : "unsatisfied")
165 << " and "
166 << (is_retired() ? "retired" : "active");
167 }
168
169 // Checks the action count (i.e. the number of WillOnce() and
170 // WillRepeatedly() clauses) against the cardinality if this hasn't
171 // been done before. Prints a warning if there are too many or too
172 // few actions.
173 // L < mutex_
CheckActionCountIfNotDone() const174 void ExpectationBase::CheckActionCountIfNotDone() const {
175 bool should_check = false;
176 {
177 MutexLock l(&mutex_);
178 if (!action_count_checked_) {
179 action_count_checked_ = true;
180 should_check = true;
181 }
182 }
183
184 if (should_check) {
185 if (!cardinality_specified_) {
186 // The cardinality was inferred - no need to check the action
187 // count against it.
188 return;
189 }
190
191 // The cardinality was explicitly 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();
195 bool too_many; // True if there are too many actions, or false
196 // if there are too few.
197 if (action_count > upper_bound ||
198 (action_count == upper_bound && repeated_action_specified_)) {
199 too_many = true;
200 } else if (0 < action_count && action_count < lower_bound &&
201 !repeated_action_specified_) {
202 too_many = false;
203 } else {
204 return;
205 }
206
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()";
218 }
219 ss << ".";
220 Log(WARNING, ss.str(), -1); // -1 means "don't print stack trace".
221 }
222 }
223
224 // Implements the .Times() clause.
UntypedTimes(const Cardinality & a_cardinality)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().");
230 } else {
231 ExpectSpecProperty(last_clause_ < kTimes,
232 ".Times() cannot appear after "
233 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
234 "or .RetiresOnSaturation().");
235 }
236 last_clause_ = kTimes;
237
238 SpecifyCardinality(a_cardinality);
239 }
240
241 // Points to the implicit sequence introduced by a living InSequence
242 // object (if any) in the current thread or NULL.
243 ThreadLocal<Sequence*> g_gmock_implicit_sequence;
244
245 // Reports an uninteresting call (whose description is in msg) in the
246 // manner specified by 'reaction'.
ReportUninterestingCall(CallReaction reaction,const string & msg)247 void ReportUninterestingCall(CallReaction reaction, const string& msg) {
248 switch (reaction) {
249 case ALLOW:
250 Log(INFO, msg, 3);
251 break;
252 case WARN:
253 Log(WARNING, msg, 3);
254 break;
255 default: // FAIL
256 Expect(false, NULL, -1, msg);
257 }
258 }
259
UntypedFunctionMockerBase()260 UntypedFunctionMockerBase::UntypedFunctionMockerBase()
261 : mock_obj_(NULL), name_("") {}
262
~UntypedFunctionMockerBase()263 UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
264
265 // Sets the mock object this mock method belongs to, and registers
266 // this information in the global mock registry. Will be called
267 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
268 // method.
269 // L < g_gmock_mutex
RegisterOwner(const void * mock_obj)270 void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj) {
271 {
272 MutexLock l(&g_gmock_mutex);
273 mock_obj_ = mock_obj;
274 }
275 Mock::Register(mock_obj, this);
276 }
277
278 // Sets the mock object this mock method belongs to, and sets the name
279 // of the mock function. Will be called upon each invocation of this
280 // mock function.
281 // L < g_gmock_mutex
SetOwnerAndName(const void * mock_obj,const char * name)282 void UntypedFunctionMockerBase::SetOwnerAndName(
283 const void* mock_obj, const char* name) {
284 // We protect name_ under g_gmock_mutex in case this mock function
285 // is called from two threads concurrently.
286 MutexLock l(&g_gmock_mutex);
287 mock_obj_ = mock_obj;
288 name_ = name;
289 }
290
291 // Returns the name of the function being mocked. Must be called
292 // after RegisterOwner() or SetOwnerAndName() has been called.
293 // L < g_gmock_mutex
MockObject() const294 const void* UntypedFunctionMockerBase::MockObject() const {
295 const void* mock_obj;
296 {
297 // We protect mock_obj_ under g_gmock_mutex in case this mock
298 // function is called from two threads concurrently.
299 MutexLock l(&g_gmock_mutex);
300 Assert(mock_obj_ != NULL, __FILE__, __LINE__,
301 "MockObject() must not be called before RegisterOwner() or "
302 "SetOwnerAndName() has been called.");
303 mock_obj = mock_obj_;
304 }
305 return mock_obj;
306 }
307
308 // Returns the name of this mock method. Must be called after
309 // SetOwnerAndName() has been called.
310 // L < g_gmock_mutex
Name() const311 const char* UntypedFunctionMockerBase::Name() const {
312 const char* name;
313 {
314 // We protect name_ under g_gmock_mutex in case this mock
315 // function is called from two threads concurrently.
316 MutexLock l(&g_gmock_mutex);
317 Assert(name_ != NULL, __FILE__, __LINE__,
318 "Name() must not be called before SetOwnerAndName() has "
319 "been called.");
320 name = name_;
321 }
322 return name;
323 }
324
325 // Calculates the result of invoking this mock function with the given
326 // arguments, prints it, and returns it. The caller is responsible
327 // for deleting the result.
328 // L < g_gmock_mutex
329 const UntypedActionResultHolderBase*
UntypedInvokeWith(const void * const untyped_args)330 UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) {
331 if (untyped_expectations_.size() == 0) {
332 // No expectation is set on this mock method - we have an
333 // uninteresting call.
334
335 // We must get Google Mock's reaction on uninteresting calls
336 // made on this mock object BEFORE performing the action,
337 // because the action may DELETE the mock object and make the
338 // following expression meaningless.
339 const CallReaction reaction =
340 Mock::GetReactionOnUninterestingCalls(MockObject());
341
342 // True iff we need to print this call's arguments and return
343 // value. This definition must be kept in sync with
344 // the behavior of ReportUninterestingCall().
345 const bool need_to_report_uninteresting_call =
346 // If the user allows this uninteresting call, we print it
347 // only when he wants informational messages.
348 reaction == ALLOW ? LogIsVisible(INFO) :
349 // If the user wants this to be a warning, we print it only
350 // when he wants to see warnings.
351 reaction == WARN ? LogIsVisible(WARNING) :
352 // Otherwise, the user wants this to be an error, and we
353 // should always print detailed information in the error.
354 true;
355
356 if (!need_to_report_uninteresting_call) {
357 // Perform the action without printing the call information.
358 return this->UntypedPerformDefaultAction(untyped_args, "");
359 }
360
361 // Warns about the uninteresting call.
362 ::std::stringstream ss;
363 this->UntypedDescribeUninterestingCall(untyped_args, &ss);
364
365 // Calculates the function result.
366 const UntypedActionResultHolderBase* const result =
367 this->UntypedPerformDefaultAction(untyped_args, ss.str());
368
369 // Prints the function result.
370 if (result != NULL)
371 result->PrintAsActionResult(&ss);
372
373 ReportUninterestingCall(reaction, ss.str());
374 return result;
375 }
376
377 bool is_excessive = false;
378 ::std::stringstream ss;
379 ::std::stringstream why;
380 ::std::stringstream loc;
381 const void* untyped_action = NULL;
382
383 // The UntypedFindMatchingExpectation() function acquires and
384 // releases g_gmock_mutex.
385 const ExpectationBase* const untyped_expectation =
386 this->UntypedFindMatchingExpectation(
387 untyped_args, &untyped_action, &is_excessive,
388 &ss, &why);
389 const bool found = untyped_expectation != NULL;
390
391 // True iff we need to print the call's arguments and return value.
392 // This definition must be kept in sync with the uses of Expect()
393 // and Log() in this function.
394 const bool need_to_report_call = !found || is_excessive || LogIsVisible(INFO);
395 if (!need_to_report_call) {
396 // Perform the action without printing the call information.
397 return
398 untyped_action == NULL ?
399 this->UntypedPerformDefaultAction(untyped_args, "") :
400 this->UntypedPerformAction(untyped_action, untyped_args);
401 }
402
403 ss << " Function call: " << Name();
404 this->UntypedPrintArgs(untyped_args, &ss);
405
406 // In case the action deletes a piece of the expectation, we
407 // generate the message beforehand.
408 if (found && !is_excessive) {
409 untyped_expectation->DescribeLocationTo(&loc);
410 }
411
412 const UntypedActionResultHolderBase* const result =
413 untyped_action == NULL ?
414 this->UntypedPerformDefaultAction(untyped_args, ss.str()) :
415 this->UntypedPerformAction(untyped_action, untyped_args);
416 if (result != NULL)
417 result->PrintAsActionResult(&ss);
418 ss << "\n" << why.str();
419
420 if (!found) {
421 // No expectation matches this call - reports a failure.
422 Expect(false, NULL, -1, ss.str());
423 } else if (is_excessive) {
424 // We had an upper-bound violation and the failure message is in ss.
425 Expect(false, untyped_expectation->file(),
426 untyped_expectation->line(), ss.str());
427 } else {
428 // We had an expected call and the matching expectation is
429 // described in ss.
430 Log(INFO, loc.str() + ss.str(), 2);
431 }
432
433 return result;
434 }
435
436 // Returns an Expectation object that references and co-owns exp,
437 // which must be an expectation on this mock function.
GetHandleOf(ExpectationBase * exp)438 Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {
439 for (UntypedExpectations::const_iterator it =
440 untyped_expectations_.begin();
441 it != untyped_expectations_.end(); ++it) {
442 if (it->get() == exp) {
443 return Expectation(*it);
444 }
445 }
446
447 Assert(false, __FILE__, __LINE__, "Cannot find expectation.");
448 return Expectation();
449 // The above statement is just to make the code compile, and will
450 // never be executed.
451 }
452
453 // Verifies that all expectations on this mock function have been
454 // satisfied. Reports one or more Google Test non-fatal failures
455 // and returns false if not.
456 // L >= g_gmock_mutex
VerifyAndClearExpectationsLocked()457 bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked() {
458 g_gmock_mutex.AssertHeld();
459 bool expectations_met = true;
460 for (UntypedExpectations::const_iterator it =
461 untyped_expectations_.begin();
462 it != untyped_expectations_.end(); ++it) {
463 ExpectationBase* const untyped_expectation = it->get();
464 if (untyped_expectation->IsOverSaturated()) {
465 // There was an upper-bound violation. Since the error was
466 // already reported when it occurred, there is no need to do
467 // anything here.
468 expectations_met = false;
469 } else if (!untyped_expectation->IsSatisfied()) {
470 expectations_met = false;
471 ::std::stringstream ss;
472 ss << "Actual function call count doesn't match "
473 << untyped_expectation->source_text() << "...\n";
474 // No need to show the source file location of the expectation
475 // in the description, as the Expect() call that follows already
476 // takes care of it.
477 untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);
478 untyped_expectation->DescribeCallCountTo(&ss);
479 Expect(false, untyped_expectation->file(),
480 untyped_expectation->line(), ss.str());
481 }
482 }
483 untyped_expectations_.clear();
484 return expectations_met;
485 }
486
487 } // namespace internal
488
489 // Class Mock.
490
491 namespace {
492
493 typedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;
494
495 // The current state of a mock object. Such information is needed for
496 // detecting leaked mock objects and explicitly verifying a mock's
497 // expectations.
498 struct MockObjectState {
MockObjectStatetesting::__anon87c379120111::MockObjectState499 MockObjectState()
500 : first_used_file(NULL), first_used_line(-1), leakable(false) {}
501
502 // Where in the source file an ON_CALL or EXPECT_CALL is first
503 // invoked on this mock object.
504 const char* first_used_file;
505 int first_used_line;
506 ::std::string first_used_test_case;
507 ::std::string first_used_test;
508 bool leakable; // true iff it's OK to leak the object.
509 FunctionMockers function_mockers; // All registered methods of the object.
510 };
511
512 // A global registry holding the state of all mock objects that are
513 // alive. A mock object is added to this registry the first time
514 // Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It
515 // is removed from the registry in the mock object's destructor.
516 class MockObjectRegistry {
517 public:
518 // Maps a mock object (identified by its address) to its state.
519 typedef std::map<const void*, MockObjectState> StateMap;
520
521 // This destructor will be called when a program exits, after all
522 // tests in it have been run. By then, there should be no mock
523 // object alive. Therefore we report any living object as test
524 // failure, unless the user explicitly asked us to ignore it.
~MockObjectRegistry()525 ~MockObjectRegistry() {
526 // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is
527 // a macro.
528
529 if (!GMOCK_FLAG(catch_leaked_mocks))
530 return;
531
532 int leaked_count = 0;
533 for (StateMap::const_iterator it = states_.begin(); it != states_.end();
534 ++it) {
535 if (it->second.leakable) // The user said it's fine to leak this object.
536 continue;
537
538 // TODO(wan@google.com): Print the type of the leaked object.
539 // This can help the user identify the leaked object.
540 std::cout << "\n";
541 const MockObjectState& state = it->second;
542 std::cout << internal::FormatFileLocation(state.first_used_file,
543 state.first_used_line);
544 std::cout << " ERROR: this mock object";
545 if (state.first_used_test != "") {
546 std::cout << " (used in test " << state.first_used_test_case << "."
547 << state.first_used_test << ")";
548 }
549 std::cout << " should be deleted but never is. Its address is @"
550 << it->first << ".";
551 leaked_count++;
552 }
553 if (leaked_count > 0) {
554 std::cout << "\nERROR: " << leaked_count
555 << " leaked mock " << (leaked_count == 1 ? "object" : "objects")
556 << " found at program exit.\n";
557 std::cout.flush();
558 ::std::cerr.flush();
559 // RUN_ALL_TESTS() has already returned when this destructor is
560 // called. Therefore we cannot use the normal Google Test
561 // failure reporting mechanism.
562 _exit(1); // We cannot call exit() as it is not reentrant and
563 // may already have been called.
564 }
565 }
566
states()567 StateMap& states() { return states_; }
568 private:
569 StateMap states_;
570 };
571
572 // Protected by g_gmock_mutex.
573 MockObjectRegistry g_mock_object_registry;
574
575 // Maps a mock object to the reaction Google Mock should have when an
576 // uninteresting method is called. Protected by g_gmock_mutex.
577 std::map<const void*, internal::CallReaction> g_uninteresting_call_reaction;
578
579 // Sets the reaction Google Mock should have when an uninteresting
580 // method of the given mock object is called.
581 // L < g_gmock_mutex
SetReactionOnUninterestingCalls(const void * mock_obj,internal::CallReaction reaction)582 void SetReactionOnUninterestingCalls(const void* mock_obj,
583 internal::CallReaction reaction) {
584 internal::MutexLock l(&internal::g_gmock_mutex);
585 g_uninteresting_call_reaction[mock_obj] = reaction;
586 }
587
588 } // namespace
589
590 // Tells Google Mock to allow uninteresting calls on the given mock
591 // object.
592 // L < g_gmock_mutex
AllowUninterestingCalls(const void * mock_obj)593 void Mock::AllowUninterestingCalls(const void* mock_obj) {
594 SetReactionOnUninterestingCalls(mock_obj, internal::ALLOW);
595 }
596
597 // Tells Google Mock to warn the user about uninteresting calls on the
598 // given mock object.
599 // L < g_gmock_mutex
WarnUninterestingCalls(const void * mock_obj)600 void Mock::WarnUninterestingCalls(const void* mock_obj) {
601 SetReactionOnUninterestingCalls(mock_obj, internal::WARN);
602 }
603
604 // Tells Google Mock to fail uninteresting calls on the given mock
605 // object.
606 // L < g_gmock_mutex
FailUninterestingCalls(const void * mock_obj)607 void Mock::FailUninterestingCalls(const void* mock_obj) {
608 SetReactionOnUninterestingCalls(mock_obj, internal::FAIL);
609 }
610
611 // Tells Google Mock the given mock object is being destroyed and its
612 // entry in the call-reaction table should be removed.
613 // L < g_gmock_mutex
UnregisterCallReaction(const void * mock_obj)614 void Mock::UnregisterCallReaction(const void* mock_obj) {
615 internal::MutexLock l(&internal::g_gmock_mutex);
616 g_uninteresting_call_reaction.erase(mock_obj);
617 }
618
619 // Returns the reaction Google Mock will have on uninteresting calls
620 // made on the given mock object.
621 // L < g_gmock_mutex
GetReactionOnUninterestingCalls(const void * mock_obj)622 internal::CallReaction Mock::GetReactionOnUninterestingCalls(
623 const void* mock_obj) {
624 internal::MutexLock l(&internal::g_gmock_mutex);
625 return (g_uninteresting_call_reaction.count(mock_obj) == 0) ?
626 internal::WARN : g_uninteresting_call_reaction[mock_obj];
627 }
628
629 // Tells Google Mock to ignore mock_obj when checking for leaked mock
630 // objects.
631 // L < g_gmock_mutex
AllowLeak(const void * mock_obj)632 void Mock::AllowLeak(const void* mock_obj) {
633 internal::MutexLock l(&internal::g_gmock_mutex);
634 g_mock_object_registry.states()[mock_obj].leakable = true;
635 }
636
637 // Verifies and clears all expectations on the given mock object. If
638 // the expectations aren't satisfied, generates one or more Google
639 // Test non-fatal failures and returns false.
640 // L < g_gmock_mutex
VerifyAndClearExpectations(void * mock_obj)641 bool Mock::VerifyAndClearExpectations(void* mock_obj) {
642 internal::MutexLock l(&internal::g_gmock_mutex);
643 return VerifyAndClearExpectationsLocked(mock_obj);
644 }
645
646 // Verifies all expectations on the given mock object and clears its
647 // default actions and expectations. Returns true iff the
648 // verification was successful.
649 // L < g_gmock_mutex
VerifyAndClear(void * mock_obj)650 bool Mock::VerifyAndClear(void* mock_obj) {
651 internal::MutexLock l(&internal::g_gmock_mutex);
652 ClearDefaultActionsLocked(mock_obj);
653 return VerifyAndClearExpectationsLocked(mock_obj);
654 }
655
656 // Verifies and clears all expectations on the given mock object. If
657 // the expectations aren't satisfied, generates one or more Google
658 // Test non-fatal failures and returns false.
659 // L >= g_gmock_mutex
VerifyAndClearExpectationsLocked(void * mock_obj)660 bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj) {
661 internal::g_gmock_mutex.AssertHeld();
662 if (g_mock_object_registry.states().count(mock_obj) == 0) {
663 // No EXPECT_CALL() was set on the given mock object.
664 return true;
665 }
666
667 // Verifies and clears the expectations on each mock method in the
668 // given mock object.
669 bool expectations_met = true;
670 FunctionMockers& mockers =
671 g_mock_object_registry.states()[mock_obj].function_mockers;
672 for (FunctionMockers::const_iterator it = mockers.begin();
673 it != mockers.end(); ++it) {
674 if (!(*it)->VerifyAndClearExpectationsLocked()) {
675 expectations_met = false;
676 }
677 }
678
679 // We don't clear the content of mockers, as they may still be
680 // needed by ClearDefaultActionsLocked().
681 return expectations_met;
682 }
683
684 // Registers a mock object and a mock method it owns.
685 // L < g_gmock_mutex
Register(const void * mock_obj,internal::UntypedFunctionMockerBase * mocker)686 void Mock::Register(const void* mock_obj,
687 internal::UntypedFunctionMockerBase* mocker) {
688 internal::MutexLock l(&internal::g_gmock_mutex);
689 g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);
690 }
691
692 // Tells Google Mock where in the source code mock_obj is used in an
693 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
694 // information helps the user identify which object it is.
695 // L < g_gmock_mutex
RegisterUseByOnCallOrExpectCall(const void * mock_obj,const char * file,int line)696 void Mock::RegisterUseByOnCallOrExpectCall(
697 const void* mock_obj, const char* file, int line) {
698 internal::MutexLock l(&internal::g_gmock_mutex);
699 MockObjectState& state = g_mock_object_registry.states()[mock_obj];
700 if (state.first_used_file == NULL) {
701 state.first_used_file = file;
702 state.first_used_line = line;
703 const TestInfo* const test_info =
704 UnitTest::GetInstance()->current_test_info();
705 if (test_info != NULL) {
706 // TODO(wan@google.com): record the test case name when the
707 // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or
708 // TearDownTestCase().
709 state.first_used_test_case = test_info->test_case_name();
710 state.first_used_test = test_info->name();
711 }
712 }
713 }
714
715 // Unregisters a mock method; removes the owning mock object from the
716 // registry when the last mock method associated with it has been
717 // unregistered. This is called only in the destructor of
718 // FunctionMockerBase.
719 // L >= g_gmock_mutex
UnregisterLocked(internal::UntypedFunctionMockerBase * mocker)720 void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) {
721 internal::g_gmock_mutex.AssertHeld();
722 for (MockObjectRegistry::StateMap::iterator it =
723 g_mock_object_registry.states().begin();
724 it != g_mock_object_registry.states().end(); ++it) {
725 FunctionMockers& mockers = it->second.function_mockers;
726 if (mockers.erase(mocker) > 0) {
727 // mocker was in mockers and has been just removed.
728 if (mockers.empty()) {
729 g_mock_object_registry.states().erase(it);
730 }
731 return;
732 }
733 }
734 }
735
736 // Clears all ON_CALL()s set on the given mock object.
737 // L >= g_gmock_mutex
ClearDefaultActionsLocked(void * mock_obj)738 void Mock::ClearDefaultActionsLocked(void* mock_obj) {
739 internal::g_gmock_mutex.AssertHeld();
740
741 if (g_mock_object_registry.states().count(mock_obj) == 0) {
742 // No ON_CALL() was set on the given mock object.
743 return;
744 }
745
746 // Clears the default actions for each mock method in the given mock
747 // object.
748 FunctionMockers& mockers =
749 g_mock_object_registry.states()[mock_obj].function_mockers;
750 for (FunctionMockers::const_iterator it = mockers.begin();
751 it != mockers.end(); ++it) {
752 (*it)->ClearDefaultActionsLocked();
753 }
754
755 // We don't clear the content of mockers, as they may still be
756 // needed by VerifyAndClearExpectationsLocked().
757 }
758
Expectation()759 Expectation::Expectation() {}
760
Expectation(const internal::linked_ptr<internal::ExpectationBase> & an_expectation_base)761 Expectation::Expectation(
762 const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base)
763 : expectation_base_(an_expectation_base) {}
764
~Expectation()765 Expectation::~Expectation() {}
766
767 // Adds an expectation to a sequence.
AddExpectation(const Expectation & expectation) const768 void Sequence::AddExpectation(const Expectation& expectation) const {
769 if (*last_expectation_ != expectation) {
770 if (last_expectation_->expectation_base() != NULL) {
771 expectation.expectation_base()->immediate_prerequisites_
772 += *last_expectation_;
773 }
774 *last_expectation_ = expectation;
775 }
776 }
777
778 // Creates the implicit sequence if there isn't one.
InSequence()779 InSequence::InSequence() {
780 if (internal::g_gmock_implicit_sequence.get() == NULL) {
781 internal::g_gmock_implicit_sequence.set(new Sequence);
782 sequence_created_ = true;
783 } else {
784 sequence_created_ = false;
785 }
786 }
787
788 // Deletes the implicit sequence if it was created by the constructor
789 // of this object.
~InSequence()790 InSequence::~InSequence() {
791 if (sequence_created_) {
792 delete internal::g_gmock_implicit_sequence.get();
793 internal::g_gmock_implicit_sequence.set(NULL);
794 }
795 }
796
797 } // namespace testing
798