blob: fbbf5811d2610a7ce898351cde334e21f0b35d33 [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
shiqiane35fdd92008-12-10 05:08:54 +000048#include <gmock/internal/gmock-internal-utils.h>
49#include <gmock/internal/gmock-port.h>
50#include <gtest/gtest.h>
51
52namespace testing {
53
54// To implement a matcher Foo for type T, define:
55// 1. a class FooMatcherImpl that implements the
56// MatcherInterface<T> interface, and
57// 2. a factory function that creates a Matcher<T> object from a
58// FooMatcherImpl*.
59//
60// The two-level delegation design makes it possible to allow a user
61// to write "v" instead of "Eq(v)" where a Matcher is expected, which
62// is impossible if we pass matchers by pointers. It also eases
63// ownership management as Matcher objects can now be copied like
64// plain values.
65
zhanyong.wan82113312010-01-08 21:55:40 +000066// MatchResultListener is an abstract class. Its << operator can be
67// used by a matcher to explain why a value matches or doesn't match.
68//
69// TODO(wan@google.com): add method
70// bool InterestedInWhy(bool result) const;
71// to indicate whether the listener is interested in why the match
72// result is 'result'.
73class MatchResultListener {
74 public:
75 // Creates a listener object with the given underlying ostream. The
76 // listener does not own the ostream.
77 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
78 virtual ~MatchResultListener() = 0; // Makes this class abstract.
79
80 // Streams x to the underlying ostream; does nothing if the ostream
81 // is NULL.
82 template <typename T>
83 MatchResultListener& operator<<(const T& x) {
84 if (stream_ != NULL)
85 *stream_ << x;
86 return *this;
87 }
88
89 // Returns the underlying ostream.
90 ::std::ostream* stream() { return stream_; }
91
zhanyong.wana862f1d2010-03-15 21:23:04 +000092 // Returns true iff the listener is interested in an explanation of
93 // the match result. A matcher's MatchAndExplain() method can use
94 // this information to avoid generating the explanation when no one
95 // intends to hear it.
96 bool IsInterested() const { return stream_ != NULL; }
97
zhanyong.wan82113312010-01-08 21:55:40 +000098 private:
99 ::std::ostream* const stream_;
100
101 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
102};
103
104inline MatchResultListener::~MatchResultListener() {
105}
106
shiqiane35fdd92008-12-10 05:08:54 +0000107// The implementation of a matcher.
108template <typename T>
109class MatcherInterface {
110 public:
111 virtual ~MatcherInterface() {}
112
zhanyong.wan82113312010-01-08 21:55:40 +0000113 // Returns true iff the matcher matches x; also explains the match
zhanyong.wana862f1d2010-03-15 21:23:04 +0000114 // result to 'listener', in the form of a non-restrictive relative
115 // clause ("which ...", "whose ...", etc) that describes x. For
116 // example, the MatchAndExplain() method of the Pointee(...) matcher
117 // should generate an explanation like "which points to ...".
zhanyong.wan82113312010-01-08 21:55:40 +0000118 //
zhanyong.wandb22c222010-01-28 21:52:29 +0000119 // You should override this method when defining a new matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000120 //
121 // It's the responsibility of the caller (Google Mock) to guarantee
122 // that 'listener' is not NULL. This helps to simplify a matcher's
123 // implementation when it doesn't care about the performance, as it
124 // can talk to 'listener' without checking its validity first.
125 // However, in order to implement dummy listeners efficiently,
126 // listener->stream() may be NULL.
zhanyong.wandb22c222010-01-28 21:52:29 +0000127 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
shiqiane35fdd92008-12-10 05:08:54 +0000128
zhanyong.wana862f1d2010-03-15 21:23:04 +0000129 // Describes this matcher to an ostream. The function should print
130 // a verb phrase that describes the property a value matching this
131 // matcher should have. The subject of the verb phrase is the value
132 // being matched. For example, the DescribeTo() method of the Gt(7)
133 // matcher prints "is greater than 7".
shiqiane35fdd92008-12-10 05:08:54 +0000134 virtual void DescribeTo(::std::ostream* os) const = 0;
135
136 // Describes the negation of this matcher to an ostream. For
137 // example, if the description of this matcher is "is greater than
138 // 7", the negated description could be "is not greater than 7".
139 // You are not required to override this when implementing
140 // MatcherInterface, but it is highly advised so that your matcher
141 // can produce good error messages.
142 virtual void DescribeNegationTo(::std::ostream* os) const {
143 *os << "not (";
144 DescribeTo(os);
145 *os << ")";
146 }
shiqiane35fdd92008-12-10 05:08:54 +0000147};
148
149namespace internal {
150
zhanyong.wan82113312010-01-08 21:55:40 +0000151// A match result listener that ignores the explanation.
152class DummyMatchResultListener : public MatchResultListener {
153 public:
154 DummyMatchResultListener() : MatchResultListener(NULL) {}
155
156 private:
157 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
158};
159
160// A match result listener that forwards the explanation to a given
161// ostream. The difference between this and MatchResultListener is
162// that the former is concrete.
163class StreamMatchResultListener : public MatchResultListener {
164 public:
165 explicit StreamMatchResultListener(::std::ostream* os)
166 : MatchResultListener(os) {}
167
168 private:
169 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
170};
171
172// A match result listener that stores the explanation in a string.
173class StringMatchResultListener : public MatchResultListener {
174 public:
175 StringMatchResultListener() : MatchResultListener(&ss_) {}
176
177 // Returns the explanation heard so far.
178 internal::string str() const { return ss_.str(); }
179
180 private:
181 ::std::stringstream ss_;
182
183 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
184};
185
shiqiane35fdd92008-12-10 05:08:54 +0000186// An internal class for implementing Matcher<T>, which will derive
187// from it. We put functionalities common to all Matcher<T>
188// specializations here to avoid code duplication.
189template <typename T>
190class MatcherBase {
191 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000192 // Returns true iff the matcher matches x; also explains the match
193 // result to 'listener'.
194 bool MatchAndExplain(T x, MatchResultListener* listener) const {
195 return impl_->MatchAndExplain(x, listener);
196 }
197
shiqiane35fdd92008-12-10 05:08:54 +0000198 // Returns true iff this matcher matches x.
zhanyong.wan82113312010-01-08 21:55:40 +0000199 bool Matches(T x) const {
200 DummyMatchResultListener dummy;
201 return MatchAndExplain(x, &dummy);
202 }
shiqiane35fdd92008-12-10 05:08:54 +0000203
204 // Describes this matcher to an ostream.
205 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
206
207 // Describes the negation of this matcher to an ostream.
208 void DescribeNegationTo(::std::ostream* os) const {
209 impl_->DescribeNegationTo(os);
210 }
211
212 // Explains why x matches, or doesn't match, the matcher.
213 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000214 StreamMatchResultListener listener(os);
215 MatchAndExplain(x, &listener);
shiqiane35fdd92008-12-10 05:08:54 +0000216 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000217
shiqiane35fdd92008-12-10 05:08:54 +0000218 protected:
219 MatcherBase() {}
220
221 // Constructs a matcher from its implementation.
222 explicit MatcherBase(const MatcherInterface<T>* impl)
223 : impl_(impl) {}
224
225 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000226
shiqiane35fdd92008-12-10 05:08:54 +0000227 private:
228 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
229 // interfaces. The former dynamically allocates a chunk of memory
230 // to hold the reference count, while the latter tracks all
231 // references using a circular linked list without allocating
232 // memory. It has been observed that linked_ptr performs better in
233 // typical scenarios. However, shared_ptr can out-perform
234 // linked_ptr when there are many more uses of the copy constructor
235 // than the default constructor.
236 //
237 // If performance becomes a problem, we should see if using
238 // shared_ptr helps.
239 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
240};
241
shiqiane35fdd92008-12-10 05:08:54 +0000242} // namespace internal
243
244// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
245// object that can check whether a value of type T matches. The
246// implementation of Matcher<T> is just a linked_ptr to const
247// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
248// from Matcher!
249template <typename T>
250class Matcher : public internal::MatcherBase<T> {
251 public:
252 // Constructs a null matcher. Needed for storing Matcher objects in
253 // STL containers.
254 Matcher() {}
255
256 // Constructs a matcher from its implementation.
257 explicit Matcher(const MatcherInterface<T>* impl)
258 : internal::MatcherBase<T>(impl) {}
259
zhanyong.wan18490652009-05-11 18:54:08 +0000260 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000261 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
262 Matcher(T value); // NOLINT
263};
264
265// The following two specializations allow the user to write str
266// instead of Eq(str) and "foo" instead of Eq("foo") when a string
267// matcher is expected.
268template <>
269class Matcher<const internal::string&>
270 : public internal::MatcherBase<const internal::string&> {
271 public:
272 Matcher() {}
273
274 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
275 : internal::MatcherBase<const internal::string&>(impl) {}
276
277 // Allows the user to write str instead of Eq(str) sometimes, where
278 // str is a string object.
279 Matcher(const internal::string& s); // NOLINT
280
281 // Allows the user to write "foo" instead of Eq("foo") sometimes.
282 Matcher(const char* s); // NOLINT
283};
284
285template <>
286class Matcher<internal::string>
287 : public internal::MatcherBase<internal::string> {
288 public:
289 Matcher() {}
290
291 explicit Matcher(const MatcherInterface<internal::string>* impl)
292 : internal::MatcherBase<internal::string>(impl) {}
293
294 // Allows the user to write str instead of Eq(str) sometimes, where
295 // str is a string object.
296 Matcher(const internal::string& s); // NOLINT
297
298 // Allows the user to write "foo" instead of Eq("foo") sometimes.
299 Matcher(const char* s); // NOLINT
300};
301
302// The PolymorphicMatcher class template makes it easy to implement a
303// polymorphic matcher (i.e. a matcher that can match values of more
304// than one type, e.g. Eq(n) and NotNull()).
305//
zhanyong.wandb22c222010-01-28 21:52:29 +0000306// To define a polymorphic matcher, a user should provide an Impl
307// class that has a DescribeTo() method and a DescribeNegationTo()
308// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000309//
zhanyong.wandb22c222010-01-28 21:52:29 +0000310// bool MatchAndExplain(const Value& value,
311// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000312//
313// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000314template <class Impl>
315class PolymorphicMatcher {
316 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000317 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000318
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000319 // Returns a mutable reference to the underlying matcher
320 // implementation object.
321 Impl& mutable_impl() { return impl_; }
322
323 // Returns an immutable reference to the underlying matcher
324 // implementation object.
325 const Impl& impl() const { return impl_; }
326
shiqiane35fdd92008-12-10 05:08:54 +0000327 template <typename T>
328 operator Matcher<T>() const {
329 return Matcher<T>(new MonomorphicImpl<T>(impl_));
330 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000331
shiqiane35fdd92008-12-10 05:08:54 +0000332 private:
333 template <typename T>
334 class MonomorphicImpl : public MatcherInterface<T> {
335 public:
336 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
337
shiqiane35fdd92008-12-10 05:08:54 +0000338 virtual void DescribeTo(::std::ostream* os) const {
339 impl_.DescribeTo(os);
340 }
341
342 virtual void DescribeNegationTo(::std::ostream* os) const {
343 impl_.DescribeNegationTo(os);
344 }
345
zhanyong.wan82113312010-01-08 21:55:40 +0000346 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000347 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000348 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000349
shiqiane35fdd92008-12-10 05:08:54 +0000350 private:
351 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000352
353 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000354 };
355
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000356 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000357
358 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000359};
360
361// Creates a matcher from its implementation. This is easier to use
362// than the Matcher<T> constructor as it doesn't require you to
363// explicitly write the template argument, e.g.
364//
365// MakeMatcher(foo);
366// vs
367// Matcher<const string&>(foo);
368template <typename T>
369inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
370 return Matcher<T>(impl);
371};
372
373// Creates a polymorphic matcher from its implementation. This is
374// easier to use than the PolymorphicMatcher<Impl> constructor as it
375// doesn't require you to explicitly write the template argument, e.g.
376//
377// MakePolymorphicMatcher(foo);
378// vs
379// PolymorphicMatcher<TypeOfFoo>(foo);
380template <class Impl>
381inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
382 return PolymorphicMatcher<Impl>(impl);
383}
384
385// In order to be safe and clear, casting between different matcher
386// types is done explicitly via MatcherCast<T>(m), which takes a
387// matcher m and returns a Matcher<T>. It compiles only when T can be
388// statically converted to the argument type of m.
389template <typename T, typename M>
390Matcher<T> MatcherCast(M m);
391
zhanyong.wan18490652009-05-11 18:54:08 +0000392// Implements SafeMatcherCast().
393//
zhanyong.wan95b12332009-09-25 18:55:50 +0000394// We use an intermediate class to do the actual safe casting as Nokia's
395// Symbian compiler cannot decide between
396// template <T, M> ... (M) and
397// template <T, U> ... (const Matcher<U>&)
398// for function templates but can for member function templates.
399template <typename T>
400class SafeMatcherCastImpl {
401 public:
402 // This overload handles polymorphic matchers only since monomorphic
403 // matchers are handled by the next one.
404 template <typename M>
405 static inline Matcher<T> Cast(M polymorphic_matcher) {
406 return Matcher<T>(polymorphic_matcher);
407 }
zhanyong.wan18490652009-05-11 18:54:08 +0000408
zhanyong.wan95b12332009-09-25 18:55:50 +0000409 // This overload handles monomorphic matchers.
410 //
411 // In general, if type T can be implicitly converted to type U, we can
412 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
413 // contravariant): just keep a copy of the original Matcher<U>, convert the
414 // argument from type T to U, and then pass it to the underlying Matcher<U>.
415 // The only exception is when U is a reference and T is not, as the
416 // underlying Matcher<U> may be interested in the argument's address, which
417 // is not preserved in the conversion from T to U.
418 template <typename U>
419 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
420 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000421 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000422 T_must_be_implicitly_convertible_to_U);
423 // Enforce that we are not converting a non-reference type T to a reference
424 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000425 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000426 internal::is_reference<T>::value || !internal::is_reference<U>::value,
427 cannot_convert_non_referentce_arg_to_reference);
428 // In case both T and U are arithmetic types, enforce that the
429 // conversion is not lossy.
zhanyong.wan02f71062010-05-10 17:14:29 +0000430 typedef GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(T)) RawT;
431 typedef GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(U)) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000432 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
433 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000434 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000435 kTIsOther || kUIsOther ||
436 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
437 conversion_of_arithmetic_types_must_be_lossless);
438 return MatcherCast<T>(matcher);
439 }
440};
441
442template <typename T, typename M>
443inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
444 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000445}
446
shiqiane35fdd92008-12-10 05:08:54 +0000447// A<T>() returns a matcher that matches any value of type T.
448template <typename T>
449Matcher<T> A();
450
451// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
452// and MUST NOT BE USED IN USER CODE!!!
453namespace internal {
454
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000455// If the explanation is not empty, prints it to the ostream.
456inline void PrintIfNotEmpty(const internal::string& explanation,
457 std::ostream* os) {
458 if (explanation != "" && os != NULL) {
459 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000460 }
461}
462
463// Matches the value against the given matcher, prints the value and explains
464// the match result to the listener. Returns the match result.
465// 'listener' must not be NULL.
466// Value cannot be passed by const reference, because some matchers take a
467// non-const argument.
468template <typename Value, typename T>
469bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
470 MatchResultListener* listener) {
471 if (!listener->IsInterested()) {
472 // If the listener is not interested, we do not need to construct the
473 // inner explanation.
474 return matcher.Matches(value);
475 }
476
477 StringMatchResultListener inner_listener;
478 const bool match = matcher.MatchAndExplain(value, &inner_listener);
479
480 UniversalPrint(value, listener->stream());
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000481 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000482
483 return match;
484}
485
shiqiane35fdd92008-12-10 05:08:54 +0000486// An internal helper class for doing compile-time loop on a tuple's
487// fields.
488template <size_t N>
489class TuplePrefix {
490 public:
491 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
492 // iff the first N fields of matcher_tuple matches the first N
493 // fields of value_tuple, respectively.
494 template <typename MatcherTuple, typename ValueTuple>
495 static bool Matches(const MatcherTuple& matcher_tuple,
496 const ValueTuple& value_tuple) {
497 using ::std::tr1::get;
498 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
499 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
500 }
501
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000502 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000503 // describes failures in matching the first N fields of matchers
504 // against the first N fields of values. If there is no failure,
505 // nothing will be streamed to os.
506 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000507 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
508 const ValueTuple& values,
509 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000510 using ::std::tr1::tuple_element;
511 using ::std::tr1::get;
512
513 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000514 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000515
516 // Then describes the failure (if any) in the (N - 1)-th (0-based)
517 // field.
518 typename tuple_element<N - 1, MatcherTuple>::type matcher =
519 get<N - 1>(matchers);
520 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
521 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000522 StringMatchResultListener listener;
523 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000524 // TODO(wan): include in the message the name of the parameter
525 // as used in MOCK_METHOD*() when possible.
526 *os << " Expected arg #" << N - 1 << ": ";
527 get<N - 1>(matchers).DescribeTo(os);
528 *os << "\n Actual: ";
529 // We remove the reference in type Value to prevent the
530 // universal printer from printing the address of value, which
531 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000532 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000533 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000534 internal::UniversalPrint(value, os);
535 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000536 *os << "\n";
537 }
538 }
539};
540
541// The base case.
542template <>
543class TuplePrefix<0> {
544 public:
545 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000546 static bool Matches(const MatcherTuple& /* matcher_tuple */,
547 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000548 return true;
549 }
550
551 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000552 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
553 const ValueTuple& /* values */,
554 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000555};
556
557// TupleMatches(matcher_tuple, value_tuple) returns true iff all
558// matchers in matcher_tuple match the corresponding fields in
559// value_tuple. It is a compiler error if matcher_tuple and
560// value_tuple have different number of fields or incompatible field
561// types.
562template <typename MatcherTuple, typename ValueTuple>
563bool TupleMatches(const MatcherTuple& matcher_tuple,
564 const ValueTuple& value_tuple) {
565 using ::std::tr1::tuple_size;
566 // Makes sure that matcher_tuple and value_tuple have the same
567 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000568 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000569 tuple_size<ValueTuple>::value,
570 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000571 return TuplePrefix<tuple_size<ValueTuple>::value>::
572 Matches(matcher_tuple, value_tuple);
573}
574
575// Describes failures in matching matchers against values. If there
576// is no failure, nothing will be streamed to os.
577template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000578void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
579 const ValueTuple& values,
580 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000581 using ::std::tr1::tuple_size;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000582 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000583 matchers, values, os);
584}
585
586// The MatcherCastImpl class template is a helper for implementing
587// MatcherCast(). We need this helper in order to partially
588// specialize the implementation of MatcherCast() (C++ allows
589// class/struct templates to be partially specialized, but not
590// function templates.).
591
592// This general version is used when MatcherCast()'s argument is a
593// polymorphic matcher (i.e. something that can be converted to a
594// Matcher but is not one yet; for example, Eq(value)).
595template <typename T, typename M>
596class MatcherCastImpl {
597 public:
598 static Matcher<T> Cast(M polymorphic_matcher) {
599 return Matcher<T>(polymorphic_matcher);
600 }
601};
602
603// This more specialized version is used when MatcherCast()'s argument
604// is already a Matcher. This only compiles when type T can be
605// statically converted to type U.
606template <typename T, typename U>
607class MatcherCastImpl<T, Matcher<U> > {
608 public:
609 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
610 return Matcher<T>(new Impl(source_matcher));
611 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000612
shiqiane35fdd92008-12-10 05:08:54 +0000613 private:
614 class Impl : public MatcherInterface<T> {
615 public:
616 explicit Impl(const Matcher<U>& source_matcher)
617 : source_matcher_(source_matcher) {}
618
619 // We delegate the matching logic to the source matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000620 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
621 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000622 }
623
624 virtual void DescribeTo(::std::ostream* os) const {
625 source_matcher_.DescribeTo(os);
626 }
627
628 virtual void DescribeNegationTo(::std::ostream* os) const {
629 source_matcher_.DescribeNegationTo(os);
630 }
631
shiqiane35fdd92008-12-10 05:08:54 +0000632 private:
633 const Matcher<U> source_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000634
635 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000636 };
637};
638
639// This even more specialized version is used for efficiently casting
640// a matcher to its own type.
641template <typename T>
642class MatcherCastImpl<T, Matcher<T> > {
643 public:
644 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
645};
646
647// Implements A<T>().
648template <typename T>
649class AnyMatcherImpl : public MatcherInterface<T> {
650 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000651 virtual bool MatchAndExplain(
652 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000653 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
654 virtual void DescribeNegationTo(::std::ostream* os) const {
655 // This is mostly for completeness' safe, as it's not very useful
656 // to write Not(A<bool>()). However we cannot completely rule out
657 // such a possibility, and it doesn't hurt to be prepared.
658 *os << "never matches";
659 }
660};
661
662// Implements _, a matcher that matches any value of any
663// type. This is a polymorphic matcher, so we need a template type
664// conversion operator to make it appearing as a Matcher<T> for any
665// type T.
666class AnythingMatcher {
667 public:
668 template <typename T>
669 operator Matcher<T>() const { return A<T>(); }
670};
671
672// Implements a matcher that compares a given value with a
673// pre-supplied value using one of the ==, <=, <, etc, operators. The
674// two values being compared don't have to have the same type.
675//
676// The matcher defined here is polymorphic (for example, Eq(5) can be
677// used to match an int, a short, a double, etc). Therefore we use
678// a template type conversion operator in the implementation.
679//
680// We define this as a macro in order to eliminate duplicated source
681// code.
682//
683// The following template definition assumes that the Rhs parameter is
684// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000685#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_( \
686 name, op, relation, negated_relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000687 template <typename Rhs> class name##Matcher { \
688 public: \
689 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
690 template <typename Lhs> \
691 operator Matcher<Lhs>() const { \
692 return MakeMatcher(new Impl<Lhs>(rhs_)); \
693 } \
694 private: \
695 template <typename Lhs> \
696 class Impl : public MatcherInterface<Lhs> { \
697 public: \
698 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
zhanyong.wan82113312010-01-08 21:55:40 +0000699 virtual bool MatchAndExplain(\
700 Lhs lhs, MatchResultListener* /* listener */) const { \
701 return lhs op rhs_; \
702 } \
shiqiane35fdd92008-12-10 05:08:54 +0000703 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000704 *os << relation " "; \
shiqiane35fdd92008-12-10 05:08:54 +0000705 UniversalPrinter<Rhs>::Print(rhs_, os); \
706 } \
707 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000708 *os << negated_relation " "; \
shiqiane35fdd92008-12-10 05:08:54 +0000709 UniversalPrinter<Rhs>::Print(rhs_, os); \
710 } \
711 private: \
712 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000713 GTEST_DISALLOW_ASSIGN_(Impl); \
shiqiane35fdd92008-12-10 05:08:54 +0000714 }; \
715 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000716 GTEST_DISALLOW_ASSIGN_(name##Matcher); \
shiqiane35fdd92008-12-10 05:08:54 +0000717 }
718
719// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
720// respectively.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000721GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "is equal to", "isn't equal to");
722GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "is >=", "isn't >=");
723GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "is >", "isn't >");
724GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "is <=", "isn't <=");
725GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "is <", "isn't <");
726GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "isn't equal to", "is equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000727
zhanyong.wane0d051e2009-02-19 00:33:37 +0000728#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000729
vladlosev79b83502009-11-18 00:43:37 +0000730// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000731// pointer that is NULL.
732class IsNullMatcher {
733 public:
vladlosev79b83502009-11-18 00:43:37 +0000734 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000735 bool MatchAndExplain(const Pointer& p,
736 MatchResultListener* /* listener */) const {
737 return GetRawPointer(p) == NULL;
738 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000739
740 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
741 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000742 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000743 }
744};
745
vladlosev79b83502009-11-18 00:43:37 +0000746// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000747// pointer that is not NULL.
748class NotNullMatcher {
749 public:
vladlosev79b83502009-11-18 00:43:37 +0000750 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000751 bool MatchAndExplain(const Pointer& p,
752 MatchResultListener* /* listener */) const {
753 return GetRawPointer(p) != NULL;
754 }
shiqiane35fdd92008-12-10 05:08:54 +0000755
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000756 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +0000757 void DescribeNegationTo(::std::ostream* os) const {
758 *os << "is NULL";
759 }
760};
761
762// Ref(variable) matches any argument that is a reference to
763// 'variable'. This matcher is polymorphic as it can match any
764// super type of the type of 'variable'.
765//
766// The RefMatcher template class implements Ref(variable). It can
767// only be instantiated with a reference type. This prevents a user
768// from mistakenly using Ref(x) to match a non-reference function
769// argument. For example, the following will righteously cause a
770// compiler error:
771//
772// int n;
773// Matcher<int> m1 = Ref(n); // This won't compile.
774// Matcher<int&> m2 = Ref(n); // This will compile.
775template <typename T>
776class RefMatcher;
777
778template <typename T>
779class RefMatcher<T&> {
780 // Google Mock is a generic framework and thus needs to support
781 // mocking any function types, including those that take non-const
782 // reference arguments. Therefore the template parameter T (and
783 // Super below) can be instantiated to either a const type or a
784 // non-const type.
785 public:
786 // RefMatcher() takes a T& instead of const T&, as we want the
787 // compiler to catch using Ref(const_value) as a matcher for a
788 // non-const reference.
789 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
790
791 template <typename Super>
792 operator Matcher<Super&>() const {
793 // By passing object_ (type T&) to Impl(), which expects a Super&,
794 // we make sure that Super is a super type of T. In particular,
795 // this catches using Ref(const_value) as a matcher for a
796 // non-const reference, as you cannot implicitly convert a const
797 // reference to a non-const reference.
798 return MakeMatcher(new Impl<Super>(object_));
799 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000800
shiqiane35fdd92008-12-10 05:08:54 +0000801 private:
802 template <typename Super>
803 class Impl : public MatcherInterface<Super&> {
804 public:
805 explicit Impl(Super& x) : object_(x) {} // NOLINT
806
zhanyong.wandb22c222010-01-28 21:52:29 +0000807 // MatchAndExplain() takes a Super& (as opposed to const Super&)
808 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +0000809 virtual bool MatchAndExplain(
810 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000811 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +0000812 return &x == &object_;
813 }
shiqiane35fdd92008-12-10 05:08:54 +0000814
815 virtual void DescribeTo(::std::ostream* os) const {
816 *os << "references the variable ";
817 UniversalPrinter<Super&>::Print(object_, os);
818 }
819
820 virtual void DescribeNegationTo(::std::ostream* os) const {
821 *os << "does not reference the variable ";
822 UniversalPrinter<Super&>::Print(object_, os);
823 }
824
shiqiane35fdd92008-12-10 05:08:54 +0000825 private:
826 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000827
828 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000829 };
830
831 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000832
833 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000834};
835
836// Polymorphic helper functions for narrow and wide string matchers.
837inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
838 return String::CaseInsensitiveCStringEquals(lhs, rhs);
839}
840
841inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
842 const wchar_t* rhs) {
843 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
844}
845
846// String comparison for narrow or wide strings that can have embedded NUL
847// characters.
848template <typename StringType>
849bool CaseInsensitiveStringEquals(const StringType& s1,
850 const StringType& s2) {
851 // Are the heads equal?
852 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
853 return false;
854 }
855
856 // Skip the equal heads.
857 const typename StringType::value_type nul = 0;
858 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
859
860 // Are we at the end of either s1 or s2?
861 if (i1 == StringType::npos || i2 == StringType::npos) {
862 return i1 == i2;
863 }
864
865 // Are the tails equal?
866 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
867}
868
869// String matchers.
870
871// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
872template <typename StringType>
873class StrEqualityMatcher {
874 public:
875 typedef typename StringType::const_pointer ConstCharPointer;
876
877 StrEqualityMatcher(const StringType& str, bool expect_eq,
878 bool case_sensitive)
879 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
880
881 // When expect_eq_ is true, returns true iff s is equal to string_;
882 // otherwise returns true iff s is not equal to string_.
zhanyong.wandb22c222010-01-28 21:52:29 +0000883 bool MatchAndExplain(ConstCharPointer s,
884 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +0000885 if (s == NULL) {
886 return !expect_eq_;
887 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000888 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000889 }
890
zhanyong.wandb22c222010-01-28 21:52:29 +0000891 bool MatchAndExplain(const StringType& s,
892 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000893 const bool eq = case_sensitive_ ? s == string_ :
894 CaseInsensitiveStringEquals(s, string_);
895 return expect_eq_ == eq;
896 }
897
898 void DescribeTo(::std::ostream* os) const {
899 DescribeToHelper(expect_eq_, os);
900 }
901
902 void DescribeNegationTo(::std::ostream* os) const {
903 DescribeToHelper(!expect_eq_, os);
904 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000905
shiqiane35fdd92008-12-10 05:08:54 +0000906 private:
907 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000908 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +0000909 *os << "equal to ";
910 if (!case_sensitive_) {
911 *os << "(ignoring case) ";
912 }
913 UniversalPrinter<StringType>::Print(string_, os);
914 }
915
916 const StringType string_;
917 const bool expect_eq_;
918 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000919
920 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000921};
922
923// Implements the polymorphic HasSubstr(substring) matcher, which
924// can be used as a Matcher<T> as long as T can be converted to a
925// string.
926template <typename StringType>
927class HasSubstrMatcher {
928 public:
929 typedef typename StringType::const_pointer ConstCharPointer;
930
931 explicit HasSubstrMatcher(const StringType& substring)
932 : substring_(substring) {}
933
934 // These overloaded methods allow HasSubstr(substring) to be used as a
935 // Matcher<T> as long as T can be converted to string. Returns true
936 // iff s contains substring_ as a substring.
zhanyong.wandb22c222010-01-28 21:52:29 +0000937 bool MatchAndExplain(ConstCharPointer s,
938 MatchResultListener* listener) const {
939 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000940 }
941
zhanyong.wandb22c222010-01-28 21:52:29 +0000942 bool MatchAndExplain(const StringType& s,
943 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000944 return s.find(substring_) != StringType::npos;
945 }
946
947 // Describes what this matcher matches.
948 void DescribeTo(::std::ostream* os) const {
949 *os << "has substring ";
950 UniversalPrinter<StringType>::Print(substring_, os);
951 }
952
953 void DescribeNegationTo(::std::ostream* os) const {
954 *os << "has no substring ";
955 UniversalPrinter<StringType>::Print(substring_, os);
956 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000957
shiqiane35fdd92008-12-10 05:08:54 +0000958 private:
959 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000960
961 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000962};
963
964// Implements the polymorphic StartsWith(substring) matcher, which
965// can be used as a Matcher<T> as long as T can be converted to a
966// string.
967template <typename StringType>
968class StartsWithMatcher {
969 public:
970 typedef typename StringType::const_pointer ConstCharPointer;
971
972 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
973 }
974
975 // These overloaded methods allow StartsWith(prefix) to be used as a
976 // Matcher<T> as long as T can be converted to string. Returns true
977 // iff s starts with prefix_.
zhanyong.wandb22c222010-01-28 21:52:29 +0000978 bool MatchAndExplain(ConstCharPointer s,
979 MatchResultListener* listener) const {
980 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000981 }
982
zhanyong.wandb22c222010-01-28 21:52:29 +0000983 bool MatchAndExplain(const StringType& s,
984 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000985 return s.length() >= prefix_.length() &&
986 s.substr(0, prefix_.length()) == prefix_;
987 }
988
989 void DescribeTo(::std::ostream* os) const {
990 *os << "starts with ";
991 UniversalPrinter<StringType>::Print(prefix_, os);
992 }
993
994 void DescribeNegationTo(::std::ostream* os) const {
995 *os << "doesn't start with ";
996 UniversalPrinter<StringType>::Print(prefix_, os);
997 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000998
shiqiane35fdd92008-12-10 05:08:54 +0000999 private:
1000 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001001
1002 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001003};
1004
1005// Implements the polymorphic EndsWith(substring) matcher, which
1006// can be used as a Matcher<T> as long as T can be converted to a
1007// string.
1008template <typename StringType>
1009class EndsWithMatcher {
1010 public:
1011 typedef typename StringType::const_pointer ConstCharPointer;
1012
1013 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1014
1015 // These overloaded methods allow EndsWith(suffix) to be used as a
1016 // Matcher<T> as long as T can be converted to string. Returns true
1017 // iff s ends with suffix_.
zhanyong.wandb22c222010-01-28 21:52:29 +00001018 bool MatchAndExplain(ConstCharPointer s,
1019 MatchResultListener* listener) const {
1020 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001021 }
1022
zhanyong.wandb22c222010-01-28 21:52:29 +00001023 bool MatchAndExplain(const StringType& s,
1024 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001025 return s.length() >= suffix_.length() &&
1026 s.substr(s.length() - suffix_.length()) == suffix_;
1027 }
1028
1029 void DescribeTo(::std::ostream* os) const {
1030 *os << "ends with ";
1031 UniversalPrinter<StringType>::Print(suffix_, os);
1032 }
1033
1034 void DescribeNegationTo(::std::ostream* os) const {
1035 *os << "doesn't end with ";
1036 UniversalPrinter<StringType>::Print(suffix_, os);
1037 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001038
shiqiane35fdd92008-12-10 05:08:54 +00001039 private:
1040 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001041
1042 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001043};
1044
shiqiane35fdd92008-12-10 05:08:54 +00001045// Implements polymorphic matchers MatchesRegex(regex) and
1046// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1047// T can be converted to a string.
1048class MatchesRegexMatcher {
1049 public:
1050 MatchesRegexMatcher(const RE* regex, bool full_match)
1051 : regex_(regex), full_match_(full_match) {}
1052
1053 // These overloaded methods allow MatchesRegex(regex) to be used as
1054 // a Matcher<T> as long as T can be converted to string. Returns
1055 // true iff s matches regular expression regex. When full_match_ is
1056 // true, a full match is done; otherwise a partial match is done.
zhanyong.wandb22c222010-01-28 21:52:29 +00001057 bool MatchAndExplain(const char* s,
1058 MatchResultListener* listener) const {
1059 return s != NULL && MatchAndExplain(internal::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001060 }
1061
zhanyong.wandb22c222010-01-28 21:52:29 +00001062 bool MatchAndExplain(const internal::string& s,
1063 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001064 return full_match_ ? RE::FullMatch(s, *regex_) :
1065 RE::PartialMatch(s, *regex_);
1066 }
1067
1068 void DescribeTo(::std::ostream* os) const {
1069 *os << (full_match_ ? "matches" : "contains")
1070 << " regular expression ";
1071 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1072 }
1073
1074 void DescribeNegationTo(::std::ostream* os) const {
1075 *os << "doesn't " << (full_match_ ? "match" : "contain")
1076 << " regular expression ";
1077 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1078 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001079
shiqiane35fdd92008-12-10 05:08:54 +00001080 private:
1081 const internal::linked_ptr<const RE> regex_;
1082 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001083
1084 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001085};
1086
shiqiane35fdd92008-12-10 05:08:54 +00001087// Implements a matcher that compares the two fields of a 2-tuple
1088// using one of the ==, <=, <, etc, operators. The two fields being
1089// compared don't have to have the same type.
1090//
1091// The matcher defined here is polymorphic (for example, Eq() can be
1092// used to match a tuple<int, short>, a tuple<const long&, double>,
1093// etc). Therefore we use a template type conversion operator in the
1094// implementation.
1095//
1096// We define this as a macro in order to eliminate duplicated source
1097// code.
zhanyong.wan2661c682009-06-09 05:42:12 +00001098#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op) \
shiqiane35fdd92008-12-10 05:08:54 +00001099 class name##2Matcher { \
1100 public: \
1101 template <typename T1, typename T2> \
1102 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
1103 return MakeMatcher(new Impl<T1, T2>); \
1104 } \
1105 private: \
1106 template <typename T1, typename T2> \
1107 class Impl : public MatcherInterface<const ::std::tr1::tuple<T1, T2>&> { \
1108 public: \
zhanyong.wan82113312010-01-08 21:55:40 +00001109 virtual bool MatchAndExplain( \
1110 const ::std::tr1::tuple<T1, T2>& args, \
1111 MatchResultListener* /* listener */) const { \
shiqiane35fdd92008-12-10 05:08:54 +00001112 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
1113 } \
1114 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +00001115 *os << "are a pair (x, y) where x " #op " y"; \
shiqiane35fdd92008-12-10 05:08:54 +00001116 } \
1117 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +00001118 *os << "are a pair (x, y) where x " #op " y is false"; \
shiqiane35fdd92008-12-10 05:08:54 +00001119 } \
1120 }; \
1121 }
1122
1123// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wan2661c682009-06-09 05:42:12 +00001124GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==);
1125GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ge, >=);
1126GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Gt, >);
1127GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Le, <=);
1128GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Lt, <);
1129GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=);
shiqiane35fdd92008-12-10 05:08:54 +00001130
zhanyong.wane0d051e2009-02-19 00:33:37 +00001131#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +00001132
zhanyong.wanc6a41232009-05-13 23:38:40 +00001133// Implements the Not(...) matcher for a particular argument type T.
1134// We do not nest it inside the NotMatcher class template, as that
1135// will prevent different instantiations of NotMatcher from sharing
1136// the same NotMatcherImpl<T> class.
1137template <typename T>
1138class NotMatcherImpl : public MatcherInterface<T> {
1139 public:
1140 explicit NotMatcherImpl(const Matcher<T>& matcher)
1141 : matcher_(matcher) {}
1142
zhanyong.wan82113312010-01-08 21:55:40 +00001143 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1144 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001145 }
1146
1147 virtual void DescribeTo(::std::ostream* os) const {
1148 matcher_.DescribeNegationTo(os);
1149 }
1150
1151 virtual void DescribeNegationTo(::std::ostream* os) const {
1152 matcher_.DescribeTo(os);
1153 }
1154
zhanyong.wanc6a41232009-05-13 23:38:40 +00001155 private:
1156 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001157
1158 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001159};
1160
shiqiane35fdd92008-12-10 05:08:54 +00001161// Implements the Not(m) matcher, which matches a value that doesn't
1162// match matcher m.
1163template <typename InnerMatcher>
1164class NotMatcher {
1165 public:
1166 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1167
1168 // This template type conversion operator allows Not(m) to be used
1169 // to match any type m can match.
1170 template <typename T>
1171 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001172 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001173 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001174
shiqiane35fdd92008-12-10 05:08:54 +00001175 private:
shiqiane35fdd92008-12-10 05:08:54 +00001176 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001177
1178 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001179};
1180
zhanyong.wanc6a41232009-05-13 23:38:40 +00001181// Implements the AllOf(m1, m2) matcher for a particular argument type
1182// T. We do not nest it inside the BothOfMatcher class template, as
1183// that will prevent different instantiations of BothOfMatcher from
1184// sharing the same BothOfMatcherImpl<T> class.
1185template <typename T>
1186class BothOfMatcherImpl : public MatcherInterface<T> {
1187 public:
1188 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1189 : matcher1_(matcher1), matcher2_(matcher2) {}
1190
zhanyong.wanc6a41232009-05-13 23:38:40 +00001191 virtual void DescribeTo(::std::ostream* os) const {
1192 *os << "(";
1193 matcher1_.DescribeTo(os);
1194 *os << ") and (";
1195 matcher2_.DescribeTo(os);
1196 *os << ")";
1197 }
1198
1199 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001200 *os << "(";
1201 matcher1_.DescribeNegationTo(os);
1202 *os << ") or (";
1203 matcher2_.DescribeNegationTo(os);
1204 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001205 }
1206
zhanyong.wan82113312010-01-08 21:55:40 +00001207 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1208 // If either matcher1_ or matcher2_ doesn't match x, we only need
1209 // to explain why one of them fails.
1210 StringMatchResultListener listener1;
1211 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1212 *listener << listener1.str();
1213 return false;
1214 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001215
zhanyong.wan82113312010-01-08 21:55:40 +00001216 StringMatchResultListener listener2;
1217 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1218 *listener << listener2.str();
1219 return false;
1220 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001221
zhanyong.wan82113312010-01-08 21:55:40 +00001222 // Otherwise we need to explain why *both* of them match.
1223 const internal::string s1 = listener1.str();
1224 const internal::string s2 = listener2.str();
1225
1226 if (s1 == "") {
1227 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001228 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001229 *listener << s1;
1230 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001231 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001232 }
1233 }
zhanyong.wan82113312010-01-08 21:55:40 +00001234 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001235 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001236
zhanyong.wanc6a41232009-05-13 23:38:40 +00001237 private:
1238 const Matcher<T> matcher1_;
1239 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001240
1241 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001242};
1243
shiqiane35fdd92008-12-10 05:08:54 +00001244// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1245// matches a value that matches all of the matchers m_1, ..., and m_n.
1246template <typename Matcher1, typename Matcher2>
1247class BothOfMatcher {
1248 public:
1249 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1250 : matcher1_(matcher1), matcher2_(matcher2) {}
1251
1252 // This template type conversion operator allows a
1253 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1254 // both Matcher1 and Matcher2 can match.
1255 template <typename T>
1256 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001257 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1258 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001259 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001260
shiqiane35fdd92008-12-10 05:08:54 +00001261 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001262 Matcher1 matcher1_;
1263 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001264
1265 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001266};
shiqiane35fdd92008-12-10 05:08:54 +00001267
zhanyong.wanc6a41232009-05-13 23:38:40 +00001268// Implements the AnyOf(m1, m2) matcher for a particular argument type
1269// T. We do not nest it inside the AnyOfMatcher class template, as
1270// that will prevent different instantiations of AnyOfMatcher from
1271// sharing the same EitherOfMatcherImpl<T> class.
1272template <typename T>
1273class EitherOfMatcherImpl : public MatcherInterface<T> {
1274 public:
1275 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1276 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001277
zhanyong.wanc6a41232009-05-13 23:38:40 +00001278 virtual void DescribeTo(::std::ostream* os) const {
1279 *os << "(";
1280 matcher1_.DescribeTo(os);
1281 *os << ") or (";
1282 matcher2_.DescribeTo(os);
1283 *os << ")";
1284 }
shiqiane35fdd92008-12-10 05:08:54 +00001285
zhanyong.wanc6a41232009-05-13 23:38:40 +00001286 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001287 *os << "(";
1288 matcher1_.DescribeNegationTo(os);
1289 *os << ") and (";
1290 matcher2_.DescribeNegationTo(os);
1291 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001292 }
shiqiane35fdd92008-12-10 05:08:54 +00001293
zhanyong.wan82113312010-01-08 21:55:40 +00001294 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1295 // If either matcher1_ or matcher2_ matches x, we just need to
1296 // explain why *one* of them matches.
1297 StringMatchResultListener listener1;
1298 if (matcher1_.MatchAndExplain(x, &listener1)) {
1299 *listener << listener1.str();
1300 return true;
1301 }
1302
1303 StringMatchResultListener listener2;
1304 if (matcher2_.MatchAndExplain(x, &listener2)) {
1305 *listener << listener2.str();
1306 return true;
1307 }
1308
1309 // Otherwise we need to explain why *both* of them fail.
1310 const internal::string s1 = listener1.str();
1311 const internal::string s2 = listener2.str();
1312
1313 if (s1 == "") {
1314 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001315 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001316 *listener << s1;
1317 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001318 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001319 }
1320 }
zhanyong.wan82113312010-01-08 21:55:40 +00001321 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001322 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001323
zhanyong.wanc6a41232009-05-13 23:38:40 +00001324 private:
1325 const Matcher<T> matcher1_;
1326 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001327
1328 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001329};
1330
1331// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1332// matches a value that matches at least one of the matchers m_1, ...,
1333// and m_n.
1334template <typename Matcher1, typename Matcher2>
1335class EitherOfMatcher {
1336 public:
1337 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1338 : matcher1_(matcher1), matcher2_(matcher2) {}
1339
1340 // This template type conversion operator allows a
1341 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1342 // both Matcher1 and Matcher2 can match.
1343 template <typename T>
1344 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001345 return Matcher<T>(new EitherOfMatcherImpl<T>(
1346 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001347 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001348
shiqiane35fdd92008-12-10 05:08:54 +00001349 private:
shiqiane35fdd92008-12-10 05:08:54 +00001350 Matcher1 matcher1_;
1351 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001352
1353 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001354};
1355
1356// Used for implementing Truly(pred), which turns a predicate into a
1357// matcher.
1358template <typename Predicate>
1359class TrulyMatcher {
1360 public:
1361 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1362
1363 // This method template allows Truly(pred) to be used as a matcher
1364 // for type T where T is the argument type of predicate 'pred'. The
1365 // argument is passed by reference as the predicate may be
1366 // interested in the address of the argument.
1367 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001368 bool MatchAndExplain(T& x, // NOLINT
1369 MatchResultListener* /* listener */) const {
zhanyong.wan652540a2009-02-23 23:37:29 +00001370#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001371 // MSVC warns about converting a value into bool (warning 4800).
1372#pragma warning(push) // Saves the current warning state.
1373#pragma warning(disable:4800) // Temporarily disables warning 4800.
1374#endif // GTEST_OS_WINDOWS
1375 return predicate_(x);
zhanyong.wan652540a2009-02-23 23:37:29 +00001376#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001377#pragma warning(pop) // Restores the warning state.
1378#endif // GTEST_OS_WINDOWS
1379 }
1380
1381 void DescribeTo(::std::ostream* os) const {
1382 *os << "satisfies the given predicate";
1383 }
1384
1385 void DescribeNegationTo(::std::ostream* os) const {
1386 *os << "doesn't satisfy the given predicate";
1387 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001388
shiqiane35fdd92008-12-10 05:08:54 +00001389 private:
1390 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001391
1392 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001393};
1394
1395// Used for implementing Matches(matcher), which turns a matcher into
1396// a predicate.
1397template <typename M>
1398class MatcherAsPredicate {
1399 public:
1400 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1401
1402 // This template operator() allows Matches(m) to be used as a
1403 // predicate on type T where m is a matcher on type T.
1404 //
1405 // The argument x is passed by reference instead of by value, as
1406 // some matcher may be interested in its address (e.g. as in
1407 // Matches(Ref(n))(x)).
1408 template <typename T>
1409 bool operator()(const T& x) const {
1410 // We let matcher_ commit to a particular type here instead of
1411 // when the MatcherAsPredicate object was constructed. This
1412 // allows us to write Matches(m) where m is a polymorphic matcher
1413 // (e.g. Eq(5)).
1414 //
1415 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1416 // compile when matcher_ has type Matcher<const T&>; if we write
1417 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1418 // when matcher_ has type Matcher<T>; if we just write
1419 // matcher_.Matches(x), it won't compile when matcher_ is
1420 // polymorphic, e.g. Eq(5).
1421 //
1422 // MatcherCast<const T&>() is necessary for making the code work
1423 // in all of the above situations.
1424 return MatcherCast<const T&>(matcher_).Matches(x);
1425 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001426
shiqiane35fdd92008-12-10 05:08:54 +00001427 private:
1428 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001429
1430 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001431};
1432
1433// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1434// argument M must be a type that can be converted to a matcher.
1435template <typename M>
1436class PredicateFormatterFromMatcher {
1437 public:
1438 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1439
1440 // This template () operator allows a PredicateFormatterFromMatcher
1441 // object to act as a predicate-formatter suitable for using with
1442 // Google Test's EXPECT_PRED_FORMAT1() macro.
1443 template <typename T>
1444 AssertionResult operator()(const char* value_text, const T& x) const {
1445 // We convert matcher_ to a Matcher<const T&> *now* instead of
1446 // when the PredicateFormatterFromMatcher object was constructed,
1447 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1448 // know which type to instantiate it to until we actually see the
1449 // type of x here.
1450 //
1451 // We write MatcherCast<const T&>(matcher_) instead of
1452 // Matcher<const T&>(matcher_), as the latter won't compile when
1453 // matcher_ has type Matcher<T> (e.g. An<int>()).
1454 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001455 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001456 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001457 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001458
1459 ::std::stringstream ss;
1460 ss << "Value of: " << value_text << "\n"
1461 << "Expected: ";
1462 matcher.DescribeTo(&ss);
1463 ss << "\n Actual: " << listener.str();
1464 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001465 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001466
shiqiane35fdd92008-12-10 05:08:54 +00001467 private:
1468 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001469
1470 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001471};
1472
1473// A helper function for converting a matcher to a predicate-formatter
1474// without the user needing to explicitly write the type. This is
1475// used for implementing ASSERT_THAT() and EXPECT_THAT().
1476template <typename M>
1477inline PredicateFormatterFromMatcher<M>
1478MakePredicateFormatterFromMatcher(const M& matcher) {
1479 return PredicateFormatterFromMatcher<M>(matcher);
1480}
1481
1482// Implements the polymorphic floating point equality matcher, which
1483// matches two float values using ULP-based approximation. The
1484// template is meant to be instantiated with FloatType being either
1485// float or double.
1486template <typename FloatType>
1487class FloatingEqMatcher {
1488 public:
1489 // Constructor for FloatingEqMatcher.
1490 // The matcher's input will be compared with rhs. The matcher treats two
1491 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1492 // equality comparisons between NANs will always return false.
1493 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1494 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1495
1496 // Implements floating point equality matcher as a Matcher<T>.
1497 template <typename T>
1498 class Impl : public MatcherInterface<T> {
1499 public:
1500 Impl(FloatType rhs, bool nan_eq_nan) :
1501 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1502
zhanyong.wan82113312010-01-08 21:55:40 +00001503 virtual bool MatchAndExplain(T value,
1504 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001505 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1506
1507 // Compares NaNs first, if nan_eq_nan_ is true.
1508 if (nan_eq_nan_ && lhs.is_nan()) {
1509 return rhs.is_nan();
1510 }
1511
1512 return lhs.AlmostEquals(rhs);
1513 }
1514
1515 virtual void DescribeTo(::std::ostream* os) const {
1516 // os->precision() returns the previously set precision, which we
1517 // store to restore the ostream to its original configuration
1518 // after outputting.
1519 const ::std::streamsize old_precision = os->precision(
1520 ::std::numeric_limits<FloatType>::digits10 + 2);
1521 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1522 if (nan_eq_nan_) {
1523 *os << "is NaN";
1524 } else {
1525 *os << "never matches";
1526 }
1527 } else {
1528 *os << "is approximately " << rhs_;
1529 }
1530 os->precision(old_precision);
1531 }
1532
1533 virtual void DescribeNegationTo(::std::ostream* os) const {
1534 // As before, get original precision.
1535 const ::std::streamsize old_precision = os->precision(
1536 ::std::numeric_limits<FloatType>::digits10 + 2);
1537 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1538 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001539 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00001540 } else {
1541 *os << "is anything";
1542 }
1543 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001544 *os << "isn't approximately " << rhs_;
shiqiane35fdd92008-12-10 05:08:54 +00001545 }
1546 // Restore original precision.
1547 os->precision(old_precision);
1548 }
1549
1550 private:
1551 const FloatType rhs_;
1552 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001553
1554 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001555 };
1556
1557 // The following 3 type conversion operators allow FloatEq(rhs) and
1558 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1559 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1560 // (While Google's C++ coding style doesn't allow arguments passed
1561 // by non-const reference, we may see them in code not conforming to
1562 // the style. Therefore Google Mock needs to support them.)
1563 operator Matcher<FloatType>() const {
1564 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1565 }
1566
1567 operator Matcher<const FloatType&>() const {
1568 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1569 }
1570
1571 operator Matcher<FloatType&>() const {
1572 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1573 }
1574 private:
1575 const FloatType rhs_;
1576 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001577
1578 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001579};
1580
1581// Implements the Pointee(m) matcher for matching a pointer whose
1582// pointee matches matcher m. The pointer can be either raw or smart.
1583template <typename InnerMatcher>
1584class PointeeMatcher {
1585 public:
1586 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1587
1588 // This type conversion operator template allows Pointee(m) to be
1589 // used as a matcher for any pointer type whose pointee type is
1590 // compatible with the inner matcher, where type Pointer can be
1591 // either a raw pointer or a smart pointer.
1592 //
1593 // The reason we do this instead of relying on
1594 // MakePolymorphicMatcher() is that the latter is not flexible
1595 // enough for implementing the DescribeTo() method of Pointee().
1596 template <typename Pointer>
1597 operator Matcher<Pointer>() const {
1598 return MakeMatcher(new Impl<Pointer>(matcher_));
1599 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001600
shiqiane35fdd92008-12-10 05:08:54 +00001601 private:
1602 // The monomorphic implementation that works for a particular pointer type.
1603 template <typename Pointer>
1604 class Impl : public MatcherInterface<Pointer> {
1605 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00001606 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
1607 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001608
1609 explicit Impl(const InnerMatcher& matcher)
1610 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1611
shiqiane35fdd92008-12-10 05:08:54 +00001612 virtual void DescribeTo(::std::ostream* os) const {
1613 *os << "points to a value that ";
1614 matcher_.DescribeTo(os);
1615 }
1616
1617 virtual void DescribeNegationTo(::std::ostream* os) const {
1618 *os << "does not point to a value that ";
1619 matcher_.DescribeTo(os);
1620 }
1621
zhanyong.wan82113312010-01-08 21:55:40 +00001622 virtual bool MatchAndExplain(Pointer pointer,
1623 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001624 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00001625 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001626
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001627 *listener << "which points to ";
1628 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001629 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001630
shiqiane35fdd92008-12-10 05:08:54 +00001631 private:
1632 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001633
1634 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001635 };
1636
1637 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001638
1639 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001640};
1641
1642// Implements the Field() matcher for matching a field (i.e. member
1643// variable) of an object.
1644template <typename Class, typename FieldType>
1645class FieldMatcher {
1646 public:
1647 FieldMatcher(FieldType Class::*field,
1648 const Matcher<const FieldType&>& matcher)
1649 : field_(field), matcher_(matcher) {}
1650
shiqiane35fdd92008-12-10 05:08:54 +00001651 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001652 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001653 matcher_.DescribeTo(os);
1654 }
1655
1656 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001657 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001658 matcher_.DescribeNegationTo(os);
1659 }
1660
zhanyong.wandb22c222010-01-28 21:52:29 +00001661 template <typename T>
1662 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
1663 return MatchAndExplainImpl(
1664 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00001665 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00001666 value, listener);
1667 }
1668
1669 private:
1670 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001671 // Symbian's C++ compiler choose which overload to use. Its type is
1672 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001673 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1674 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001675 *listener << "whose given field is ";
1676 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001677 }
1678
zhanyong.wandb22c222010-01-28 21:52:29 +00001679 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1680 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001681 if (p == NULL)
1682 return false;
1683
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001684 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001685 // Since *p has a field, it must be a class/struct/union type and
1686 // thus cannot be a pointer. Therefore we pass false_type() as
1687 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001688 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001689 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001690
shiqiane35fdd92008-12-10 05:08:54 +00001691 const FieldType Class::*field_;
1692 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001693
1694 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001695};
1696
shiqiane35fdd92008-12-10 05:08:54 +00001697// Implements the Property() matcher for matching a property
1698// (i.e. return value of a getter method) of an object.
1699template <typename Class, typename PropertyType>
1700class PropertyMatcher {
1701 public:
1702 // The property may have a reference type, so 'const PropertyType&'
1703 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00001704 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00001705 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00001706 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001707
1708 PropertyMatcher(PropertyType (Class::*property)() const,
1709 const Matcher<RefToConstProperty>& matcher)
1710 : property_(property), matcher_(matcher) {}
1711
shiqiane35fdd92008-12-10 05:08:54 +00001712 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001713 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001714 matcher_.DescribeTo(os);
1715 }
1716
1717 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001718 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001719 matcher_.DescribeNegationTo(os);
1720 }
1721
zhanyong.wandb22c222010-01-28 21:52:29 +00001722 template <typename T>
1723 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
1724 return MatchAndExplainImpl(
1725 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00001726 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00001727 value, listener);
1728 }
1729
1730 private:
1731 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001732 // Symbian's C++ compiler choose which overload to use. Its type is
1733 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001734 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1735 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001736 *listener << "whose given property is ";
1737 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
1738 // which takes a non-const reference as argument.
1739 RefToConstProperty result = (obj.*property_)();
1740 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001741 }
1742
zhanyong.wandb22c222010-01-28 21:52:29 +00001743 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1744 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001745 if (p == NULL)
1746 return false;
1747
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001748 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001749 // Since *p has a property method, it must be a class/struct/union
1750 // type and thus cannot be a pointer. Therefore we pass
1751 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001752 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001753 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001754
shiqiane35fdd92008-12-10 05:08:54 +00001755 PropertyType (Class::*property_)() const;
1756 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001757
1758 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001759};
1760
shiqiane35fdd92008-12-10 05:08:54 +00001761// Type traits specifying various features of different functors for ResultOf.
1762// The default template specifies features for functor objects.
1763// Functor classes have to typedef argument_type and result_type
1764// to be compatible with ResultOf.
1765template <typename Functor>
1766struct CallableTraits {
1767 typedef typename Functor::result_type ResultType;
1768 typedef Functor StorageType;
1769
zhanyong.wan32de5f52009-12-23 00:13:23 +00001770 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00001771 template <typename T>
1772 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1773};
1774
1775// Specialization for function pointers.
1776template <typename ArgType, typename ResType>
1777struct CallableTraits<ResType(*)(ArgType)> {
1778 typedef ResType ResultType;
1779 typedef ResType(*StorageType)(ArgType);
1780
1781 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001782 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00001783 << "NULL function pointer is passed into ResultOf().";
1784 }
1785 template <typename T>
1786 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1787 return (*f)(arg);
1788 }
1789};
1790
1791// Implements the ResultOf() matcher for matching a return value of a
1792// unary function of an object.
1793template <typename Callable>
1794class ResultOfMatcher {
1795 public:
1796 typedef typename CallableTraits<Callable>::ResultType ResultType;
1797
1798 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1799 : callable_(callable), matcher_(matcher) {
1800 CallableTraits<Callable>::CheckIsValid(callable_);
1801 }
1802
1803 template <typename T>
1804 operator Matcher<T>() const {
1805 return Matcher<T>(new Impl<T>(callable_, matcher_));
1806 }
1807
1808 private:
1809 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1810
1811 template <typename T>
1812 class Impl : public MatcherInterface<T> {
1813 public:
1814 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1815 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00001816
1817 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001818 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001819 matcher_.DescribeTo(os);
1820 }
1821
1822 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001823 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001824 matcher_.DescribeNegationTo(os);
1825 }
1826
zhanyong.wan82113312010-01-08 21:55:40 +00001827 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001828 *listener << "which is mapped by the given callable to ";
1829 // Cannot pass the return value (for example, int) to
1830 // MatchPrintAndExplain, which takes a non-const reference as argument.
1831 ResultType result =
1832 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
1833 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001834 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001835
shiqiane35fdd92008-12-10 05:08:54 +00001836 private:
1837 // Functors often define operator() as non-const method even though
1838 // they are actualy stateless. But we need to use them even when
1839 // 'this' is a const pointer. It's the user's responsibility not to
1840 // use stateful callables with ResultOf(), which does't guarantee
1841 // how many times the callable will be invoked.
1842 mutable CallableStorageType callable_;
1843 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001844
1845 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001846 }; // class Impl
1847
1848 const CallableStorageType callable_;
1849 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001850
1851 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001852};
1853
zhanyong.wan6a896b52009-01-16 01:13:50 +00001854// Implements an equality matcher for any STL-style container whose elements
1855// support ==. This matcher is like Eq(), but its failure explanations provide
1856// more detailed information that is useful when the container is used as a set.
1857// The failure message reports elements that are in one of the operands but not
1858// the other. The failure messages do not report duplicate or out-of-order
1859// elements in the containers (which don't properly matter to sets, but can
1860// occur if the containers are vectors or lists, for example).
1861//
1862// Uses the container's const_iterator, value_type, operator ==,
1863// begin(), and end().
1864template <typename Container>
1865class ContainerEqMatcher {
1866 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00001867 typedef internal::StlContainerView<Container> View;
1868 typedef typename View::type StlContainer;
1869 typedef typename View::const_reference StlContainerReference;
1870
1871 // We make a copy of rhs in case the elements in it are modified
1872 // after this matcher is created.
1873 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
1874 // Makes sure the user doesn't instantiate this class template
1875 // with a const or reference type.
1876 testing::StaticAssertTypeEq<Container,
zhanyong.wan02f71062010-05-10 17:14:29 +00001877 GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(Container))>();
zhanyong.wanb8243162009-06-04 05:48:20 +00001878 }
1879
zhanyong.wan6a896b52009-01-16 01:13:50 +00001880 void DescribeTo(::std::ostream* os) const {
1881 *os << "equals ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001882 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001883 }
1884 void DescribeNegationTo(::std::ostream* os) const {
1885 *os << "does not equal ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001886 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001887 }
1888
zhanyong.wanb8243162009-06-04 05:48:20 +00001889 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00001890 bool MatchAndExplain(const LhsContainer& lhs,
1891 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00001892 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00001893 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00001894 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00001895 LhsView;
1896 typedef typename LhsView::type LhsStlContainer;
1897 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00001898 if (lhs_stl_container == rhs_)
1899 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00001900
zhanyong.wane122e452010-01-12 09:03:52 +00001901 ::std::ostream* const os = listener->stream();
1902 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001903 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00001904 bool printed_header = false;
1905 for (typename LhsStlContainer::const_iterator it =
1906 lhs_stl_container.begin();
1907 it != lhs_stl_container.end(); ++it) {
1908 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
1909 rhs_.end()) {
1910 if (printed_header) {
1911 *os << ", ";
1912 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001913 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00001914 printed_header = true;
1915 }
zhanyong.wan6953a722010-01-13 05:15:07 +00001916 UniversalPrinter<typename LhsStlContainer::value_type>::
1917 Print(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001918 }
zhanyong.wane122e452010-01-12 09:03:52 +00001919 }
1920
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001921 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00001922 bool printed_header2 = false;
1923 for (typename StlContainer::const_iterator it = rhs_.begin();
1924 it != rhs_.end(); ++it) {
1925 if (internal::ArrayAwareFind(
1926 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
1927 lhs_stl_container.end()) {
1928 if (printed_header2) {
1929 *os << ", ";
1930 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001931 *os << (printed_header ? ",\nand" : "which")
1932 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00001933 printed_header2 = true;
1934 }
1935 UniversalPrinter<typename StlContainer::value_type>::Print(*it, os);
1936 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00001937 }
1938 }
1939
zhanyong.wane122e452010-01-12 09:03:52 +00001940 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00001941 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001942
zhanyong.wan6a896b52009-01-16 01:13:50 +00001943 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00001944 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001945
1946 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001947};
1948
zhanyong.wan33605ba2010-04-22 23:37:47 +00001949// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00001950template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00001951class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00001952 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00001953 typedef GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(Container)) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00001954 typedef StlContainerView<RawContainer> View;
1955 typedef typename View::type StlContainer;
1956 typedef typename View::const_reference StlContainerReference;
1957 typedef typename StlContainer::value_type Element;
1958
1959 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00001960 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00001961 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00001962 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00001963
zhanyong.wan33605ba2010-04-22 23:37:47 +00001964 // Checks whether:
1965 // * All elements in the container match, if all_elements_should_match.
1966 // * Any element in the container matches, if !all_elements_should_match.
1967 bool MatchAndExplainImpl(bool all_elements_should_match,
1968 Container container,
1969 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00001970 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00001971 size_t i = 0;
1972 for (typename StlContainer::const_iterator it = stl_container.begin();
1973 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001974 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00001975 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
1976
1977 if (matches != all_elements_should_match) {
1978 *listener << "whose element #" << i
1979 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001980 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00001981 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00001982 }
1983 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00001984 return all_elements_should_match;
1985 }
1986
1987 protected:
1988 const Matcher<const Element&> inner_matcher_;
1989
1990 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
1991};
1992
1993// Implements Contains(element_matcher) for the given argument type Container.
1994// Symmetric to EachMatcherImpl.
1995template <typename Container>
1996class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
1997 public:
1998 template <typename InnerMatcher>
1999 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2000 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2001
2002 // Describes what this matcher does.
2003 virtual void DescribeTo(::std::ostream* os) const {
2004 *os << "contains at least one element that ";
2005 this->inner_matcher_.DescribeTo(os);
2006 }
2007
2008 virtual void DescribeNegationTo(::std::ostream* os) const {
2009 *os << "doesn't contain any element that ";
2010 this->inner_matcher_.DescribeTo(os);
2011 }
2012
2013 virtual bool MatchAndExplain(Container container,
2014 MatchResultListener* listener) const {
2015 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002016 }
2017
2018 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002019 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002020};
2021
zhanyong.wan33605ba2010-04-22 23:37:47 +00002022// Implements Each(element_matcher) for the given argument type Container.
2023// Symmetric to ContainsMatcherImpl.
2024template <typename Container>
2025class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2026 public:
2027 template <typename InnerMatcher>
2028 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2029 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2030
2031 // Describes what this matcher does.
2032 virtual void DescribeTo(::std::ostream* os) const {
2033 *os << "only contains elements that ";
2034 this->inner_matcher_.DescribeTo(os);
2035 }
2036
2037 virtual void DescribeNegationTo(::std::ostream* os) const {
2038 *os << "contains some element that ";
2039 this->inner_matcher_.DescribeNegationTo(os);
2040 }
2041
2042 virtual bool MatchAndExplain(Container container,
2043 MatchResultListener* listener) const {
2044 return this->MatchAndExplainImpl(true, container, listener);
2045 }
2046
2047 private:
2048 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2049};
2050
zhanyong.wanb8243162009-06-04 05:48:20 +00002051// Implements polymorphic Contains(element_matcher).
2052template <typename M>
2053class ContainsMatcher {
2054 public:
2055 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2056
2057 template <typename Container>
2058 operator Matcher<Container>() const {
2059 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2060 }
2061
2062 private:
2063 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002064
2065 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002066};
2067
zhanyong.wan33605ba2010-04-22 23:37:47 +00002068// Implements polymorphic Each(element_matcher).
2069template <typename M>
2070class EachMatcher {
2071 public:
2072 explicit EachMatcher(M m) : inner_matcher_(m) {}
2073
2074 template <typename Container>
2075 operator Matcher<Container>() const {
2076 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2077 }
2078
2079 private:
2080 const M inner_matcher_;
2081
2082 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2083};
2084
zhanyong.wanb5937da2009-07-16 20:26:41 +00002085// Implements Key(inner_matcher) for the given argument pair type.
2086// Key(inner_matcher) matches an std::pair whose 'first' field matches
2087// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2088// std::map that contains at least one element whose key is >= 5.
2089template <typename PairType>
2090class KeyMatcherImpl : public MatcherInterface<PairType> {
2091 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00002092 typedef GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(PairType)) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002093 typedef typename RawPairType::first_type KeyType;
2094
2095 template <typename InnerMatcher>
2096 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2097 : inner_matcher_(
2098 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2099 }
2100
2101 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002102 virtual bool MatchAndExplain(PairType key_value,
2103 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002104 StringMatchResultListener inner_listener;
2105 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2106 &inner_listener);
2107 const internal::string explanation = inner_listener.str();
2108 if (explanation != "") {
2109 *listener << "whose first field is a value " << explanation;
2110 }
2111 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002112 }
2113
2114 // Describes what this matcher does.
2115 virtual void DescribeTo(::std::ostream* os) const {
2116 *os << "has a key that ";
2117 inner_matcher_.DescribeTo(os);
2118 }
2119
2120 // Describes what the negation of this matcher does.
2121 virtual void DescribeNegationTo(::std::ostream* os) const {
2122 *os << "doesn't have a key that ";
2123 inner_matcher_.DescribeTo(os);
2124 }
2125
zhanyong.wanb5937da2009-07-16 20:26:41 +00002126 private:
2127 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002128
2129 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002130};
2131
2132// Implements polymorphic Key(matcher_for_key).
2133template <typename M>
2134class KeyMatcher {
2135 public:
2136 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2137
2138 template <typename PairType>
2139 operator Matcher<PairType>() const {
2140 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2141 }
2142
2143 private:
2144 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002145
2146 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002147};
2148
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002149// Implements Pair(first_matcher, second_matcher) for the given argument pair
2150// type with its two matchers. See Pair() function below.
2151template <typename PairType>
2152class PairMatcherImpl : public MatcherInterface<PairType> {
2153 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00002154 typedef GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(PairType)) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002155 typedef typename RawPairType::first_type FirstType;
2156 typedef typename RawPairType::second_type SecondType;
2157
2158 template <typename FirstMatcher, typename SecondMatcher>
2159 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2160 : first_matcher_(
2161 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2162 second_matcher_(
2163 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2164 }
2165
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002166 // Describes what this matcher does.
2167 virtual void DescribeTo(::std::ostream* os) const {
2168 *os << "has a first field that ";
2169 first_matcher_.DescribeTo(os);
2170 *os << ", and has a second field that ";
2171 second_matcher_.DescribeTo(os);
2172 }
2173
2174 // Describes what the negation of this matcher does.
2175 virtual void DescribeNegationTo(::std::ostream* os) const {
2176 *os << "has a first field that ";
2177 first_matcher_.DescribeNegationTo(os);
2178 *os << ", or has a second field that ";
2179 second_matcher_.DescribeNegationTo(os);
2180 }
2181
zhanyong.wan82113312010-01-08 21:55:40 +00002182 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2183 // matches second_matcher.
2184 virtual bool MatchAndExplain(PairType a_pair,
2185 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002186 if (!listener->IsInterested()) {
2187 // If the listener is not interested, we don't need to construct the
2188 // explanation.
2189 return first_matcher_.Matches(a_pair.first) &&
2190 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00002191 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002192 StringMatchResultListener first_inner_listener;
2193 if (!first_matcher_.MatchAndExplain(a_pair.first,
2194 &first_inner_listener)) {
2195 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002196 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002197 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002198 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002199 StringMatchResultListener second_inner_listener;
2200 if (!second_matcher_.MatchAndExplain(a_pair.second,
2201 &second_inner_listener)) {
2202 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002203 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002204 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002205 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002206 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
2207 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00002208 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002209 }
2210
2211 private:
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002212 void ExplainSuccess(const internal::string& first_explanation,
2213 const internal::string& second_explanation,
2214 MatchResultListener* listener) const {
2215 *listener << "whose both fields match";
2216 if (first_explanation != "") {
2217 *listener << ", where the first field is a value " << first_explanation;
2218 }
2219 if (second_explanation != "") {
2220 *listener << ", ";
2221 if (first_explanation != "") {
2222 *listener << "and ";
2223 } else {
2224 *listener << "where ";
2225 }
2226 *listener << "the second field is a value " << second_explanation;
2227 }
2228 }
2229
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002230 const Matcher<const FirstType&> first_matcher_;
2231 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002232
2233 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002234};
2235
2236// Implements polymorphic Pair(first_matcher, second_matcher).
2237template <typename FirstMatcher, typename SecondMatcher>
2238class PairMatcher {
2239 public:
2240 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2241 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2242
2243 template <typename PairType>
2244 operator Matcher<PairType> () const {
2245 return MakeMatcher(
2246 new PairMatcherImpl<PairType>(
2247 first_matcher_, second_matcher_));
2248 }
2249
2250 private:
2251 const FirstMatcher first_matcher_;
2252 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002253
2254 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002255};
2256
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002257// Implements ElementsAre() and ElementsAreArray().
2258template <typename Container>
2259class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2260 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00002261 typedef GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(Container)) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002262 typedef internal::StlContainerView<RawContainer> View;
2263 typedef typename View::type StlContainer;
2264 typedef typename View::const_reference StlContainerReference;
2265 typedef typename StlContainer::value_type Element;
2266
2267 // Constructs the matcher from a sequence of element values or
2268 // element matchers.
2269 template <typename InputIter>
zhanyong.wan32de5f52009-12-23 00:13:23 +00002270 ElementsAreMatcherImpl(InputIter first, size_t a_count) {
2271 matchers_.reserve(a_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002272 InputIter it = first;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002273 for (size_t i = 0; i != a_count; ++i, ++it) {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002274 matchers_.push_back(MatcherCast<const Element&>(*it));
2275 }
2276 }
2277
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002278 // Describes what this matcher does.
2279 virtual void DescribeTo(::std::ostream* os) const {
2280 if (count() == 0) {
2281 *os << "is empty";
2282 } else if (count() == 1) {
2283 *os << "has 1 element that ";
2284 matchers_[0].DescribeTo(os);
2285 } else {
2286 *os << "has " << Elements(count()) << " where\n";
2287 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002288 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002289 matchers_[i].DescribeTo(os);
2290 if (i + 1 < count()) {
2291 *os << ",\n";
2292 }
2293 }
2294 }
2295 }
2296
2297 // Describes what the negation of this matcher does.
2298 virtual void DescribeNegationTo(::std::ostream* os) const {
2299 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002300 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002301 return;
2302 }
2303
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002304 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002305 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002306 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002307 matchers_[i].DescribeNegationTo(os);
2308 if (i + 1 < count()) {
2309 *os << ", or\n";
2310 }
2311 }
2312 }
2313
zhanyong.wan82113312010-01-08 21:55:40 +00002314 virtual bool MatchAndExplain(Container container,
2315 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002316 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002317 const size_t actual_count = stl_container.size();
2318 if (actual_count != count()) {
2319 // The element count doesn't match. If the container is empty,
2320 // there's no need to explain anything as Google Mock already
2321 // prints the empty container. Otherwise we just need to show
2322 // how many elements there actually are.
2323 if (actual_count != 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002324 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002325 }
zhanyong.wan82113312010-01-08 21:55:40 +00002326 return false;
2327 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002328
zhanyong.wan82113312010-01-08 21:55:40 +00002329 typename StlContainer::const_iterator it = stl_container.begin();
2330 // explanations[i] is the explanation of the element at index i.
2331 std::vector<internal::string> explanations(count());
2332 for (size_t i = 0; i != count(); ++it, ++i) {
2333 StringMatchResultListener s;
2334 if (matchers_[i].MatchAndExplain(*it, &s)) {
2335 explanations[i] = s.str();
2336 } else {
2337 // The container has the right size but the i-th element
2338 // doesn't match its expectation.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002339 *listener << "whose element #" << i << " doesn't match";
2340 PrintIfNotEmpty(s.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002341 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002342 }
2343 }
zhanyong.wan82113312010-01-08 21:55:40 +00002344
2345 // Every element matches its expectation. We need to explain why
2346 // (the obvious ones can be skipped).
zhanyong.wan82113312010-01-08 21:55:40 +00002347 bool reason_printed = false;
2348 for (size_t i = 0; i != count(); ++i) {
2349 const internal::string& s = explanations[i];
2350 if (!s.empty()) {
2351 if (reason_printed) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002352 *listener << ",\nand ";
zhanyong.wan82113312010-01-08 21:55:40 +00002353 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002354 *listener << "whose element #" << i << " matches, " << s;
zhanyong.wan82113312010-01-08 21:55:40 +00002355 reason_printed = true;
2356 }
2357 }
2358
2359 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002360 }
2361
2362 private:
2363 static Message Elements(size_t count) {
2364 return Message() << count << (count == 1 ? " element" : " elements");
2365 }
2366
2367 size_t count() const { return matchers_.size(); }
2368 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002369
2370 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002371};
2372
2373// Implements ElementsAre() of 0 arguments.
2374class ElementsAreMatcher0 {
2375 public:
2376 ElementsAreMatcher0() {}
2377
2378 template <typename Container>
2379 operator Matcher<Container>() const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002380 typedef GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(Container))
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002381 RawContainer;
2382 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2383 Element;
2384
2385 const Matcher<const Element&>* const matchers = NULL;
2386 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 0));
2387 }
2388};
2389
2390// Implements ElementsAreArray().
2391template <typename T>
2392class ElementsAreArrayMatcher {
2393 public:
2394 ElementsAreArrayMatcher(const T* first, size_t count) :
2395 first_(first), count_(count) {}
2396
2397 template <typename Container>
2398 operator Matcher<Container>() const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002399 typedef GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(Container))
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002400 RawContainer;
2401 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2402 Element;
2403
2404 return MakeMatcher(new ElementsAreMatcherImpl<Container>(first_, count_));
2405 }
2406
2407 private:
2408 const T* const first_;
2409 const size_t count_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002410
2411 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002412};
2413
2414// Constants denoting interpolations in a matcher description string.
2415const int kTupleInterpolation = -1; // "%(*)s"
2416const int kPercentInterpolation = -2; // "%%"
2417const int kInvalidInterpolation = -3; // "%" followed by invalid text
2418
2419// Records the location and content of an interpolation.
2420struct Interpolation {
2421 Interpolation(const char* start, const char* end, int param)
2422 : start_pos(start), end_pos(end), param_index(param) {}
2423
2424 // Points to the start of the interpolation (the '%' character).
2425 const char* start_pos;
2426 // Points to the first character after the interpolation.
2427 const char* end_pos;
2428 // 0-based index of the interpolated matcher parameter;
2429 // kTupleInterpolation for "%(*)s"; kPercentInterpolation for "%%".
2430 int param_index;
2431};
2432
2433typedef ::std::vector<Interpolation> Interpolations;
2434
2435// Parses a matcher description string and returns a vector of
2436// interpolations that appear in the string; generates non-fatal
2437// failures iff 'description' is an invalid matcher description.
2438// 'param_names' is a NULL-terminated array of parameter names in the
2439// order they appear in the MATCHER_P*() parameter list.
2440Interpolations ValidateMatcherDescription(
2441 const char* param_names[], const char* description);
2442
2443// Returns the actual matcher description, given the matcher name,
2444// user-supplied description template string, interpolations in the
2445// string, and the printed values of the matcher parameters.
2446string FormatMatcherDescription(
2447 const char* matcher_name, const char* description,
2448 const Interpolations& interp, const Strings& param_values);
2449
shiqiane35fdd92008-12-10 05:08:54 +00002450} // namespace internal
2451
2452// Implements MatcherCast().
2453template <typename T, typename M>
2454inline Matcher<T> MatcherCast(M matcher) {
2455 return internal::MatcherCastImpl<T, M>::Cast(matcher);
2456}
2457
2458// _ is a matcher that matches anything of any type.
2459//
2460// This definition is fine as:
2461//
2462// 1. The C++ standard permits using the name _ in a namespace that
2463// is not the global namespace or ::std.
2464// 2. The AnythingMatcher class has no data member or constructor,
2465// so it's OK to create global variables of this type.
2466// 3. c-style has approved of using _ in this case.
2467const internal::AnythingMatcher _ = {};
2468// Creates a matcher that matches any value of the given type T.
2469template <typename T>
2470inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2471
2472// Creates a matcher that matches any value of the given type T.
2473template <typename T>
2474inline Matcher<T> An() { return A<T>(); }
2475
2476// Creates a polymorphic matcher that matches anything equal to x.
2477// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2478// wouldn't compile.
2479template <typename T>
2480inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2481
2482// Constructs a Matcher<T> from a 'value' of type T. The constructed
2483// matcher matches any value that's equal to 'value'.
2484template <typename T>
2485Matcher<T>::Matcher(T value) { *this = Eq(value); }
2486
2487// Creates a monomorphic matcher that matches anything with type Lhs
2488// and equal to rhs. A user may need to use this instead of Eq(...)
2489// in order to resolve an overloading ambiguity.
2490//
2491// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2492// or Matcher<T>(x), but more readable than the latter.
2493//
2494// We could define similar monomorphic matchers for other comparison
2495// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2496// it yet as those are used much less than Eq() in practice. A user
2497// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2498// for example.
2499template <typename Lhs, typename Rhs>
2500inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2501
2502// Creates a polymorphic matcher that matches anything >= x.
2503template <typename Rhs>
2504inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2505 return internal::GeMatcher<Rhs>(x);
2506}
2507
2508// Creates a polymorphic matcher that matches anything > x.
2509template <typename Rhs>
2510inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2511 return internal::GtMatcher<Rhs>(x);
2512}
2513
2514// Creates a polymorphic matcher that matches anything <= x.
2515template <typename Rhs>
2516inline internal::LeMatcher<Rhs> Le(Rhs x) {
2517 return internal::LeMatcher<Rhs>(x);
2518}
2519
2520// Creates a polymorphic matcher that matches anything < x.
2521template <typename Rhs>
2522inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2523 return internal::LtMatcher<Rhs>(x);
2524}
2525
2526// Creates a polymorphic matcher that matches anything != x.
2527template <typename Rhs>
2528inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2529 return internal::NeMatcher<Rhs>(x);
2530}
2531
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002532// Creates a polymorphic matcher that matches any NULL pointer.
2533inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2534 return MakePolymorphicMatcher(internal::IsNullMatcher());
2535}
2536
shiqiane35fdd92008-12-10 05:08:54 +00002537// Creates a polymorphic matcher that matches any non-NULL pointer.
2538// This is convenient as Not(NULL) doesn't compile (the compiler
2539// thinks that that expression is comparing a pointer with an integer).
2540inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2541 return MakePolymorphicMatcher(internal::NotNullMatcher());
2542}
2543
2544// Creates a polymorphic matcher that matches any argument that
2545// references variable x.
2546template <typename T>
2547inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2548 return internal::RefMatcher<T&>(x);
2549}
2550
2551// Creates a matcher that matches any double argument approximately
2552// equal to rhs, where two NANs are considered unequal.
2553inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2554 return internal::FloatingEqMatcher<double>(rhs, false);
2555}
2556
2557// Creates a matcher that matches any double argument approximately
2558// equal to rhs, including NaN values when rhs is NaN.
2559inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2560 return internal::FloatingEqMatcher<double>(rhs, true);
2561}
2562
2563// Creates a matcher that matches any float argument approximately
2564// equal to rhs, where two NANs are considered unequal.
2565inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2566 return internal::FloatingEqMatcher<float>(rhs, false);
2567}
2568
2569// Creates a matcher that matches any double argument approximately
2570// equal to rhs, including NaN values when rhs is NaN.
2571inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2572 return internal::FloatingEqMatcher<float>(rhs, true);
2573}
2574
2575// Creates a matcher that matches a pointer (raw or smart) that points
2576// to a value that matches inner_matcher.
2577template <typename InnerMatcher>
2578inline internal::PointeeMatcher<InnerMatcher> Pointee(
2579 const InnerMatcher& inner_matcher) {
2580 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2581}
2582
2583// Creates a matcher that matches an object whose given field matches
2584// 'matcher'. For example,
2585// Field(&Foo::number, Ge(5))
2586// matches a Foo object x iff x.number >= 5.
2587template <typename Class, typename FieldType, typename FieldMatcher>
2588inline PolymorphicMatcher<
2589 internal::FieldMatcher<Class, FieldType> > Field(
2590 FieldType Class::*field, const FieldMatcher& matcher) {
2591 return MakePolymorphicMatcher(
2592 internal::FieldMatcher<Class, FieldType>(
2593 field, MatcherCast<const FieldType&>(matcher)));
2594 // The call to MatcherCast() is required for supporting inner
2595 // matchers of compatible types. For example, it allows
2596 // Field(&Foo::bar, m)
2597 // to compile where bar is an int32 and m is a matcher for int64.
2598}
2599
2600// Creates a matcher that matches an object whose given property
2601// matches 'matcher'. For example,
2602// Property(&Foo::str, StartsWith("hi"))
2603// matches a Foo object x iff x.str() starts with "hi".
2604template <typename Class, typename PropertyType, typename PropertyMatcher>
2605inline PolymorphicMatcher<
2606 internal::PropertyMatcher<Class, PropertyType> > Property(
2607 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2608 return MakePolymorphicMatcher(
2609 internal::PropertyMatcher<Class, PropertyType>(
2610 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00002611 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002612 // The call to MatcherCast() is required for supporting inner
2613 // matchers of compatible types. For example, it allows
2614 // Property(&Foo::bar, m)
2615 // to compile where bar() returns an int32 and m is a matcher for int64.
2616}
2617
2618// Creates a matcher that matches an object iff the result of applying
2619// a callable to x matches 'matcher'.
2620// For example,
2621// ResultOf(f, StartsWith("hi"))
2622// matches a Foo object x iff f(x) starts with "hi".
2623// callable parameter can be a function, function pointer, or a functor.
2624// Callable has to satisfy the following conditions:
2625// * It is required to keep no state affecting the results of
2626// the calls on it and make no assumptions about how many calls
2627// will be made. Any state it keeps must be protected from the
2628// concurrent access.
2629// * If it is a function object, it has to define type result_type.
2630// We recommend deriving your functor classes from std::unary_function.
2631template <typename Callable, typename ResultOfMatcher>
2632internal::ResultOfMatcher<Callable> ResultOf(
2633 Callable callable, const ResultOfMatcher& matcher) {
2634 return internal::ResultOfMatcher<Callable>(
2635 callable,
2636 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2637 matcher));
2638 // The call to MatcherCast() is required for supporting inner
2639 // matchers of compatible types. For example, it allows
2640 // ResultOf(Function, m)
2641 // to compile where Function() returns an int32 and m is a matcher for int64.
2642}
2643
2644// String matchers.
2645
2646// Matches a string equal to str.
2647inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2648 StrEq(const internal::string& str) {
2649 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2650 str, true, true));
2651}
2652
2653// Matches a string not equal to str.
2654inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2655 StrNe(const internal::string& str) {
2656 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2657 str, false, true));
2658}
2659
2660// Matches a string equal to str, ignoring case.
2661inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2662 StrCaseEq(const internal::string& str) {
2663 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2664 str, true, false));
2665}
2666
2667// Matches a string not equal to str, ignoring case.
2668inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2669 StrCaseNe(const internal::string& str) {
2670 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2671 str, false, false));
2672}
2673
2674// Creates a matcher that matches any string, std::string, or C string
2675// that contains the given substring.
2676inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2677 HasSubstr(const internal::string& substring) {
2678 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
2679 substring));
2680}
2681
2682// Matches a string that starts with 'prefix' (case-sensitive).
2683inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
2684 StartsWith(const internal::string& prefix) {
2685 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
2686 prefix));
2687}
2688
2689// Matches a string that ends with 'suffix' (case-sensitive).
2690inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
2691 EndsWith(const internal::string& suffix) {
2692 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
2693 suffix));
2694}
2695
shiqiane35fdd92008-12-10 05:08:54 +00002696// Matches a string that fully matches regular expression 'regex'.
2697// The matcher takes ownership of 'regex'.
2698inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2699 const internal::RE* regex) {
2700 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2701}
2702inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2703 const internal::string& regex) {
2704 return MatchesRegex(new internal::RE(regex));
2705}
2706
2707// Matches a string that contains regular expression 'regex'.
2708// The matcher takes ownership of 'regex'.
2709inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2710 const internal::RE* regex) {
2711 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2712}
2713inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2714 const internal::string& regex) {
2715 return ContainsRegex(new internal::RE(regex));
2716}
2717
shiqiane35fdd92008-12-10 05:08:54 +00002718#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2719// Wide string matchers.
2720
2721// Matches a string equal to str.
2722inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2723 StrEq(const internal::wstring& str) {
2724 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2725 str, true, true));
2726}
2727
2728// Matches a string not equal to str.
2729inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2730 StrNe(const internal::wstring& str) {
2731 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2732 str, false, true));
2733}
2734
2735// Matches a string equal to str, ignoring case.
2736inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2737 StrCaseEq(const internal::wstring& str) {
2738 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2739 str, true, false));
2740}
2741
2742// Matches a string not equal to str, ignoring case.
2743inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2744 StrCaseNe(const internal::wstring& str) {
2745 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2746 str, false, false));
2747}
2748
2749// Creates a matcher that matches any wstring, std::wstring, or C wide string
2750// that contains the given substring.
2751inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2752 HasSubstr(const internal::wstring& substring) {
2753 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2754 substring));
2755}
2756
2757// Matches a string that starts with 'prefix' (case-sensitive).
2758inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2759 StartsWith(const internal::wstring& prefix) {
2760 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2761 prefix));
2762}
2763
2764// Matches a string that ends with 'suffix' (case-sensitive).
2765inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2766 EndsWith(const internal::wstring& suffix) {
2767 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2768 suffix));
2769}
2770
2771#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2772
2773// Creates a polymorphic matcher that matches a 2-tuple where the
2774// first field == the second field.
2775inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2776
2777// Creates a polymorphic matcher that matches a 2-tuple where the
2778// first field >= the second field.
2779inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2780
2781// Creates a polymorphic matcher that matches a 2-tuple where the
2782// first field > the second field.
2783inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2784
2785// Creates a polymorphic matcher that matches a 2-tuple where the
2786// first field <= the second field.
2787inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2788
2789// Creates a polymorphic matcher that matches a 2-tuple where the
2790// first field < the second field.
2791inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2792
2793// Creates a polymorphic matcher that matches a 2-tuple where the
2794// first field != the second field.
2795inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2796
2797// Creates a matcher that matches any value of type T that m doesn't
2798// match.
2799template <typename InnerMatcher>
2800inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2801 return internal::NotMatcher<InnerMatcher>(m);
2802}
2803
2804// Creates a matcher that matches any value that matches all of the
2805// given matchers.
2806//
2807// For now we only support up to 5 matchers. Support for more
2808// matchers can be added as needed, or the user can use nested
2809// AllOf()s.
2810template <typename Matcher1, typename Matcher2>
2811inline internal::BothOfMatcher<Matcher1, Matcher2>
2812AllOf(Matcher1 m1, Matcher2 m2) {
2813 return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2);
2814}
2815
2816template <typename Matcher1, typename Matcher2, typename Matcher3>
2817inline internal::BothOfMatcher<Matcher1,
2818 internal::BothOfMatcher<Matcher2, Matcher3> >
2819AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2820 return AllOf(m1, AllOf(m2, m3));
2821}
2822
2823template <typename Matcher1, typename Matcher2, typename Matcher3,
2824 typename Matcher4>
2825inline internal::BothOfMatcher<Matcher1,
2826 internal::BothOfMatcher<Matcher2,
2827 internal::BothOfMatcher<Matcher3, Matcher4> > >
2828AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2829 return AllOf(m1, AllOf(m2, m3, m4));
2830}
2831
2832template <typename Matcher1, typename Matcher2, typename Matcher3,
2833 typename Matcher4, typename Matcher5>
2834inline internal::BothOfMatcher<Matcher1,
2835 internal::BothOfMatcher<Matcher2,
2836 internal::BothOfMatcher<Matcher3,
2837 internal::BothOfMatcher<Matcher4, Matcher5> > > >
2838AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2839 return AllOf(m1, AllOf(m2, m3, m4, m5));
2840}
2841
2842// Creates a matcher that matches any value that matches at least one
2843// of the given matchers.
2844//
2845// For now we only support up to 5 matchers. Support for more
2846// matchers can be added as needed, or the user can use nested
2847// AnyOf()s.
2848template <typename Matcher1, typename Matcher2>
2849inline internal::EitherOfMatcher<Matcher1, Matcher2>
2850AnyOf(Matcher1 m1, Matcher2 m2) {
2851 return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2);
2852}
2853
2854template <typename Matcher1, typename Matcher2, typename Matcher3>
2855inline internal::EitherOfMatcher<Matcher1,
2856 internal::EitherOfMatcher<Matcher2, Matcher3> >
2857AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2858 return AnyOf(m1, AnyOf(m2, m3));
2859}
2860
2861template <typename Matcher1, typename Matcher2, typename Matcher3,
2862 typename Matcher4>
2863inline internal::EitherOfMatcher<Matcher1,
2864 internal::EitherOfMatcher<Matcher2,
2865 internal::EitherOfMatcher<Matcher3, Matcher4> > >
2866AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2867 return AnyOf(m1, AnyOf(m2, m3, m4));
2868}
2869
2870template <typename Matcher1, typename Matcher2, typename Matcher3,
2871 typename Matcher4, typename Matcher5>
2872inline internal::EitherOfMatcher<Matcher1,
2873 internal::EitherOfMatcher<Matcher2,
2874 internal::EitherOfMatcher<Matcher3,
2875 internal::EitherOfMatcher<Matcher4, Matcher5> > > >
2876AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2877 return AnyOf(m1, AnyOf(m2, m3, m4, m5));
2878}
2879
2880// Returns a matcher that matches anything that satisfies the given
2881// predicate. The predicate can be any unary function or functor
2882// whose return type can be implicitly converted to bool.
2883template <typename Predicate>
2884inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
2885Truly(Predicate pred) {
2886 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
2887}
2888
zhanyong.wan6a896b52009-01-16 01:13:50 +00002889// Returns a matcher that matches an equal container.
2890// This matcher behaves like Eq(), but in the event of mismatch lists the
2891// values that are included in one container but not the other. (Duplicate
2892// values and order differences are not explained.)
2893template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00002894inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00002895 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00002896 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002897 // This following line is for working around a bug in MSVC 8.0,
2898 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002899 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00002900 return MakePolymorphicMatcher(
2901 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00002902}
2903
2904// Matches an STL-style container or a native array that contains at
2905// least one element matching the given value or matcher.
2906//
2907// Examples:
2908// ::std::set<int> page_ids;
2909// page_ids.insert(3);
2910// page_ids.insert(1);
2911// EXPECT_THAT(page_ids, Contains(1));
2912// EXPECT_THAT(page_ids, Contains(Gt(2)));
2913// EXPECT_THAT(page_ids, Not(Contains(4)));
2914//
2915// ::std::map<int, size_t> page_lengths;
2916// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00002917// EXPECT_THAT(page_lengths,
2918// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00002919//
2920// const char* user_ids[] = { "joe", "mike", "tom" };
2921// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
2922template <typename M>
2923inline internal::ContainsMatcher<M> Contains(M matcher) {
2924 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002925}
2926
zhanyong.wan33605ba2010-04-22 23:37:47 +00002927// Matches an STL-style container or a native array that contains only
2928// elements matching the given value or matcher.
2929//
2930// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
2931// the messages are different.
2932//
2933// Examples:
2934// ::std::set<int> page_ids;
2935// // Each(m) matches an empty container, regardless of what m is.
2936// EXPECT_THAT(page_ids, Each(Eq(1)));
2937// EXPECT_THAT(page_ids, Each(Eq(77)));
2938//
2939// page_ids.insert(3);
2940// EXPECT_THAT(page_ids, Each(Gt(0)));
2941// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
2942// page_ids.insert(1);
2943// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
2944//
2945// ::std::map<int, size_t> page_lengths;
2946// page_lengths[1] = 100;
2947// page_lengths[2] = 200;
2948// page_lengths[3] = 300;
2949// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
2950// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
2951//
2952// const char* user_ids[] = { "joe", "mike", "tom" };
2953// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
2954template <typename M>
2955inline internal::EachMatcher<M> Each(M matcher) {
2956 return internal::EachMatcher<M>(matcher);
2957}
2958
zhanyong.wanb5937da2009-07-16 20:26:41 +00002959// Key(inner_matcher) matches an std::pair whose 'first' field matches
2960// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2961// std::map that contains at least one element whose key is >= 5.
2962template <typename M>
2963inline internal::KeyMatcher<M> Key(M inner_matcher) {
2964 return internal::KeyMatcher<M>(inner_matcher);
2965}
2966
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002967// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
2968// matches first_matcher and whose 'second' field matches second_matcher. For
2969// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
2970// to match a std::map<int, string> that contains exactly one element whose key
2971// is >= 5 and whose value equals "foo".
2972template <typename FirstMatcher, typename SecondMatcher>
2973inline internal::PairMatcher<FirstMatcher, SecondMatcher>
2974Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
2975 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
2976 first_matcher, second_matcher);
2977}
2978
shiqiane35fdd92008-12-10 05:08:54 +00002979// Returns a predicate that is satisfied by anything that matches the
2980// given matcher.
2981template <typename M>
2982inline internal::MatcherAsPredicate<M> Matches(M matcher) {
2983 return internal::MatcherAsPredicate<M>(matcher);
2984}
2985
zhanyong.wanb8243162009-06-04 05:48:20 +00002986// Returns true iff the value matches the matcher.
2987template <typename T, typename M>
2988inline bool Value(const T& value, M matcher) {
2989 return testing::Matches(matcher)(value);
2990}
2991
zhanyong.wan34b034c2010-03-05 21:23:23 +00002992// Matches the value against the given matcher and explains the match
2993// result to listener.
2994template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00002995inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00002996 M matcher, const T& value, MatchResultListener* listener) {
2997 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
2998}
2999
zhanyong.wanbf550852009-06-09 06:09:53 +00003000// AllArgs(m) is a synonym of m. This is useful in
3001//
3002// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
3003//
3004// which is easier to read than
3005//
3006// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
3007template <typename InnerMatcher>
3008inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
3009
shiqiane35fdd92008-12-10 05:08:54 +00003010// These macros allow using matchers to check values in Google Test
3011// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
3012// succeed iff the value matches the matcher. If the assertion fails,
3013// the value and the description of the matcher will be printed.
3014#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
3015 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3016#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
3017 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3018
3019} // namespace testing
3020
3021#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_