blob: 7266fba7ef38b14d6361f093d540427b150c4e66 [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// 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 some commonly used argument matchers. More
35// matchers can be defined by the user implementing the
36// MatcherInterface<T> interface if necessary.
37
38#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
39#define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
40
zhanyong.wan6a896b52009-01-16 01:13:50 +000041#include <algorithm>
zhanyong.wan16cf4732009-05-14 20:55:30 +000042#include <limits>
shiqiane35fdd92008-12-10 05:08:54 +000043#include <ostream> // NOLINT
44#include <sstream>
45#include <string>
46#include <vector>
47
48#include <gmock/gmock-printers.h>
49#include <gmock/internal/gmock-internal-utils.h>
50#include <gmock/internal/gmock-port.h>
51#include <gtest/gtest.h>
52
53namespace testing {
54
55// To implement a matcher Foo for type T, define:
56// 1. a class FooMatcherImpl that implements the
57// MatcherInterface<T> interface, and
58// 2. a factory function that creates a Matcher<T> object from a
59// FooMatcherImpl*.
60//
61// The two-level delegation design makes it possible to allow a user
62// to write "v" instead of "Eq(v)" where a Matcher is expected, which
63// is impossible if we pass matchers by pointers. It also eases
64// ownership management as Matcher objects can now be copied like
65// plain values.
66
67// The implementation of a matcher.
68template <typename T>
69class MatcherInterface {
70 public:
71 virtual ~MatcherInterface() {}
72
73 // Returns true iff the matcher matches x.
74 virtual bool Matches(T x) const = 0;
75
76 // Describes this matcher to an ostream.
77 virtual void DescribeTo(::std::ostream* os) const = 0;
78
79 // Describes the negation of this matcher to an ostream. For
80 // example, if the description of this matcher is "is greater than
81 // 7", the negated description could be "is not greater than 7".
82 // You are not required to override this when implementing
83 // MatcherInterface, but it is highly advised so that your matcher
84 // can produce good error messages.
85 virtual void DescribeNegationTo(::std::ostream* os) const {
86 *os << "not (";
87 DescribeTo(os);
88 *os << ")";
89 }
90
91 // Explains why x matches, or doesn't match, the matcher. Override
92 // this to provide any additional information that helps a user
93 // understand the match result.
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +000094 virtual void ExplainMatchResultTo(T /* x */, ::std::ostream* /* os */) const {
shiqiane35fdd92008-12-10 05:08:54 +000095 // By default, nothing more needs to be explained, as Google Mock
96 // has already printed the value of x when this function is
97 // called.
98 }
99};
100
101namespace internal {
102
103// An internal class for implementing Matcher<T>, which will derive
104// from it. We put functionalities common to all Matcher<T>
105// specializations here to avoid code duplication.
106template <typename T>
107class MatcherBase {
108 public:
109 // Returns true iff this matcher matches x.
110 bool Matches(T x) const { return impl_->Matches(x); }
111
112 // Describes this matcher to an ostream.
113 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
114
115 // Describes the negation of this matcher to an ostream.
116 void DescribeNegationTo(::std::ostream* os) const {
117 impl_->DescribeNegationTo(os);
118 }
119
120 // Explains why x matches, or doesn't match, the matcher.
121 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
122 impl_->ExplainMatchResultTo(x, os);
123 }
124 protected:
125 MatcherBase() {}
126
127 // Constructs a matcher from its implementation.
128 explicit MatcherBase(const MatcherInterface<T>* impl)
129 : impl_(impl) {}
130
131 virtual ~MatcherBase() {}
132 private:
133 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
134 // interfaces. The former dynamically allocates a chunk of memory
135 // to hold the reference count, while the latter tracks all
136 // references using a circular linked list without allocating
137 // memory. It has been observed that linked_ptr performs better in
138 // typical scenarios. However, shared_ptr can out-perform
139 // linked_ptr when there are many more uses of the copy constructor
140 // than the default constructor.
141 //
142 // If performance becomes a problem, we should see if using
143 // shared_ptr helps.
144 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
145};
146
147// The default implementation of ExplainMatchResultTo() for
148// polymorphic matchers.
149template <typename PolymorphicMatcherImpl, typename T>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000150inline void ExplainMatchResultTo(const PolymorphicMatcherImpl& /* impl */,
151 const T& /* x */,
152 ::std::ostream* /* os */) {
shiqiane35fdd92008-12-10 05:08:54 +0000153 // By default, nothing more needs to be said, as Google Mock already
154 // prints the value of x elsewhere.
155}
156
157} // namespace internal
158
159// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
160// object that can check whether a value of type T matches. The
161// implementation of Matcher<T> is just a linked_ptr to const
162// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
163// from Matcher!
164template <typename T>
165class Matcher : public internal::MatcherBase<T> {
166 public:
167 // Constructs a null matcher. Needed for storing Matcher objects in
168 // STL containers.
169 Matcher() {}
170
171 // Constructs a matcher from its implementation.
172 explicit Matcher(const MatcherInterface<T>* impl)
173 : internal::MatcherBase<T>(impl) {}
174
zhanyong.wan18490652009-05-11 18:54:08 +0000175 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000176 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
177 Matcher(T value); // NOLINT
178};
179
180// The following two specializations allow the user to write str
181// instead of Eq(str) and "foo" instead of Eq("foo") when a string
182// matcher is expected.
183template <>
184class Matcher<const internal::string&>
185 : public internal::MatcherBase<const internal::string&> {
186 public:
187 Matcher() {}
188
189 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
190 : internal::MatcherBase<const internal::string&>(impl) {}
191
192 // Allows the user to write str instead of Eq(str) sometimes, where
193 // str is a string object.
194 Matcher(const internal::string& s); // NOLINT
195
196 // Allows the user to write "foo" instead of Eq("foo") sometimes.
197 Matcher(const char* s); // NOLINT
198};
199
200template <>
201class Matcher<internal::string>
202 : public internal::MatcherBase<internal::string> {
203 public:
204 Matcher() {}
205
206 explicit Matcher(const MatcherInterface<internal::string>* impl)
207 : internal::MatcherBase<internal::string>(impl) {}
208
209 // Allows the user to write str instead of Eq(str) sometimes, where
210 // str is a string object.
211 Matcher(const internal::string& s); // NOLINT
212
213 // Allows the user to write "foo" instead of Eq("foo") sometimes.
214 Matcher(const char* s); // NOLINT
215};
216
217// The PolymorphicMatcher class template makes it easy to implement a
218// polymorphic matcher (i.e. a matcher that can match values of more
219// than one type, e.g. Eq(n) and NotNull()).
220//
221// To define a polymorphic matcher, a user first provides a Impl class
222// that has a Matches() method, a DescribeTo() method, and a
223// DescribeNegationTo() method. The Matches() method is usually a
224// method template (such that it works with multiple types). Then the
225// user creates the polymorphic matcher using
226// MakePolymorphicMatcher(). To provide additional explanation to the
227// match result, define a FREE function (or function template)
228//
229// void ExplainMatchResultTo(const Impl& matcher, const Value& value,
230// ::std::ostream* os);
231//
232// in the SAME NAME SPACE where Impl is defined. See the definition
233// of NotNull() for a complete example.
234template <class Impl>
235class PolymorphicMatcher {
236 public:
237 explicit PolymorphicMatcher(const Impl& impl) : impl_(impl) {}
238
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000239 // Returns a mutable reference to the underlying matcher
240 // implementation object.
241 Impl& mutable_impl() { return impl_; }
242
243 // Returns an immutable reference to the underlying matcher
244 // implementation object.
245 const Impl& impl() const { return impl_; }
246
shiqiane35fdd92008-12-10 05:08:54 +0000247 template <typename T>
248 operator Matcher<T>() const {
249 return Matcher<T>(new MonomorphicImpl<T>(impl_));
250 }
251 private:
252 template <typename T>
253 class MonomorphicImpl : public MatcherInterface<T> {
254 public:
255 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
256
257 virtual bool Matches(T x) const { return impl_.Matches(x); }
258
259 virtual void DescribeTo(::std::ostream* os) const {
260 impl_.DescribeTo(os);
261 }
262
263 virtual void DescribeNegationTo(::std::ostream* os) const {
264 impl_.DescribeNegationTo(os);
265 }
266
267 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
268 using ::testing::internal::ExplainMatchResultTo;
269
270 // C++ uses Argument-Dependent Look-up (aka Koenig Look-up) to
271 // resolve the call to ExplainMatchResultTo() here. This
272 // means that if there's a ExplainMatchResultTo() function
273 // defined in the name space where class Impl is defined, it
274 // will be picked by the compiler as the better match.
275 // Otherwise the default implementation of it in
276 // ::testing::internal will be picked.
277 //
278 // This look-up rule lets a writer of a polymorphic matcher
279 // customize the behavior of ExplainMatchResultTo() when he
280 // cares to. Nothing needs to be done by the writer if he
281 // doesn't need to customize it.
282 ExplainMatchResultTo(impl_, x, os);
283 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000284
shiqiane35fdd92008-12-10 05:08:54 +0000285 private:
286 const Impl impl_;
287 };
288
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000289 Impl impl_;
shiqiane35fdd92008-12-10 05:08:54 +0000290};
291
292// Creates a matcher from its implementation. This is easier to use
293// than the Matcher<T> constructor as it doesn't require you to
294// explicitly write the template argument, e.g.
295//
296// MakeMatcher(foo);
297// vs
298// Matcher<const string&>(foo);
299template <typename T>
300inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
301 return Matcher<T>(impl);
302};
303
304// Creates a polymorphic matcher from its implementation. This is
305// easier to use than the PolymorphicMatcher<Impl> constructor as it
306// doesn't require you to explicitly write the template argument, e.g.
307//
308// MakePolymorphicMatcher(foo);
309// vs
310// PolymorphicMatcher<TypeOfFoo>(foo);
311template <class Impl>
312inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
313 return PolymorphicMatcher<Impl>(impl);
314}
315
316// In order to be safe and clear, casting between different matcher
317// types is done explicitly via MatcherCast<T>(m), which takes a
318// matcher m and returns a Matcher<T>. It compiles only when T can be
319// statically converted to the argument type of m.
320template <typename T, typename M>
321Matcher<T> MatcherCast(M m);
322
zhanyong.wan18490652009-05-11 18:54:08 +0000323// TODO(vladl@google.com): Modify the implementation to reject casting
324// Matcher<int> to Matcher<double>.
325// Implements SafeMatcherCast().
326//
327// This overload handles polymorphic matchers only since monomorphic
328// matchers are handled by the next one.
329template <typename T, typename M>
330inline Matcher<T> SafeMatcherCast(M polymorphic_matcher) {
331 return Matcher<T>(polymorphic_matcher);
332}
333
334// This overload handles monomorphic matchers.
335//
336// In general, if type T can be implicitly converted to type U, we can
337// safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
338// contravariant): just keep a copy of the original Matcher<U>, convert the
339// argument from type T to U, and then pass it to the underlying Matcher<U>.
340// The only exception is when U is a reference and T is not, as the
341// underlying Matcher<U> may be interested in the argument's address, which
342// is not preserved in the conversion from T to U.
343template <typename T, typename U>
344Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) {
345 // Enforce that T can be implicitly converted to U.
346 GMOCK_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
347 T_must_be_implicitly_convertible_to_U);
348 // Enforce that we are not converting a non-reference type T to a reference
349 // type U.
350 GMOCK_COMPILE_ASSERT_(
351 internal::is_reference<T>::value || !internal::is_reference<U>::value,
352 cannot_convert_non_referentce_arg_to_reference);
zhanyong.wan16cf4732009-05-14 20:55:30 +0000353 // In case both T and U are arithmetic types, enforce that the
354 // conversion is not lossy.
355 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(T)) RawT;
356 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(U)) RawU;
357 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
358 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
359 GMOCK_COMPILE_ASSERT_(
360 kTIsOther || kUIsOther ||
361 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
362 conversion_of_arithmetic_types_must_be_lossless);
zhanyong.wan18490652009-05-11 18:54:08 +0000363 return MatcherCast<T>(matcher);
364}
365
shiqiane35fdd92008-12-10 05:08:54 +0000366// A<T>() returns a matcher that matches any value of type T.
367template <typename T>
368Matcher<T> A();
369
370// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
371// and MUST NOT BE USED IN USER CODE!!!
372namespace internal {
373
374// Appends the explanation on the result of matcher.Matches(value) to
375// os iff the explanation is not empty.
376template <typename T>
377void ExplainMatchResultAsNeededTo(const Matcher<T>& matcher, T value,
378 ::std::ostream* os) {
379 ::std::stringstream reason;
380 matcher.ExplainMatchResultTo(value, &reason);
381 const internal::string s = reason.str();
382 if (s != "") {
383 *os << " (" << s << ")";
384 }
385}
386
387// An internal helper class for doing compile-time loop on a tuple's
388// fields.
389template <size_t N>
390class TuplePrefix {
391 public:
392 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
393 // iff the first N fields of matcher_tuple matches the first N
394 // fields of value_tuple, respectively.
395 template <typename MatcherTuple, typename ValueTuple>
396 static bool Matches(const MatcherTuple& matcher_tuple,
397 const ValueTuple& value_tuple) {
398 using ::std::tr1::get;
399 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
400 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
401 }
402
403 // TuplePrefix<N>::DescribeMatchFailuresTo(matchers, values, os)
404 // describes failures in matching the first N fields of matchers
405 // against the first N fields of values. If there is no failure,
406 // nothing will be streamed to os.
407 template <typename MatcherTuple, typename ValueTuple>
408 static void DescribeMatchFailuresTo(const MatcherTuple& matchers,
409 const ValueTuple& values,
410 ::std::ostream* os) {
411 using ::std::tr1::tuple_element;
412 using ::std::tr1::get;
413
414 // First, describes failures in the first N - 1 fields.
415 TuplePrefix<N - 1>::DescribeMatchFailuresTo(matchers, values, os);
416
417 // Then describes the failure (if any) in the (N - 1)-th (0-based)
418 // field.
419 typename tuple_element<N - 1, MatcherTuple>::type matcher =
420 get<N - 1>(matchers);
421 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
422 Value value = get<N - 1>(values);
423 if (!matcher.Matches(value)) {
424 // TODO(wan): include in the message the name of the parameter
425 // as used in MOCK_METHOD*() when possible.
426 *os << " Expected arg #" << N - 1 << ": ";
427 get<N - 1>(matchers).DescribeTo(os);
428 *os << "\n Actual: ";
429 // We remove the reference in type Value to prevent the
430 // universal printer from printing the address of value, which
431 // isn't interesting to the user most of the time. The
432 // matcher's ExplainMatchResultTo() method handles the case when
433 // the address is interesting.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000434 internal::UniversalPrinter<GMOCK_REMOVE_REFERENCE_(Value)>::
shiqiane35fdd92008-12-10 05:08:54 +0000435 Print(value, os);
436 ExplainMatchResultAsNeededTo<Value>(matcher, value, os);
437 *os << "\n";
438 }
439 }
440};
441
442// The base case.
443template <>
444class TuplePrefix<0> {
445 public:
446 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000447 static bool Matches(const MatcherTuple& /* matcher_tuple */,
448 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000449 return true;
450 }
451
452 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000453 static void DescribeMatchFailuresTo(const MatcherTuple& /* matchers */,
454 const ValueTuple& /* values */,
455 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000456};
457
458// TupleMatches(matcher_tuple, value_tuple) returns true iff all
459// matchers in matcher_tuple match the corresponding fields in
460// value_tuple. It is a compiler error if matcher_tuple and
461// value_tuple have different number of fields or incompatible field
462// types.
463template <typename MatcherTuple, typename ValueTuple>
464bool TupleMatches(const MatcherTuple& matcher_tuple,
465 const ValueTuple& value_tuple) {
466 using ::std::tr1::tuple_size;
467 // Makes sure that matcher_tuple and value_tuple have the same
468 // number of fields.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000469 GMOCK_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
470 tuple_size<ValueTuple>::value,
471 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000472 return TuplePrefix<tuple_size<ValueTuple>::value>::
473 Matches(matcher_tuple, value_tuple);
474}
475
476// Describes failures in matching matchers against values. If there
477// is no failure, nothing will be streamed to os.
478template <typename MatcherTuple, typename ValueTuple>
479void DescribeMatchFailureTupleTo(const MatcherTuple& matchers,
480 const ValueTuple& values,
481 ::std::ostream* os) {
482 using ::std::tr1::tuple_size;
483 TuplePrefix<tuple_size<MatcherTuple>::value>::DescribeMatchFailuresTo(
484 matchers, values, os);
485}
486
487// The MatcherCastImpl class template is a helper for implementing
488// MatcherCast(). We need this helper in order to partially
489// specialize the implementation of MatcherCast() (C++ allows
490// class/struct templates to be partially specialized, but not
491// function templates.).
492
493// This general version is used when MatcherCast()'s argument is a
494// polymorphic matcher (i.e. something that can be converted to a
495// Matcher but is not one yet; for example, Eq(value)).
496template <typename T, typename M>
497class MatcherCastImpl {
498 public:
499 static Matcher<T> Cast(M polymorphic_matcher) {
500 return Matcher<T>(polymorphic_matcher);
501 }
502};
503
504// This more specialized version is used when MatcherCast()'s argument
505// is already a Matcher. This only compiles when type T can be
506// statically converted to type U.
507template <typename T, typename U>
508class MatcherCastImpl<T, Matcher<U> > {
509 public:
510 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
511 return Matcher<T>(new Impl(source_matcher));
512 }
513 private:
514 class Impl : public MatcherInterface<T> {
515 public:
516 explicit Impl(const Matcher<U>& source_matcher)
517 : source_matcher_(source_matcher) {}
518
519 // We delegate the matching logic to the source matcher.
520 virtual bool Matches(T x) const {
521 return source_matcher_.Matches(static_cast<U>(x));
522 }
523
524 virtual void DescribeTo(::std::ostream* os) const {
525 source_matcher_.DescribeTo(os);
526 }
527
528 virtual void DescribeNegationTo(::std::ostream* os) const {
529 source_matcher_.DescribeNegationTo(os);
530 }
531
532 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
533 source_matcher_.ExplainMatchResultTo(static_cast<U>(x), os);
534 }
535 private:
536 const Matcher<U> source_matcher_;
537 };
538};
539
540// This even more specialized version is used for efficiently casting
541// a matcher to its own type.
542template <typename T>
543class MatcherCastImpl<T, Matcher<T> > {
544 public:
545 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
546};
547
548// Implements A<T>().
549template <typename T>
550class AnyMatcherImpl : public MatcherInterface<T> {
551 public:
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000552 virtual bool Matches(T /* x */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000553 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
554 virtual void DescribeNegationTo(::std::ostream* os) const {
555 // This is mostly for completeness' safe, as it's not very useful
556 // to write Not(A<bool>()). However we cannot completely rule out
557 // such a possibility, and it doesn't hurt to be prepared.
558 *os << "never matches";
559 }
560};
561
562// Implements _, a matcher that matches any value of any
563// type. This is a polymorphic matcher, so we need a template type
564// conversion operator to make it appearing as a Matcher<T> for any
565// type T.
566class AnythingMatcher {
567 public:
568 template <typename T>
569 operator Matcher<T>() const { return A<T>(); }
570};
571
572// Implements a matcher that compares a given value with a
573// pre-supplied value using one of the ==, <=, <, etc, operators. The
574// two values being compared don't have to have the same type.
575//
576// The matcher defined here is polymorphic (for example, Eq(5) can be
577// used to match an int, a short, a double, etc). Therefore we use
578// a template type conversion operator in the implementation.
579//
580// We define this as a macro in order to eliminate duplicated source
581// code.
582//
583// The following template definition assumes that the Rhs parameter is
584// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wane0d051e2009-02-19 00:33:37 +0000585#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000586 template <typename Rhs> class name##Matcher { \
587 public: \
588 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
589 template <typename Lhs> \
590 operator Matcher<Lhs>() const { \
591 return MakeMatcher(new Impl<Lhs>(rhs_)); \
592 } \
593 private: \
594 template <typename Lhs> \
595 class Impl : public MatcherInterface<Lhs> { \
596 public: \
597 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
598 virtual bool Matches(Lhs lhs) const { return lhs op rhs_; } \
599 virtual void DescribeTo(::std::ostream* os) const { \
600 *os << "is " relation " "; \
601 UniversalPrinter<Rhs>::Print(rhs_, os); \
602 } \
603 virtual void DescribeNegationTo(::std::ostream* os) const { \
604 *os << "is not " relation " "; \
605 UniversalPrinter<Rhs>::Print(rhs_, os); \
606 } \
607 private: \
608 Rhs rhs_; \
609 }; \
610 Rhs rhs_; \
611 }
612
613// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
614// respectively.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000615GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "equal to");
616GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "greater than or equal to");
617GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "greater than");
618GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "less than or equal to");
619GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "less than");
620GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "not equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000621
zhanyong.wane0d051e2009-02-19 00:33:37 +0000622#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000623
624// Implements the polymorphic NotNull() matcher, which matches any
625// pointer that is not NULL.
626class NotNullMatcher {
627 public:
628 template <typename T>
629 bool Matches(T* p) const { return p != NULL; }
630
631 void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; }
632 void DescribeNegationTo(::std::ostream* os) const {
633 *os << "is NULL";
634 }
635};
636
637// Ref(variable) matches any argument that is a reference to
638// 'variable'. This matcher is polymorphic as it can match any
639// super type of the type of 'variable'.
640//
641// The RefMatcher template class implements Ref(variable). It can
642// only be instantiated with a reference type. This prevents a user
643// from mistakenly using Ref(x) to match a non-reference function
644// argument. For example, the following will righteously cause a
645// compiler error:
646//
647// int n;
648// Matcher<int> m1 = Ref(n); // This won't compile.
649// Matcher<int&> m2 = Ref(n); // This will compile.
650template <typename T>
651class RefMatcher;
652
653template <typename T>
654class RefMatcher<T&> {
655 // Google Mock is a generic framework and thus needs to support
656 // mocking any function types, including those that take non-const
657 // reference arguments. Therefore the template parameter T (and
658 // Super below) can be instantiated to either a const type or a
659 // non-const type.
660 public:
661 // RefMatcher() takes a T& instead of const T&, as we want the
662 // compiler to catch using Ref(const_value) as a matcher for a
663 // non-const reference.
664 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
665
666 template <typename Super>
667 operator Matcher<Super&>() const {
668 // By passing object_ (type T&) to Impl(), which expects a Super&,
669 // we make sure that Super is a super type of T. In particular,
670 // this catches using Ref(const_value) as a matcher for a
671 // non-const reference, as you cannot implicitly convert a const
672 // reference to a non-const reference.
673 return MakeMatcher(new Impl<Super>(object_));
674 }
675 private:
676 template <typename Super>
677 class Impl : public MatcherInterface<Super&> {
678 public:
679 explicit Impl(Super& x) : object_(x) {} // NOLINT
680
681 // Matches() takes a Super& (as opposed to const Super&) in
682 // order to match the interface MatcherInterface<Super&>.
683 virtual bool Matches(Super& x) const { return &x == &object_; } // NOLINT
684
685 virtual void DescribeTo(::std::ostream* os) const {
686 *os << "references the variable ";
687 UniversalPrinter<Super&>::Print(object_, os);
688 }
689
690 virtual void DescribeNegationTo(::std::ostream* os) const {
691 *os << "does not reference the variable ";
692 UniversalPrinter<Super&>::Print(object_, os);
693 }
694
695 virtual void ExplainMatchResultTo(Super& x, // NOLINT
696 ::std::ostream* os) const {
697 *os << "is located @" << static_cast<const void*>(&x);
698 }
699 private:
700 const Super& object_;
701 };
702
703 T& object_;
704};
705
706// Polymorphic helper functions for narrow and wide string matchers.
707inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
708 return String::CaseInsensitiveCStringEquals(lhs, rhs);
709}
710
711inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
712 const wchar_t* rhs) {
713 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
714}
715
716// String comparison for narrow or wide strings that can have embedded NUL
717// characters.
718template <typename StringType>
719bool CaseInsensitiveStringEquals(const StringType& s1,
720 const StringType& s2) {
721 // Are the heads equal?
722 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
723 return false;
724 }
725
726 // Skip the equal heads.
727 const typename StringType::value_type nul = 0;
728 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
729
730 // Are we at the end of either s1 or s2?
731 if (i1 == StringType::npos || i2 == StringType::npos) {
732 return i1 == i2;
733 }
734
735 // Are the tails equal?
736 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
737}
738
739// String matchers.
740
741// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
742template <typename StringType>
743class StrEqualityMatcher {
744 public:
745 typedef typename StringType::const_pointer ConstCharPointer;
746
747 StrEqualityMatcher(const StringType& str, bool expect_eq,
748 bool case_sensitive)
749 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
750
751 // When expect_eq_ is true, returns true iff s is equal to string_;
752 // otherwise returns true iff s is not equal to string_.
753 bool Matches(ConstCharPointer s) const {
754 if (s == NULL) {
755 return !expect_eq_;
756 }
757 return Matches(StringType(s));
758 }
759
760 bool Matches(const StringType& s) const {
761 const bool eq = case_sensitive_ ? s == string_ :
762 CaseInsensitiveStringEquals(s, string_);
763 return expect_eq_ == eq;
764 }
765
766 void DescribeTo(::std::ostream* os) const {
767 DescribeToHelper(expect_eq_, os);
768 }
769
770 void DescribeNegationTo(::std::ostream* os) const {
771 DescribeToHelper(!expect_eq_, os);
772 }
773 private:
774 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
775 *os << "is ";
776 if (!expect_eq) {
777 *os << "not ";
778 }
779 *os << "equal to ";
780 if (!case_sensitive_) {
781 *os << "(ignoring case) ";
782 }
783 UniversalPrinter<StringType>::Print(string_, os);
784 }
785
786 const StringType string_;
787 const bool expect_eq_;
788 const bool case_sensitive_;
789};
790
791// Implements the polymorphic HasSubstr(substring) matcher, which
792// can be used as a Matcher<T> as long as T can be converted to a
793// string.
794template <typename StringType>
795class HasSubstrMatcher {
796 public:
797 typedef typename StringType::const_pointer ConstCharPointer;
798
799 explicit HasSubstrMatcher(const StringType& substring)
800 : substring_(substring) {}
801
802 // These overloaded methods allow HasSubstr(substring) to be used as a
803 // Matcher<T> as long as T can be converted to string. Returns true
804 // iff s contains substring_ as a substring.
805 bool Matches(ConstCharPointer s) const {
806 return s != NULL && Matches(StringType(s));
807 }
808
809 bool Matches(const StringType& s) const {
810 return s.find(substring_) != StringType::npos;
811 }
812
813 // Describes what this matcher matches.
814 void DescribeTo(::std::ostream* os) const {
815 *os << "has substring ";
816 UniversalPrinter<StringType>::Print(substring_, os);
817 }
818
819 void DescribeNegationTo(::std::ostream* os) const {
820 *os << "has no substring ";
821 UniversalPrinter<StringType>::Print(substring_, os);
822 }
823 private:
824 const StringType substring_;
825};
826
827// Implements the polymorphic StartsWith(substring) matcher, which
828// can be used as a Matcher<T> as long as T can be converted to a
829// string.
830template <typename StringType>
831class StartsWithMatcher {
832 public:
833 typedef typename StringType::const_pointer ConstCharPointer;
834
835 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
836 }
837
838 // These overloaded methods allow StartsWith(prefix) to be used as a
839 // Matcher<T> as long as T can be converted to string. Returns true
840 // iff s starts with prefix_.
841 bool Matches(ConstCharPointer s) const {
842 return s != NULL && Matches(StringType(s));
843 }
844
845 bool Matches(const StringType& s) const {
846 return s.length() >= prefix_.length() &&
847 s.substr(0, prefix_.length()) == prefix_;
848 }
849
850 void DescribeTo(::std::ostream* os) const {
851 *os << "starts with ";
852 UniversalPrinter<StringType>::Print(prefix_, os);
853 }
854
855 void DescribeNegationTo(::std::ostream* os) const {
856 *os << "doesn't start with ";
857 UniversalPrinter<StringType>::Print(prefix_, os);
858 }
859 private:
860 const StringType prefix_;
861};
862
863// Implements the polymorphic EndsWith(substring) matcher, which
864// can be used as a Matcher<T> as long as T can be converted to a
865// string.
866template <typename StringType>
867class EndsWithMatcher {
868 public:
869 typedef typename StringType::const_pointer ConstCharPointer;
870
871 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
872
873 // These overloaded methods allow EndsWith(suffix) to be used as a
874 // Matcher<T> as long as T can be converted to string. Returns true
875 // iff s ends with suffix_.
876 bool Matches(ConstCharPointer s) const {
877 return s != NULL && Matches(StringType(s));
878 }
879
880 bool Matches(const StringType& s) const {
881 return s.length() >= suffix_.length() &&
882 s.substr(s.length() - suffix_.length()) == suffix_;
883 }
884
885 void DescribeTo(::std::ostream* os) const {
886 *os << "ends with ";
887 UniversalPrinter<StringType>::Print(suffix_, os);
888 }
889
890 void DescribeNegationTo(::std::ostream* os) const {
891 *os << "doesn't end with ";
892 UniversalPrinter<StringType>::Print(suffix_, os);
893 }
894 private:
895 const StringType suffix_;
896};
897
898#if GMOCK_HAS_REGEX
899
900// Implements polymorphic matchers MatchesRegex(regex) and
901// ContainsRegex(regex), which can be used as a Matcher<T> as long as
902// T can be converted to a string.
903class MatchesRegexMatcher {
904 public:
905 MatchesRegexMatcher(const RE* regex, bool full_match)
906 : regex_(regex), full_match_(full_match) {}
907
908 // These overloaded methods allow MatchesRegex(regex) to be used as
909 // a Matcher<T> as long as T can be converted to string. Returns
910 // true iff s matches regular expression regex. When full_match_ is
911 // true, a full match is done; otherwise a partial match is done.
912 bool Matches(const char* s) const {
913 return s != NULL && Matches(internal::string(s));
914 }
915
916 bool Matches(const internal::string& s) const {
917 return full_match_ ? RE::FullMatch(s, *regex_) :
918 RE::PartialMatch(s, *regex_);
919 }
920
921 void DescribeTo(::std::ostream* os) const {
922 *os << (full_match_ ? "matches" : "contains")
923 << " regular expression ";
924 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
925 }
926
927 void DescribeNegationTo(::std::ostream* os) const {
928 *os << "doesn't " << (full_match_ ? "match" : "contain")
929 << " regular expression ";
930 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
931 }
932 private:
933 const internal::linked_ptr<const RE> regex_;
934 const bool full_match_;
935};
936
937#endif // GMOCK_HAS_REGEX
938
939// Implements a matcher that compares the two fields of a 2-tuple
940// using one of the ==, <=, <, etc, operators. The two fields being
941// compared don't have to have the same type.
942//
943// The matcher defined here is polymorphic (for example, Eq() can be
944// used to match a tuple<int, short>, a tuple<const long&, double>,
945// etc). Therefore we use a template type conversion operator in the
946// implementation.
947//
948// We define this as a macro in order to eliminate duplicated source
949// code.
zhanyong.wan2661c682009-06-09 05:42:12 +0000950#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op) \
shiqiane35fdd92008-12-10 05:08:54 +0000951 class name##2Matcher { \
952 public: \
953 template <typename T1, typename T2> \
954 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
955 return MakeMatcher(new Impl<T1, T2>); \
956 } \
957 private: \
958 template <typename T1, typename T2> \
959 class Impl : public MatcherInterface<const ::std::tr1::tuple<T1, T2>&> { \
960 public: \
961 virtual bool Matches(const ::std::tr1::tuple<T1, T2>& args) const { \
962 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
963 } \
964 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +0000965 *os << "are a pair (x, y) where x " #op " y"; \
shiqiane35fdd92008-12-10 05:08:54 +0000966 } \
967 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +0000968 *os << "are a pair (x, y) where x " #op " y is false"; \
shiqiane35fdd92008-12-10 05:08:54 +0000969 } \
970 }; \
971 }
972
973// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wan2661c682009-06-09 05:42:12 +0000974GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==);
975GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ge, >=);
976GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Gt, >);
977GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Le, <=);
978GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Lt, <);
979GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=);
shiqiane35fdd92008-12-10 05:08:54 +0000980
zhanyong.wane0d051e2009-02-19 00:33:37 +0000981#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000982
zhanyong.wanc6a41232009-05-13 23:38:40 +0000983// Implements the Not(...) matcher for a particular argument type T.
984// We do not nest it inside the NotMatcher class template, as that
985// will prevent different instantiations of NotMatcher from sharing
986// the same NotMatcherImpl<T> class.
987template <typename T>
988class NotMatcherImpl : public MatcherInterface<T> {
989 public:
990 explicit NotMatcherImpl(const Matcher<T>& matcher)
991 : matcher_(matcher) {}
992
993 virtual bool Matches(T x) const {
994 return !matcher_.Matches(x);
995 }
996
997 virtual void DescribeTo(::std::ostream* os) const {
998 matcher_.DescribeNegationTo(os);
999 }
1000
1001 virtual void DescribeNegationTo(::std::ostream* os) const {
1002 matcher_.DescribeTo(os);
1003 }
1004
1005 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1006 matcher_.ExplainMatchResultTo(x, os);
1007 }
1008 private:
1009 const Matcher<T> matcher_;
1010};
1011
shiqiane35fdd92008-12-10 05:08:54 +00001012// Implements the Not(m) matcher, which matches a value that doesn't
1013// match matcher m.
1014template <typename InnerMatcher>
1015class NotMatcher {
1016 public:
1017 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1018
1019 // This template type conversion operator allows Not(m) to be used
1020 // to match any type m can match.
1021 template <typename T>
1022 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001023 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001024 }
1025 private:
shiqiane35fdd92008-12-10 05:08:54 +00001026 InnerMatcher matcher_;
1027};
1028
zhanyong.wanc6a41232009-05-13 23:38:40 +00001029// Implements the AllOf(m1, m2) matcher for a particular argument type
1030// T. We do not nest it inside the BothOfMatcher class template, as
1031// that will prevent different instantiations of BothOfMatcher from
1032// sharing the same BothOfMatcherImpl<T> class.
1033template <typename T>
1034class BothOfMatcherImpl : public MatcherInterface<T> {
1035 public:
1036 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1037 : matcher1_(matcher1), matcher2_(matcher2) {}
1038
1039 virtual bool Matches(T x) const {
1040 return matcher1_.Matches(x) && matcher2_.Matches(x);
1041 }
1042
1043 virtual void DescribeTo(::std::ostream* os) const {
1044 *os << "(";
1045 matcher1_.DescribeTo(os);
1046 *os << ") and (";
1047 matcher2_.DescribeTo(os);
1048 *os << ")";
1049 }
1050
1051 virtual void DescribeNegationTo(::std::ostream* os) const {
1052 *os << "not ";
1053 DescribeTo(os);
1054 }
1055
1056 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1057 if (Matches(x)) {
1058 // When both matcher1_ and matcher2_ match x, we need to
1059 // explain why *both* of them match.
1060 ::std::stringstream ss1;
1061 matcher1_.ExplainMatchResultTo(x, &ss1);
1062 const internal::string s1 = ss1.str();
1063
1064 ::std::stringstream ss2;
1065 matcher2_.ExplainMatchResultTo(x, &ss2);
1066 const internal::string s2 = ss2.str();
1067
1068 if (s1 == "") {
1069 *os << s2;
1070 } else {
1071 *os << s1;
1072 if (s2 != "") {
1073 *os << "; " << s2;
1074 }
1075 }
1076 } else {
1077 // Otherwise we only need to explain why *one* of them fails
1078 // to match.
1079 if (!matcher1_.Matches(x)) {
1080 matcher1_.ExplainMatchResultTo(x, os);
1081 } else {
1082 matcher2_.ExplainMatchResultTo(x, os);
1083 }
1084 }
1085 }
1086 private:
1087 const Matcher<T> matcher1_;
1088 const Matcher<T> matcher2_;
1089};
1090
shiqiane35fdd92008-12-10 05:08:54 +00001091// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1092// matches a value that matches all of the matchers m_1, ..., and m_n.
1093template <typename Matcher1, typename Matcher2>
1094class BothOfMatcher {
1095 public:
1096 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1097 : matcher1_(matcher1), matcher2_(matcher2) {}
1098
1099 // This template type conversion operator allows a
1100 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1101 // both Matcher1 and Matcher2 can match.
1102 template <typename T>
1103 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001104 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1105 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001106 }
1107 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001108 Matcher1 matcher1_;
1109 Matcher2 matcher2_;
1110};
shiqiane35fdd92008-12-10 05:08:54 +00001111
zhanyong.wanc6a41232009-05-13 23:38:40 +00001112// Implements the AnyOf(m1, m2) matcher for a particular argument type
1113// T. We do not nest it inside the AnyOfMatcher class template, as
1114// that will prevent different instantiations of AnyOfMatcher from
1115// sharing the same EitherOfMatcherImpl<T> class.
1116template <typename T>
1117class EitherOfMatcherImpl : public MatcherInterface<T> {
1118 public:
1119 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1120 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001121
zhanyong.wanc6a41232009-05-13 23:38:40 +00001122 virtual bool Matches(T x) const {
1123 return matcher1_.Matches(x) || matcher2_.Matches(x);
1124 }
shiqiane35fdd92008-12-10 05:08:54 +00001125
zhanyong.wanc6a41232009-05-13 23:38:40 +00001126 virtual void DescribeTo(::std::ostream* os) const {
1127 *os << "(";
1128 matcher1_.DescribeTo(os);
1129 *os << ") or (";
1130 matcher2_.DescribeTo(os);
1131 *os << ")";
1132 }
shiqiane35fdd92008-12-10 05:08:54 +00001133
zhanyong.wanc6a41232009-05-13 23:38:40 +00001134 virtual void DescribeNegationTo(::std::ostream* os) const {
1135 *os << "not ";
1136 DescribeTo(os);
1137 }
shiqiane35fdd92008-12-10 05:08:54 +00001138
zhanyong.wanc6a41232009-05-13 23:38:40 +00001139 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1140 if (Matches(x)) {
1141 // If either matcher1_ or matcher2_ matches x, we just need
1142 // to explain why *one* of them matches.
1143 if (matcher1_.Matches(x)) {
1144 matcher1_.ExplainMatchResultTo(x, os);
shiqiane35fdd92008-12-10 05:08:54 +00001145 } else {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001146 matcher2_.ExplainMatchResultTo(x, os);
1147 }
1148 } else {
1149 // Otherwise we need to explain why *neither* matches.
1150 ::std::stringstream ss1;
1151 matcher1_.ExplainMatchResultTo(x, &ss1);
1152 const internal::string s1 = ss1.str();
1153
1154 ::std::stringstream ss2;
1155 matcher2_.ExplainMatchResultTo(x, &ss2);
1156 const internal::string s2 = ss2.str();
1157
1158 if (s1 == "") {
1159 *os << s2;
1160 } else {
1161 *os << s1;
1162 if (s2 != "") {
1163 *os << "; " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001164 }
1165 }
1166 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001167 }
1168 private:
1169 const Matcher<T> matcher1_;
1170 const Matcher<T> matcher2_;
shiqiane35fdd92008-12-10 05:08:54 +00001171};
1172
1173// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1174// matches a value that matches at least one of the matchers m_1, ...,
1175// and m_n.
1176template <typename Matcher1, typename Matcher2>
1177class EitherOfMatcher {
1178 public:
1179 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1180 : matcher1_(matcher1), matcher2_(matcher2) {}
1181
1182 // This template type conversion operator allows a
1183 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1184 // both Matcher1 and Matcher2 can match.
1185 template <typename T>
1186 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001187 return Matcher<T>(new EitherOfMatcherImpl<T>(
1188 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001189 }
1190 private:
shiqiane35fdd92008-12-10 05:08:54 +00001191 Matcher1 matcher1_;
1192 Matcher2 matcher2_;
1193};
1194
1195// Used for implementing Truly(pred), which turns a predicate into a
1196// matcher.
1197template <typename Predicate>
1198class TrulyMatcher {
1199 public:
1200 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1201
1202 // This method template allows Truly(pred) to be used as a matcher
1203 // for type T where T is the argument type of predicate 'pred'. The
1204 // argument is passed by reference as the predicate may be
1205 // interested in the address of the argument.
1206 template <typename T>
zhanyong.wan16cf4732009-05-14 20:55:30 +00001207 bool Matches(T& x) const { // NOLINT
zhanyong.wan652540a2009-02-23 23:37:29 +00001208#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001209 // MSVC warns about converting a value into bool (warning 4800).
1210#pragma warning(push) // Saves the current warning state.
1211#pragma warning(disable:4800) // Temporarily disables warning 4800.
1212#endif // GTEST_OS_WINDOWS
1213 return predicate_(x);
zhanyong.wan652540a2009-02-23 23:37:29 +00001214#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001215#pragma warning(pop) // Restores the warning state.
1216#endif // GTEST_OS_WINDOWS
1217 }
1218
1219 void DescribeTo(::std::ostream* os) const {
1220 *os << "satisfies the given predicate";
1221 }
1222
1223 void DescribeNegationTo(::std::ostream* os) const {
1224 *os << "doesn't satisfy the given predicate";
1225 }
1226 private:
1227 Predicate predicate_;
1228};
1229
1230// Used for implementing Matches(matcher), which turns a matcher into
1231// a predicate.
1232template <typename M>
1233class MatcherAsPredicate {
1234 public:
1235 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1236
1237 // This template operator() allows Matches(m) to be used as a
1238 // predicate on type T where m is a matcher on type T.
1239 //
1240 // The argument x is passed by reference instead of by value, as
1241 // some matcher may be interested in its address (e.g. as in
1242 // Matches(Ref(n))(x)).
1243 template <typename T>
1244 bool operator()(const T& x) const {
1245 // We let matcher_ commit to a particular type here instead of
1246 // when the MatcherAsPredicate object was constructed. This
1247 // allows us to write Matches(m) where m is a polymorphic matcher
1248 // (e.g. Eq(5)).
1249 //
1250 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1251 // compile when matcher_ has type Matcher<const T&>; if we write
1252 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1253 // when matcher_ has type Matcher<T>; if we just write
1254 // matcher_.Matches(x), it won't compile when matcher_ is
1255 // polymorphic, e.g. Eq(5).
1256 //
1257 // MatcherCast<const T&>() is necessary for making the code work
1258 // in all of the above situations.
1259 return MatcherCast<const T&>(matcher_).Matches(x);
1260 }
1261 private:
1262 M matcher_;
1263};
1264
1265// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1266// argument M must be a type that can be converted to a matcher.
1267template <typename M>
1268class PredicateFormatterFromMatcher {
1269 public:
1270 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1271
1272 // This template () operator allows a PredicateFormatterFromMatcher
1273 // object to act as a predicate-formatter suitable for using with
1274 // Google Test's EXPECT_PRED_FORMAT1() macro.
1275 template <typename T>
1276 AssertionResult operator()(const char* value_text, const T& x) const {
1277 // We convert matcher_ to a Matcher<const T&> *now* instead of
1278 // when the PredicateFormatterFromMatcher object was constructed,
1279 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1280 // know which type to instantiate it to until we actually see the
1281 // type of x here.
1282 //
1283 // We write MatcherCast<const T&>(matcher_) instead of
1284 // Matcher<const T&>(matcher_), as the latter won't compile when
1285 // matcher_ has type Matcher<T> (e.g. An<int>()).
1286 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
1287 if (matcher.Matches(x)) {
1288 return AssertionSuccess();
1289 } else {
1290 ::std::stringstream ss;
1291 ss << "Value of: " << value_text << "\n"
1292 << "Expected: ";
1293 matcher.DescribeTo(&ss);
1294 ss << "\n Actual: ";
1295 UniversalPrinter<T>::Print(x, &ss);
1296 ExplainMatchResultAsNeededTo<const T&>(matcher, x, &ss);
1297 return AssertionFailure(Message() << ss.str());
1298 }
1299 }
1300 private:
1301 const M matcher_;
1302};
1303
1304// A helper function for converting a matcher to a predicate-formatter
1305// without the user needing to explicitly write the type. This is
1306// used for implementing ASSERT_THAT() and EXPECT_THAT().
1307template <typename M>
1308inline PredicateFormatterFromMatcher<M>
1309MakePredicateFormatterFromMatcher(const M& matcher) {
1310 return PredicateFormatterFromMatcher<M>(matcher);
1311}
1312
1313// Implements the polymorphic floating point equality matcher, which
1314// matches two float values using ULP-based approximation. The
1315// template is meant to be instantiated with FloatType being either
1316// float or double.
1317template <typename FloatType>
1318class FloatingEqMatcher {
1319 public:
1320 // Constructor for FloatingEqMatcher.
1321 // The matcher's input will be compared with rhs. The matcher treats two
1322 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1323 // equality comparisons between NANs will always return false.
1324 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1325 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1326
1327 // Implements floating point equality matcher as a Matcher<T>.
1328 template <typename T>
1329 class Impl : public MatcherInterface<T> {
1330 public:
1331 Impl(FloatType rhs, bool nan_eq_nan) :
1332 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1333
1334 virtual bool Matches(T value) const {
1335 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1336
1337 // Compares NaNs first, if nan_eq_nan_ is true.
1338 if (nan_eq_nan_ && lhs.is_nan()) {
1339 return rhs.is_nan();
1340 }
1341
1342 return lhs.AlmostEquals(rhs);
1343 }
1344
1345 virtual void DescribeTo(::std::ostream* os) const {
1346 // os->precision() returns the previously set precision, which we
1347 // store to restore the ostream to its original configuration
1348 // after outputting.
1349 const ::std::streamsize old_precision = os->precision(
1350 ::std::numeric_limits<FloatType>::digits10 + 2);
1351 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1352 if (nan_eq_nan_) {
1353 *os << "is NaN";
1354 } else {
1355 *os << "never matches";
1356 }
1357 } else {
1358 *os << "is approximately " << rhs_;
1359 }
1360 os->precision(old_precision);
1361 }
1362
1363 virtual void DescribeNegationTo(::std::ostream* os) const {
1364 // As before, get original precision.
1365 const ::std::streamsize old_precision = os->precision(
1366 ::std::numeric_limits<FloatType>::digits10 + 2);
1367 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1368 if (nan_eq_nan_) {
1369 *os << "is not NaN";
1370 } else {
1371 *os << "is anything";
1372 }
1373 } else {
1374 *os << "is not approximately " << rhs_;
1375 }
1376 // Restore original precision.
1377 os->precision(old_precision);
1378 }
1379
1380 private:
1381 const FloatType rhs_;
1382 const bool nan_eq_nan_;
1383 };
1384
1385 // The following 3 type conversion operators allow FloatEq(rhs) and
1386 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1387 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1388 // (While Google's C++ coding style doesn't allow arguments passed
1389 // by non-const reference, we may see them in code not conforming to
1390 // the style. Therefore Google Mock needs to support them.)
1391 operator Matcher<FloatType>() const {
1392 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1393 }
1394
1395 operator Matcher<const FloatType&>() const {
1396 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1397 }
1398
1399 operator Matcher<FloatType&>() const {
1400 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1401 }
1402 private:
1403 const FloatType rhs_;
1404 const bool nan_eq_nan_;
1405};
1406
1407// Implements the Pointee(m) matcher for matching a pointer whose
1408// pointee matches matcher m. The pointer can be either raw or smart.
1409template <typename InnerMatcher>
1410class PointeeMatcher {
1411 public:
1412 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1413
1414 // This type conversion operator template allows Pointee(m) to be
1415 // used as a matcher for any pointer type whose pointee type is
1416 // compatible with the inner matcher, where type Pointer can be
1417 // either a raw pointer or a smart pointer.
1418 //
1419 // The reason we do this instead of relying on
1420 // MakePolymorphicMatcher() is that the latter is not flexible
1421 // enough for implementing the DescribeTo() method of Pointee().
1422 template <typename Pointer>
1423 operator Matcher<Pointer>() const {
1424 return MakeMatcher(new Impl<Pointer>(matcher_));
1425 }
1426 private:
1427 // The monomorphic implementation that works for a particular pointer type.
1428 template <typename Pointer>
1429 class Impl : public MatcherInterface<Pointer> {
1430 public:
zhanyong.wane0d051e2009-02-19 00:33:37 +00001431 typedef typename PointeeOf<GMOCK_REMOVE_CONST_( // NOLINT
1432 GMOCK_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001433
1434 explicit Impl(const InnerMatcher& matcher)
1435 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1436
1437 virtual bool Matches(Pointer p) const {
1438 return GetRawPointer(p) != NULL && matcher_.Matches(*p);
1439 }
1440
1441 virtual void DescribeTo(::std::ostream* os) const {
1442 *os << "points to a value that ";
1443 matcher_.DescribeTo(os);
1444 }
1445
1446 virtual void DescribeNegationTo(::std::ostream* os) const {
1447 *os << "does not point to a value that ";
1448 matcher_.DescribeTo(os);
1449 }
1450
1451 virtual void ExplainMatchResultTo(Pointer pointer,
1452 ::std::ostream* os) const {
1453 if (GetRawPointer(pointer) == NULL)
1454 return;
1455
1456 ::std::stringstream ss;
1457 matcher_.ExplainMatchResultTo(*pointer, &ss);
1458 const internal::string s = ss.str();
1459 if (s != "") {
1460 *os << "points to a value that " << s;
1461 }
1462 }
1463 private:
1464 const Matcher<const Pointee&> matcher_;
1465 };
1466
1467 const InnerMatcher matcher_;
1468};
1469
1470// Implements the Field() matcher for matching a field (i.e. member
1471// variable) of an object.
1472template <typename Class, typename FieldType>
1473class FieldMatcher {
1474 public:
1475 FieldMatcher(FieldType Class::*field,
1476 const Matcher<const FieldType&>& matcher)
1477 : field_(field), matcher_(matcher) {}
1478
1479 // Returns true iff the inner matcher matches obj.field.
1480 bool Matches(const Class& obj) const {
1481 return matcher_.Matches(obj.*field_);
1482 }
1483
1484 // Returns true iff the inner matcher matches obj->field.
1485 bool Matches(const Class* p) const {
1486 return (p != NULL) && matcher_.Matches(p->*field_);
1487 }
1488
1489 void DescribeTo(::std::ostream* os) const {
1490 *os << "the given field ";
1491 matcher_.DescribeTo(os);
1492 }
1493
1494 void DescribeNegationTo(::std::ostream* os) const {
1495 *os << "the given field ";
1496 matcher_.DescribeNegationTo(os);
1497 }
1498
zhanyong.wan18490652009-05-11 18:54:08 +00001499 // The first argument of ExplainMatchResultTo() is needed to help
1500 // Symbian's C++ compiler choose which overload to use. Its type is
1501 // true_type iff the Field() matcher is used to match a pointer.
1502 void ExplainMatchResultTo(false_type /* is_not_pointer */, const Class& obj,
1503 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001504 ::std::stringstream ss;
1505 matcher_.ExplainMatchResultTo(obj.*field_, &ss);
1506 const internal::string s = ss.str();
1507 if (s != "") {
1508 *os << "the given field " << s;
1509 }
1510 }
1511
zhanyong.wan18490652009-05-11 18:54:08 +00001512 void ExplainMatchResultTo(true_type /* is_pointer */, const Class* p,
1513 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001514 if (p != NULL) {
zhanyong.wan18490652009-05-11 18:54:08 +00001515 // Since *p has a field, it must be a class/struct/union type
1516 // and thus cannot be a pointer. Therefore we pass false_type()
1517 // as the first argument.
1518 ExplainMatchResultTo(false_type(), *p, os);
shiqiane35fdd92008-12-10 05:08:54 +00001519 }
1520 }
1521 private:
1522 const FieldType Class::*field_;
1523 const Matcher<const FieldType&> matcher_;
1524};
1525
zhanyong.wan18490652009-05-11 18:54:08 +00001526// Explains the result of matching an object or pointer against a field matcher.
1527template <typename Class, typename FieldType, typename T>
shiqiane35fdd92008-12-10 05:08:54 +00001528void ExplainMatchResultTo(const FieldMatcher<Class, FieldType>& matcher,
zhanyong.wan18490652009-05-11 18:54:08 +00001529 const T& value, ::std::ostream* os) {
1530 matcher.ExplainMatchResultTo(
1531 typename ::testing::internal::is_pointer<T>::type(), value, os);
shiqiane35fdd92008-12-10 05:08:54 +00001532}
1533
1534// Implements the Property() matcher for matching a property
1535// (i.e. return value of a getter method) of an object.
1536template <typename Class, typename PropertyType>
1537class PropertyMatcher {
1538 public:
1539 // The property may have a reference type, so 'const PropertyType&'
1540 // may cause double references and fail to compile. That's why we
1541 // need GMOCK_REFERENCE_TO_CONST, which works regardless of
1542 // PropertyType being a reference or not.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001543 typedef GMOCK_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001544
1545 PropertyMatcher(PropertyType (Class::*property)() const,
1546 const Matcher<RefToConstProperty>& matcher)
1547 : property_(property), matcher_(matcher) {}
1548
1549 // Returns true iff obj.property() matches the inner matcher.
1550 bool Matches(const Class& obj) const {
1551 return matcher_.Matches((obj.*property_)());
1552 }
1553
1554 // Returns true iff p->property() matches the inner matcher.
1555 bool Matches(const Class* p) const {
1556 return (p != NULL) && matcher_.Matches((p->*property_)());
1557 }
1558
1559 void DescribeTo(::std::ostream* os) const {
1560 *os << "the given property ";
1561 matcher_.DescribeTo(os);
1562 }
1563
1564 void DescribeNegationTo(::std::ostream* os) const {
1565 *os << "the given property ";
1566 matcher_.DescribeNegationTo(os);
1567 }
1568
zhanyong.wan18490652009-05-11 18:54:08 +00001569 // The first argument of ExplainMatchResultTo() is needed to help
1570 // Symbian's C++ compiler choose which overload to use. Its type is
1571 // true_type iff the Property() matcher is used to match a pointer.
1572 void ExplainMatchResultTo(false_type /* is_not_pointer */, const Class& obj,
1573 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001574 ::std::stringstream ss;
1575 matcher_.ExplainMatchResultTo((obj.*property_)(), &ss);
1576 const internal::string s = ss.str();
1577 if (s != "") {
1578 *os << "the given property " << s;
1579 }
1580 }
1581
zhanyong.wan18490652009-05-11 18:54:08 +00001582 void ExplainMatchResultTo(true_type /* is_pointer */, const Class* p,
1583 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001584 if (p != NULL) {
zhanyong.wan18490652009-05-11 18:54:08 +00001585 // Since *p has a property method, it must be a
1586 // class/struct/union type and thus cannot be a pointer.
1587 // Therefore we pass false_type() as the first argument.
1588 ExplainMatchResultTo(false_type(), *p, os);
shiqiane35fdd92008-12-10 05:08:54 +00001589 }
1590 }
1591 private:
1592 PropertyType (Class::*property_)() const;
1593 const Matcher<RefToConstProperty> matcher_;
1594};
1595
zhanyong.wan18490652009-05-11 18:54:08 +00001596// Explains the result of matching an object or pointer against a
1597// property matcher.
1598template <typename Class, typename PropertyType, typename T>
shiqiane35fdd92008-12-10 05:08:54 +00001599void ExplainMatchResultTo(const PropertyMatcher<Class, PropertyType>& matcher,
zhanyong.wan18490652009-05-11 18:54:08 +00001600 const T& value, ::std::ostream* os) {
1601 matcher.ExplainMatchResultTo(
1602 typename ::testing::internal::is_pointer<T>::type(), value, os);
shiqiane35fdd92008-12-10 05:08:54 +00001603}
1604
1605// Type traits specifying various features of different functors for ResultOf.
1606// The default template specifies features for functor objects.
1607// Functor classes have to typedef argument_type and result_type
1608// to be compatible with ResultOf.
1609template <typename Functor>
1610struct CallableTraits {
1611 typedef typename Functor::result_type ResultType;
1612 typedef Functor StorageType;
1613
1614 static void CheckIsValid(Functor functor) {}
1615 template <typename T>
1616 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1617};
1618
1619// Specialization for function pointers.
1620template <typename ArgType, typename ResType>
1621struct CallableTraits<ResType(*)(ArgType)> {
1622 typedef ResType ResultType;
1623 typedef ResType(*StorageType)(ArgType);
1624
1625 static void CheckIsValid(ResType(*f)(ArgType)) {
1626 GMOCK_CHECK_(f != NULL)
1627 << "NULL function pointer is passed into ResultOf().";
1628 }
1629 template <typename T>
1630 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1631 return (*f)(arg);
1632 }
1633};
1634
1635// Implements the ResultOf() matcher for matching a return value of a
1636// unary function of an object.
1637template <typename Callable>
1638class ResultOfMatcher {
1639 public:
1640 typedef typename CallableTraits<Callable>::ResultType ResultType;
1641
1642 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1643 : callable_(callable), matcher_(matcher) {
1644 CallableTraits<Callable>::CheckIsValid(callable_);
1645 }
1646
1647 template <typename T>
1648 operator Matcher<T>() const {
1649 return Matcher<T>(new Impl<T>(callable_, matcher_));
1650 }
1651
1652 private:
1653 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1654
1655 template <typename T>
1656 class Impl : public MatcherInterface<T> {
1657 public:
1658 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1659 : callable_(callable), matcher_(matcher) {}
1660 // Returns true iff callable_(obj) matches the inner matcher.
1661 // The calling syntax is different for different types of callables
1662 // so we abstract it in CallableTraits<Callable>::Invoke().
1663 virtual bool Matches(T obj) const {
1664 return matcher_.Matches(
1665 CallableTraits<Callable>::template Invoke<T>(callable_, obj));
1666 }
1667
1668 virtual void DescribeTo(::std::ostream* os) const {
1669 *os << "result of the given callable ";
1670 matcher_.DescribeTo(os);
1671 }
1672
1673 virtual void DescribeNegationTo(::std::ostream* os) const {
1674 *os << "result of the given callable ";
1675 matcher_.DescribeNegationTo(os);
1676 }
1677
1678 virtual void ExplainMatchResultTo(T obj, ::std::ostream* os) const {
1679 ::std::stringstream ss;
1680 matcher_.ExplainMatchResultTo(
1681 CallableTraits<Callable>::template Invoke<T>(callable_, obj),
1682 &ss);
1683 const internal::string s = ss.str();
1684 if (s != "")
1685 *os << "result of the given callable " << s;
1686 }
1687 private:
1688 // Functors often define operator() as non-const method even though
1689 // they are actualy stateless. But we need to use them even when
1690 // 'this' is a const pointer. It's the user's responsibility not to
1691 // use stateful callables with ResultOf(), which does't guarantee
1692 // how many times the callable will be invoked.
1693 mutable CallableStorageType callable_;
1694 const Matcher<ResultType> matcher_;
1695 }; // class Impl
1696
1697 const CallableStorageType callable_;
1698 const Matcher<ResultType> matcher_;
1699};
1700
1701// Explains the result of matching a value against a functor matcher.
1702template <typename T, typename Callable>
1703void ExplainMatchResultTo(const ResultOfMatcher<Callable>& matcher,
1704 T obj, ::std::ostream* os) {
1705 matcher.ExplainMatchResultTo(obj, os);
1706}
1707
zhanyong.wan6a896b52009-01-16 01:13:50 +00001708// Implements an equality matcher for any STL-style container whose elements
1709// support ==. This matcher is like Eq(), but its failure explanations provide
1710// more detailed information that is useful when the container is used as a set.
1711// The failure message reports elements that are in one of the operands but not
1712// the other. The failure messages do not report duplicate or out-of-order
1713// elements in the containers (which don't properly matter to sets, but can
1714// occur if the containers are vectors or lists, for example).
1715//
1716// Uses the container's const_iterator, value_type, operator ==,
1717// begin(), and end().
1718template <typename Container>
1719class ContainerEqMatcher {
1720 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00001721 typedef internal::StlContainerView<Container> View;
1722 typedef typename View::type StlContainer;
1723 typedef typename View::const_reference StlContainerReference;
1724
1725 // We make a copy of rhs in case the elements in it are modified
1726 // after this matcher is created.
1727 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
1728 // Makes sure the user doesn't instantiate this class template
1729 // with a const or reference type.
1730 testing::StaticAssertTypeEq<Container,
1731 GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))>();
1732 }
1733
1734 template <typename LhsContainer>
1735 bool Matches(const LhsContainer& lhs) const {
1736 // GMOCK_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
1737 // that causes LhsContainer to be a const type sometimes.
1738 typedef internal::StlContainerView<GMOCK_REMOVE_CONST_(LhsContainer)>
1739 LhsView;
1740 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
1741 return lhs_stl_container == rhs_;
1742 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00001743 void DescribeTo(::std::ostream* os) const {
1744 *os << "equals ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001745 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001746 }
1747 void DescribeNegationTo(::std::ostream* os) const {
1748 *os << "does not equal ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001749 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001750 }
1751
zhanyong.wanb8243162009-06-04 05:48:20 +00001752 template <typename LhsContainer>
1753 void ExplainMatchResultTo(const LhsContainer& lhs,
zhanyong.wan6a896b52009-01-16 01:13:50 +00001754 ::std::ostream* os) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00001755 // GMOCK_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
1756 // that causes LhsContainer to be a const type sometimes.
1757 typedef internal::StlContainerView<GMOCK_REMOVE_CONST_(LhsContainer)>
1758 LhsView;
1759 typedef typename LhsView::type LhsStlContainer;
1760 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
1761
zhanyong.wan6a896b52009-01-16 01:13:50 +00001762 // Something is different. Check for missing values first.
1763 bool printed_header = false;
zhanyong.wanb8243162009-06-04 05:48:20 +00001764 for (typename LhsStlContainer::const_iterator it =
1765 lhs_stl_container.begin();
1766 it != lhs_stl_container.end(); ++it) {
1767 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
1768 rhs_.end()) {
zhanyong.wan6a896b52009-01-16 01:13:50 +00001769 if (printed_header) {
1770 *os << ", ";
1771 } else {
1772 *os << "Only in actual: ";
1773 printed_header = true;
1774 }
zhanyong.wanb8243162009-06-04 05:48:20 +00001775 UniversalPrinter<typename LhsStlContainer::value_type>::Print(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001776 }
1777 }
1778
1779 // Now check for extra values.
1780 bool printed_header2 = false;
zhanyong.wanb8243162009-06-04 05:48:20 +00001781 for (typename StlContainer::const_iterator it = rhs_.begin();
zhanyong.wan6a896b52009-01-16 01:13:50 +00001782 it != rhs_.end(); ++it) {
zhanyong.wanb8243162009-06-04 05:48:20 +00001783 if (internal::ArrayAwareFind(
1784 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
1785 lhs_stl_container.end()) {
zhanyong.wan6a896b52009-01-16 01:13:50 +00001786 if (printed_header2) {
1787 *os << ", ";
1788 } else {
1789 *os << (printed_header ? "; not" : "Not") << " in actual: ";
1790 printed_header2 = true;
1791 }
zhanyong.wanb8243162009-06-04 05:48:20 +00001792 UniversalPrinter<typename StlContainer::value_type>::Print(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001793 }
1794 }
1795 }
1796 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00001797 const StlContainer rhs_;
zhanyong.wan6a896b52009-01-16 01:13:50 +00001798};
1799
zhanyong.wanb8243162009-06-04 05:48:20 +00001800template <typename LhsContainer, typename Container>
zhanyong.wan6a896b52009-01-16 01:13:50 +00001801void ExplainMatchResultTo(const ContainerEqMatcher<Container>& matcher,
zhanyong.wanb8243162009-06-04 05:48:20 +00001802 const LhsContainer& lhs,
zhanyong.wan6a896b52009-01-16 01:13:50 +00001803 ::std::ostream* os) {
1804 matcher.ExplainMatchResultTo(lhs, os);
1805}
1806
zhanyong.wanb8243162009-06-04 05:48:20 +00001807// Implements Contains(element_matcher) for the given argument type Container.
1808template <typename Container>
1809class ContainsMatcherImpl : public MatcherInterface<Container> {
1810 public:
1811 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
1812 typedef StlContainerView<RawContainer> View;
1813 typedef typename View::type StlContainer;
1814 typedef typename View::const_reference StlContainerReference;
1815 typedef typename StlContainer::value_type Element;
1816
1817 template <typename InnerMatcher>
1818 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
1819 : inner_matcher_(
1820 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
1821
1822 // Returns true iff 'container' matches.
1823 virtual bool Matches(Container container) const {
1824 StlContainerReference stl_container = View::ConstReference(container);
1825 for (typename StlContainer::const_iterator it = stl_container.begin();
1826 it != stl_container.end(); ++it) {
1827 if (inner_matcher_.Matches(*it))
1828 return true;
1829 }
1830 return false;
1831 }
1832
1833 // Describes what this matcher does.
1834 virtual void DescribeTo(::std::ostream* os) const {
1835 *os << "contains at least one element that ";
1836 inner_matcher_.DescribeTo(os);
1837 }
1838
1839 // Describes what the negation of this matcher does.
1840 virtual void DescribeNegationTo(::std::ostream* os) const {
1841 *os << "doesn't contain any element that ";
1842 inner_matcher_.DescribeTo(os);
1843 }
1844
1845 // Explains why 'container' matches, or doesn't match, this matcher.
1846 virtual void ExplainMatchResultTo(Container container,
1847 ::std::ostream* os) const {
1848 StlContainerReference stl_container = View::ConstReference(container);
1849
1850 // We need to explain which (if any) element matches inner_matcher_.
1851 typename StlContainer::const_iterator it = stl_container.begin();
1852 for (size_t i = 0; it != stl_container.end(); ++it, ++i) {
1853 if (inner_matcher_.Matches(*it)) {
1854 *os << "element " << i << " matches";
1855 return;
1856 }
1857 }
1858 }
1859
1860 private:
1861 const Matcher<const Element&> inner_matcher_;
1862};
1863
1864// Implements polymorphic Contains(element_matcher).
1865template <typename M>
1866class ContainsMatcher {
1867 public:
1868 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
1869
1870 template <typename Container>
1871 operator Matcher<Container>() const {
1872 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
1873 }
1874
1875 private:
1876 const M inner_matcher_;
1877};
1878
zhanyong.wanb5937da2009-07-16 20:26:41 +00001879// Implements Key(inner_matcher) for the given argument pair type.
1880// Key(inner_matcher) matches an std::pair whose 'first' field matches
1881// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
1882// std::map that contains at least one element whose key is >= 5.
1883template <typename PairType>
1884class KeyMatcherImpl : public MatcherInterface<PairType> {
1885 public:
1886 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
1887 typedef typename RawPairType::first_type KeyType;
1888
1889 template <typename InnerMatcher>
1890 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
1891 : inner_matcher_(
1892 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
1893 }
1894
1895 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
1896 virtual bool Matches(PairType key_value) const {
1897 return inner_matcher_.Matches(key_value.first);
1898 }
1899
1900 // Describes what this matcher does.
1901 virtual void DescribeTo(::std::ostream* os) const {
1902 *os << "has a key that ";
1903 inner_matcher_.DescribeTo(os);
1904 }
1905
1906 // Describes what the negation of this matcher does.
1907 virtual void DescribeNegationTo(::std::ostream* os) const {
1908 *os << "doesn't have a key that ";
1909 inner_matcher_.DescribeTo(os);
1910 }
1911
1912 // Explains why 'key_value' matches, or doesn't match, this matcher.
1913 virtual void ExplainMatchResultTo(PairType key_value,
1914 ::std::ostream* os) const {
1915 inner_matcher_.ExplainMatchResultTo(key_value.first, os);
1916 }
1917
1918 private:
1919 const Matcher<const KeyType&> inner_matcher_;
1920};
1921
1922// Implements polymorphic Key(matcher_for_key).
1923template <typename M>
1924class KeyMatcher {
1925 public:
1926 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
1927
1928 template <typename PairType>
1929 operator Matcher<PairType>() const {
1930 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
1931 }
1932
1933 private:
1934 const M matcher_for_key_;
1935};
1936
zhanyong.wan1afe1c72009-07-21 23:26:31 +00001937// Implements ElementsAre() and ElementsAreArray().
1938template <typename Container>
1939class ElementsAreMatcherImpl : public MatcherInterface<Container> {
1940 public:
1941 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
1942 typedef internal::StlContainerView<RawContainer> View;
1943 typedef typename View::type StlContainer;
1944 typedef typename View::const_reference StlContainerReference;
1945 typedef typename StlContainer::value_type Element;
1946
1947 // Constructs the matcher from a sequence of element values or
1948 // element matchers.
1949 template <typename InputIter>
1950 ElementsAreMatcherImpl(InputIter first, size_t count) {
1951 matchers_.reserve(count);
1952 InputIter it = first;
1953 for (size_t i = 0; i != count; ++i, ++it) {
1954 matchers_.push_back(MatcherCast<const Element&>(*it));
1955 }
1956 }
1957
1958 // Returns true iff 'container' matches.
1959 virtual bool Matches(Container container) const {
1960 StlContainerReference stl_container = View::ConstReference(container);
1961 if (stl_container.size() != count())
1962 return false;
1963
1964 typename StlContainer::const_iterator it = stl_container.begin();
1965 for (size_t i = 0; i != count(); ++it, ++i) {
1966 if (!matchers_[i].Matches(*it))
1967 return false;
1968 }
1969
1970 return true;
1971 }
1972
1973 // Describes what this matcher does.
1974 virtual void DescribeTo(::std::ostream* os) const {
1975 if (count() == 0) {
1976 *os << "is empty";
1977 } else if (count() == 1) {
1978 *os << "has 1 element that ";
1979 matchers_[0].DescribeTo(os);
1980 } else {
1981 *os << "has " << Elements(count()) << " where\n";
1982 for (size_t i = 0; i != count(); ++i) {
1983 *os << "element " << i << " ";
1984 matchers_[i].DescribeTo(os);
1985 if (i + 1 < count()) {
1986 *os << ",\n";
1987 }
1988 }
1989 }
1990 }
1991
1992 // Describes what the negation of this matcher does.
1993 virtual void DescribeNegationTo(::std::ostream* os) const {
1994 if (count() == 0) {
1995 *os << "is not empty";
1996 return;
1997 }
1998
1999 *os << "does not have " << Elements(count()) << ", or\n";
2000 for (size_t i = 0; i != count(); ++i) {
2001 *os << "element " << i << " ";
2002 matchers_[i].DescribeNegationTo(os);
2003 if (i + 1 < count()) {
2004 *os << ", or\n";
2005 }
2006 }
2007 }
2008
2009 // Explains why 'container' matches, or doesn't match, this matcher.
2010 virtual void ExplainMatchResultTo(Container container,
2011 ::std::ostream* os) const {
2012 StlContainerReference stl_container = View::ConstReference(container);
2013 if (Matches(container)) {
2014 // We need to explain why *each* element matches (the obvious
2015 // ones can be skipped).
2016
2017 bool reason_printed = false;
2018 typename StlContainer::const_iterator it = stl_container.begin();
2019 for (size_t i = 0; i != count(); ++it, ++i) {
2020 ::std::stringstream ss;
2021 matchers_[i].ExplainMatchResultTo(*it, &ss);
2022
2023 const string s = ss.str();
2024 if (!s.empty()) {
2025 if (reason_printed) {
2026 *os << ",\n";
2027 }
2028 *os << "element " << i << " " << s;
2029 reason_printed = true;
2030 }
2031 }
2032 } else {
2033 // We need to explain why the container doesn't match.
2034 const size_t actual_count = stl_container.size();
2035 if (actual_count != count()) {
2036 // The element count doesn't match. If the container is
2037 // empty, there's no need to explain anything as Google Mock
2038 // already prints the empty container. Otherwise we just need
2039 // to show how many elements there actually are.
2040 if (actual_count != 0) {
2041 *os << "has " << Elements(actual_count);
2042 }
2043 return;
2044 }
2045
2046 // The container has the right size but at least one element
2047 // doesn't match expectation. We need to find this element and
2048 // explain why it doesn't match.
2049 typename StlContainer::const_iterator it = stl_container.begin();
2050 for (size_t i = 0; i != count(); ++it, ++i) {
2051 if (matchers_[i].Matches(*it)) {
2052 continue;
2053 }
2054
2055 *os << "element " << i << " doesn't match";
2056
2057 ::std::stringstream ss;
2058 matchers_[i].ExplainMatchResultTo(*it, &ss);
2059 const string s = ss.str();
2060 if (!s.empty()) {
2061 *os << " (" << s << ")";
2062 }
2063 return;
2064 }
2065 }
2066 }
2067
2068 private:
2069 static Message Elements(size_t count) {
2070 return Message() << count << (count == 1 ? " element" : " elements");
2071 }
2072
2073 size_t count() const { return matchers_.size(); }
2074 std::vector<Matcher<const Element&> > matchers_;
2075};
2076
2077// Implements ElementsAre() of 0 arguments.
2078class ElementsAreMatcher0 {
2079 public:
2080 ElementsAreMatcher0() {}
2081
2082 template <typename Container>
2083 operator Matcher<Container>() const {
2084 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2085 RawContainer;
2086 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2087 Element;
2088
2089 const Matcher<const Element&>* const matchers = NULL;
2090 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 0));
2091 }
2092};
2093
2094// Implements ElementsAreArray().
2095template <typename T>
2096class ElementsAreArrayMatcher {
2097 public:
2098 ElementsAreArrayMatcher(const T* first, size_t count) :
2099 first_(first), count_(count) {}
2100
2101 template <typename Container>
2102 operator Matcher<Container>() const {
2103 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2104 RawContainer;
2105 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2106 Element;
2107
2108 return MakeMatcher(new ElementsAreMatcherImpl<Container>(first_, count_));
2109 }
2110
2111 private:
2112 const T* const first_;
2113 const size_t count_;
2114};
2115
2116// Constants denoting interpolations in a matcher description string.
2117const int kTupleInterpolation = -1; // "%(*)s"
2118const int kPercentInterpolation = -2; // "%%"
2119const int kInvalidInterpolation = -3; // "%" followed by invalid text
2120
2121// Records the location and content of an interpolation.
2122struct Interpolation {
2123 Interpolation(const char* start, const char* end, int param)
2124 : start_pos(start), end_pos(end), param_index(param) {}
2125
2126 // Points to the start of the interpolation (the '%' character).
2127 const char* start_pos;
2128 // Points to the first character after the interpolation.
2129 const char* end_pos;
2130 // 0-based index of the interpolated matcher parameter;
2131 // kTupleInterpolation for "%(*)s"; kPercentInterpolation for "%%".
2132 int param_index;
2133};
2134
2135typedef ::std::vector<Interpolation> Interpolations;
2136
2137// Parses a matcher description string and returns a vector of
2138// interpolations that appear in the string; generates non-fatal
2139// failures iff 'description' is an invalid matcher description.
2140// 'param_names' is a NULL-terminated array of parameter names in the
2141// order they appear in the MATCHER_P*() parameter list.
2142Interpolations ValidateMatcherDescription(
2143 const char* param_names[], const char* description);
2144
2145// Returns the actual matcher description, given the matcher name,
2146// user-supplied description template string, interpolations in the
2147// string, and the printed values of the matcher parameters.
2148string FormatMatcherDescription(
2149 const char* matcher_name, const char* description,
2150 const Interpolations& interp, const Strings& param_values);
2151
shiqiane35fdd92008-12-10 05:08:54 +00002152} // namespace internal
2153
2154// Implements MatcherCast().
2155template <typename T, typename M>
2156inline Matcher<T> MatcherCast(M matcher) {
2157 return internal::MatcherCastImpl<T, M>::Cast(matcher);
2158}
2159
2160// _ is a matcher that matches anything of any type.
2161//
2162// This definition is fine as:
2163//
2164// 1. The C++ standard permits using the name _ in a namespace that
2165// is not the global namespace or ::std.
2166// 2. The AnythingMatcher class has no data member or constructor,
2167// so it's OK to create global variables of this type.
2168// 3. c-style has approved of using _ in this case.
2169const internal::AnythingMatcher _ = {};
2170// Creates a matcher that matches any value of the given type T.
2171template <typename T>
2172inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2173
2174// Creates a matcher that matches any value of the given type T.
2175template <typename T>
2176inline Matcher<T> An() { return A<T>(); }
2177
2178// Creates a polymorphic matcher that matches anything equal to x.
2179// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2180// wouldn't compile.
2181template <typename T>
2182inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2183
2184// Constructs a Matcher<T> from a 'value' of type T. The constructed
2185// matcher matches any value that's equal to 'value'.
2186template <typename T>
2187Matcher<T>::Matcher(T value) { *this = Eq(value); }
2188
2189// Creates a monomorphic matcher that matches anything with type Lhs
2190// and equal to rhs. A user may need to use this instead of Eq(...)
2191// in order to resolve an overloading ambiguity.
2192//
2193// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2194// or Matcher<T>(x), but more readable than the latter.
2195//
2196// We could define similar monomorphic matchers for other comparison
2197// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2198// it yet as those are used much less than Eq() in practice. A user
2199// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2200// for example.
2201template <typename Lhs, typename Rhs>
2202inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2203
2204// Creates a polymorphic matcher that matches anything >= x.
2205template <typename Rhs>
2206inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2207 return internal::GeMatcher<Rhs>(x);
2208}
2209
2210// Creates a polymorphic matcher that matches anything > x.
2211template <typename Rhs>
2212inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2213 return internal::GtMatcher<Rhs>(x);
2214}
2215
2216// Creates a polymorphic matcher that matches anything <= x.
2217template <typename Rhs>
2218inline internal::LeMatcher<Rhs> Le(Rhs x) {
2219 return internal::LeMatcher<Rhs>(x);
2220}
2221
2222// Creates a polymorphic matcher that matches anything < x.
2223template <typename Rhs>
2224inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2225 return internal::LtMatcher<Rhs>(x);
2226}
2227
2228// Creates a polymorphic matcher that matches anything != x.
2229template <typename Rhs>
2230inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2231 return internal::NeMatcher<Rhs>(x);
2232}
2233
2234// Creates a polymorphic matcher that matches any non-NULL pointer.
2235// This is convenient as Not(NULL) doesn't compile (the compiler
2236// thinks that that expression is comparing a pointer with an integer).
2237inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2238 return MakePolymorphicMatcher(internal::NotNullMatcher());
2239}
2240
2241// Creates a polymorphic matcher that matches any argument that
2242// references variable x.
2243template <typename T>
2244inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2245 return internal::RefMatcher<T&>(x);
2246}
2247
2248// Creates a matcher that matches any double argument approximately
2249// equal to rhs, where two NANs are considered unequal.
2250inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2251 return internal::FloatingEqMatcher<double>(rhs, false);
2252}
2253
2254// Creates a matcher that matches any double argument approximately
2255// equal to rhs, including NaN values when rhs is NaN.
2256inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2257 return internal::FloatingEqMatcher<double>(rhs, true);
2258}
2259
2260// Creates a matcher that matches any float argument approximately
2261// equal to rhs, where two NANs are considered unequal.
2262inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2263 return internal::FloatingEqMatcher<float>(rhs, false);
2264}
2265
2266// Creates a matcher that matches any double argument approximately
2267// equal to rhs, including NaN values when rhs is NaN.
2268inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2269 return internal::FloatingEqMatcher<float>(rhs, true);
2270}
2271
2272// Creates a matcher that matches a pointer (raw or smart) that points
2273// to a value that matches inner_matcher.
2274template <typename InnerMatcher>
2275inline internal::PointeeMatcher<InnerMatcher> Pointee(
2276 const InnerMatcher& inner_matcher) {
2277 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2278}
2279
2280// Creates a matcher that matches an object whose given field matches
2281// 'matcher'. For example,
2282// Field(&Foo::number, Ge(5))
2283// matches a Foo object x iff x.number >= 5.
2284template <typename Class, typename FieldType, typename FieldMatcher>
2285inline PolymorphicMatcher<
2286 internal::FieldMatcher<Class, FieldType> > Field(
2287 FieldType Class::*field, const FieldMatcher& matcher) {
2288 return MakePolymorphicMatcher(
2289 internal::FieldMatcher<Class, FieldType>(
2290 field, MatcherCast<const FieldType&>(matcher)));
2291 // The call to MatcherCast() is required for supporting inner
2292 // matchers of compatible types. For example, it allows
2293 // Field(&Foo::bar, m)
2294 // to compile where bar is an int32 and m is a matcher for int64.
2295}
2296
2297// Creates a matcher that matches an object whose given property
2298// matches 'matcher'. For example,
2299// Property(&Foo::str, StartsWith("hi"))
2300// matches a Foo object x iff x.str() starts with "hi".
2301template <typename Class, typename PropertyType, typename PropertyMatcher>
2302inline PolymorphicMatcher<
2303 internal::PropertyMatcher<Class, PropertyType> > Property(
2304 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2305 return MakePolymorphicMatcher(
2306 internal::PropertyMatcher<Class, PropertyType>(
2307 property,
zhanyong.wane0d051e2009-02-19 00:33:37 +00002308 MatcherCast<GMOCK_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002309 // The call to MatcherCast() is required for supporting inner
2310 // matchers of compatible types. For example, it allows
2311 // Property(&Foo::bar, m)
2312 // to compile where bar() returns an int32 and m is a matcher for int64.
2313}
2314
2315// Creates a matcher that matches an object iff the result of applying
2316// a callable to x matches 'matcher'.
2317// For example,
2318// ResultOf(f, StartsWith("hi"))
2319// matches a Foo object x iff f(x) starts with "hi".
2320// callable parameter can be a function, function pointer, or a functor.
2321// Callable has to satisfy the following conditions:
2322// * It is required to keep no state affecting the results of
2323// the calls on it and make no assumptions about how many calls
2324// will be made. Any state it keeps must be protected from the
2325// concurrent access.
2326// * If it is a function object, it has to define type result_type.
2327// We recommend deriving your functor classes from std::unary_function.
2328template <typename Callable, typename ResultOfMatcher>
2329internal::ResultOfMatcher<Callable> ResultOf(
2330 Callable callable, const ResultOfMatcher& matcher) {
2331 return internal::ResultOfMatcher<Callable>(
2332 callable,
2333 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2334 matcher));
2335 // The call to MatcherCast() is required for supporting inner
2336 // matchers of compatible types. For example, it allows
2337 // ResultOf(Function, m)
2338 // to compile where Function() returns an int32 and m is a matcher for int64.
2339}
2340
2341// String matchers.
2342
2343// Matches a string equal to str.
2344inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2345 StrEq(const internal::string& str) {
2346 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2347 str, true, true));
2348}
2349
2350// Matches a string not equal to str.
2351inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2352 StrNe(const internal::string& str) {
2353 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2354 str, false, true));
2355}
2356
2357// Matches a string equal to str, ignoring case.
2358inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2359 StrCaseEq(const internal::string& str) {
2360 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2361 str, true, false));
2362}
2363
2364// Matches a string not equal to str, ignoring case.
2365inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2366 StrCaseNe(const internal::string& str) {
2367 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2368 str, false, false));
2369}
2370
2371// Creates a matcher that matches any string, std::string, or C string
2372// that contains the given substring.
2373inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2374 HasSubstr(const internal::string& substring) {
2375 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
2376 substring));
2377}
2378
2379// Matches a string that starts with 'prefix' (case-sensitive).
2380inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
2381 StartsWith(const internal::string& prefix) {
2382 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
2383 prefix));
2384}
2385
2386// Matches a string that ends with 'suffix' (case-sensitive).
2387inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
2388 EndsWith(const internal::string& suffix) {
2389 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
2390 suffix));
2391}
2392
2393#ifdef GMOCK_HAS_REGEX
2394
2395// Matches a string that fully matches regular expression 'regex'.
2396// The matcher takes ownership of 'regex'.
2397inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2398 const internal::RE* regex) {
2399 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2400}
2401inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2402 const internal::string& regex) {
2403 return MatchesRegex(new internal::RE(regex));
2404}
2405
2406// Matches a string that contains regular expression 'regex'.
2407// The matcher takes ownership of 'regex'.
2408inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2409 const internal::RE* regex) {
2410 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2411}
2412inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2413 const internal::string& regex) {
2414 return ContainsRegex(new internal::RE(regex));
2415}
2416
2417#endif // GMOCK_HAS_REGEX
2418
2419#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2420// Wide string matchers.
2421
2422// Matches a string equal to str.
2423inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2424 StrEq(const internal::wstring& str) {
2425 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2426 str, true, true));
2427}
2428
2429// Matches a string not equal to str.
2430inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2431 StrNe(const internal::wstring& str) {
2432 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2433 str, false, true));
2434}
2435
2436// Matches a string equal to str, ignoring case.
2437inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2438 StrCaseEq(const internal::wstring& str) {
2439 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2440 str, true, false));
2441}
2442
2443// Matches a string not equal to str, ignoring case.
2444inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2445 StrCaseNe(const internal::wstring& str) {
2446 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2447 str, false, false));
2448}
2449
2450// Creates a matcher that matches any wstring, std::wstring, or C wide string
2451// that contains the given substring.
2452inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2453 HasSubstr(const internal::wstring& substring) {
2454 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2455 substring));
2456}
2457
2458// Matches a string that starts with 'prefix' (case-sensitive).
2459inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2460 StartsWith(const internal::wstring& prefix) {
2461 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2462 prefix));
2463}
2464
2465// Matches a string that ends with 'suffix' (case-sensitive).
2466inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2467 EndsWith(const internal::wstring& suffix) {
2468 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2469 suffix));
2470}
2471
2472#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2473
2474// Creates a polymorphic matcher that matches a 2-tuple where the
2475// first field == the second field.
2476inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2477
2478// Creates a polymorphic matcher that matches a 2-tuple where the
2479// first field >= the second field.
2480inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2481
2482// Creates a polymorphic matcher that matches a 2-tuple where the
2483// first field > the second field.
2484inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2485
2486// Creates a polymorphic matcher that matches a 2-tuple where the
2487// first field <= the second field.
2488inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2489
2490// Creates a polymorphic matcher that matches a 2-tuple where the
2491// first field < the second field.
2492inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2493
2494// Creates a polymorphic matcher that matches a 2-tuple where the
2495// first field != the second field.
2496inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2497
2498// Creates a matcher that matches any value of type T that m doesn't
2499// match.
2500template <typename InnerMatcher>
2501inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2502 return internal::NotMatcher<InnerMatcher>(m);
2503}
2504
2505// Creates a matcher that matches any value that matches all of the
2506// given matchers.
2507//
2508// For now we only support up to 5 matchers. Support for more
2509// matchers can be added as needed, or the user can use nested
2510// AllOf()s.
2511template <typename Matcher1, typename Matcher2>
2512inline internal::BothOfMatcher<Matcher1, Matcher2>
2513AllOf(Matcher1 m1, Matcher2 m2) {
2514 return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2);
2515}
2516
2517template <typename Matcher1, typename Matcher2, typename Matcher3>
2518inline internal::BothOfMatcher<Matcher1,
2519 internal::BothOfMatcher<Matcher2, Matcher3> >
2520AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2521 return AllOf(m1, AllOf(m2, m3));
2522}
2523
2524template <typename Matcher1, typename Matcher2, typename Matcher3,
2525 typename Matcher4>
2526inline internal::BothOfMatcher<Matcher1,
2527 internal::BothOfMatcher<Matcher2,
2528 internal::BothOfMatcher<Matcher3, Matcher4> > >
2529AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2530 return AllOf(m1, AllOf(m2, m3, m4));
2531}
2532
2533template <typename Matcher1, typename Matcher2, typename Matcher3,
2534 typename Matcher4, typename Matcher5>
2535inline internal::BothOfMatcher<Matcher1,
2536 internal::BothOfMatcher<Matcher2,
2537 internal::BothOfMatcher<Matcher3,
2538 internal::BothOfMatcher<Matcher4, Matcher5> > > >
2539AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2540 return AllOf(m1, AllOf(m2, m3, m4, m5));
2541}
2542
2543// Creates a matcher that matches any value that matches at least one
2544// of the given matchers.
2545//
2546// For now we only support up to 5 matchers. Support for more
2547// matchers can be added as needed, or the user can use nested
2548// AnyOf()s.
2549template <typename Matcher1, typename Matcher2>
2550inline internal::EitherOfMatcher<Matcher1, Matcher2>
2551AnyOf(Matcher1 m1, Matcher2 m2) {
2552 return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2);
2553}
2554
2555template <typename Matcher1, typename Matcher2, typename Matcher3>
2556inline internal::EitherOfMatcher<Matcher1,
2557 internal::EitherOfMatcher<Matcher2, Matcher3> >
2558AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2559 return AnyOf(m1, AnyOf(m2, m3));
2560}
2561
2562template <typename Matcher1, typename Matcher2, typename Matcher3,
2563 typename Matcher4>
2564inline internal::EitherOfMatcher<Matcher1,
2565 internal::EitherOfMatcher<Matcher2,
2566 internal::EitherOfMatcher<Matcher3, Matcher4> > >
2567AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2568 return AnyOf(m1, AnyOf(m2, m3, m4));
2569}
2570
2571template <typename Matcher1, typename Matcher2, typename Matcher3,
2572 typename Matcher4, typename Matcher5>
2573inline internal::EitherOfMatcher<Matcher1,
2574 internal::EitherOfMatcher<Matcher2,
2575 internal::EitherOfMatcher<Matcher3,
2576 internal::EitherOfMatcher<Matcher4, Matcher5> > > >
2577AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2578 return AnyOf(m1, AnyOf(m2, m3, m4, m5));
2579}
2580
2581// Returns a matcher that matches anything that satisfies the given
2582// predicate. The predicate can be any unary function or functor
2583// whose return type can be implicitly converted to bool.
2584template <typename Predicate>
2585inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
2586Truly(Predicate pred) {
2587 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
2588}
2589
zhanyong.wan6a896b52009-01-16 01:13:50 +00002590// Returns a matcher that matches an equal container.
2591// This matcher behaves like Eq(), but in the event of mismatch lists the
2592// values that are included in one container but not the other. (Duplicate
2593// values and order differences are not explained.)
2594template <typename Container>
zhanyong.wanb8243162009-06-04 05:48:20 +00002595inline PolymorphicMatcher<internal::ContainerEqMatcher<
2596 GMOCK_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00002597 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002598 // This following line is for working around a bug in MSVC 8.0,
2599 // which causes Container to be a const type sometimes.
2600 typedef GMOCK_REMOVE_CONST_(Container) RawContainer;
2601 return MakePolymorphicMatcher(internal::ContainerEqMatcher<RawContainer>(rhs));
2602}
2603
2604// Matches an STL-style container or a native array that contains at
2605// least one element matching the given value or matcher.
2606//
2607// Examples:
2608// ::std::set<int> page_ids;
2609// page_ids.insert(3);
2610// page_ids.insert(1);
2611// EXPECT_THAT(page_ids, Contains(1));
2612// EXPECT_THAT(page_ids, Contains(Gt(2)));
2613// EXPECT_THAT(page_ids, Not(Contains(4)));
2614//
2615// ::std::map<int, size_t> page_lengths;
2616// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00002617// EXPECT_THAT(page_lengths,
2618// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00002619//
2620// const char* user_ids[] = { "joe", "mike", "tom" };
2621// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
2622template <typename M>
2623inline internal::ContainsMatcher<M> Contains(M matcher) {
2624 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002625}
2626
zhanyong.wanb5937da2009-07-16 20:26:41 +00002627// Key(inner_matcher) matches an std::pair whose 'first' field matches
2628// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2629// std::map that contains at least one element whose key is >= 5.
2630template <typename M>
2631inline internal::KeyMatcher<M> Key(M inner_matcher) {
2632 return internal::KeyMatcher<M>(inner_matcher);
2633}
2634
shiqiane35fdd92008-12-10 05:08:54 +00002635// Returns a predicate that is satisfied by anything that matches the
2636// given matcher.
2637template <typename M>
2638inline internal::MatcherAsPredicate<M> Matches(M matcher) {
2639 return internal::MatcherAsPredicate<M>(matcher);
2640}
2641
zhanyong.wanb8243162009-06-04 05:48:20 +00002642// Returns true iff the value matches the matcher.
2643template <typename T, typename M>
2644inline bool Value(const T& value, M matcher) {
2645 return testing::Matches(matcher)(value);
2646}
2647
zhanyong.wanbf550852009-06-09 06:09:53 +00002648// AllArgs(m) is a synonym of m. This is useful in
2649//
2650// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
2651//
2652// which is easier to read than
2653//
2654// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
2655template <typename InnerMatcher>
2656inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
2657
shiqiane35fdd92008-12-10 05:08:54 +00002658// These macros allow using matchers to check values in Google Test
2659// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
2660// succeed iff the value matches the matcher. If the assertion fails,
2661// the value and the description of the matcher will be printed.
2662#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
2663 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2664#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
2665 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2666
2667} // namespace testing
2668
2669#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_