blob: 66efecd4eb43a87ef9275f624badaa5544756150 [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
zhanyong.wan82113312010-01-08 21:55:40 +000067// MatchResultListener is an abstract class. Its << operator can be
68// used by a matcher to explain why a value matches or doesn't match.
69//
70// TODO(wan@google.com): add method
71// bool InterestedInWhy(bool result) const;
72// to indicate whether the listener is interested in why the match
73// result is 'result'.
74class MatchResultListener {
75 public:
76 // Creates a listener object with the given underlying ostream. The
77 // listener does not own the ostream.
78 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
79 virtual ~MatchResultListener() = 0; // Makes this class abstract.
80
81 // Streams x to the underlying ostream; does nothing if the ostream
82 // is NULL.
83 template <typename T>
84 MatchResultListener& operator<<(const T& x) {
85 if (stream_ != NULL)
86 *stream_ << x;
87 return *this;
88 }
89
90 // Returns the underlying ostream.
91 ::std::ostream* stream() { return stream_; }
92
zhanyong.wana862f1d2010-03-15 21:23:04 +000093 // Returns true iff the listener is interested in an explanation of
94 // the match result. A matcher's MatchAndExplain() method can use
95 // this information to avoid generating the explanation when no one
96 // intends to hear it.
97 bool IsInterested() const { return stream_ != NULL; }
98
zhanyong.wan82113312010-01-08 21:55:40 +000099 private:
100 ::std::ostream* const stream_;
101
102 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
103};
104
105inline MatchResultListener::~MatchResultListener() {
106}
107
shiqiane35fdd92008-12-10 05:08:54 +0000108// The implementation of a matcher.
109template <typename T>
110class MatcherInterface {
111 public:
112 virtual ~MatcherInterface() {}
113
zhanyong.wan82113312010-01-08 21:55:40 +0000114 // Returns true iff the matcher matches x; also explains the match
zhanyong.wana862f1d2010-03-15 21:23:04 +0000115 // result to 'listener', in the form of a non-restrictive relative
116 // clause ("which ...", "whose ...", etc) that describes x. For
117 // example, the MatchAndExplain() method of the Pointee(...) matcher
118 // should generate an explanation like "which points to ...".
zhanyong.wan82113312010-01-08 21:55:40 +0000119 //
zhanyong.wandb22c222010-01-28 21:52:29 +0000120 // You should override this method when defining a new matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000121 //
122 // It's the responsibility of the caller (Google Mock) to guarantee
123 // that 'listener' is not NULL. This helps to simplify a matcher's
124 // implementation when it doesn't care about the performance, as it
125 // can talk to 'listener' without checking its validity first.
126 // However, in order to implement dummy listeners efficiently,
127 // listener->stream() may be NULL.
zhanyong.wandb22c222010-01-28 21:52:29 +0000128 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
shiqiane35fdd92008-12-10 05:08:54 +0000129
zhanyong.wana862f1d2010-03-15 21:23:04 +0000130 // Describes this matcher to an ostream. The function should print
131 // a verb phrase that describes the property a value matching this
132 // matcher should have. The subject of the verb phrase is the value
133 // being matched. For example, the DescribeTo() method of the Gt(7)
134 // matcher prints "is greater than 7".
shiqiane35fdd92008-12-10 05:08:54 +0000135 virtual void DescribeTo(::std::ostream* os) const = 0;
136
137 // Describes the negation of this matcher to an ostream. For
138 // example, if the description of this matcher is "is greater than
139 // 7", the negated description could be "is not greater than 7".
140 // You are not required to override this when implementing
141 // MatcherInterface, but it is highly advised so that your matcher
142 // can produce good error messages.
143 virtual void DescribeNegationTo(::std::ostream* os) const {
144 *os << "not (";
145 DescribeTo(os);
146 *os << ")";
147 }
shiqiane35fdd92008-12-10 05:08:54 +0000148};
149
150namespace internal {
151
zhanyong.wan82113312010-01-08 21:55:40 +0000152// A match result listener that ignores the explanation.
153class DummyMatchResultListener : public MatchResultListener {
154 public:
155 DummyMatchResultListener() : MatchResultListener(NULL) {}
156
157 private:
158 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
159};
160
161// A match result listener that forwards the explanation to a given
162// ostream. The difference between this and MatchResultListener is
163// that the former is concrete.
164class StreamMatchResultListener : public MatchResultListener {
165 public:
166 explicit StreamMatchResultListener(::std::ostream* os)
167 : MatchResultListener(os) {}
168
169 private:
170 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
171};
172
173// A match result listener that stores the explanation in a string.
174class StringMatchResultListener : public MatchResultListener {
175 public:
176 StringMatchResultListener() : MatchResultListener(&ss_) {}
177
178 // Returns the explanation heard so far.
179 internal::string str() const { return ss_.str(); }
180
181 private:
182 ::std::stringstream ss_;
183
184 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
185};
186
shiqiane35fdd92008-12-10 05:08:54 +0000187// An internal class for implementing Matcher<T>, which will derive
188// from it. We put functionalities common to all Matcher<T>
189// specializations here to avoid code duplication.
190template <typename T>
191class MatcherBase {
192 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000193 // Returns true iff the matcher matches x; also explains the match
194 // result to 'listener'.
195 bool MatchAndExplain(T x, MatchResultListener* listener) const {
196 return impl_->MatchAndExplain(x, listener);
197 }
198
shiqiane35fdd92008-12-10 05:08:54 +0000199 // Returns true iff this matcher matches x.
zhanyong.wan82113312010-01-08 21:55:40 +0000200 bool Matches(T x) const {
201 DummyMatchResultListener dummy;
202 return MatchAndExplain(x, &dummy);
203 }
shiqiane35fdd92008-12-10 05:08:54 +0000204
205 // Describes this matcher to an ostream.
206 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
207
208 // Describes the negation of this matcher to an ostream.
209 void DescribeNegationTo(::std::ostream* os) const {
210 impl_->DescribeNegationTo(os);
211 }
212
213 // Explains why x matches, or doesn't match, the matcher.
214 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000215 StreamMatchResultListener listener(os);
216 MatchAndExplain(x, &listener);
shiqiane35fdd92008-12-10 05:08:54 +0000217 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000218
shiqiane35fdd92008-12-10 05:08:54 +0000219 protected:
220 MatcherBase() {}
221
222 // Constructs a matcher from its implementation.
223 explicit MatcherBase(const MatcherInterface<T>* impl)
224 : impl_(impl) {}
225
226 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000227
shiqiane35fdd92008-12-10 05:08:54 +0000228 private:
229 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
230 // interfaces. The former dynamically allocates a chunk of memory
231 // to hold the reference count, while the latter tracks all
232 // references using a circular linked list without allocating
233 // memory. It has been observed that linked_ptr performs better in
234 // typical scenarios. However, shared_ptr can out-perform
235 // linked_ptr when there are many more uses of the copy constructor
236 // than the default constructor.
237 //
238 // If performance becomes a problem, we should see if using
239 // shared_ptr helps.
240 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
241};
242
shiqiane35fdd92008-12-10 05:08:54 +0000243} // namespace internal
244
245// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
246// object that can check whether a value of type T matches. The
247// implementation of Matcher<T> is just a linked_ptr to const
248// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
249// from Matcher!
250template <typename T>
251class Matcher : public internal::MatcherBase<T> {
252 public:
253 // Constructs a null matcher. Needed for storing Matcher objects in
254 // STL containers.
255 Matcher() {}
256
257 // Constructs a matcher from its implementation.
258 explicit Matcher(const MatcherInterface<T>* impl)
259 : internal::MatcherBase<T>(impl) {}
260
zhanyong.wan18490652009-05-11 18:54:08 +0000261 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000262 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
263 Matcher(T value); // NOLINT
264};
265
266// The following two specializations allow the user to write str
267// instead of Eq(str) and "foo" instead of Eq("foo") when a string
268// matcher is expected.
269template <>
270class Matcher<const internal::string&>
271 : public internal::MatcherBase<const internal::string&> {
272 public:
273 Matcher() {}
274
275 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
276 : internal::MatcherBase<const internal::string&>(impl) {}
277
278 // Allows the user to write str instead of Eq(str) sometimes, where
279 // str is a string object.
280 Matcher(const internal::string& s); // NOLINT
281
282 // Allows the user to write "foo" instead of Eq("foo") sometimes.
283 Matcher(const char* s); // NOLINT
284};
285
286template <>
287class Matcher<internal::string>
288 : public internal::MatcherBase<internal::string> {
289 public:
290 Matcher() {}
291
292 explicit Matcher(const MatcherInterface<internal::string>* impl)
293 : internal::MatcherBase<internal::string>(impl) {}
294
295 // Allows the user to write str instead of Eq(str) sometimes, where
296 // str is a string object.
297 Matcher(const internal::string& s); // NOLINT
298
299 // Allows the user to write "foo" instead of Eq("foo") sometimes.
300 Matcher(const char* s); // NOLINT
301};
302
303// The PolymorphicMatcher class template makes it easy to implement a
304// polymorphic matcher (i.e. a matcher that can match values of more
305// than one type, e.g. Eq(n) and NotNull()).
306//
zhanyong.wandb22c222010-01-28 21:52:29 +0000307// To define a polymorphic matcher, a user should provide an Impl
308// class that has a DescribeTo() method and a DescribeNegationTo()
309// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000310//
zhanyong.wandb22c222010-01-28 21:52:29 +0000311// bool MatchAndExplain(const Value& value,
312// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000313//
314// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000315template <class Impl>
316class PolymorphicMatcher {
317 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000318 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000319
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000320 // Returns a mutable reference to the underlying matcher
321 // implementation object.
322 Impl& mutable_impl() { return impl_; }
323
324 // Returns an immutable reference to the underlying matcher
325 // implementation object.
326 const Impl& impl() const { return impl_; }
327
shiqiane35fdd92008-12-10 05:08:54 +0000328 template <typename T>
329 operator Matcher<T>() const {
330 return Matcher<T>(new MonomorphicImpl<T>(impl_));
331 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000332
shiqiane35fdd92008-12-10 05:08:54 +0000333 private:
334 template <typename T>
335 class MonomorphicImpl : public MatcherInterface<T> {
336 public:
337 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
338
shiqiane35fdd92008-12-10 05:08:54 +0000339 virtual void DescribeTo(::std::ostream* os) const {
340 impl_.DescribeTo(os);
341 }
342
343 virtual void DescribeNegationTo(::std::ostream* os) const {
344 impl_.DescribeNegationTo(os);
345 }
346
zhanyong.wan82113312010-01-08 21:55:40 +0000347 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000348 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000349 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000350
shiqiane35fdd92008-12-10 05:08:54 +0000351 private:
352 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000353
354 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000355 };
356
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000357 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000358
359 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000360};
361
362// Creates a matcher from its implementation. This is easier to use
363// than the Matcher<T> constructor as it doesn't require you to
364// explicitly write the template argument, e.g.
365//
366// MakeMatcher(foo);
367// vs
368// Matcher<const string&>(foo);
369template <typename T>
370inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
371 return Matcher<T>(impl);
372};
373
374// Creates a polymorphic matcher from its implementation. This is
375// easier to use than the PolymorphicMatcher<Impl> constructor as it
376// doesn't require you to explicitly write the template argument, e.g.
377//
378// MakePolymorphicMatcher(foo);
379// vs
380// PolymorphicMatcher<TypeOfFoo>(foo);
381template <class Impl>
382inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
383 return PolymorphicMatcher<Impl>(impl);
384}
385
386// In order to be safe and clear, casting between different matcher
387// types is done explicitly via MatcherCast<T>(m), which takes a
388// matcher m and returns a Matcher<T>. It compiles only when T can be
389// statically converted to the argument type of m.
390template <typename T, typename M>
391Matcher<T> MatcherCast(M m);
392
zhanyong.wan18490652009-05-11 18:54:08 +0000393// Implements SafeMatcherCast().
394//
zhanyong.wan95b12332009-09-25 18:55:50 +0000395// We use an intermediate class to do the actual safe casting as Nokia's
396// Symbian compiler cannot decide between
397// template <T, M> ... (M) and
398// template <T, U> ... (const Matcher<U>&)
399// for function templates but can for member function templates.
400template <typename T>
401class SafeMatcherCastImpl {
402 public:
403 // This overload handles polymorphic matchers only since monomorphic
404 // matchers are handled by the next one.
405 template <typename M>
406 static inline Matcher<T> Cast(M polymorphic_matcher) {
407 return Matcher<T>(polymorphic_matcher);
408 }
zhanyong.wan18490652009-05-11 18:54:08 +0000409
zhanyong.wan95b12332009-09-25 18:55:50 +0000410 // This overload handles monomorphic matchers.
411 //
412 // In general, if type T can be implicitly converted to type U, we can
413 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
414 // contravariant): just keep a copy of the original Matcher<U>, convert the
415 // argument from type T to U, and then pass it to the underlying Matcher<U>.
416 // The only exception is when U is a reference and T is not, as the
417 // underlying Matcher<U> may be interested in the argument's address, which
418 // is not preserved in the conversion from T to U.
419 template <typename U>
420 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
421 // Enforce that T can be implicitly converted to U.
422 GMOCK_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
423 T_must_be_implicitly_convertible_to_U);
424 // Enforce that we are not converting a non-reference type T to a reference
425 // type U.
426 GMOCK_COMPILE_ASSERT_(
427 internal::is_reference<T>::value || !internal::is_reference<U>::value,
428 cannot_convert_non_referentce_arg_to_reference);
429 // In case both T and U are arithmetic types, enforce that the
430 // conversion is not lossy.
431 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(T)) RawT;
432 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(U)) RawU;
433 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
434 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
435 GMOCK_COMPILE_ASSERT_(
436 kTIsOther || kUIsOther ||
437 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
438 conversion_of_arithmetic_types_must_be_lossless);
439 return MatcherCast<T>(matcher);
440 }
441};
442
443template <typename T, typename M>
444inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
445 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000446}
447
shiqiane35fdd92008-12-10 05:08:54 +0000448// A<T>() returns a matcher that matches any value of type T.
449template <typename T>
450Matcher<T> A();
451
452// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
453// and MUST NOT BE USED IN USER CODE!!!
454namespace internal {
455
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000456// If the explanation is not empty, prints it to the ostream.
457inline void PrintIfNotEmpty(const internal::string& explanation,
458 std::ostream* os) {
459 if (explanation != "" && os != NULL) {
460 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000461 }
462}
463
464// Matches the value against the given matcher, prints the value and explains
465// the match result to the listener. Returns the match result.
466// 'listener' must not be NULL.
467// Value cannot be passed by const reference, because some matchers take a
468// non-const argument.
469template <typename Value, typename T>
470bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
471 MatchResultListener* listener) {
472 if (!listener->IsInterested()) {
473 // If the listener is not interested, we do not need to construct the
474 // inner explanation.
475 return matcher.Matches(value);
476 }
477
478 StringMatchResultListener inner_listener;
479 const bool match = matcher.MatchAndExplain(value, &inner_listener);
480
481 UniversalPrint(value, listener->stream());
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000482 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000483
484 return match;
485}
486
shiqiane35fdd92008-12-10 05:08:54 +0000487// An internal helper class for doing compile-time loop on a tuple's
488// fields.
489template <size_t N>
490class TuplePrefix {
491 public:
492 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
493 // iff the first N fields of matcher_tuple matches the first N
494 // fields of value_tuple, respectively.
495 template <typename MatcherTuple, typename ValueTuple>
496 static bool Matches(const MatcherTuple& matcher_tuple,
497 const ValueTuple& value_tuple) {
498 using ::std::tr1::get;
499 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
500 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
501 }
502
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000503 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000504 // describes failures in matching the first N fields of matchers
505 // against the first N fields of values. If there is no failure,
506 // nothing will be streamed to os.
507 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000508 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
509 const ValueTuple& values,
510 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000511 using ::std::tr1::tuple_element;
512 using ::std::tr1::get;
513
514 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000515 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000516
517 // Then describes the failure (if any) in the (N - 1)-th (0-based)
518 // field.
519 typename tuple_element<N - 1, MatcherTuple>::type matcher =
520 get<N - 1>(matchers);
521 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
522 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000523 StringMatchResultListener listener;
524 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000525 // TODO(wan): include in the message the name of the parameter
526 // as used in MOCK_METHOD*() when possible.
527 *os << " Expected arg #" << N - 1 << ": ";
528 get<N - 1>(matchers).DescribeTo(os);
529 *os << "\n Actual: ";
530 // We remove the reference in type Value to prevent the
531 // universal printer from printing the address of value, which
532 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000533 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000534 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000535 internal::UniversalPrint(value, os);
536 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000537 *os << "\n";
538 }
539 }
540};
541
542// The base case.
543template <>
544class TuplePrefix<0> {
545 public:
546 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000547 static bool Matches(const MatcherTuple& /* matcher_tuple */,
548 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000549 return true;
550 }
551
552 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000553 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
554 const ValueTuple& /* values */,
555 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000556};
557
558// TupleMatches(matcher_tuple, value_tuple) returns true iff all
559// matchers in matcher_tuple match the corresponding fields in
560// value_tuple. It is a compiler error if matcher_tuple and
561// value_tuple have different number of fields or incompatible field
562// types.
563template <typename MatcherTuple, typename ValueTuple>
564bool TupleMatches(const MatcherTuple& matcher_tuple,
565 const ValueTuple& value_tuple) {
566 using ::std::tr1::tuple_size;
567 // Makes sure that matcher_tuple and value_tuple have the same
568 // number of fields.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000569 GMOCK_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
570 tuple_size<ValueTuple>::value,
571 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000572 return TuplePrefix<tuple_size<ValueTuple>::value>::
573 Matches(matcher_tuple, value_tuple);
574}
575
576// Describes failures in matching matchers against values. If there
577// is no failure, nothing will be streamed to os.
578template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000579void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
580 const ValueTuple& values,
581 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000582 using ::std::tr1::tuple_size;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000583 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000584 matchers, values, os);
585}
586
587// The MatcherCastImpl class template is a helper for implementing
588// MatcherCast(). We need this helper in order to partially
589// specialize the implementation of MatcherCast() (C++ allows
590// class/struct templates to be partially specialized, but not
591// function templates.).
592
593// This general version is used when MatcherCast()'s argument is a
594// polymorphic matcher (i.e. something that can be converted to a
595// Matcher but is not one yet; for example, Eq(value)).
596template <typename T, typename M>
597class MatcherCastImpl {
598 public:
599 static Matcher<T> Cast(M polymorphic_matcher) {
600 return Matcher<T>(polymorphic_matcher);
601 }
602};
603
604// This more specialized version is used when MatcherCast()'s argument
605// is already a Matcher. This only compiles when type T can be
606// statically converted to type U.
607template <typename T, typename U>
608class MatcherCastImpl<T, Matcher<U> > {
609 public:
610 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
611 return Matcher<T>(new Impl(source_matcher));
612 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000613
shiqiane35fdd92008-12-10 05:08:54 +0000614 private:
615 class Impl : public MatcherInterface<T> {
616 public:
617 explicit Impl(const Matcher<U>& source_matcher)
618 : source_matcher_(source_matcher) {}
619
620 // We delegate the matching logic to the source matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000621 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
622 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000623 }
624
625 virtual void DescribeTo(::std::ostream* os) const {
626 source_matcher_.DescribeTo(os);
627 }
628
629 virtual void DescribeNegationTo(::std::ostream* os) const {
630 source_matcher_.DescribeNegationTo(os);
631 }
632
shiqiane35fdd92008-12-10 05:08:54 +0000633 private:
634 const Matcher<U> source_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000635
636 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000637 };
638};
639
640// This even more specialized version is used for efficiently casting
641// a matcher to its own type.
642template <typename T>
643class MatcherCastImpl<T, Matcher<T> > {
644 public:
645 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
646};
647
648// Implements A<T>().
649template <typename T>
650class AnyMatcherImpl : public MatcherInterface<T> {
651 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000652 virtual bool MatchAndExplain(
653 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000654 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
655 virtual void DescribeNegationTo(::std::ostream* os) const {
656 // This is mostly for completeness' safe, as it's not very useful
657 // to write Not(A<bool>()). However we cannot completely rule out
658 // such a possibility, and it doesn't hurt to be prepared.
659 *os << "never matches";
660 }
661};
662
663// Implements _, a matcher that matches any value of any
664// type. This is a polymorphic matcher, so we need a template type
665// conversion operator to make it appearing as a Matcher<T> for any
666// type T.
667class AnythingMatcher {
668 public:
669 template <typename T>
670 operator Matcher<T>() const { return A<T>(); }
671};
672
673// Implements a matcher that compares a given value with a
674// pre-supplied value using one of the ==, <=, <, etc, operators. The
675// two values being compared don't have to have the same type.
676//
677// The matcher defined here is polymorphic (for example, Eq(5) can be
678// used to match an int, a short, a double, etc). Therefore we use
679// a template type conversion operator in the implementation.
680//
681// We define this as a macro in order to eliminate duplicated source
682// code.
683//
684// The following template definition assumes that the Rhs parameter is
685// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000686#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_( \
687 name, op, relation, negated_relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000688 template <typename Rhs> class name##Matcher { \
689 public: \
690 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
691 template <typename Lhs> \
692 operator Matcher<Lhs>() const { \
693 return MakeMatcher(new Impl<Lhs>(rhs_)); \
694 } \
695 private: \
696 template <typename Lhs> \
697 class Impl : public MatcherInterface<Lhs> { \
698 public: \
699 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
zhanyong.wan82113312010-01-08 21:55:40 +0000700 virtual bool MatchAndExplain(\
701 Lhs lhs, MatchResultListener* /* listener */) const { \
702 return lhs op rhs_; \
703 } \
shiqiane35fdd92008-12-10 05:08:54 +0000704 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000705 *os << relation " "; \
shiqiane35fdd92008-12-10 05:08:54 +0000706 UniversalPrinter<Rhs>::Print(rhs_, os); \
707 } \
708 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000709 *os << negated_relation " "; \
shiqiane35fdd92008-12-10 05:08:54 +0000710 UniversalPrinter<Rhs>::Print(rhs_, os); \
711 } \
712 private: \
713 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000714 GTEST_DISALLOW_ASSIGN_(Impl); \
shiqiane35fdd92008-12-10 05:08:54 +0000715 }; \
716 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000717 GTEST_DISALLOW_ASSIGN_(name##Matcher); \
shiqiane35fdd92008-12-10 05:08:54 +0000718 }
719
720// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
721// respectively.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000722GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "is equal to", "isn't equal to");
723GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "is >=", "isn't >=");
724GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "is >", "isn't >");
725GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "is <=", "isn't <=");
726GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "is <", "isn't <");
727GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "isn't equal to", "is equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000728
zhanyong.wane0d051e2009-02-19 00:33:37 +0000729#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000730
vladlosev79b83502009-11-18 00:43:37 +0000731// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000732// pointer that is NULL.
733class IsNullMatcher {
734 public:
vladlosev79b83502009-11-18 00:43:37 +0000735 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000736 bool MatchAndExplain(const Pointer& p,
737 MatchResultListener* /* listener */) const {
738 return GetRawPointer(p) == NULL;
739 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000740
741 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
742 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000743 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000744 }
745};
746
vladlosev79b83502009-11-18 00:43:37 +0000747// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000748// pointer that is not NULL.
749class NotNullMatcher {
750 public:
vladlosev79b83502009-11-18 00:43:37 +0000751 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000752 bool MatchAndExplain(const Pointer& p,
753 MatchResultListener* /* listener */) const {
754 return GetRawPointer(p) != NULL;
755 }
shiqiane35fdd92008-12-10 05:08:54 +0000756
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000757 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +0000758 void DescribeNegationTo(::std::ostream* os) const {
759 *os << "is NULL";
760 }
761};
762
763// Ref(variable) matches any argument that is a reference to
764// 'variable'. This matcher is polymorphic as it can match any
765// super type of the type of 'variable'.
766//
767// The RefMatcher template class implements Ref(variable). It can
768// only be instantiated with a reference type. This prevents a user
769// from mistakenly using Ref(x) to match a non-reference function
770// argument. For example, the following will righteously cause a
771// compiler error:
772//
773// int n;
774// Matcher<int> m1 = Ref(n); // This won't compile.
775// Matcher<int&> m2 = Ref(n); // This will compile.
776template <typename T>
777class RefMatcher;
778
779template <typename T>
780class RefMatcher<T&> {
781 // Google Mock is a generic framework and thus needs to support
782 // mocking any function types, including those that take non-const
783 // reference arguments. Therefore the template parameter T (and
784 // Super below) can be instantiated to either a const type or a
785 // non-const type.
786 public:
787 // RefMatcher() takes a T& instead of const T&, as we want the
788 // compiler to catch using Ref(const_value) as a matcher for a
789 // non-const reference.
790 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
791
792 template <typename Super>
793 operator Matcher<Super&>() const {
794 // By passing object_ (type T&) to Impl(), which expects a Super&,
795 // we make sure that Super is a super type of T. In particular,
796 // this catches using Ref(const_value) as a matcher for a
797 // non-const reference, as you cannot implicitly convert a const
798 // reference to a non-const reference.
799 return MakeMatcher(new Impl<Super>(object_));
800 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000801
shiqiane35fdd92008-12-10 05:08:54 +0000802 private:
803 template <typename Super>
804 class Impl : public MatcherInterface<Super&> {
805 public:
806 explicit Impl(Super& x) : object_(x) {} // NOLINT
807
zhanyong.wandb22c222010-01-28 21:52:29 +0000808 // MatchAndExplain() takes a Super& (as opposed to const Super&)
809 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +0000810 virtual bool MatchAndExplain(
811 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000812 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +0000813 return &x == &object_;
814 }
shiqiane35fdd92008-12-10 05:08:54 +0000815
816 virtual void DescribeTo(::std::ostream* os) const {
817 *os << "references the variable ";
818 UniversalPrinter<Super&>::Print(object_, os);
819 }
820
821 virtual void DescribeNegationTo(::std::ostream* os) const {
822 *os << "does not reference the variable ";
823 UniversalPrinter<Super&>::Print(object_, os);
824 }
825
shiqiane35fdd92008-12-10 05:08:54 +0000826 private:
827 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000828
829 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000830 };
831
832 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000833
834 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000835};
836
837// Polymorphic helper functions for narrow and wide string matchers.
838inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
839 return String::CaseInsensitiveCStringEquals(lhs, rhs);
840}
841
842inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
843 const wchar_t* rhs) {
844 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
845}
846
847// String comparison for narrow or wide strings that can have embedded NUL
848// characters.
849template <typename StringType>
850bool CaseInsensitiveStringEquals(const StringType& s1,
851 const StringType& s2) {
852 // Are the heads equal?
853 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
854 return false;
855 }
856
857 // Skip the equal heads.
858 const typename StringType::value_type nul = 0;
859 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
860
861 // Are we at the end of either s1 or s2?
862 if (i1 == StringType::npos || i2 == StringType::npos) {
863 return i1 == i2;
864 }
865
866 // Are the tails equal?
867 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
868}
869
870// String matchers.
871
872// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
873template <typename StringType>
874class StrEqualityMatcher {
875 public:
876 typedef typename StringType::const_pointer ConstCharPointer;
877
878 StrEqualityMatcher(const StringType& str, bool expect_eq,
879 bool case_sensitive)
880 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
881
882 // When expect_eq_ is true, returns true iff s is equal to string_;
883 // otherwise returns true iff s is not equal to string_.
zhanyong.wandb22c222010-01-28 21:52:29 +0000884 bool MatchAndExplain(ConstCharPointer s,
885 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +0000886 if (s == NULL) {
887 return !expect_eq_;
888 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000889 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000890 }
891
zhanyong.wandb22c222010-01-28 21:52:29 +0000892 bool MatchAndExplain(const StringType& s,
893 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000894 const bool eq = case_sensitive_ ? s == string_ :
895 CaseInsensitiveStringEquals(s, string_);
896 return expect_eq_ == eq;
897 }
898
899 void DescribeTo(::std::ostream* os) const {
900 DescribeToHelper(expect_eq_, os);
901 }
902
903 void DescribeNegationTo(::std::ostream* os) const {
904 DescribeToHelper(!expect_eq_, os);
905 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000906
shiqiane35fdd92008-12-10 05:08:54 +0000907 private:
908 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000909 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +0000910 *os << "equal to ";
911 if (!case_sensitive_) {
912 *os << "(ignoring case) ";
913 }
914 UniversalPrinter<StringType>::Print(string_, os);
915 }
916
917 const StringType string_;
918 const bool expect_eq_;
919 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000920
921 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000922};
923
924// Implements the polymorphic HasSubstr(substring) matcher, which
925// can be used as a Matcher<T> as long as T can be converted to a
926// string.
927template <typename StringType>
928class HasSubstrMatcher {
929 public:
930 typedef typename StringType::const_pointer ConstCharPointer;
931
932 explicit HasSubstrMatcher(const StringType& substring)
933 : substring_(substring) {}
934
935 // These overloaded methods allow HasSubstr(substring) to be used as a
936 // Matcher<T> as long as T can be converted to string. Returns true
937 // iff s contains substring_ as a substring.
zhanyong.wandb22c222010-01-28 21:52:29 +0000938 bool MatchAndExplain(ConstCharPointer s,
939 MatchResultListener* listener) const {
940 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000941 }
942
zhanyong.wandb22c222010-01-28 21:52:29 +0000943 bool MatchAndExplain(const StringType& s,
944 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000945 return s.find(substring_) != StringType::npos;
946 }
947
948 // Describes what this matcher matches.
949 void DescribeTo(::std::ostream* os) const {
950 *os << "has substring ";
951 UniversalPrinter<StringType>::Print(substring_, os);
952 }
953
954 void DescribeNegationTo(::std::ostream* os) const {
955 *os << "has no substring ";
956 UniversalPrinter<StringType>::Print(substring_, os);
957 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000958
shiqiane35fdd92008-12-10 05:08:54 +0000959 private:
960 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000961
962 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000963};
964
965// Implements the polymorphic StartsWith(substring) matcher, which
966// can be used as a Matcher<T> as long as T can be converted to a
967// string.
968template <typename StringType>
969class StartsWithMatcher {
970 public:
971 typedef typename StringType::const_pointer ConstCharPointer;
972
973 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
974 }
975
976 // These overloaded methods allow StartsWith(prefix) to be used as a
977 // Matcher<T> as long as T can be converted to string. Returns true
978 // iff s starts with prefix_.
zhanyong.wandb22c222010-01-28 21:52:29 +0000979 bool MatchAndExplain(ConstCharPointer s,
980 MatchResultListener* listener) const {
981 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000982 }
983
zhanyong.wandb22c222010-01-28 21:52:29 +0000984 bool MatchAndExplain(const StringType& s,
985 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000986 return s.length() >= prefix_.length() &&
987 s.substr(0, prefix_.length()) == prefix_;
988 }
989
990 void DescribeTo(::std::ostream* os) const {
991 *os << "starts with ";
992 UniversalPrinter<StringType>::Print(prefix_, os);
993 }
994
995 void DescribeNegationTo(::std::ostream* os) const {
996 *os << "doesn't start with ";
997 UniversalPrinter<StringType>::Print(prefix_, os);
998 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000999
shiqiane35fdd92008-12-10 05:08:54 +00001000 private:
1001 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001002
1003 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001004};
1005
1006// Implements the polymorphic EndsWith(substring) matcher, which
1007// can be used as a Matcher<T> as long as T can be converted to a
1008// string.
1009template <typename StringType>
1010class EndsWithMatcher {
1011 public:
1012 typedef typename StringType::const_pointer ConstCharPointer;
1013
1014 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1015
1016 // These overloaded methods allow EndsWith(suffix) to be used as a
1017 // Matcher<T> as long as T can be converted to string. Returns true
1018 // iff s ends with suffix_.
zhanyong.wandb22c222010-01-28 21:52:29 +00001019 bool MatchAndExplain(ConstCharPointer s,
1020 MatchResultListener* listener) const {
1021 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001022 }
1023
zhanyong.wandb22c222010-01-28 21:52:29 +00001024 bool MatchAndExplain(const StringType& s,
1025 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001026 return s.length() >= suffix_.length() &&
1027 s.substr(s.length() - suffix_.length()) == suffix_;
1028 }
1029
1030 void DescribeTo(::std::ostream* os) const {
1031 *os << "ends with ";
1032 UniversalPrinter<StringType>::Print(suffix_, os);
1033 }
1034
1035 void DescribeNegationTo(::std::ostream* os) const {
1036 *os << "doesn't end with ";
1037 UniversalPrinter<StringType>::Print(suffix_, os);
1038 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001039
shiqiane35fdd92008-12-10 05:08:54 +00001040 private:
1041 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001042
1043 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001044};
1045
shiqiane35fdd92008-12-10 05:08:54 +00001046// Implements polymorphic matchers MatchesRegex(regex) and
1047// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1048// T can be converted to a string.
1049class MatchesRegexMatcher {
1050 public:
1051 MatchesRegexMatcher(const RE* regex, bool full_match)
1052 : regex_(regex), full_match_(full_match) {}
1053
1054 // These overloaded methods allow MatchesRegex(regex) to be used as
1055 // a Matcher<T> as long as T can be converted to string. Returns
1056 // true iff s matches regular expression regex. When full_match_ is
1057 // true, a full match is done; otherwise a partial match is done.
zhanyong.wandb22c222010-01-28 21:52:29 +00001058 bool MatchAndExplain(const char* s,
1059 MatchResultListener* listener) const {
1060 return s != NULL && MatchAndExplain(internal::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001061 }
1062
zhanyong.wandb22c222010-01-28 21:52:29 +00001063 bool MatchAndExplain(const internal::string& s,
1064 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001065 return full_match_ ? RE::FullMatch(s, *regex_) :
1066 RE::PartialMatch(s, *regex_);
1067 }
1068
1069 void DescribeTo(::std::ostream* os) const {
1070 *os << (full_match_ ? "matches" : "contains")
1071 << " regular expression ";
1072 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1073 }
1074
1075 void DescribeNegationTo(::std::ostream* os) const {
1076 *os << "doesn't " << (full_match_ ? "match" : "contain")
1077 << " regular expression ";
1078 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1079 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001080
shiqiane35fdd92008-12-10 05:08:54 +00001081 private:
1082 const internal::linked_ptr<const RE> regex_;
1083 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001084
1085 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001086};
1087
shiqiane35fdd92008-12-10 05:08:54 +00001088// Implements a matcher that compares the two fields of a 2-tuple
1089// using one of the ==, <=, <, etc, operators. The two fields being
1090// compared don't have to have the same type.
1091//
1092// The matcher defined here is polymorphic (for example, Eq() can be
1093// used to match a tuple<int, short>, a tuple<const long&, double>,
1094// etc). Therefore we use a template type conversion operator in the
1095// implementation.
1096//
1097// We define this as a macro in order to eliminate duplicated source
1098// code.
zhanyong.wan2661c682009-06-09 05:42:12 +00001099#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op) \
shiqiane35fdd92008-12-10 05:08:54 +00001100 class name##2Matcher { \
1101 public: \
1102 template <typename T1, typename T2> \
1103 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
1104 return MakeMatcher(new Impl<T1, T2>); \
1105 } \
1106 private: \
1107 template <typename T1, typename T2> \
1108 class Impl : public MatcherInterface<const ::std::tr1::tuple<T1, T2>&> { \
1109 public: \
zhanyong.wan82113312010-01-08 21:55:40 +00001110 virtual bool MatchAndExplain( \
1111 const ::std::tr1::tuple<T1, T2>& args, \
1112 MatchResultListener* /* listener */) const { \
shiqiane35fdd92008-12-10 05:08:54 +00001113 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
1114 } \
1115 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +00001116 *os << "are a pair (x, y) where x " #op " y"; \
shiqiane35fdd92008-12-10 05:08:54 +00001117 } \
1118 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +00001119 *os << "are a pair (x, y) where x " #op " y is false"; \
shiqiane35fdd92008-12-10 05:08:54 +00001120 } \
1121 }; \
1122 }
1123
1124// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wan2661c682009-06-09 05:42:12 +00001125GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==);
1126GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ge, >=);
1127GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Gt, >);
1128GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Le, <=);
1129GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Lt, <);
1130GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=);
shiqiane35fdd92008-12-10 05:08:54 +00001131
zhanyong.wane0d051e2009-02-19 00:33:37 +00001132#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +00001133
zhanyong.wanc6a41232009-05-13 23:38:40 +00001134// Implements the Not(...) matcher for a particular argument type T.
1135// We do not nest it inside the NotMatcher class template, as that
1136// will prevent different instantiations of NotMatcher from sharing
1137// the same NotMatcherImpl<T> class.
1138template <typename T>
1139class NotMatcherImpl : public MatcherInterface<T> {
1140 public:
1141 explicit NotMatcherImpl(const Matcher<T>& matcher)
1142 : matcher_(matcher) {}
1143
zhanyong.wan82113312010-01-08 21:55:40 +00001144 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1145 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001146 }
1147
1148 virtual void DescribeTo(::std::ostream* os) const {
1149 matcher_.DescribeNegationTo(os);
1150 }
1151
1152 virtual void DescribeNegationTo(::std::ostream* os) const {
1153 matcher_.DescribeTo(os);
1154 }
1155
zhanyong.wanc6a41232009-05-13 23:38:40 +00001156 private:
1157 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001158
1159 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001160};
1161
shiqiane35fdd92008-12-10 05:08:54 +00001162// Implements the Not(m) matcher, which matches a value that doesn't
1163// match matcher m.
1164template <typename InnerMatcher>
1165class NotMatcher {
1166 public:
1167 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1168
1169 // This template type conversion operator allows Not(m) to be used
1170 // to match any type m can match.
1171 template <typename T>
1172 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001173 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001174 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001175
shiqiane35fdd92008-12-10 05:08:54 +00001176 private:
shiqiane35fdd92008-12-10 05:08:54 +00001177 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001178
1179 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001180};
1181
zhanyong.wanc6a41232009-05-13 23:38:40 +00001182// Implements the AllOf(m1, m2) matcher for a particular argument type
1183// T. We do not nest it inside the BothOfMatcher class template, as
1184// that will prevent different instantiations of BothOfMatcher from
1185// sharing the same BothOfMatcherImpl<T> class.
1186template <typename T>
1187class BothOfMatcherImpl : public MatcherInterface<T> {
1188 public:
1189 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1190 : matcher1_(matcher1), matcher2_(matcher2) {}
1191
zhanyong.wanc6a41232009-05-13 23:38:40 +00001192 virtual void DescribeTo(::std::ostream* os) const {
1193 *os << "(";
1194 matcher1_.DescribeTo(os);
1195 *os << ") and (";
1196 matcher2_.DescribeTo(os);
1197 *os << ")";
1198 }
1199
1200 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001201 *os << "(";
1202 matcher1_.DescribeNegationTo(os);
1203 *os << ") or (";
1204 matcher2_.DescribeNegationTo(os);
1205 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001206 }
1207
zhanyong.wan82113312010-01-08 21:55:40 +00001208 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1209 // If either matcher1_ or matcher2_ doesn't match x, we only need
1210 // to explain why one of them fails.
1211 StringMatchResultListener listener1;
1212 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1213 *listener << listener1.str();
1214 return false;
1215 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001216
zhanyong.wan82113312010-01-08 21:55:40 +00001217 StringMatchResultListener listener2;
1218 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1219 *listener << listener2.str();
1220 return false;
1221 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001222
zhanyong.wan82113312010-01-08 21:55:40 +00001223 // Otherwise we need to explain why *both* of them match.
1224 const internal::string s1 = listener1.str();
1225 const internal::string s2 = listener2.str();
1226
1227 if (s1 == "") {
1228 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001229 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001230 *listener << s1;
1231 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001232 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001233 }
1234 }
zhanyong.wan82113312010-01-08 21:55:40 +00001235 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001236 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001237
zhanyong.wanc6a41232009-05-13 23:38:40 +00001238 private:
1239 const Matcher<T> matcher1_;
1240 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001241
1242 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001243};
1244
shiqiane35fdd92008-12-10 05:08:54 +00001245// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1246// matches a value that matches all of the matchers m_1, ..., and m_n.
1247template <typename Matcher1, typename Matcher2>
1248class BothOfMatcher {
1249 public:
1250 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1251 : matcher1_(matcher1), matcher2_(matcher2) {}
1252
1253 // This template type conversion operator allows a
1254 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1255 // both Matcher1 and Matcher2 can match.
1256 template <typename T>
1257 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001258 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1259 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001260 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001261
shiqiane35fdd92008-12-10 05:08:54 +00001262 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001263 Matcher1 matcher1_;
1264 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001265
1266 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001267};
shiqiane35fdd92008-12-10 05:08:54 +00001268
zhanyong.wanc6a41232009-05-13 23:38:40 +00001269// Implements the AnyOf(m1, m2) matcher for a particular argument type
1270// T. We do not nest it inside the AnyOfMatcher class template, as
1271// that will prevent different instantiations of AnyOfMatcher from
1272// sharing the same EitherOfMatcherImpl<T> class.
1273template <typename T>
1274class EitherOfMatcherImpl : public MatcherInterface<T> {
1275 public:
1276 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1277 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001278
zhanyong.wanc6a41232009-05-13 23:38:40 +00001279 virtual void DescribeTo(::std::ostream* os) const {
1280 *os << "(";
1281 matcher1_.DescribeTo(os);
1282 *os << ") or (";
1283 matcher2_.DescribeTo(os);
1284 *os << ")";
1285 }
shiqiane35fdd92008-12-10 05:08:54 +00001286
zhanyong.wanc6a41232009-05-13 23:38:40 +00001287 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001288 *os << "(";
1289 matcher1_.DescribeNegationTo(os);
1290 *os << ") and (";
1291 matcher2_.DescribeNegationTo(os);
1292 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001293 }
shiqiane35fdd92008-12-10 05:08:54 +00001294
zhanyong.wan82113312010-01-08 21:55:40 +00001295 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1296 // If either matcher1_ or matcher2_ matches x, we just need to
1297 // explain why *one* of them matches.
1298 StringMatchResultListener listener1;
1299 if (matcher1_.MatchAndExplain(x, &listener1)) {
1300 *listener << listener1.str();
1301 return true;
1302 }
1303
1304 StringMatchResultListener listener2;
1305 if (matcher2_.MatchAndExplain(x, &listener2)) {
1306 *listener << listener2.str();
1307 return true;
1308 }
1309
1310 // Otherwise we need to explain why *both* of them fail.
1311 const internal::string s1 = listener1.str();
1312 const internal::string s2 = listener2.str();
1313
1314 if (s1 == "") {
1315 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001316 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001317 *listener << s1;
1318 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001319 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001320 }
1321 }
zhanyong.wan82113312010-01-08 21:55:40 +00001322 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001323 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001324
zhanyong.wanc6a41232009-05-13 23:38:40 +00001325 private:
1326 const Matcher<T> matcher1_;
1327 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001328
1329 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001330};
1331
1332// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1333// matches a value that matches at least one of the matchers m_1, ...,
1334// and m_n.
1335template <typename Matcher1, typename Matcher2>
1336class EitherOfMatcher {
1337 public:
1338 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1339 : matcher1_(matcher1), matcher2_(matcher2) {}
1340
1341 // This template type conversion operator allows a
1342 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1343 // both Matcher1 and Matcher2 can match.
1344 template <typename T>
1345 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001346 return Matcher<T>(new EitherOfMatcherImpl<T>(
1347 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001348 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001349
shiqiane35fdd92008-12-10 05:08:54 +00001350 private:
shiqiane35fdd92008-12-10 05:08:54 +00001351 Matcher1 matcher1_;
1352 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001353
1354 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001355};
1356
1357// Used for implementing Truly(pred), which turns a predicate into a
1358// matcher.
1359template <typename Predicate>
1360class TrulyMatcher {
1361 public:
1362 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1363
1364 // This method template allows Truly(pred) to be used as a matcher
1365 // for type T where T is the argument type of predicate 'pred'. The
1366 // argument is passed by reference as the predicate may be
1367 // interested in the address of the argument.
1368 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001369 bool MatchAndExplain(T& x, // NOLINT
1370 MatchResultListener* /* listener */) const {
zhanyong.wan652540a2009-02-23 23:37:29 +00001371#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001372 // MSVC warns about converting a value into bool (warning 4800).
1373#pragma warning(push) // Saves the current warning state.
1374#pragma warning(disable:4800) // Temporarily disables warning 4800.
1375#endif // GTEST_OS_WINDOWS
1376 return predicate_(x);
zhanyong.wan652540a2009-02-23 23:37:29 +00001377#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001378#pragma warning(pop) // Restores the warning state.
1379#endif // GTEST_OS_WINDOWS
1380 }
1381
1382 void DescribeTo(::std::ostream* os) const {
1383 *os << "satisfies the given predicate";
1384 }
1385
1386 void DescribeNegationTo(::std::ostream* os) const {
1387 *os << "doesn't satisfy the given predicate";
1388 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001389
shiqiane35fdd92008-12-10 05:08:54 +00001390 private:
1391 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001392
1393 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001394};
1395
1396// Used for implementing Matches(matcher), which turns a matcher into
1397// a predicate.
1398template <typename M>
1399class MatcherAsPredicate {
1400 public:
1401 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1402
1403 // This template operator() allows Matches(m) to be used as a
1404 // predicate on type T where m is a matcher on type T.
1405 //
1406 // The argument x is passed by reference instead of by value, as
1407 // some matcher may be interested in its address (e.g. as in
1408 // Matches(Ref(n))(x)).
1409 template <typename T>
1410 bool operator()(const T& x) const {
1411 // We let matcher_ commit to a particular type here instead of
1412 // when the MatcherAsPredicate object was constructed. This
1413 // allows us to write Matches(m) where m is a polymorphic matcher
1414 // (e.g. Eq(5)).
1415 //
1416 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1417 // compile when matcher_ has type Matcher<const T&>; if we write
1418 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1419 // when matcher_ has type Matcher<T>; if we just write
1420 // matcher_.Matches(x), it won't compile when matcher_ is
1421 // polymorphic, e.g. Eq(5).
1422 //
1423 // MatcherCast<const T&>() is necessary for making the code work
1424 // in all of the above situations.
1425 return MatcherCast<const T&>(matcher_).Matches(x);
1426 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001427
shiqiane35fdd92008-12-10 05:08:54 +00001428 private:
1429 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001430
1431 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001432};
1433
1434// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1435// argument M must be a type that can be converted to a matcher.
1436template <typename M>
1437class PredicateFormatterFromMatcher {
1438 public:
1439 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1440
1441 // This template () operator allows a PredicateFormatterFromMatcher
1442 // object to act as a predicate-formatter suitable for using with
1443 // Google Test's EXPECT_PRED_FORMAT1() macro.
1444 template <typename T>
1445 AssertionResult operator()(const char* value_text, const T& x) const {
1446 // We convert matcher_ to a Matcher<const T&> *now* instead of
1447 // when the PredicateFormatterFromMatcher object was constructed,
1448 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1449 // know which type to instantiate it to until we actually see the
1450 // type of x here.
1451 //
1452 // We write MatcherCast<const T&>(matcher_) instead of
1453 // Matcher<const T&>(matcher_), as the latter won't compile when
1454 // matcher_ has type Matcher<T> (e.g. An<int>()).
1455 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001456 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001457 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001458 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001459
1460 ::std::stringstream ss;
1461 ss << "Value of: " << value_text << "\n"
1462 << "Expected: ";
1463 matcher.DescribeTo(&ss);
1464 ss << "\n Actual: " << listener.str();
1465 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001466 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001467
shiqiane35fdd92008-12-10 05:08:54 +00001468 private:
1469 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001470
1471 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001472};
1473
1474// A helper function for converting a matcher to a predicate-formatter
1475// without the user needing to explicitly write the type. This is
1476// used for implementing ASSERT_THAT() and EXPECT_THAT().
1477template <typename M>
1478inline PredicateFormatterFromMatcher<M>
1479MakePredicateFormatterFromMatcher(const M& matcher) {
1480 return PredicateFormatterFromMatcher<M>(matcher);
1481}
1482
1483// Implements the polymorphic floating point equality matcher, which
1484// matches two float values using ULP-based approximation. The
1485// template is meant to be instantiated with FloatType being either
1486// float or double.
1487template <typename FloatType>
1488class FloatingEqMatcher {
1489 public:
1490 // Constructor for FloatingEqMatcher.
1491 // The matcher's input will be compared with rhs. The matcher treats two
1492 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1493 // equality comparisons between NANs will always return false.
1494 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1495 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1496
1497 // Implements floating point equality matcher as a Matcher<T>.
1498 template <typename T>
1499 class Impl : public MatcherInterface<T> {
1500 public:
1501 Impl(FloatType rhs, bool nan_eq_nan) :
1502 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1503
zhanyong.wan82113312010-01-08 21:55:40 +00001504 virtual bool MatchAndExplain(T value,
1505 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001506 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1507
1508 // Compares NaNs first, if nan_eq_nan_ is true.
1509 if (nan_eq_nan_ && lhs.is_nan()) {
1510 return rhs.is_nan();
1511 }
1512
1513 return lhs.AlmostEquals(rhs);
1514 }
1515
1516 virtual void DescribeTo(::std::ostream* os) const {
1517 // os->precision() returns the previously set precision, which we
1518 // store to restore the ostream to its original configuration
1519 // after outputting.
1520 const ::std::streamsize old_precision = os->precision(
1521 ::std::numeric_limits<FloatType>::digits10 + 2);
1522 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1523 if (nan_eq_nan_) {
1524 *os << "is NaN";
1525 } else {
1526 *os << "never matches";
1527 }
1528 } else {
1529 *os << "is approximately " << rhs_;
1530 }
1531 os->precision(old_precision);
1532 }
1533
1534 virtual void DescribeNegationTo(::std::ostream* os) const {
1535 // As before, get original precision.
1536 const ::std::streamsize old_precision = os->precision(
1537 ::std::numeric_limits<FloatType>::digits10 + 2);
1538 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1539 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001540 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00001541 } else {
1542 *os << "is anything";
1543 }
1544 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001545 *os << "isn't approximately " << rhs_;
shiqiane35fdd92008-12-10 05:08:54 +00001546 }
1547 // Restore original precision.
1548 os->precision(old_precision);
1549 }
1550
1551 private:
1552 const FloatType rhs_;
1553 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001554
1555 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001556 };
1557
1558 // The following 3 type conversion operators allow FloatEq(rhs) and
1559 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1560 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1561 // (While Google's C++ coding style doesn't allow arguments passed
1562 // by non-const reference, we may see them in code not conforming to
1563 // the style. Therefore Google Mock needs to support them.)
1564 operator Matcher<FloatType>() const {
1565 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1566 }
1567
1568 operator Matcher<const FloatType&>() const {
1569 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1570 }
1571
1572 operator Matcher<FloatType&>() const {
1573 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1574 }
1575 private:
1576 const FloatType rhs_;
1577 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001578
1579 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001580};
1581
1582// Implements the Pointee(m) matcher for matching a pointer whose
1583// pointee matches matcher m. The pointer can be either raw or smart.
1584template <typename InnerMatcher>
1585class PointeeMatcher {
1586 public:
1587 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1588
1589 // This type conversion operator template allows Pointee(m) to be
1590 // used as a matcher for any pointer type whose pointee type is
1591 // compatible with the inner matcher, where type Pointer can be
1592 // either a raw pointer or a smart pointer.
1593 //
1594 // The reason we do this instead of relying on
1595 // MakePolymorphicMatcher() is that the latter is not flexible
1596 // enough for implementing the DescribeTo() method of Pointee().
1597 template <typename Pointer>
1598 operator Matcher<Pointer>() const {
1599 return MakeMatcher(new Impl<Pointer>(matcher_));
1600 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001601
shiqiane35fdd92008-12-10 05:08:54 +00001602 private:
1603 // The monomorphic implementation that works for a particular pointer type.
1604 template <typename Pointer>
1605 class Impl : public MatcherInterface<Pointer> {
1606 public:
zhanyong.wane0d051e2009-02-19 00:33:37 +00001607 typedef typename PointeeOf<GMOCK_REMOVE_CONST_( // NOLINT
1608 GMOCK_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001609
1610 explicit Impl(const InnerMatcher& matcher)
1611 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1612
shiqiane35fdd92008-12-10 05:08:54 +00001613 virtual void DescribeTo(::std::ostream* os) const {
1614 *os << "points to a value that ";
1615 matcher_.DescribeTo(os);
1616 }
1617
1618 virtual void DescribeNegationTo(::std::ostream* os) const {
1619 *os << "does not point to a value that ";
1620 matcher_.DescribeTo(os);
1621 }
1622
zhanyong.wan82113312010-01-08 21:55:40 +00001623 virtual bool MatchAndExplain(Pointer pointer,
1624 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001625 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00001626 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001627
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001628 *listener << "which points to ";
1629 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001630 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001631
shiqiane35fdd92008-12-10 05:08:54 +00001632 private:
1633 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001634
1635 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001636 };
1637
1638 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001639
1640 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001641};
1642
1643// Implements the Field() matcher for matching a field (i.e. member
1644// variable) of an object.
1645template <typename Class, typename FieldType>
1646class FieldMatcher {
1647 public:
1648 FieldMatcher(FieldType Class::*field,
1649 const Matcher<const FieldType&>& matcher)
1650 : field_(field), matcher_(matcher) {}
1651
shiqiane35fdd92008-12-10 05:08:54 +00001652 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001653 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001654 matcher_.DescribeTo(os);
1655 }
1656
1657 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001658 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001659 matcher_.DescribeNegationTo(os);
1660 }
1661
zhanyong.wandb22c222010-01-28 21:52:29 +00001662 template <typename T>
1663 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
1664 return MatchAndExplainImpl(
1665 typename ::testing::internal::
1666 is_pointer<GMOCK_REMOVE_CONST_(T)>::type(),
1667 value, listener);
1668 }
1669
1670 private:
1671 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001672 // Symbian's C++ compiler choose which overload to use. Its type is
1673 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001674 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1675 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001676 *listener << "whose given field is ";
1677 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001678 }
1679
zhanyong.wandb22c222010-01-28 21:52:29 +00001680 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1681 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001682 if (p == NULL)
1683 return false;
1684
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001685 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001686 // Since *p has a field, it must be a class/struct/union type and
1687 // thus cannot be a pointer. Therefore we pass false_type() as
1688 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001689 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001690 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001691
shiqiane35fdd92008-12-10 05:08:54 +00001692 const FieldType Class::*field_;
1693 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001694
1695 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001696};
1697
shiqiane35fdd92008-12-10 05:08:54 +00001698// Implements the Property() matcher for matching a property
1699// (i.e. return value of a getter method) of an object.
1700template <typename Class, typename PropertyType>
1701class PropertyMatcher {
1702 public:
1703 // The property may have a reference type, so 'const PropertyType&'
1704 // may cause double references and fail to compile. That's why we
1705 // need GMOCK_REFERENCE_TO_CONST, which works regardless of
1706 // PropertyType being a reference or not.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001707 typedef GMOCK_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001708
1709 PropertyMatcher(PropertyType (Class::*property)() const,
1710 const Matcher<RefToConstProperty>& matcher)
1711 : property_(property), matcher_(matcher) {}
1712
shiqiane35fdd92008-12-10 05:08:54 +00001713 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001714 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001715 matcher_.DescribeTo(os);
1716 }
1717
1718 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001719 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001720 matcher_.DescribeNegationTo(os);
1721 }
1722
zhanyong.wandb22c222010-01-28 21:52:29 +00001723 template <typename T>
1724 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
1725 return MatchAndExplainImpl(
1726 typename ::testing::internal::
1727 is_pointer<GMOCK_REMOVE_CONST_(T)>::type(),
1728 value, listener);
1729 }
1730
1731 private:
1732 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001733 // Symbian's C++ compiler choose which overload to use. Its type is
1734 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001735 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1736 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001737 *listener << "whose given property is ";
1738 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
1739 // which takes a non-const reference as argument.
1740 RefToConstProperty result = (obj.*property_)();
1741 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001742 }
1743
zhanyong.wandb22c222010-01-28 21:52:29 +00001744 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1745 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001746 if (p == NULL)
1747 return false;
1748
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001749 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001750 // Since *p has a property method, it must be a class/struct/union
1751 // type and thus cannot be a pointer. Therefore we pass
1752 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001753 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001754 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001755
shiqiane35fdd92008-12-10 05:08:54 +00001756 PropertyType (Class::*property_)() const;
1757 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001758
1759 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001760};
1761
shiqiane35fdd92008-12-10 05:08:54 +00001762// Type traits specifying various features of different functors for ResultOf.
1763// The default template specifies features for functor objects.
1764// Functor classes have to typedef argument_type and result_type
1765// to be compatible with ResultOf.
1766template <typename Functor>
1767struct CallableTraits {
1768 typedef typename Functor::result_type ResultType;
1769 typedef Functor StorageType;
1770
zhanyong.wan32de5f52009-12-23 00:13:23 +00001771 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00001772 template <typename T>
1773 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1774};
1775
1776// Specialization for function pointers.
1777template <typename ArgType, typename ResType>
1778struct CallableTraits<ResType(*)(ArgType)> {
1779 typedef ResType ResultType;
1780 typedef ResType(*StorageType)(ArgType);
1781
1782 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001783 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00001784 << "NULL function pointer is passed into ResultOf().";
1785 }
1786 template <typename T>
1787 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1788 return (*f)(arg);
1789 }
1790};
1791
1792// Implements the ResultOf() matcher for matching a return value of a
1793// unary function of an object.
1794template <typename Callable>
1795class ResultOfMatcher {
1796 public:
1797 typedef typename CallableTraits<Callable>::ResultType ResultType;
1798
1799 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1800 : callable_(callable), matcher_(matcher) {
1801 CallableTraits<Callable>::CheckIsValid(callable_);
1802 }
1803
1804 template <typename T>
1805 operator Matcher<T>() const {
1806 return Matcher<T>(new Impl<T>(callable_, matcher_));
1807 }
1808
1809 private:
1810 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1811
1812 template <typename T>
1813 class Impl : public MatcherInterface<T> {
1814 public:
1815 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1816 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00001817
1818 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001819 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001820 matcher_.DescribeTo(os);
1821 }
1822
1823 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001824 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001825 matcher_.DescribeNegationTo(os);
1826 }
1827
zhanyong.wan82113312010-01-08 21:55:40 +00001828 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001829 *listener << "which is mapped by the given callable to ";
1830 // Cannot pass the return value (for example, int) to
1831 // MatchPrintAndExplain, which takes a non-const reference as argument.
1832 ResultType result =
1833 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
1834 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001835 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001836
shiqiane35fdd92008-12-10 05:08:54 +00001837 private:
1838 // Functors often define operator() as non-const method even though
1839 // they are actualy stateless. But we need to use them even when
1840 // 'this' is a const pointer. It's the user's responsibility not to
1841 // use stateful callables with ResultOf(), which does't guarantee
1842 // how many times the callable will be invoked.
1843 mutable CallableStorageType callable_;
1844 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001845
1846 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001847 }; // class Impl
1848
1849 const CallableStorageType callable_;
1850 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001851
1852 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001853};
1854
zhanyong.wan6a896b52009-01-16 01:13:50 +00001855// Implements an equality matcher for any STL-style container whose elements
1856// support ==. This matcher is like Eq(), but its failure explanations provide
1857// more detailed information that is useful when the container is used as a set.
1858// The failure message reports elements that are in one of the operands but not
1859// the other. The failure messages do not report duplicate or out-of-order
1860// elements in the containers (which don't properly matter to sets, but can
1861// occur if the containers are vectors or lists, for example).
1862//
1863// Uses the container's const_iterator, value_type, operator ==,
1864// begin(), and end().
1865template <typename Container>
1866class ContainerEqMatcher {
1867 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00001868 typedef internal::StlContainerView<Container> View;
1869 typedef typename View::type StlContainer;
1870 typedef typename View::const_reference StlContainerReference;
1871
1872 // We make a copy of rhs in case the elements in it are modified
1873 // after this matcher is created.
1874 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
1875 // Makes sure the user doesn't instantiate this class template
1876 // with a const or reference type.
1877 testing::StaticAssertTypeEq<Container,
1878 GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))>();
1879 }
1880
zhanyong.wan6a896b52009-01-16 01:13:50 +00001881 void DescribeTo(::std::ostream* os) const {
1882 *os << "equals ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001883 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001884 }
1885 void DescribeNegationTo(::std::ostream* os) const {
1886 *os << "does not equal ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001887 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001888 }
1889
zhanyong.wanb8243162009-06-04 05:48:20 +00001890 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00001891 bool MatchAndExplain(const LhsContainer& lhs,
1892 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00001893 // GMOCK_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
1894 // that causes LhsContainer to be a const type sometimes.
1895 typedef internal::StlContainerView<GMOCK_REMOVE_CONST_(LhsContainer)>
1896 LhsView;
1897 typedef typename LhsView::type LhsStlContainer;
1898 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00001899 if (lhs_stl_container == rhs_)
1900 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00001901
zhanyong.wane122e452010-01-12 09:03:52 +00001902 ::std::ostream* const os = listener->stream();
1903 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001904 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00001905 bool printed_header = false;
1906 for (typename LhsStlContainer::const_iterator it =
1907 lhs_stl_container.begin();
1908 it != lhs_stl_container.end(); ++it) {
1909 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
1910 rhs_.end()) {
1911 if (printed_header) {
1912 *os << ", ";
1913 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001914 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00001915 printed_header = true;
1916 }
zhanyong.wan6953a722010-01-13 05:15:07 +00001917 UniversalPrinter<typename LhsStlContainer::value_type>::
1918 Print(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001919 }
zhanyong.wane122e452010-01-12 09:03:52 +00001920 }
1921
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001922 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00001923 bool printed_header2 = false;
1924 for (typename StlContainer::const_iterator it = rhs_.begin();
1925 it != rhs_.end(); ++it) {
1926 if (internal::ArrayAwareFind(
1927 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
1928 lhs_stl_container.end()) {
1929 if (printed_header2) {
1930 *os << ", ";
1931 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001932 *os << (printed_header ? ",\nand" : "which")
1933 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00001934 printed_header2 = true;
1935 }
1936 UniversalPrinter<typename StlContainer::value_type>::Print(*it, os);
1937 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00001938 }
1939 }
1940
zhanyong.wane122e452010-01-12 09:03:52 +00001941 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00001942 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001943
zhanyong.wan6a896b52009-01-16 01:13:50 +00001944 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00001945 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001946
1947 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001948};
1949
zhanyong.wanb8243162009-06-04 05:48:20 +00001950// Implements Contains(element_matcher) for the given argument type Container.
1951template <typename Container>
1952class ContainsMatcherImpl : public MatcherInterface<Container> {
1953 public:
1954 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
1955 typedef StlContainerView<RawContainer> View;
1956 typedef typename View::type StlContainer;
1957 typedef typename View::const_reference StlContainerReference;
1958 typedef typename StlContainer::value_type Element;
1959
1960 template <typename InnerMatcher>
1961 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
1962 : inner_matcher_(
1963 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
1964
zhanyong.wanb8243162009-06-04 05:48:20 +00001965 // Describes what this matcher does.
1966 virtual void DescribeTo(::std::ostream* os) const {
1967 *os << "contains at least one element that ";
1968 inner_matcher_.DescribeTo(os);
1969 }
1970
1971 // Describes what the negation of this matcher does.
1972 virtual void DescribeNegationTo(::std::ostream* os) const {
1973 *os << "doesn't contain any element that ";
1974 inner_matcher_.DescribeTo(os);
1975 }
1976
zhanyong.wan82113312010-01-08 21:55:40 +00001977 virtual bool MatchAndExplain(Container container,
1978 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00001979 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00001980 size_t i = 0;
1981 for (typename StlContainer::const_iterator it = stl_container.begin();
1982 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001983 StringMatchResultListener inner_listener;
1984 if (inner_matcher_.MatchAndExplain(*it, &inner_listener)) {
1985 *listener << "whose element #" << i << " matches";
1986 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00001987 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00001988 }
1989 }
zhanyong.wan82113312010-01-08 21:55:40 +00001990 return false;
zhanyong.wanb8243162009-06-04 05:48:20 +00001991 }
1992
1993 private:
1994 const Matcher<const Element&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001995
1996 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00001997};
1998
1999// Implements polymorphic Contains(element_matcher).
2000template <typename M>
2001class ContainsMatcher {
2002 public:
2003 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2004
2005 template <typename Container>
2006 operator Matcher<Container>() const {
2007 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2008 }
2009
2010 private:
2011 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002012
2013 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002014};
2015
zhanyong.wanb5937da2009-07-16 20:26:41 +00002016// Implements Key(inner_matcher) for the given argument pair type.
2017// Key(inner_matcher) matches an std::pair whose 'first' field matches
2018// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2019// std::map that contains at least one element whose key is >= 5.
2020template <typename PairType>
2021class KeyMatcherImpl : public MatcherInterface<PairType> {
2022 public:
2023 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
2024 typedef typename RawPairType::first_type KeyType;
2025
2026 template <typename InnerMatcher>
2027 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2028 : inner_matcher_(
2029 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2030 }
2031
2032 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002033 virtual bool MatchAndExplain(PairType key_value,
2034 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002035 StringMatchResultListener inner_listener;
2036 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2037 &inner_listener);
2038 const internal::string explanation = inner_listener.str();
2039 if (explanation != "") {
2040 *listener << "whose first field is a value " << explanation;
2041 }
2042 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002043 }
2044
2045 // Describes what this matcher does.
2046 virtual void DescribeTo(::std::ostream* os) const {
2047 *os << "has a key that ";
2048 inner_matcher_.DescribeTo(os);
2049 }
2050
2051 // Describes what the negation of this matcher does.
2052 virtual void DescribeNegationTo(::std::ostream* os) const {
2053 *os << "doesn't have a key that ";
2054 inner_matcher_.DescribeTo(os);
2055 }
2056
zhanyong.wanb5937da2009-07-16 20:26:41 +00002057 private:
2058 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002059
2060 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002061};
2062
2063// Implements polymorphic Key(matcher_for_key).
2064template <typename M>
2065class KeyMatcher {
2066 public:
2067 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2068
2069 template <typename PairType>
2070 operator Matcher<PairType>() const {
2071 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2072 }
2073
2074 private:
2075 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002076
2077 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002078};
2079
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002080// Implements Pair(first_matcher, second_matcher) for the given argument pair
2081// type with its two matchers. See Pair() function below.
2082template <typename PairType>
2083class PairMatcherImpl : public MatcherInterface<PairType> {
2084 public:
2085 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
2086 typedef typename RawPairType::first_type FirstType;
2087 typedef typename RawPairType::second_type SecondType;
2088
2089 template <typename FirstMatcher, typename SecondMatcher>
2090 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2091 : first_matcher_(
2092 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2093 second_matcher_(
2094 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2095 }
2096
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002097 // Describes what this matcher does.
2098 virtual void DescribeTo(::std::ostream* os) const {
2099 *os << "has a first field that ";
2100 first_matcher_.DescribeTo(os);
2101 *os << ", and has a second field that ";
2102 second_matcher_.DescribeTo(os);
2103 }
2104
2105 // Describes what the negation of this matcher does.
2106 virtual void DescribeNegationTo(::std::ostream* os) const {
2107 *os << "has a first field that ";
2108 first_matcher_.DescribeNegationTo(os);
2109 *os << ", or has a second field that ";
2110 second_matcher_.DescribeNegationTo(os);
2111 }
2112
zhanyong.wan82113312010-01-08 21:55:40 +00002113 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2114 // matches second_matcher.
2115 virtual bool MatchAndExplain(PairType a_pair,
2116 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002117 if (!listener->IsInterested()) {
2118 // If the listener is not interested, we don't need to construct the
2119 // explanation.
2120 return first_matcher_.Matches(a_pair.first) &&
2121 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00002122 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002123 StringMatchResultListener first_inner_listener;
2124 if (!first_matcher_.MatchAndExplain(a_pair.first,
2125 &first_inner_listener)) {
2126 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002127 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002128 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002129 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002130 StringMatchResultListener second_inner_listener;
2131 if (!second_matcher_.MatchAndExplain(a_pair.second,
2132 &second_inner_listener)) {
2133 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002134 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002135 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002136 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002137 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
2138 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00002139 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002140 }
2141
2142 private:
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002143 void ExplainSuccess(const internal::string& first_explanation,
2144 const internal::string& second_explanation,
2145 MatchResultListener* listener) const {
2146 *listener << "whose both fields match";
2147 if (first_explanation != "") {
2148 *listener << ", where the first field is a value " << first_explanation;
2149 }
2150 if (second_explanation != "") {
2151 *listener << ", ";
2152 if (first_explanation != "") {
2153 *listener << "and ";
2154 } else {
2155 *listener << "where ";
2156 }
2157 *listener << "the second field is a value " << second_explanation;
2158 }
2159 }
2160
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002161 const Matcher<const FirstType&> first_matcher_;
2162 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002163
2164 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002165};
2166
2167// Implements polymorphic Pair(first_matcher, second_matcher).
2168template <typename FirstMatcher, typename SecondMatcher>
2169class PairMatcher {
2170 public:
2171 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2172 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2173
2174 template <typename PairType>
2175 operator Matcher<PairType> () const {
2176 return MakeMatcher(
2177 new PairMatcherImpl<PairType>(
2178 first_matcher_, second_matcher_));
2179 }
2180
2181 private:
2182 const FirstMatcher first_matcher_;
2183 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002184
2185 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002186};
2187
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002188// Implements ElementsAre() and ElementsAreArray().
2189template <typename Container>
2190class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2191 public:
2192 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
2193 typedef internal::StlContainerView<RawContainer> View;
2194 typedef typename View::type StlContainer;
2195 typedef typename View::const_reference StlContainerReference;
2196 typedef typename StlContainer::value_type Element;
2197
2198 // Constructs the matcher from a sequence of element values or
2199 // element matchers.
2200 template <typename InputIter>
zhanyong.wan32de5f52009-12-23 00:13:23 +00002201 ElementsAreMatcherImpl(InputIter first, size_t a_count) {
2202 matchers_.reserve(a_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002203 InputIter it = first;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002204 for (size_t i = 0; i != a_count; ++i, ++it) {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002205 matchers_.push_back(MatcherCast<const Element&>(*it));
2206 }
2207 }
2208
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002209 // Describes what this matcher does.
2210 virtual void DescribeTo(::std::ostream* os) const {
2211 if (count() == 0) {
2212 *os << "is empty";
2213 } else if (count() == 1) {
2214 *os << "has 1 element that ";
2215 matchers_[0].DescribeTo(os);
2216 } else {
2217 *os << "has " << Elements(count()) << " where\n";
2218 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002219 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002220 matchers_[i].DescribeTo(os);
2221 if (i + 1 < count()) {
2222 *os << ",\n";
2223 }
2224 }
2225 }
2226 }
2227
2228 // Describes what the negation of this matcher does.
2229 virtual void DescribeNegationTo(::std::ostream* os) const {
2230 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002231 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002232 return;
2233 }
2234
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002235 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002236 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002237 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002238 matchers_[i].DescribeNegationTo(os);
2239 if (i + 1 < count()) {
2240 *os << ", or\n";
2241 }
2242 }
2243 }
2244
zhanyong.wan82113312010-01-08 21:55:40 +00002245 virtual bool MatchAndExplain(Container container,
2246 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002247 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002248 const size_t actual_count = stl_container.size();
2249 if (actual_count != count()) {
2250 // The element count doesn't match. If the container is empty,
2251 // there's no need to explain anything as Google Mock already
2252 // prints the empty container. Otherwise we just need to show
2253 // how many elements there actually are.
2254 if (actual_count != 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002255 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002256 }
zhanyong.wan82113312010-01-08 21:55:40 +00002257 return false;
2258 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002259
zhanyong.wan82113312010-01-08 21:55:40 +00002260 typename StlContainer::const_iterator it = stl_container.begin();
2261 // explanations[i] is the explanation of the element at index i.
2262 std::vector<internal::string> explanations(count());
2263 for (size_t i = 0; i != count(); ++it, ++i) {
2264 StringMatchResultListener s;
2265 if (matchers_[i].MatchAndExplain(*it, &s)) {
2266 explanations[i] = s.str();
2267 } else {
2268 // The container has the right size but the i-th element
2269 // doesn't match its expectation.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002270 *listener << "whose element #" << i << " doesn't match";
2271 PrintIfNotEmpty(s.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002272 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002273 }
2274 }
zhanyong.wan82113312010-01-08 21:55:40 +00002275
2276 // Every element matches its expectation. We need to explain why
2277 // (the obvious ones can be skipped).
zhanyong.wan82113312010-01-08 21:55:40 +00002278 bool reason_printed = false;
2279 for (size_t i = 0; i != count(); ++i) {
2280 const internal::string& s = explanations[i];
2281 if (!s.empty()) {
2282 if (reason_printed) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002283 *listener << ",\nand ";
zhanyong.wan82113312010-01-08 21:55:40 +00002284 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002285 *listener << "whose element #" << i << " matches, " << s;
zhanyong.wan82113312010-01-08 21:55:40 +00002286 reason_printed = true;
2287 }
2288 }
2289
2290 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002291 }
2292
2293 private:
2294 static Message Elements(size_t count) {
2295 return Message() << count << (count == 1 ? " element" : " elements");
2296 }
2297
2298 size_t count() const { return matchers_.size(); }
2299 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002300
2301 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002302};
2303
2304// Implements ElementsAre() of 0 arguments.
2305class ElementsAreMatcher0 {
2306 public:
2307 ElementsAreMatcher0() {}
2308
2309 template <typename Container>
2310 operator Matcher<Container>() const {
2311 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2312 RawContainer;
2313 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2314 Element;
2315
2316 const Matcher<const Element&>* const matchers = NULL;
2317 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 0));
2318 }
2319};
2320
2321// Implements ElementsAreArray().
2322template <typename T>
2323class ElementsAreArrayMatcher {
2324 public:
2325 ElementsAreArrayMatcher(const T* first, size_t count) :
2326 first_(first), count_(count) {}
2327
2328 template <typename Container>
2329 operator Matcher<Container>() const {
2330 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2331 RawContainer;
2332 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2333 Element;
2334
2335 return MakeMatcher(new ElementsAreMatcherImpl<Container>(first_, count_));
2336 }
2337
2338 private:
2339 const T* const first_;
2340 const size_t count_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002341
2342 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002343};
2344
2345// Constants denoting interpolations in a matcher description string.
2346const int kTupleInterpolation = -1; // "%(*)s"
2347const int kPercentInterpolation = -2; // "%%"
2348const int kInvalidInterpolation = -3; // "%" followed by invalid text
2349
2350// Records the location and content of an interpolation.
2351struct Interpolation {
2352 Interpolation(const char* start, const char* end, int param)
2353 : start_pos(start), end_pos(end), param_index(param) {}
2354
2355 // Points to the start of the interpolation (the '%' character).
2356 const char* start_pos;
2357 // Points to the first character after the interpolation.
2358 const char* end_pos;
2359 // 0-based index of the interpolated matcher parameter;
2360 // kTupleInterpolation for "%(*)s"; kPercentInterpolation for "%%".
2361 int param_index;
2362};
2363
2364typedef ::std::vector<Interpolation> Interpolations;
2365
2366// Parses a matcher description string and returns a vector of
2367// interpolations that appear in the string; generates non-fatal
2368// failures iff 'description' is an invalid matcher description.
2369// 'param_names' is a NULL-terminated array of parameter names in the
2370// order they appear in the MATCHER_P*() parameter list.
2371Interpolations ValidateMatcherDescription(
2372 const char* param_names[], const char* description);
2373
2374// Returns the actual matcher description, given the matcher name,
2375// user-supplied description template string, interpolations in the
2376// string, and the printed values of the matcher parameters.
2377string FormatMatcherDescription(
2378 const char* matcher_name, const char* description,
2379 const Interpolations& interp, const Strings& param_values);
2380
shiqiane35fdd92008-12-10 05:08:54 +00002381} // namespace internal
2382
2383// Implements MatcherCast().
2384template <typename T, typename M>
2385inline Matcher<T> MatcherCast(M matcher) {
2386 return internal::MatcherCastImpl<T, M>::Cast(matcher);
2387}
2388
2389// _ is a matcher that matches anything of any type.
2390//
2391// This definition is fine as:
2392//
2393// 1. The C++ standard permits using the name _ in a namespace that
2394// is not the global namespace or ::std.
2395// 2. The AnythingMatcher class has no data member or constructor,
2396// so it's OK to create global variables of this type.
2397// 3. c-style has approved of using _ in this case.
2398const internal::AnythingMatcher _ = {};
2399// Creates a matcher that matches any value of the given type T.
2400template <typename T>
2401inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2402
2403// Creates a matcher that matches any value of the given type T.
2404template <typename T>
2405inline Matcher<T> An() { return A<T>(); }
2406
2407// Creates a polymorphic matcher that matches anything equal to x.
2408// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2409// wouldn't compile.
2410template <typename T>
2411inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2412
2413// Constructs a Matcher<T> from a 'value' of type T. The constructed
2414// matcher matches any value that's equal to 'value'.
2415template <typename T>
2416Matcher<T>::Matcher(T value) { *this = Eq(value); }
2417
2418// Creates a monomorphic matcher that matches anything with type Lhs
2419// and equal to rhs. A user may need to use this instead of Eq(...)
2420// in order to resolve an overloading ambiguity.
2421//
2422// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2423// or Matcher<T>(x), but more readable than the latter.
2424//
2425// We could define similar monomorphic matchers for other comparison
2426// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2427// it yet as those are used much less than Eq() in practice. A user
2428// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2429// for example.
2430template <typename Lhs, typename Rhs>
2431inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2432
2433// Creates a polymorphic matcher that matches anything >= x.
2434template <typename Rhs>
2435inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2436 return internal::GeMatcher<Rhs>(x);
2437}
2438
2439// Creates a polymorphic matcher that matches anything > x.
2440template <typename Rhs>
2441inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2442 return internal::GtMatcher<Rhs>(x);
2443}
2444
2445// Creates a polymorphic matcher that matches anything <= x.
2446template <typename Rhs>
2447inline internal::LeMatcher<Rhs> Le(Rhs x) {
2448 return internal::LeMatcher<Rhs>(x);
2449}
2450
2451// Creates a polymorphic matcher that matches anything < x.
2452template <typename Rhs>
2453inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2454 return internal::LtMatcher<Rhs>(x);
2455}
2456
2457// Creates a polymorphic matcher that matches anything != x.
2458template <typename Rhs>
2459inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2460 return internal::NeMatcher<Rhs>(x);
2461}
2462
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002463// Creates a polymorphic matcher that matches any NULL pointer.
2464inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2465 return MakePolymorphicMatcher(internal::IsNullMatcher());
2466}
2467
shiqiane35fdd92008-12-10 05:08:54 +00002468// Creates a polymorphic matcher that matches any non-NULL pointer.
2469// This is convenient as Not(NULL) doesn't compile (the compiler
2470// thinks that that expression is comparing a pointer with an integer).
2471inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2472 return MakePolymorphicMatcher(internal::NotNullMatcher());
2473}
2474
2475// Creates a polymorphic matcher that matches any argument that
2476// references variable x.
2477template <typename T>
2478inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2479 return internal::RefMatcher<T&>(x);
2480}
2481
2482// Creates a matcher that matches any double argument approximately
2483// equal to rhs, where two NANs are considered unequal.
2484inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2485 return internal::FloatingEqMatcher<double>(rhs, false);
2486}
2487
2488// Creates a matcher that matches any double argument approximately
2489// equal to rhs, including NaN values when rhs is NaN.
2490inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2491 return internal::FloatingEqMatcher<double>(rhs, true);
2492}
2493
2494// Creates a matcher that matches any float argument approximately
2495// equal to rhs, where two NANs are considered unequal.
2496inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2497 return internal::FloatingEqMatcher<float>(rhs, false);
2498}
2499
2500// Creates a matcher that matches any double argument approximately
2501// equal to rhs, including NaN values when rhs is NaN.
2502inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2503 return internal::FloatingEqMatcher<float>(rhs, true);
2504}
2505
2506// Creates a matcher that matches a pointer (raw or smart) that points
2507// to a value that matches inner_matcher.
2508template <typename InnerMatcher>
2509inline internal::PointeeMatcher<InnerMatcher> Pointee(
2510 const InnerMatcher& inner_matcher) {
2511 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2512}
2513
2514// Creates a matcher that matches an object whose given field matches
2515// 'matcher'. For example,
2516// Field(&Foo::number, Ge(5))
2517// matches a Foo object x iff x.number >= 5.
2518template <typename Class, typename FieldType, typename FieldMatcher>
2519inline PolymorphicMatcher<
2520 internal::FieldMatcher<Class, FieldType> > Field(
2521 FieldType Class::*field, const FieldMatcher& matcher) {
2522 return MakePolymorphicMatcher(
2523 internal::FieldMatcher<Class, FieldType>(
2524 field, MatcherCast<const FieldType&>(matcher)));
2525 // The call to MatcherCast() is required for supporting inner
2526 // matchers of compatible types. For example, it allows
2527 // Field(&Foo::bar, m)
2528 // to compile where bar is an int32 and m is a matcher for int64.
2529}
2530
2531// Creates a matcher that matches an object whose given property
2532// matches 'matcher'. For example,
2533// Property(&Foo::str, StartsWith("hi"))
2534// matches a Foo object x iff x.str() starts with "hi".
2535template <typename Class, typename PropertyType, typename PropertyMatcher>
2536inline PolymorphicMatcher<
2537 internal::PropertyMatcher<Class, PropertyType> > Property(
2538 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2539 return MakePolymorphicMatcher(
2540 internal::PropertyMatcher<Class, PropertyType>(
2541 property,
zhanyong.wane0d051e2009-02-19 00:33:37 +00002542 MatcherCast<GMOCK_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002543 // The call to MatcherCast() is required for supporting inner
2544 // matchers of compatible types. For example, it allows
2545 // Property(&Foo::bar, m)
2546 // to compile where bar() returns an int32 and m is a matcher for int64.
2547}
2548
2549// Creates a matcher that matches an object iff the result of applying
2550// a callable to x matches 'matcher'.
2551// For example,
2552// ResultOf(f, StartsWith("hi"))
2553// matches a Foo object x iff f(x) starts with "hi".
2554// callable parameter can be a function, function pointer, or a functor.
2555// Callable has to satisfy the following conditions:
2556// * It is required to keep no state affecting the results of
2557// the calls on it and make no assumptions about how many calls
2558// will be made. Any state it keeps must be protected from the
2559// concurrent access.
2560// * If it is a function object, it has to define type result_type.
2561// We recommend deriving your functor classes from std::unary_function.
2562template <typename Callable, typename ResultOfMatcher>
2563internal::ResultOfMatcher<Callable> ResultOf(
2564 Callable callable, const ResultOfMatcher& matcher) {
2565 return internal::ResultOfMatcher<Callable>(
2566 callable,
2567 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2568 matcher));
2569 // The call to MatcherCast() is required for supporting inner
2570 // matchers of compatible types. For example, it allows
2571 // ResultOf(Function, m)
2572 // to compile where Function() returns an int32 and m is a matcher for int64.
2573}
2574
2575// String matchers.
2576
2577// Matches a string equal to str.
2578inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2579 StrEq(const internal::string& str) {
2580 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2581 str, true, true));
2582}
2583
2584// Matches a string not equal to str.
2585inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2586 StrNe(const internal::string& str) {
2587 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2588 str, false, true));
2589}
2590
2591// Matches a string equal to str, ignoring case.
2592inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2593 StrCaseEq(const internal::string& str) {
2594 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2595 str, true, false));
2596}
2597
2598// Matches a string not equal to str, ignoring case.
2599inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2600 StrCaseNe(const internal::string& str) {
2601 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2602 str, false, false));
2603}
2604
2605// Creates a matcher that matches any string, std::string, or C string
2606// that contains the given substring.
2607inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2608 HasSubstr(const internal::string& substring) {
2609 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
2610 substring));
2611}
2612
2613// Matches a string that starts with 'prefix' (case-sensitive).
2614inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
2615 StartsWith(const internal::string& prefix) {
2616 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
2617 prefix));
2618}
2619
2620// Matches a string that ends with 'suffix' (case-sensitive).
2621inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
2622 EndsWith(const internal::string& suffix) {
2623 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
2624 suffix));
2625}
2626
shiqiane35fdd92008-12-10 05:08:54 +00002627// Matches a string that fully matches regular expression 'regex'.
2628// The matcher takes ownership of 'regex'.
2629inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2630 const internal::RE* regex) {
2631 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2632}
2633inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2634 const internal::string& regex) {
2635 return MatchesRegex(new internal::RE(regex));
2636}
2637
2638// Matches a string that contains regular expression 'regex'.
2639// The matcher takes ownership of 'regex'.
2640inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2641 const internal::RE* regex) {
2642 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2643}
2644inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2645 const internal::string& regex) {
2646 return ContainsRegex(new internal::RE(regex));
2647}
2648
shiqiane35fdd92008-12-10 05:08:54 +00002649#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2650// Wide string matchers.
2651
2652// Matches a string equal to str.
2653inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2654 StrEq(const internal::wstring& str) {
2655 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2656 str, true, true));
2657}
2658
2659// Matches a string not equal to str.
2660inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2661 StrNe(const internal::wstring& str) {
2662 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2663 str, false, true));
2664}
2665
2666// Matches a string equal to str, ignoring case.
2667inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2668 StrCaseEq(const internal::wstring& str) {
2669 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2670 str, true, false));
2671}
2672
2673// Matches a string not equal to str, ignoring case.
2674inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2675 StrCaseNe(const internal::wstring& str) {
2676 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2677 str, false, false));
2678}
2679
2680// Creates a matcher that matches any wstring, std::wstring, or C wide string
2681// that contains the given substring.
2682inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2683 HasSubstr(const internal::wstring& substring) {
2684 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2685 substring));
2686}
2687
2688// Matches a string that starts with 'prefix' (case-sensitive).
2689inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2690 StartsWith(const internal::wstring& prefix) {
2691 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2692 prefix));
2693}
2694
2695// Matches a string that ends with 'suffix' (case-sensitive).
2696inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2697 EndsWith(const internal::wstring& suffix) {
2698 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2699 suffix));
2700}
2701
2702#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2703
2704// Creates a polymorphic matcher that matches a 2-tuple where the
2705// first field == the second field.
2706inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2707
2708// Creates a polymorphic matcher that matches a 2-tuple where the
2709// first field >= the second field.
2710inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2711
2712// Creates a polymorphic matcher that matches a 2-tuple where the
2713// first field > the second field.
2714inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2715
2716// Creates a polymorphic matcher that matches a 2-tuple where the
2717// first field <= the second field.
2718inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2719
2720// Creates a polymorphic matcher that matches a 2-tuple where the
2721// first field < the second field.
2722inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2723
2724// Creates a polymorphic matcher that matches a 2-tuple where the
2725// first field != the second field.
2726inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2727
2728// Creates a matcher that matches any value of type T that m doesn't
2729// match.
2730template <typename InnerMatcher>
2731inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2732 return internal::NotMatcher<InnerMatcher>(m);
2733}
2734
2735// Creates a matcher that matches any value that matches all of the
2736// given matchers.
2737//
2738// For now we only support up to 5 matchers. Support for more
2739// matchers can be added as needed, or the user can use nested
2740// AllOf()s.
2741template <typename Matcher1, typename Matcher2>
2742inline internal::BothOfMatcher<Matcher1, Matcher2>
2743AllOf(Matcher1 m1, Matcher2 m2) {
2744 return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2);
2745}
2746
2747template <typename Matcher1, typename Matcher2, typename Matcher3>
2748inline internal::BothOfMatcher<Matcher1,
2749 internal::BothOfMatcher<Matcher2, Matcher3> >
2750AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2751 return AllOf(m1, AllOf(m2, m3));
2752}
2753
2754template <typename Matcher1, typename Matcher2, typename Matcher3,
2755 typename Matcher4>
2756inline internal::BothOfMatcher<Matcher1,
2757 internal::BothOfMatcher<Matcher2,
2758 internal::BothOfMatcher<Matcher3, Matcher4> > >
2759AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2760 return AllOf(m1, AllOf(m2, m3, m4));
2761}
2762
2763template <typename Matcher1, typename Matcher2, typename Matcher3,
2764 typename Matcher4, typename Matcher5>
2765inline internal::BothOfMatcher<Matcher1,
2766 internal::BothOfMatcher<Matcher2,
2767 internal::BothOfMatcher<Matcher3,
2768 internal::BothOfMatcher<Matcher4, Matcher5> > > >
2769AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2770 return AllOf(m1, AllOf(m2, m3, m4, m5));
2771}
2772
2773// Creates a matcher that matches any value that matches at least one
2774// of the given matchers.
2775//
2776// For now we only support up to 5 matchers. Support for more
2777// matchers can be added as needed, or the user can use nested
2778// AnyOf()s.
2779template <typename Matcher1, typename Matcher2>
2780inline internal::EitherOfMatcher<Matcher1, Matcher2>
2781AnyOf(Matcher1 m1, Matcher2 m2) {
2782 return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2);
2783}
2784
2785template <typename Matcher1, typename Matcher2, typename Matcher3>
2786inline internal::EitherOfMatcher<Matcher1,
2787 internal::EitherOfMatcher<Matcher2, Matcher3> >
2788AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2789 return AnyOf(m1, AnyOf(m2, m3));
2790}
2791
2792template <typename Matcher1, typename Matcher2, typename Matcher3,
2793 typename Matcher4>
2794inline internal::EitherOfMatcher<Matcher1,
2795 internal::EitherOfMatcher<Matcher2,
2796 internal::EitherOfMatcher<Matcher3, Matcher4> > >
2797AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2798 return AnyOf(m1, AnyOf(m2, m3, m4));
2799}
2800
2801template <typename Matcher1, typename Matcher2, typename Matcher3,
2802 typename Matcher4, typename Matcher5>
2803inline internal::EitherOfMatcher<Matcher1,
2804 internal::EitherOfMatcher<Matcher2,
2805 internal::EitherOfMatcher<Matcher3,
2806 internal::EitherOfMatcher<Matcher4, Matcher5> > > >
2807AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2808 return AnyOf(m1, AnyOf(m2, m3, m4, m5));
2809}
2810
2811// Returns a matcher that matches anything that satisfies the given
2812// predicate. The predicate can be any unary function or functor
2813// whose return type can be implicitly converted to bool.
2814template <typename Predicate>
2815inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
2816Truly(Predicate pred) {
2817 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
2818}
2819
zhanyong.wan6a896b52009-01-16 01:13:50 +00002820// Returns a matcher that matches an equal container.
2821// This matcher behaves like Eq(), but in the event of mismatch lists the
2822// values that are included in one container but not the other. (Duplicate
2823// values and order differences are not explained.)
2824template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00002825inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wanb8243162009-06-04 05:48:20 +00002826 GMOCK_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00002827 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002828 // This following line is for working around a bug in MSVC 8.0,
2829 // which causes Container to be a const type sometimes.
2830 typedef GMOCK_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00002831 return MakePolymorphicMatcher(
2832 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00002833}
2834
2835// Matches an STL-style container or a native array that contains at
2836// least one element matching the given value or matcher.
2837//
2838// Examples:
2839// ::std::set<int> page_ids;
2840// page_ids.insert(3);
2841// page_ids.insert(1);
2842// EXPECT_THAT(page_ids, Contains(1));
2843// EXPECT_THAT(page_ids, Contains(Gt(2)));
2844// EXPECT_THAT(page_ids, Not(Contains(4)));
2845//
2846// ::std::map<int, size_t> page_lengths;
2847// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00002848// EXPECT_THAT(page_lengths,
2849// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00002850//
2851// const char* user_ids[] = { "joe", "mike", "tom" };
2852// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
2853template <typename M>
2854inline internal::ContainsMatcher<M> Contains(M matcher) {
2855 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002856}
2857
zhanyong.wanb5937da2009-07-16 20:26:41 +00002858// Key(inner_matcher) matches an std::pair whose 'first' field matches
2859// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2860// std::map that contains at least one element whose key is >= 5.
2861template <typename M>
2862inline internal::KeyMatcher<M> Key(M inner_matcher) {
2863 return internal::KeyMatcher<M>(inner_matcher);
2864}
2865
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002866// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
2867// matches first_matcher and whose 'second' field matches second_matcher. For
2868// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
2869// to match a std::map<int, string> that contains exactly one element whose key
2870// is >= 5 and whose value equals "foo".
2871template <typename FirstMatcher, typename SecondMatcher>
2872inline internal::PairMatcher<FirstMatcher, SecondMatcher>
2873Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
2874 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
2875 first_matcher, second_matcher);
2876}
2877
shiqiane35fdd92008-12-10 05:08:54 +00002878// Returns a predicate that is satisfied by anything that matches the
2879// given matcher.
2880template <typename M>
2881inline internal::MatcherAsPredicate<M> Matches(M matcher) {
2882 return internal::MatcherAsPredicate<M>(matcher);
2883}
2884
zhanyong.wanb8243162009-06-04 05:48:20 +00002885// Returns true iff the value matches the matcher.
2886template <typename T, typename M>
2887inline bool Value(const T& value, M matcher) {
2888 return testing::Matches(matcher)(value);
2889}
2890
zhanyong.wan34b034c2010-03-05 21:23:23 +00002891// Matches the value against the given matcher and explains the match
2892// result to listener.
2893template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00002894inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00002895 M matcher, const T& value, MatchResultListener* listener) {
2896 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
2897}
2898
zhanyong.wanbf550852009-06-09 06:09:53 +00002899// AllArgs(m) is a synonym of m. This is useful in
2900//
2901// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
2902//
2903// which is easier to read than
2904//
2905// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
2906template <typename InnerMatcher>
2907inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
2908
shiqiane35fdd92008-12-10 05:08:54 +00002909// These macros allow using matchers to check values in Google Test
2910// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
2911// succeed iff the value matches the matcher. If the assertion fails,
2912// the value and the description of the matcher will be printed.
2913#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
2914 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2915#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
2916 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2917
2918} // namespace testing
2919
2920#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_