Coverage Report

Created: 2020-06-26 05:44

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