blob: f4d5b0a60b9729880370d4adfa68cc1a6a18e0a3 [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
239 template <typename T>
240 operator Matcher<T>() const {
241 return Matcher<T>(new MonomorphicImpl<T>(impl_));
242 }
243 private:
244 template <typename T>
245 class MonomorphicImpl : public MatcherInterface<T> {
246 public:
247 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
248
249 virtual bool Matches(T x) const { return impl_.Matches(x); }
250
251 virtual void DescribeTo(::std::ostream* os) const {
252 impl_.DescribeTo(os);
253 }
254
255 virtual void DescribeNegationTo(::std::ostream* os) const {
256 impl_.DescribeNegationTo(os);
257 }
258
259 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
260 using ::testing::internal::ExplainMatchResultTo;
261
262 // C++ uses Argument-Dependent Look-up (aka Koenig Look-up) to
263 // resolve the call to ExplainMatchResultTo() here. This
264 // means that if there's a ExplainMatchResultTo() function
265 // defined in the name space where class Impl is defined, it
266 // will be picked by the compiler as the better match.
267 // Otherwise the default implementation of it in
268 // ::testing::internal will be picked.
269 //
270 // This look-up rule lets a writer of a polymorphic matcher
271 // customize the behavior of ExplainMatchResultTo() when he
272 // cares to. Nothing needs to be done by the writer if he
273 // doesn't need to customize it.
274 ExplainMatchResultTo(impl_, x, os);
275 }
276 private:
277 const Impl impl_;
278 };
279
280 const Impl impl_;
281};
282
283// Creates a matcher from its implementation. This is easier to use
284// than the Matcher<T> constructor as it doesn't require you to
285// explicitly write the template argument, e.g.
286//
287// MakeMatcher(foo);
288// vs
289// Matcher<const string&>(foo);
290template <typename T>
291inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
292 return Matcher<T>(impl);
293};
294
295// Creates a polymorphic matcher from its implementation. This is
296// easier to use than the PolymorphicMatcher<Impl> constructor as it
297// doesn't require you to explicitly write the template argument, e.g.
298//
299// MakePolymorphicMatcher(foo);
300// vs
301// PolymorphicMatcher<TypeOfFoo>(foo);
302template <class Impl>
303inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
304 return PolymorphicMatcher<Impl>(impl);
305}
306
307// In order to be safe and clear, casting between different matcher
308// types is done explicitly via MatcherCast<T>(m), which takes a
309// matcher m and returns a Matcher<T>. It compiles only when T can be
310// statically converted to the argument type of m.
311template <typename T, typename M>
312Matcher<T> MatcherCast(M m);
313
zhanyong.wan18490652009-05-11 18:54:08 +0000314// TODO(vladl@google.com): Modify the implementation to reject casting
315// Matcher<int> to Matcher<double>.
316// Implements SafeMatcherCast().
317//
318// This overload handles polymorphic matchers only since monomorphic
319// matchers are handled by the next one.
320template <typename T, typename M>
321inline Matcher<T> SafeMatcherCast(M polymorphic_matcher) {
322 return Matcher<T>(polymorphic_matcher);
323}
324
325// This overload handles monomorphic matchers.
326//
327// In general, if type T can be implicitly converted to type U, we can
328// safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
329// contravariant): just keep a copy of the original Matcher<U>, convert the
330// argument from type T to U, and then pass it to the underlying Matcher<U>.
331// The only exception is when U is a reference and T is not, as the
332// underlying Matcher<U> may be interested in the argument's address, which
333// is not preserved in the conversion from T to U.
334template <typename T, typename U>
335Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) {
336 // Enforce that T can be implicitly converted to U.
337 GMOCK_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
338 T_must_be_implicitly_convertible_to_U);
339 // Enforce that we are not converting a non-reference type T to a reference
340 // type U.
341 GMOCK_COMPILE_ASSERT_(
342 internal::is_reference<T>::value || !internal::is_reference<U>::value,
343 cannot_convert_non_referentce_arg_to_reference);
zhanyong.wan16cf4732009-05-14 20:55:30 +0000344 // In case both T and U are arithmetic types, enforce that the
345 // conversion is not lossy.
346 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(T)) RawT;
347 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(U)) RawU;
348 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
349 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
350 GMOCK_COMPILE_ASSERT_(
351 kTIsOther || kUIsOther ||
352 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
353 conversion_of_arithmetic_types_must_be_lossless);
zhanyong.wan18490652009-05-11 18:54:08 +0000354 return MatcherCast<T>(matcher);
355}
356
shiqiane35fdd92008-12-10 05:08:54 +0000357// A<T>() returns a matcher that matches any value of type T.
358template <typename T>
359Matcher<T> A();
360
361// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
362// and MUST NOT BE USED IN USER CODE!!!
363namespace internal {
364
365// Appends the explanation on the result of matcher.Matches(value) to
366// os iff the explanation is not empty.
367template <typename T>
368void ExplainMatchResultAsNeededTo(const Matcher<T>& matcher, T value,
369 ::std::ostream* os) {
370 ::std::stringstream reason;
371 matcher.ExplainMatchResultTo(value, &reason);
372 const internal::string s = reason.str();
373 if (s != "") {
374 *os << " (" << s << ")";
375 }
376}
377
378// An internal helper class for doing compile-time loop on a tuple's
379// fields.
380template <size_t N>
381class TuplePrefix {
382 public:
383 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
384 // iff the first N fields of matcher_tuple matches the first N
385 // fields of value_tuple, respectively.
386 template <typename MatcherTuple, typename ValueTuple>
387 static bool Matches(const MatcherTuple& matcher_tuple,
388 const ValueTuple& value_tuple) {
389 using ::std::tr1::get;
390 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
391 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
392 }
393
394 // TuplePrefix<N>::DescribeMatchFailuresTo(matchers, values, os)
395 // describes failures in matching the first N fields of matchers
396 // against the first N fields of values. If there is no failure,
397 // nothing will be streamed to os.
398 template <typename MatcherTuple, typename ValueTuple>
399 static void DescribeMatchFailuresTo(const MatcherTuple& matchers,
400 const ValueTuple& values,
401 ::std::ostream* os) {
402 using ::std::tr1::tuple_element;
403 using ::std::tr1::get;
404
405 // First, describes failures in the first N - 1 fields.
406 TuplePrefix<N - 1>::DescribeMatchFailuresTo(matchers, values, os);
407
408 // Then describes the failure (if any) in the (N - 1)-th (0-based)
409 // field.
410 typename tuple_element<N - 1, MatcherTuple>::type matcher =
411 get<N - 1>(matchers);
412 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
413 Value value = get<N - 1>(values);
414 if (!matcher.Matches(value)) {
415 // TODO(wan): include in the message the name of the parameter
416 // as used in MOCK_METHOD*() when possible.
417 *os << " Expected arg #" << N - 1 << ": ";
418 get<N - 1>(matchers).DescribeTo(os);
419 *os << "\n Actual: ";
420 // We remove the reference in type Value to prevent the
421 // universal printer from printing the address of value, which
422 // isn't interesting to the user most of the time. The
423 // matcher's ExplainMatchResultTo() method handles the case when
424 // the address is interesting.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000425 internal::UniversalPrinter<GMOCK_REMOVE_REFERENCE_(Value)>::
shiqiane35fdd92008-12-10 05:08:54 +0000426 Print(value, os);
427 ExplainMatchResultAsNeededTo<Value>(matcher, value, os);
428 *os << "\n";
429 }
430 }
431};
432
433// The base case.
434template <>
435class TuplePrefix<0> {
436 public:
437 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000438 static bool Matches(const MatcherTuple& /* matcher_tuple */,
439 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000440 return true;
441 }
442
443 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000444 static void DescribeMatchFailuresTo(const MatcherTuple& /* matchers */,
445 const ValueTuple& /* values */,
446 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000447};
448
449// TupleMatches(matcher_tuple, value_tuple) returns true iff all
450// matchers in matcher_tuple match the corresponding fields in
451// value_tuple. It is a compiler error if matcher_tuple and
452// value_tuple have different number of fields or incompatible field
453// types.
454template <typename MatcherTuple, typename ValueTuple>
455bool TupleMatches(const MatcherTuple& matcher_tuple,
456 const ValueTuple& value_tuple) {
457 using ::std::tr1::tuple_size;
458 // Makes sure that matcher_tuple and value_tuple have the same
459 // number of fields.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000460 GMOCK_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
461 tuple_size<ValueTuple>::value,
462 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000463 return TuplePrefix<tuple_size<ValueTuple>::value>::
464 Matches(matcher_tuple, value_tuple);
465}
466
467// Describes failures in matching matchers against values. If there
468// is no failure, nothing will be streamed to os.
469template <typename MatcherTuple, typename ValueTuple>
470void DescribeMatchFailureTupleTo(const MatcherTuple& matchers,
471 const ValueTuple& values,
472 ::std::ostream* os) {
473 using ::std::tr1::tuple_size;
474 TuplePrefix<tuple_size<MatcherTuple>::value>::DescribeMatchFailuresTo(
475 matchers, values, os);
476}
477
478// The MatcherCastImpl class template is a helper for implementing
479// MatcherCast(). We need this helper in order to partially
480// specialize the implementation of MatcherCast() (C++ allows
481// class/struct templates to be partially specialized, but not
482// function templates.).
483
484// This general version is used when MatcherCast()'s argument is a
485// polymorphic matcher (i.e. something that can be converted to a
486// Matcher but is not one yet; for example, Eq(value)).
487template <typename T, typename M>
488class MatcherCastImpl {
489 public:
490 static Matcher<T> Cast(M polymorphic_matcher) {
491 return Matcher<T>(polymorphic_matcher);
492 }
493};
494
495// This more specialized version is used when MatcherCast()'s argument
496// is already a Matcher. This only compiles when type T can be
497// statically converted to type U.
498template <typename T, typename U>
499class MatcherCastImpl<T, Matcher<U> > {
500 public:
501 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
502 return Matcher<T>(new Impl(source_matcher));
503 }
504 private:
505 class Impl : public MatcherInterface<T> {
506 public:
507 explicit Impl(const Matcher<U>& source_matcher)
508 : source_matcher_(source_matcher) {}
509
510 // We delegate the matching logic to the source matcher.
511 virtual bool Matches(T x) const {
512 return source_matcher_.Matches(static_cast<U>(x));
513 }
514
515 virtual void DescribeTo(::std::ostream* os) const {
516 source_matcher_.DescribeTo(os);
517 }
518
519 virtual void DescribeNegationTo(::std::ostream* os) const {
520 source_matcher_.DescribeNegationTo(os);
521 }
522
523 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
524 source_matcher_.ExplainMatchResultTo(static_cast<U>(x), os);
525 }
526 private:
527 const Matcher<U> source_matcher_;
528 };
529};
530
531// This even more specialized version is used for efficiently casting
532// a matcher to its own type.
533template <typename T>
534class MatcherCastImpl<T, Matcher<T> > {
535 public:
536 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
537};
538
539// Implements A<T>().
540template <typename T>
541class AnyMatcherImpl : public MatcherInterface<T> {
542 public:
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000543 virtual bool Matches(T /* x */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000544 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
545 virtual void DescribeNegationTo(::std::ostream* os) const {
546 // This is mostly for completeness' safe, as it's not very useful
547 // to write Not(A<bool>()). However we cannot completely rule out
548 // such a possibility, and it doesn't hurt to be prepared.
549 *os << "never matches";
550 }
551};
552
553// Implements _, a matcher that matches any value of any
554// type. This is a polymorphic matcher, so we need a template type
555// conversion operator to make it appearing as a Matcher<T> for any
556// type T.
557class AnythingMatcher {
558 public:
559 template <typename T>
560 operator Matcher<T>() const { return A<T>(); }
561};
562
563// Implements a matcher that compares a given value with a
564// pre-supplied value using one of the ==, <=, <, etc, operators. The
565// two values being compared don't have to have the same type.
566//
567// The matcher defined here is polymorphic (for example, Eq(5) can be
568// used to match an int, a short, a double, etc). Therefore we use
569// a template type conversion operator in the implementation.
570//
571// We define this as a macro in order to eliminate duplicated source
572// code.
573//
574// The following template definition assumes that the Rhs parameter is
575// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wane0d051e2009-02-19 00:33:37 +0000576#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000577 template <typename Rhs> class name##Matcher { \
578 public: \
579 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
580 template <typename Lhs> \
581 operator Matcher<Lhs>() const { \
582 return MakeMatcher(new Impl<Lhs>(rhs_)); \
583 } \
584 private: \
585 template <typename Lhs> \
586 class Impl : public MatcherInterface<Lhs> { \
587 public: \
588 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
589 virtual bool Matches(Lhs lhs) const { return lhs op rhs_; } \
590 virtual void DescribeTo(::std::ostream* os) const { \
591 *os << "is " relation " "; \
592 UniversalPrinter<Rhs>::Print(rhs_, os); \
593 } \
594 virtual void DescribeNegationTo(::std::ostream* os) const { \
595 *os << "is not " relation " "; \
596 UniversalPrinter<Rhs>::Print(rhs_, os); \
597 } \
598 private: \
599 Rhs rhs_; \
600 }; \
601 Rhs rhs_; \
602 }
603
604// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
605// respectively.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000606GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "equal to");
607GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "greater than or equal to");
608GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "greater than");
609GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "less than or equal to");
610GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "less than");
611GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "not equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000612
zhanyong.wane0d051e2009-02-19 00:33:37 +0000613#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000614
615// Implements the polymorphic NotNull() matcher, which matches any
616// pointer that is not NULL.
617class NotNullMatcher {
618 public:
619 template <typename T>
620 bool Matches(T* p) const { return p != NULL; }
621
622 void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; }
623 void DescribeNegationTo(::std::ostream* os) const {
624 *os << "is NULL";
625 }
626};
627
628// Ref(variable) matches any argument that is a reference to
629// 'variable'. This matcher is polymorphic as it can match any
630// super type of the type of 'variable'.
631//
632// The RefMatcher template class implements Ref(variable). It can
633// only be instantiated with a reference type. This prevents a user
634// from mistakenly using Ref(x) to match a non-reference function
635// argument. For example, the following will righteously cause a
636// compiler error:
637//
638// int n;
639// Matcher<int> m1 = Ref(n); // This won't compile.
640// Matcher<int&> m2 = Ref(n); // This will compile.
641template <typename T>
642class RefMatcher;
643
644template <typename T>
645class RefMatcher<T&> {
646 // Google Mock is a generic framework and thus needs to support
647 // mocking any function types, including those that take non-const
648 // reference arguments. Therefore the template parameter T (and
649 // Super below) can be instantiated to either a const type or a
650 // non-const type.
651 public:
652 // RefMatcher() takes a T& instead of const T&, as we want the
653 // compiler to catch using Ref(const_value) as a matcher for a
654 // non-const reference.
655 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
656
657 template <typename Super>
658 operator Matcher<Super&>() const {
659 // By passing object_ (type T&) to Impl(), which expects a Super&,
660 // we make sure that Super is a super type of T. In particular,
661 // this catches using Ref(const_value) as a matcher for a
662 // non-const reference, as you cannot implicitly convert a const
663 // reference to a non-const reference.
664 return MakeMatcher(new Impl<Super>(object_));
665 }
666 private:
667 template <typename Super>
668 class Impl : public MatcherInterface<Super&> {
669 public:
670 explicit Impl(Super& x) : object_(x) {} // NOLINT
671
672 // Matches() takes a Super& (as opposed to const Super&) in
673 // order to match the interface MatcherInterface<Super&>.
674 virtual bool Matches(Super& x) const { return &x == &object_; } // NOLINT
675
676 virtual void DescribeTo(::std::ostream* os) const {
677 *os << "references the variable ";
678 UniversalPrinter<Super&>::Print(object_, os);
679 }
680
681 virtual void DescribeNegationTo(::std::ostream* os) const {
682 *os << "does not reference the variable ";
683 UniversalPrinter<Super&>::Print(object_, os);
684 }
685
686 virtual void ExplainMatchResultTo(Super& x, // NOLINT
687 ::std::ostream* os) const {
688 *os << "is located @" << static_cast<const void*>(&x);
689 }
690 private:
691 const Super& object_;
692 };
693
694 T& object_;
695};
696
697// Polymorphic helper functions for narrow and wide string matchers.
698inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
699 return String::CaseInsensitiveCStringEquals(lhs, rhs);
700}
701
702inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
703 const wchar_t* rhs) {
704 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
705}
706
707// String comparison for narrow or wide strings that can have embedded NUL
708// characters.
709template <typename StringType>
710bool CaseInsensitiveStringEquals(const StringType& s1,
711 const StringType& s2) {
712 // Are the heads equal?
713 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
714 return false;
715 }
716
717 // Skip the equal heads.
718 const typename StringType::value_type nul = 0;
719 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
720
721 // Are we at the end of either s1 or s2?
722 if (i1 == StringType::npos || i2 == StringType::npos) {
723 return i1 == i2;
724 }
725
726 // Are the tails equal?
727 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
728}
729
730// String matchers.
731
732// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
733template <typename StringType>
734class StrEqualityMatcher {
735 public:
736 typedef typename StringType::const_pointer ConstCharPointer;
737
738 StrEqualityMatcher(const StringType& str, bool expect_eq,
739 bool case_sensitive)
740 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
741
742 // When expect_eq_ is true, returns true iff s is equal to string_;
743 // otherwise returns true iff s is not equal to string_.
744 bool Matches(ConstCharPointer s) const {
745 if (s == NULL) {
746 return !expect_eq_;
747 }
748 return Matches(StringType(s));
749 }
750
751 bool Matches(const StringType& s) const {
752 const bool eq = case_sensitive_ ? s == string_ :
753 CaseInsensitiveStringEquals(s, string_);
754 return expect_eq_ == eq;
755 }
756
757 void DescribeTo(::std::ostream* os) const {
758 DescribeToHelper(expect_eq_, os);
759 }
760
761 void DescribeNegationTo(::std::ostream* os) const {
762 DescribeToHelper(!expect_eq_, os);
763 }
764 private:
765 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
766 *os << "is ";
767 if (!expect_eq) {
768 *os << "not ";
769 }
770 *os << "equal to ";
771 if (!case_sensitive_) {
772 *os << "(ignoring case) ";
773 }
774 UniversalPrinter<StringType>::Print(string_, os);
775 }
776
777 const StringType string_;
778 const bool expect_eq_;
779 const bool case_sensitive_;
780};
781
782// Implements the polymorphic HasSubstr(substring) matcher, which
783// can be used as a Matcher<T> as long as T can be converted to a
784// string.
785template <typename StringType>
786class HasSubstrMatcher {
787 public:
788 typedef typename StringType::const_pointer ConstCharPointer;
789
790 explicit HasSubstrMatcher(const StringType& substring)
791 : substring_(substring) {}
792
793 // These overloaded methods allow HasSubstr(substring) to be used as a
794 // Matcher<T> as long as T can be converted to string. Returns true
795 // iff s contains substring_ as a substring.
796 bool Matches(ConstCharPointer s) const {
797 return s != NULL && Matches(StringType(s));
798 }
799
800 bool Matches(const StringType& s) const {
801 return s.find(substring_) != StringType::npos;
802 }
803
804 // Describes what this matcher matches.
805 void DescribeTo(::std::ostream* os) const {
806 *os << "has substring ";
807 UniversalPrinter<StringType>::Print(substring_, os);
808 }
809
810 void DescribeNegationTo(::std::ostream* os) const {
811 *os << "has no substring ";
812 UniversalPrinter<StringType>::Print(substring_, os);
813 }
814 private:
815 const StringType substring_;
816};
817
818// Implements the polymorphic StartsWith(substring) matcher, which
819// can be used as a Matcher<T> as long as T can be converted to a
820// string.
821template <typename StringType>
822class StartsWithMatcher {
823 public:
824 typedef typename StringType::const_pointer ConstCharPointer;
825
826 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
827 }
828
829 // These overloaded methods allow StartsWith(prefix) to be used as a
830 // Matcher<T> as long as T can be converted to string. Returns true
831 // iff s starts with prefix_.
832 bool Matches(ConstCharPointer s) const {
833 return s != NULL && Matches(StringType(s));
834 }
835
836 bool Matches(const StringType& s) const {
837 return s.length() >= prefix_.length() &&
838 s.substr(0, prefix_.length()) == prefix_;
839 }
840
841 void DescribeTo(::std::ostream* os) const {
842 *os << "starts with ";
843 UniversalPrinter<StringType>::Print(prefix_, os);
844 }
845
846 void DescribeNegationTo(::std::ostream* os) const {
847 *os << "doesn't start with ";
848 UniversalPrinter<StringType>::Print(prefix_, os);
849 }
850 private:
851 const StringType prefix_;
852};
853
854// Implements the polymorphic EndsWith(substring) matcher, which
855// can be used as a Matcher<T> as long as T can be converted to a
856// string.
857template <typename StringType>
858class EndsWithMatcher {
859 public:
860 typedef typename StringType::const_pointer ConstCharPointer;
861
862 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
863
864 // These overloaded methods allow EndsWith(suffix) to be used as a
865 // Matcher<T> as long as T can be converted to string. Returns true
866 // iff s ends with suffix_.
867 bool Matches(ConstCharPointer s) const {
868 return s != NULL && Matches(StringType(s));
869 }
870
871 bool Matches(const StringType& s) const {
872 return s.length() >= suffix_.length() &&
873 s.substr(s.length() - suffix_.length()) == suffix_;
874 }
875
876 void DescribeTo(::std::ostream* os) const {
877 *os << "ends with ";
878 UniversalPrinter<StringType>::Print(suffix_, os);
879 }
880
881 void DescribeNegationTo(::std::ostream* os) const {
882 *os << "doesn't end with ";
883 UniversalPrinter<StringType>::Print(suffix_, os);
884 }
885 private:
886 const StringType suffix_;
887};
888
889#if GMOCK_HAS_REGEX
890
891// Implements polymorphic matchers MatchesRegex(regex) and
892// ContainsRegex(regex), which can be used as a Matcher<T> as long as
893// T can be converted to a string.
894class MatchesRegexMatcher {
895 public:
896 MatchesRegexMatcher(const RE* regex, bool full_match)
897 : regex_(regex), full_match_(full_match) {}
898
899 // These overloaded methods allow MatchesRegex(regex) to be used as
900 // a Matcher<T> as long as T can be converted to string. Returns
901 // true iff s matches regular expression regex. When full_match_ is
902 // true, a full match is done; otherwise a partial match is done.
903 bool Matches(const char* s) const {
904 return s != NULL && Matches(internal::string(s));
905 }
906
907 bool Matches(const internal::string& s) const {
908 return full_match_ ? RE::FullMatch(s, *regex_) :
909 RE::PartialMatch(s, *regex_);
910 }
911
912 void DescribeTo(::std::ostream* os) const {
913 *os << (full_match_ ? "matches" : "contains")
914 << " regular expression ";
915 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
916 }
917
918 void DescribeNegationTo(::std::ostream* os) const {
919 *os << "doesn't " << (full_match_ ? "match" : "contain")
920 << " regular expression ";
921 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
922 }
923 private:
924 const internal::linked_ptr<const RE> regex_;
925 const bool full_match_;
926};
927
928#endif // GMOCK_HAS_REGEX
929
930// Implements a matcher that compares the two fields of a 2-tuple
931// using one of the ==, <=, <, etc, operators. The two fields being
932// compared don't have to have the same type.
933//
934// The matcher defined here is polymorphic (for example, Eq() can be
935// used to match a tuple<int, short>, a tuple<const long&, double>,
936// etc). Therefore we use a template type conversion operator in the
937// implementation.
938//
939// We define this as a macro in order to eliminate duplicated source
940// code.
zhanyong.wan2661c682009-06-09 05:42:12 +0000941#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op) \
shiqiane35fdd92008-12-10 05:08:54 +0000942 class name##2Matcher { \
943 public: \
944 template <typename T1, typename T2> \
945 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
946 return MakeMatcher(new Impl<T1, T2>); \
947 } \
948 private: \
949 template <typename T1, typename T2> \
950 class Impl : public MatcherInterface<const ::std::tr1::tuple<T1, T2>&> { \
951 public: \
952 virtual bool Matches(const ::std::tr1::tuple<T1, T2>& args) const { \
953 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
954 } \
955 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +0000956 *os << "are a pair (x, y) where x " #op " y"; \
shiqiane35fdd92008-12-10 05:08:54 +0000957 } \
958 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +0000959 *os << "are a pair (x, y) where x " #op " y is false"; \
shiqiane35fdd92008-12-10 05:08:54 +0000960 } \
961 }; \
962 }
963
964// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wan2661c682009-06-09 05:42:12 +0000965GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==);
966GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ge, >=);
967GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Gt, >);
968GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Le, <=);
969GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Lt, <);
970GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=);
shiqiane35fdd92008-12-10 05:08:54 +0000971
zhanyong.wane0d051e2009-02-19 00:33:37 +0000972#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000973
zhanyong.wanc6a41232009-05-13 23:38:40 +0000974// Implements the Not(...) matcher for a particular argument type T.
975// We do not nest it inside the NotMatcher class template, as that
976// will prevent different instantiations of NotMatcher from sharing
977// the same NotMatcherImpl<T> class.
978template <typename T>
979class NotMatcherImpl : public MatcherInterface<T> {
980 public:
981 explicit NotMatcherImpl(const Matcher<T>& matcher)
982 : matcher_(matcher) {}
983
984 virtual bool Matches(T x) const {
985 return !matcher_.Matches(x);
986 }
987
988 virtual void DescribeTo(::std::ostream* os) const {
989 matcher_.DescribeNegationTo(os);
990 }
991
992 virtual void DescribeNegationTo(::std::ostream* os) const {
993 matcher_.DescribeTo(os);
994 }
995
996 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
997 matcher_.ExplainMatchResultTo(x, os);
998 }
999 private:
1000 const Matcher<T> matcher_;
1001};
1002
shiqiane35fdd92008-12-10 05:08:54 +00001003// Implements the Not(m) matcher, which matches a value that doesn't
1004// match matcher m.
1005template <typename InnerMatcher>
1006class NotMatcher {
1007 public:
1008 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1009
1010 // This template type conversion operator allows Not(m) to be used
1011 // to match any type m can match.
1012 template <typename T>
1013 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001014 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001015 }
1016 private:
shiqiane35fdd92008-12-10 05:08:54 +00001017 InnerMatcher matcher_;
1018};
1019
zhanyong.wanc6a41232009-05-13 23:38:40 +00001020// Implements the AllOf(m1, m2) matcher for a particular argument type
1021// T. We do not nest it inside the BothOfMatcher class template, as
1022// that will prevent different instantiations of BothOfMatcher from
1023// sharing the same BothOfMatcherImpl<T> class.
1024template <typename T>
1025class BothOfMatcherImpl : public MatcherInterface<T> {
1026 public:
1027 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1028 : matcher1_(matcher1), matcher2_(matcher2) {}
1029
1030 virtual bool Matches(T x) const {
1031 return matcher1_.Matches(x) && matcher2_.Matches(x);
1032 }
1033
1034 virtual void DescribeTo(::std::ostream* os) const {
1035 *os << "(";
1036 matcher1_.DescribeTo(os);
1037 *os << ") and (";
1038 matcher2_.DescribeTo(os);
1039 *os << ")";
1040 }
1041
1042 virtual void DescribeNegationTo(::std::ostream* os) const {
1043 *os << "not ";
1044 DescribeTo(os);
1045 }
1046
1047 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1048 if (Matches(x)) {
1049 // When both matcher1_ and matcher2_ match x, we need to
1050 // explain why *both* of them match.
1051 ::std::stringstream ss1;
1052 matcher1_.ExplainMatchResultTo(x, &ss1);
1053 const internal::string s1 = ss1.str();
1054
1055 ::std::stringstream ss2;
1056 matcher2_.ExplainMatchResultTo(x, &ss2);
1057 const internal::string s2 = ss2.str();
1058
1059 if (s1 == "") {
1060 *os << s2;
1061 } else {
1062 *os << s1;
1063 if (s2 != "") {
1064 *os << "; " << s2;
1065 }
1066 }
1067 } else {
1068 // Otherwise we only need to explain why *one* of them fails
1069 // to match.
1070 if (!matcher1_.Matches(x)) {
1071 matcher1_.ExplainMatchResultTo(x, os);
1072 } else {
1073 matcher2_.ExplainMatchResultTo(x, os);
1074 }
1075 }
1076 }
1077 private:
1078 const Matcher<T> matcher1_;
1079 const Matcher<T> matcher2_;
1080};
1081
shiqiane35fdd92008-12-10 05:08:54 +00001082// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1083// matches a value that matches all of the matchers m_1, ..., and m_n.
1084template <typename Matcher1, typename Matcher2>
1085class BothOfMatcher {
1086 public:
1087 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1088 : matcher1_(matcher1), matcher2_(matcher2) {}
1089
1090 // This template type conversion operator allows a
1091 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1092 // both Matcher1 and Matcher2 can match.
1093 template <typename T>
1094 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001095 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1096 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001097 }
1098 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001099 Matcher1 matcher1_;
1100 Matcher2 matcher2_;
1101};
shiqiane35fdd92008-12-10 05:08:54 +00001102
zhanyong.wanc6a41232009-05-13 23:38:40 +00001103// Implements the AnyOf(m1, m2) matcher for a particular argument type
1104// T. We do not nest it inside the AnyOfMatcher class template, as
1105// that will prevent different instantiations of AnyOfMatcher from
1106// sharing the same EitherOfMatcherImpl<T> class.
1107template <typename T>
1108class EitherOfMatcherImpl : public MatcherInterface<T> {
1109 public:
1110 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1111 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001112
zhanyong.wanc6a41232009-05-13 23:38:40 +00001113 virtual bool Matches(T x) const {
1114 return matcher1_.Matches(x) || matcher2_.Matches(x);
1115 }
shiqiane35fdd92008-12-10 05:08:54 +00001116
zhanyong.wanc6a41232009-05-13 23:38:40 +00001117 virtual void DescribeTo(::std::ostream* os) const {
1118 *os << "(";
1119 matcher1_.DescribeTo(os);
1120 *os << ") or (";
1121 matcher2_.DescribeTo(os);
1122 *os << ")";
1123 }
shiqiane35fdd92008-12-10 05:08:54 +00001124
zhanyong.wanc6a41232009-05-13 23:38:40 +00001125 virtual void DescribeNegationTo(::std::ostream* os) const {
1126 *os << "not ";
1127 DescribeTo(os);
1128 }
shiqiane35fdd92008-12-10 05:08:54 +00001129
zhanyong.wanc6a41232009-05-13 23:38:40 +00001130 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1131 if (Matches(x)) {
1132 // If either matcher1_ or matcher2_ matches x, we just need
1133 // to explain why *one* of them matches.
1134 if (matcher1_.Matches(x)) {
1135 matcher1_.ExplainMatchResultTo(x, os);
shiqiane35fdd92008-12-10 05:08:54 +00001136 } else {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001137 matcher2_.ExplainMatchResultTo(x, os);
1138 }
1139 } else {
1140 // Otherwise we need to explain why *neither* matches.
1141 ::std::stringstream ss1;
1142 matcher1_.ExplainMatchResultTo(x, &ss1);
1143 const internal::string s1 = ss1.str();
1144
1145 ::std::stringstream ss2;
1146 matcher2_.ExplainMatchResultTo(x, &ss2);
1147 const internal::string s2 = ss2.str();
1148
1149 if (s1 == "") {
1150 *os << s2;
1151 } else {
1152 *os << s1;
1153 if (s2 != "") {
1154 *os << "; " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001155 }
1156 }
1157 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001158 }
1159 private:
1160 const Matcher<T> matcher1_;
1161 const Matcher<T> matcher2_;
shiqiane35fdd92008-12-10 05:08:54 +00001162};
1163
1164// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1165// matches a value that matches at least one of the matchers m_1, ...,
1166// and m_n.
1167template <typename Matcher1, typename Matcher2>
1168class EitherOfMatcher {
1169 public:
1170 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1171 : matcher1_(matcher1), matcher2_(matcher2) {}
1172
1173 // This template type conversion operator allows a
1174 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1175 // both Matcher1 and Matcher2 can match.
1176 template <typename T>
1177 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001178 return Matcher<T>(new EitherOfMatcherImpl<T>(
1179 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001180 }
1181 private:
shiqiane35fdd92008-12-10 05:08:54 +00001182 Matcher1 matcher1_;
1183 Matcher2 matcher2_;
1184};
1185
1186// Used for implementing Truly(pred), which turns a predicate into a
1187// matcher.
1188template <typename Predicate>
1189class TrulyMatcher {
1190 public:
1191 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1192
1193 // This method template allows Truly(pred) to be used as a matcher
1194 // for type T where T is the argument type of predicate 'pred'. The
1195 // argument is passed by reference as the predicate may be
1196 // interested in the address of the argument.
1197 template <typename T>
zhanyong.wan16cf4732009-05-14 20:55:30 +00001198 bool Matches(T& x) const { // NOLINT
zhanyong.wan652540a2009-02-23 23:37:29 +00001199#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001200 // MSVC warns about converting a value into bool (warning 4800).
1201#pragma warning(push) // Saves the current warning state.
1202#pragma warning(disable:4800) // Temporarily disables warning 4800.
1203#endif // GTEST_OS_WINDOWS
1204 return predicate_(x);
zhanyong.wan652540a2009-02-23 23:37:29 +00001205#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001206#pragma warning(pop) // Restores the warning state.
1207#endif // GTEST_OS_WINDOWS
1208 }
1209
1210 void DescribeTo(::std::ostream* os) const {
1211 *os << "satisfies the given predicate";
1212 }
1213
1214 void DescribeNegationTo(::std::ostream* os) const {
1215 *os << "doesn't satisfy the given predicate";
1216 }
1217 private:
1218 Predicate predicate_;
1219};
1220
1221// Used for implementing Matches(matcher), which turns a matcher into
1222// a predicate.
1223template <typename M>
1224class MatcherAsPredicate {
1225 public:
1226 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1227
1228 // This template operator() allows Matches(m) to be used as a
1229 // predicate on type T where m is a matcher on type T.
1230 //
1231 // The argument x is passed by reference instead of by value, as
1232 // some matcher may be interested in its address (e.g. as in
1233 // Matches(Ref(n))(x)).
1234 template <typename T>
1235 bool operator()(const T& x) const {
1236 // We let matcher_ commit to a particular type here instead of
1237 // when the MatcherAsPredicate object was constructed. This
1238 // allows us to write Matches(m) where m is a polymorphic matcher
1239 // (e.g. Eq(5)).
1240 //
1241 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1242 // compile when matcher_ has type Matcher<const T&>; if we write
1243 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1244 // when matcher_ has type Matcher<T>; if we just write
1245 // matcher_.Matches(x), it won't compile when matcher_ is
1246 // polymorphic, e.g. Eq(5).
1247 //
1248 // MatcherCast<const T&>() is necessary for making the code work
1249 // in all of the above situations.
1250 return MatcherCast<const T&>(matcher_).Matches(x);
1251 }
1252 private:
1253 M matcher_;
1254};
1255
1256// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1257// argument M must be a type that can be converted to a matcher.
1258template <typename M>
1259class PredicateFormatterFromMatcher {
1260 public:
1261 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1262
1263 // This template () operator allows a PredicateFormatterFromMatcher
1264 // object to act as a predicate-formatter suitable for using with
1265 // Google Test's EXPECT_PRED_FORMAT1() macro.
1266 template <typename T>
1267 AssertionResult operator()(const char* value_text, const T& x) const {
1268 // We convert matcher_ to a Matcher<const T&> *now* instead of
1269 // when the PredicateFormatterFromMatcher object was constructed,
1270 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1271 // know which type to instantiate it to until we actually see the
1272 // type of x here.
1273 //
1274 // We write MatcherCast<const T&>(matcher_) instead of
1275 // Matcher<const T&>(matcher_), as the latter won't compile when
1276 // matcher_ has type Matcher<T> (e.g. An<int>()).
1277 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
1278 if (matcher.Matches(x)) {
1279 return AssertionSuccess();
1280 } else {
1281 ::std::stringstream ss;
1282 ss << "Value of: " << value_text << "\n"
1283 << "Expected: ";
1284 matcher.DescribeTo(&ss);
1285 ss << "\n Actual: ";
1286 UniversalPrinter<T>::Print(x, &ss);
1287 ExplainMatchResultAsNeededTo<const T&>(matcher, x, &ss);
1288 return AssertionFailure(Message() << ss.str());
1289 }
1290 }
1291 private:
1292 const M matcher_;
1293};
1294
1295// A helper function for converting a matcher to a predicate-formatter
1296// without the user needing to explicitly write the type. This is
1297// used for implementing ASSERT_THAT() and EXPECT_THAT().
1298template <typename M>
1299inline PredicateFormatterFromMatcher<M>
1300MakePredicateFormatterFromMatcher(const M& matcher) {
1301 return PredicateFormatterFromMatcher<M>(matcher);
1302}
1303
1304// Implements the polymorphic floating point equality matcher, which
1305// matches two float values using ULP-based approximation. The
1306// template is meant to be instantiated with FloatType being either
1307// float or double.
1308template <typename FloatType>
1309class FloatingEqMatcher {
1310 public:
1311 // Constructor for FloatingEqMatcher.
1312 // The matcher's input will be compared with rhs. The matcher treats two
1313 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1314 // equality comparisons between NANs will always return false.
1315 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1316 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1317
1318 // Implements floating point equality matcher as a Matcher<T>.
1319 template <typename T>
1320 class Impl : public MatcherInterface<T> {
1321 public:
1322 Impl(FloatType rhs, bool nan_eq_nan) :
1323 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1324
1325 virtual bool Matches(T value) const {
1326 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1327
1328 // Compares NaNs first, if nan_eq_nan_ is true.
1329 if (nan_eq_nan_ && lhs.is_nan()) {
1330 return rhs.is_nan();
1331 }
1332
1333 return lhs.AlmostEquals(rhs);
1334 }
1335
1336 virtual void DescribeTo(::std::ostream* os) const {
1337 // os->precision() returns the previously set precision, which we
1338 // store to restore the ostream to its original configuration
1339 // after outputting.
1340 const ::std::streamsize old_precision = os->precision(
1341 ::std::numeric_limits<FloatType>::digits10 + 2);
1342 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1343 if (nan_eq_nan_) {
1344 *os << "is NaN";
1345 } else {
1346 *os << "never matches";
1347 }
1348 } else {
1349 *os << "is approximately " << rhs_;
1350 }
1351 os->precision(old_precision);
1352 }
1353
1354 virtual void DescribeNegationTo(::std::ostream* os) const {
1355 // As before, get original precision.
1356 const ::std::streamsize old_precision = os->precision(
1357 ::std::numeric_limits<FloatType>::digits10 + 2);
1358 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1359 if (nan_eq_nan_) {
1360 *os << "is not NaN";
1361 } else {
1362 *os << "is anything";
1363 }
1364 } else {
1365 *os << "is not approximately " << rhs_;
1366 }
1367 // Restore original precision.
1368 os->precision(old_precision);
1369 }
1370
1371 private:
1372 const FloatType rhs_;
1373 const bool nan_eq_nan_;
1374 };
1375
1376 // The following 3 type conversion operators allow FloatEq(rhs) and
1377 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1378 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1379 // (While Google's C++ coding style doesn't allow arguments passed
1380 // by non-const reference, we may see them in code not conforming to
1381 // the style. Therefore Google Mock needs to support them.)
1382 operator Matcher<FloatType>() const {
1383 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1384 }
1385
1386 operator Matcher<const FloatType&>() const {
1387 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1388 }
1389
1390 operator Matcher<FloatType&>() const {
1391 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1392 }
1393 private:
1394 const FloatType rhs_;
1395 const bool nan_eq_nan_;
1396};
1397
1398// Implements the Pointee(m) matcher for matching a pointer whose
1399// pointee matches matcher m. The pointer can be either raw or smart.
1400template <typename InnerMatcher>
1401class PointeeMatcher {
1402 public:
1403 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1404
1405 // This type conversion operator template allows Pointee(m) to be
1406 // used as a matcher for any pointer type whose pointee type is
1407 // compatible with the inner matcher, where type Pointer can be
1408 // either a raw pointer or a smart pointer.
1409 //
1410 // The reason we do this instead of relying on
1411 // MakePolymorphicMatcher() is that the latter is not flexible
1412 // enough for implementing the DescribeTo() method of Pointee().
1413 template <typename Pointer>
1414 operator Matcher<Pointer>() const {
1415 return MakeMatcher(new Impl<Pointer>(matcher_));
1416 }
1417 private:
1418 // The monomorphic implementation that works for a particular pointer type.
1419 template <typename Pointer>
1420 class Impl : public MatcherInterface<Pointer> {
1421 public:
zhanyong.wane0d051e2009-02-19 00:33:37 +00001422 typedef typename PointeeOf<GMOCK_REMOVE_CONST_( // NOLINT
1423 GMOCK_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001424
1425 explicit Impl(const InnerMatcher& matcher)
1426 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1427
1428 virtual bool Matches(Pointer p) const {
1429 return GetRawPointer(p) != NULL && matcher_.Matches(*p);
1430 }
1431
1432 virtual void DescribeTo(::std::ostream* os) const {
1433 *os << "points to a value that ";
1434 matcher_.DescribeTo(os);
1435 }
1436
1437 virtual void DescribeNegationTo(::std::ostream* os) const {
1438 *os << "does not point to a value that ";
1439 matcher_.DescribeTo(os);
1440 }
1441
1442 virtual void ExplainMatchResultTo(Pointer pointer,
1443 ::std::ostream* os) const {
1444 if (GetRawPointer(pointer) == NULL)
1445 return;
1446
1447 ::std::stringstream ss;
1448 matcher_.ExplainMatchResultTo(*pointer, &ss);
1449 const internal::string s = ss.str();
1450 if (s != "") {
1451 *os << "points to a value that " << s;
1452 }
1453 }
1454 private:
1455 const Matcher<const Pointee&> matcher_;
1456 };
1457
1458 const InnerMatcher matcher_;
1459};
1460
1461// Implements the Field() matcher for matching a field (i.e. member
1462// variable) of an object.
1463template <typename Class, typename FieldType>
1464class FieldMatcher {
1465 public:
1466 FieldMatcher(FieldType Class::*field,
1467 const Matcher<const FieldType&>& matcher)
1468 : field_(field), matcher_(matcher) {}
1469
1470 // Returns true iff the inner matcher matches obj.field.
1471 bool Matches(const Class& obj) const {
1472 return matcher_.Matches(obj.*field_);
1473 }
1474
1475 // Returns true iff the inner matcher matches obj->field.
1476 bool Matches(const Class* p) const {
1477 return (p != NULL) && matcher_.Matches(p->*field_);
1478 }
1479
1480 void DescribeTo(::std::ostream* os) const {
1481 *os << "the given field ";
1482 matcher_.DescribeTo(os);
1483 }
1484
1485 void DescribeNegationTo(::std::ostream* os) const {
1486 *os << "the given field ";
1487 matcher_.DescribeNegationTo(os);
1488 }
1489
zhanyong.wan18490652009-05-11 18:54:08 +00001490 // The first argument of ExplainMatchResultTo() is needed to help
1491 // Symbian's C++ compiler choose which overload to use. Its type is
1492 // true_type iff the Field() matcher is used to match a pointer.
1493 void ExplainMatchResultTo(false_type /* is_not_pointer */, const Class& obj,
1494 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001495 ::std::stringstream ss;
1496 matcher_.ExplainMatchResultTo(obj.*field_, &ss);
1497 const internal::string s = ss.str();
1498 if (s != "") {
1499 *os << "the given field " << s;
1500 }
1501 }
1502
zhanyong.wan18490652009-05-11 18:54:08 +00001503 void ExplainMatchResultTo(true_type /* is_pointer */, const Class* p,
1504 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001505 if (p != NULL) {
zhanyong.wan18490652009-05-11 18:54:08 +00001506 // Since *p has a field, it must be a class/struct/union type
1507 // and thus cannot be a pointer. Therefore we pass false_type()
1508 // as the first argument.
1509 ExplainMatchResultTo(false_type(), *p, os);
shiqiane35fdd92008-12-10 05:08:54 +00001510 }
1511 }
1512 private:
1513 const FieldType Class::*field_;
1514 const Matcher<const FieldType&> matcher_;
1515};
1516
zhanyong.wan18490652009-05-11 18:54:08 +00001517// Explains the result of matching an object or pointer against a field matcher.
1518template <typename Class, typename FieldType, typename T>
shiqiane35fdd92008-12-10 05:08:54 +00001519void ExplainMatchResultTo(const FieldMatcher<Class, FieldType>& matcher,
zhanyong.wan18490652009-05-11 18:54:08 +00001520 const T& value, ::std::ostream* os) {
1521 matcher.ExplainMatchResultTo(
1522 typename ::testing::internal::is_pointer<T>::type(), value, os);
shiqiane35fdd92008-12-10 05:08:54 +00001523}
1524
1525// Implements the Property() matcher for matching a property
1526// (i.e. return value of a getter method) of an object.
1527template <typename Class, typename PropertyType>
1528class PropertyMatcher {
1529 public:
1530 // The property may have a reference type, so 'const PropertyType&'
1531 // may cause double references and fail to compile. That's why we
1532 // need GMOCK_REFERENCE_TO_CONST, which works regardless of
1533 // PropertyType being a reference or not.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001534 typedef GMOCK_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001535
1536 PropertyMatcher(PropertyType (Class::*property)() const,
1537 const Matcher<RefToConstProperty>& matcher)
1538 : property_(property), matcher_(matcher) {}
1539
1540 // Returns true iff obj.property() matches the inner matcher.
1541 bool Matches(const Class& obj) const {
1542 return matcher_.Matches((obj.*property_)());
1543 }
1544
1545 // Returns true iff p->property() matches the inner matcher.
1546 bool Matches(const Class* p) const {
1547 return (p != NULL) && matcher_.Matches((p->*property_)());
1548 }
1549
1550 void DescribeTo(::std::ostream* os) const {
1551 *os << "the given property ";
1552 matcher_.DescribeTo(os);
1553 }
1554
1555 void DescribeNegationTo(::std::ostream* os) const {
1556 *os << "the given property ";
1557 matcher_.DescribeNegationTo(os);
1558 }
1559
zhanyong.wan18490652009-05-11 18:54:08 +00001560 // The first argument of ExplainMatchResultTo() is needed to help
1561 // Symbian's C++ compiler choose which overload to use. Its type is
1562 // true_type iff the Property() matcher is used to match a pointer.
1563 void ExplainMatchResultTo(false_type /* is_not_pointer */, const Class& obj,
1564 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001565 ::std::stringstream ss;
1566 matcher_.ExplainMatchResultTo((obj.*property_)(), &ss);
1567 const internal::string s = ss.str();
1568 if (s != "") {
1569 *os << "the given property " << s;
1570 }
1571 }
1572
zhanyong.wan18490652009-05-11 18:54:08 +00001573 void ExplainMatchResultTo(true_type /* is_pointer */, const Class* p,
1574 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001575 if (p != NULL) {
zhanyong.wan18490652009-05-11 18:54:08 +00001576 // Since *p has a property method, it must be a
1577 // class/struct/union type and thus cannot be a pointer.
1578 // Therefore we pass false_type() as the first argument.
1579 ExplainMatchResultTo(false_type(), *p, os);
shiqiane35fdd92008-12-10 05:08:54 +00001580 }
1581 }
1582 private:
1583 PropertyType (Class::*property_)() const;
1584 const Matcher<RefToConstProperty> matcher_;
1585};
1586
zhanyong.wan18490652009-05-11 18:54:08 +00001587// Explains the result of matching an object or pointer against a
1588// property matcher.
1589template <typename Class, typename PropertyType, typename T>
shiqiane35fdd92008-12-10 05:08:54 +00001590void ExplainMatchResultTo(const PropertyMatcher<Class, PropertyType>& matcher,
zhanyong.wan18490652009-05-11 18:54:08 +00001591 const T& value, ::std::ostream* os) {
1592 matcher.ExplainMatchResultTo(
1593 typename ::testing::internal::is_pointer<T>::type(), value, os);
shiqiane35fdd92008-12-10 05:08:54 +00001594}
1595
1596// Type traits specifying various features of different functors for ResultOf.
1597// The default template specifies features for functor objects.
1598// Functor classes have to typedef argument_type and result_type
1599// to be compatible with ResultOf.
1600template <typename Functor>
1601struct CallableTraits {
1602 typedef typename Functor::result_type ResultType;
1603 typedef Functor StorageType;
1604
1605 static void CheckIsValid(Functor functor) {}
1606 template <typename T>
1607 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1608};
1609
1610// Specialization for function pointers.
1611template <typename ArgType, typename ResType>
1612struct CallableTraits<ResType(*)(ArgType)> {
1613 typedef ResType ResultType;
1614 typedef ResType(*StorageType)(ArgType);
1615
1616 static void CheckIsValid(ResType(*f)(ArgType)) {
1617 GMOCK_CHECK_(f != NULL)
1618 << "NULL function pointer is passed into ResultOf().";
1619 }
1620 template <typename T>
1621 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1622 return (*f)(arg);
1623 }
1624};
1625
1626// Implements the ResultOf() matcher for matching a return value of a
1627// unary function of an object.
1628template <typename Callable>
1629class ResultOfMatcher {
1630 public:
1631 typedef typename CallableTraits<Callable>::ResultType ResultType;
1632
1633 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1634 : callable_(callable), matcher_(matcher) {
1635 CallableTraits<Callable>::CheckIsValid(callable_);
1636 }
1637
1638 template <typename T>
1639 operator Matcher<T>() const {
1640 return Matcher<T>(new Impl<T>(callable_, matcher_));
1641 }
1642
1643 private:
1644 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1645
1646 template <typename T>
1647 class Impl : public MatcherInterface<T> {
1648 public:
1649 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1650 : callable_(callable), matcher_(matcher) {}
1651 // Returns true iff callable_(obj) matches the inner matcher.
1652 // The calling syntax is different for different types of callables
1653 // so we abstract it in CallableTraits<Callable>::Invoke().
1654 virtual bool Matches(T obj) const {
1655 return matcher_.Matches(
1656 CallableTraits<Callable>::template Invoke<T>(callable_, obj));
1657 }
1658
1659 virtual void DescribeTo(::std::ostream* os) const {
1660 *os << "result of the given callable ";
1661 matcher_.DescribeTo(os);
1662 }
1663
1664 virtual void DescribeNegationTo(::std::ostream* os) const {
1665 *os << "result of the given callable ";
1666 matcher_.DescribeNegationTo(os);
1667 }
1668
1669 virtual void ExplainMatchResultTo(T obj, ::std::ostream* os) const {
1670 ::std::stringstream ss;
1671 matcher_.ExplainMatchResultTo(
1672 CallableTraits<Callable>::template Invoke<T>(callable_, obj),
1673 &ss);
1674 const internal::string s = ss.str();
1675 if (s != "")
1676 *os << "result of the given callable " << s;
1677 }
1678 private:
1679 // Functors often define operator() as non-const method even though
1680 // they are actualy stateless. But we need to use them even when
1681 // 'this' is a const pointer. It's the user's responsibility not to
1682 // use stateful callables with ResultOf(), which does't guarantee
1683 // how many times the callable will be invoked.
1684 mutable CallableStorageType callable_;
1685 const Matcher<ResultType> matcher_;
1686 }; // class Impl
1687
1688 const CallableStorageType callable_;
1689 const Matcher<ResultType> matcher_;
1690};
1691
1692// Explains the result of matching a value against a functor matcher.
1693template <typename T, typename Callable>
1694void ExplainMatchResultTo(const ResultOfMatcher<Callable>& matcher,
1695 T obj, ::std::ostream* os) {
1696 matcher.ExplainMatchResultTo(obj, os);
1697}
1698
zhanyong.wan6a896b52009-01-16 01:13:50 +00001699// Implements an equality matcher for any STL-style container whose elements
1700// support ==. This matcher is like Eq(), but its failure explanations provide
1701// more detailed information that is useful when the container is used as a set.
1702// The failure message reports elements that are in one of the operands but not
1703// the other. The failure messages do not report duplicate or out-of-order
1704// elements in the containers (which don't properly matter to sets, but can
1705// occur if the containers are vectors or lists, for example).
1706//
1707// Uses the container's const_iterator, value_type, operator ==,
1708// begin(), and end().
1709template <typename Container>
1710class ContainerEqMatcher {
1711 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00001712 typedef internal::StlContainerView<Container> View;
1713 typedef typename View::type StlContainer;
1714 typedef typename View::const_reference StlContainerReference;
1715
1716 // We make a copy of rhs in case the elements in it are modified
1717 // after this matcher is created.
1718 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
1719 // Makes sure the user doesn't instantiate this class template
1720 // with a const or reference type.
1721 testing::StaticAssertTypeEq<Container,
1722 GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))>();
1723 }
1724
1725 template <typename LhsContainer>
1726 bool Matches(const LhsContainer& lhs) const {
1727 // GMOCK_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
1728 // that causes LhsContainer to be a const type sometimes.
1729 typedef internal::StlContainerView<GMOCK_REMOVE_CONST_(LhsContainer)>
1730 LhsView;
1731 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
1732 return lhs_stl_container == rhs_;
1733 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00001734 void DescribeTo(::std::ostream* os) const {
1735 *os << "equals ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001736 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001737 }
1738 void DescribeNegationTo(::std::ostream* os) const {
1739 *os << "does not equal ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001740 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001741 }
1742
zhanyong.wanb8243162009-06-04 05:48:20 +00001743 template <typename LhsContainer>
1744 void ExplainMatchResultTo(const LhsContainer& lhs,
zhanyong.wan6a896b52009-01-16 01:13:50 +00001745 ::std::ostream* os) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00001746 // GMOCK_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
1747 // that causes LhsContainer to be a const type sometimes.
1748 typedef internal::StlContainerView<GMOCK_REMOVE_CONST_(LhsContainer)>
1749 LhsView;
1750 typedef typename LhsView::type LhsStlContainer;
1751 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
1752
zhanyong.wan6a896b52009-01-16 01:13:50 +00001753 // Something is different. Check for missing values first.
1754 bool printed_header = false;
zhanyong.wanb8243162009-06-04 05:48:20 +00001755 for (typename LhsStlContainer::const_iterator it =
1756 lhs_stl_container.begin();
1757 it != lhs_stl_container.end(); ++it) {
1758 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
1759 rhs_.end()) {
zhanyong.wan6a896b52009-01-16 01:13:50 +00001760 if (printed_header) {
1761 *os << ", ";
1762 } else {
1763 *os << "Only in actual: ";
1764 printed_header = true;
1765 }
zhanyong.wanb8243162009-06-04 05:48:20 +00001766 UniversalPrinter<typename LhsStlContainer::value_type>::Print(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001767 }
1768 }
1769
1770 // Now check for extra values.
1771 bool printed_header2 = false;
zhanyong.wanb8243162009-06-04 05:48:20 +00001772 for (typename StlContainer::const_iterator it = rhs_.begin();
zhanyong.wan6a896b52009-01-16 01:13:50 +00001773 it != rhs_.end(); ++it) {
zhanyong.wanb8243162009-06-04 05:48:20 +00001774 if (internal::ArrayAwareFind(
1775 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
1776 lhs_stl_container.end()) {
zhanyong.wan6a896b52009-01-16 01:13:50 +00001777 if (printed_header2) {
1778 *os << ", ";
1779 } else {
1780 *os << (printed_header ? "; not" : "Not") << " in actual: ";
1781 printed_header2 = true;
1782 }
zhanyong.wanb8243162009-06-04 05:48:20 +00001783 UniversalPrinter<typename StlContainer::value_type>::Print(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001784 }
1785 }
1786 }
1787 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00001788 const StlContainer rhs_;
zhanyong.wan6a896b52009-01-16 01:13:50 +00001789};
1790
zhanyong.wanb8243162009-06-04 05:48:20 +00001791template <typename LhsContainer, typename Container>
zhanyong.wan6a896b52009-01-16 01:13:50 +00001792void ExplainMatchResultTo(const ContainerEqMatcher<Container>& matcher,
zhanyong.wanb8243162009-06-04 05:48:20 +00001793 const LhsContainer& lhs,
zhanyong.wan6a896b52009-01-16 01:13:50 +00001794 ::std::ostream* os) {
1795 matcher.ExplainMatchResultTo(lhs, os);
1796}
1797
zhanyong.wanb8243162009-06-04 05:48:20 +00001798// Implements Contains(element_matcher) for the given argument type Container.
1799template <typename Container>
1800class ContainsMatcherImpl : public MatcherInterface<Container> {
1801 public:
1802 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
1803 typedef StlContainerView<RawContainer> View;
1804 typedef typename View::type StlContainer;
1805 typedef typename View::const_reference StlContainerReference;
1806 typedef typename StlContainer::value_type Element;
1807
1808 template <typename InnerMatcher>
1809 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
1810 : inner_matcher_(
1811 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
1812
1813 // Returns true iff 'container' matches.
1814 virtual bool Matches(Container container) const {
1815 StlContainerReference stl_container = View::ConstReference(container);
1816 for (typename StlContainer::const_iterator it = stl_container.begin();
1817 it != stl_container.end(); ++it) {
1818 if (inner_matcher_.Matches(*it))
1819 return true;
1820 }
1821 return false;
1822 }
1823
1824 // Describes what this matcher does.
1825 virtual void DescribeTo(::std::ostream* os) const {
1826 *os << "contains at least one element that ";
1827 inner_matcher_.DescribeTo(os);
1828 }
1829
1830 // Describes what the negation of this matcher does.
1831 virtual void DescribeNegationTo(::std::ostream* os) const {
1832 *os << "doesn't contain any element that ";
1833 inner_matcher_.DescribeTo(os);
1834 }
1835
1836 // Explains why 'container' matches, or doesn't match, this matcher.
1837 virtual void ExplainMatchResultTo(Container container,
1838 ::std::ostream* os) const {
1839 StlContainerReference stl_container = View::ConstReference(container);
1840
1841 // We need to explain which (if any) element matches inner_matcher_.
1842 typename StlContainer::const_iterator it = stl_container.begin();
1843 for (size_t i = 0; it != stl_container.end(); ++it, ++i) {
1844 if (inner_matcher_.Matches(*it)) {
1845 *os << "element " << i << " matches";
1846 return;
1847 }
1848 }
1849 }
1850
1851 private:
1852 const Matcher<const Element&> inner_matcher_;
1853};
1854
1855// Implements polymorphic Contains(element_matcher).
1856template <typename M>
1857class ContainsMatcher {
1858 public:
1859 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
1860
1861 template <typename Container>
1862 operator Matcher<Container>() const {
1863 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
1864 }
1865
1866 private:
1867 const M inner_matcher_;
1868};
1869
shiqiane35fdd92008-12-10 05:08:54 +00001870} // namespace internal
1871
1872// Implements MatcherCast().
1873template <typename T, typename M>
1874inline Matcher<T> MatcherCast(M matcher) {
1875 return internal::MatcherCastImpl<T, M>::Cast(matcher);
1876}
1877
1878// _ is a matcher that matches anything of any type.
1879//
1880// This definition is fine as:
1881//
1882// 1. The C++ standard permits using the name _ in a namespace that
1883// is not the global namespace or ::std.
1884// 2. The AnythingMatcher class has no data member or constructor,
1885// so it's OK to create global variables of this type.
1886// 3. c-style has approved of using _ in this case.
1887const internal::AnythingMatcher _ = {};
1888// Creates a matcher that matches any value of the given type T.
1889template <typename T>
1890inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
1891
1892// Creates a matcher that matches any value of the given type T.
1893template <typename T>
1894inline Matcher<T> An() { return A<T>(); }
1895
1896// Creates a polymorphic matcher that matches anything equal to x.
1897// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
1898// wouldn't compile.
1899template <typename T>
1900inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
1901
1902// Constructs a Matcher<T> from a 'value' of type T. The constructed
1903// matcher matches any value that's equal to 'value'.
1904template <typename T>
1905Matcher<T>::Matcher(T value) { *this = Eq(value); }
1906
1907// Creates a monomorphic matcher that matches anything with type Lhs
1908// and equal to rhs. A user may need to use this instead of Eq(...)
1909// in order to resolve an overloading ambiguity.
1910//
1911// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
1912// or Matcher<T>(x), but more readable than the latter.
1913//
1914// We could define similar monomorphic matchers for other comparison
1915// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
1916// it yet as those are used much less than Eq() in practice. A user
1917// can always write Matcher<T>(Lt(5)) to be explicit about the type,
1918// for example.
1919template <typename Lhs, typename Rhs>
1920inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
1921
1922// Creates a polymorphic matcher that matches anything >= x.
1923template <typename Rhs>
1924inline internal::GeMatcher<Rhs> Ge(Rhs x) {
1925 return internal::GeMatcher<Rhs>(x);
1926}
1927
1928// Creates a polymorphic matcher that matches anything > x.
1929template <typename Rhs>
1930inline internal::GtMatcher<Rhs> Gt(Rhs x) {
1931 return internal::GtMatcher<Rhs>(x);
1932}
1933
1934// Creates a polymorphic matcher that matches anything <= x.
1935template <typename Rhs>
1936inline internal::LeMatcher<Rhs> Le(Rhs x) {
1937 return internal::LeMatcher<Rhs>(x);
1938}
1939
1940// Creates a polymorphic matcher that matches anything < x.
1941template <typename Rhs>
1942inline internal::LtMatcher<Rhs> Lt(Rhs x) {
1943 return internal::LtMatcher<Rhs>(x);
1944}
1945
1946// Creates a polymorphic matcher that matches anything != x.
1947template <typename Rhs>
1948inline internal::NeMatcher<Rhs> Ne(Rhs x) {
1949 return internal::NeMatcher<Rhs>(x);
1950}
1951
1952// Creates a polymorphic matcher that matches any non-NULL pointer.
1953// This is convenient as Not(NULL) doesn't compile (the compiler
1954// thinks that that expression is comparing a pointer with an integer).
1955inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
1956 return MakePolymorphicMatcher(internal::NotNullMatcher());
1957}
1958
1959// Creates a polymorphic matcher that matches any argument that
1960// references variable x.
1961template <typename T>
1962inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
1963 return internal::RefMatcher<T&>(x);
1964}
1965
1966// Creates a matcher that matches any double argument approximately
1967// equal to rhs, where two NANs are considered unequal.
1968inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
1969 return internal::FloatingEqMatcher<double>(rhs, false);
1970}
1971
1972// Creates a matcher that matches any double argument approximately
1973// equal to rhs, including NaN values when rhs is NaN.
1974inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
1975 return internal::FloatingEqMatcher<double>(rhs, true);
1976}
1977
1978// Creates a matcher that matches any float argument approximately
1979// equal to rhs, where two NANs are considered unequal.
1980inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
1981 return internal::FloatingEqMatcher<float>(rhs, false);
1982}
1983
1984// Creates a matcher that matches any double argument approximately
1985// equal to rhs, including NaN values when rhs is NaN.
1986inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
1987 return internal::FloatingEqMatcher<float>(rhs, true);
1988}
1989
1990// Creates a matcher that matches a pointer (raw or smart) that points
1991// to a value that matches inner_matcher.
1992template <typename InnerMatcher>
1993inline internal::PointeeMatcher<InnerMatcher> Pointee(
1994 const InnerMatcher& inner_matcher) {
1995 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
1996}
1997
1998// Creates a matcher that matches an object whose given field matches
1999// 'matcher'. For example,
2000// Field(&Foo::number, Ge(5))
2001// matches a Foo object x iff x.number >= 5.
2002template <typename Class, typename FieldType, typename FieldMatcher>
2003inline PolymorphicMatcher<
2004 internal::FieldMatcher<Class, FieldType> > Field(
2005 FieldType Class::*field, const FieldMatcher& matcher) {
2006 return MakePolymorphicMatcher(
2007 internal::FieldMatcher<Class, FieldType>(
2008 field, MatcherCast<const FieldType&>(matcher)));
2009 // The call to MatcherCast() is required for supporting inner
2010 // matchers of compatible types. For example, it allows
2011 // Field(&Foo::bar, m)
2012 // to compile where bar is an int32 and m is a matcher for int64.
2013}
2014
2015// Creates a matcher that matches an object whose given property
2016// matches 'matcher'. For example,
2017// Property(&Foo::str, StartsWith("hi"))
2018// matches a Foo object x iff x.str() starts with "hi".
2019template <typename Class, typename PropertyType, typename PropertyMatcher>
2020inline PolymorphicMatcher<
2021 internal::PropertyMatcher<Class, PropertyType> > Property(
2022 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2023 return MakePolymorphicMatcher(
2024 internal::PropertyMatcher<Class, PropertyType>(
2025 property,
zhanyong.wane0d051e2009-02-19 00:33:37 +00002026 MatcherCast<GMOCK_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002027 // The call to MatcherCast() is required for supporting inner
2028 // matchers of compatible types. For example, it allows
2029 // Property(&Foo::bar, m)
2030 // to compile where bar() returns an int32 and m is a matcher for int64.
2031}
2032
2033// Creates a matcher that matches an object iff the result of applying
2034// a callable to x matches 'matcher'.
2035// For example,
2036// ResultOf(f, StartsWith("hi"))
2037// matches a Foo object x iff f(x) starts with "hi".
2038// callable parameter can be a function, function pointer, or a functor.
2039// Callable has to satisfy the following conditions:
2040// * It is required to keep no state affecting the results of
2041// the calls on it and make no assumptions about how many calls
2042// will be made. Any state it keeps must be protected from the
2043// concurrent access.
2044// * If it is a function object, it has to define type result_type.
2045// We recommend deriving your functor classes from std::unary_function.
2046template <typename Callable, typename ResultOfMatcher>
2047internal::ResultOfMatcher<Callable> ResultOf(
2048 Callable callable, const ResultOfMatcher& matcher) {
2049 return internal::ResultOfMatcher<Callable>(
2050 callable,
2051 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2052 matcher));
2053 // The call to MatcherCast() is required for supporting inner
2054 // matchers of compatible types. For example, it allows
2055 // ResultOf(Function, m)
2056 // to compile where Function() returns an int32 and m is a matcher for int64.
2057}
2058
2059// String matchers.
2060
2061// Matches a string equal to str.
2062inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2063 StrEq(const internal::string& str) {
2064 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2065 str, true, true));
2066}
2067
2068// Matches a string not equal to str.
2069inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2070 StrNe(const internal::string& str) {
2071 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2072 str, false, true));
2073}
2074
2075// Matches a string equal to str, ignoring case.
2076inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2077 StrCaseEq(const internal::string& str) {
2078 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2079 str, true, false));
2080}
2081
2082// Matches a string not equal to str, ignoring case.
2083inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2084 StrCaseNe(const internal::string& str) {
2085 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2086 str, false, false));
2087}
2088
2089// Creates a matcher that matches any string, std::string, or C string
2090// that contains the given substring.
2091inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2092 HasSubstr(const internal::string& substring) {
2093 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
2094 substring));
2095}
2096
2097// Matches a string that starts with 'prefix' (case-sensitive).
2098inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
2099 StartsWith(const internal::string& prefix) {
2100 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
2101 prefix));
2102}
2103
2104// Matches a string that ends with 'suffix' (case-sensitive).
2105inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
2106 EndsWith(const internal::string& suffix) {
2107 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
2108 suffix));
2109}
2110
2111#ifdef GMOCK_HAS_REGEX
2112
2113// Matches a string that fully matches regular expression 'regex'.
2114// The matcher takes ownership of 'regex'.
2115inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2116 const internal::RE* regex) {
2117 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2118}
2119inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2120 const internal::string& regex) {
2121 return MatchesRegex(new internal::RE(regex));
2122}
2123
2124// Matches a string that contains regular expression 'regex'.
2125// The matcher takes ownership of 'regex'.
2126inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2127 const internal::RE* regex) {
2128 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2129}
2130inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2131 const internal::string& regex) {
2132 return ContainsRegex(new internal::RE(regex));
2133}
2134
2135#endif // GMOCK_HAS_REGEX
2136
2137#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2138// Wide string matchers.
2139
2140// Matches a string equal to str.
2141inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2142 StrEq(const internal::wstring& str) {
2143 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2144 str, true, true));
2145}
2146
2147// Matches a string not equal to str.
2148inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2149 StrNe(const internal::wstring& str) {
2150 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2151 str, false, true));
2152}
2153
2154// Matches a string equal to str, ignoring case.
2155inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2156 StrCaseEq(const internal::wstring& str) {
2157 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2158 str, true, false));
2159}
2160
2161// Matches a string not equal to str, ignoring case.
2162inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2163 StrCaseNe(const internal::wstring& str) {
2164 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2165 str, false, false));
2166}
2167
2168// Creates a matcher that matches any wstring, std::wstring, or C wide string
2169// that contains the given substring.
2170inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2171 HasSubstr(const internal::wstring& substring) {
2172 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2173 substring));
2174}
2175
2176// Matches a string that starts with 'prefix' (case-sensitive).
2177inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2178 StartsWith(const internal::wstring& prefix) {
2179 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2180 prefix));
2181}
2182
2183// Matches a string that ends with 'suffix' (case-sensitive).
2184inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2185 EndsWith(const internal::wstring& suffix) {
2186 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2187 suffix));
2188}
2189
2190#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2191
2192// Creates a polymorphic matcher that matches a 2-tuple where the
2193// first field == the second field.
2194inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2195
2196// Creates a polymorphic matcher that matches a 2-tuple where the
2197// first field >= the second field.
2198inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2199
2200// Creates a polymorphic matcher that matches a 2-tuple where the
2201// first field > the second field.
2202inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2203
2204// Creates a polymorphic matcher that matches a 2-tuple where the
2205// first field <= the second field.
2206inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2207
2208// Creates a polymorphic matcher that matches a 2-tuple where the
2209// first field < the second field.
2210inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2211
2212// Creates a polymorphic matcher that matches a 2-tuple where the
2213// first field != the second field.
2214inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2215
2216// Creates a matcher that matches any value of type T that m doesn't
2217// match.
2218template <typename InnerMatcher>
2219inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2220 return internal::NotMatcher<InnerMatcher>(m);
2221}
2222
2223// Creates a matcher that matches any value that matches all of the
2224// given matchers.
2225//
2226// For now we only support up to 5 matchers. Support for more
2227// matchers can be added as needed, or the user can use nested
2228// AllOf()s.
2229template <typename Matcher1, typename Matcher2>
2230inline internal::BothOfMatcher<Matcher1, Matcher2>
2231AllOf(Matcher1 m1, Matcher2 m2) {
2232 return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2);
2233}
2234
2235template <typename Matcher1, typename Matcher2, typename Matcher3>
2236inline internal::BothOfMatcher<Matcher1,
2237 internal::BothOfMatcher<Matcher2, Matcher3> >
2238AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2239 return AllOf(m1, AllOf(m2, m3));
2240}
2241
2242template <typename Matcher1, typename Matcher2, typename Matcher3,
2243 typename Matcher4>
2244inline internal::BothOfMatcher<Matcher1,
2245 internal::BothOfMatcher<Matcher2,
2246 internal::BothOfMatcher<Matcher3, Matcher4> > >
2247AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2248 return AllOf(m1, AllOf(m2, m3, m4));
2249}
2250
2251template <typename Matcher1, typename Matcher2, typename Matcher3,
2252 typename Matcher4, typename Matcher5>
2253inline internal::BothOfMatcher<Matcher1,
2254 internal::BothOfMatcher<Matcher2,
2255 internal::BothOfMatcher<Matcher3,
2256 internal::BothOfMatcher<Matcher4, Matcher5> > > >
2257AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2258 return AllOf(m1, AllOf(m2, m3, m4, m5));
2259}
2260
2261// Creates a matcher that matches any value that matches at least one
2262// of the given matchers.
2263//
2264// For now we only support up to 5 matchers. Support for more
2265// matchers can be added as needed, or the user can use nested
2266// AnyOf()s.
2267template <typename Matcher1, typename Matcher2>
2268inline internal::EitherOfMatcher<Matcher1, Matcher2>
2269AnyOf(Matcher1 m1, Matcher2 m2) {
2270 return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2);
2271}
2272
2273template <typename Matcher1, typename Matcher2, typename Matcher3>
2274inline internal::EitherOfMatcher<Matcher1,
2275 internal::EitherOfMatcher<Matcher2, Matcher3> >
2276AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2277 return AnyOf(m1, AnyOf(m2, m3));
2278}
2279
2280template <typename Matcher1, typename Matcher2, typename Matcher3,
2281 typename Matcher4>
2282inline internal::EitherOfMatcher<Matcher1,
2283 internal::EitherOfMatcher<Matcher2,
2284 internal::EitherOfMatcher<Matcher3, Matcher4> > >
2285AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2286 return AnyOf(m1, AnyOf(m2, m3, m4));
2287}
2288
2289template <typename Matcher1, typename Matcher2, typename Matcher3,
2290 typename Matcher4, typename Matcher5>
2291inline internal::EitherOfMatcher<Matcher1,
2292 internal::EitherOfMatcher<Matcher2,
2293 internal::EitherOfMatcher<Matcher3,
2294 internal::EitherOfMatcher<Matcher4, Matcher5> > > >
2295AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2296 return AnyOf(m1, AnyOf(m2, m3, m4, m5));
2297}
2298
2299// Returns a matcher that matches anything that satisfies the given
2300// predicate. The predicate can be any unary function or functor
2301// whose return type can be implicitly converted to bool.
2302template <typename Predicate>
2303inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
2304Truly(Predicate pred) {
2305 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
2306}
2307
zhanyong.wan6a896b52009-01-16 01:13:50 +00002308// Returns a matcher that matches an equal container.
2309// This matcher behaves like Eq(), but in the event of mismatch lists the
2310// values that are included in one container but not the other. (Duplicate
2311// values and order differences are not explained.)
2312template <typename Container>
zhanyong.wanb8243162009-06-04 05:48:20 +00002313inline PolymorphicMatcher<internal::ContainerEqMatcher<
2314 GMOCK_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00002315 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002316 // This following line is for working around a bug in MSVC 8.0,
2317 // which causes Container to be a const type sometimes.
2318 typedef GMOCK_REMOVE_CONST_(Container) RawContainer;
2319 return MakePolymorphicMatcher(internal::ContainerEqMatcher<RawContainer>(rhs));
2320}
2321
2322// Matches an STL-style container or a native array that contains at
2323// least one element matching the given value or matcher.
2324//
2325// Examples:
2326// ::std::set<int> page_ids;
2327// page_ids.insert(3);
2328// page_ids.insert(1);
2329// EXPECT_THAT(page_ids, Contains(1));
2330// EXPECT_THAT(page_ids, Contains(Gt(2)));
2331// EXPECT_THAT(page_ids, Not(Contains(4)));
2332//
2333// ::std::map<int, size_t> page_lengths;
2334// page_lengths[1] = 100;
2335// EXPECT_THAT(map_int, Contains(::std::pair<const int, size_t>(1, 100)));
2336//
2337// const char* user_ids[] = { "joe", "mike", "tom" };
2338// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
2339template <typename M>
2340inline internal::ContainsMatcher<M> Contains(M matcher) {
2341 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002342}
2343
shiqiane35fdd92008-12-10 05:08:54 +00002344// Returns a predicate that is satisfied by anything that matches the
2345// given matcher.
2346template <typename M>
2347inline internal::MatcherAsPredicate<M> Matches(M matcher) {
2348 return internal::MatcherAsPredicate<M>(matcher);
2349}
2350
zhanyong.wanb8243162009-06-04 05:48:20 +00002351// Returns true iff the value matches the matcher.
2352template <typename T, typename M>
2353inline bool Value(const T& value, M matcher) {
2354 return testing::Matches(matcher)(value);
2355}
2356
shiqiane35fdd92008-12-10 05:08:54 +00002357// These macros allow using matchers to check values in Google Test
2358// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
2359// succeed iff the value matches the matcher. If the assertion fails,
2360// the value and the description of the matcher will be printed.
2361#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
2362 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2363#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
2364 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2365
2366} // namespace testing
2367
2368#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_