blob: 89a9e2ec0f648d378f0b5ab90b0eacfb3661ad83 [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
zhanyong.wan53e08c42010-09-14 05:38:21 +000049#include "gmock/internal/gmock-internal-utils.h"
50#include "gmock/internal/gmock-port.h"
51#include "gtest/gtest.h"
shiqiane35fdd92008-12-10 05:08:54 +000052
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:
vladlosev88032d82010-11-17 23:29:21 +0000253 // Constructs a null matcher. Needed for storing Matcher objects in STL
254 // containers. A default-constructed matcher is not yet initialized. You
255 // cannot use it until a valid value has been assigned to it.
shiqiane35fdd92008-12-10 05:08:54 +0000256 Matcher() {}
257
258 // Constructs a matcher from its implementation.
259 explicit Matcher(const MatcherInterface<T>* impl)
260 : internal::MatcherBase<T>(impl) {}
261
zhanyong.wan18490652009-05-11 18:54:08 +0000262 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000263 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
264 Matcher(T value); // NOLINT
265};
266
267// The following two specializations allow the user to write str
268// instead of Eq(str) and "foo" instead of Eq("foo") when a string
269// matcher is expected.
270template <>
vladlosev587c1b32011-05-20 00:42:22 +0000271class GTEST_API_ Matcher<const internal::string&>
shiqiane35fdd92008-12-10 05:08:54 +0000272 : public internal::MatcherBase<const internal::string&> {
273 public:
274 Matcher() {}
275
276 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
277 : internal::MatcherBase<const internal::string&>(impl) {}
278
279 // Allows the user to write str instead of Eq(str) sometimes, where
280 // str is a string object.
281 Matcher(const internal::string& s); // NOLINT
282
283 // Allows the user to write "foo" instead of Eq("foo") sometimes.
284 Matcher(const char* s); // NOLINT
285};
286
287template <>
vladlosev587c1b32011-05-20 00:42:22 +0000288class GTEST_API_ Matcher<internal::string>
shiqiane35fdd92008-12-10 05:08:54 +0000289 : public internal::MatcherBase<internal::string> {
290 public:
291 Matcher() {}
292
293 explicit Matcher(const MatcherInterface<internal::string>* impl)
294 : internal::MatcherBase<internal::string>(impl) {}
295
296 // Allows the user to write str instead of Eq(str) sometimes, where
297 // str is a string object.
298 Matcher(const internal::string& s); // NOLINT
299
300 // Allows the user to write "foo" instead of Eq("foo") sometimes.
301 Matcher(const char* s); // NOLINT
302};
303
304// The PolymorphicMatcher class template makes it easy to implement a
305// polymorphic matcher (i.e. a matcher that can match values of more
306// than one type, e.g. Eq(n) and NotNull()).
307//
zhanyong.wandb22c222010-01-28 21:52:29 +0000308// To define a polymorphic matcher, a user should provide an Impl
309// class that has a DescribeTo() method and a DescribeNegationTo()
310// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000311//
zhanyong.wandb22c222010-01-28 21:52:29 +0000312// bool MatchAndExplain(const Value& value,
313// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000314//
315// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000316template <class Impl>
317class PolymorphicMatcher {
318 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000319 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000320
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000321 // Returns a mutable reference to the underlying matcher
322 // implementation object.
323 Impl& mutable_impl() { return impl_; }
324
325 // Returns an immutable reference to the underlying matcher
326 // implementation object.
327 const Impl& impl() const { return impl_; }
328
shiqiane35fdd92008-12-10 05:08:54 +0000329 template <typename T>
330 operator Matcher<T>() const {
331 return Matcher<T>(new MonomorphicImpl<T>(impl_));
332 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000333
shiqiane35fdd92008-12-10 05:08:54 +0000334 private:
335 template <typename T>
336 class MonomorphicImpl : public MatcherInterface<T> {
337 public:
338 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
339
shiqiane35fdd92008-12-10 05:08:54 +0000340 virtual void DescribeTo(::std::ostream* os) const {
341 impl_.DescribeTo(os);
342 }
343
344 virtual void DescribeNegationTo(::std::ostream* os) const {
345 impl_.DescribeNegationTo(os);
346 }
347
zhanyong.wan82113312010-01-08 21:55:40 +0000348 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000349 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000350 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000351
shiqiane35fdd92008-12-10 05:08:54 +0000352 private:
353 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000354
355 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000356 };
357
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000358 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000359
360 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000361};
362
363// Creates a matcher from its implementation. This is easier to use
364// than the Matcher<T> constructor as it doesn't require you to
365// explicitly write the template argument, e.g.
366//
367// MakeMatcher(foo);
368// vs
369// Matcher<const string&>(foo);
370template <typename T>
371inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
372 return Matcher<T>(impl);
373};
374
375// Creates a polymorphic matcher from its implementation. This is
376// easier to use than the PolymorphicMatcher<Impl> constructor as it
377// doesn't require you to explicitly write the template argument, e.g.
378//
379// MakePolymorphicMatcher(foo);
380// vs
381// PolymorphicMatcher<TypeOfFoo>(foo);
382template <class Impl>
383inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
384 return PolymorphicMatcher<Impl>(impl);
385}
386
387// In order to be safe and clear, casting between different matcher
388// types is done explicitly via MatcherCast<T>(m), which takes a
389// matcher m and returns a Matcher<T>. It compiles only when T can be
390// statically converted to the argument type of m.
391template <typename T, typename M>
392Matcher<T> MatcherCast(M m);
393
zhanyong.wan18490652009-05-11 18:54:08 +0000394// Implements SafeMatcherCast().
395//
zhanyong.wan95b12332009-09-25 18:55:50 +0000396// We use an intermediate class to do the actual safe casting as Nokia's
397// Symbian compiler cannot decide between
398// template <T, M> ... (M) and
399// template <T, U> ... (const Matcher<U>&)
400// for function templates but can for member function templates.
401template <typename T>
402class SafeMatcherCastImpl {
403 public:
404 // This overload handles polymorphic matchers only since monomorphic
405 // matchers are handled by the next one.
406 template <typename M>
407 static inline Matcher<T> Cast(M polymorphic_matcher) {
408 return Matcher<T>(polymorphic_matcher);
409 }
zhanyong.wan18490652009-05-11 18:54:08 +0000410
zhanyong.wan95b12332009-09-25 18:55:50 +0000411 // This overload handles monomorphic matchers.
412 //
413 // In general, if type T can be implicitly converted to type U, we can
414 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
415 // contravariant): just keep a copy of the original Matcher<U>, convert the
416 // argument from type T to U, and then pass it to the underlying Matcher<U>.
417 // The only exception is when U is a reference and T is not, as the
418 // underlying Matcher<U> may be interested in the argument's address, which
419 // is not preserved in the conversion from T to U.
420 template <typename U>
421 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
422 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000423 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000424 T_must_be_implicitly_convertible_to_U);
425 // Enforce that we are not converting a non-reference type T to a reference
426 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000427 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000428 internal::is_reference<T>::value || !internal::is_reference<U>::value,
429 cannot_convert_non_referentce_arg_to_reference);
430 // In case both T and U are arithmetic types, enforce that the
431 // conversion is not lossy.
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000432 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
433 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000434 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
435 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000436 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000437 kTIsOther || kUIsOther ||
438 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
439 conversion_of_arithmetic_types_must_be_lossless);
440 return MatcherCast<T>(matcher);
441 }
442};
443
444template <typename T, typename M>
445inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
446 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000447}
448
shiqiane35fdd92008-12-10 05:08:54 +0000449// A<T>() returns a matcher that matches any value of type T.
450template <typename T>
451Matcher<T> A();
452
453// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
454// and MUST NOT BE USED IN USER CODE!!!
455namespace internal {
456
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000457// If the explanation is not empty, prints it to the ostream.
458inline void PrintIfNotEmpty(const internal::string& explanation,
459 std::ostream* os) {
460 if (explanation != "" && os != NULL) {
461 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000462 }
463}
464
zhanyong.wan736baa82010-09-27 17:44:16 +0000465// Returns true if the given type name is easy to read by a human.
466// This is used to decide whether printing the type of a value might
467// be helpful.
468inline bool IsReadableTypeName(const string& type_name) {
469 // We consider a type name readable if it's short or doesn't contain
470 // a template or function type.
471 return (type_name.length() <= 20 ||
472 type_name.find_first_of("<(") == string::npos);
473}
474
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000475// Matches the value against the given matcher, prints the value and explains
476// the match result to the listener. Returns the match result.
477// 'listener' must not be NULL.
478// Value cannot be passed by const reference, because some matchers take a
479// non-const argument.
480template <typename Value, typename T>
481bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
482 MatchResultListener* listener) {
483 if (!listener->IsInterested()) {
484 // If the listener is not interested, we do not need to construct the
485 // inner explanation.
486 return matcher.Matches(value);
487 }
488
489 StringMatchResultListener inner_listener;
490 const bool match = matcher.MatchAndExplain(value, &inner_listener);
491
492 UniversalPrint(value, listener->stream());
zhanyong.wan736baa82010-09-27 17:44:16 +0000493#if GTEST_HAS_RTTI
494 const string& type_name = GetTypeName<Value>();
495 if (IsReadableTypeName(type_name))
496 *listener->stream() << " (of type " << type_name << ")";
497#endif
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000498 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000499
500 return match;
501}
502
shiqiane35fdd92008-12-10 05:08:54 +0000503// An internal helper class for doing compile-time loop on a tuple's
504// fields.
505template <size_t N>
506class TuplePrefix {
507 public:
508 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
509 // iff the first N fields of matcher_tuple matches the first N
510 // fields of value_tuple, respectively.
511 template <typename MatcherTuple, typename ValueTuple>
512 static bool Matches(const MatcherTuple& matcher_tuple,
513 const ValueTuple& value_tuple) {
514 using ::std::tr1::get;
515 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
516 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
517 }
518
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000519 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000520 // describes failures in matching the first N fields of matchers
521 // against the first N fields of values. If there is no failure,
522 // nothing will be streamed to os.
523 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000524 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
525 const ValueTuple& values,
526 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000527 using ::std::tr1::tuple_element;
528 using ::std::tr1::get;
529
530 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000531 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000532
533 // Then describes the failure (if any) in the (N - 1)-th (0-based)
534 // field.
535 typename tuple_element<N - 1, MatcherTuple>::type matcher =
536 get<N - 1>(matchers);
537 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
538 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000539 StringMatchResultListener listener;
540 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000541 // TODO(wan): include in the message the name of the parameter
542 // as used in MOCK_METHOD*() when possible.
543 *os << " Expected arg #" << N - 1 << ": ";
544 get<N - 1>(matchers).DescribeTo(os);
545 *os << "\n Actual: ";
546 // We remove the reference in type Value to prevent the
547 // universal printer from printing the address of value, which
548 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000549 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000550 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000551 internal::UniversalPrint(value, os);
552 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000553 *os << "\n";
554 }
555 }
556};
557
558// The base case.
559template <>
560class TuplePrefix<0> {
561 public:
562 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000563 static bool Matches(const MatcherTuple& /* matcher_tuple */,
564 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000565 return true;
566 }
567
568 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000569 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
570 const ValueTuple& /* values */,
571 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000572};
573
574// TupleMatches(matcher_tuple, value_tuple) returns true iff all
575// matchers in matcher_tuple match the corresponding fields in
576// value_tuple. It is a compiler error if matcher_tuple and
577// value_tuple have different number of fields or incompatible field
578// types.
579template <typename MatcherTuple, typename ValueTuple>
580bool TupleMatches(const MatcherTuple& matcher_tuple,
581 const ValueTuple& value_tuple) {
582 using ::std::tr1::tuple_size;
583 // Makes sure that matcher_tuple and value_tuple have the same
584 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000585 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000586 tuple_size<ValueTuple>::value,
587 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000588 return TuplePrefix<tuple_size<ValueTuple>::value>::
589 Matches(matcher_tuple, value_tuple);
590}
591
592// Describes failures in matching matchers against values. If there
593// is no failure, nothing will be streamed to os.
594template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000595void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
596 const ValueTuple& values,
597 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000598 using ::std::tr1::tuple_size;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000599 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000600 matchers, values, os);
601}
602
603// The MatcherCastImpl class template is a helper for implementing
604// MatcherCast(). We need this helper in order to partially
605// specialize the implementation of MatcherCast() (C++ allows
606// class/struct templates to be partially specialized, but not
607// function templates.).
608
609// This general version is used when MatcherCast()'s argument is a
610// polymorphic matcher (i.e. something that can be converted to a
611// Matcher but is not one yet; for example, Eq(value)).
612template <typename T, typename M>
613class MatcherCastImpl {
614 public:
615 static Matcher<T> Cast(M polymorphic_matcher) {
616 return Matcher<T>(polymorphic_matcher);
617 }
618};
619
620// This more specialized version is used when MatcherCast()'s argument
621// is already a Matcher. This only compiles when type T can be
622// statically converted to type U.
623template <typename T, typename U>
624class MatcherCastImpl<T, Matcher<U> > {
625 public:
626 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
627 return Matcher<T>(new Impl(source_matcher));
628 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000629
shiqiane35fdd92008-12-10 05:08:54 +0000630 private:
631 class Impl : public MatcherInterface<T> {
632 public:
633 explicit Impl(const Matcher<U>& source_matcher)
634 : source_matcher_(source_matcher) {}
635
636 // We delegate the matching logic to the source matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000637 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
638 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000639 }
640
641 virtual void DescribeTo(::std::ostream* os) const {
642 source_matcher_.DescribeTo(os);
643 }
644
645 virtual void DescribeNegationTo(::std::ostream* os) const {
646 source_matcher_.DescribeNegationTo(os);
647 }
648
shiqiane35fdd92008-12-10 05:08:54 +0000649 private:
650 const Matcher<U> source_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000651
652 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000653 };
654};
655
656// This even more specialized version is used for efficiently casting
657// a matcher to its own type.
658template <typename T>
659class MatcherCastImpl<T, Matcher<T> > {
660 public:
661 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
662};
663
664// Implements A<T>().
665template <typename T>
666class AnyMatcherImpl : public MatcherInterface<T> {
667 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000668 virtual bool MatchAndExplain(
669 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000670 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
671 virtual void DescribeNegationTo(::std::ostream* os) const {
672 // This is mostly for completeness' safe, as it's not very useful
673 // to write Not(A<bool>()). However we cannot completely rule out
674 // such a possibility, and it doesn't hurt to be prepared.
675 *os << "never matches";
676 }
677};
678
679// Implements _, a matcher that matches any value of any
680// type. This is a polymorphic matcher, so we need a template type
681// conversion operator to make it appearing as a Matcher<T> for any
682// type T.
683class AnythingMatcher {
684 public:
685 template <typename T>
686 operator Matcher<T>() const { return A<T>(); }
687};
688
689// Implements a matcher that compares a given value with a
690// pre-supplied value using one of the ==, <=, <, etc, operators. The
691// two values being compared don't have to have the same type.
692//
693// The matcher defined here is polymorphic (for example, Eq(5) can be
694// used to match an int, a short, a double, etc). Therefore we use
695// a template type conversion operator in the implementation.
696//
697// We define this as a macro in order to eliminate duplicated source
698// code.
699//
700// The following template definition assumes that the Rhs parameter is
701// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000702#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_( \
703 name, op, relation, negated_relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000704 template <typename Rhs> class name##Matcher { \
705 public: \
706 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
707 template <typename Lhs> \
708 operator Matcher<Lhs>() const { \
709 return MakeMatcher(new Impl<Lhs>(rhs_)); \
710 } \
711 private: \
712 template <typename Lhs> \
713 class Impl : public MatcherInterface<Lhs> { \
714 public: \
715 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
zhanyong.wan82113312010-01-08 21:55:40 +0000716 virtual bool MatchAndExplain(\
717 Lhs lhs, MatchResultListener* /* listener */) const { \
718 return lhs op rhs_; \
719 } \
shiqiane35fdd92008-12-10 05:08:54 +0000720 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000721 *os << relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000722 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000723 } \
724 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000725 *os << negated_relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000726 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000727 } \
728 private: \
729 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000730 GTEST_DISALLOW_ASSIGN_(Impl); \
shiqiane35fdd92008-12-10 05:08:54 +0000731 }; \
732 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000733 GTEST_DISALLOW_ASSIGN_(name##Matcher); \
shiqiane35fdd92008-12-10 05:08:54 +0000734 }
735
736// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
737// respectively.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000738GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "is equal to", "isn't equal to");
739GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "is >=", "isn't >=");
740GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "is >", "isn't >");
741GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "is <=", "isn't <=");
742GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "is <", "isn't <");
743GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "isn't equal to", "is equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000744
zhanyong.wane0d051e2009-02-19 00:33:37 +0000745#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000746
vladlosev79b83502009-11-18 00:43:37 +0000747// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000748// pointer that is NULL.
749class IsNullMatcher {
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 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000756
757 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
758 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000759 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000760 }
761};
762
vladlosev79b83502009-11-18 00:43:37 +0000763// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000764// pointer that is not NULL.
765class NotNullMatcher {
766 public:
vladlosev79b83502009-11-18 00:43:37 +0000767 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000768 bool MatchAndExplain(const Pointer& p,
769 MatchResultListener* /* listener */) const {
770 return GetRawPointer(p) != NULL;
771 }
shiqiane35fdd92008-12-10 05:08:54 +0000772
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000773 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +0000774 void DescribeNegationTo(::std::ostream* os) const {
775 *os << "is NULL";
776 }
777};
778
779// Ref(variable) matches any argument that is a reference to
780// 'variable'. This matcher is polymorphic as it can match any
781// super type of the type of 'variable'.
782//
783// The RefMatcher template class implements Ref(variable). It can
784// only be instantiated with a reference type. This prevents a user
785// from mistakenly using Ref(x) to match a non-reference function
786// argument. For example, the following will righteously cause a
787// compiler error:
788//
789// int n;
790// Matcher<int> m1 = Ref(n); // This won't compile.
791// Matcher<int&> m2 = Ref(n); // This will compile.
792template <typename T>
793class RefMatcher;
794
795template <typename T>
796class RefMatcher<T&> {
797 // Google Mock is a generic framework and thus needs to support
798 // mocking any function types, including those that take non-const
799 // reference arguments. Therefore the template parameter T (and
800 // Super below) can be instantiated to either a const type or a
801 // non-const type.
802 public:
803 // RefMatcher() takes a T& instead of const T&, as we want the
804 // compiler to catch using Ref(const_value) as a matcher for a
805 // non-const reference.
806 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
807
808 template <typename Super>
809 operator Matcher<Super&>() const {
810 // By passing object_ (type T&) to Impl(), which expects a Super&,
811 // we make sure that Super is a super type of T. In particular,
812 // this catches using Ref(const_value) as a matcher for a
813 // non-const reference, as you cannot implicitly convert a const
814 // reference to a non-const reference.
815 return MakeMatcher(new Impl<Super>(object_));
816 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000817
shiqiane35fdd92008-12-10 05:08:54 +0000818 private:
819 template <typename Super>
820 class Impl : public MatcherInterface<Super&> {
821 public:
822 explicit Impl(Super& x) : object_(x) {} // NOLINT
823
zhanyong.wandb22c222010-01-28 21:52:29 +0000824 // MatchAndExplain() takes a Super& (as opposed to const Super&)
825 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +0000826 virtual bool MatchAndExplain(
827 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000828 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +0000829 return &x == &object_;
830 }
shiqiane35fdd92008-12-10 05:08:54 +0000831
832 virtual void DescribeTo(::std::ostream* os) const {
833 *os << "references the variable ";
834 UniversalPrinter<Super&>::Print(object_, os);
835 }
836
837 virtual void DescribeNegationTo(::std::ostream* os) const {
838 *os << "does not reference the variable ";
839 UniversalPrinter<Super&>::Print(object_, os);
840 }
841
shiqiane35fdd92008-12-10 05:08:54 +0000842 private:
843 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000844
845 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000846 };
847
848 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000849
850 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000851};
852
853// Polymorphic helper functions for narrow and wide string matchers.
854inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
855 return String::CaseInsensitiveCStringEquals(lhs, rhs);
856}
857
858inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
859 const wchar_t* rhs) {
860 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
861}
862
863// String comparison for narrow or wide strings that can have embedded NUL
864// characters.
865template <typename StringType>
866bool CaseInsensitiveStringEquals(const StringType& s1,
867 const StringType& s2) {
868 // Are the heads equal?
869 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
870 return false;
871 }
872
873 // Skip the equal heads.
874 const typename StringType::value_type nul = 0;
875 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
876
877 // Are we at the end of either s1 or s2?
878 if (i1 == StringType::npos || i2 == StringType::npos) {
879 return i1 == i2;
880 }
881
882 // Are the tails equal?
883 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
884}
885
886// String matchers.
887
888// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
889template <typename StringType>
890class StrEqualityMatcher {
891 public:
892 typedef typename StringType::const_pointer ConstCharPointer;
893
894 StrEqualityMatcher(const StringType& str, bool expect_eq,
895 bool case_sensitive)
896 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
897
898 // When expect_eq_ is true, returns true iff s is equal to string_;
899 // otherwise returns true iff s is not equal to string_.
zhanyong.wandb22c222010-01-28 21:52:29 +0000900 bool MatchAndExplain(ConstCharPointer s,
901 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +0000902 if (s == NULL) {
903 return !expect_eq_;
904 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000905 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000906 }
907
zhanyong.wandb22c222010-01-28 21:52:29 +0000908 bool MatchAndExplain(const StringType& s,
909 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000910 const bool eq = case_sensitive_ ? s == string_ :
911 CaseInsensitiveStringEquals(s, string_);
912 return expect_eq_ == eq;
913 }
914
915 void DescribeTo(::std::ostream* os) const {
916 DescribeToHelper(expect_eq_, os);
917 }
918
919 void DescribeNegationTo(::std::ostream* os) const {
920 DescribeToHelper(!expect_eq_, os);
921 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000922
shiqiane35fdd92008-12-10 05:08:54 +0000923 private:
924 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000925 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +0000926 *os << "equal to ";
927 if (!case_sensitive_) {
928 *os << "(ignoring case) ";
929 }
vladloseve2e8ba42010-05-13 18:16:03 +0000930 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +0000931 }
932
933 const StringType string_;
934 const bool expect_eq_;
935 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000936
937 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000938};
939
940// Implements the polymorphic HasSubstr(substring) matcher, which
941// can be used as a Matcher<T> as long as T can be converted to a
942// string.
943template <typename StringType>
944class HasSubstrMatcher {
945 public:
946 typedef typename StringType::const_pointer ConstCharPointer;
947
948 explicit HasSubstrMatcher(const StringType& substring)
949 : substring_(substring) {}
950
951 // These overloaded methods allow HasSubstr(substring) to be used as a
952 // Matcher<T> as long as T can be converted to string. Returns true
953 // iff s contains substring_ as a substring.
zhanyong.wandb22c222010-01-28 21:52:29 +0000954 bool MatchAndExplain(ConstCharPointer s,
955 MatchResultListener* listener) const {
956 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000957 }
958
zhanyong.wandb22c222010-01-28 21:52:29 +0000959 bool MatchAndExplain(const StringType& s,
960 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000961 return s.find(substring_) != StringType::npos;
962 }
963
964 // Describes what this matcher matches.
965 void DescribeTo(::std::ostream* os) const {
966 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +0000967 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +0000968 }
969
970 void DescribeNegationTo(::std::ostream* os) const {
971 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +0000972 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +0000973 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000974
shiqiane35fdd92008-12-10 05:08:54 +0000975 private:
976 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000977
978 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000979};
980
981// Implements the polymorphic StartsWith(substring) matcher, which
982// can be used as a Matcher<T> as long as T can be converted to a
983// string.
984template <typename StringType>
985class StartsWithMatcher {
986 public:
987 typedef typename StringType::const_pointer ConstCharPointer;
988
989 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
990 }
991
992 // These overloaded methods allow StartsWith(prefix) to be used as a
993 // Matcher<T> as long as T can be converted to string. Returns true
994 // iff s starts with prefix_.
zhanyong.wandb22c222010-01-28 21:52:29 +0000995 bool MatchAndExplain(ConstCharPointer s,
996 MatchResultListener* listener) const {
997 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000998 }
999
zhanyong.wandb22c222010-01-28 21:52:29 +00001000 bool MatchAndExplain(const StringType& s,
1001 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001002 return s.length() >= prefix_.length() &&
1003 s.substr(0, prefix_.length()) == prefix_;
1004 }
1005
1006 void DescribeTo(::std::ostream* os) const {
1007 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001008 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001009 }
1010
1011 void DescribeNegationTo(::std::ostream* os) const {
1012 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001013 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001014 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001015
shiqiane35fdd92008-12-10 05:08:54 +00001016 private:
1017 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001018
1019 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001020};
1021
1022// Implements the polymorphic EndsWith(substring) matcher, which
1023// can be used as a Matcher<T> as long as T can be converted to a
1024// string.
1025template <typename StringType>
1026class EndsWithMatcher {
1027 public:
1028 typedef typename StringType::const_pointer ConstCharPointer;
1029
1030 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1031
1032 // These overloaded methods allow EndsWith(suffix) to be used as a
1033 // Matcher<T> as long as T can be converted to string. Returns true
1034 // iff s ends with suffix_.
zhanyong.wandb22c222010-01-28 21:52:29 +00001035 bool MatchAndExplain(ConstCharPointer s,
1036 MatchResultListener* listener) const {
1037 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001038 }
1039
zhanyong.wandb22c222010-01-28 21:52:29 +00001040 bool MatchAndExplain(const StringType& s,
1041 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001042 return s.length() >= suffix_.length() &&
1043 s.substr(s.length() - suffix_.length()) == suffix_;
1044 }
1045
1046 void DescribeTo(::std::ostream* os) const {
1047 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001048 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001049 }
1050
1051 void DescribeNegationTo(::std::ostream* os) const {
1052 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001053 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001054 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001055
shiqiane35fdd92008-12-10 05:08:54 +00001056 private:
1057 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001058
1059 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001060};
1061
shiqiane35fdd92008-12-10 05:08:54 +00001062// Implements polymorphic matchers MatchesRegex(regex) and
1063// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1064// T can be converted to a string.
1065class MatchesRegexMatcher {
1066 public:
1067 MatchesRegexMatcher(const RE* regex, bool full_match)
1068 : regex_(regex), full_match_(full_match) {}
1069
1070 // These overloaded methods allow MatchesRegex(regex) to be used as
1071 // a Matcher<T> as long as T can be converted to string. Returns
1072 // true iff s matches regular expression regex. When full_match_ is
1073 // true, a full match is done; otherwise a partial match is done.
zhanyong.wandb22c222010-01-28 21:52:29 +00001074 bool MatchAndExplain(const char* s,
1075 MatchResultListener* listener) const {
1076 return s != NULL && MatchAndExplain(internal::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001077 }
1078
zhanyong.wandb22c222010-01-28 21:52:29 +00001079 bool MatchAndExplain(const internal::string& s,
1080 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001081 return full_match_ ? RE::FullMatch(s, *regex_) :
1082 RE::PartialMatch(s, *regex_);
1083 }
1084
1085 void DescribeTo(::std::ostream* os) const {
1086 *os << (full_match_ ? "matches" : "contains")
1087 << " regular expression ";
1088 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1089 }
1090
1091 void DescribeNegationTo(::std::ostream* os) const {
1092 *os << "doesn't " << (full_match_ ? "match" : "contain")
1093 << " regular expression ";
1094 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1095 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001096
shiqiane35fdd92008-12-10 05:08:54 +00001097 private:
1098 const internal::linked_ptr<const RE> regex_;
1099 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001100
1101 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001102};
1103
shiqiane35fdd92008-12-10 05:08:54 +00001104// Implements a matcher that compares the two fields of a 2-tuple
1105// using one of the ==, <=, <, etc, operators. The two fields being
1106// compared don't have to have the same type.
1107//
1108// The matcher defined here is polymorphic (for example, Eq() can be
1109// used to match a tuple<int, short>, a tuple<const long&, double>,
1110// etc). Therefore we use a template type conversion operator in the
1111// implementation.
1112//
1113// We define this as a macro in order to eliminate duplicated source
1114// code.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001115#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +00001116 class name##2Matcher { \
1117 public: \
1118 template <typename T1, typename T2> \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001119 operator Matcher< ::std::tr1::tuple<T1, T2> >() const { \
1120 return MakeMatcher(new Impl< ::std::tr1::tuple<T1, T2> >); \
1121 } \
1122 template <typename T1, typename T2> \
shiqiane35fdd92008-12-10 05:08:54 +00001123 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001124 return MakeMatcher(new Impl<const ::std::tr1::tuple<T1, T2>&>); \
shiqiane35fdd92008-12-10 05:08:54 +00001125 } \
1126 private: \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001127 template <typename Tuple> \
1128 class Impl : public MatcherInterface<Tuple> { \
shiqiane35fdd92008-12-10 05:08:54 +00001129 public: \
zhanyong.wan82113312010-01-08 21:55:40 +00001130 virtual bool MatchAndExplain( \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001131 Tuple args, \
zhanyong.wan82113312010-01-08 21:55:40 +00001132 MatchResultListener* /* listener */) const { \
shiqiane35fdd92008-12-10 05:08:54 +00001133 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
1134 } \
1135 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001136 *os << "are " relation; \
shiqiane35fdd92008-12-10 05:08:54 +00001137 } \
1138 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001139 *os << "aren't " relation; \
shiqiane35fdd92008-12-10 05:08:54 +00001140 } \
1141 }; \
1142 }
1143
1144// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001145GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "an equal pair");
1146GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1147 Ge, >=, "a pair where the first >= the second");
1148GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1149 Gt, >, "a pair where the first > the second");
1150GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1151 Le, <=, "a pair where the first <= the second");
1152GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1153 Lt, <, "a pair where the first < the second");
1154GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=, "an unequal pair");
shiqiane35fdd92008-12-10 05:08:54 +00001155
zhanyong.wane0d051e2009-02-19 00:33:37 +00001156#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +00001157
zhanyong.wanc6a41232009-05-13 23:38:40 +00001158// Implements the Not(...) matcher for a particular argument type T.
1159// We do not nest it inside the NotMatcher class template, as that
1160// will prevent different instantiations of NotMatcher from sharing
1161// the same NotMatcherImpl<T> class.
1162template <typename T>
1163class NotMatcherImpl : public MatcherInterface<T> {
1164 public:
1165 explicit NotMatcherImpl(const Matcher<T>& matcher)
1166 : matcher_(matcher) {}
1167
zhanyong.wan82113312010-01-08 21:55:40 +00001168 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1169 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001170 }
1171
1172 virtual void DescribeTo(::std::ostream* os) const {
1173 matcher_.DescribeNegationTo(os);
1174 }
1175
1176 virtual void DescribeNegationTo(::std::ostream* os) const {
1177 matcher_.DescribeTo(os);
1178 }
1179
zhanyong.wanc6a41232009-05-13 23:38:40 +00001180 private:
1181 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001182
1183 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001184};
1185
shiqiane35fdd92008-12-10 05:08:54 +00001186// Implements the Not(m) matcher, which matches a value that doesn't
1187// match matcher m.
1188template <typename InnerMatcher>
1189class NotMatcher {
1190 public:
1191 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1192
1193 // This template type conversion operator allows Not(m) to be used
1194 // to match any type m can match.
1195 template <typename T>
1196 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001197 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001198 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001199
shiqiane35fdd92008-12-10 05:08:54 +00001200 private:
shiqiane35fdd92008-12-10 05:08:54 +00001201 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001202
1203 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001204};
1205
zhanyong.wanc6a41232009-05-13 23:38:40 +00001206// Implements the AllOf(m1, m2) matcher for a particular argument type
1207// T. We do not nest it inside the BothOfMatcher class template, as
1208// that will prevent different instantiations of BothOfMatcher from
1209// sharing the same BothOfMatcherImpl<T> class.
1210template <typename T>
1211class BothOfMatcherImpl : public MatcherInterface<T> {
1212 public:
1213 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1214 : matcher1_(matcher1), matcher2_(matcher2) {}
1215
zhanyong.wanc6a41232009-05-13 23:38:40 +00001216 virtual void DescribeTo(::std::ostream* os) const {
1217 *os << "(";
1218 matcher1_.DescribeTo(os);
1219 *os << ") and (";
1220 matcher2_.DescribeTo(os);
1221 *os << ")";
1222 }
1223
1224 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001225 *os << "(";
1226 matcher1_.DescribeNegationTo(os);
1227 *os << ") or (";
1228 matcher2_.DescribeNegationTo(os);
1229 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001230 }
1231
zhanyong.wan82113312010-01-08 21:55:40 +00001232 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1233 // If either matcher1_ or matcher2_ doesn't match x, we only need
1234 // to explain why one of them fails.
1235 StringMatchResultListener listener1;
1236 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1237 *listener << listener1.str();
1238 return false;
1239 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001240
zhanyong.wan82113312010-01-08 21:55:40 +00001241 StringMatchResultListener listener2;
1242 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1243 *listener << listener2.str();
1244 return false;
1245 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001246
zhanyong.wan82113312010-01-08 21:55:40 +00001247 // Otherwise we need to explain why *both* of them match.
1248 const internal::string s1 = listener1.str();
1249 const internal::string s2 = listener2.str();
1250
1251 if (s1 == "") {
1252 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001253 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001254 *listener << s1;
1255 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001256 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001257 }
1258 }
zhanyong.wan82113312010-01-08 21:55:40 +00001259 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001260 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001261
zhanyong.wanc6a41232009-05-13 23:38:40 +00001262 private:
1263 const Matcher<T> matcher1_;
1264 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001265
1266 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001267};
1268
shiqiane35fdd92008-12-10 05:08:54 +00001269// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1270// matches a value that matches all of the matchers m_1, ..., and m_n.
1271template <typename Matcher1, typename Matcher2>
1272class BothOfMatcher {
1273 public:
1274 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1275 : matcher1_(matcher1), matcher2_(matcher2) {}
1276
1277 // This template type conversion operator allows a
1278 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1279 // both Matcher1 and Matcher2 can match.
1280 template <typename T>
1281 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001282 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1283 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001284 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001285
shiqiane35fdd92008-12-10 05:08:54 +00001286 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001287 Matcher1 matcher1_;
1288 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001289
1290 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001291};
shiqiane35fdd92008-12-10 05:08:54 +00001292
zhanyong.wanc6a41232009-05-13 23:38:40 +00001293// Implements the AnyOf(m1, m2) matcher for a particular argument type
1294// T. We do not nest it inside the AnyOfMatcher class template, as
1295// that will prevent different instantiations of AnyOfMatcher from
1296// sharing the same EitherOfMatcherImpl<T> class.
1297template <typename T>
1298class EitherOfMatcherImpl : public MatcherInterface<T> {
1299 public:
1300 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1301 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001302
zhanyong.wanc6a41232009-05-13 23:38:40 +00001303 virtual void DescribeTo(::std::ostream* os) const {
1304 *os << "(";
1305 matcher1_.DescribeTo(os);
1306 *os << ") or (";
1307 matcher2_.DescribeTo(os);
1308 *os << ")";
1309 }
shiqiane35fdd92008-12-10 05:08:54 +00001310
zhanyong.wanc6a41232009-05-13 23:38:40 +00001311 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001312 *os << "(";
1313 matcher1_.DescribeNegationTo(os);
1314 *os << ") and (";
1315 matcher2_.DescribeNegationTo(os);
1316 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001317 }
shiqiane35fdd92008-12-10 05:08:54 +00001318
zhanyong.wan82113312010-01-08 21:55:40 +00001319 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1320 // If either matcher1_ or matcher2_ matches x, we just need to
1321 // explain why *one* of them matches.
1322 StringMatchResultListener listener1;
1323 if (matcher1_.MatchAndExplain(x, &listener1)) {
1324 *listener << listener1.str();
1325 return true;
1326 }
1327
1328 StringMatchResultListener listener2;
1329 if (matcher2_.MatchAndExplain(x, &listener2)) {
1330 *listener << listener2.str();
1331 return true;
1332 }
1333
1334 // Otherwise we need to explain why *both* of them fail.
1335 const internal::string s1 = listener1.str();
1336 const internal::string s2 = listener2.str();
1337
1338 if (s1 == "") {
1339 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001340 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001341 *listener << s1;
1342 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001343 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001344 }
1345 }
zhanyong.wan82113312010-01-08 21:55:40 +00001346 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001347 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001348
zhanyong.wanc6a41232009-05-13 23:38:40 +00001349 private:
1350 const Matcher<T> matcher1_;
1351 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001352
1353 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001354};
1355
1356// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1357// matches a value that matches at least one of the matchers m_1, ...,
1358// and m_n.
1359template <typename Matcher1, typename Matcher2>
1360class EitherOfMatcher {
1361 public:
1362 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1363 : matcher1_(matcher1), matcher2_(matcher2) {}
1364
1365 // This template type conversion operator allows a
1366 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1367 // both Matcher1 and Matcher2 can match.
1368 template <typename T>
1369 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001370 return Matcher<T>(new EitherOfMatcherImpl<T>(
1371 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001372 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001373
shiqiane35fdd92008-12-10 05:08:54 +00001374 private:
shiqiane35fdd92008-12-10 05:08:54 +00001375 Matcher1 matcher1_;
1376 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001377
1378 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001379};
1380
1381// Used for implementing Truly(pred), which turns a predicate into a
1382// matcher.
1383template <typename Predicate>
1384class TrulyMatcher {
1385 public:
1386 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1387
1388 // This method template allows Truly(pred) to be used as a matcher
1389 // for type T where T is the argument type of predicate 'pred'. The
1390 // argument is passed by reference as the predicate may be
1391 // interested in the address of the argument.
1392 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001393 bool MatchAndExplain(T& x, // NOLINT
1394 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00001395 // Without the if-statement, MSVC sometimes warns about converting
1396 // a value to bool (warning 4800).
1397 //
1398 // We cannot write 'return !!predicate_(x);' as that doesn't work
1399 // when predicate_(x) returns a class convertible to bool but
1400 // having no operator!().
1401 if (predicate_(x))
1402 return true;
1403 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001404 }
1405
1406 void DescribeTo(::std::ostream* os) const {
1407 *os << "satisfies the given predicate";
1408 }
1409
1410 void DescribeNegationTo(::std::ostream* os) const {
1411 *os << "doesn't satisfy the given predicate";
1412 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001413
shiqiane35fdd92008-12-10 05:08:54 +00001414 private:
1415 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001416
1417 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001418};
1419
1420// Used for implementing Matches(matcher), which turns a matcher into
1421// a predicate.
1422template <typename M>
1423class MatcherAsPredicate {
1424 public:
1425 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1426
1427 // This template operator() allows Matches(m) to be used as a
1428 // predicate on type T where m is a matcher on type T.
1429 //
1430 // The argument x is passed by reference instead of by value, as
1431 // some matcher may be interested in its address (e.g. as in
1432 // Matches(Ref(n))(x)).
1433 template <typename T>
1434 bool operator()(const T& x) const {
1435 // We let matcher_ commit to a particular type here instead of
1436 // when the MatcherAsPredicate object was constructed. This
1437 // allows us to write Matches(m) where m is a polymorphic matcher
1438 // (e.g. Eq(5)).
1439 //
1440 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1441 // compile when matcher_ has type Matcher<const T&>; if we write
1442 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1443 // when matcher_ has type Matcher<T>; if we just write
1444 // matcher_.Matches(x), it won't compile when matcher_ is
1445 // polymorphic, e.g. Eq(5).
1446 //
1447 // MatcherCast<const T&>() is necessary for making the code work
1448 // in all of the above situations.
1449 return MatcherCast<const T&>(matcher_).Matches(x);
1450 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001451
shiqiane35fdd92008-12-10 05:08:54 +00001452 private:
1453 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001454
1455 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001456};
1457
1458// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1459// argument M must be a type that can be converted to a matcher.
1460template <typename M>
1461class PredicateFormatterFromMatcher {
1462 public:
1463 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1464
1465 // This template () operator allows a PredicateFormatterFromMatcher
1466 // object to act as a predicate-formatter suitable for using with
1467 // Google Test's EXPECT_PRED_FORMAT1() macro.
1468 template <typename T>
1469 AssertionResult operator()(const char* value_text, const T& x) const {
1470 // We convert matcher_ to a Matcher<const T&> *now* instead of
1471 // when the PredicateFormatterFromMatcher object was constructed,
1472 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1473 // know which type to instantiate it to until we actually see the
1474 // type of x here.
1475 //
1476 // We write MatcherCast<const T&>(matcher_) instead of
1477 // Matcher<const T&>(matcher_), as the latter won't compile when
1478 // matcher_ has type Matcher<T> (e.g. An<int>()).
1479 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001480 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001481 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001482 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001483
1484 ::std::stringstream ss;
1485 ss << "Value of: " << value_text << "\n"
1486 << "Expected: ";
1487 matcher.DescribeTo(&ss);
1488 ss << "\n Actual: " << listener.str();
1489 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001490 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001491
shiqiane35fdd92008-12-10 05:08:54 +00001492 private:
1493 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001494
1495 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001496};
1497
1498// A helper function for converting a matcher to a predicate-formatter
1499// without the user needing to explicitly write the type. This is
1500// used for implementing ASSERT_THAT() and EXPECT_THAT().
1501template <typename M>
1502inline PredicateFormatterFromMatcher<M>
1503MakePredicateFormatterFromMatcher(const M& matcher) {
1504 return PredicateFormatterFromMatcher<M>(matcher);
1505}
1506
1507// Implements the polymorphic floating point equality matcher, which
1508// matches two float values using ULP-based approximation. The
1509// template is meant to be instantiated with FloatType being either
1510// float or double.
1511template <typename FloatType>
1512class FloatingEqMatcher {
1513 public:
1514 // Constructor for FloatingEqMatcher.
1515 // The matcher's input will be compared with rhs. The matcher treats two
1516 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1517 // equality comparisons between NANs will always return false.
1518 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1519 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1520
1521 // Implements floating point equality matcher as a Matcher<T>.
1522 template <typename T>
1523 class Impl : public MatcherInterface<T> {
1524 public:
1525 Impl(FloatType rhs, bool nan_eq_nan) :
1526 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1527
zhanyong.wan82113312010-01-08 21:55:40 +00001528 virtual bool MatchAndExplain(T value,
1529 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001530 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1531
1532 // Compares NaNs first, if nan_eq_nan_ is true.
1533 if (nan_eq_nan_ && lhs.is_nan()) {
1534 return rhs.is_nan();
1535 }
1536
1537 return lhs.AlmostEquals(rhs);
1538 }
1539
1540 virtual void DescribeTo(::std::ostream* os) const {
1541 // os->precision() returns the previously set precision, which we
1542 // store to restore the ostream to its original configuration
1543 // after outputting.
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_) {
1548 *os << "is NaN";
1549 } else {
1550 *os << "never matches";
1551 }
1552 } else {
1553 *os << "is approximately " << rhs_;
1554 }
1555 os->precision(old_precision);
1556 }
1557
1558 virtual void DescribeNegationTo(::std::ostream* os) const {
1559 // As before, get original precision.
1560 const ::std::streamsize old_precision = os->precision(
1561 ::std::numeric_limits<FloatType>::digits10 + 2);
1562 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1563 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001564 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00001565 } else {
1566 *os << "is anything";
1567 }
1568 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001569 *os << "isn't approximately " << rhs_;
shiqiane35fdd92008-12-10 05:08:54 +00001570 }
1571 // Restore original precision.
1572 os->precision(old_precision);
1573 }
1574
1575 private:
1576 const FloatType rhs_;
1577 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001578
1579 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001580 };
1581
1582 // The following 3 type conversion operators allow FloatEq(rhs) and
1583 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1584 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1585 // (While Google's C++ coding style doesn't allow arguments passed
1586 // by non-const reference, we may see them in code not conforming to
1587 // the style. Therefore Google Mock needs to support them.)
1588 operator Matcher<FloatType>() const {
1589 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1590 }
1591
1592 operator Matcher<const FloatType&>() const {
1593 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1594 }
1595
1596 operator Matcher<FloatType&>() const {
1597 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1598 }
1599 private:
1600 const FloatType rhs_;
1601 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001602
1603 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001604};
1605
1606// Implements the Pointee(m) matcher for matching a pointer whose
1607// pointee matches matcher m. The pointer can be either raw or smart.
1608template <typename InnerMatcher>
1609class PointeeMatcher {
1610 public:
1611 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1612
1613 // This type conversion operator template allows Pointee(m) to be
1614 // used as a matcher for any pointer type whose pointee type is
1615 // compatible with the inner matcher, where type Pointer can be
1616 // either a raw pointer or a smart pointer.
1617 //
1618 // The reason we do this instead of relying on
1619 // MakePolymorphicMatcher() is that the latter is not flexible
1620 // enough for implementing the DescribeTo() method of Pointee().
1621 template <typename Pointer>
1622 operator Matcher<Pointer>() const {
1623 return MakeMatcher(new Impl<Pointer>(matcher_));
1624 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001625
shiqiane35fdd92008-12-10 05:08:54 +00001626 private:
1627 // The monomorphic implementation that works for a particular pointer type.
1628 template <typename Pointer>
1629 class Impl : public MatcherInterface<Pointer> {
1630 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00001631 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
1632 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001633
1634 explicit Impl(const InnerMatcher& matcher)
1635 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1636
shiqiane35fdd92008-12-10 05:08:54 +00001637 virtual void DescribeTo(::std::ostream* os) const {
1638 *os << "points to a value that ";
1639 matcher_.DescribeTo(os);
1640 }
1641
1642 virtual void DescribeNegationTo(::std::ostream* os) const {
1643 *os << "does not point to a value that ";
1644 matcher_.DescribeTo(os);
1645 }
1646
zhanyong.wan82113312010-01-08 21:55:40 +00001647 virtual bool MatchAndExplain(Pointer pointer,
1648 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001649 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00001650 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001651
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001652 *listener << "which points to ";
1653 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001654 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001655
shiqiane35fdd92008-12-10 05:08:54 +00001656 private:
1657 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001658
1659 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001660 };
1661
1662 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001663
1664 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001665};
1666
1667// Implements the Field() matcher for matching a field (i.e. member
1668// variable) of an object.
1669template <typename Class, typename FieldType>
1670class FieldMatcher {
1671 public:
1672 FieldMatcher(FieldType Class::*field,
1673 const Matcher<const FieldType&>& matcher)
1674 : field_(field), matcher_(matcher) {}
1675
shiqiane35fdd92008-12-10 05:08:54 +00001676 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001677 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001678 matcher_.DescribeTo(os);
1679 }
1680
1681 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001682 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001683 matcher_.DescribeNegationTo(os);
1684 }
1685
zhanyong.wandb22c222010-01-28 21:52:29 +00001686 template <typename T>
1687 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
1688 return MatchAndExplainImpl(
1689 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00001690 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00001691 value, listener);
1692 }
1693
1694 private:
1695 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001696 // Symbian's C++ compiler choose which overload to use. Its type is
1697 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001698 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1699 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001700 *listener << "whose given field is ";
1701 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001702 }
1703
zhanyong.wandb22c222010-01-28 21:52:29 +00001704 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1705 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001706 if (p == NULL)
1707 return false;
1708
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001709 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001710 // Since *p has a field, it must be a class/struct/union type and
1711 // thus cannot be a pointer. Therefore we pass false_type() as
1712 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001713 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001714 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001715
shiqiane35fdd92008-12-10 05:08:54 +00001716 const FieldType Class::*field_;
1717 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001718
1719 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001720};
1721
shiqiane35fdd92008-12-10 05:08:54 +00001722// Implements the Property() matcher for matching a property
1723// (i.e. return value of a getter method) of an object.
1724template <typename Class, typename PropertyType>
1725class PropertyMatcher {
1726 public:
1727 // The property may have a reference type, so 'const PropertyType&'
1728 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00001729 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00001730 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00001731 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001732
1733 PropertyMatcher(PropertyType (Class::*property)() const,
1734 const Matcher<RefToConstProperty>& matcher)
1735 : property_(property), matcher_(matcher) {}
1736
shiqiane35fdd92008-12-10 05:08:54 +00001737 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001738 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001739 matcher_.DescribeTo(os);
1740 }
1741
1742 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001743 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001744 matcher_.DescribeNegationTo(os);
1745 }
1746
zhanyong.wandb22c222010-01-28 21:52:29 +00001747 template <typename T>
1748 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
1749 return MatchAndExplainImpl(
1750 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00001751 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00001752 value, listener);
1753 }
1754
1755 private:
1756 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001757 // Symbian's C++ compiler choose which overload to use. Its type is
1758 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001759 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1760 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001761 *listener << "whose given property is ";
1762 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
1763 // which takes a non-const reference as argument.
1764 RefToConstProperty result = (obj.*property_)();
1765 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001766 }
1767
zhanyong.wandb22c222010-01-28 21:52:29 +00001768 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1769 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001770 if (p == NULL)
1771 return false;
1772
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001773 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001774 // Since *p has a property method, it must be a class/struct/union
1775 // type and thus cannot be a pointer. Therefore we pass
1776 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001777 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001778 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001779
shiqiane35fdd92008-12-10 05:08:54 +00001780 PropertyType (Class::*property_)() const;
1781 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001782
1783 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001784};
1785
shiqiane35fdd92008-12-10 05:08:54 +00001786// Type traits specifying various features of different functors for ResultOf.
1787// The default template specifies features for functor objects.
1788// Functor classes have to typedef argument_type and result_type
1789// to be compatible with ResultOf.
1790template <typename Functor>
1791struct CallableTraits {
1792 typedef typename Functor::result_type ResultType;
1793 typedef Functor StorageType;
1794
zhanyong.wan32de5f52009-12-23 00:13:23 +00001795 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00001796 template <typename T>
1797 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1798};
1799
1800// Specialization for function pointers.
1801template <typename ArgType, typename ResType>
1802struct CallableTraits<ResType(*)(ArgType)> {
1803 typedef ResType ResultType;
1804 typedef ResType(*StorageType)(ArgType);
1805
1806 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001807 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00001808 << "NULL function pointer is passed into ResultOf().";
1809 }
1810 template <typename T>
1811 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1812 return (*f)(arg);
1813 }
1814};
1815
1816// Implements the ResultOf() matcher for matching a return value of a
1817// unary function of an object.
1818template <typename Callable>
1819class ResultOfMatcher {
1820 public:
1821 typedef typename CallableTraits<Callable>::ResultType ResultType;
1822
1823 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1824 : callable_(callable), matcher_(matcher) {
1825 CallableTraits<Callable>::CheckIsValid(callable_);
1826 }
1827
1828 template <typename T>
1829 operator Matcher<T>() const {
1830 return Matcher<T>(new Impl<T>(callable_, matcher_));
1831 }
1832
1833 private:
1834 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1835
1836 template <typename T>
1837 class Impl : public MatcherInterface<T> {
1838 public:
1839 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1840 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00001841
1842 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001843 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001844 matcher_.DescribeTo(os);
1845 }
1846
1847 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001848 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001849 matcher_.DescribeNegationTo(os);
1850 }
1851
zhanyong.wan82113312010-01-08 21:55:40 +00001852 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001853 *listener << "which is mapped by the given callable to ";
1854 // Cannot pass the return value (for example, int) to
1855 // MatchPrintAndExplain, which takes a non-const reference as argument.
1856 ResultType result =
1857 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
1858 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001859 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001860
shiqiane35fdd92008-12-10 05:08:54 +00001861 private:
1862 // Functors often define operator() as non-const method even though
1863 // they are actualy stateless. But we need to use them even when
1864 // 'this' is a const pointer. It's the user's responsibility not to
1865 // use stateful callables with ResultOf(), which does't guarantee
1866 // how many times the callable will be invoked.
1867 mutable CallableStorageType callable_;
1868 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001869
1870 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001871 }; // class Impl
1872
1873 const CallableStorageType callable_;
1874 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001875
1876 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001877};
1878
zhanyong.wan6a896b52009-01-16 01:13:50 +00001879// Implements an equality matcher for any STL-style container whose elements
1880// support ==. This matcher is like Eq(), but its failure explanations provide
1881// more detailed information that is useful when the container is used as a set.
1882// The failure message reports elements that are in one of the operands but not
1883// the other. The failure messages do not report duplicate or out-of-order
1884// elements in the containers (which don't properly matter to sets, but can
1885// occur if the containers are vectors or lists, for example).
1886//
1887// Uses the container's const_iterator, value_type, operator ==,
1888// begin(), and end().
1889template <typename Container>
1890class ContainerEqMatcher {
1891 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00001892 typedef internal::StlContainerView<Container> View;
1893 typedef typename View::type StlContainer;
1894 typedef typename View::const_reference StlContainerReference;
1895
1896 // We make a copy of rhs in case the elements in it are modified
1897 // after this matcher is created.
1898 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
1899 // Makes sure the user doesn't instantiate this class template
1900 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001901 (void)testing::StaticAssertTypeEq<Container,
1902 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00001903 }
1904
zhanyong.wan6a896b52009-01-16 01:13:50 +00001905 void DescribeTo(::std::ostream* os) const {
1906 *os << "equals ";
vladloseve2e8ba42010-05-13 18:16:03 +00001907 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001908 }
1909 void DescribeNegationTo(::std::ostream* os) const {
1910 *os << "does not equal ";
vladloseve2e8ba42010-05-13 18:16:03 +00001911 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001912 }
1913
zhanyong.wanb8243162009-06-04 05:48:20 +00001914 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00001915 bool MatchAndExplain(const LhsContainer& lhs,
1916 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00001917 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00001918 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00001919 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00001920 LhsView;
1921 typedef typename LhsView::type LhsStlContainer;
1922 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00001923 if (lhs_stl_container == rhs_)
1924 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00001925
zhanyong.wane122e452010-01-12 09:03:52 +00001926 ::std::ostream* const os = listener->stream();
1927 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001928 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00001929 bool printed_header = false;
1930 for (typename LhsStlContainer::const_iterator it =
1931 lhs_stl_container.begin();
1932 it != lhs_stl_container.end(); ++it) {
1933 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
1934 rhs_.end()) {
1935 if (printed_header) {
1936 *os << ", ";
1937 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001938 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00001939 printed_header = true;
1940 }
vladloseve2e8ba42010-05-13 18:16:03 +00001941 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001942 }
zhanyong.wane122e452010-01-12 09:03:52 +00001943 }
1944
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001945 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00001946 bool printed_header2 = false;
1947 for (typename StlContainer::const_iterator it = rhs_.begin();
1948 it != rhs_.end(); ++it) {
1949 if (internal::ArrayAwareFind(
1950 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
1951 lhs_stl_container.end()) {
1952 if (printed_header2) {
1953 *os << ", ";
1954 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001955 *os << (printed_header ? ",\nand" : "which")
1956 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00001957 printed_header2 = true;
1958 }
vladloseve2e8ba42010-05-13 18:16:03 +00001959 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00001960 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00001961 }
1962 }
1963
zhanyong.wane122e452010-01-12 09:03:52 +00001964 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00001965 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001966
zhanyong.wan6a896b52009-01-16 01:13:50 +00001967 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00001968 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001969
1970 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001971};
1972
zhanyong.wan898725c2011-09-16 16:45:39 +00001973// A comparator functor that uses the < operator to compare two values.
1974struct LessComparator {
1975 template <typename T, typename U>
1976 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
1977};
1978
1979// Implements WhenSortedBy(comparator, container_matcher).
1980template <typename Comparator, typename ContainerMatcher>
1981class WhenSortedByMatcher {
1982 public:
1983 WhenSortedByMatcher(const Comparator& comparator,
1984 const ContainerMatcher& matcher)
1985 : comparator_(comparator), matcher_(matcher) {}
1986
1987 template <typename LhsContainer>
1988 operator Matcher<LhsContainer>() const {
1989 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
1990 }
1991
1992 template <typename LhsContainer>
1993 class Impl : public MatcherInterface<LhsContainer> {
1994 public:
1995 typedef internal::StlContainerView<
1996 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
1997 typedef typename LhsView::type LhsStlContainer;
1998 typedef typename LhsView::const_reference LhsStlContainerReference;
1999 typedef typename LhsStlContainer::value_type LhsValue;
2000
2001 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2002 : comparator_(comparator), matcher_(matcher) {}
2003
2004 virtual void DescribeTo(::std::ostream* os) const {
2005 *os << "(when sorted) ";
2006 matcher_.DescribeTo(os);
2007 }
2008
2009 virtual void DescribeNegationTo(::std::ostream* os) const {
2010 *os << "(when sorted) ";
2011 matcher_.DescribeNegationTo(os);
2012 }
2013
2014 virtual bool MatchAndExplain(LhsContainer lhs,
2015 MatchResultListener* listener) const {
2016 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2017 std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2018 lhs_stl_container.end());
2019 std::sort(sorted_container.begin(), sorted_container.end(), comparator_);
2020
2021 if (!listener->IsInterested()) {
2022 // If the listener is not interested, we do not need to
2023 // construct the inner explanation.
2024 return matcher_.Matches(sorted_container);
2025 }
2026
2027 *listener << "which is ";
2028 UniversalPrint(sorted_container, listener->stream());
2029 *listener << " when sorted";
2030
2031 StringMatchResultListener inner_listener;
2032 const bool match = matcher_.MatchAndExplain(sorted_container,
2033 &inner_listener);
2034 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2035 return match;
2036 }
2037
2038 private:
2039 const Comparator comparator_;
2040 const Matcher<const std::vector<LhsValue>&> matcher_;
2041
2042 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2043 };
2044
2045 private:
2046 const Comparator comparator_;
2047 const ContainerMatcher matcher_;
2048
2049 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2050};
2051
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002052// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2053// must be able to be safely cast to Matcher<tuple<const T1&, const
2054// T2&> >, where T1 and T2 are the types of elements in the LHS
2055// container and the RHS container respectively.
2056template <typename TupleMatcher, typename RhsContainer>
2057class PointwiseMatcher {
2058 public:
2059 typedef internal::StlContainerView<RhsContainer> RhsView;
2060 typedef typename RhsView::type RhsStlContainer;
2061 typedef typename RhsStlContainer::value_type RhsValue;
2062
2063 // Like ContainerEq, we make a copy of rhs in case the elements in
2064 // it are modified after this matcher is created.
2065 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2066 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2067 // Makes sure the user doesn't instantiate this class template
2068 // with a const or reference type.
2069 (void)testing::StaticAssertTypeEq<RhsContainer,
2070 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2071 }
2072
2073 template <typename LhsContainer>
2074 operator Matcher<LhsContainer>() const {
2075 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2076 }
2077
2078 template <typename LhsContainer>
2079 class Impl : public MatcherInterface<LhsContainer> {
2080 public:
2081 typedef internal::StlContainerView<
2082 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2083 typedef typename LhsView::type LhsStlContainer;
2084 typedef typename LhsView::const_reference LhsStlContainerReference;
2085 typedef typename LhsStlContainer::value_type LhsValue;
2086 // We pass the LHS value and the RHS value to the inner matcher by
2087 // reference, as they may be expensive to copy. We must use tuple
2088 // instead of pair here, as a pair cannot hold references (C++ 98,
2089 // 20.2.2 [lib.pairs]).
2090 typedef std::tr1::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
2091
2092 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2093 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2094 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2095 rhs_(rhs) {}
2096
2097 virtual void DescribeTo(::std::ostream* os) const {
2098 *os << "contains " << rhs_.size()
2099 << " values, where each value and its corresponding value in ";
2100 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2101 *os << " ";
2102 mono_tuple_matcher_.DescribeTo(os);
2103 }
2104 virtual void DescribeNegationTo(::std::ostream* os) const {
2105 *os << "doesn't contain exactly " << rhs_.size()
2106 << " values, or contains a value x at some index i"
2107 << " where x and the i-th value of ";
2108 UniversalPrint(rhs_, os);
2109 *os << " ";
2110 mono_tuple_matcher_.DescribeNegationTo(os);
2111 }
2112
2113 virtual bool MatchAndExplain(LhsContainer lhs,
2114 MatchResultListener* listener) const {
2115 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2116 const size_t actual_size = lhs_stl_container.size();
2117 if (actual_size != rhs_.size()) {
2118 *listener << "which contains " << actual_size << " values";
2119 return false;
2120 }
2121
2122 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2123 typename RhsStlContainer::const_iterator right = rhs_.begin();
2124 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2125 const InnerMatcherArg value_pair(*left, *right);
2126
2127 if (listener->IsInterested()) {
2128 StringMatchResultListener inner_listener;
2129 if (!mono_tuple_matcher_.MatchAndExplain(
2130 value_pair, &inner_listener)) {
2131 *listener << "where the value pair (";
2132 UniversalPrint(*left, listener->stream());
2133 *listener << ", ";
2134 UniversalPrint(*right, listener->stream());
2135 *listener << ") at index #" << i << " don't match";
2136 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2137 return false;
2138 }
2139 } else {
2140 if (!mono_tuple_matcher_.Matches(value_pair))
2141 return false;
2142 }
2143 }
2144
2145 return true;
2146 }
2147
2148 private:
2149 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2150 const RhsStlContainer rhs_;
2151
2152 GTEST_DISALLOW_ASSIGN_(Impl);
2153 };
2154
2155 private:
2156 const TupleMatcher tuple_matcher_;
2157 const RhsStlContainer rhs_;
2158
2159 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2160};
2161
zhanyong.wan33605ba2010-04-22 23:37:47 +00002162// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002163template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002164class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002165 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002166 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002167 typedef StlContainerView<RawContainer> View;
2168 typedef typename View::type StlContainer;
2169 typedef typename View::const_reference StlContainerReference;
2170 typedef typename StlContainer::value_type Element;
2171
2172 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002173 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002174 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002175 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002176
zhanyong.wan33605ba2010-04-22 23:37:47 +00002177 // Checks whether:
2178 // * All elements in the container match, if all_elements_should_match.
2179 // * Any element in the container matches, if !all_elements_should_match.
2180 bool MatchAndExplainImpl(bool all_elements_should_match,
2181 Container container,
2182 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002183 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002184 size_t i = 0;
2185 for (typename StlContainer::const_iterator it = stl_container.begin();
2186 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002187 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00002188 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2189
2190 if (matches != all_elements_should_match) {
2191 *listener << "whose element #" << i
2192 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002193 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00002194 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00002195 }
2196 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00002197 return all_elements_should_match;
2198 }
2199
2200 protected:
2201 const Matcher<const Element&> inner_matcher_;
2202
2203 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2204};
2205
2206// Implements Contains(element_matcher) for the given argument type Container.
2207// Symmetric to EachMatcherImpl.
2208template <typename Container>
2209class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2210 public:
2211 template <typename InnerMatcher>
2212 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2213 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2214
2215 // Describes what this matcher does.
2216 virtual void DescribeTo(::std::ostream* os) const {
2217 *os << "contains at least one element that ";
2218 this->inner_matcher_.DescribeTo(os);
2219 }
2220
2221 virtual void DescribeNegationTo(::std::ostream* os) const {
2222 *os << "doesn't contain any element that ";
2223 this->inner_matcher_.DescribeTo(os);
2224 }
2225
2226 virtual bool MatchAndExplain(Container container,
2227 MatchResultListener* listener) const {
2228 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002229 }
2230
2231 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002232 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002233};
2234
zhanyong.wan33605ba2010-04-22 23:37:47 +00002235// Implements Each(element_matcher) for the given argument type Container.
2236// Symmetric to ContainsMatcherImpl.
2237template <typename Container>
2238class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2239 public:
2240 template <typename InnerMatcher>
2241 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2242 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2243
2244 // Describes what this matcher does.
2245 virtual void DescribeTo(::std::ostream* os) const {
2246 *os << "only contains elements that ";
2247 this->inner_matcher_.DescribeTo(os);
2248 }
2249
2250 virtual void DescribeNegationTo(::std::ostream* os) const {
2251 *os << "contains some element that ";
2252 this->inner_matcher_.DescribeNegationTo(os);
2253 }
2254
2255 virtual bool MatchAndExplain(Container container,
2256 MatchResultListener* listener) const {
2257 return this->MatchAndExplainImpl(true, container, listener);
2258 }
2259
2260 private:
2261 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2262};
2263
zhanyong.wanb8243162009-06-04 05:48:20 +00002264// Implements polymorphic Contains(element_matcher).
2265template <typename M>
2266class ContainsMatcher {
2267 public:
2268 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2269
2270 template <typename Container>
2271 operator Matcher<Container>() const {
2272 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2273 }
2274
2275 private:
2276 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002277
2278 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002279};
2280
zhanyong.wan33605ba2010-04-22 23:37:47 +00002281// Implements polymorphic Each(element_matcher).
2282template <typename M>
2283class EachMatcher {
2284 public:
2285 explicit EachMatcher(M m) : inner_matcher_(m) {}
2286
2287 template <typename Container>
2288 operator Matcher<Container>() const {
2289 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2290 }
2291
2292 private:
2293 const M inner_matcher_;
2294
2295 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2296};
2297
zhanyong.wanb5937da2009-07-16 20:26:41 +00002298// Implements Key(inner_matcher) for the given argument pair type.
2299// Key(inner_matcher) matches an std::pair whose 'first' field matches
2300// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2301// std::map that contains at least one element whose key is >= 5.
2302template <typename PairType>
2303class KeyMatcherImpl : public MatcherInterface<PairType> {
2304 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002305 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002306 typedef typename RawPairType::first_type KeyType;
2307
2308 template <typename InnerMatcher>
2309 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2310 : inner_matcher_(
2311 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2312 }
2313
2314 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002315 virtual bool MatchAndExplain(PairType key_value,
2316 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002317 StringMatchResultListener inner_listener;
2318 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2319 &inner_listener);
2320 const internal::string explanation = inner_listener.str();
2321 if (explanation != "") {
2322 *listener << "whose first field is a value " << explanation;
2323 }
2324 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002325 }
2326
2327 // Describes what this matcher does.
2328 virtual void DescribeTo(::std::ostream* os) const {
2329 *os << "has a key that ";
2330 inner_matcher_.DescribeTo(os);
2331 }
2332
2333 // Describes what the negation of this matcher does.
2334 virtual void DescribeNegationTo(::std::ostream* os) const {
2335 *os << "doesn't have a key that ";
2336 inner_matcher_.DescribeTo(os);
2337 }
2338
zhanyong.wanb5937da2009-07-16 20:26:41 +00002339 private:
2340 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002341
2342 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002343};
2344
2345// Implements polymorphic Key(matcher_for_key).
2346template <typename M>
2347class KeyMatcher {
2348 public:
2349 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2350
2351 template <typename PairType>
2352 operator Matcher<PairType>() const {
2353 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2354 }
2355
2356 private:
2357 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002358
2359 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002360};
2361
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002362// Implements Pair(first_matcher, second_matcher) for the given argument pair
2363// type with its two matchers. See Pair() function below.
2364template <typename PairType>
2365class PairMatcherImpl : public MatcherInterface<PairType> {
2366 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002367 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002368 typedef typename RawPairType::first_type FirstType;
2369 typedef typename RawPairType::second_type SecondType;
2370
2371 template <typename FirstMatcher, typename SecondMatcher>
2372 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2373 : first_matcher_(
2374 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2375 second_matcher_(
2376 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2377 }
2378
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002379 // Describes what this matcher does.
2380 virtual void DescribeTo(::std::ostream* os) const {
2381 *os << "has a first field that ";
2382 first_matcher_.DescribeTo(os);
2383 *os << ", and has a second field that ";
2384 second_matcher_.DescribeTo(os);
2385 }
2386
2387 // Describes what the negation of this matcher does.
2388 virtual void DescribeNegationTo(::std::ostream* os) const {
2389 *os << "has a first field that ";
2390 first_matcher_.DescribeNegationTo(os);
2391 *os << ", or has a second field that ";
2392 second_matcher_.DescribeNegationTo(os);
2393 }
2394
zhanyong.wan82113312010-01-08 21:55:40 +00002395 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2396 // matches second_matcher.
2397 virtual bool MatchAndExplain(PairType a_pair,
2398 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002399 if (!listener->IsInterested()) {
2400 // If the listener is not interested, we don't need to construct the
2401 // explanation.
2402 return first_matcher_.Matches(a_pair.first) &&
2403 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00002404 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002405 StringMatchResultListener first_inner_listener;
2406 if (!first_matcher_.MatchAndExplain(a_pair.first,
2407 &first_inner_listener)) {
2408 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002409 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002410 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002411 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002412 StringMatchResultListener second_inner_listener;
2413 if (!second_matcher_.MatchAndExplain(a_pair.second,
2414 &second_inner_listener)) {
2415 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002416 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002417 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002418 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002419 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
2420 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00002421 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002422 }
2423
2424 private:
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002425 void ExplainSuccess(const internal::string& first_explanation,
2426 const internal::string& second_explanation,
2427 MatchResultListener* listener) const {
2428 *listener << "whose both fields match";
2429 if (first_explanation != "") {
2430 *listener << ", where the first field is a value " << first_explanation;
2431 }
2432 if (second_explanation != "") {
2433 *listener << ", ";
2434 if (first_explanation != "") {
2435 *listener << "and ";
2436 } else {
2437 *listener << "where ";
2438 }
2439 *listener << "the second field is a value " << second_explanation;
2440 }
2441 }
2442
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002443 const Matcher<const FirstType&> first_matcher_;
2444 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002445
2446 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002447};
2448
2449// Implements polymorphic Pair(first_matcher, second_matcher).
2450template <typename FirstMatcher, typename SecondMatcher>
2451class PairMatcher {
2452 public:
2453 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2454 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2455
2456 template <typename PairType>
2457 operator Matcher<PairType> () const {
2458 return MakeMatcher(
2459 new PairMatcherImpl<PairType>(
2460 first_matcher_, second_matcher_));
2461 }
2462
2463 private:
2464 const FirstMatcher first_matcher_;
2465 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002466
2467 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002468};
2469
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002470// Implements ElementsAre() and ElementsAreArray().
2471template <typename Container>
2472class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2473 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002474 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002475 typedef internal::StlContainerView<RawContainer> View;
2476 typedef typename View::type StlContainer;
2477 typedef typename View::const_reference StlContainerReference;
2478 typedef typename StlContainer::value_type Element;
2479
2480 // Constructs the matcher from a sequence of element values or
2481 // element matchers.
2482 template <typename InputIter>
zhanyong.wan32de5f52009-12-23 00:13:23 +00002483 ElementsAreMatcherImpl(InputIter first, size_t a_count) {
2484 matchers_.reserve(a_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002485 InputIter it = first;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002486 for (size_t i = 0; i != a_count; ++i, ++it) {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002487 matchers_.push_back(MatcherCast<const Element&>(*it));
2488 }
2489 }
2490
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002491 // Describes what this matcher does.
2492 virtual void DescribeTo(::std::ostream* os) const {
2493 if (count() == 0) {
2494 *os << "is empty";
2495 } else if (count() == 1) {
2496 *os << "has 1 element that ";
2497 matchers_[0].DescribeTo(os);
2498 } else {
2499 *os << "has " << Elements(count()) << " where\n";
2500 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002501 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002502 matchers_[i].DescribeTo(os);
2503 if (i + 1 < count()) {
2504 *os << ",\n";
2505 }
2506 }
2507 }
2508 }
2509
2510 // Describes what the negation of this matcher does.
2511 virtual void DescribeNegationTo(::std::ostream* os) const {
2512 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002513 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002514 return;
2515 }
2516
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002517 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002518 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002519 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002520 matchers_[i].DescribeNegationTo(os);
2521 if (i + 1 < count()) {
2522 *os << ", or\n";
2523 }
2524 }
2525 }
2526
zhanyong.wan82113312010-01-08 21:55:40 +00002527 virtual bool MatchAndExplain(Container container,
2528 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002529 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002530 const size_t actual_count = stl_container.size();
2531 if (actual_count != count()) {
2532 // The element count doesn't match. If the container is empty,
2533 // there's no need to explain anything as Google Mock already
2534 // prints the empty container. Otherwise we just need to show
2535 // how many elements there actually are.
2536 if (actual_count != 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002537 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002538 }
zhanyong.wan82113312010-01-08 21:55:40 +00002539 return false;
2540 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002541
zhanyong.wan82113312010-01-08 21:55:40 +00002542 typename StlContainer::const_iterator it = stl_container.begin();
2543 // explanations[i] is the explanation of the element at index i.
2544 std::vector<internal::string> explanations(count());
2545 for (size_t i = 0; i != count(); ++it, ++i) {
2546 StringMatchResultListener s;
2547 if (matchers_[i].MatchAndExplain(*it, &s)) {
2548 explanations[i] = s.str();
2549 } else {
2550 // The container has the right size but the i-th element
2551 // doesn't match its expectation.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002552 *listener << "whose element #" << i << " doesn't match";
2553 PrintIfNotEmpty(s.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002554 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002555 }
2556 }
zhanyong.wan82113312010-01-08 21:55:40 +00002557
2558 // Every element matches its expectation. We need to explain why
2559 // (the obvious ones can be skipped).
zhanyong.wan82113312010-01-08 21:55:40 +00002560 bool reason_printed = false;
2561 for (size_t i = 0; i != count(); ++i) {
2562 const internal::string& s = explanations[i];
2563 if (!s.empty()) {
2564 if (reason_printed) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002565 *listener << ",\nand ";
zhanyong.wan82113312010-01-08 21:55:40 +00002566 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002567 *listener << "whose element #" << i << " matches, " << s;
zhanyong.wan82113312010-01-08 21:55:40 +00002568 reason_printed = true;
2569 }
2570 }
2571
2572 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002573 }
2574
2575 private:
2576 static Message Elements(size_t count) {
2577 return Message() << count << (count == 1 ? " element" : " elements");
2578 }
2579
2580 size_t count() const { return matchers_.size(); }
2581 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002582
2583 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002584};
2585
2586// Implements ElementsAre() of 0 arguments.
2587class ElementsAreMatcher0 {
2588 public:
2589 ElementsAreMatcher0() {}
2590
2591 template <typename Container>
2592 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002593 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002594 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2595 Element;
2596
2597 const Matcher<const Element&>* const matchers = NULL;
2598 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 0));
2599 }
2600};
2601
2602// Implements ElementsAreArray().
2603template <typename T>
2604class ElementsAreArrayMatcher {
2605 public:
2606 ElementsAreArrayMatcher(const T* first, size_t count) :
2607 first_(first), count_(count) {}
2608
2609 template <typename Container>
2610 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002611 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002612 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2613 Element;
2614
2615 return MakeMatcher(new ElementsAreMatcherImpl<Container>(first_, count_));
2616 }
2617
2618 private:
2619 const T* const first_;
2620 const size_t count_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002621
2622 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002623};
2624
zhanyong.wanb4140802010-06-08 22:53:57 +00002625// Returns the description for a matcher defined using the MATCHER*()
2626// macro where the user-supplied description string is "", if
2627// 'negation' is false; otherwise returns the description of the
2628// negation of the matcher. 'param_values' contains a list of strings
2629// that are the print-out of the matcher's parameters.
vladlosev587c1b32011-05-20 00:42:22 +00002630GTEST_API_ string FormatMatcherDescription(bool negation,
2631 const char* matcher_name,
2632 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002633
shiqiane35fdd92008-12-10 05:08:54 +00002634} // namespace internal
2635
2636// Implements MatcherCast().
2637template <typename T, typename M>
2638inline Matcher<T> MatcherCast(M matcher) {
2639 return internal::MatcherCastImpl<T, M>::Cast(matcher);
2640}
2641
2642// _ is a matcher that matches anything of any type.
2643//
2644// This definition is fine as:
2645//
2646// 1. The C++ standard permits using the name _ in a namespace that
2647// is not the global namespace or ::std.
2648// 2. The AnythingMatcher class has no data member or constructor,
2649// so it's OK to create global variables of this type.
2650// 3. c-style has approved of using _ in this case.
2651const internal::AnythingMatcher _ = {};
2652// Creates a matcher that matches any value of the given type T.
2653template <typename T>
2654inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2655
2656// Creates a matcher that matches any value of the given type T.
2657template <typename T>
2658inline Matcher<T> An() { return A<T>(); }
2659
2660// Creates a polymorphic matcher that matches anything equal to x.
2661// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2662// wouldn't compile.
2663template <typename T>
2664inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2665
2666// Constructs a Matcher<T> from a 'value' of type T. The constructed
2667// matcher matches any value that's equal to 'value'.
2668template <typename T>
2669Matcher<T>::Matcher(T value) { *this = Eq(value); }
2670
2671// Creates a monomorphic matcher that matches anything with type Lhs
2672// and equal to rhs. A user may need to use this instead of Eq(...)
2673// in order to resolve an overloading ambiguity.
2674//
2675// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2676// or Matcher<T>(x), but more readable than the latter.
2677//
2678// We could define similar monomorphic matchers for other comparison
2679// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2680// it yet as those are used much less than Eq() in practice. A user
2681// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2682// for example.
2683template <typename Lhs, typename Rhs>
2684inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2685
2686// Creates a polymorphic matcher that matches anything >= x.
2687template <typename Rhs>
2688inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2689 return internal::GeMatcher<Rhs>(x);
2690}
2691
2692// Creates a polymorphic matcher that matches anything > x.
2693template <typename Rhs>
2694inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2695 return internal::GtMatcher<Rhs>(x);
2696}
2697
2698// Creates a polymorphic matcher that matches anything <= x.
2699template <typename Rhs>
2700inline internal::LeMatcher<Rhs> Le(Rhs x) {
2701 return internal::LeMatcher<Rhs>(x);
2702}
2703
2704// Creates a polymorphic matcher that matches anything < x.
2705template <typename Rhs>
2706inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2707 return internal::LtMatcher<Rhs>(x);
2708}
2709
2710// Creates a polymorphic matcher that matches anything != x.
2711template <typename Rhs>
2712inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2713 return internal::NeMatcher<Rhs>(x);
2714}
2715
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002716// Creates a polymorphic matcher that matches any NULL pointer.
2717inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2718 return MakePolymorphicMatcher(internal::IsNullMatcher());
2719}
2720
shiqiane35fdd92008-12-10 05:08:54 +00002721// Creates a polymorphic matcher that matches any non-NULL pointer.
2722// This is convenient as Not(NULL) doesn't compile (the compiler
2723// thinks that that expression is comparing a pointer with an integer).
2724inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2725 return MakePolymorphicMatcher(internal::NotNullMatcher());
2726}
2727
2728// Creates a polymorphic matcher that matches any argument that
2729// references variable x.
2730template <typename T>
2731inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2732 return internal::RefMatcher<T&>(x);
2733}
2734
2735// Creates a matcher that matches any double argument approximately
2736// equal to rhs, where two NANs are considered unequal.
2737inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2738 return internal::FloatingEqMatcher<double>(rhs, false);
2739}
2740
2741// Creates a matcher that matches any double argument approximately
2742// equal to rhs, including NaN values when rhs is NaN.
2743inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2744 return internal::FloatingEqMatcher<double>(rhs, true);
2745}
2746
2747// Creates a matcher that matches any float argument approximately
2748// equal to rhs, where two NANs are considered unequal.
2749inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2750 return internal::FloatingEqMatcher<float>(rhs, false);
2751}
2752
2753// Creates a matcher that matches any double argument approximately
2754// equal to rhs, including NaN values when rhs is NaN.
2755inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2756 return internal::FloatingEqMatcher<float>(rhs, true);
2757}
2758
2759// Creates a matcher that matches a pointer (raw or smart) that points
2760// to a value that matches inner_matcher.
2761template <typename InnerMatcher>
2762inline internal::PointeeMatcher<InnerMatcher> Pointee(
2763 const InnerMatcher& inner_matcher) {
2764 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2765}
2766
2767// Creates a matcher that matches an object whose given field matches
2768// 'matcher'. For example,
2769// Field(&Foo::number, Ge(5))
2770// matches a Foo object x iff x.number >= 5.
2771template <typename Class, typename FieldType, typename FieldMatcher>
2772inline PolymorphicMatcher<
2773 internal::FieldMatcher<Class, FieldType> > Field(
2774 FieldType Class::*field, const FieldMatcher& matcher) {
2775 return MakePolymorphicMatcher(
2776 internal::FieldMatcher<Class, FieldType>(
2777 field, MatcherCast<const FieldType&>(matcher)));
2778 // The call to MatcherCast() is required for supporting inner
2779 // matchers of compatible types. For example, it allows
2780 // Field(&Foo::bar, m)
2781 // to compile where bar is an int32 and m is a matcher for int64.
2782}
2783
2784// Creates a matcher that matches an object whose given property
2785// matches 'matcher'. For example,
2786// Property(&Foo::str, StartsWith("hi"))
2787// matches a Foo object x iff x.str() starts with "hi".
2788template <typename Class, typename PropertyType, typename PropertyMatcher>
2789inline PolymorphicMatcher<
2790 internal::PropertyMatcher<Class, PropertyType> > Property(
2791 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2792 return MakePolymorphicMatcher(
2793 internal::PropertyMatcher<Class, PropertyType>(
2794 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00002795 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002796 // The call to MatcherCast() is required for supporting inner
2797 // matchers of compatible types. For example, it allows
2798 // Property(&Foo::bar, m)
2799 // to compile where bar() returns an int32 and m is a matcher for int64.
2800}
2801
2802// Creates a matcher that matches an object iff the result of applying
2803// a callable to x matches 'matcher'.
2804// For example,
2805// ResultOf(f, StartsWith("hi"))
2806// matches a Foo object x iff f(x) starts with "hi".
2807// callable parameter can be a function, function pointer, or a functor.
2808// Callable has to satisfy the following conditions:
2809// * It is required to keep no state affecting the results of
2810// the calls on it and make no assumptions about how many calls
2811// will be made. Any state it keeps must be protected from the
2812// concurrent access.
2813// * If it is a function object, it has to define type result_type.
2814// We recommend deriving your functor classes from std::unary_function.
2815template <typename Callable, typename ResultOfMatcher>
2816internal::ResultOfMatcher<Callable> ResultOf(
2817 Callable callable, const ResultOfMatcher& matcher) {
2818 return internal::ResultOfMatcher<Callable>(
2819 callable,
2820 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2821 matcher));
2822 // The call to MatcherCast() is required for supporting inner
2823 // matchers of compatible types. For example, it allows
2824 // ResultOf(Function, m)
2825 // to compile where Function() returns an int32 and m is a matcher for int64.
2826}
2827
2828// String matchers.
2829
2830// Matches a string equal to str.
2831inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2832 StrEq(const internal::string& str) {
2833 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2834 str, true, true));
2835}
2836
2837// Matches a string not equal to str.
2838inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2839 StrNe(const internal::string& str) {
2840 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2841 str, false, true));
2842}
2843
2844// Matches a string equal to str, ignoring case.
2845inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2846 StrCaseEq(const internal::string& str) {
2847 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2848 str, true, false));
2849}
2850
2851// Matches a string not equal to str, ignoring case.
2852inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2853 StrCaseNe(const internal::string& str) {
2854 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2855 str, false, false));
2856}
2857
2858// Creates a matcher that matches any string, std::string, or C string
2859// that contains the given substring.
2860inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2861 HasSubstr(const internal::string& substring) {
2862 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
2863 substring));
2864}
2865
2866// Matches a string that starts with 'prefix' (case-sensitive).
2867inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
2868 StartsWith(const internal::string& prefix) {
2869 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
2870 prefix));
2871}
2872
2873// Matches a string that ends with 'suffix' (case-sensitive).
2874inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
2875 EndsWith(const internal::string& suffix) {
2876 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
2877 suffix));
2878}
2879
shiqiane35fdd92008-12-10 05:08:54 +00002880// Matches a string that fully matches regular expression 'regex'.
2881// The matcher takes ownership of 'regex'.
2882inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2883 const internal::RE* regex) {
2884 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2885}
2886inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2887 const internal::string& regex) {
2888 return MatchesRegex(new internal::RE(regex));
2889}
2890
2891// Matches a string that contains regular expression 'regex'.
2892// The matcher takes ownership of 'regex'.
2893inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2894 const internal::RE* regex) {
2895 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2896}
2897inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2898 const internal::string& regex) {
2899 return ContainsRegex(new internal::RE(regex));
2900}
2901
shiqiane35fdd92008-12-10 05:08:54 +00002902#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2903// Wide string matchers.
2904
2905// Matches a string equal to str.
2906inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2907 StrEq(const internal::wstring& str) {
2908 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2909 str, true, true));
2910}
2911
2912// Matches a string not equal to str.
2913inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2914 StrNe(const internal::wstring& str) {
2915 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2916 str, false, true));
2917}
2918
2919// Matches a string equal to str, ignoring case.
2920inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2921 StrCaseEq(const internal::wstring& str) {
2922 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2923 str, true, false));
2924}
2925
2926// Matches a string not equal to str, ignoring case.
2927inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2928 StrCaseNe(const internal::wstring& str) {
2929 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2930 str, false, false));
2931}
2932
2933// Creates a matcher that matches any wstring, std::wstring, or C wide string
2934// that contains the given substring.
2935inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2936 HasSubstr(const internal::wstring& substring) {
2937 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2938 substring));
2939}
2940
2941// Matches a string that starts with 'prefix' (case-sensitive).
2942inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2943 StartsWith(const internal::wstring& prefix) {
2944 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2945 prefix));
2946}
2947
2948// Matches a string that ends with 'suffix' (case-sensitive).
2949inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2950 EndsWith(const internal::wstring& suffix) {
2951 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2952 suffix));
2953}
2954
2955#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2956
2957// Creates a polymorphic matcher that matches a 2-tuple where the
2958// first field == the second field.
2959inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2960
2961// Creates a polymorphic matcher that matches a 2-tuple where the
2962// first field >= the second field.
2963inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2964
2965// Creates a polymorphic matcher that matches a 2-tuple where the
2966// first field > the second field.
2967inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2968
2969// Creates a polymorphic matcher that matches a 2-tuple where the
2970// first field <= the second field.
2971inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2972
2973// Creates a polymorphic matcher that matches a 2-tuple where the
2974// first field < the second field.
2975inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2976
2977// Creates a polymorphic matcher that matches a 2-tuple where the
2978// first field != the second field.
2979inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2980
2981// Creates a matcher that matches any value of type T that m doesn't
2982// match.
2983template <typename InnerMatcher>
2984inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2985 return internal::NotMatcher<InnerMatcher>(m);
2986}
2987
shiqiane35fdd92008-12-10 05:08:54 +00002988// Returns a matcher that matches anything that satisfies the given
2989// predicate. The predicate can be any unary function or functor
2990// whose return type can be implicitly converted to bool.
2991template <typename Predicate>
2992inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
2993Truly(Predicate pred) {
2994 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
2995}
2996
zhanyong.wan6a896b52009-01-16 01:13:50 +00002997// Returns a matcher that matches an equal container.
2998// This matcher behaves like Eq(), but in the event of mismatch lists the
2999// values that are included in one container but not the other. (Duplicate
3000// values and order differences are not explained.)
3001template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00003002inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00003003 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00003004 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00003005 // This following line is for working around a bug in MSVC 8.0,
3006 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00003007 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00003008 return MakePolymorphicMatcher(
3009 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00003010}
3011
zhanyong.wan898725c2011-09-16 16:45:39 +00003012// Returns a matcher that matches a container that, when sorted using
3013// the given comparator, matches container_matcher.
3014template <typename Comparator, typename ContainerMatcher>
3015inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
3016WhenSortedBy(const Comparator& comparator,
3017 const ContainerMatcher& container_matcher) {
3018 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
3019 comparator, container_matcher);
3020}
3021
3022// Returns a matcher that matches a container that, when sorted using
3023// the < operator, matches container_matcher.
3024template <typename ContainerMatcher>
3025inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
3026WhenSorted(const ContainerMatcher& container_matcher) {
3027 return
3028 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
3029 internal::LessComparator(), container_matcher);
3030}
3031
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003032// Matches an STL-style container or a native array that contains the
3033// same number of elements as in rhs, where its i-th element and rhs's
3034// i-th element (as a pair) satisfy the given pair matcher, for all i.
3035// TupleMatcher must be able to be safely cast to Matcher<tuple<const
3036// T1&, const T2&> >, where T1 and T2 are the types of elements in the
3037// LHS container and the RHS container respectively.
3038template <typename TupleMatcher, typename Container>
3039inline internal::PointwiseMatcher<TupleMatcher,
3040 GTEST_REMOVE_CONST_(Container)>
3041Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
3042 // This following line is for working around a bug in MSVC 8.0,
3043 // which causes Container to be a const type sometimes.
3044 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
3045 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
3046 tuple_matcher, rhs);
3047}
3048
zhanyong.wanb8243162009-06-04 05:48:20 +00003049// Matches an STL-style container or a native array that contains at
3050// least one element matching the given value or matcher.
3051//
3052// Examples:
3053// ::std::set<int> page_ids;
3054// page_ids.insert(3);
3055// page_ids.insert(1);
3056// EXPECT_THAT(page_ids, Contains(1));
3057// EXPECT_THAT(page_ids, Contains(Gt(2)));
3058// EXPECT_THAT(page_ids, Not(Contains(4)));
3059//
3060// ::std::map<int, size_t> page_lengths;
3061// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00003062// EXPECT_THAT(page_lengths,
3063// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00003064//
3065// const char* user_ids[] = { "joe", "mike", "tom" };
3066// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
3067template <typename M>
3068inline internal::ContainsMatcher<M> Contains(M matcher) {
3069 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00003070}
3071
zhanyong.wan33605ba2010-04-22 23:37:47 +00003072// Matches an STL-style container or a native array that contains only
3073// elements matching the given value or matcher.
3074//
3075// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
3076// the messages are different.
3077//
3078// Examples:
3079// ::std::set<int> page_ids;
3080// // Each(m) matches an empty container, regardless of what m is.
3081// EXPECT_THAT(page_ids, Each(Eq(1)));
3082// EXPECT_THAT(page_ids, Each(Eq(77)));
3083//
3084// page_ids.insert(3);
3085// EXPECT_THAT(page_ids, Each(Gt(0)));
3086// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
3087// page_ids.insert(1);
3088// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
3089//
3090// ::std::map<int, size_t> page_lengths;
3091// page_lengths[1] = 100;
3092// page_lengths[2] = 200;
3093// page_lengths[3] = 300;
3094// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
3095// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
3096//
3097// const char* user_ids[] = { "joe", "mike", "tom" };
3098// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
3099template <typename M>
3100inline internal::EachMatcher<M> Each(M matcher) {
3101 return internal::EachMatcher<M>(matcher);
3102}
3103
zhanyong.wanb5937da2009-07-16 20:26:41 +00003104// Key(inner_matcher) matches an std::pair whose 'first' field matches
3105// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3106// std::map that contains at least one element whose key is >= 5.
3107template <typename M>
3108inline internal::KeyMatcher<M> Key(M inner_matcher) {
3109 return internal::KeyMatcher<M>(inner_matcher);
3110}
3111
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003112// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
3113// matches first_matcher and whose 'second' field matches second_matcher. For
3114// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
3115// to match a std::map<int, string> that contains exactly one element whose key
3116// is >= 5 and whose value equals "foo".
3117template <typename FirstMatcher, typename SecondMatcher>
3118inline internal::PairMatcher<FirstMatcher, SecondMatcher>
3119Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
3120 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
3121 first_matcher, second_matcher);
3122}
3123
shiqiane35fdd92008-12-10 05:08:54 +00003124// Returns a predicate that is satisfied by anything that matches the
3125// given matcher.
3126template <typename M>
3127inline internal::MatcherAsPredicate<M> Matches(M matcher) {
3128 return internal::MatcherAsPredicate<M>(matcher);
3129}
3130
zhanyong.wanb8243162009-06-04 05:48:20 +00003131// Returns true iff the value matches the matcher.
3132template <typename T, typename M>
3133inline bool Value(const T& value, M matcher) {
3134 return testing::Matches(matcher)(value);
3135}
3136
zhanyong.wan34b034c2010-03-05 21:23:23 +00003137// Matches the value against the given matcher and explains the match
3138// result to listener.
3139template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00003140inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00003141 M matcher, const T& value, MatchResultListener* listener) {
3142 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
3143}
3144
zhanyong.wanbf550852009-06-09 06:09:53 +00003145// AllArgs(m) is a synonym of m. This is useful in
3146//
3147// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
3148//
3149// which is easier to read than
3150//
3151// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
3152template <typename InnerMatcher>
3153inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
3154
shiqiane35fdd92008-12-10 05:08:54 +00003155// These macros allow using matchers to check values in Google Test
3156// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
3157// succeed iff the value matches the matcher. If the assertion fails,
3158// the value and the description of the matcher will be printed.
3159#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
3160 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3161#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
3162 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3163
3164} // namespace testing
3165
3166#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_