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