blob: 2a42bf949f41635e3df8862a173d1997d5b5f54e [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>
zhanyong.wanab5b77c2010-05-17 19:32:48 +000046#include <utility>
shiqiane35fdd92008-12-10 05:08:54 +000047#include <vector>
48
shiqiane35fdd92008-12-10 05:08:54 +000049#include <gmock/internal/gmock-internal-utils.h>
50#include <gmock/internal/gmock-port.h>
51#include <gtest/gtest.h>
52
53namespace testing {
54
55// To implement a matcher Foo for type T, define:
56// 1. a class FooMatcherImpl that implements the
57// MatcherInterface<T> interface, and
58// 2. a factory function that creates a Matcher<T> object from a
59// FooMatcherImpl*.
60//
61// The two-level delegation design makes it possible to allow a user
62// to write "v" instead of "Eq(v)" where a Matcher is expected, which
63// is impossible if we pass matchers by pointers. It also eases
64// ownership management as Matcher objects can now be copied like
65// plain values.
66
zhanyong.wan82113312010-01-08 21:55:40 +000067// MatchResultListener is an abstract class. Its << operator can be
68// used by a matcher to explain why a value matches or doesn't match.
69//
70// TODO(wan@google.com): add method
71// bool InterestedInWhy(bool result) const;
72// to indicate whether the listener is interested in why the match
73// result is 'result'.
74class MatchResultListener {
75 public:
76 // Creates a listener object with the given underlying ostream. The
77 // listener does not own the ostream.
78 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
79 virtual ~MatchResultListener() = 0; // Makes this class abstract.
80
81 // Streams x to the underlying ostream; does nothing if the ostream
82 // is NULL.
83 template <typename T>
84 MatchResultListener& operator<<(const T& x) {
85 if (stream_ != NULL)
86 *stream_ << x;
87 return *this;
88 }
89
90 // Returns the underlying ostream.
91 ::std::ostream* stream() { return stream_; }
92
zhanyong.wana862f1d2010-03-15 21:23:04 +000093 // Returns true iff the listener is interested in an explanation of
94 // the match result. A matcher's MatchAndExplain() method can use
95 // this information to avoid generating the explanation when no one
96 // intends to hear it.
97 bool IsInterested() const { return stream_ != NULL; }
98
zhanyong.wan82113312010-01-08 21:55:40 +000099 private:
100 ::std::ostream* const stream_;
101
102 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
103};
104
105inline MatchResultListener::~MatchResultListener() {
106}
107
shiqiane35fdd92008-12-10 05:08:54 +0000108// The implementation of a matcher.
109template <typename T>
110class MatcherInterface {
111 public:
112 virtual ~MatcherInterface() {}
113
zhanyong.wan82113312010-01-08 21:55:40 +0000114 // Returns true iff the matcher matches x; also explains the match
zhanyong.wana862f1d2010-03-15 21:23:04 +0000115 // result to 'listener', in the form of a non-restrictive relative
116 // clause ("which ...", "whose ...", etc) that describes x. For
117 // example, the MatchAndExplain() method of the Pointee(...) matcher
118 // should generate an explanation like "which points to ...".
zhanyong.wan82113312010-01-08 21:55:40 +0000119 //
zhanyong.wandb22c222010-01-28 21:52:29 +0000120 // You should override this method when defining a new matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000121 //
122 // It's the responsibility of the caller (Google Mock) to guarantee
123 // that 'listener' is not NULL. This helps to simplify a matcher's
124 // implementation when it doesn't care about the performance, as it
125 // can talk to 'listener' without checking its validity first.
126 // However, in order to implement dummy listeners efficiently,
127 // listener->stream() may be NULL.
zhanyong.wandb22c222010-01-28 21:52:29 +0000128 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
shiqiane35fdd92008-12-10 05:08:54 +0000129
zhanyong.wana862f1d2010-03-15 21:23:04 +0000130 // Describes this matcher to an ostream. The function should print
131 // a verb phrase that describes the property a value matching this
132 // matcher should have. The subject of the verb phrase is the value
133 // being matched. For example, the DescribeTo() method of the Gt(7)
134 // matcher prints "is greater than 7".
shiqiane35fdd92008-12-10 05:08:54 +0000135 virtual void DescribeTo(::std::ostream* os) const = 0;
136
137 // Describes the negation of this matcher to an ostream. For
138 // example, if the description of this matcher is "is greater than
139 // 7", the negated description could be "is not greater than 7".
140 // You are not required to override this when implementing
141 // MatcherInterface, but it is highly advised so that your matcher
142 // can produce good error messages.
143 virtual void DescribeNegationTo(::std::ostream* os) const {
144 *os << "not (";
145 DescribeTo(os);
146 *os << ")";
147 }
shiqiane35fdd92008-12-10 05:08:54 +0000148};
149
150namespace internal {
151
zhanyong.wan82113312010-01-08 21:55:40 +0000152// A match result listener that ignores the explanation.
153class DummyMatchResultListener : public MatchResultListener {
154 public:
155 DummyMatchResultListener() : MatchResultListener(NULL) {}
156
157 private:
158 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
159};
160
161// A match result listener that forwards the explanation to a given
162// ostream. The difference between this and MatchResultListener is
163// that the former is concrete.
164class StreamMatchResultListener : public MatchResultListener {
165 public:
166 explicit StreamMatchResultListener(::std::ostream* os)
167 : MatchResultListener(os) {}
168
169 private:
170 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
171};
172
173// A match result listener that stores the explanation in a string.
174class StringMatchResultListener : public MatchResultListener {
175 public:
176 StringMatchResultListener() : MatchResultListener(&ss_) {}
177
178 // Returns the explanation heard so far.
179 internal::string str() const { return ss_.str(); }
180
181 private:
182 ::std::stringstream ss_;
183
184 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
185};
186
shiqiane35fdd92008-12-10 05:08:54 +0000187// An internal class for implementing Matcher<T>, which will derive
188// from it. We put functionalities common to all Matcher<T>
189// specializations here to avoid code duplication.
190template <typename T>
191class MatcherBase {
192 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000193 // Returns true iff the matcher matches x; also explains the match
194 // result to 'listener'.
195 bool MatchAndExplain(T x, MatchResultListener* listener) const {
196 return impl_->MatchAndExplain(x, listener);
197 }
198
shiqiane35fdd92008-12-10 05:08:54 +0000199 // Returns true iff this matcher matches x.
zhanyong.wan82113312010-01-08 21:55:40 +0000200 bool Matches(T x) const {
201 DummyMatchResultListener dummy;
202 return MatchAndExplain(x, &dummy);
203 }
shiqiane35fdd92008-12-10 05:08:54 +0000204
205 // Describes this matcher to an ostream.
206 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
207
208 // Describes the negation of this matcher to an ostream.
209 void DescribeNegationTo(::std::ostream* os) const {
210 impl_->DescribeNegationTo(os);
211 }
212
213 // Explains why x matches, or doesn't match, the matcher.
214 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000215 StreamMatchResultListener listener(os);
216 MatchAndExplain(x, &listener);
shiqiane35fdd92008-12-10 05:08:54 +0000217 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000218
shiqiane35fdd92008-12-10 05:08:54 +0000219 protected:
220 MatcherBase() {}
221
222 // Constructs a matcher from its implementation.
223 explicit MatcherBase(const MatcherInterface<T>* impl)
224 : impl_(impl) {}
225
226 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000227
shiqiane35fdd92008-12-10 05:08:54 +0000228 private:
229 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
230 // interfaces. The former dynamically allocates a chunk of memory
231 // to hold the reference count, while the latter tracks all
232 // references using a circular linked list without allocating
233 // memory. It has been observed that linked_ptr performs better in
234 // typical scenarios. However, shared_ptr can out-perform
235 // linked_ptr when there are many more uses of the copy constructor
236 // than the default constructor.
237 //
238 // If performance becomes a problem, we should see if using
239 // shared_ptr helps.
240 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
241};
242
shiqiane35fdd92008-12-10 05:08:54 +0000243} // namespace internal
244
245// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
246// object that can check whether a value of type T matches. The
247// implementation of Matcher<T> is just a linked_ptr to const
248// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
249// from Matcher!
250template <typename T>
251class Matcher : public internal::MatcherBase<T> {
252 public:
253 // Constructs a null matcher. Needed for storing Matcher objects in
254 // STL containers.
255 Matcher() {}
256
257 // Constructs a matcher from its implementation.
258 explicit Matcher(const MatcherInterface<T>* impl)
259 : internal::MatcherBase<T>(impl) {}
260
zhanyong.wan18490652009-05-11 18:54:08 +0000261 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000262 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
263 Matcher(T value); // NOLINT
264};
265
266// The following two specializations allow the user to write str
267// instead of Eq(str) and "foo" instead of Eq("foo") when a string
268// matcher is expected.
269template <>
270class Matcher<const internal::string&>
271 : public internal::MatcherBase<const internal::string&> {
272 public:
273 Matcher() {}
274
275 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
276 : internal::MatcherBase<const internal::string&>(impl) {}
277
278 // Allows the user to write str instead of Eq(str) sometimes, where
279 // str is a string object.
280 Matcher(const internal::string& s); // NOLINT
281
282 // Allows the user to write "foo" instead of Eq("foo") sometimes.
283 Matcher(const char* s); // NOLINT
284};
285
286template <>
287class Matcher<internal::string>
288 : public internal::MatcherBase<internal::string> {
289 public:
290 Matcher() {}
291
292 explicit Matcher(const MatcherInterface<internal::string>* impl)
293 : internal::MatcherBase<internal::string>(impl) {}
294
295 // Allows the user to write str instead of Eq(str) sometimes, where
296 // str is a string object.
297 Matcher(const internal::string& s); // NOLINT
298
299 // Allows the user to write "foo" instead of Eq("foo") sometimes.
300 Matcher(const char* s); // NOLINT
301};
302
303// The PolymorphicMatcher class template makes it easy to implement a
304// polymorphic matcher (i.e. a matcher that can match values of more
305// than one type, e.g. Eq(n) and NotNull()).
306//
zhanyong.wandb22c222010-01-28 21:52:29 +0000307// To define a polymorphic matcher, a user should provide an Impl
308// class that has a DescribeTo() method and a DescribeNegationTo()
309// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000310//
zhanyong.wandb22c222010-01-28 21:52:29 +0000311// bool MatchAndExplain(const Value& value,
312// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000313//
314// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000315template <class Impl>
316class PolymorphicMatcher {
317 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000318 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000319
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000320 // Returns a mutable reference to the underlying matcher
321 // implementation object.
322 Impl& mutable_impl() { return impl_; }
323
324 // Returns an immutable reference to the underlying matcher
325 // implementation object.
326 const Impl& impl() const { return impl_; }
327
shiqiane35fdd92008-12-10 05:08:54 +0000328 template <typename T>
329 operator Matcher<T>() const {
330 return Matcher<T>(new MonomorphicImpl<T>(impl_));
331 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000332
shiqiane35fdd92008-12-10 05:08:54 +0000333 private:
334 template <typename T>
335 class MonomorphicImpl : public MatcherInterface<T> {
336 public:
337 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
338
shiqiane35fdd92008-12-10 05:08:54 +0000339 virtual void DescribeTo(::std::ostream* os) const {
340 impl_.DescribeTo(os);
341 }
342
343 virtual void DescribeNegationTo(::std::ostream* os) const {
344 impl_.DescribeNegationTo(os);
345 }
346
zhanyong.wan82113312010-01-08 21:55:40 +0000347 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000348 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000349 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000350
shiqiane35fdd92008-12-10 05:08:54 +0000351 private:
352 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000353
354 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000355 };
356
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000357 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000358
359 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000360};
361
362// Creates a matcher from its implementation. This is easier to use
363// than the Matcher<T> constructor as it doesn't require you to
364// explicitly write the template argument, e.g.
365//
366// MakeMatcher(foo);
367// vs
368// Matcher<const string&>(foo);
369template <typename T>
370inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
371 return Matcher<T>(impl);
372};
373
374// Creates a polymorphic matcher from its implementation. This is
375// easier to use than the PolymorphicMatcher<Impl> constructor as it
376// doesn't require you to explicitly write the template argument, e.g.
377//
378// MakePolymorphicMatcher(foo);
379// vs
380// PolymorphicMatcher<TypeOfFoo>(foo);
381template <class Impl>
382inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
383 return PolymorphicMatcher<Impl>(impl);
384}
385
386// In order to be safe and clear, casting between different matcher
387// types is done explicitly via MatcherCast<T>(m), which takes a
388// matcher m and returns a Matcher<T>. It compiles only when T can be
389// statically converted to the argument type of m.
390template <typename T, typename M>
391Matcher<T> MatcherCast(M m);
392
zhanyong.wan18490652009-05-11 18:54:08 +0000393// Implements SafeMatcherCast().
394//
zhanyong.wan95b12332009-09-25 18:55:50 +0000395// We use an intermediate class to do the actual safe casting as Nokia's
396// Symbian compiler cannot decide between
397// template <T, M> ... (M) and
398// template <T, U> ... (const Matcher<U>&)
399// for function templates but can for member function templates.
400template <typename T>
401class SafeMatcherCastImpl {
402 public:
403 // This overload handles polymorphic matchers only since monomorphic
404 // matchers are handled by the next one.
405 template <typename M>
406 static inline Matcher<T> Cast(M polymorphic_matcher) {
407 return Matcher<T>(polymorphic_matcher);
408 }
zhanyong.wan18490652009-05-11 18:54:08 +0000409
zhanyong.wan95b12332009-09-25 18:55:50 +0000410 // This overload handles monomorphic matchers.
411 //
412 // In general, if type T can be implicitly converted to type U, we can
413 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
414 // contravariant): just keep a copy of the original Matcher<U>, convert the
415 // argument from type T to U, and then pass it to the underlying Matcher<U>.
416 // The only exception is when U is a reference and T is not, as the
417 // underlying Matcher<U> may be interested in the argument's address, which
418 // is not preserved in the conversion from T to U.
419 template <typename U>
420 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
421 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000422 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000423 T_must_be_implicitly_convertible_to_U);
424 // Enforce that we are not converting a non-reference type T to a reference
425 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000426 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000427 internal::is_reference<T>::value || !internal::is_reference<U>::value,
428 cannot_convert_non_referentce_arg_to_reference);
429 // In case both T and U are arithmetic types, enforce that the
430 // conversion is not lossy.
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000431 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
432 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000433 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
434 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000435 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000436 kTIsOther || kUIsOther ||
437 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
438 conversion_of_arithmetic_types_must_be_lossless);
439 return MatcherCast<T>(matcher);
440 }
441};
442
443template <typename T, typename M>
444inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
445 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000446}
447
shiqiane35fdd92008-12-10 05:08:54 +0000448// A<T>() returns a matcher that matches any value of type T.
449template <typename T>
450Matcher<T> A();
451
452// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
453// and MUST NOT BE USED IN USER CODE!!!
454namespace internal {
455
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000456// If the explanation is not empty, prints it to the ostream.
457inline void PrintIfNotEmpty(const internal::string& explanation,
458 std::ostream* os) {
459 if (explanation != "" && os != NULL) {
460 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000461 }
462}
463
464// Matches the value against the given matcher, prints the value and explains
465// the match result to the listener. Returns the match result.
466// 'listener' must not be NULL.
467// Value cannot be passed by const reference, because some matchers take a
468// non-const argument.
469template <typename Value, typename T>
470bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
471 MatchResultListener* listener) {
472 if (!listener->IsInterested()) {
473 // If the listener is not interested, we do not need to construct the
474 // inner explanation.
475 return matcher.Matches(value);
476 }
477
478 StringMatchResultListener inner_listener;
479 const bool match = matcher.MatchAndExplain(value, &inner_listener);
480
481 UniversalPrint(value, listener->stream());
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000482 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000483
484 return match;
485}
486
shiqiane35fdd92008-12-10 05:08:54 +0000487// An internal helper class for doing compile-time loop on a tuple's
488// fields.
489template <size_t N>
490class TuplePrefix {
491 public:
492 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
493 // iff the first N fields of matcher_tuple matches the first N
494 // fields of value_tuple, respectively.
495 template <typename MatcherTuple, typename ValueTuple>
496 static bool Matches(const MatcherTuple& matcher_tuple,
497 const ValueTuple& value_tuple) {
498 using ::std::tr1::get;
499 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
500 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
501 }
502
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000503 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000504 // describes failures in matching the first N fields of matchers
505 // against the first N fields of values. If there is no failure,
506 // nothing will be streamed to os.
507 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000508 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
509 const ValueTuple& values,
510 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000511 using ::std::tr1::tuple_element;
512 using ::std::tr1::get;
513
514 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000515 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000516
517 // Then describes the failure (if any) in the (N - 1)-th (0-based)
518 // field.
519 typename tuple_element<N - 1, MatcherTuple>::type matcher =
520 get<N - 1>(matchers);
521 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
522 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000523 StringMatchResultListener listener;
524 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000525 // TODO(wan): include in the message the name of the parameter
526 // as used in MOCK_METHOD*() when possible.
527 *os << " Expected arg #" << N - 1 << ": ";
528 get<N - 1>(matchers).DescribeTo(os);
529 *os << "\n Actual: ";
530 // We remove the reference in type Value to prevent the
531 // universal printer from printing the address of value, which
532 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000533 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000534 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000535 internal::UniversalPrint(value, os);
536 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000537 *os << "\n";
538 }
539 }
540};
541
542// The base case.
543template <>
544class TuplePrefix<0> {
545 public:
546 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000547 static bool Matches(const MatcherTuple& /* matcher_tuple */,
548 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000549 return true;
550 }
551
552 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000553 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
554 const ValueTuple& /* values */,
555 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000556};
557
558// TupleMatches(matcher_tuple, value_tuple) returns true iff all
559// matchers in matcher_tuple match the corresponding fields in
560// value_tuple. It is a compiler error if matcher_tuple and
561// value_tuple have different number of fields or incompatible field
562// types.
563template <typename MatcherTuple, typename ValueTuple>
564bool TupleMatches(const MatcherTuple& matcher_tuple,
565 const ValueTuple& value_tuple) {
566 using ::std::tr1::tuple_size;
567 // Makes sure that matcher_tuple and value_tuple have the same
568 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000569 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000570 tuple_size<ValueTuple>::value,
571 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000572 return TuplePrefix<tuple_size<ValueTuple>::value>::
573 Matches(matcher_tuple, value_tuple);
574}
575
576// Describes failures in matching matchers against values. If there
577// is no failure, nothing will be streamed to os.
578template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000579void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
580 const ValueTuple& values,
581 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000582 using ::std::tr1::tuple_size;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000583 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000584 matchers, values, os);
585}
586
587// The MatcherCastImpl class template is a helper for implementing
588// MatcherCast(). We need this helper in order to partially
589// specialize the implementation of MatcherCast() (C++ allows
590// class/struct templates to be partially specialized, but not
591// function templates.).
592
593// This general version is used when MatcherCast()'s argument is a
594// polymorphic matcher (i.e. something that can be converted to a
595// Matcher but is not one yet; for example, Eq(value)).
596template <typename T, typename M>
597class MatcherCastImpl {
598 public:
599 static Matcher<T> Cast(M polymorphic_matcher) {
600 return Matcher<T>(polymorphic_matcher);
601 }
602};
603
604// This more specialized version is used when MatcherCast()'s argument
605// is already a Matcher. This only compiles when type T can be
606// statically converted to type U.
607template <typename T, typename U>
608class MatcherCastImpl<T, Matcher<U> > {
609 public:
610 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
611 return Matcher<T>(new Impl(source_matcher));
612 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000613
shiqiane35fdd92008-12-10 05:08:54 +0000614 private:
615 class Impl : public MatcherInterface<T> {
616 public:
617 explicit Impl(const Matcher<U>& source_matcher)
618 : source_matcher_(source_matcher) {}
619
620 // We delegate the matching logic to the source matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000621 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
622 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000623 }
624
625 virtual void DescribeTo(::std::ostream* os) const {
626 source_matcher_.DescribeTo(os);
627 }
628
629 virtual void DescribeNegationTo(::std::ostream* os) const {
630 source_matcher_.DescribeNegationTo(os);
631 }
632
shiqiane35fdd92008-12-10 05:08:54 +0000633 private:
634 const Matcher<U> source_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000635
636 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000637 };
638};
639
640// This even more specialized version is used for efficiently casting
641// a matcher to its own type.
642template <typename T>
643class MatcherCastImpl<T, Matcher<T> > {
644 public:
645 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
646};
647
648// Implements A<T>().
649template <typename T>
650class AnyMatcherImpl : public MatcherInterface<T> {
651 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000652 virtual bool MatchAndExplain(
653 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000654 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
655 virtual void DescribeNegationTo(::std::ostream* os) const {
656 // This is mostly for completeness' safe, as it's not very useful
657 // to write Not(A<bool>()). However we cannot completely rule out
658 // such a possibility, and it doesn't hurt to be prepared.
659 *os << "never matches";
660 }
661};
662
663// Implements _, a matcher that matches any value of any
664// type. This is a polymorphic matcher, so we need a template type
665// conversion operator to make it appearing as a Matcher<T> for any
666// type T.
667class AnythingMatcher {
668 public:
669 template <typename T>
670 operator Matcher<T>() const { return A<T>(); }
671};
672
673// Implements a matcher that compares a given value with a
674// pre-supplied value using one of the ==, <=, <, etc, operators. The
675// two values being compared don't have to have the same type.
676//
677// The matcher defined here is polymorphic (for example, Eq(5) can be
678// used to match an int, a short, a double, etc). Therefore we use
679// a template type conversion operator in the implementation.
680//
681// We define this as a macro in order to eliminate duplicated source
682// code.
683//
684// The following template definition assumes that the Rhs parameter is
685// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000686#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_( \
687 name, op, relation, negated_relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000688 template <typename Rhs> class name##Matcher { \
689 public: \
690 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
691 template <typename Lhs> \
692 operator Matcher<Lhs>() const { \
693 return MakeMatcher(new Impl<Lhs>(rhs_)); \
694 } \
695 private: \
696 template <typename Lhs> \
697 class Impl : public MatcherInterface<Lhs> { \
698 public: \
699 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
zhanyong.wan82113312010-01-08 21:55:40 +0000700 virtual bool MatchAndExplain(\
701 Lhs lhs, MatchResultListener* /* listener */) const { \
702 return lhs op rhs_; \
703 } \
shiqiane35fdd92008-12-10 05:08:54 +0000704 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000705 *os << relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000706 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000707 } \
708 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000709 *os << negated_relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000710 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000711 } \
712 private: \
713 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000714 GTEST_DISALLOW_ASSIGN_(Impl); \
shiqiane35fdd92008-12-10 05:08:54 +0000715 }; \
716 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000717 GTEST_DISALLOW_ASSIGN_(name##Matcher); \
shiqiane35fdd92008-12-10 05:08:54 +0000718 }
719
720// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
721// respectively.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000722GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "is equal to", "isn't equal to");
723GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "is >=", "isn't >=");
724GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "is >", "isn't >");
725GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "is <=", "isn't <=");
726GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "is <", "isn't <");
727GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "isn't equal to", "is equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000728
zhanyong.wane0d051e2009-02-19 00:33:37 +0000729#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000730
vladlosev79b83502009-11-18 00:43:37 +0000731// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000732// pointer that is NULL.
733class IsNullMatcher {
734 public:
vladlosev79b83502009-11-18 00:43:37 +0000735 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000736 bool MatchAndExplain(const Pointer& p,
737 MatchResultListener* /* listener */) const {
738 return GetRawPointer(p) == NULL;
739 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000740
741 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
742 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000743 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000744 }
745};
746
vladlosev79b83502009-11-18 00:43:37 +0000747// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000748// pointer that is not NULL.
749class NotNullMatcher {
750 public:
vladlosev79b83502009-11-18 00:43:37 +0000751 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000752 bool MatchAndExplain(const Pointer& p,
753 MatchResultListener* /* listener */) const {
754 return GetRawPointer(p) != NULL;
755 }
shiqiane35fdd92008-12-10 05:08:54 +0000756
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000757 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +0000758 void DescribeNegationTo(::std::ostream* os) const {
759 *os << "is NULL";
760 }
761};
762
763// Ref(variable) matches any argument that is a reference to
764// 'variable'. This matcher is polymorphic as it can match any
765// super type of the type of 'variable'.
766//
767// The RefMatcher template class implements Ref(variable). It can
768// only be instantiated with a reference type. This prevents a user
769// from mistakenly using Ref(x) to match a non-reference function
770// argument. For example, the following will righteously cause a
771// compiler error:
772//
773// int n;
774// Matcher<int> m1 = Ref(n); // This won't compile.
775// Matcher<int&> m2 = Ref(n); // This will compile.
776template <typename T>
777class RefMatcher;
778
779template <typename T>
780class RefMatcher<T&> {
781 // Google Mock is a generic framework and thus needs to support
782 // mocking any function types, including those that take non-const
783 // reference arguments. Therefore the template parameter T (and
784 // Super below) can be instantiated to either a const type or a
785 // non-const type.
786 public:
787 // RefMatcher() takes a T& instead of const T&, as we want the
788 // compiler to catch using Ref(const_value) as a matcher for a
789 // non-const reference.
790 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
791
792 template <typename Super>
793 operator Matcher<Super&>() const {
794 // By passing object_ (type T&) to Impl(), which expects a Super&,
795 // we make sure that Super is a super type of T. In particular,
796 // this catches using Ref(const_value) as a matcher for a
797 // non-const reference, as you cannot implicitly convert a const
798 // reference to a non-const reference.
799 return MakeMatcher(new Impl<Super>(object_));
800 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000801
shiqiane35fdd92008-12-10 05:08:54 +0000802 private:
803 template <typename Super>
804 class Impl : public MatcherInterface<Super&> {
805 public:
806 explicit Impl(Super& x) : object_(x) {} // NOLINT
807
zhanyong.wandb22c222010-01-28 21:52:29 +0000808 // MatchAndExplain() takes a Super& (as opposed to const Super&)
809 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +0000810 virtual bool MatchAndExplain(
811 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000812 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +0000813 return &x == &object_;
814 }
shiqiane35fdd92008-12-10 05:08:54 +0000815
816 virtual void DescribeTo(::std::ostream* os) const {
817 *os << "references the variable ";
818 UniversalPrinter<Super&>::Print(object_, os);
819 }
820
821 virtual void DescribeNegationTo(::std::ostream* os) const {
822 *os << "does not reference the variable ";
823 UniversalPrinter<Super&>::Print(object_, os);
824 }
825
shiqiane35fdd92008-12-10 05:08:54 +0000826 private:
827 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000828
829 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000830 };
831
832 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000833
834 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000835};
836
837// Polymorphic helper functions for narrow and wide string matchers.
838inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
839 return String::CaseInsensitiveCStringEquals(lhs, rhs);
840}
841
842inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
843 const wchar_t* rhs) {
844 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
845}
846
847// String comparison for narrow or wide strings that can have embedded NUL
848// characters.
849template <typename StringType>
850bool CaseInsensitiveStringEquals(const StringType& s1,
851 const StringType& s2) {
852 // Are the heads equal?
853 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
854 return false;
855 }
856
857 // Skip the equal heads.
858 const typename StringType::value_type nul = 0;
859 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
860
861 // Are we at the end of either s1 or s2?
862 if (i1 == StringType::npos || i2 == StringType::npos) {
863 return i1 == i2;
864 }
865
866 // Are the tails equal?
867 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
868}
869
870// String matchers.
871
872// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
873template <typename StringType>
874class StrEqualityMatcher {
875 public:
876 typedef typename StringType::const_pointer ConstCharPointer;
877
878 StrEqualityMatcher(const StringType& str, bool expect_eq,
879 bool case_sensitive)
880 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
881
882 // When expect_eq_ is true, returns true iff s is equal to string_;
883 // otherwise returns true iff s is not equal to string_.
zhanyong.wandb22c222010-01-28 21:52:29 +0000884 bool MatchAndExplain(ConstCharPointer s,
885 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +0000886 if (s == NULL) {
887 return !expect_eq_;
888 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000889 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000890 }
891
zhanyong.wandb22c222010-01-28 21:52:29 +0000892 bool MatchAndExplain(const StringType& s,
893 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000894 const bool eq = case_sensitive_ ? s == string_ :
895 CaseInsensitiveStringEquals(s, string_);
896 return expect_eq_ == eq;
897 }
898
899 void DescribeTo(::std::ostream* os) const {
900 DescribeToHelper(expect_eq_, os);
901 }
902
903 void DescribeNegationTo(::std::ostream* os) const {
904 DescribeToHelper(!expect_eq_, os);
905 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000906
shiqiane35fdd92008-12-10 05:08:54 +0000907 private:
908 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000909 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +0000910 *os << "equal to ";
911 if (!case_sensitive_) {
912 *os << "(ignoring case) ";
913 }
vladloseve2e8ba42010-05-13 18:16:03 +0000914 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +0000915 }
916
917 const StringType string_;
918 const bool expect_eq_;
919 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000920
921 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000922};
923
924// Implements the polymorphic HasSubstr(substring) matcher, which
925// can be used as a Matcher<T> as long as T can be converted to a
926// string.
927template <typename StringType>
928class HasSubstrMatcher {
929 public:
930 typedef typename StringType::const_pointer ConstCharPointer;
931
932 explicit HasSubstrMatcher(const StringType& substring)
933 : substring_(substring) {}
934
935 // These overloaded methods allow HasSubstr(substring) to be used as a
936 // Matcher<T> as long as T can be converted to string. Returns true
937 // iff s contains substring_ as a substring.
zhanyong.wandb22c222010-01-28 21:52:29 +0000938 bool MatchAndExplain(ConstCharPointer s,
939 MatchResultListener* listener) const {
940 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000941 }
942
zhanyong.wandb22c222010-01-28 21:52:29 +0000943 bool MatchAndExplain(const StringType& s,
944 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000945 return s.find(substring_) != StringType::npos;
946 }
947
948 // Describes what this matcher matches.
949 void DescribeTo(::std::ostream* os) const {
950 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +0000951 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +0000952 }
953
954 void DescribeNegationTo(::std::ostream* os) const {
955 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +0000956 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +0000957 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000958
shiqiane35fdd92008-12-10 05:08:54 +0000959 private:
960 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000961
962 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000963};
964
965// Implements the polymorphic StartsWith(substring) matcher, which
966// can be used as a Matcher<T> as long as T can be converted to a
967// string.
968template <typename StringType>
969class StartsWithMatcher {
970 public:
971 typedef typename StringType::const_pointer ConstCharPointer;
972
973 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
974 }
975
976 // These overloaded methods allow StartsWith(prefix) to be used as a
977 // Matcher<T> as long as T can be converted to string. Returns true
978 // iff s starts with prefix_.
zhanyong.wandb22c222010-01-28 21:52:29 +0000979 bool MatchAndExplain(ConstCharPointer s,
980 MatchResultListener* listener) const {
981 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000982 }
983
zhanyong.wandb22c222010-01-28 21:52:29 +0000984 bool MatchAndExplain(const StringType& s,
985 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000986 return s.length() >= prefix_.length() &&
987 s.substr(0, prefix_.length()) == prefix_;
988 }
989
990 void DescribeTo(::std::ostream* os) const {
991 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +0000992 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +0000993 }
994
995 void DescribeNegationTo(::std::ostream* os) const {
996 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +0000997 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +0000998 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000999
shiqiane35fdd92008-12-10 05:08:54 +00001000 private:
1001 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001002
1003 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001004};
1005
1006// Implements the polymorphic EndsWith(substring) matcher, which
1007// can be used as a Matcher<T> as long as T can be converted to a
1008// string.
1009template <typename StringType>
1010class EndsWithMatcher {
1011 public:
1012 typedef typename StringType::const_pointer ConstCharPointer;
1013
1014 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1015
1016 // These overloaded methods allow EndsWith(suffix) to be used as a
1017 // Matcher<T> as long as T can be converted to string. Returns true
1018 // iff s ends with suffix_.
zhanyong.wandb22c222010-01-28 21:52:29 +00001019 bool MatchAndExplain(ConstCharPointer s,
1020 MatchResultListener* listener) const {
1021 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001022 }
1023
zhanyong.wandb22c222010-01-28 21:52:29 +00001024 bool MatchAndExplain(const StringType& s,
1025 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001026 return s.length() >= suffix_.length() &&
1027 s.substr(s.length() - suffix_.length()) == suffix_;
1028 }
1029
1030 void DescribeTo(::std::ostream* os) const {
1031 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001032 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001033 }
1034
1035 void DescribeNegationTo(::std::ostream* os) const {
1036 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001037 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001038 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001039
shiqiane35fdd92008-12-10 05:08:54 +00001040 private:
1041 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001042
1043 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001044};
1045
shiqiane35fdd92008-12-10 05:08:54 +00001046// Implements polymorphic matchers MatchesRegex(regex) and
1047// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1048// T can be converted to a string.
1049class MatchesRegexMatcher {
1050 public:
1051 MatchesRegexMatcher(const RE* regex, bool full_match)
1052 : regex_(regex), full_match_(full_match) {}
1053
1054 // These overloaded methods allow MatchesRegex(regex) to be used as
1055 // a Matcher<T> as long as T can be converted to string. Returns
1056 // true iff s matches regular expression regex. When full_match_ is
1057 // true, a full match is done; otherwise a partial match is done.
zhanyong.wandb22c222010-01-28 21:52:29 +00001058 bool MatchAndExplain(const char* s,
1059 MatchResultListener* listener) const {
1060 return s != NULL && MatchAndExplain(internal::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001061 }
1062
zhanyong.wandb22c222010-01-28 21:52:29 +00001063 bool MatchAndExplain(const internal::string& s,
1064 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001065 return full_match_ ? RE::FullMatch(s, *regex_) :
1066 RE::PartialMatch(s, *regex_);
1067 }
1068
1069 void DescribeTo(::std::ostream* os) const {
1070 *os << (full_match_ ? "matches" : "contains")
1071 << " regular expression ";
1072 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1073 }
1074
1075 void DescribeNegationTo(::std::ostream* os) const {
1076 *os << "doesn't " << (full_match_ ? "match" : "contain")
1077 << " regular expression ";
1078 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1079 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001080
shiqiane35fdd92008-12-10 05:08:54 +00001081 private:
1082 const internal::linked_ptr<const RE> regex_;
1083 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001084
1085 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001086};
1087
shiqiane35fdd92008-12-10 05:08:54 +00001088// Implements a matcher that compares the two fields of a 2-tuple
1089// using one of the ==, <=, <, etc, operators. The two fields being
1090// compared don't have to have the same type.
1091//
1092// The matcher defined here is polymorphic (for example, Eq() can be
1093// used to match a tuple<int, short>, a tuple<const long&, double>,
1094// etc). Therefore we use a template type conversion operator in the
1095// implementation.
1096//
1097// We define this as a macro in order to eliminate duplicated source
1098// code.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001099#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +00001100 class name##2Matcher { \
1101 public: \
1102 template <typename T1, typename T2> \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001103 operator Matcher< ::std::tr1::tuple<T1, T2> >() const { \
1104 return MakeMatcher(new Impl< ::std::tr1::tuple<T1, T2> >); \
1105 } \
1106 template <typename T1, typename T2> \
shiqiane35fdd92008-12-10 05:08:54 +00001107 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001108 return MakeMatcher(new Impl<const ::std::tr1::tuple<T1, T2>&>); \
shiqiane35fdd92008-12-10 05:08:54 +00001109 } \
1110 private: \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001111 template <typename Tuple> \
1112 class Impl : public MatcherInterface<Tuple> { \
shiqiane35fdd92008-12-10 05:08:54 +00001113 public: \
zhanyong.wan82113312010-01-08 21:55:40 +00001114 virtual bool MatchAndExplain( \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001115 Tuple args, \
zhanyong.wan82113312010-01-08 21:55:40 +00001116 MatchResultListener* /* listener */) const { \
shiqiane35fdd92008-12-10 05:08:54 +00001117 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
1118 } \
1119 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001120 *os << "are " relation; \
shiqiane35fdd92008-12-10 05:08:54 +00001121 } \
1122 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001123 *os << "aren't " relation; \
shiqiane35fdd92008-12-10 05:08:54 +00001124 } \
1125 }; \
1126 }
1127
1128// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001129GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "an equal pair");
1130GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1131 Ge, >=, "a pair where the first >= the second");
1132GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1133 Gt, >, "a pair where the first > the second");
1134GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1135 Le, <=, "a pair where the first <= the second");
1136GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1137 Lt, <, "a pair where the first < the second");
1138GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=, "an unequal pair");
shiqiane35fdd92008-12-10 05:08:54 +00001139
zhanyong.wane0d051e2009-02-19 00:33:37 +00001140#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +00001141
zhanyong.wanc6a41232009-05-13 23:38:40 +00001142// Implements the Not(...) matcher for a particular argument type T.
1143// We do not nest it inside the NotMatcher class template, as that
1144// will prevent different instantiations of NotMatcher from sharing
1145// the same NotMatcherImpl<T> class.
1146template <typename T>
1147class NotMatcherImpl : public MatcherInterface<T> {
1148 public:
1149 explicit NotMatcherImpl(const Matcher<T>& matcher)
1150 : matcher_(matcher) {}
1151
zhanyong.wan82113312010-01-08 21:55:40 +00001152 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1153 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001154 }
1155
1156 virtual void DescribeTo(::std::ostream* os) const {
1157 matcher_.DescribeNegationTo(os);
1158 }
1159
1160 virtual void DescribeNegationTo(::std::ostream* os) const {
1161 matcher_.DescribeTo(os);
1162 }
1163
zhanyong.wanc6a41232009-05-13 23:38:40 +00001164 private:
1165 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001166
1167 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001168};
1169
shiqiane35fdd92008-12-10 05:08:54 +00001170// Implements the Not(m) matcher, which matches a value that doesn't
1171// match matcher m.
1172template <typename InnerMatcher>
1173class NotMatcher {
1174 public:
1175 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1176
1177 // This template type conversion operator allows Not(m) to be used
1178 // to match any type m can match.
1179 template <typename T>
1180 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001181 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001182 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001183
shiqiane35fdd92008-12-10 05:08:54 +00001184 private:
shiqiane35fdd92008-12-10 05:08:54 +00001185 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001186
1187 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001188};
1189
zhanyong.wanc6a41232009-05-13 23:38:40 +00001190// Implements the AllOf(m1, m2) matcher for a particular argument type
1191// T. We do not nest it inside the BothOfMatcher class template, as
1192// that will prevent different instantiations of BothOfMatcher from
1193// sharing the same BothOfMatcherImpl<T> class.
1194template <typename T>
1195class BothOfMatcherImpl : public MatcherInterface<T> {
1196 public:
1197 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1198 : matcher1_(matcher1), matcher2_(matcher2) {}
1199
zhanyong.wanc6a41232009-05-13 23:38:40 +00001200 virtual void DescribeTo(::std::ostream* os) const {
1201 *os << "(";
1202 matcher1_.DescribeTo(os);
1203 *os << ") and (";
1204 matcher2_.DescribeTo(os);
1205 *os << ")";
1206 }
1207
1208 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001209 *os << "(";
1210 matcher1_.DescribeNegationTo(os);
1211 *os << ") or (";
1212 matcher2_.DescribeNegationTo(os);
1213 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001214 }
1215
zhanyong.wan82113312010-01-08 21:55:40 +00001216 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1217 // If either matcher1_ or matcher2_ doesn't match x, we only need
1218 // to explain why one of them fails.
1219 StringMatchResultListener listener1;
1220 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1221 *listener << listener1.str();
1222 return false;
1223 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001224
zhanyong.wan82113312010-01-08 21:55:40 +00001225 StringMatchResultListener listener2;
1226 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1227 *listener << listener2.str();
1228 return false;
1229 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001230
zhanyong.wan82113312010-01-08 21:55:40 +00001231 // Otherwise we need to explain why *both* of them match.
1232 const internal::string s1 = listener1.str();
1233 const internal::string s2 = listener2.str();
1234
1235 if (s1 == "") {
1236 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001237 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001238 *listener << s1;
1239 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001240 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001241 }
1242 }
zhanyong.wan82113312010-01-08 21:55:40 +00001243 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001244 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001245
zhanyong.wanc6a41232009-05-13 23:38:40 +00001246 private:
1247 const Matcher<T> matcher1_;
1248 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001249
1250 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001251};
1252
shiqiane35fdd92008-12-10 05:08:54 +00001253// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1254// matches a value that matches all of the matchers m_1, ..., and m_n.
1255template <typename Matcher1, typename Matcher2>
1256class BothOfMatcher {
1257 public:
1258 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1259 : matcher1_(matcher1), matcher2_(matcher2) {}
1260
1261 // This template type conversion operator allows a
1262 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1263 // both Matcher1 and Matcher2 can match.
1264 template <typename T>
1265 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001266 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1267 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001268 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001269
shiqiane35fdd92008-12-10 05:08:54 +00001270 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001271 Matcher1 matcher1_;
1272 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001273
1274 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001275};
shiqiane35fdd92008-12-10 05:08:54 +00001276
zhanyong.wanc6a41232009-05-13 23:38:40 +00001277// Implements the AnyOf(m1, m2) matcher for a particular argument type
1278// T. We do not nest it inside the AnyOfMatcher class template, as
1279// that will prevent different instantiations of AnyOfMatcher from
1280// sharing the same EitherOfMatcherImpl<T> class.
1281template <typename T>
1282class EitherOfMatcherImpl : public MatcherInterface<T> {
1283 public:
1284 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1285 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001286
zhanyong.wanc6a41232009-05-13 23:38:40 +00001287 virtual void DescribeTo(::std::ostream* os) const {
1288 *os << "(";
1289 matcher1_.DescribeTo(os);
1290 *os << ") or (";
1291 matcher2_.DescribeTo(os);
1292 *os << ")";
1293 }
shiqiane35fdd92008-12-10 05:08:54 +00001294
zhanyong.wanc6a41232009-05-13 23:38:40 +00001295 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001296 *os << "(";
1297 matcher1_.DescribeNegationTo(os);
1298 *os << ") and (";
1299 matcher2_.DescribeNegationTo(os);
1300 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001301 }
shiqiane35fdd92008-12-10 05:08:54 +00001302
zhanyong.wan82113312010-01-08 21:55:40 +00001303 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1304 // If either matcher1_ or matcher2_ matches x, we just need to
1305 // explain why *one* of them matches.
1306 StringMatchResultListener listener1;
1307 if (matcher1_.MatchAndExplain(x, &listener1)) {
1308 *listener << listener1.str();
1309 return true;
1310 }
1311
1312 StringMatchResultListener listener2;
1313 if (matcher2_.MatchAndExplain(x, &listener2)) {
1314 *listener << listener2.str();
1315 return true;
1316 }
1317
1318 // Otherwise we need to explain why *both* of them fail.
1319 const internal::string s1 = listener1.str();
1320 const internal::string s2 = listener2.str();
1321
1322 if (s1 == "") {
1323 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001324 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001325 *listener << s1;
1326 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001327 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001328 }
1329 }
zhanyong.wan82113312010-01-08 21:55:40 +00001330 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001331 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001332
zhanyong.wanc6a41232009-05-13 23:38:40 +00001333 private:
1334 const Matcher<T> matcher1_;
1335 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001336
1337 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001338};
1339
1340// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1341// matches a value that matches at least one of the matchers m_1, ...,
1342// and m_n.
1343template <typename Matcher1, typename Matcher2>
1344class EitherOfMatcher {
1345 public:
1346 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1347 : matcher1_(matcher1), matcher2_(matcher2) {}
1348
1349 // This template type conversion operator allows a
1350 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1351 // both Matcher1 and Matcher2 can match.
1352 template <typename T>
1353 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001354 return Matcher<T>(new EitherOfMatcherImpl<T>(
1355 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001356 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001357
shiqiane35fdd92008-12-10 05:08:54 +00001358 private:
shiqiane35fdd92008-12-10 05:08:54 +00001359 Matcher1 matcher1_;
1360 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001361
1362 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001363};
1364
1365// Used for implementing Truly(pred), which turns a predicate into a
1366// matcher.
1367template <typename Predicate>
1368class TrulyMatcher {
1369 public:
1370 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1371
1372 // This method template allows Truly(pred) to be used as a matcher
1373 // for type T where T is the argument type of predicate 'pred'. The
1374 // argument is passed by reference as the predicate may be
1375 // interested in the address of the argument.
1376 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001377 bool MatchAndExplain(T& x, // NOLINT
1378 MatchResultListener* /* listener */) const {
zhanyong.wan652540a2009-02-23 23:37:29 +00001379#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001380 // MSVC warns about converting a value into bool (warning 4800).
1381#pragma warning(push) // Saves the current warning state.
1382#pragma warning(disable:4800) // Temporarily disables warning 4800.
1383#endif // GTEST_OS_WINDOWS
1384 return predicate_(x);
zhanyong.wan652540a2009-02-23 23:37:29 +00001385#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001386#pragma warning(pop) // Restores the warning state.
1387#endif // GTEST_OS_WINDOWS
1388 }
1389
1390 void DescribeTo(::std::ostream* os) const {
1391 *os << "satisfies the given predicate";
1392 }
1393
1394 void DescribeNegationTo(::std::ostream* os) const {
1395 *os << "doesn't satisfy the given predicate";
1396 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001397
shiqiane35fdd92008-12-10 05:08:54 +00001398 private:
1399 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001400
1401 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001402};
1403
1404// Used for implementing Matches(matcher), which turns a matcher into
1405// a predicate.
1406template <typename M>
1407class MatcherAsPredicate {
1408 public:
1409 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1410
1411 // This template operator() allows Matches(m) to be used as a
1412 // predicate on type T where m is a matcher on type T.
1413 //
1414 // The argument x is passed by reference instead of by value, as
1415 // some matcher may be interested in its address (e.g. as in
1416 // Matches(Ref(n))(x)).
1417 template <typename T>
1418 bool operator()(const T& x) const {
1419 // We let matcher_ commit to a particular type here instead of
1420 // when the MatcherAsPredicate object was constructed. This
1421 // allows us to write Matches(m) where m is a polymorphic matcher
1422 // (e.g. Eq(5)).
1423 //
1424 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1425 // compile when matcher_ has type Matcher<const T&>; if we write
1426 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1427 // when matcher_ has type Matcher<T>; if we just write
1428 // matcher_.Matches(x), it won't compile when matcher_ is
1429 // polymorphic, e.g. Eq(5).
1430 //
1431 // MatcherCast<const T&>() is necessary for making the code work
1432 // in all of the above situations.
1433 return MatcherCast<const T&>(matcher_).Matches(x);
1434 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001435
shiqiane35fdd92008-12-10 05:08:54 +00001436 private:
1437 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001438
1439 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001440};
1441
1442// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1443// argument M must be a type that can be converted to a matcher.
1444template <typename M>
1445class PredicateFormatterFromMatcher {
1446 public:
1447 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1448
1449 // This template () operator allows a PredicateFormatterFromMatcher
1450 // object to act as a predicate-formatter suitable for using with
1451 // Google Test's EXPECT_PRED_FORMAT1() macro.
1452 template <typename T>
1453 AssertionResult operator()(const char* value_text, const T& x) const {
1454 // We convert matcher_ to a Matcher<const T&> *now* instead of
1455 // when the PredicateFormatterFromMatcher object was constructed,
1456 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1457 // know which type to instantiate it to until we actually see the
1458 // type of x here.
1459 //
1460 // We write MatcherCast<const T&>(matcher_) instead of
1461 // Matcher<const T&>(matcher_), as the latter won't compile when
1462 // matcher_ has type Matcher<T> (e.g. An<int>()).
1463 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001464 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001465 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001466 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001467
1468 ::std::stringstream ss;
1469 ss << "Value of: " << value_text << "\n"
1470 << "Expected: ";
1471 matcher.DescribeTo(&ss);
1472 ss << "\n Actual: " << listener.str();
1473 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001474 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001475
shiqiane35fdd92008-12-10 05:08:54 +00001476 private:
1477 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001478
1479 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001480};
1481
1482// A helper function for converting a matcher to a predicate-formatter
1483// without the user needing to explicitly write the type. This is
1484// used for implementing ASSERT_THAT() and EXPECT_THAT().
1485template <typename M>
1486inline PredicateFormatterFromMatcher<M>
1487MakePredicateFormatterFromMatcher(const M& matcher) {
1488 return PredicateFormatterFromMatcher<M>(matcher);
1489}
1490
1491// Implements the polymorphic floating point equality matcher, which
1492// matches two float values using ULP-based approximation. The
1493// template is meant to be instantiated with FloatType being either
1494// float or double.
1495template <typename FloatType>
1496class FloatingEqMatcher {
1497 public:
1498 // Constructor for FloatingEqMatcher.
1499 // The matcher's input will be compared with rhs. The matcher treats two
1500 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1501 // equality comparisons between NANs will always return false.
1502 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1503 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1504
1505 // Implements floating point equality matcher as a Matcher<T>.
1506 template <typename T>
1507 class Impl : public MatcherInterface<T> {
1508 public:
1509 Impl(FloatType rhs, bool nan_eq_nan) :
1510 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1511
zhanyong.wan82113312010-01-08 21:55:40 +00001512 virtual bool MatchAndExplain(T value,
1513 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001514 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1515
1516 // Compares NaNs first, if nan_eq_nan_ is true.
1517 if (nan_eq_nan_ && lhs.is_nan()) {
1518 return rhs.is_nan();
1519 }
1520
1521 return lhs.AlmostEquals(rhs);
1522 }
1523
1524 virtual void DescribeTo(::std::ostream* os) const {
1525 // os->precision() returns the previously set precision, which we
1526 // store to restore the ostream to its original configuration
1527 // after outputting.
1528 const ::std::streamsize old_precision = os->precision(
1529 ::std::numeric_limits<FloatType>::digits10 + 2);
1530 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1531 if (nan_eq_nan_) {
1532 *os << "is NaN";
1533 } else {
1534 *os << "never matches";
1535 }
1536 } else {
1537 *os << "is approximately " << rhs_;
1538 }
1539 os->precision(old_precision);
1540 }
1541
1542 virtual void DescribeNegationTo(::std::ostream* os) const {
1543 // As before, get original precision.
1544 const ::std::streamsize old_precision = os->precision(
1545 ::std::numeric_limits<FloatType>::digits10 + 2);
1546 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1547 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001548 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00001549 } else {
1550 *os << "is anything";
1551 }
1552 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001553 *os << "isn't approximately " << rhs_;
shiqiane35fdd92008-12-10 05:08:54 +00001554 }
1555 // Restore original precision.
1556 os->precision(old_precision);
1557 }
1558
1559 private:
1560 const FloatType rhs_;
1561 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001562
1563 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001564 };
1565
1566 // The following 3 type conversion operators allow FloatEq(rhs) and
1567 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1568 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1569 // (While Google's C++ coding style doesn't allow arguments passed
1570 // by non-const reference, we may see them in code not conforming to
1571 // the style. Therefore Google Mock needs to support them.)
1572 operator Matcher<FloatType>() const {
1573 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1574 }
1575
1576 operator Matcher<const FloatType&>() const {
1577 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1578 }
1579
1580 operator Matcher<FloatType&>() const {
1581 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1582 }
1583 private:
1584 const FloatType rhs_;
1585 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001586
1587 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001588};
1589
1590// Implements the Pointee(m) matcher for matching a pointer whose
1591// pointee matches matcher m. The pointer can be either raw or smart.
1592template <typename InnerMatcher>
1593class PointeeMatcher {
1594 public:
1595 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1596
1597 // This type conversion operator template allows Pointee(m) to be
1598 // used as a matcher for any pointer type whose pointee type is
1599 // compatible with the inner matcher, where type Pointer can be
1600 // either a raw pointer or a smart pointer.
1601 //
1602 // The reason we do this instead of relying on
1603 // MakePolymorphicMatcher() is that the latter is not flexible
1604 // enough for implementing the DescribeTo() method of Pointee().
1605 template <typename Pointer>
1606 operator Matcher<Pointer>() const {
1607 return MakeMatcher(new Impl<Pointer>(matcher_));
1608 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001609
shiqiane35fdd92008-12-10 05:08:54 +00001610 private:
1611 // The monomorphic implementation that works for a particular pointer type.
1612 template <typename Pointer>
1613 class Impl : public MatcherInterface<Pointer> {
1614 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00001615 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
1616 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001617
1618 explicit Impl(const InnerMatcher& matcher)
1619 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1620
shiqiane35fdd92008-12-10 05:08:54 +00001621 virtual void DescribeTo(::std::ostream* os) const {
1622 *os << "points to a value that ";
1623 matcher_.DescribeTo(os);
1624 }
1625
1626 virtual void DescribeNegationTo(::std::ostream* os) const {
1627 *os << "does not point to a value that ";
1628 matcher_.DescribeTo(os);
1629 }
1630
zhanyong.wan82113312010-01-08 21:55:40 +00001631 virtual bool MatchAndExplain(Pointer pointer,
1632 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001633 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00001634 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001635
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001636 *listener << "which points to ";
1637 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001638 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001639
shiqiane35fdd92008-12-10 05:08:54 +00001640 private:
1641 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001642
1643 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001644 };
1645
1646 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001647
1648 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001649};
1650
1651// Implements the Field() matcher for matching a field (i.e. member
1652// variable) of an object.
1653template <typename Class, typename FieldType>
1654class FieldMatcher {
1655 public:
1656 FieldMatcher(FieldType Class::*field,
1657 const Matcher<const FieldType&>& matcher)
1658 : field_(field), matcher_(matcher) {}
1659
shiqiane35fdd92008-12-10 05:08:54 +00001660 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001661 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001662 matcher_.DescribeTo(os);
1663 }
1664
1665 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001666 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001667 matcher_.DescribeNegationTo(os);
1668 }
1669
zhanyong.wandb22c222010-01-28 21:52:29 +00001670 template <typename T>
1671 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
1672 return MatchAndExplainImpl(
1673 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00001674 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00001675 value, listener);
1676 }
1677
1678 private:
1679 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001680 // Symbian's C++ compiler choose which overload to use. Its type is
1681 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001682 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1683 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001684 *listener << "whose given field is ";
1685 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001686 }
1687
zhanyong.wandb22c222010-01-28 21:52:29 +00001688 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1689 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001690 if (p == NULL)
1691 return false;
1692
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001693 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001694 // Since *p has a field, it must be a class/struct/union type and
1695 // thus cannot be a pointer. Therefore we pass false_type() as
1696 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001697 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001698 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001699
shiqiane35fdd92008-12-10 05:08:54 +00001700 const FieldType Class::*field_;
1701 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001702
1703 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001704};
1705
shiqiane35fdd92008-12-10 05:08:54 +00001706// Implements the Property() matcher for matching a property
1707// (i.e. return value of a getter method) of an object.
1708template <typename Class, typename PropertyType>
1709class PropertyMatcher {
1710 public:
1711 // The property may have a reference type, so 'const PropertyType&'
1712 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00001713 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00001714 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00001715 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001716
1717 PropertyMatcher(PropertyType (Class::*property)() const,
1718 const Matcher<RefToConstProperty>& matcher)
1719 : property_(property), matcher_(matcher) {}
1720
shiqiane35fdd92008-12-10 05:08:54 +00001721 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001722 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001723 matcher_.DescribeTo(os);
1724 }
1725
1726 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001727 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001728 matcher_.DescribeNegationTo(os);
1729 }
1730
zhanyong.wandb22c222010-01-28 21:52:29 +00001731 template <typename T>
1732 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
1733 return MatchAndExplainImpl(
1734 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00001735 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00001736 value, listener);
1737 }
1738
1739 private:
1740 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001741 // Symbian's C++ compiler choose which overload to use. Its type is
1742 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001743 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1744 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001745 *listener << "whose given property is ";
1746 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
1747 // which takes a non-const reference as argument.
1748 RefToConstProperty result = (obj.*property_)();
1749 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001750 }
1751
zhanyong.wandb22c222010-01-28 21:52:29 +00001752 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1753 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001754 if (p == NULL)
1755 return false;
1756
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001757 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001758 // Since *p has a property method, it must be a class/struct/union
1759 // type and thus cannot be a pointer. Therefore we pass
1760 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001761 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001762 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001763
shiqiane35fdd92008-12-10 05:08:54 +00001764 PropertyType (Class::*property_)() const;
1765 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001766
1767 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001768};
1769
shiqiane35fdd92008-12-10 05:08:54 +00001770// Type traits specifying various features of different functors for ResultOf.
1771// The default template specifies features for functor objects.
1772// Functor classes have to typedef argument_type and result_type
1773// to be compatible with ResultOf.
1774template <typename Functor>
1775struct CallableTraits {
1776 typedef typename Functor::result_type ResultType;
1777 typedef Functor StorageType;
1778
zhanyong.wan32de5f52009-12-23 00:13:23 +00001779 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00001780 template <typename T>
1781 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1782};
1783
1784// Specialization for function pointers.
1785template <typename ArgType, typename ResType>
1786struct CallableTraits<ResType(*)(ArgType)> {
1787 typedef ResType ResultType;
1788 typedef ResType(*StorageType)(ArgType);
1789
1790 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001791 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00001792 << "NULL function pointer is passed into ResultOf().";
1793 }
1794 template <typename T>
1795 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1796 return (*f)(arg);
1797 }
1798};
1799
1800// Implements the ResultOf() matcher for matching a return value of a
1801// unary function of an object.
1802template <typename Callable>
1803class ResultOfMatcher {
1804 public:
1805 typedef typename CallableTraits<Callable>::ResultType ResultType;
1806
1807 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1808 : callable_(callable), matcher_(matcher) {
1809 CallableTraits<Callable>::CheckIsValid(callable_);
1810 }
1811
1812 template <typename T>
1813 operator Matcher<T>() const {
1814 return Matcher<T>(new Impl<T>(callable_, matcher_));
1815 }
1816
1817 private:
1818 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1819
1820 template <typename T>
1821 class Impl : public MatcherInterface<T> {
1822 public:
1823 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1824 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00001825
1826 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001827 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001828 matcher_.DescribeTo(os);
1829 }
1830
1831 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001832 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001833 matcher_.DescribeNegationTo(os);
1834 }
1835
zhanyong.wan82113312010-01-08 21:55:40 +00001836 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001837 *listener << "which is mapped by the given callable to ";
1838 // Cannot pass the return value (for example, int) to
1839 // MatchPrintAndExplain, which takes a non-const reference as argument.
1840 ResultType result =
1841 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
1842 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001843 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001844
shiqiane35fdd92008-12-10 05:08:54 +00001845 private:
1846 // Functors often define operator() as non-const method even though
1847 // they are actualy stateless. But we need to use them even when
1848 // 'this' is a const pointer. It's the user's responsibility not to
1849 // use stateful callables with ResultOf(), which does't guarantee
1850 // how many times the callable will be invoked.
1851 mutable CallableStorageType callable_;
1852 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001853
1854 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001855 }; // class Impl
1856
1857 const CallableStorageType callable_;
1858 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001859
1860 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001861};
1862
zhanyong.wan6a896b52009-01-16 01:13:50 +00001863// Implements an equality matcher for any STL-style container whose elements
1864// support ==. This matcher is like Eq(), but its failure explanations provide
1865// more detailed information that is useful when the container is used as a set.
1866// The failure message reports elements that are in one of the operands but not
1867// the other. The failure messages do not report duplicate or out-of-order
1868// elements in the containers (which don't properly matter to sets, but can
1869// occur if the containers are vectors or lists, for example).
1870//
1871// Uses the container's const_iterator, value_type, operator ==,
1872// begin(), and end().
1873template <typename Container>
1874class ContainerEqMatcher {
1875 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00001876 typedef internal::StlContainerView<Container> View;
1877 typedef typename View::type StlContainer;
1878 typedef typename View::const_reference StlContainerReference;
1879
1880 // We make a copy of rhs in case the elements in it are modified
1881 // after this matcher is created.
1882 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
1883 // Makes sure the user doesn't instantiate this class template
1884 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001885 (void)testing::StaticAssertTypeEq<Container,
1886 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00001887 }
1888
zhanyong.wan6a896b52009-01-16 01:13:50 +00001889 void DescribeTo(::std::ostream* os) const {
1890 *os << "equals ";
vladloseve2e8ba42010-05-13 18:16:03 +00001891 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001892 }
1893 void DescribeNegationTo(::std::ostream* os) const {
1894 *os << "does not equal ";
vladloseve2e8ba42010-05-13 18:16:03 +00001895 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001896 }
1897
zhanyong.wanb8243162009-06-04 05:48:20 +00001898 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00001899 bool MatchAndExplain(const LhsContainer& lhs,
1900 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00001901 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00001902 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00001903 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00001904 LhsView;
1905 typedef typename LhsView::type LhsStlContainer;
1906 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00001907 if (lhs_stl_container == rhs_)
1908 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00001909
zhanyong.wane122e452010-01-12 09:03:52 +00001910 ::std::ostream* const os = listener->stream();
1911 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001912 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00001913 bool printed_header = false;
1914 for (typename LhsStlContainer::const_iterator it =
1915 lhs_stl_container.begin();
1916 it != lhs_stl_container.end(); ++it) {
1917 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
1918 rhs_.end()) {
1919 if (printed_header) {
1920 *os << ", ";
1921 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001922 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00001923 printed_header = true;
1924 }
vladloseve2e8ba42010-05-13 18:16:03 +00001925 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001926 }
zhanyong.wane122e452010-01-12 09:03:52 +00001927 }
1928
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001929 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00001930 bool printed_header2 = false;
1931 for (typename StlContainer::const_iterator it = rhs_.begin();
1932 it != rhs_.end(); ++it) {
1933 if (internal::ArrayAwareFind(
1934 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
1935 lhs_stl_container.end()) {
1936 if (printed_header2) {
1937 *os << ", ";
1938 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001939 *os << (printed_header ? ",\nand" : "which")
1940 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00001941 printed_header2 = true;
1942 }
vladloseve2e8ba42010-05-13 18:16:03 +00001943 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00001944 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00001945 }
1946 }
1947
zhanyong.wane122e452010-01-12 09:03:52 +00001948 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00001949 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001950
zhanyong.wan6a896b52009-01-16 01:13:50 +00001951 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00001952 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001953
1954 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001955};
1956
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001957// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
1958// must be able to be safely cast to Matcher<tuple<const T1&, const
1959// T2&> >, where T1 and T2 are the types of elements in the LHS
1960// container and the RHS container respectively.
1961template <typename TupleMatcher, typename RhsContainer>
1962class PointwiseMatcher {
1963 public:
1964 typedef internal::StlContainerView<RhsContainer> RhsView;
1965 typedef typename RhsView::type RhsStlContainer;
1966 typedef typename RhsStlContainer::value_type RhsValue;
1967
1968 // Like ContainerEq, we make a copy of rhs in case the elements in
1969 // it are modified after this matcher is created.
1970 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
1971 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
1972 // Makes sure the user doesn't instantiate this class template
1973 // with a const or reference type.
1974 (void)testing::StaticAssertTypeEq<RhsContainer,
1975 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
1976 }
1977
1978 template <typename LhsContainer>
1979 operator Matcher<LhsContainer>() const {
1980 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
1981 }
1982
1983 template <typename LhsContainer>
1984 class Impl : public MatcherInterface<LhsContainer> {
1985 public:
1986 typedef internal::StlContainerView<
1987 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
1988 typedef typename LhsView::type LhsStlContainer;
1989 typedef typename LhsView::const_reference LhsStlContainerReference;
1990 typedef typename LhsStlContainer::value_type LhsValue;
1991 // We pass the LHS value and the RHS value to the inner matcher by
1992 // reference, as they may be expensive to copy. We must use tuple
1993 // instead of pair here, as a pair cannot hold references (C++ 98,
1994 // 20.2.2 [lib.pairs]).
1995 typedef std::tr1::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
1996
1997 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
1998 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
1999 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2000 rhs_(rhs) {}
2001
2002 virtual void DescribeTo(::std::ostream* os) const {
2003 *os << "contains " << rhs_.size()
2004 << " values, where each value and its corresponding value in ";
2005 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2006 *os << " ";
2007 mono_tuple_matcher_.DescribeTo(os);
2008 }
2009 virtual void DescribeNegationTo(::std::ostream* os) const {
2010 *os << "doesn't contain exactly " << rhs_.size()
2011 << " values, or contains a value x at some index i"
2012 << " where x and the i-th value of ";
2013 UniversalPrint(rhs_, os);
2014 *os << " ";
2015 mono_tuple_matcher_.DescribeNegationTo(os);
2016 }
2017
2018 virtual bool MatchAndExplain(LhsContainer lhs,
2019 MatchResultListener* listener) const {
2020 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2021 const size_t actual_size = lhs_stl_container.size();
2022 if (actual_size != rhs_.size()) {
2023 *listener << "which contains " << actual_size << " values";
2024 return false;
2025 }
2026
2027 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2028 typename RhsStlContainer::const_iterator right = rhs_.begin();
2029 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2030 const InnerMatcherArg value_pair(*left, *right);
2031
2032 if (listener->IsInterested()) {
2033 StringMatchResultListener inner_listener;
2034 if (!mono_tuple_matcher_.MatchAndExplain(
2035 value_pair, &inner_listener)) {
2036 *listener << "where the value pair (";
2037 UniversalPrint(*left, listener->stream());
2038 *listener << ", ";
2039 UniversalPrint(*right, listener->stream());
2040 *listener << ") at index #" << i << " don't match";
2041 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2042 return false;
2043 }
2044 } else {
2045 if (!mono_tuple_matcher_.Matches(value_pair))
2046 return false;
2047 }
2048 }
2049
2050 return true;
2051 }
2052
2053 private:
2054 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2055 const RhsStlContainer rhs_;
2056
2057 GTEST_DISALLOW_ASSIGN_(Impl);
2058 };
2059
2060 private:
2061 const TupleMatcher tuple_matcher_;
2062 const RhsStlContainer rhs_;
2063
2064 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2065};
2066
zhanyong.wan33605ba2010-04-22 23:37:47 +00002067// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002068template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002069class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002070 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002071 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002072 typedef StlContainerView<RawContainer> View;
2073 typedef typename View::type StlContainer;
2074 typedef typename View::const_reference StlContainerReference;
2075 typedef typename StlContainer::value_type Element;
2076
2077 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002078 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002079 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002080 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002081
zhanyong.wan33605ba2010-04-22 23:37:47 +00002082 // Checks whether:
2083 // * All elements in the container match, if all_elements_should_match.
2084 // * Any element in the container matches, if !all_elements_should_match.
2085 bool MatchAndExplainImpl(bool all_elements_should_match,
2086 Container container,
2087 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002088 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002089 size_t i = 0;
2090 for (typename StlContainer::const_iterator it = stl_container.begin();
2091 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002092 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00002093 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2094
2095 if (matches != all_elements_should_match) {
2096 *listener << "whose element #" << i
2097 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002098 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00002099 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00002100 }
2101 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00002102 return all_elements_should_match;
2103 }
2104
2105 protected:
2106 const Matcher<const Element&> inner_matcher_;
2107
2108 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2109};
2110
2111// Implements Contains(element_matcher) for the given argument type Container.
2112// Symmetric to EachMatcherImpl.
2113template <typename Container>
2114class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2115 public:
2116 template <typename InnerMatcher>
2117 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2118 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2119
2120 // Describes what this matcher does.
2121 virtual void DescribeTo(::std::ostream* os) const {
2122 *os << "contains at least one element that ";
2123 this->inner_matcher_.DescribeTo(os);
2124 }
2125
2126 virtual void DescribeNegationTo(::std::ostream* os) const {
2127 *os << "doesn't contain any element that ";
2128 this->inner_matcher_.DescribeTo(os);
2129 }
2130
2131 virtual bool MatchAndExplain(Container container,
2132 MatchResultListener* listener) const {
2133 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002134 }
2135
2136 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002137 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002138};
2139
zhanyong.wan33605ba2010-04-22 23:37:47 +00002140// Implements Each(element_matcher) for the given argument type Container.
2141// Symmetric to ContainsMatcherImpl.
2142template <typename Container>
2143class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2144 public:
2145 template <typename InnerMatcher>
2146 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2147 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2148
2149 // Describes what this matcher does.
2150 virtual void DescribeTo(::std::ostream* os) const {
2151 *os << "only contains elements that ";
2152 this->inner_matcher_.DescribeTo(os);
2153 }
2154
2155 virtual void DescribeNegationTo(::std::ostream* os) const {
2156 *os << "contains some element that ";
2157 this->inner_matcher_.DescribeNegationTo(os);
2158 }
2159
2160 virtual bool MatchAndExplain(Container container,
2161 MatchResultListener* listener) const {
2162 return this->MatchAndExplainImpl(true, container, listener);
2163 }
2164
2165 private:
2166 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2167};
2168
zhanyong.wanb8243162009-06-04 05:48:20 +00002169// Implements polymorphic Contains(element_matcher).
2170template <typename M>
2171class ContainsMatcher {
2172 public:
2173 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2174
2175 template <typename Container>
2176 operator Matcher<Container>() const {
2177 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2178 }
2179
2180 private:
2181 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002182
2183 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002184};
2185
zhanyong.wan33605ba2010-04-22 23:37:47 +00002186// Implements polymorphic Each(element_matcher).
2187template <typename M>
2188class EachMatcher {
2189 public:
2190 explicit EachMatcher(M m) : inner_matcher_(m) {}
2191
2192 template <typename Container>
2193 operator Matcher<Container>() const {
2194 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2195 }
2196
2197 private:
2198 const M inner_matcher_;
2199
2200 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2201};
2202
zhanyong.wanb5937da2009-07-16 20:26:41 +00002203// Implements Key(inner_matcher) for the given argument pair type.
2204// Key(inner_matcher) matches an std::pair whose 'first' field matches
2205// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2206// std::map that contains at least one element whose key is >= 5.
2207template <typename PairType>
2208class KeyMatcherImpl : public MatcherInterface<PairType> {
2209 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002210 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002211 typedef typename RawPairType::first_type KeyType;
2212
2213 template <typename InnerMatcher>
2214 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2215 : inner_matcher_(
2216 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2217 }
2218
2219 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002220 virtual bool MatchAndExplain(PairType key_value,
2221 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002222 StringMatchResultListener inner_listener;
2223 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2224 &inner_listener);
2225 const internal::string explanation = inner_listener.str();
2226 if (explanation != "") {
2227 *listener << "whose first field is a value " << explanation;
2228 }
2229 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002230 }
2231
2232 // Describes what this matcher does.
2233 virtual void DescribeTo(::std::ostream* os) const {
2234 *os << "has a key that ";
2235 inner_matcher_.DescribeTo(os);
2236 }
2237
2238 // Describes what the negation of this matcher does.
2239 virtual void DescribeNegationTo(::std::ostream* os) const {
2240 *os << "doesn't have a key that ";
2241 inner_matcher_.DescribeTo(os);
2242 }
2243
zhanyong.wanb5937da2009-07-16 20:26:41 +00002244 private:
2245 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002246
2247 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002248};
2249
2250// Implements polymorphic Key(matcher_for_key).
2251template <typename M>
2252class KeyMatcher {
2253 public:
2254 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2255
2256 template <typename PairType>
2257 operator Matcher<PairType>() const {
2258 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2259 }
2260
2261 private:
2262 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002263
2264 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002265};
2266
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002267// Implements Pair(first_matcher, second_matcher) for the given argument pair
2268// type with its two matchers. See Pair() function below.
2269template <typename PairType>
2270class PairMatcherImpl : public MatcherInterface<PairType> {
2271 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002272 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002273 typedef typename RawPairType::first_type FirstType;
2274 typedef typename RawPairType::second_type SecondType;
2275
2276 template <typename FirstMatcher, typename SecondMatcher>
2277 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2278 : first_matcher_(
2279 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2280 second_matcher_(
2281 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2282 }
2283
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002284 // Describes what this matcher does.
2285 virtual void DescribeTo(::std::ostream* os) const {
2286 *os << "has a first field that ";
2287 first_matcher_.DescribeTo(os);
2288 *os << ", and has a second field that ";
2289 second_matcher_.DescribeTo(os);
2290 }
2291
2292 // Describes what the negation of this matcher does.
2293 virtual void DescribeNegationTo(::std::ostream* os) const {
2294 *os << "has a first field that ";
2295 first_matcher_.DescribeNegationTo(os);
2296 *os << ", or has a second field that ";
2297 second_matcher_.DescribeNegationTo(os);
2298 }
2299
zhanyong.wan82113312010-01-08 21:55:40 +00002300 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2301 // matches second_matcher.
2302 virtual bool MatchAndExplain(PairType a_pair,
2303 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002304 if (!listener->IsInterested()) {
2305 // If the listener is not interested, we don't need to construct the
2306 // explanation.
2307 return first_matcher_.Matches(a_pair.first) &&
2308 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00002309 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002310 StringMatchResultListener first_inner_listener;
2311 if (!first_matcher_.MatchAndExplain(a_pair.first,
2312 &first_inner_listener)) {
2313 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002314 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002315 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002316 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002317 StringMatchResultListener second_inner_listener;
2318 if (!second_matcher_.MatchAndExplain(a_pair.second,
2319 &second_inner_listener)) {
2320 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002321 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002322 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002323 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002324 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
2325 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00002326 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002327 }
2328
2329 private:
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002330 void ExplainSuccess(const internal::string& first_explanation,
2331 const internal::string& second_explanation,
2332 MatchResultListener* listener) const {
2333 *listener << "whose both fields match";
2334 if (first_explanation != "") {
2335 *listener << ", where the first field is a value " << first_explanation;
2336 }
2337 if (second_explanation != "") {
2338 *listener << ", ";
2339 if (first_explanation != "") {
2340 *listener << "and ";
2341 } else {
2342 *listener << "where ";
2343 }
2344 *listener << "the second field is a value " << second_explanation;
2345 }
2346 }
2347
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002348 const Matcher<const FirstType&> first_matcher_;
2349 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002350
2351 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002352};
2353
2354// Implements polymorphic Pair(first_matcher, second_matcher).
2355template <typename FirstMatcher, typename SecondMatcher>
2356class PairMatcher {
2357 public:
2358 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2359 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2360
2361 template <typename PairType>
2362 operator Matcher<PairType> () const {
2363 return MakeMatcher(
2364 new PairMatcherImpl<PairType>(
2365 first_matcher_, second_matcher_));
2366 }
2367
2368 private:
2369 const FirstMatcher first_matcher_;
2370 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002371
2372 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002373};
2374
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002375// Implements ElementsAre() and ElementsAreArray().
2376template <typename Container>
2377class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2378 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002379 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002380 typedef internal::StlContainerView<RawContainer> View;
2381 typedef typename View::type StlContainer;
2382 typedef typename View::const_reference StlContainerReference;
2383 typedef typename StlContainer::value_type Element;
2384
2385 // Constructs the matcher from a sequence of element values or
2386 // element matchers.
2387 template <typename InputIter>
zhanyong.wan32de5f52009-12-23 00:13:23 +00002388 ElementsAreMatcherImpl(InputIter first, size_t a_count) {
2389 matchers_.reserve(a_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002390 InputIter it = first;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002391 for (size_t i = 0; i != a_count; ++i, ++it) {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002392 matchers_.push_back(MatcherCast<const Element&>(*it));
2393 }
2394 }
2395
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002396 // Describes what this matcher does.
2397 virtual void DescribeTo(::std::ostream* os) const {
2398 if (count() == 0) {
2399 *os << "is empty";
2400 } else if (count() == 1) {
2401 *os << "has 1 element that ";
2402 matchers_[0].DescribeTo(os);
2403 } else {
2404 *os << "has " << Elements(count()) << " where\n";
2405 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002406 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002407 matchers_[i].DescribeTo(os);
2408 if (i + 1 < count()) {
2409 *os << ",\n";
2410 }
2411 }
2412 }
2413 }
2414
2415 // Describes what the negation of this matcher does.
2416 virtual void DescribeNegationTo(::std::ostream* os) const {
2417 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002418 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002419 return;
2420 }
2421
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002422 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002423 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002424 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002425 matchers_[i].DescribeNegationTo(os);
2426 if (i + 1 < count()) {
2427 *os << ", or\n";
2428 }
2429 }
2430 }
2431
zhanyong.wan82113312010-01-08 21:55:40 +00002432 virtual bool MatchAndExplain(Container container,
2433 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002434 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002435 const size_t actual_count = stl_container.size();
2436 if (actual_count != count()) {
2437 // The element count doesn't match. If the container is empty,
2438 // there's no need to explain anything as Google Mock already
2439 // prints the empty container. Otherwise we just need to show
2440 // how many elements there actually are.
2441 if (actual_count != 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002442 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002443 }
zhanyong.wan82113312010-01-08 21:55:40 +00002444 return false;
2445 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002446
zhanyong.wan82113312010-01-08 21:55:40 +00002447 typename StlContainer::const_iterator it = stl_container.begin();
2448 // explanations[i] is the explanation of the element at index i.
2449 std::vector<internal::string> explanations(count());
2450 for (size_t i = 0; i != count(); ++it, ++i) {
2451 StringMatchResultListener s;
2452 if (matchers_[i].MatchAndExplain(*it, &s)) {
2453 explanations[i] = s.str();
2454 } else {
2455 // The container has the right size but the i-th element
2456 // doesn't match its expectation.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002457 *listener << "whose element #" << i << " doesn't match";
2458 PrintIfNotEmpty(s.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002459 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002460 }
2461 }
zhanyong.wan82113312010-01-08 21:55:40 +00002462
2463 // Every element matches its expectation. We need to explain why
2464 // (the obvious ones can be skipped).
zhanyong.wan82113312010-01-08 21:55:40 +00002465 bool reason_printed = false;
2466 for (size_t i = 0; i != count(); ++i) {
2467 const internal::string& s = explanations[i];
2468 if (!s.empty()) {
2469 if (reason_printed) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002470 *listener << ",\nand ";
zhanyong.wan82113312010-01-08 21:55:40 +00002471 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002472 *listener << "whose element #" << i << " matches, " << s;
zhanyong.wan82113312010-01-08 21:55:40 +00002473 reason_printed = true;
2474 }
2475 }
2476
2477 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002478 }
2479
2480 private:
2481 static Message Elements(size_t count) {
2482 return Message() << count << (count == 1 ? " element" : " elements");
2483 }
2484
2485 size_t count() const { return matchers_.size(); }
2486 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002487
2488 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002489};
2490
2491// Implements ElementsAre() of 0 arguments.
2492class ElementsAreMatcher0 {
2493 public:
2494 ElementsAreMatcher0() {}
2495
2496 template <typename Container>
2497 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002498 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002499 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2500 Element;
2501
2502 const Matcher<const Element&>* const matchers = NULL;
2503 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 0));
2504 }
2505};
2506
2507// Implements ElementsAreArray().
2508template <typename T>
2509class ElementsAreArrayMatcher {
2510 public:
2511 ElementsAreArrayMatcher(const T* first, size_t count) :
2512 first_(first), count_(count) {}
2513
2514 template <typename Container>
2515 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002516 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002517 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2518 Element;
2519
2520 return MakeMatcher(new ElementsAreMatcherImpl<Container>(first_, count_));
2521 }
2522
2523 private:
2524 const T* const first_;
2525 const size_t count_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002526
2527 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002528};
2529
2530// Constants denoting interpolations in a matcher description string.
2531const int kTupleInterpolation = -1; // "%(*)s"
2532const int kPercentInterpolation = -2; // "%%"
2533const int kInvalidInterpolation = -3; // "%" followed by invalid text
2534
2535// Records the location and content of an interpolation.
2536struct Interpolation {
2537 Interpolation(const char* start, const char* end, int param)
2538 : start_pos(start), end_pos(end), param_index(param) {}
2539
2540 // Points to the start of the interpolation (the '%' character).
2541 const char* start_pos;
2542 // Points to the first character after the interpolation.
2543 const char* end_pos;
2544 // 0-based index of the interpolated matcher parameter;
2545 // kTupleInterpolation for "%(*)s"; kPercentInterpolation for "%%".
2546 int param_index;
2547};
2548
2549typedef ::std::vector<Interpolation> Interpolations;
2550
2551// Parses a matcher description string and returns a vector of
2552// interpolations that appear in the string; generates non-fatal
2553// failures iff 'description' is an invalid matcher description.
2554// 'param_names' is a NULL-terminated array of parameter names in the
2555// order they appear in the MATCHER_P*() parameter list.
2556Interpolations ValidateMatcherDescription(
2557 const char* param_names[], const char* description);
2558
2559// Returns the actual matcher description, given the matcher name,
2560// user-supplied description template string, interpolations in the
2561// string, and the printed values of the matcher parameters.
2562string FormatMatcherDescription(
2563 const char* matcher_name, const char* description,
2564 const Interpolations& interp, const Strings& param_values);
2565
shiqiane35fdd92008-12-10 05:08:54 +00002566} // namespace internal
2567
2568// Implements MatcherCast().
2569template <typename T, typename M>
2570inline Matcher<T> MatcherCast(M matcher) {
2571 return internal::MatcherCastImpl<T, M>::Cast(matcher);
2572}
2573
2574// _ is a matcher that matches anything of any type.
2575//
2576// This definition is fine as:
2577//
2578// 1. The C++ standard permits using the name _ in a namespace that
2579// is not the global namespace or ::std.
2580// 2. The AnythingMatcher class has no data member or constructor,
2581// so it's OK to create global variables of this type.
2582// 3. c-style has approved of using _ in this case.
2583const internal::AnythingMatcher _ = {};
2584// Creates a matcher that matches any value of the given type T.
2585template <typename T>
2586inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2587
2588// Creates a matcher that matches any value of the given type T.
2589template <typename T>
2590inline Matcher<T> An() { return A<T>(); }
2591
2592// Creates a polymorphic matcher that matches anything equal to x.
2593// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2594// wouldn't compile.
2595template <typename T>
2596inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2597
2598// Constructs a Matcher<T> from a 'value' of type T. The constructed
2599// matcher matches any value that's equal to 'value'.
2600template <typename T>
2601Matcher<T>::Matcher(T value) { *this = Eq(value); }
2602
2603// Creates a monomorphic matcher that matches anything with type Lhs
2604// and equal to rhs. A user may need to use this instead of Eq(...)
2605// in order to resolve an overloading ambiguity.
2606//
2607// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2608// or Matcher<T>(x), but more readable than the latter.
2609//
2610// We could define similar monomorphic matchers for other comparison
2611// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2612// it yet as those are used much less than Eq() in practice. A user
2613// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2614// for example.
2615template <typename Lhs, typename Rhs>
2616inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2617
2618// Creates a polymorphic matcher that matches anything >= x.
2619template <typename Rhs>
2620inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2621 return internal::GeMatcher<Rhs>(x);
2622}
2623
2624// Creates a polymorphic matcher that matches anything > x.
2625template <typename Rhs>
2626inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2627 return internal::GtMatcher<Rhs>(x);
2628}
2629
2630// Creates a polymorphic matcher that matches anything <= x.
2631template <typename Rhs>
2632inline internal::LeMatcher<Rhs> Le(Rhs x) {
2633 return internal::LeMatcher<Rhs>(x);
2634}
2635
2636// Creates a polymorphic matcher that matches anything < x.
2637template <typename Rhs>
2638inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2639 return internal::LtMatcher<Rhs>(x);
2640}
2641
2642// Creates a polymorphic matcher that matches anything != x.
2643template <typename Rhs>
2644inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2645 return internal::NeMatcher<Rhs>(x);
2646}
2647
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002648// Creates a polymorphic matcher that matches any NULL pointer.
2649inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2650 return MakePolymorphicMatcher(internal::IsNullMatcher());
2651}
2652
shiqiane35fdd92008-12-10 05:08:54 +00002653// Creates a polymorphic matcher that matches any non-NULL pointer.
2654// This is convenient as Not(NULL) doesn't compile (the compiler
2655// thinks that that expression is comparing a pointer with an integer).
2656inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2657 return MakePolymorphicMatcher(internal::NotNullMatcher());
2658}
2659
2660// Creates a polymorphic matcher that matches any argument that
2661// references variable x.
2662template <typename T>
2663inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2664 return internal::RefMatcher<T&>(x);
2665}
2666
2667// Creates a matcher that matches any double argument approximately
2668// equal to rhs, where two NANs are considered unequal.
2669inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2670 return internal::FloatingEqMatcher<double>(rhs, false);
2671}
2672
2673// Creates a matcher that matches any double argument approximately
2674// equal to rhs, including NaN values when rhs is NaN.
2675inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2676 return internal::FloatingEqMatcher<double>(rhs, true);
2677}
2678
2679// Creates a matcher that matches any float argument approximately
2680// equal to rhs, where two NANs are considered unequal.
2681inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2682 return internal::FloatingEqMatcher<float>(rhs, false);
2683}
2684
2685// Creates a matcher that matches any double argument approximately
2686// equal to rhs, including NaN values when rhs is NaN.
2687inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2688 return internal::FloatingEqMatcher<float>(rhs, true);
2689}
2690
2691// Creates a matcher that matches a pointer (raw or smart) that points
2692// to a value that matches inner_matcher.
2693template <typename InnerMatcher>
2694inline internal::PointeeMatcher<InnerMatcher> Pointee(
2695 const InnerMatcher& inner_matcher) {
2696 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2697}
2698
2699// Creates a matcher that matches an object whose given field matches
2700// 'matcher'. For example,
2701// Field(&Foo::number, Ge(5))
2702// matches a Foo object x iff x.number >= 5.
2703template <typename Class, typename FieldType, typename FieldMatcher>
2704inline PolymorphicMatcher<
2705 internal::FieldMatcher<Class, FieldType> > Field(
2706 FieldType Class::*field, const FieldMatcher& matcher) {
2707 return MakePolymorphicMatcher(
2708 internal::FieldMatcher<Class, FieldType>(
2709 field, MatcherCast<const FieldType&>(matcher)));
2710 // The call to MatcherCast() is required for supporting inner
2711 // matchers of compatible types. For example, it allows
2712 // Field(&Foo::bar, m)
2713 // to compile where bar is an int32 and m is a matcher for int64.
2714}
2715
2716// Creates a matcher that matches an object whose given property
2717// matches 'matcher'. For example,
2718// Property(&Foo::str, StartsWith("hi"))
2719// matches a Foo object x iff x.str() starts with "hi".
2720template <typename Class, typename PropertyType, typename PropertyMatcher>
2721inline PolymorphicMatcher<
2722 internal::PropertyMatcher<Class, PropertyType> > Property(
2723 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2724 return MakePolymorphicMatcher(
2725 internal::PropertyMatcher<Class, PropertyType>(
2726 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00002727 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002728 // The call to MatcherCast() is required for supporting inner
2729 // matchers of compatible types. For example, it allows
2730 // Property(&Foo::bar, m)
2731 // to compile where bar() returns an int32 and m is a matcher for int64.
2732}
2733
2734// Creates a matcher that matches an object iff the result of applying
2735// a callable to x matches 'matcher'.
2736// For example,
2737// ResultOf(f, StartsWith("hi"))
2738// matches a Foo object x iff f(x) starts with "hi".
2739// callable parameter can be a function, function pointer, or a functor.
2740// Callable has to satisfy the following conditions:
2741// * It is required to keep no state affecting the results of
2742// the calls on it and make no assumptions about how many calls
2743// will be made. Any state it keeps must be protected from the
2744// concurrent access.
2745// * If it is a function object, it has to define type result_type.
2746// We recommend deriving your functor classes from std::unary_function.
2747template <typename Callable, typename ResultOfMatcher>
2748internal::ResultOfMatcher<Callable> ResultOf(
2749 Callable callable, const ResultOfMatcher& matcher) {
2750 return internal::ResultOfMatcher<Callable>(
2751 callable,
2752 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2753 matcher));
2754 // The call to MatcherCast() is required for supporting inner
2755 // matchers of compatible types. For example, it allows
2756 // ResultOf(Function, m)
2757 // to compile where Function() returns an int32 and m is a matcher for int64.
2758}
2759
2760// String matchers.
2761
2762// Matches a string equal to str.
2763inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2764 StrEq(const internal::string& str) {
2765 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2766 str, true, true));
2767}
2768
2769// Matches a string not equal to str.
2770inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2771 StrNe(const internal::string& str) {
2772 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2773 str, false, true));
2774}
2775
2776// Matches a string equal to str, ignoring case.
2777inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2778 StrCaseEq(const internal::string& str) {
2779 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2780 str, true, false));
2781}
2782
2783// Matches a string not equal to str, ignoring case.
2784inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2785 StrCaseNe(const internal::string& str) {
2786 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2787 str, false, false));
2788}
2789
2790// Creates a matcher that matches any string, std::string, or C string
2791// that contains the given substring.
2792inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2793 HasSubstr(const internal::string& substring) {
2794 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
2795 substring));
2796}
2797
2798// Matches a string that starts with 'prefix' (case-sensitive).
2799inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
2800 StartsWith(const internal::string& prefix) {
2801 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
2802 prefix));
2803}
2804
2805// Matches a string that ends with 'suffix' (case-sensitive).
2806inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
2807 EndsWith(const internal::string& suffix) {
2808 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
2809 suffix));
2810}
2811
shiqiane35fdd92008-12-10 05:08:54 +00002812// Matches a string that fully matches regular expression 'regex'.
2813// The matcher takes ownership of 'regex'.
2814inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2815 const internal::RE* regex) {
2816 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2817}
2818inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2819 const internal::string& regex) {
2820 return MatchesRegex(new internal::RE(regex));
2821}
2822
2823// Matches a string that contains regular expression 'regex'.
2824// The matcher takes ownership of 'regex'.
2825inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2826 const internal::RE* regex) {
2827 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2828}
2829inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2830 const internal::string& regex) {
2831 return ContainsRegex(new internal::RE(regex));
2832}
2833
shiqiane35fdd92008-12-10 05:08:54 +00002834#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2835// Wide string matchers.
2836
2837// Matches a string equal to str.
2838inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2839 StrEq(const internal::wstring& str) {
2840 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2841 str, true, true));
2842}
2843
2844// Matches a string not equal to str.
2845inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2846 StrNe(const internal::wstring& str) {
2847 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2848 str, false, true));
2849}
2850
2851// Matches a string equal to str, ignoring case.
2852inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2853 StrCaseEq(const internal::wstring& str) {
2854 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2855 str, true, false));
2856}
2857
2858// Matches a string not equal to str, ignoring case.
2859inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2860 StrCaseNe(const internal::wstring& str) {
2861 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2862 str, false, false));
2863}
2864
2865// Creates a matcher that matches any wstring, std::wstring, or C wide string
2866// that contains the given substring.
2867inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2868 HasSubstr(const internal::wstring& substring) {
2869 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2870 substring));
2871}
2872
2873// Matches a string that starts with 'prefix' (case-sensitive).
2874inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2875 StartsWith(const internal::wstring& prefix) {
2876 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2877 prefix));
2878}
2879
2880// Matches a string that ends with 'suffix' (case-sensitive).
2881inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2882 EndsWith(const internal::wstring& suffix) {
2883 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2884 suffix));
2885}
2886
2887#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2888
2889// Creates a polymorphic matcher that matches a 2-tuple where the
2890// first field == the second field.
2891inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2892
2893// Creates a polymorphic matcher that matches a 2-tuple where the
2894// first field >= the second field.
2895inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2896
2897// Creates a polymorphic matcher that matches a 2-tuple where the
2898// first field > the second field.
2899inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2900
2901// Creates a polymorphic matcher that matches a 2-tuple where the
2902// first field <= the second field.
2903inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2904
2905// Creates a polymorphic matcher that matches a 2-tuple where the
2906// first field < the second field.
2907inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2908
2909// Creates a polymorphic matcher that matches a 2-tuple where the
2910// first field != the second field.
2911inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2912
2913// Creates a matcher that matches any value of type T that m doesn't
2914// match.
2915template <typename InnerMatcher>
2916inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2917 return internal::NotMatcher<InnerMatcher>(m);
2918}
2919
2920// Creates a matcher that matches any value that matches all of the
2921// given matchers.
2922//
2923// For now we only support up to 5 matchers. Support for more
2924// matchers can be added as needed, or the user can use nested
2925// AllOf()s.
2926template <typename Matcher1, typename Matcher2>
2927inline internal::BothOfMatcher<Matcher1, Matcher2>
2928AllOf(Matcher1 m1, Matcher2 m2) {
2929 return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2);
2930}
2931
2932template <typename Matcher1, typename Matcher2, typename Matcher3>
2933inline internal::BothOfMatcher<Matcher1,
2934 internal::BothOfMatcher<Matcher2, Matcher3> >
2935AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2936 return AllOf(m1, AllOf(m2, m3));
2937}
2938
2939template <typename Matcher1, typename Matcher2, typename Matcher3,
2940 typename Matcher4>
2941inline internal::BothOfMatcher<Matcher1,
2942 internal::BothOfMatcher<Matcher2,
2943 internal::BothOfMatcher<Matcher3, Matcher4> > >
2944AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2945 return AllOf(m1, AllOf(m2, m3, m4));
2946}
2947
2948template <typename Matcher1, typename Matcher2, typename Matcher3,
2949 typename Matcher4, typename Matcher5>
2950inline internal::BothOfMatcher<Matcher1,
2951 internal::BothOfMatcher<Matcher2,
2952 internal::BothOfMatcher<Matcher3,
2953 internal::BothOfMatcher<Matcher4, Matcher5> > > >
2954AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2955 return AllOf(m1, AllOf(m2, m3, m4, m5));
2956}
2957
2958// Creates a matcher that matches any value that matches at least one
2959// of the given matchers.
2960//
2961// For now we only support up to 5 matchers. Support for more
2962// matchers can be added as needed, or the user can use nested
2963// AnyOf()s.
2964template <typename Matcher1, typename Matcher2>
2965inline internal::EitherOfMatcher<Matcher1, Matcher2>
2966AnyOf(Matcher1 m1, Matcher2 m2) {
2967 return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2);
2968}
2969
2970template <typename Matcher1, typename Matcher2, typename Matcher3>
2971inline internal::EitherOfMatcher<Matcher1,
2972 internal::EitherOfMatcher<Matcher2, Matcher3> >
2973AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2974 return AnyOf(m1, AnyOf(m2, m3));
2975}
2976
2977template <typename Matcher1, typename Matcher2, typename Matcher3,
2978 typename Matcher4>
2979inline internal::EitherOfMatcher<Matcher1,
2980 internal::EitherOfMatcher<Matcher2,
2981 internal::EitherOfMatcher<Matcher3, Matcher4> > >
2982AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2983 return AnyOf(m1, AnyOf(m2, m3, m4));
2984}
2985
2986template <typename Matcher1, typename Matcher2, typename Matcher3,
2987 typename Matcher4, typename Matcher5>
2988inline internal::EitherOfMatcher<Matcher1,
2989 internal::EitherOfMatcher<Matcher2,
2990 internal::EitherOfMatcher<Matcher3,
2991 internal::EitherOfMatcher<Matcher4, Matcher5> > > >
2992AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2993 return AnyOf(m1, AnyOf(m2, m3, m4, m5));
2994}
2995
2996// Returns a matcher that matches anything that satisfies the given
2997// predicate. The predicate can be any unary function or functor
2998// whose return type can be implicitly converted to bool.
2999template <typename Predicate>
3000inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
3001Truly(Predicate pred) {
3002 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
3003}
3004
zhanyong.wan6a896b52009-01-16 01:13:50 +00003005// Returns a matcher that matches an equal container.
3006// This matcher behaves like Eq(), but in the event of mismatch lists the
3007// values that are included in one container but not the other. (Duplicate
3008// values and order differences are not explained.)
3009template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00003010inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00003011 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00003012 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00003013 // This following line is for working around a bug in MSVC 8.0,
3014 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00003015 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00003016 return MakePolymorphicMatcher(
3017 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00003018}
3019
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003020// Matches an STL-style container or a native array that contains the
3021// same number of elements as in rhs, where its i-th element and rhs's
3022// i-th element (as a pair) satisfy the given pair matcher, for all i.
3023// TupleMatcher must be able to be safely cast to Matcher<tuple<const
3024// T1&, const T2&> >, where T1 and T2 are the types of elements in the
3025// LHS container and the RHS container respectively.
3026template <typename TupleMatcher, typename Container>
3027inline internal::PointwiseMatcher<TupleMatcher,
3028 GTEST_REMOVE_CONST_(Container)>
3029Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
3030 // This following line is for working around a bug in MSVC 8.0,
3031 // which causes Container to be a const type sometimes.
3032 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
3033 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
3034 tuple_matcher, rhs);
3035}
3036
zhanyong.wanb8243162009-06-04 05:48:20 +00003037// Matches an STL-style container or a native array that contains at
3038// least one element matching the given value or matcher.
3039//
3040// Examples:
3041// ::std::set<int> page_ids;
3042// page_ids.insert(3);
3043// page_ids.insert(1);
3044// EXPECT_THAT(page_ids, Contains(1));
3045// EXPECT_THAT(page_ids, Contains(Gt(2)));
3046// EXPECT_THAT(page_ids, Not(Contains(4)));
3047//
3048// ::std::map<int, size_t> page_lengths;
3049// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00003050// EXPECT_THAT(page_lengths,
3051// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00003052//
3053// const char* user_ids[] = { "joe", "mike", "tom" };
3054// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
3055template <typename M>
3056inline internal::ContainsMatcher<M> Contains(M matcher) {
3057 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00003058}
3059
zhanyong.wan33605ba2010-04-22 23:37:47 +00003060// Matches an STL-style container or a native array that contains only
3061// elements matching the given value or matcher.
3062//
3063// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
3064// the messages are different.
3065//
3066// Examples:
3067// ::std::set<int> page_ids;
3068// // Each(m) matches an empty container, regardless of what m is.
3069// EXPECT_THAT(page_ids, Each(Eq(1)));
3070// EXPECT_THAT(page_ids, Each(Eq(77)));
3071//
3072// page_ids.insert(3);
3073// EXPECT_THAT(page_ids, Each(Gt(0)));
3074// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
3075// page_ids.insert(1);
3076// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
3077//
3078// ::std::map<int, size_t> page_lengths;
3079// page_lengths[1] = 100;
3080// page_lengths[2] = 200;
3081// page_lengths[3] = 300;
3082// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
3083// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
3084//
3085// const char* user_ids[] = { "joe", "mike", "tom" };
3086// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
3087template <typename M>
3088inline internal::EachMatcher<M> Each(M matcher) {
3089 return internal::EachMatcher<M>(matcher);
3090}
3091
zhanyong.wanb5937da2009-07-16 20:26:41 +00003092// Key(inner_matcher) matches an std::pair whose 'first' field matches
3093// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3094// std::map that contains at least one element whose key is >= 5.
3095template <typename M>
3096inline internal::KeyMatcher<M> Key(M inner_matcher) {
3097 return internal::KeyMatcher<M>(inner_matcher);
3098}
3099
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003100// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
3101// matches first_matcher and whose 'second' field matches second_matcher. For
3102// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
3103// to match a std::map<int, string> that contains exactly one element whose key
3104// is >= 5 and whose value equals "foo".
3105template <typename FirstMatcher, typename SecondMatcher>
3106inline internal::PairMatcher<FirstMatcher, SecondMatcher>
3107Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
3108 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
3109 first_matcher, second_matcher);
3110}
3111
shiqiane35fdd92008-12-10 05:08:54 +00003112// Returns a predicate that is satisfied by anything that matches the
3113// given matcher.
3114template <typename M>
3115inline internal::MatcherAsPredicate<M> Matches(M matcher) {
3116 return internal::MatcherAsPredicate<M>(matcher);
3117}
3118
zhanyong.wanb8243162009-06-04 05:48:20 +00003119// Returns true iff the value matches the matcher.
3120template <typename T, typename M>
3121inline bool Value(const T& value, M matcher) {
3122 return testing::Matches(matcher)(value);
3123}
3124
zhanyong.wan34b034c2010-03-05 21:23:23 +00003125// Matches the value against the given matcher and explains the match
3126// result to listener.
3127template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00003128inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00003129 M matcher, const T& value, MatchResultListener* listener) {
3130 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
3131}
3132
zhanyong.wanbf550852009-06-09 06:09:53 +00003133// AllArgs(m) is a synonym of m. This is useful in
3134//
3135// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
3136//
3137// which is easier to read than
3138//
3139// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
3140template <typename InnerMatcher>
3141inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
3142
shiqiane35fdd92008-12-10 05:08:54 +00003143// These macros allow using matchers to check values in Google Test
3144// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
3145// succeed iff the value matches the matcher. If the assertion fails,
3146// the value and the description of the matcher will be printed.
3147#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
3148 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3149#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
3150 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3151
3152} // namespace testing
3153
3154#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_