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