blob: 7ca2f007938d2403f4232eb9d3af71e8a3b5b203 [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.wan33605ba2010-04-22 23:37:47 +00001950// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00001951template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00001952class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00001953 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>
zhanyong.wan33605ba2010-04-22 23:37:47 +00001961 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00001962 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00001963 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00001964
zhanyong.wan33605ba2010-04-22 23:37:47 +00001965 // Checks whether:
1966 // * All elements in the container match, if all_elements_should_match.
1967 // * Any element in the container matches, if !all_elements_should_match.
1968 bool MatchAndExplainImpl(bool all_elements_should_match,
1969 Container container,
1970 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00001971 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00001972 size_t i = 0;
1973 for (typename StlContainer::const_iterator it = stl_container.begin();
1974 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001975 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00001976 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
1977
1978 if (matches != all_elements_should_match) {
1979 *listener << "whose element #" << i
1980 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001981 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00001982 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00001983 }
1984 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00001985 return all_elements_should_match;
1986 }
1987
1988 protected:
1989 const Matcher<const Element&> inner_matcher_;
1990
1991 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
1992};
1993
1994// Implements Contains(element_matcher) for the given argument type Container.
1995// Symmetric to EachMatcherImpl.
1996template <typename Container>
1997class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
1998 public:
1999 template <typename InnerMatcher>
2000 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2001 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2002
2003 // Describes what this matcher does.
2004 virtual void DescribeTo(::std::ostream* os) const {
2005 *os << "contains at least one element that ";
2006 this->inner_matcher_.DescribeTo(os);
2007 }
2008
2009 virtual void DescribeNegationTo(::std::ostream* os) const {
2010 *os << "doesn't contain any element that ";
2011 this->inner_matcher_.DescribeTo(os);
2012 }
2013
2014 virtual bool MatchAndExplain(Container container,
2015 MatchResultListener* listener) const {
2016 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002017 }
2018
2019 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002020 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002021};
2022
zhanyong.wan33605ba2010-04-22 23:37:47 +00002023// Implements Each(element_matcher) for the given argument type Container.
2024// Symmetric to ContainsMatcherImpl.
2025template <typename Container>
2026class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2027 public:
2028 template <typename InnerMatcher>
2029 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2030 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2031
2032 // Describes what this matcher does.
2033 virtual void DescribeTo(::std::ostream* os) const {
2034 *os << "only contains elements that ";
2035 this->inner_matcher_.DescribeTo(os);
2036 }
2037
2038 virtual void DescribeNegationTo(::std::ostream* os) const {
2039 *os << "contains some element that ";
2040 this->inner_matcher_.DescribeNegationTo(os);
2041 }
2042
2043 virtual bool MatchAndExplain(Container container,
2044 MatchResultListener* listener) const {
2045 return this->MatchAndExplainImpl(true, container, listener);
2046 }
2047
2048 private:
2049 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2050};
2051
zhanyong.wanb8243162009-06-04 05:48:20 +00002052// Implements polymorphic Contains(element_matcher).
2053template <typename M>
2054class ContainsMatcher {
2055 public:
2056 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2057
2058 template <typename Container>
2059 operator Matcher<Container>() const {
2060 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2061 }
2062
2063 private:
2064 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002065
2066 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002067};
2068
zhanyong.wan33605ba2010-04-22 23:37:47 +00002069// Implements polymorphic Each(element_matcher).
2070template <typename M>
2071class EachMatcher {
2072 public:
2073 explicit EachMatcher(M m) : inner_matcher_(m) {}
2074
2075 template <typename Container>
2076 operator Matcher<Container>() const {
2077 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2078 }
2079
2080 private:
2081 const M inner_matcher_;
2082
2083 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2084};
2085
zhanyong.wanb5937da2009-07-16 20:26:41 +00002086// Implements Key(inner_matcher) for the given argument pair type.
2087// Key(inner_matcher) matches an std::pair whose 'first' field matches
2088// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2089// std::map that contains at least one element whose key is >= 5.
2090template <typename PairType>
2091class KeyMatcherImpl : public MatcherInterface<PairType> {
2092 public:
2093 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
2094 typedef typename RawPairType::first_type KeyType;
2095
2096 template <typename InnerMatcher>
2097 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2098 : inner_matcher_(
2099 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2100 }
2101
2102 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002103 virtual bool MatchAndExplain(PairType key_value,
2104 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002105 StringMatchResultListener inner_listener;
2106 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2107 &inner_listener);
2108 const internal::string explanation = inner_listener.str();
2109 if (explanation != "") {
2110 *listener << "whose first field is a value " << explanation;
2111 }
2112 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002113 }
2114
2115 // Describes what this matcher does.
2116 virtual void DescribeTo(::std::ostream* os) const {
2117 *os << "has a key that ";
2118 inner_matcher_.DescribeTo(os);
2119 }
2120
2121 // Describes what the negation of this matcher does.
2122 virtual void DescribeNegationTo(::std::ostream* os) const {
2123 *os << "doesn't have a key that ";
2124 inner_matcher_.DescribeTo(os);
2125 }
2126
zhanyong.wanb5937da2009-07-16 20:26:41 +00002127 private:
2128 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002129
2130 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002131};
2132
2133// Implements polymorphic Key(matcher_for_key).
2134template <typename M>
2135class KeyMatcher {
2136 public:
2137 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2138
2139 template <typename PairType>
2140 operator Matcher<PairType>() const {
2141 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2142 }
2143
2144 private:
2145 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002146
2147 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002148};
2149
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002150// Implements Pair(first_matcher, second_matcher) for the given argument pair
2151// type with its two matchers. See Pair() function below.
2152template <typename PairType>
2153class PairMatcherImpl : public MatcherInterface<PairType> {
2154 public:
2155 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
2156 typedef typename RawPairType::first_type FirstType;
2157 typedef typename RawPairType::second_type SecondType;
2158
2159 template <typename FirstMatcher, typename SecondMatcher>
2160 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2161 : first_matcher_(
2162 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2163 second_matcher_(
2164 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2165 }
2166
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002167 // Describes what this matcher does.
2168 virtual void DescribeTo(::std::ostream* os) const {
2169 *os << "has a first field that ";
2170 first_matcher_.DescribeTo(os);
2171 *os << ", and has a second field that ";
2172 second_matcher_.DescribeTo(os);
2173 }
2174
2175 // Describes what the negation of this matcher does.
2176 virtual void DescribeNegationTo(::std::ostream* os) const {
2177 *os << "has a first field that ";
2178 first_matcher_.DescribeNegationTo(os);
2179 *os << ", or has a second field that ";
2180 second_matcher_.DescribeNegationTo(os);
2181 }
2182
zhanyong.wan82113312010-01-08 21:55:40 +00002183 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2184 // matches second_matcher.
2185 virtual bool MatchAndExplain(PairType a_pair,
2186 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002187 if (!listener->IsInterested()) {
2188 // If the listener is not interested, we don't need to construct the
2189 // explanation.
2190 return first_matcher_.Matches(a_pair.first) &&
2191 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00002192 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002193 StringMatchResultListener first_inner_listener;
2194 if (!first_matcher_.MatchAndExplain(a_pair.first,
2195 &first_inner_listener)) {
2196 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002197 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002198 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002199 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002200 StringMatchResultListener second_inner_listener;
2201 if (!second_matcher_.MatchAndExplain(a_pair.second,
2202 &second_inner_listener)) {
2203 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002204 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002205 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002206 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002207 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
2208 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00002209 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002210 }
2211
2212 private:
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002213 void ExplainSuccess(const internal::string& first_explanation,
2214 const internal::string& second_explanation,
2215 MatchResultListener* listener) const {
2216 *listener << "whose both fields match";
2217 if (first_explanation != "") {
2218 *listener << ", where the first field is a value " << first_explanation;
2219 }
2220 if (second_explanation != "") {
2221 *listener << ", ";
2222 if (first_explanation != "") {
2223 *listener << "and ";
2224 } else {
2225 *listener << "where ";
2226 }
2227 *listener << "the second field is a value " << second_explanation;
2228 }
2229 }
2230
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002231 const Matcher<const FirstType&> first_matcher_;
2232 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002233
2234 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002235};
2236
2237// Implements polymorphic Pair(first_matcher, second_matcher).
2238template <typename FirstMatcher, typename SecondMatcher>
2239class PairMatcher {
2240 public:
2241 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2242 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2243
2244 template <typename PairType>
2245 operator Matcher<PairType> () const {
2246 return MakeMatcher(
2247 new PairMatcherImpl<PairType>(
2248 first_matcher_, second_matcher_));
2249 }
2250
2251 private:
2252 const FirstMatcher first_matcher_;
2253 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002254
2255 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002256};
2257
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002258// Implements ElementsAre() and ElementsAreArray().
2259template <typename Container>
2260class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2261 public:
2262 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
2263 typedef internal::StlContainerView<RawContainer> View;
2264 typedef typename View::type StlContainer;
2265 typedef typename View::const_reference StlContainerReference;
2266 typedef typename StlContainer::value_type Element;
2267
2268 // Constructs the matcher from a sequence of element values or
2269 // element matchers.
2270 template <typename InputIter>
zhanyong.wan32de5f52009-12-23 00:13:23 +00002271 ElementsAreMatcherImpl(InputIter first, size_t a_count) {
2272 matchers_.reserve(a_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002273 InputIter it = first;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002274 for (size_t i = 0; i != a_count; ++i, ++it) {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002275 matchers_.push_back(MatcherCast<const Element&>(*it));
2276 }
2277 }
2278
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002279 // Describes what this matcher does.
2280 virtual void DescribeTo(::std::ostream* os) const {
2281 if (count() == 0) {
2282 *os << "is empty";
2283 } else if (count() == 1) {
2284 *os << "has 1 element that ";
2285 matchers_[0].DescribeTo(os);
2286 } else {
2287 *os << "has " << Elements(count()) << " where\n";
2288 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002289 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002290 matchers_[i].DescribeTo(os);
2291 if (i + 1 < count()) {
2292 *os << ",\n";
2293 }
2294 }
2295 }
2296 }
2297
2298 // Describes what the negation of this matcher does.
2299 virtual void DescribeNegationTo(::std::ostream* os) const {
2300 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002301 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002302 return;
2303 }
2304
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002305 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002306 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002307 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002308 matchers_[i].DescribeNegationTo(os);
2309 if (i + 1 < count()) {
2310 *os << ", or\n";
2311 }
2312 }
2313 }
2314
zhanyong.wan82113312010-01-08 21:55:40 +00002315 virtual bool MatchAndExplain(Container container,
2316 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002317 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002318 const size_t actual_count = stl_container.size();
2319 if (actual_count != count()) {
2320 // The element count doesn't match. If the container is empty,
2321 // there's no need to explain anything as Google Mock already
2322 // prints the empty container. Otherwise we just need to show
2323 // how many elements there actually are.
2324 if (actual_count != 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002325 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002326 }
zhanyong.wan82113312010-01-08 21:55:40 +00002327 return false;
2328 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002329
zhanyong.wan82113312010-01-08 21:55:40 +00002330 typename StlContainer::const_iterator it = stl_container.begin();
2331 // explanations[i] is the explanation of the element at index i.
2332 std::vector<internal::string> explanations(count());
2333 for (size_t i = 0; i != count(); ++it, ++i) {
2334 StringMatchResultListener s;
2335 if (matchers_[i].MatchAndExplain(*it, &s)) {
2336 explanations[i] = s.str();
2337 } else {
2338 // The container has the right size but the i-th element
2339 // doesn't match its expectation.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002340 *listener << "whose element #" << i << " doesn't match";
2341 PrintIfNotEmpty(s.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002342 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002343 }
2344 }
zhanyong.wan82113312010-01-08 21:55:40 +00002345
2346 // Every element matches its expectation. We need to explain why
2347 // (the obvious ones can be skipped).
zhanyong.wan82113312010-01-08 21:55:40 +00002348 bool reason_printed = false;
2349 for (size_t i = 0; i != count(); ++i) {
2350 const internal::string& s = explanations[i];
2351 if (!s.empty()) {
2352 if (reason_printed) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002353 *listener << ",\nand ";
zhanyong.wan82113312010-01-08 21:55:40 +00002354 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002355 *listener << "whose element #" << i << " matches, " << s;
zhanyong.wan82113312010-01-08 21:55:40 +00002356 reason_printed = true;
2357 }
2358 }
2359
2360 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002361 }
2362
2363 private:
2364 static Message Elements(size_t count) {
2365 return Message() << count << (count == 1 ? " element" : " elements");
2366 }
2367
2368 size_t count() const { return matchers_.size(); }
2369 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002370
2371 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002372};
2373
2374// Implements ElementsAre() of 0 arguments.
2375class ElementsAreMatcher0 {
2376 public:
2377 ElementsAreMatcher0() {}
2378
2379 template <typename Container>
2380 operator Matcher<Container>() const {
2381 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2382 RawContainer;
2383 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2384 Element;
2385
2386 const Matcher<const Element&>* const matchers = NULL;
2387 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 0));
2388 }
2389};
2390
2391// Implements ElementsAreArray().
2392template <typename T>
2393class ElementsAreArrayMatcher {
2394 public:
2395 ElementsAreArrayMatcher(const T* first, size_t count) :
2396 first_(first), count_(count) {}
2397
2398 template <typename Container>
2399 operator Matcher<Container>() const {
2400 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2401 RawContainer;
2402 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2403 Element;
2404
2405 return MakeMatcher(new ElementsAreMatcherImpl<Container>(first_, count_));
2406 }
2407
2408 private:
2409 const T* const first_;
2410 const size_t count_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002411
2412 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002413};
2414
2415// Constants denoting interpolations in a matcher description string.
2416const int kTupleInterpolation = -1; // "%(*)s"
2417const int kPercentInterpolation = -2; // "%%"
2418const int kInvalidInterpolation = -3; // "%" followed by invalid text
2419
2420// Records the location and content of an interpolation.
2421struct Interpolation {
2422 Interpolation(const char* start, const char* end, int param)
2423 : start_pos(start), end_pos(end), param_index(param) {}
2424
2425 // Points to the start of the interpolation (the '%' character).
2426 const char* start_pos;
2427 // Points to the first character after the interpolation.
2428 const char* end_pos;
2429 // 0-based index of the interpolated matcher parameter;
2430 // kTupleInterpolation for "%(*)s"; kPercentInterpolation for "%%".
2431 int param_index;
2432};
2433
2434typedef ::std::vector<Interpolation> Interpolations;
2435
2436// Parses a matcher description string and returns a vector of
2437// interpolations that appear in the string; generates non-fatal
2438// failures iff 'description' is an invalid matcher description.
2439// 'param_names' is a NULL-terminated array of parameter names in the
2440// order they appear in the MATCHER_P*() parameter list.
2441Interpolations ValidateMatcherDescription(
2442 const char* param_names[], const char* description);
2443
2444// Returns the actual matcher description, given the matcher name,
2445// user-supplied description template string, interpolations in the
2446// string, and the printed values of the matcher parameters.
2447string FormatMatcherDescription(
2448 const char* matcher_name, const char* description,
2449 const Interpolations& interp, const Strings& param_values);
2450
shiqiane35fdd92008-12-10 05:08:54 +00002451} // namespace internal
2452
2453// Implements MatcherCast().
2454template <typename T, typename M>
2455inline Matcher<T> MatcherCast(M matcher) {
2456 return internal::MatcherCastImpl<T, M>::Cast(matcher);
2457}
2458
2459// _ is a matcher that matches anything of any type.
2460//
2461// This definition is fine as:
2462//
2463// 1. The C++ standard permits using the name _ in a namespace that
2464// is not the global namespace or ::std.
2465// 2. The AnythingMatcher class has no data member or constructor,
2466// so it's OK to create global variables of this type.
2467// 3. c-style has approved of using _ in this case.
2468const internal::AnythingMatcher _ = {};
2469// Creates a matcher that matches any value of the given type T.
2470template <typename T>
2471inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2472
2473// Creates a matcher that matches any value of the given type T.
2474template <typename T>
2475inline Matcher<T> An() { return A<T>(); }
2476
2477// Creates a polymorphic matcher that matches anything equal to x.
2478// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2479// wouldn't compile.
2480template <typename T>
2481inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2482
2483// Constructs a Matcher<T> from a 'value' of type T. The constructed
2484// matcher matches any value that's equal to 'value'.
2485template <typename T>
2486Matcher<T>::Matcher(T value) { *this = Eq(value); }
2487
2488// Creates a monomorphic matcher that matches anything with type Lhs
2489// and equal to rhs. A user may need to use this instead of Eq(...)
2490// in order to resolve an overloading ambiguity.
2491//
2492// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2493// or Matcher<T>(x), but more readable than the latter.
2494//
2495// We could define similar monomorphic matchers for other comparison
2496// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2497// it yet as those are used much less than Eq() in practice. A user
2498// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2499// for example.
2500template <typename Lhs, typename Rhs>
2501inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2502
2503// Creates a polymorphic matcher that matches anything >= x.
2504template <typename Rhs>
2505inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2506 return internal::GeMatcher<Rhs>(x);
2507}
2508
2509// Creates a polymorphic matcher that matches anything > x.
2510template <typename Rhs>
2511inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2512 return internal::GtMatcher<Rhs>(x);
2513}
2514
2515// Creates a polymorphic matcher that matches anything <= x.
2516template <typename Rhs>
2517inline internal::LeMatcher<Rhs> Le(Rhs x) {
2518 return internal::LeMatcher<Rhs>(x);
2519}
2520
2521// Creates a polymorphic matcher that matches anything < x.
2522template <typename Rhs>
2523inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2524 return internal::LtMatcher<Rhs>(x);
2525}
2526
2527// Creates a polymorphic matcher that matches anything != x.
2528template <typename Rhs>
2529inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2530 return internal::NeMatcher<Rhs>(x);
2531}
2532
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002533// Creates a polymorphic matcher that matches any NULL pointer.
2534inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2535 return MakePolymorphicMatcher(internal::IsNullMatcher());
2536}
2537
shiqiane35fdd92008-12-10 05:08:54 +00002538// Creates a polymorphic matcher that matches any non-NULL pointer.
2539// This is convenient as Not(NULL) doesn't compile (the compiler
2540// thinks that that expression is comparing a pointer with an integer).
2541inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2542 return MakePolymorphicMatcher(internal::NotNullMatcher());
2543}
2544
2545// Creates a polymorphic matcher that matches any argument that
2546// references variable x.
2547template <typename T>
2548inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2549 return internal::RefMatcher<T&>(x);
2550}
2551
2552// Creates a matcher that matches any double argument approximately
2553// equal to rhs, where two NANs are considered unequal.
2554inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2555 return internal::FloatingEqMatcher<double>(rhs, false);
2556}
2557
2558// Creates a matcher that matches any double argument approximately
2559// equal to rhs, including NaN values when rhs is NaN.
2560inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2561 return internal::FloatingEqMatcher<double>(rhs, true);
2562}
2563
2564// Creates a matcher that matches any float argument approximately
2565// equal to rhs, where two NANs are considered unequal.
2566inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2567 return internal::FloatingEqMatcher<float>(rhs, false);
2568}
2569
2570// Creates a matcher that matches any double argument approximately
2571// equal to rhs, including NaN values when rhs is NaN.
2572inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2573 return internal::FloatingEqMatcher<float>(rhs, true);
2574}
2575
2576// Creates a matcher that matches a pointer (raw or smart) that points
2577// to a value that matches inner_matcher.
2578template <typename InnerMatcher>
2579inline internal::PointeeMatcher<InnerMatcher> Pointee(
2580 const InnerMatcher& inner_matcher) {
2581 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2582}
2583
2584// Creates a matcher that matches an object whose given field matches
2585// 'matcher'. For example,
2586// Field(&Foo::number, Ge(5))
2587// matches a Foo object x iff x.number >= 5.
2588template <typename Class, typename FieldType, typename FieldMatcher>
2589inline PolymorphicMatcher<
2590 internal::FieldMatcher<Class, FieldType> > Field(
2591 FieldType Class::*field, const FieldMatcher& matcher) {
2592 return MakePolymorphicMatcher(
2593 internal::FieldMatcher<Class, FieldType>(
2594 field, MatcherCast<const FieldType&>(matcher)));
2595 // The call to MatcherCast() is required for supporting inner
2596 // matchers of compatible types. For example, it allows
2597 // Field(&Foo::bar, m)
2598 // to compile where bar is an int32 and m is a matcher for int64.
2599}
2600
2601// Creates a matcher that matches an object whose given property
2602// matches 'matcher'. For example,
2603// Property(&Foo::str, StartsWith("hi"))
2604// matches a Foo object x iff x.str() starts with "hi".
2605template <typename Class, typename PropertyType, typename PropertyMatcher>
2606inline PolymorphicMatcher<
2607 internal::PropertyMatcher<Class, PropertyType> > Property(
2608 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2609 return MakePolymorphicMatcher(
2610 internal::PropertyMatcher<Class, PropertyType>(
2611 property,
zhanyong.wane0d051e2009-02-19 00:33:37 +00002612 MatcherCast<GMOCK_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002613 // The call to MatcherCast() is required for supporting inner
2614 // matchers of compatible types. For example, it allows
2615 // Property(&Foo::bar, m)
2616 // to compile where bar() returns an int32 and m is a matcher for int64.
2617}
2618
2619// Creates a matcher that matches an object iff the result of applying
2620// a callable to x matches 'matcher'.
2621// For example,
2622// ResultOf(f, StartsWith("hi"))
2623// matches a Foo object x iff f(x) starts with "hi".
2624// callable parameter can be a function, function pointer, or a functor.
2625// Callable has to satisfy the following conditions:
2626// * It is required to keep no state affecting the results of
2627// the calls on it and make no assumptions about how many calls
2628// will be made. Any state it keeps must be protected from the
2629// concurrent access.
2630// * If it is a function object, it has to define type result_type.
2631// We recommend deriving your functor classes from std::unary_function.
2632template <typename Callable, typename ResultOfMatcher>
2633internal::ResultOfMatcher<Callable> ResultOf(
2634 Callable callable, const ResultOfMatcher& matcher) {
2635 return internal::ResultOfMatcher<Callable>(
2636 callable,
2637 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2638 matcher));
2639 // The call to MatcherCast() is required for supporting inner
2640 // matchers of compatible types. For example, it allows
2641 // ResultOf(Function, m)
2642 // to compile where Function() returns an int32 and m is a matcher for int64.
2643}
2644
2645// String matchers.
2646
2647// Matches a string equal to str.
2648inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2649 StrEq(const internal::string& str) {
2650 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2651 str, true, true));
2652}
2653
2654// Matches a string not equal to str.
2655inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2656 StrNe(const internal::string& str) {
2657 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2658 str, false, true));
2659}
2660
2661// Matches a string equal to str, ignoring case.
2662inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2663 StrCaseEq(const internal::string& str) {
2664 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2665 str, true, false));
2666}
2667
2668// Matches a string not equal to str, ignoring case.
2669inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2670 StrCaseNe(const internal::string& str) {
2671 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2672 str, false, false));
2673}
2674
2675// Creates a matcher that matches any string, std::string, or C string
2676// that contains the given substring.
2677inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2678 HasSubstr(const internal::string& substring) {
2679 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
2680 substring));
2681}
2682
2683// Matches a string that starts with 'prefix' (case-sensitive).
2684inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
2685 StartsWith(const internal::string& prefix) {
2686 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
2687 prefix));
2688}
2689
2690// Matches a string that ends with 'suffix' (case-sensitive).
2691inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
2692 EndsWith(const internal::string& suffix) {
2693 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
2694 suffix));
2695}
2696
shiqiane35fdd92008-12-10 05:08:54 +00002697// Matches a string that fully matches regular expression 'regex'.
2698// The matcher takes ownership of 'regex'.
2699inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2700 const internal::RE* regex) {
2701 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2702}
2703inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2704 const internal::string& regex) {
2705 return MatchesRegex(new internal::RE(regex));
2706}
2707
2708// Matches a string that contains regular expression 'regex'.
2709// The matcher takes ownership of 'regex'.
2710inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2711 const internal::RE* regex) {
2712 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2713}
2714inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2715 const internal::string& regex) {
2716 return ContainsRegex(new internal::RE(regex));
2717}
2718
shiqiane35fdd92008-12-10 05:08:54 +00002719#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2720// Wide string matchers.
2721
2722// Matches a string equal to str.
2723inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2724 StrEq(const internal::wstring& str) {
2725 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2726 str, true, true));
2727}
2728
2729// Matches a string not equal to str.
2730inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2731 StrNe(const internal::wstring& str) {
2732 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2733 str, false, true));
2734}
2735
2736// Matches a string equal to str, ignoring case.
2737inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2738 StrCaseEq(const internal::wstring& str) {
2739 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2740 str, true, false));
2741}
2742
2743// Matches a string not equal to str, ignoring case.
2744inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2745 StrCaseNe(const internal::wstring& str) {
2746 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2747 str, false, false));
2748}
2749
2750// Creates a matcher that matches any wstring, std::wstring, or C wide string
2751// that contains the given substring.
2752inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2753 HasSubstr(const internal::wstring& substring) {
2754 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2755 substring));
2756}
2757
2758// Matches a string that starts with 'prefix' (case-sensitive).
2759inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2760 StartsWith(const internal::wstring& prefix) {
2761 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2762 prefix));
2763}
2764
2765// Matches a string that ends with 'suffix' (case-sensitive).
2766inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2767 EndsWith(const internal::wstring& suffix) {
2768 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2769 suffix));
2770}
2771
2772#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2773
2774// Creates a polymorphic matcher that matches a 2-tuple where the
2775// first field == the second field.
2776inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2777
2778// Creates a polymorphic matcher that matches a 2-tuple where the
2779// first field >= the second field.
2780inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2781
2782// Creates a polymorphic matcher that matches a 2-tuple where the
2783// first field > the second field.
2784inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2785
2786// Creates a polymorphic matcher that matches a 2-tuple where the
2787// first field <= the second field.
2788inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2789
2790// Creates a polymorphic matcher that matches a 2-tuple where the
2791// first field < the second field.
2792inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2793
2794// Creates a polymorphic matcher that matches a 2-tuple where the
2795// first field != the second field.
2796inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2797
2798// Creates a matcher that matches any value of type T that m doesn't
2799// match.
2800template <typename InnerMatcher>
2801inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2802 return internal::NotMatcher<InnerMatcher>(m);
2803}
2804
2805// Creates a matcher that matches any value that matches all of the
2806// given matchers.
2807//
2808// For now we only support up to 5 matchers. Support for more
2809// matchers can be added as needed, or the user can use nested
2810// AllOf()s.
2811template <typename Matcher1, typename Matcher2>
2812inline internal::BothOfMatcher<Matcher1, Matcher2>
2813AllOf(Matcher1 m1, Matcher2 m2) {
2814 return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2);
2815}
2816
2817template <typename Matcher1, typename Matcher2, typename Matcher3>
2818inline internal::BothOfMatcher<Matcher1,
2819 internal::BothOfMatcher<Matcher2, Matcher3> >
2820AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2821 return AllOf(m1, AllOf(m2, m3));
2822}
2823
2824template <typename Matcher1, typename Matcher2, typename Matcher3,
2825 typename Matcher4>
2826inline internal::BothOfMatcher<Matcher1,
2827 internal::BothOfMatcher<Matcher2,
2828 internal::BothOfMatcher<Matcher3, Matcher4> > >
2829AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2830 return AllOf(m1, AllOf(m2, m3, m4));
2831}
2832
2833template <typename Matcher1, typename Matcher2, typename Matcher3,
2834 typename Matcher4, typename Matcher5>
2835inline internal::BothOfMatcher<Matcher1,
2836 internal::BothOfMatcher<Matcher2,
2837 internal::BothOfMatcher<Matcher3,
2838 internal::BothOfMatcher<Matcher4, Matcher5> > > >
2839AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2840 return AllOf(m1, AllOf(m2, m3, m4, m5));
2841}
2842
2843// Creates a matcher that matches any value that matches at least one
2844// of the given matchers.
2845//
2846// For now we only support up to 5 matchers. Support for more
2847// matchers can be added as needed, or the user can use nested
2848// AnyOf()s.
2849template <typename Matcher1, typename Matcher2>
2850inline internal::EitherOfMatcher<Matcher1, Matcher2>
2851AnyOf(Matcher1 m1, Matcher2 m2) {
2852 return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2);
2853}
2854
2855template <typename Matcher1, typename Matcher2, typename Matcher3>
2856inline internal::EitherOfMatcher<Matcher1,
2857 internal::EitherOfMatcher<Matcher2, Matcher3> >
2858AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2859 return AnyOf(m1, AnyOf(m2, m3));
2860}
2861
2862template <typename Matcher1, typename Matcher2, typename Matcher3,
2863 typename Matcher4>
2864inline internal::EitherOfMatcher<Matcher1,
2865 internal::EitherOfMatcher<Matcher2,
2866 internal::EitherOfMatcher<Matcher3, Matcher4> > >
2867AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2868 return AnyOf(m1, AnyOf(m2, m3, m4));
2869}
2870
2871template <typename Matcher1, typename Matcher2, typename Matcher3,
2872 typename Matcher4, typename Matcher5>
2873inline internal::EitherOfMatcher<Matcher1,
2874 internal::EitherOfMatcher<Matcher2,
2875 internal::EitherOfMatcher<Matcher3,
2876 internal::EitherOfMatcher<Matcher4, Matcher5> > > >
2877AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2878 return AnyOf(m1, AnyOf(m2, m3, m4, m5));
2879}
2880
2881// Returns a matcher that matches anything that satisfies the given
2882// predicate. The predicate can be any unary function or functor
2883// whose return type can be implicitly converted to bool.
2884template <typename Predicate>
2885inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
2886Truly(Predicate pred) {
2887 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
2888}
2889
zhanyong.wan6a896b52009-01-16 01:13:50 +00002890// Returns a matcher that matches an equal container.
2891// This matcher behaves like Eq(), but in the event of mismatch lists the
2892// values that are included in one container but not the other. (Duplicate
2893// values and order differences are not explained.)
2894template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00002895inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wanb8243162009-06-04 05:48:20 +00002896 GMOCK_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00002897 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002898 // This following line is for working around a bug in MSVC 8.0,
2899 // which causes Container to be a const type sometimes.
2900 typedef GMOCK_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00002901 return MakePolymorphicMatcher(
2902 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00002903}
2904
2905// Matches an STL-style container or a native array that contains at
2906// least one element matching the given value or matcher.
2907//
2908// Examples:
2909// ::std::set<int> page_ids;
2910// page_ids.insert(3);
2911// page_ids.insert(1);
2912// EXPECT_THAT(page_ids, Contains(1));
2913// EXPECT_THAT(page_ids, Contains(Gt(2)));
2914// EXPECT_THAT(page_ids, Not(Contains(4)));
2915//
2916// ::std::map<int, size_t> page_lengths;
2917// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00002918// EXPECT_THAT(page_lengths,
2919// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00002920//
2921// const char* user_ids[] = { "joe", "mike", "tom" };
2922// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
2923template <typename M>
2924inline internal::ContainsMatcher<M> Contains(M matcher) {
2925 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002926}
2927
zhanyong.wan33605ba2010-04-22 23:37:47 +00002928// Matches an STL-style container or a native array that contains only
2929// elements matching the given value or matcher.
2930//
2931// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
2932// the messages are different.
2933//
2934// Examples:
2935// ::std::set<int> page_ids;
2936// // Each(m) matches an empty container, regardless of what m is.
2937// EXPECT_THAT(page_ids, Each(Eq(1)));
2938// EXPECT_THAT(page_ids, Each(Eq(77)));
2939//
2940// page_ids.insert(3);
2941// EXPECT_THAT(page_ids, Each(Gt(0)));
2942// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
2943// page_ids.insert(1);
2944// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
2945//
2946// ::std::map<int, size_t> page_lengths;
2947// page_lengths[1] = 100;
2948// page_lengths[2] = 200;
2949// page_lengths[3] = 300;
2950// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
2951// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
2952//
2953// const char* user_ids[] = { "joe", "mike", "tom" };
2954// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
2955template <typename M>
2956inline internal::EachMatcher<M> Each(M matcher) {
2957 return internal::EachMatcher<M>(matcher);
2958}
2959
zhanyong.wanb5937da2009-07-16 20:26:41 +00002960// Key(inner_matcher) matches an std::pair whose 'first' field matches
2961// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2962// std::map that contains at least one element whose key is >= 5.
2963template <typename M>
2964inline internal::KeyMatcher<M> Key(M inner_matcher) {
2965 return internal::KeyMatcher<M>(inner_matcher);
2966}
2967
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002968// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
2969// matches first_matcher and whose 'second' field matches second_matcher. For
2970// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
2971// to match a std::map<int, string> that contains exactly one element whose key
2972// is >= 5 and whose value equals "foo".
2973template <typename FirstMatcher, typename SecondMatcher>
2974inline internal::PairMatcher<FirstMatcher, SecondMatcher>
2975Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
2976 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
2977 first_matcher, second_matcher);
2978}
2979
shiqiane35fdd92008-12-10 05:08:54 +00002980// Returns a predicate that is satisfied by anything that matches the
2981// given matcher.
2982template <typename M>
2983inline internal::MatcherAsPredicate<M> Matches(M matcher) {
2984 return internal::MatcherAsPredicate<M>(matcher);
2985}
2986
zhanyong.wanb8243162009-06-04 05:48:20 +00002987// Returns true iff the value matches the matcher.
2988template <typename T, typename M>
2989inline bool Value(const T& value, M matcher) {
2990 return testing::Matches(matcher)(value);
2991}
2992
zhanyong.wan34b034c2010-03-05 21:23:23 +00002993// Matches the value against the given matcher and explains the match
2994// result to listener.
2995template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00002996inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00002997 M matcher, const T& value, MatchResultListener* listener) {
2998 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
2999}
3000
zhanyong.wanbf550852009-06-09 06:09:53 +00003001// AllArgs(m) is a synonym of m. This is useful in
3002//
3003// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
3004//
3005// which is easier to read than
3006//
3007// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
3008template <typename InnerMatcher>
3009inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
3010
shiqiane35fdd92008-12-10 05:08:54 +00003011// These macros allow using matchers to check values in Google Test
3012// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
3013// succeed iff the value matches the matcher. If the assertion fails,
3014// the value and the description of the matcher will be printed.
3015#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
3016 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3017#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
3018 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3019
3020} // namespace testing
3021
3022#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_