blob: 751574ca2574b59525fbd55b778473d4497ec0b6 [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
jgm79a367e2012-04-10 16:02:11 +0000387// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
388// and MUST NOT BE USED IN USER CODE!!!
389namespace internal {
390
391// The MatcherCastImpl class template is a helper for implementing
392// MatcherCast(). We need this helper in order to partially
393// specialize the implementation of MatcherCast() (C++ allows
394// class/struct templates to be partially specialized, but not
395// function templates.).
396
397// This general version is used when MatcherCast()'s argument is a
398// polymorphic matcher (i.e. something that can be converted to a
399// Matcher but is not one yet; for example, Eq(value)) or a value (for
400// example, "hello").
401template <typename T, typename M>
402class MatcherCastImpl {
403 public:
404 static Matcher<T> Cast(M polymorphic_matcher_or_value) {
405 // M can be a polymorhic matcher, in which case we want to use
406 // its conversion operator to create Matcher<T>. Or it can be a value
407 // that should be passed to the Matcher<T>'s constructor.
408 //
409 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
410 // polymorphic matcher because it'll be ambiguous if T has an implicit
411 // constructor from M (this usually happens when T has an implicit
412 // constructor from any type).
413 //
414 // It won't work to unconditionally implict_cast
415 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
416 // a user-defined conversion from M to T if one exists (assuming M is
417 // a value).
418 return CastImpl(
419 polymorphic_matcher_or_value,
420 BooleanConstant<
421 internal::ImplicitlyConvertible<M, Matcher<T> >::value>());
422 }
423
424 private:
425 static Matcher<T> CastImpl(M value, BooleanConstant<false>) {
426 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
427 // matcher. It must be a value then. Use direct initialization to create
428 // a matcher.
429 return Matcher<T>(ImplicitCast_<T>(value));
430 }
431
432 static Matcher<T> CastImpl(M polymorphic_matcher_or_value,
433 BooleanConstant<true>) {
434 // M is implicitly convertible to Matcher<T>, which means that either
435 // M is a polymorhpic matcher or Matcher<T> has an implicit constructor
436 // from M. In both cases using the implicit conversion will produce a
437 // matcher.
438 //
439 // Even if T has an implicit constructor from M, it won't be called because
440 // creating Matcher<T> would require a chain of two user-defined conversions
441 // (first to create T from M and then to create Matcher<T> from T).
442 return polymorphic_matcher_or_value;
443 }
444};
445
446// This more specialized version is used when MatcherCast()'s argument
447// is already a Matcher. This only compiles when type T can be
448// statically converted to type U.
449template <typename T, typename U>
450class MatcherCastImpl<T, Matcher<U> > {
451 public:
452 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
453 return Matcher<T>(new Impl(source_matcher));
454 }
455
456 private:
457 class Impl : public MatcherInterface<T> {
458 public:
459 explicit Impl(const Matcher<U>& source_matcher)
460 : source_matcher_(source_matcher) {}
461
462 // We delegate the matching logic to the source matcher.
463 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
464 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
465 }
466
467 virtual void DescribeTo(::std::ostream* os) const {
468 source_matcher_.DescribeTo(os);
469 }
470
471 virtual void DescribeNegationTo(::std::ostream* os) const {
472 source_matcher_.DescribeNegationTo(os);
473 }
474
475 private:
476 const Matcher<U> source_matcher_;
477
478 GTEST_DISALLOW_ASSIGN_(Impl);
479 };
480};
481
482// This even more specialized version is used for efficiently casting
483// a matcher to its own type.
484template <typename T>
485class MatcherCastImpl<T, Matcher<T> > {
486 public:
487 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
488};
489
490} // namespace internal
491
shiqiane35fdd92008-12-10 05:08:54 +0000492// In order to be safe and clear, casting between different matcher
493// types is done explicitly via MatcherCast<T>(m), which takes a
494// matcher m and returns a Matcher<T>. It compiles only when T can be
495// statically converted to the argument type of m.
496template <typename T, typename M>
jgm79a367e2012-04-10 16:02:11 +0000497inline Matcher<T> MatcherCast(M matcher) {
498 return internal::MatcherCastImpl<T, M>::Cast(matcher);
499}
shiqiane35fdd92008-12-10 05:08:54 +0000500
zhanyong.wan18490652009-05-11 18:54:08 +0000501// Implements SafeMatcherCast().
502//
zhanyong.wan95b12332009-09-25 18:55:50 +0000503// We use an intermediate class to do the actual safe casting as Nokia's
504// Symbian compiler cannot decide between
505// template <T, M> ... (M) and
506// template <T, U> ... (const Matcher<U>&)
507// for function templates but can for member function templates.
508template <typename T>
509class SafeMatcherCastImpl {
510 public:
jgm79a367e2012-04-10 16:02:11 +0000511 // This overload handles polymorphic matchers and values only since
512 // monomorphic matchers are handled by the next one.
zhanyong.wan95b12332009-09-25 18:55:50 +0000513 template <typename M>
jgm79a367e2012-04-10 16:02:11 +0000514 static inline Matcher<T> Cast(M polymorphic_matcher_or_value) {
515 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
zhanyong.wan95b12332009-09-25 18:55:50 +0000516 }
zhanyong.wan18490652009-05-11 18:54:08 +0000517
zhanyong.wan95b12332009-09-25 18:55:50 +0000518 // This overload handles monomorphic matchers.
519 //
520 // In general, if type T can be implicitly converted to type U, we can
521 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
522 // contravariant): just keep a copy of the original Matcher<U>, convert the
523 // argument from type T to U, and then pass it to the underlying Matcher<U>.
524 // The only exception is when U is a reference and T is not, as the
525 // underlying Matcher<U> may be interested in the argument's address, which
526 // is not preserved in the conversion from T to U.
527 template <typename U>
528 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
529 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000530 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000531 T_must_be_implicitly_convertible_to_U);
532 // Enforce that we are not converting a non-reference type T to a reference
533 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000534 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000535 internal::is_reference<T>::value || !internal::is_reference<U>::value,
536 cannot_convert_non_referentce_arg_to_reference);
537 // In case both T and U are arithmetic types, enforce that the
538 // conversion is not lossy.
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000539 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
540 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000541 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
542 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000543 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000544 kTIsOther || kUIsOther ||
545 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
546 conversion_of_arithmetic_types_must_be_lossless);
547 return MatcherCast<T>(matcher);
548 }
549};
550
551template <typename T, typename M>
552inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
553 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000554}
555
shiqiane35fdd92008-12-10 05:08:54 +0000556// A<T>() returns a matcher that matches any value of type T.
557template <typename T>
558Matcher<T> A();
559
560// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
561// and MUST NOT BE USED IN USER CODE!!!
562namespace internal {
563
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000564// If the explanation is not empty, prints it to the ostream.
565inline void PrintIfNotEmpty(const internal::string& explanation,
566 std::ostream* os) {
567 if (explanation != "" && os != NULL) {
568 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000569 }
570}
571
zhanyong.wan736baa82010-09-27 17:44:16 +0000572// Returns true if the given type name is easy to read by a human.
573// This is used to decide whether printing the type of a value might
574// be helpful.
575inline bool IsReadableTypeName(const string& type_name) {
576 // We consider a type name readable if it's short or doesn't contain
577 // a template or function type.
578 return (type_name.length() <= 20 ||
579 type_name.find_first_of("<(") == string::npos);
580}
581
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000582// Matches the value against the given matcher, prints the value and explains
583// the match result to the listener. Returns the match result.
584// 'listener' must not be NULL.
585// Value cannot be passed by const reference, because some matchers take a
586// non-const argument.
587template <typename Value, typename T>
588bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
589 MatchResultListener* listener) {
590 if (!listener->IsInterested()) {
591 // If the listener is not interested, we do not need to construct the
592 // inner explanation.
593 return matcher.Matches(value);
594 }
595
596 StringMatchResultListener inner_listener;
597 const bool match = matcher.MatchAndExplain(value, &inner_listener);
598
599 UniversalPrint(value, listener->stream());
zhanyong.wan736baa82010-09-27 17:44:16 +0000600#if GTEST_HAS_RTTI
601 const string& type_name = GetTypeName<Value>();
602 if (IsReadableTypeName(type_name))
603 *listener->stream() << " (of type " << type_name << ")";
604#endif
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000605 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000606
607 return match;
608}
609
shiqiane35fdd92008-12-10 05:08:54 +0000610// An internal helper class for doing compile-time loop on a tuple's
611// fields.
612template <size_t N>
613class TuplePrefix {
614 public:
615 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
616 // iff the first N fields of matcher_tuple matches the first N
617 // fields of value_tuple, respectively.
618 template <typename MatcherTuple, typename ValueTuple>
619 static bool Matches(const MatcherTuple& matcher_tuple,
620 const ValueTuple& value_tuple) {
621 using ::std::tr1::get;
622 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
623 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
624 }
625
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000626 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000627 // describes failures in matching the first N fields of matchers
628 // against the first N fields of values. If there is no failure,
629 // nothing will be streamed to os.
630 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000631 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
632 const ValueTuple& values,
633 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000634 using ::std::tr1::tuple_element;
635 using ::std::tr1::get;
636
637 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000638 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000639
640 // Then describes the failure (if any) in the (N - 1)-th (0-based)
641 // field.
642 typename tuple_element<N - 1, MatcherTuple>::type matcher =
643 get<N - 1>(matchers);
644 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
645 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000646 StringMatchResultListener listener;
647 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000648 // TODO(wan): include in the message the name of the parameter
649 // as used in MOCK_METHOD*() when possible.
650 *os << " Expected arg #" << N - 1 << ": ";
651 get<N - 1>(matchers).DescribeTo(os);
652 *os << "\n Actual: ";
653 // We remove the reference in type Value to prevent the
654 // universal printer from printing the address of value, which
655 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000656 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000657 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000658 internal::UniversalPrint(value, os);
659 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000660 *os << "\n";
661 }
662 }
663};
664
665// The base case.
666template <>
667class TuplePrefix<0> {
668 public:
669 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000670 static bool Matches(const MatcherTuple& /* matcher_tuple */,
671 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000672 return true;
673 }
674
675 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000676 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
677 const ValueTuple& /* values */,
678 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000679};
680
681// TupleMatches(matcher_tuple, value_tuple) returns true iff all
682// matchers in matcher_tuple match the corresponding fields in
683// value_tuple. It is a compiler error if matcher_tuple and
684// value_tuple have different number of fields or incompatible field
685// types.
686template <typename MatcherTuple, typename ValueTuple>
687bool TupleMatches(const MatcherTuple& matcher_tuple,
688 const ValueTuple& value_tuple) {
689 using ::std::tr1::tuple_size;
690 // Makes sure that matcher_tuple and value_tuple have the same
691 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000692 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000693 tuple_size<ValueTuple>::value,
694 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000695 return TuplePrefix<tuple_size<ValueTuple>::value>::
696 Matches(matcher_tuple, value_tuple);
697}
698
699// Describes failures in matching matchers against values. If there
700// is no failure, nothing will be streamed to os.
701template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000702void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
703 const ValueTuple& values,
704 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000705 using ::std::tr1::tuple_size;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000706 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000707 matchers, values, os);
708}
709
shiqiane35fdd92008-12-10 05:08:54 +0000710// Implements A<T>().
711template <typename T>
712class AnyMatcherImpl : public MatcherInterface<T> {
713 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000714 virtual bool MatchAndExplain(
715 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000716 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
717 virtual void DescribeNegationTo(::std::ostream* os) const {
718 // This is mostly for completeness' safe, as it's not very useful
719 // to write Not(A<bool>()). However we cannot completely rule out
720 // such a possibility, and it doesn't hurt to be prepared.
721 *os << "never matches";
722 }
723};
724
725// Implements _, a matcher that matches any value of any
726// type. This is a polymorphic matcher, so we need a template type
727// conversion operator to make it appearing as a Matcher<T> for any
728// type T.
729class AnythingMatcher {
730 public:
731 template <typename T>
732 operator Matcher<T>() const { return A<T>(); }
733};
734
735// Implements a matcher that compares a given value with a
736// pre-supplied value using one of the ==, <=, <, etc, operators. The
737// two values being compared don't have to have the same type.
738//
739// The matcher defined here is polymorphic (for example, Eq(5) can be
740// used to match an int, a short, a double, etc). Therefore we use
741// a template type conversion operator in the implementation.
742//
743// We define this as a macro in order to eliminate duplicated source
744// code.
745//
746// The following template definition assumes that the Rhs parameter is
747// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000748#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_( \
749 name, op, relation, negated_relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000750 template <typename Rhs> class name##Matcher { \
751 public: \
752 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
753 template <typename Lhs> \
754 operator Matcher<Lhs>() const { \
755 return MakeMatcher(new Impl<Lhs>(rhs_)); \
756 } \
757 private: \
758 template <typename Lhs> \
759 class Impl : public MatcherInterface<Lhs> { \
760 public: \
761 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
zhanyong.wan82113312010-01-08 21:55:40 +0000762 virtual bool MatchAndExplain(\
763 Lhs lhs, MatchResultListener* /* listener */) const { \
764 return lhs op rhs_; \
765 } \
shiqiane35fdd92008-12-10 05:08:54 +0000766 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000767 *os << relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000768 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000769 } \
770 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000771 *os << negated_relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000772 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000773 } \
774 private: \
775 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000776 GTEST_DISALLOW_ASSIGN_(Impl); \
shiqiane35fdd92008-12-10 05:08:54 +0000777 }; \
778 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000779 GTEST_DISALLOW_ASSIGN_(name##Matcher); \
shiqiane35fdd92008-12-10 05:08:54 +0000780 }
781
782// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
783// respectively.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000784GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "is equal to", "isn't equal to");
785GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "is >=", "isn't >=");
786GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "is >", "isn't >");
787GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "is <=", "isn't <=");
788GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "is <", "isn't <");
789GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "isn't equal to", "is equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000790
zhanyong.wane0d051e2009-02-19 00:33:37 +0000791#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000792
vladlosev79b83502009-11-18 00:43:37 +0000793// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000794// pointer that is NULL.
795class IsNullMatcher {
796 public:
vladlosev79b83502009-11-18 00:43:37 +0000797 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000798 bool MatchAndExplain(const Pointer& p,
799 MatchResultListener* /* listener */) const {
800 return GetRawPointer(p) == NULL;
801 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000802
803 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
804 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000805 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000806 }
807};
808
vladlosev79b83502009-11-18 00:43:37 +0000809// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000810// pointer that is not NULL.
811class NotNullMatcher {
812 public:
vladlosev79b83502009-11-18 00:43:37 +0000813 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000814 bool MatchAndExplain(const Pointer& p,
815 MatchResultListener* /* listener */) const {
816 return GetRawPointer(p) != NULL;
817 }
shiqiane35fdd92008-12-10 05:08:54 +0000818
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000819 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +0000820 void DescribeNegationTo(::std::ostream* os) const {
821 *os << "is NULL";
822 }
823};
824
825// Ref(variable) matches any argument that is a reference to
826// 'variable'. This matcher is polymorphic as it can match any
827// super type of the type of 'variable'.
828//
829// The RefMatcher template class implements Ref(variable). It can
830// only be instantiated with a reference type. This prevents a user
831// from mistakenly using Ref(x) to match a non-reference function
832// argument. For example, the following will righteously cause a
833// compiler error:
834//
835// int n;
836// Matcher<int> m1 = Ref(n); // This won't compile.
837// Matcher<int&> m2 = Ref(n); // This will compile.
838template <typename T>
839class RefMatcher;
840
841template <typename T>
842class RefMatcher<T&> {
843 // Google Mock is a generic framework and thus needs to support
844 // mocking any function types, including those that take non-const
845 // reference arguments. Therefore the template parameter T (and
846 // Super below) can be instantiated to either a const type or a
847 // non-const type.
848 public:
849 // RefMatcher() takes a T& instead of const T&, as we want the
850 // compiler to catch using Ref(const_value) as a matcher for a
851 // non-const reference.
852 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
853
854 template <typename Super>
855 operator Matcher<Super&>() const {
856 // By passing object_ (type T&) to Impl(), which expects a Super&,
857 // we make sure that Super is a super type of T. In particular,
858 // this catches using Ref(const_value) as a matcher for a
859 // non-const reference, as you cannot implicitly convert a const
860 // reference to a non-const reference.
861 return MakeMatcher(new Impl<Super>(object_));
862 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000863
shiqiane35fdd92008-12-10 05:08:54 +0000864 private:
865 template <typename Super>
866 class Impl : public MatcherInterface<Super&> {
867 public:
868 explicit Impl(Super& x) : object_(x) {} // NOLINT
869
zhanyong.wandb22c222010-01-28 21:52:29 +0000870 // MatchAndExplain() takes a Super& (as opposed to const Super&)
871 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +0000872 virtual bool MatchAndExplain(
873 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000874 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +0000875 return &x == &object_;
876 }
shiqiane35fdd92008-12-10 05:08:54 +0000877
878 virtual void DescribeTo(::std::ostream* os) const {
879 *os << "references the variable ";
880 UniversalPrinter<Super&>::Print(object_, os);
881 }
882
883 virtual void DescribeNegationTo(::std::ostream* os) const {
884 *os << "does not reference the variable ";
885 UniversalPrinter<Super&>::Print(object_, os);
886 }
887
shiqiane35fdd92008-12-10 05:08:54 +0000888 private:
889 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000890
891 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000892 };
893
894 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000895
896 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000897};
898
899// Polymorphic helper functions for narrow and wide string matchers.
900inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
901 return String::CaseInsensitiveCStringEquals(lhs, rhs);
902}
903
904inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
905 const wchar_t* rhs) {
906 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
907}
908
909// String comparison for narrow or wide strings that can have embedded NUL
910// characters.
911template <typename StringType>
912bool CaseInsensitiveStringEquals(const StringType& s1,
913 const StringType& s2) {
914 // Are the heads equal?
915 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
916 return false;
917 }
918
919 // Skip the equal heads.
920 const typename StringType::value_type nul = 0;
921 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
922
923 // Are we at the end of either s1 or s2?
924 if (i1 == StringType::npos || i2 == StringType::npos) {
925 return i1 == i2;
926 }
927
928 // Are the tails equal?
929 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
930}
931
932// String matchers.
933
934// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
935template <typename StringType>
936class StrEqualityMatcher {
937 public:
shiqiane35fdd92008-12-10 05:08:54 +0000938 StrEqualityMatcher(const StringType& str, bool expect_eq,
939 bool case_sensitive)
940 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
941
jgm38513a82012-11-15 15:50:36 +0000942 // Accepts pointer types, particularly:
943 // const char*
944 // char*
945 // const wchar_t*
946 // wchar_t*
947 template <typename CharType>
948 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +0000949 if (s == NULL) {
950 return !expect_eq_;
951 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000952 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000953 }
954
jgm38513a82012-11-15 15:50:36 +0000955 // Matches anything that can convert to StringType.
956 //
957 // This is a template, not just a plain function with const StringType&,
958 // because StringPiece has some interfering non-explicit constructors.
959 template <typename MatcheeStringType>
960 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +0000961 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +0000962 const StringType& s2(s);
963 const bool eq = case_sensitive_ ? s2 == string_ :
964 CaseInsensitiveStringEquals(s2, string_);
shiqiane35fdd92008-12-10 05:08:54 +0000965 return expect_eq_ == eq;
966 }
967
968 void DescribeTo(::std::ostream* os) const {
969 DescribeToHelper(expect_eq_, os);
970 }
971
972 void DescribeNegationTo(::std::ostream* os) const {
973 DescribeToHelper(!expect_eq_, os);
974 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000975
shiqiane35fdd92008-12-10 05:08:54 +0000976 private:
977 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000978 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +0000979 *os << "equal to ";
980 if (!case_sensitive_) {
981 *os << "(ignoring case) ";
982 }
vladloseve2e8ba42010-05-13 18:16:03 +0000983 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +0000984 }
985
986 const StringType string_;
987 const bool expect_eq_;
988 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000989
990 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000991};
992
993// Implements the polymorphic HasSubstr(substring) matcher, which
994// can be used as a Matcher<T> as long as T can be converted to a
995// string.
996template <typename StringType>
997class HasSubstrMatcher {
998 public:
shiqiane35fdd92008-12-10 05:08:54 +0000999 explicit HasSubstrMatcher(const StringType& substring)
1000 : substring_(substring) {}
1001
jgm38513a82012-11-15 15:50:36 +00001002 // Accepts pointer types, particularly:
1003 // const char*
1004 // char*
1005 // const wchar_t*
1006 // wchar_t*
1007 template <typename CharType>
1008 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001009 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001010 }
1011
jgm38513a82012-11-15 15:50:36 +00001012 // Matches anything that can convert to StringType.
1013 //
1014 // This is a template, not just a plain function with const StringType&,
1015 // because StringPiece has some interfering non-explicit constructors.
1016 template <typename MatcheeStringType>
1017 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001018 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001019 const StringType& s2(s);
1020 return s2.find(substring_) != StringType::npos;
shiqiane35fdd92008-12-10 05:08:54 +00001021 }
1022
1023 // Describes what this matcher matches.
1024 void DescribeTo(::std::ostream* os) const {
1025 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001026 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001027 }
1028
1029 void DescribeNegationTo(::std::ostream* os) const {
1030 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001031 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001032 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001033
shiqiane35fdd92008-12-10 05:08:54 +00001034 private:
1035 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001036
1037 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001038};
1039
1040// Implements the polymorphic StartsWith(substring) matcher, which
1041// can be used as a Matcher<T> as long as T can be converted to a
1042// string.
1043template <typename StringType>
1044class StartsWithMatcher {
1045 public:
shiqiane35fdd92008-12-10 05:08:54 +00001046 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1047 }
1048
jgm38513a82012-11-15 15:50:36 +00001049 // Accepts pointer types, particularly:
1050 // const char*
1051 // char*
1052 // const wchar_t*
1053 // wchar_t*
1054 template <typename CharType>
1055 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001056 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001057 }
1058
jgm38513a82012-11-15 15:50:36 +00001059 // Matches anything that can convert to StringType.
1060 //
1061 // This is a template, not just a plain function with const StringType&,
1062 // because StringPiece has some interfering non-explicit constructors.
1063 template <typename MatcheeStringType>
1064 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001065 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001066 const StringType& s2(s);
1067 return s2.length() >= prefix_.length() &&
1068 s2.substr(0, prefix_.length()) == prefix_;
shiqiane35fdd92008-12-10 05:08:54 +00001069 }
1070
1071 void DescribeTo(::std::ostream* os) const {
1072 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001073 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001074 }
1075
1076 void DescribeNegationTo(::std::ostream* os) const {
1077 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001078 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001079 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001080
shiqiane35fdd92008-12-10 05:08:54 +00001081 private:
1082 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001083
1084 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001085};
1086
1087// Implements the polymorphic EndsWith(substring) matcher, which
1088// can be used as a Matcher<T> as long as T can be converted to a
1089// string.
1090template <typename StringType>
1091class EndsWithMatcher {
1092 public:
shiqiane35fdd92008-12-10 05:08:54 +00001093 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1094
jgm38513a82012-11-15 15:50:36 +00001095 // Accepts pointer types, particularly:
1096 // const char*
1097 // char*
1098 // const wchar_t*
1099 // wchar_t*
1100 template <typename CharType>
1101 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001102 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001103 }
1104
jgm38513a82012-11-15 15:50:36 +00001105 // Matches anything that can convert to StringType.
1106 //
1107 // This is a template, not just a plain function with const StringType&,
1108 // because StringPiece has some interfering non-explicit constructors.
1109 template <typename MatcheeStringType>
1110 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001111 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001112 const StringType& s2(s);
1113 return s2.length() >= suffix_.length() &&
1114 s2.substr(s2.length() - suffix_.length()) == suffix_;
shiqiane35fdd92008-12-10 05:08:54 +00001115 }
1116
1117 void DescribeTo(::std::ostream* os) const {
1118 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001119 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001120 }
1121
1122 void DescribeNegationTo(::std::ostream* os) const {
1123 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001124 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001125 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001126
shiqiane35fdd92008-12-10 05:08:54 +00001127 private:
1128 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001129
1130 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001131};
1132
shiqiane35fdd92008-12-10 05:08:54 +00001133// Implements polymorphic matchers MatchesRegex(regex) and
1134// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1135// T can be converted to a string.
1136class MatchesRegexMatcher {
1137 public:
1138 MatchesRegexMatcher(const RE* regex, bool full_match)
1139 : regex_(regex), full_match_(full_match) {}
1140
jgm38513a82012-11-15 15:50:36 +00001141 // Accepts pointer types, particularly:
1142 // const char*
1143 // char*
1144 // const wchar_t*
1145 // wchar_t*
1146 template <typename CharType>
1147 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001148 return s != NULL && MatchAndExplain(internal::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001149 }
1150
jgm38513a82012-11-15 15:50:36 +00001151 // Matches anything that can convert to internal::string.
1152 //
1153 // This is a template, not just a plain function with const internal::string&,
1154 // because StringPiece has some interfering non-explicit constructors.
1155 template <class MatcheeStringType>
1156 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001157 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001158 const internal::string& s2(s);
1159 return full_match_ ? RE::FullMatch(s2, *regex_) :
1160 RE::PartialMatch(s2, *regex_);
shiqiane35fdd92008-12-10 05:08:54 +00001161 }
1162
1163 void DescribeTo(::std::ostream* os) const {
1164 *os << (full_match_ ? "matches" : "contains")
1165 << " regular expression ";
1166 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1167 }
1168
1169 void DescribeNegationTo(::std::ostream* os) const {
1170 *os << "doesn't " << (full_match_ ? "match" : "contain")
1171 << " regular expression ";
1172 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1173 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001174
shiqiane35fdd92008-12-10 05:08:54 +00001175 private:
1176 const internal::linked_ptr<const RE> regex_;
1177 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001178
1179 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001180};
1181
shiqiane35fdd92008-12-10 05:08:54 +00001182// Implements a matcher that compares the two fields of a 2-tuple
1183// using one of the ==, <=, <, etc, operators. The two fields being
1184// compared don't have to have the same type.
1185//
1186// The matcher defined here is polymorphic (for example, Eq() can be
1187// used to match a tuple<int, short>, a tuple<const long&, double>,
1188// etc). Therefore we use a template type conversion operator in the
1189// implementation.
1190//
1191// We define this as a macro in order to eliminate duplicated source
1192// code.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001193#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +00001194 class name##2Matcher { \
1195 public: \
1196 template <typename T1, typename T2> \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001197 operator Matcher< ::std::tr1::tuple<T1, T2> >() const { \
1198 return MakeMatcher(new Impl< ::std::tr1::tuple<T1, T2> >); \
1199 } \
1200 template <typename T1, typename T2> \
shiqiane35fdd92008-12-10 05:08:54 +00001201 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001202 return MakeMatcher(new Impl<const ::std::tr1::tuple<T1, T2>&>); \
shiqiane35fdd92008-12-10 05:08:54 +00001203 } \
1204 private: \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001205 template <typename Tuple> \
1206 class Impl : public MatcherInterface<Tuple> { \
shiqiane35fdd92008-12-10 05:08:54 +00001207 public: \
zhanyong.wan82113312010-01-08 21:55:40 +00001208 virtual bool MatchAndExplain( \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001209 Tuple args, \
zhanyong.wan82113312010-01-08 21:55:40 +00001210 MatchResultListener* /* listener */) const { \
shiqiane35fdd92008-12-10 05:08:54 +00001211 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
1212 } \
1213 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001214 *os << "are " relation; \
shiqiane35fdd92008-12-10 05:08:54 +00001215 } \
1216 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001217 *os << "aren't " relation; \
shiqiane35fdd92008-12-10 05:08:54 +00001218 } \
1219 }; \
1220 }
1221
1222// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001223GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "an equal pair");
1224GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1225 Ge, >=, "a pair where the first >= the second");
1226GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1227 Gt, >, "a pair where the first > the second");
1228GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1229 Le, <=, "a pair where the first <= the second");
1230GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1231 Lt, <, "a pair where the first < the second");
1232GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=, "an unequal pair");
shiqiane35fdd92008-12-10 05:08:54 +00001233
zhanyong.wane0d051e2009-02-19 00:33:37 +00001234#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +00001235
zhanyong.wanc6a41232009-05-13 23:38:40 +00001236// Implements the Not(...) matcher for a particular argument type T.
1237// We do not nest it inside the NotMatcher class template, as that
1238// will prevent different instantiations of NotMatcher from sharing
1239// the same NotMatcherImpl<T> class.
1240template <typename T>
1241class NotMatcherImpl : public MatcherInterface<T> {
1242 public:
1243 explicit NotMatcherImpl(const Matcher<T>& matcher)
1244 : matcher_(matcher) {}
1245
zhanyong.wan82113312010-01-08 21:55:40 +00001246 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1247 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001248 }
1249
1250 virtual void DescribeTo(::std::ostream* os) const {
1251 matcher_.DescribeNegationTo(os);
1252 }
1253
1254 virtual void DescribeNegationTo(::std::ostream* os) const {
1255 matcher_.DescribeTo(os);
1256 }
1257
zhanyong.wanc6a41232009-05-13 23:38:40 +00001258 private:
1259 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001260
1261 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001262};
1263
shiqiane35fdd92008-12-10 05:08:54 +00001264// Implements the Not(m) matcher, which matches a value that doesn't
1265// match matcher m.
1266template <typename InnerMatcher>
1267class NotMatcher {
1268 public:
1269 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1270
1271 // This template type conversion operator allows Not(m) to be used
1272 // to match any type m can match.
1273 template <typename T>
1274 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001275 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001276 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001277
shiqiane35fdd92008-12-10 05:08:54 +00001278 private:
shiqiane35fdd92008-12-10 05:08:54 +00001279 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001280
1281 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001282};
1283
zhanyong.wanc6a41232009-05-13 23:38:40 +00001284// Implements the AllOf(m1, m2) matcher for a particular argument type
1285// T. We do not nest it inside the BothOfMatcher class template, as
1286// that will prevent different instantiations of BothOfMatcher from
1287// sharing the same BothOfMatcherImpl<T> class.
1288template <typename T>
1289class BothOfMatcherImpl : public MatcherInterface<T> {
1290 public:
1291 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1292 : matcher1_(matcher1), matcher2_(matcher2) {}
1293
zhanyong.wanc6a41232009-05-13 23:38:40 +00001294 virtual void DescribeTo(::std::ostream* os) const {
1295 *os << "(";
1296 matcher1_.DescribeTo(os);
1297 *os << ") and (";
1298 matcher2_.DescribeTo(os);
1299 *os << ")";
1300 }
1301
1302 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001303 *os << "(";
1304 matcher1_.DescribeNegationTo(os);
1305 *os << ") or (";
1306 matcher2_.DescribeNegationTo(os);
1307 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001308 }
1309
zhanyong.wan82113312010-01-08 21:55:40 +00001310 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1311 // If either matcher1_ or matcher2_ doesn't match x, we only need
1312 // to explain why one of them fails.
1313 StringMatchResultListener listener1;
1314 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1315 *listener << listener1.str();
1316 return false;
1317 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001318
zhanyong.wan82113312010-01-08 21:55:40 +00001319 StringMatchResultListener listener2;
1320 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1321 *listener << listener2.str();
1322 return false;
1323 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001324
zhanyong.wan82113312010-01-08 21:55:40 +00001325 // Otherwise we need to explain why *both* of them match.
1326 const internal::string s1 = listener1.str();
1327 const internal::string s2 = listener2.str();
1328
1329 if (s1 == "") {
1330 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001331 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001332 *listener << s1;
1333 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001334 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001335 }
1336 }
zhanyong.wan82113312010-01-08 21:55:40 +00001337 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001338 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001339
zhanyong.wanc6a41232009-05-13 23:38:40 +00001340 private:
1341 const Matcher<T> matcher1_;
1342 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001343
1344 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001345};
1346
shiqiane35fdd92008-12-10 05:08:54 +00001347// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1348// matches a value that matches all of the matchers m_1, ..., and m_n.
1349template <typename Matcher1, typename Matcher2>
1350class BothOfMatcher {
1351 public:
1352 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1353 : matcher1_(matcher1), matcher2_(matcher2) {}
1354
1355 // This template type conversion operator allows a
1356 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1357 // both Matcher1 and Matcher2 can match.
1358 template <typename T>
1359 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001360 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1361 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001362 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001363
shiqiane35fdd92008-12-10 05:08:54 +00001364 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001365 Matcher1 matcher1_;
1366 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001367
1368 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001369};
shiqiane35fdd92008-12-10 05:08:54 +00001370
zhanyong.wanc6a41232009-05-13 23:38:40 +00001371// Implements the AnyOf(m1, m2) matcher for a particular argument type
1372// T. We do not nest it inside the AnyOfMatcher class template, as
1373// that will prevent different instantiations of AnyOfMatcher from
1374// sharing the same EitherOfMatcherImpl<T> class.
1375template <typename T>
1376class EitherOfMatcherImpl : public MatcherInterface<T> {
1377 public:
1378 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1379 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001380
zhanyong.wanc6a41232009-05-13 23:38:40 +00001381 virtual void DescribeTo(::std::ostream* os) const {
1382 *os << "(";
1383 matcher1_.DescribeTo(os);
1384 *os << ") or (";
1385 matcher2_.DescribeTo(os);
1386 *os << ")";
1387 }
shiqiane35fdd92008-12-10 05:08:54 +00001388
zhanyong.wanc6a41232009-05-13 23:38:40 +00001389 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001390 *os << "(";
1391 matcher1_.DescribeNegationTo(os);
1392 *os << ") and (";
1393 matcher2_.DescribeNegationTo(os);
1394 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001395 }
shiqiane35fdd92008-12-10 05:08:54 +00001396
zhanyong.wan82113312010-01-08 21:55:40 +00001397 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1398 // If either matcher1_ or matcher2_ matches x, we just need to
1399 // explain why *one* of them matches.
1400 StringMatchResultListener listener1;
1401 if (matcher1_.MatchAndExplain(x, &listener1)) {
1402 *listener << listener1.str();
1403 return true;
1404 }
1405
1406 StringMatchResultListener listener2;
1407 if (matcher2_.MatchAndExplain(x, &listener2)) {
1408 *listener << listener2.str();
1409 return true;
1410 }
1411
1412 // Otherwise we need to explain why *both* of them fail.
1413 const internal::string s1 = listener1.str();
1414 const internal::string s2 = listener2.str();
1415
1416 if (s1 == "") {
1417 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001418 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001419 *listener << s1;
1420 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001421 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001422 }
1423 }
zhanyong.wan82113312010-01-08 21:55:40 +00001424 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001425 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001426
zhanyong.wanc6a41232009-05-13 23:38:40 +00001427 private:
1428 const Matcher<T> matcher1_;
1429 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001430
1431 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001432};
1433
1434// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1435// matches a value that matches at least one of the matchers m_1, ...,
1436// and m_n.
1437template <typename Matcher1, typename Matcher2>
1438class EitherOfMatcher {
1439 public:
1440 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1441 : matcher1_(matcher1), matcher2_(matcher2) {}
1442
1443 // This template type conversion operator allows a
1444 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1445 // both Matcher1 and Matcher2 can match.
1446 template <typename T>
1447 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001448 return Matcher<T>(new EitherOfMatcherImpl<T>(
1449 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001450 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001451
shiqiane35fdd92008-12-10 05:08:54 +00001452 private:
shiqiane35fdd92008-12-10 05:08:54 +00001453 Matcher1 matcher1_;
1454 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001455
1456 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001457};
1458
1459// Used for implementing Truly(pred), which turns a predicate into a
1460// matcher.
1461template <typename Predicate>
1462class TrulyMatcher {
1463 public:
1464 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1465
1466 // This method template allows Truly(pred) to be used as a matcher
1467 // for type T where T is the argument type of predicate 'pred'. The
1468 // argument is passed by reference as the predicate may be
1469 // interested in the address of the argument.
1470 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001471 bool MatchAndExplain(T& x, // NOLINT
1472 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00001473 // Without the if-statement, MSVC sometimes warns about converting
1474 // a value to bool (warning 4800).
1475 //
1476 // We cannot write 'return !!predicate_(x);' as that doesn't work
1477 // when predicate_(x) returns a class convertible to bool but
1478 // having no operator!().
1479 if (predicate_(x))
1480 return true;
1481 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001482 }
1483
1484 void DescribeTo(::std::ostream* os) const {
1485 *os << "satisfies the given predicate";
1486 }
1487
1488 void DescribeNegationTo(::std::ostream* os) const {
1489 *os << "doesn't satisfy the given predicate";
1490 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001491
shiqiane35fdd92008-12-10 05:08:54 +00001492 private:
1493 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001494
1495 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001496};
1497
1498// Used for implementing Matches(matcher), which turns a matcher into
1499// a predicate.
1500template <typename M>
1501class MatcherAsPredicate {
1502 public:
1503 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1504
1505 // This template operator() allows Matches(m) to be used as a
1506 // predicate on type T where m is a matcher on type T.
1507 //
1508 // The argument x is passed by reference instead of by value, as
1509 // some matcher may be interested in its address (e.g. as in
1510 // Matches(Ref(n))(x)).
1511 template <typename T>
1512 bool operator()(const T& x) const {
1513 // We let matcher_ commit to a particular type here instead of
1514 // when the MatcherAsPredicate object was constructed. This
1515 // allows us to write Matches(m) where m is a polymorphic matcher
1516 // (e.g. Eq(5)).
1517 //
1518 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1519 // compile when matcher_ has type Matcher<const T&>; if we write
1520 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1521 // when matcher_ has type Matcher<T>; if we just write
1522 // matcher_.Matches(x), it won't compile when matcher_ is
1523 // polymorphic, e.g. Eq(5).
1524 //
1525 // MatcherCast<const T&>() is necessary for making the code work
1526 // in all of the above situations.
1527 return MatcherCast<const T&>(matcher_).Matches(x);
1528 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001529
shiqiane35fdd92008-12-10 05:08:54 +00001530 private:
1531 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001532
1533 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001534};
1535
1536// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1537// argument M must be a type that can be converted to a matcher.
1538template <typename M>
1539class PredicateFormatterFromMatcher {
1540 public:
1541 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1542
1543 // This template () operator allows a PredicateFormatterFromMatcher
1544 // object to act as a predicate-formatter suitable for using with
1545 // Google Test's EXPECT_PRED_FORMAT1() macro.
1546 template <typename T>
1547 AssertionResult operator()(const char* value_text, const T& x) const {
1548 // We convert matcher_ to a Matcher<const T&> *now* instead of
1549 // when the PredicateFormatterFromMatcher object was constructed,
1550 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1551 // know which type to instantiate it to until we actually see the
1552 // type of x here.
1553 //
1554 // We write MatcherCast<const T&>(matcher_) instead of
1555 // Matcher<const T&>(matcher_), as the latter won't compile when
1556 // matcher_ has type Matcher<T> (e.g. An<int>()).
1557 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001558 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001559 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001560 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001561
1562 ::std::stringstream ss;
1563 ss << "Value of: " << value_text << "\n"
1564 << "Expected: ";
1565 matcher.DescribeTo(&ss);
1566 ss << "\n Actual: " << listener.str();
1567 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001568 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001569
shiqiane35fdd92008-12-10 05:08:54 +00001570 private:
1571 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001572
1573 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001574};
1575
1576// A helper function for converting a matcher to a predicate-formatter
1577// without the user needing to explicitly write the type. This is
1578// used for implementing ASSERT_THAT() and EXPECT_THAT().
1579template <typename M>
1580inline PredicateFormatterFromMatcher<M>
1581MakePredicateFormatterFromMatcher(const M& matcher) {
1582 return PredicateFormatterFromMatcher<M>(matcher);
1583}
1584
1585// Implements the polymorphic floating point equality matcher, which
1586// matches two float values using ULP-based approximation. The
1587// template is meant to be instantiated with FloatType being either
1588// float or double.
1589template <typename FloatType>
1590class FloatingEqMatcher {
1591 public:
1592 // Constructor for FloatingEqMatcher.
1593 // The matcher's input will be compared with rhs. The matcher treats two
1594 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1595 // equality comparisons between NANs will always return false.
1596 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1597 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1598
1599 // Implements floating point equality matcher as a Matcher<T>.
1600 template <typename T>
1601 class Impl : public MatcherInterface<T> {
1602 public:
1603 Impl(FloatType rhs, bool nan_eq_nan) :
1604 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1605
zhanyong.wan82113312010-01-08 21:55:40 +00001606 virtual bool MatchAndExplain(T value,
1607 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001608 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1609
1610 // Compares NaNs first, if nan_eq_nan_ is true.
1611 if (nan_eq_nan_ && lhs.is_nan()) {
1612 return rhs.is_nan();
1613 }
1614
1615 return lhs.AlmostEquals(rhs);
1616 }
1617
1618 virtual void DescribeTo(::std::ostream* os) const {
1619 // os->precision() returns the previously set precision, which we
1620 // store to restore the ostream to its original configuration
1621 // after outputting.
1622 const ::std::streamsize old_precision = os->precision(
1623 ::std::numeric_limits<FloatType>::digits10 + 2);
1624 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1625 if (nan_eq_nan_) {
1626 *os << "is NaN";
1627 } else {
1628 *os << "never matches";
1629 }
1630 } else {
1631 *os << "is approximately " << rhs_;
1632 }
1633 os->precision(old_precision);
1634 }
1635
1636 virtual void DescribeNegationTo(::std::ostream* os) const {
1637 // As before, get original precision.
1638 const ::std::streamsize old_precision = os->precision(
1639 ::std::numeric_limits<FloatType>::digits10 + 2);
1640 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1641 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001642 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00001643 } else {
1644 *os << "is anything";
1645 }
1646 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001647 *os << "isn't approximately " << rhs_;
shiqiane35fdd92008-12-10 05:08:54 +00001648 }
1649 // Restore original precision.
1650 os->precision(old_precision);
1651 }
1652
1653 private:
1654 const FloatType rhs_;
1655 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001656
1657 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001658 };
1659
1660 // The following 3 type conversion operators allow FloatEq(rhs) and
1661 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1662 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1663 // (While Google's C++ coding style doesn't allow arguments passed
1664 // by non-const reference, we may see them in code not conforming to
1665 // the style. Therefore Google Mock needs to support them.)
1666 operator Matcher<FloatType>() const {
1667 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1668 }
1669
1670 operator Matcher<const FloatType&>() const {
1671 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1672 }
1673
1674 operator Matcher<FloatType&>() const {
1675 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1676 }
jgm79a367e2012-04-10 16:02:11 +00001677
shiqiane35fdd92008-12-10 05:08:54 +00001678 private:
1679 const FloatType rhs_;
1680 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001681
1682 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001683};
1684
1685// Implements the Pointee(m) matcher for matching a pointer whose
1686// pointee matches matcher m. The pointer can be either raw or smart.
1687template <typename InnerMatcher>
1688class PointeeMatcher {
1689 public:
1690 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1691
1692 // This type conversion operator template allows Pointee(m) to be
1693 // used as a matcher for any pointer type whose pointee type is
1694 // compatible with the inner matcher, where type Pointer can be
1695 // either a raw pointer or a smart pointer.
1696 //
1697 // The reason we do this instead of relying on
1698 // MakePolymorphicMatcher() is that the latter is not flexible
1699 // enough for implementing the DescribeTo() method of Pointee().
1700 template <typename Pointer>
1701 operator Matcher<Pointer>() const {
1702 return MakeMatcher(new Impl<Pointer>(matcher_));
1703 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001704
shiqiane35fdd92008-12-10 05:08:54 +00001705 private:
1706 // The monomorphic implementation that works for a particular pointer type.
1707 template <typename Pointer>
1708 class Impl : public MatcherInterface<Pointer> {
1709 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00001710 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
1711 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001712
1713 explicit Impl(const InnerMatcher& matcher)
1714 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1715
shiqiane35fdd92008-12-10 05:08:54 +00001716 virtual void DescribeTo(::std::ostream* os) const {
1717 *os << "points to a value that ";
1718 matcher_.DescribeTo(os);
1719 }
1720
1721 virtual void DescribeNegationTo(::std::ostream* os) const {
1722 *os << "does not point to a value that ";
1723 matcher_.DescribeTo(os);
1724 }
1725
zhanyong.wan82113312010-01-08 21:55:40 +00001726 virtual bool MatchAndExplain(Pointer pointer,
1727 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001728 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00001729 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001730
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001731 *listener << "which points to ";
1732 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001733 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001734
shiqiane35fdd92008-12-10 05:08:54 +00001735 private:
1736 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001737
1738 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001739 };
1740
1741 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001742
1743 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001744};
1745
1746// Implements the Field() matcher for matching a field (i.e. member
1747// variable) of an object.
1748template <typename Class, typename FieldType>
1749class FieldMatcher {
1750 public:
1751 FieldMatcher(FieldType Class::*field,
1752 const Matcher<const FieldType&>& matcher)
1753 : field_(field), matcher_(matcher) {}
1754
shiqiane35fdd92008-12-10 05:08:54 +00001755 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001756 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001757 matcher_.DescribeTo(os);
1758 }
1759
1760 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001761 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001762 matcher_.DescribeNegationTo(os);
1763 }
1764
zhanyong.wandb22c222010-01-28 21:52:29 +00001765 template <typename T>
1766 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
1767 return MatchAndExplainImpl(
1768 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00001769 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00001770 value, listener);
1771 }
1772
1773 private:
1774 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001775 // Symbian's C++ compiler choose which overload to use. Its type is
1776 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001777 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1778 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001779 *listener << "whose given field is ";
1780 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001781 }
1782
zhanyong.wandb22c222010-01-28 21:52:29 +00001783 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1784 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001785 if (p == NULL)
1786 return false;
1787
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001788 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001789 // Since *p has a field, it must be a class/struct/union type and
1790 // thus cannot be a pointer. Therefore we pass false_type() as
1791 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001792 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001793 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001794
shiqiane35fdd92008-12-10 05:08:54 +00001795 const FieldType Class::*field_;
1796 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001797
1798 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001799};
1800
shiqiane35fdd92008-12-10 05:08:54 +00001801// Implements the Property() matcher for matching a property
1802// (i.e. return value of a getter method) of an object.
1803template <typename Class, typename PropertyType>
1804class PropertyMatcher {
1805 public:
1806 // The property may have a reference type, so 'const PropertyType&'
1807 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00001808 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00001809 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00001810 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001811
1812 PropertyMatcher(PropertyType (Class::*property)() const,
1813 const Matcher<RefToConstProperty>& matcher)
1814 : property_(property), matcher_(matcher) {}
1815
shiqiane35fdd92008-12-10 05:08:54 +00001816 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001817 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001818 matcher_.DescribeTo(os);
1819 }
1820
1821 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001822 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001823 matcher_.DescribeNegationTo(os);
1824 }
1825
zhanyong.wandb22c222010-01-28 21:52:29 +00001826 template <typename T>
1827 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
1828 return MatchAndExplainImpl(
1829 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00001830 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00001831 value, listener);
1832 }
1833
1834 private:
1835 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001836 // Symbian's C++ compiler choose which overload to use. Its type is
1837 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001838 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1839 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001840 *listener << "whose given property is ";
1841 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
1842 // which takes a non-const reference as argument.
1843 RefToConstProperty result = (obj.*property_)();
1844 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001845 }
1846
zhanyong.wandb22c222010-01-28 21:52:29 +00001847 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1848 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001849 if (p == NULL)
1850 return false;
1851
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001852 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001853 // Since *p has a property method, it must be a class/struct/union
1854 // type and thus cannot be a pointer. Therefore we pass
1855 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001856 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001857 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001858
shiqiane35fdd92008-12-10 05:08:54 +00001859 PropertyType (Class::*property_)() const;
1860 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001861
1862 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001863};
1864
shiqiane35fdd92008-12-10 05:08:54 +00001865// Type traits specifying various features of different functors for ResultOf.
1866// The default template specifies features for functor objects.
1867// Functor classes have to typedef argument_type and result_type
1868// to be compatible with ResultOf.
1869template <typename Functor>
1870struct CallableTraits {
1871 typedef typename Functor::result_type ResultType;
1872 typedef Functor StorageType;
1873
zhanyong.wan32de5f52009-12-23 00:13:23 +00001874 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00001875 template <typename T>
1876 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1877};
1878
1879// Specialization for function pointers.
1880template <typename ArgType, typename ResType>
1881struct CallableTraits<ResType(*)(ArgType)> {
1882 typedef ResType ResultType;
1883 typedef ResType(*StorageType)(ArgType);
1884
1885 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001886 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00001887 << "NULL function pointer is passed into ResultOf().";
1888 }
1889 template <typename T>
1890 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1891 return (*f)(arg);
1892 }
1893};
1894
1895// Implements the ResultOf() matcher for matching a return value of a
1896// unary function of an object.
1897template <typename Callable>
1898class ResultOfMatcher {
1899 public:
1900 typedef typename CallableTraits<Callable>::ResultType ResultType;
1901
1902 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1903 : callable_(callable), matcher_(matcher) {
1904 CallableTraits<Callable>::CheckIsValid(callable_);
1905 }
1906
1907 template <typename T>
1908 operator Matcher<T>() const {
1909 return Matcher<T>(new Impl<T>(callable_, matcher_));
1910 }
1911
1912 private:
1913 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1914
1915 template <typename T>
1916 class Impl : public MatcherInterface<T> {
1917 public:
1918 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1919 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00001920
1921 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001922 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001923 matcher_.DescribeTo(os);
1924 }
1925
1926 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001927 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001928 matcher_.DescribeNegationTo(os);
1929 }
1930
zhanyong.wan82113312010-01-08 21:55:40 +00001931 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001932 *listener << "which is mapped by the given callable to ";
1933 // Cannot pass the return value (for example, int) to
1934 // MatchPrintAndExplain, which takes a non-const reference as argument.
1935 ResultType result =
1936 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
1937 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001938 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001939
shiqiane35fdd92008-12-10 05:08:54 +00001940 private:
1941 // Functors often define operator() as non-const method even though
1942 // they are actualy stateless. But we need to use them even when
1943 // 'this' is a const pointer. It's the user's responsibility not to
1944 // use stateful callables with ResultOf(), which does't guarantee
1945 // how many times the callable will be invoked.
1946 mutable CallableStorageType callable_;
1947 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001948
1949 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001950 }; // class Impl
1951
1952 const CallableStorageType callable_;
1953 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001954
1955 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001956};
1957
zhanyong.wan6a896b52009-01-16 01:13:50 +00001958// Implements an equality matcher for any STL-style container whose elements
1959// support ==. This matcher is like Eq(), but its failure explanations provide
1960// more detailed information that is useful when the container is used as a set.
1961// The failure message reports elements that are in one of the operands but not
1962// the other. The failure messages do not report duplicate or out-of-order
1963// elements in the containers (which don't properly matter to sets, but can
1964// occur if the containers are vectors or lists, for example).
1965//
1966// Uses the container's const_iterator, value_type, operator ==,
1967// begin(), and end().
1968template <typename Container>
1969class ContainerEqMatcher {
1970 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00001971 typedef internal::StlContainerView<Container> View;
1972 typedef typename View::type StlContainer;
1973 typedef typename View::const_reference StlContainerReference;
1974
1975 // We make a copy of rhs in case the elements in it are modified
1976 // after this matcher is created.
1977 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
1978 // Makes sure the user doesn't instantiate this class template
1979 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001980 (void)testing::StaticAssertTypeEq<Container,
1981 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00001982 }
1983
zhanyong.wan6a896b52009-01-16 01:13:50 +00001984 void DescribeTo(::std::ostream* os) const {
1985 *os << "equals ";
vladloseve2e8ba42010-05-13 18:16:03 +00001986 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001987 }
1988 void DescribeNegationTo(::std::ostream* os) const {
1989 *os << "does not equal ";
vladloseve2e8ba42010-05-13 18:16:03 +00001990 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001991 }
1992
zhanyong.wanb8243162009-06-04 05:48:20 +00001993 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00001994 bool MatchAndExplain(const LhsContainer& lhs,
1995 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00001996 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00001997 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00001998 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00001999 LhsView;
2000 typedef typename LhsView::type LhsStlContainer;
2001 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00002002 if (lhs_stl_container == rhs_)
2003 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002004
zhanyong.wane122e452010-01-12 09:03:52 +00002005 ::std::ostream* const os = listener->stream();
2006 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002007 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002008 bool printed_header = false;
2009 for (typename LhsStlContainer::const_iterator it =
2010 lhs_stl_container.begin();
2011 it != lhs_stl_container.end(); ++it) {
2012 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
2013 rhs_.end()) {
2014 if (printed_header) {
2015 *os << ", ";
2016 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002017 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002018 printed_header = true;
2019 }
vladloseve2e8ba42010-05-13 18:16:03 +00002020 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002021 }
zhanyong.wane122e452010-01-12 09:03:52 +00002022 }
2023
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002024 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002025 bool printed_header2 = false;
2026 for (typename StlContainer::const_iterator it = rhs_.begin();
2027 it != rhs_.end(); ++it) {
2028 if (internal::ArrayAwareFind(
2029 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2030 lhs_stl_container.end()) {
2031 if (printed_header2) {
2032 *os << ", ";
2033 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002034 *os << (printed_header ? ",\nand" : "which")
2035 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002036 printed_header2 = true;
2037 }
vladloseve2e8ba42010-05-13 18:16:03 +00002038 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002039 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002040 }
2041 }
2042
zhanyong.wane122e452010-01-12 09:03:52 +00002043 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002044 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002045
zhanyong.wan6a896b52009-01-16 01:13:50 +00002046 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00002047 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002048
2049 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002050};
2051
zhanyong.wan898725c2011-09-16 16:45:39 +00002052// A comparator functor that uses the < operator to compare two values.
2053struct LessComparator {
2054 template <typename T, typename U>
2055 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2056};
2057
2058// Implements WhenSortedBy(comparator, container_matcher).
2059template <typename Comparator, typename ContainerMatcher>
2060class WhenSortedByMatcher {
2061 public:
2062 WhenSortedByMatcher(const Comparator& comparator,
2063 const ContainerMatcher& matcher)
2064 : comparator_(comparator), matcher_(matcher) {}
2065
2066 template <typename LhsContainer>
2067 operator Matcher<LhsContainer>() const {
2068 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2069 }
2070
2071 template <typename LhsContainer>
2072 class Impl : public MatcherInterface<LhsContainer> {
2073 public:
2074 typedef internal::StlContainerView<
2075 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2076 typedef typename LhsView::type LhsStlContainer;
2077 typedef typename LhsView::const_reference LhsStlContainerReference;
2078 typedef typename LhsStlContainer::value_type LhsValue;
2079
2080 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2081 : comparator_(comparator), matcher_(matcher) {}
2082
2083 virtual void DescribeTo(::std::ostream* os) const {
2084 *os << "(when sorted) ";
2085 matcher_.DescribeTo(os);
2086 }
2087
2088 virtual void DescribeNegationTo(::std::ostream* os) const {
2089 *os << "(when sorted) ";
2090 matcher_.DescribeNegationTo(os);
2091 }
2092
2093 virtual bool MatchAndExplain(LhsContainer lhs,
2094 MatchResultListener* listener) const {
2095 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2096 std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2097 lhs_stl_container.end());
2098 std::sort(sorted_container.begin(), sorted_container.end(), comparator_);
2099
2100 if (!listener->IsInterested()) {
2101 // If the listener is not interested, we do not need to
2102 // construct the inner explanation.
2103 return matcher_.Matches(sorted_container);
2104 }
2105
2106 *listener << "which is ";
2107 UniversalPrint(sorted_container, listener->stream());
2108 *listener << " when sorted";
2109
2110 StringMatchResultListener inner_listener;
2111 const bool match = matcher_.MatchAndExplain(sorted_container,
2112 &inner_listener);
2113 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2114 return match;
2115 }
2116
2117 private:
2118 const Comparator comparator_;
2119 const Matcher<const std::vector<LhsValue>&> matcher_;
2120
2121 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2122 };
2123
2124 private:
2125 const Comparator comparator_;
2126 const ContainerMatcher matcher_;
2127
2128 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2129};
2130
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002131// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2132// must be able to be safely cast to Matcher<tuple<const T1&, const
2133// T2&> >, where T1 and T2 are the types of elements in the LHS
2134// container and the RHS container respectively.
2135template <typename TupleMatcher, typename RhsContainer>
2136class PointwiseMatcher {
2137 public:
2138 typedef internal::StlContainerView<RhsContainer> RhsView;
2139 typedef typename RhsView::type RhsStlContainer;
2140 typedef typename RhsStlContainer::value_type RhsValue;
2141
2142 // Like ContainerEq, we make a copy of rhs in case the elements in
2143 // it are modified after this matcher is created.
2144 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2145 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2146 // Makes sure the user doesn't instantiate this class template
2147 // with a const or reference type.
2148 (void)testing::StaticAssertTypeEq<RhsContainer,
2149 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2150 }
2151
2152 template <typename LhsContainer>
2153 operator Matcher<LhsContainer>() const {
2154 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2155 }
2156
2157 template <typename LhsContainer>
2158 class Impl : public MatcherInterface<LhsContainer> {
2159 public:
2160 typedef internal::StlContainerView<
2161 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2162 typedef typename LhsView::type LhsStlContainer;
2163 typedef typename LhsView::const_reference LhsStlContainerReference;
2164 typedef typename LhsStlContainer::value_type LhsValue;
2165 // We pass the LHS value and the RHS value to the inner matcher by
2166 // reference, as they may be expensive to copy. We must use tuple
2167 // instead of pair here, as a pair cannot hold references (C++ 98,
2168 // 20.2.2 [lib.pairs]).
2169 typedef std::tr1::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
2170
2171 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2172 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2173 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2174 rhs_(rhs) {}
2175
2176 virtual void DescribeTo(::std::ostream* os) const {
2177 *os << "contains " << rhs_.size()
2178 << " values, where each value and its corresponding value in ";
2179 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2180 *os << " ";
2181 mono_tuple_matcher_.DescribeTo(os);
2182 }
2183 virtual void DescribeNegationTo(::std::ostream* os) const {
2184 *os << "doesn't contain exactly " << rhs_.size()
2185 << " values, or contains a value x at some index i"
2186 << " where x and the i-th value of ";
2187 UniversalPrint(rhs_, os);
2188 *os << " ";
2189 mono_tuple_matcher_.DescribeNegationTo(os);
2190 }
2191
2192 virtual bool MatchAndExplain(LhsContainer lhs,
2193 MatchResultListener* listener) const {
2194 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2195 const size_t actual_size = lhs_stl_container.size();
2196 if (actual_size != rhs_.size()) {
2197 *listener << "which contains " << actual_size << " values";
2198 return false;
2199 }
2200
2201 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2202 typename RhsStlContainer::const_iterator right = rhs_.begin();
2203 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2204 const InnerMatcherArg value_pair(*left, *right);
2205
2206 if (listener->IsInterested()) {
2207 StringMatchResultListener inner_listener;
2208 if (!mono_tuple_matcher_.MatchAndExplain(
2209 value_pair, &inner_listener)) {
2210 *listener << "where the value pair (";
2211 UniversalPrint(*left, listener->stream());
2212 *listener << ", ";
2213 UniversalPrint(*right, listener->stream());
2214 *listener << ") at index #" << i << " don't match";
2215 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2216 return false;
2217 }
2218 } else {
2219 if (!mono_tuple_matcher_.Matches(value_pair))
2220 return false;
2221 }
2222 }
2223
2224 return true;
2225 }
2226
2227 private:
2228 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2229 const RhsStlContainer rhs_;
2230
2231 GTEST_DISALLOW_ASSIGN_(Impl);
2232 };
2233
2234 private:
2235 const TupleMatcher tuple_matcher_;
2236 const RhsStlContainer rhs_;
2237
2238 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2239};
2240
zhanyong.wan33605ba2010-04-22 23:37:47 +00002241// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002242template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002243class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002244 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002245 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002246 typedef StlContainerView<RawContainer> View;
2247 typedef typename View::type StlContainer;
2248 typedef typename View::const_reference StlContainerReference;
2249 typedef typename StlContainer::value_type Element;
2250
2251 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002252 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002253 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002254 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002255
zhanyong.wan33605ba2010-04-22 23:37:47 +00002256 // Checks whether:
2257 // * All elements in the container match, if all_elements_should_match.
2258 // * Any element in the container matches, if !all_elements_should_match.
2259 bool MatchAndExplainImpl(bool all_elements_should_match,
2260 Container container,
2261 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002262 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002263 size_t i = 0;
2264 for (typename StlContainer::const_iterator it = stl_container.begin();
2265 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002266 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00002267 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2268
2269 if (matches != all_elements_should_match) {
2270 *listener << "whose element #" << i
2271 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002272 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00002273 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00002274 }
2275 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00002276 return all_elements_should_match;
2277 }
2278
2279 protected:
2280 const Matcher<const Element&> inner_matcher_;
2281
2282 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2283};
2284
2285// Implements Contains(element_matcher) for the given argument type Container.
2286// Symmetric to EachMatcherImpl.
2287template <typename Container>
2288class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2289 public:
2290 template <typename InnerMatcher>
2291 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2292 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2293
2294 // Describes what this matcher does.
2295 virtual void DescribeTo(::std::ostream* os) const {
2296 *os << "contains at least one element that ";
2297 this->inner_matcher_.DescribeTo(os);
2298 }
2299
2300 virtual void DescribeNegationTo(::std::ostream* os) const {
2301 *os << "doesn't contain any element that ";
2302 this->inner_matcher_.DescribeTo(os);
2303 }
2304
2305 virtual bool MatchAndExplain(Container container,
2306 MatchResultListener* listener) const {
2307 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002308 }
2309
2310 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002311 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002312};
2313
zhanyong.wan33605ba2010-04-22 23:37:47 +00002314// Implements Each(element_matcher) for the given argument type Container.
2315// Symmetric to ContainsMatcherImpl.
2316template <typename Container>
2317class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2318 public:
2319 template <typename InnerMatcher>
2320 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2321 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2322
2323 // Describes what this matcher does.
2324 virtual void DescribeTo(::std::ostream* os) const {
2325 *os << "only contains elements that ";
2326 this->inner_matcher_.DescribeTo(os);
2327 }
2328
2329 virtual void DescribeNegationTo(::std::ostream* os) const {
2330 *os << "contains some element that ";
2331 this->inner_matcher_.DescribeNegationTo(os);
2332 }
2333
2334 virtual bool MatchAndExplain(Container container,
2335 MatchResultListener* listener) const {
2336 return this->MatchAndExplainImpl(true, container, listener);
2337 }
2338
2339 private:
2340 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2341};
2342
zhanyong.wanb8243162009-06-04 05:48:20 +00002343// Implements polymorphic Contains(element_matcher).
2344template <typename M>
2345class ContainsMatcher {
2346 public:
2347 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2348
2349 template <typename Container>
2350 operator Matcher<Container>() const {
2351 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2352 }
2353
2354 private:
2355 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002356
2357 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002358};
2359
zhanyong.wan33605ba2010-04-22 23:37:47 +00002360// Implements polymorphic Each(element_matcher).
2361template <typename M>
2362class EachMatcher {
2363 public:
2364 explicit EachMatcher(M m) : inner_matcher_(m) {}
2365
2366 template <typename Container>
2367 operator Matcher<Container>() const {
2368 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2369 }
2370
2371 private:
2372 const M inner_matcher_;
2373
2374 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2375};
2376
zhanyong.wanb5937da2009-07-16 20:26:41 +00002377// Implements Key(inner_matcher) for the given argument pair type.
2378// Key(inner_matcher) matches an std::pair whose 'first' field matches
2379// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2380// std::map that contains at least one element whose key is >= 5.
2381template <typename PairType>
2382class KeyMatcherImpl : public MatcherInterface<PairType> {
2383 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002384 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002385 typedef typename RawPairType::first_type KeyType;
2386
2387 template <typename InnerMatcher>
2388 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2389 : inner_matcher_(
2390 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2391 }
2392
2393 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002394 virtual bool MatchAndExplain(PairType key_value,
2395 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002396 StringMatchResultListener inner_listener;
2397 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2398 &inner_listener);
2399 const internal::string explanation = inner_listener.str();
2400 if (explanation != "") {
2401 *listener << "whose first field is a value " << explanation;
2402 }
2403 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002404 }
2405
2406 // Describes what this matcher does.
2407 virtual void DescribeTo(::std::ostream* os) const {
2408 *os << "has a key that ";
2409 inner_matcher_.DescribeTo(os);
2410 }
2411
2412 // Describes what the negation of this matcher does.
2413 virtual void DescribeNegationTo(::std::ostream* os) const {
2414 *os << "doesn't have a key that ";
2415 inner_matcher_.DescribeTo(os);
2416 }
2417
zhanyong.wanb5937da2009-07-16 20:26:41 +00002418 private:
2419 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002420
2421 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002422};
2423
2424// Implements polymorphic Key(matcher_for_key).
2425template <typename M>
2426class KeyMatcher {
2427 public:
2428 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2429
2430 template <typename PairType>
2431 operator Matcher<PairType>() const {
2432 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2433 }
2434
2435 private:
2436 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002437
2438 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002439};
2440
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002441// Implements Pair(first_matcher, second_matcher) for the given argument pair
2442// type with its two matchers. See Pair() function below.
2443template <typename PairType>
2444class PairMatcherImpl : public MatcherInterface<PairType> {
2445 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002446 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002447 typedef typename RawPairType::first_type FirstType;
2448 typedef typename RawPairType::second_type SecondType;
2449
2450 template <typename FirstMatcher, typename SecondMatcher>
2451 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2452 : first_matcher_(
2453 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2454 second_matcher_(
2455 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2456 }
2457
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002458 // Describes what this matcher does.
2459 virtual void DescribeTo(::std::ostream* os) const {
2460 *os << "has a first field that ";
2461 first_matcher_.DescribeTo(os);
2462 *os << ", and has a second field that ";
2463 second_matcher_.DescribeTo(os);
2464 }
2465
2466 // Describes what the negation of this matcher does.
2467 virtual void DescribeNegationTo(::std::ostream* os) const {
2468 *os << "has a first field that ";
2469 first_matcher_.DescribeNegationTo(os);
2470 *os << ", or has a second field that ";
2471 second_matcher_.DescribeNegationTo(os);
2472 }
2473
zhanyong.wan82113312010-01-08 21:55:40 +00002474 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2475 // matches second_matcher.
2476 virtual bool MatchAndExplain(PairType a_pair,
2477 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002478 if (!listener->IsInterested()) {
2479 // If the listener is not interested, we don't need to construct the
2480 // explanation.
2481 return first_matcher_.Matches(a_pair.first) &&
2482 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00002483 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002484 StringMatchResultListener first_inner_listener;
2485 if (!first_matcher_.MatchAndExplain(a_pair.first,
2486 &first_inner_listener)) {
2487 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002488 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002489 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002490 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002491 StringMatchResultListener second_inner_listener;
2492 if (!second_matcher_.MatchAndExplain(a_pair.second,
2493 &second_inner_listener)) {
2494 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002495 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002496 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002497 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002498 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
2499 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00002500 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002501 }
2502
2503 private:
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002504 void ExplainSuccess(const internal::string& first_explanation,
2505 const internal::string& second_explanation,
2506 MatchResultListener* listener) const {
2507 *listener << "whose both fields match";
2508 if (first_explanation != "") {
2509 *listener << ", where the first field is a value " << first_explanation;
2510 }
2511 if (second_explanation != "") {
2512 *listener << ", ";
2513 if (first_explanation != "") {
2514 *listener << "and ";
2515 } else {
2516 *listener << "where ";
2517 }
2518 *listener << "the second field is a value " << second_explanation;
2519 }
2520 }
2521
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002522 const Matcher<const FirstType&> first_matcher_;
2523 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002524
2525 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002526};
2527
2528// Implements polymorphic Pair(first_matcher, second_matcher).
2529template <typename FirstMatcher, typename SecondMatcher>
2530class PairMatcher {
2531 public:
2532 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2533 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2534
2535 template <typename PairType>
2536 operator Matcher<PairType> () const {
2537 return MakeMatcher(
2538 new PairMatcherImpl<PairType>(
2539 first_matcher_, second_matcher_));
2540 }
2541
2542 private:
2543 const FirstMatcher first_matcher_;
2544 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002545
2546 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002547};
2548
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002549// Implements ElementsAre() and ElementsAreArray().
2550template <typename Container>
2551class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2552 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002553 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002554 typedef internal::StlContainerView<RawContainer> View;
2555 typedef typename View::type StlContainer;
2556 typedef typename View::const_reference StlContainerReference;
2557 typedef typename StlContainer::value_type Element;
2558
2559 // Constructs the matcher from a sequence of element values or
2560 // element matchers.
2561 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00002562 ElementsAreMatcherImpl(InputIter first, InputIter last) {
2563 while (first != last) {
2564 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002565 }
2566 }
2567
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002568 // Describes what this matcher does.
2569 virtual void DescribeTo(::std::ostream* os) const {
2570 if (count() == 0) {
2571 *os << "is empty";
2572 } else if (count() == 1) {
2573 *os << "has 1 element that ";
2574 matchers_[0].DescribeTo(os);
2575 } else {
2576 *os << "has " << Elements(count()) << " where\n";
2577 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002578 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002579 matchers_[i].DescribeTo(os);
2580 if (i + 1 < count()) {
2581 *os << ",\n";
2582 }
2583 }
2584 }
2585 }
2586
2587 // Describes what the negation of this matcher does.
2588 virtual void DescribeNegationTo(::std::ostream* os) const {
2589 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002590 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002591 return;
2592 }
2593
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002594 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002595 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002596 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002597 matchers_[i].DescribeNegationTo(os);
2598 if (i + 1 < count()) {
2599 *os << ", or\n";
2600 }
2601 }
2602 }
2603
zhanyong.wan82113312010-01-08 21:55:40 +00002604 virtual bool MatchAndExplain(Container container,
2605 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002606 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002607 const size_t actual_count = stl_container.size();
2608 if (actual_count != count()) {
2609 // The element count doesn't match. If the container is empty,
2610 // there's no need to explain anything as Google Mock already
2611 // prints the empty container. Otherwise we just need to show
2612 // how many elements there actually are.
2613 if (actual_count != 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002614 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002615 }
zhanyong.wan82113312010-01-08 21:55:40 +00002616 return false;
2617 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002618
zhanyong.wan82113312010-01-08 21:55:40 +00002619 typename StlContainer::const_iterator it = stl_container.begin();
2620 // explanations[i] is the explanation of the element at index i.
2621 std::vector<internal::string> explanations(count());
2622 for (size_t i = 0; i != count(); ++it, ++i) {
2623 StringMatchResultListener s;
2624 if (matchers_[i].MatchAndExplain(*it, &s)) {
2625 explanations[i] = s.str();
2626 } else {
2627 // The container has the right size but the i-th element
2628 // doesn't match its expectation.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002629 *listener << "whose element #" << i << " doesn't match";
2630 PrintIfNotEmpty(s.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002631 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002632 }
2633 }
zhanyong.wan82113312010-01-08 21:55:40 +00002634
2635 // Every element matches its expectation. We need to explain why
2636 // (the obvious ones can be skipped).
zhanyong.wan82113312010-01-08 21:55:40 +00002637 bool reason_printed = false;
2638 for (size_t i = 0; i != count(); ++i) {
2639 const internal::string& s = explanations[i];
2640 if (!s.empty()) {
2641 if (reason_printed) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002642 *listener << ",\nand ";
zhanyong.wan82113312010-01-08 21:55:40 +00002643 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002644 *listener << "whose element #" << i << " matches, " << s;
zhanyong.wan82113312010-01-08 21:55:40 +00002645 reason_printed = true;
2646 }
2647 }
2648
2649 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002650 }
2651
2652 private:
2653 static Message Elements(size_t count) {
2654 return Message() << count << (count == 1 ? " element" : " elements");
2655 }
2656
2657 size_t count() const { return matchers_.size(); }
2658 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002659
2660 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002661};
2662
2663// Implements ElementsAre() of 0 arguments.
2664class ElementsAreMatcher0 {
2665 public:
2666 ElementsAreMatcher0() {}
2667
2668 template <typename Container>
2669 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002670 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002671 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2672 Element;
2673
2674 const Matcher<const Element&>* const matchers = NULL;
jgm38513a82012-11-15 15:50:36 +00002675 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers,
2676 matchers));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002677 }
2678};
2679
2680// Implements ElementsAreArray().
2681template <typename T>
2682class ElementsAreArrayMatcher {
2683 public:
jgm38513a82012-11-15 15:50:36 +00002684 template <typename Iter>
2685 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002686
2687 template <typename Container>
2688 operator Matcher<Container>() const {
jgm38513a82012-11-15 15:50:36 +00002689 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
2690 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002691 }
2692
2693 private:
jgm38513a82012-11-15 15:50:36 +00002694 const std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002695
2696 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002697};
2698
zhanyong.wanb4140802010-06-08 22:53:57 +00002699// Returns the description for a matcher defined using the MATCHER*()
2700// macro where the user-supplied description string is "", if
2701// 'negation' is false; otherwise returns the description of the
2702// negation of the matcher. 'param_values' contains a list of strings
2703// that are the print-out of the matcher's parameters.
vladlosev587c1b32011-05-20 00:42:22 +00002704GTEST_API_ string FormatMatcherDescription(bool negation,
2705 const char* matcher_name,
2706 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002707
shiqiane35fdd92008-12-10 05:08:54 +00002708} // namespace internal
2709
shiqiane35fdd92008-12-10 05:08:54 +00002710// _ is a matcher that matches anything of any type.
2711//
2712// This definition is fine as:
2713//
2714// 1. The C++ standard permits using the name _ in a namespace that
2715// is not the global namespace or ::std.
2716// 2. The AnythingMatcher class has no data member or constructor,
2717// so it's OK to create global variables of this type.
2718// 3. c-style has approved of using _ in this case.
2719const internal::AnythingMatcher _ = {};
2720// Creates a matcher that matches any value of the given type T.
2721template <typename T>
2722inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2723
2724// Creates a matcher that matches any value of the given type T.
2725template <typename T>
2726inline Matcher<T> An() { return A<T>(); }
2727
2728// Creates a polymorphic matcher that matches anything equal to x.
2729// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2730// wouldn't compile.
2731template <typename T>
2732inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2733
2734// Constructs a Matcher<T> from a 'value' of type T. The constructed
2735// matcher matches any value that's equal to 'value'.
2736template <typename T>
2737Matcher<T>::Matcher(T value) { *this = Eq(value); }
2738
2739// Creates a monomorphic matcher that matches anything with type Lhs
2740// and equal to rhs. A user may need to use this instead of Eq(...)
2741// in order to resolve an overloading ambiguity.
2742//
2743// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2744// or Matcher<T>(x), but more readable than the latter.
2745//
2746// We could define similar monomorphic matchers for other comparison
2747// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2748// it yet as those are used much less than Eq() in practice. A user
2749// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2750// for example.
2751template <typename Lhs, typename Rhs>
2752inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2753
2754// Creates a polymorphic matcher that matches anything >= x.
2755template <typename Rhs>
2756inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2757 return internal::GeMatcher<Rhs>(x);
2758}
2759
2760// Creates a polymorphic matcher that matches anything > x.
2761template <typename Rhs>
2762inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2763 return internal::GtMatcher<Rhs>(x);
2764}
2765
2766// Creates a polymorphic matcher that matches anything <= x.
2767template <typename Rhs>
2768inline internal::LeMatcher<Rhs> Le(Rhs x) {
2769 return internal::LeMatcher<Rhs>(x);
2770}
2771
2772// Creates a polymorphic matcher that matches anything < x.
2773template <typename Rhs>
2774inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2775 return internal::LtMatcher<Rhs>(x);
2776}
2777
2778// Creates a polymorphic matcher that matches anything != x.
2779template <typename Rhs>
2780inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2781 return internal::NeMatcher<Rhs>(x);
2782}
2783
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002784// Creates a polymorphic matcher that matches any NULL pointer.
2785inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2786 return MakePolymorphicMatcher(internal::IsNullMatcher());
2787}
2788
shiqiane35fdd92008-12-10 05:08:54 +00002789// Creates a polymorphic matcher that matches any non-NULL pointer.
2790// This is convenient as Not(NULL) doesn't compile (the compiler
2791// thinks that that expression is comparing a pointer with an integer).
2792inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2793 return MakePolymorphicMatcher(internal::NotNullMatcher());
2794}
2795
2796// Creates a polymorphic matcher that matches any argument that
2797// references variable x.
2798template <typename T>
2799inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2800 return internal::RefMatcher<T&>(x);
2801}
2802
2803// Creates a matcher that matches any double argument approximately
2804// equal to rhs, where two NANs are considered unequal.
2805inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2806 return internal::FloatingEqMatcher<double>(rhs, false);
2807}
2808
2809// Creates a matcher that matches any double argument approximately
2810// equal to rhs, including NaN values when rhs is NaN.
2811inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2812 return internal::FloatingEqMatcher<double>(rhs, true);
2813}
2814
2815// Creates a matcher that matches any float argument approximately
2816// equal to rhs, where two NANs are considered unequal.
2817inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2818 return internal::FloatingEqMatcher<float>(rhs, false);
2819}
2820
2821// Creates a matcher that matches any double argument approximately
2822// equal to rhs, including NaN values when rhs is NaN.
2823inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2824 return internal::FloatingEqMatcher<float>(rhs, true);
2825}
2826
2827// Creates a matcher that matches a pointer (raw or smart) that points
2828// to a value that matches inner_matcher.
2829template <typename InnerMatcher>
2830inline internal::PointeeMatcher<InnerMatcher> Pointee(
2831 const InnerMatcher& inner_matcher) {
2832 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2833}
2834
2835// Creates a matcher that matches an object whose given field matches
2836// 'matcher'. For example,
2837// Field(&Foo::number, Ge(5))
2838// matches a Foo object x iff x.number >= 5.
2839template <typename Class, typename FieldType, typename FieldMatcher>
2840inline PolymorphicMatcher<
2841 internal::FieldMatcher<Class, FieldType> > Field(
2842 FieldType Class::*field, const FieldMatcher& matcher) {
2843 return MakePolymorphicMatcher(
2844 internal::FieldMatcher<Class, FieldType>(
2845 field, MatcherCast<const FieldType&>(matcher)));
2846 // The call to MatcherCast() is required for supporting inner
2847 // matchers of compatible types. For example, it allows
2848 // Field(&Foo::bar, m)
2849 // to compile where bar is an int32 and m is a matcher for int64.
2850}
2851
2852// Creates a matcher that matches an object whose given property
2853// matches 'matcher'. For example,
2854// Property(&Foo::str, StartsWith("hi"))
2855// matches a Foo object x iff x.str() starts with "hi".
2856template <typename Class, typename PropertyType, typename PropertyMatcher>
2857inline PolymorphicMatcher<
2858 internal::PropertyMatcher<Class, PropertyType> > Property(
2859 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2860 return MakePolymorphicMatcher(
2861 internal::PropertyMatcher<Class, PropertyType>(
2862 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00002863 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002864 // The call to MatcherCast() is required for supporting inner
2865 // matchers of compatible types. For example, it allows
2866 // Property(&Foo::bar, m)
2867 // to compile where bar() returns an int32 and m is a matcher for int64.
2868}
2869
2870// Creates a matcher that matches an object iff the result of applying
2871// a callable to x matches 'matcher'.
2872// For example,
2873// ResultOf(f, StartsWith("hi"))
2874// matches a Foo object x iff f(x) starts with "hi".
2875// callable parameter can be a function, function pointer, or a functor.
2876// Callable has to satisfy the following conditions:
2877// * It is required to keep no state affecting the results of
2878// the calls on it and make no assumptions about how many calls
2879// will be made. Any state it keeps must be protected from the
2880// concurrent access.
2881// * If it is a function object, it has to define type result_type.
2882// We recommend deriving your functor classes from std::unary_function.
2883template <typename Callable, typename ResultOfMatcher>
2884internal::ResultOfMatcher<Callable> ResultOf(
2885 Callable callable, const ResultOfMatcher& matcher) {
2886 return internal::ResultOfMatcher<Callable>(
2887 callable,
2888 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2889 matcher));
2890 // The call to MatcherCast() is required for supporting inner
2891 // matchers of compatible types. For example, it allows
2892 // ResultOf(Function, m)
2893 // to compile where Function() returns an int32 and m is a matcher for int64.
2894}
2895
2896// String matchers.
2897
2898// Matches a string equal to str.
2899inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2900 StrEq(const internal::string& str) {
2901 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2902 str, true, true));
2903}
2904
2905// Matches a string not equal to str.
2906inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2907 StrNe(const internal::string& str) {
2908 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2909 str, false, true));
2910}
2911
2912// Matches a string equal to str, ignoring case.
2913inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2914 StrCaseEq(const internal::string& str) {
2915 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2916 str, true, false));
2917}
2918
2919// Matches a string not equal to str, ignoring case.
2920inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2921 StrCaseNe(const internal::string& str) {
2922 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2923 str, false, false));
2924}
2925
2926// Creates a matcher that matches any string, std::string, or C string
2927// that contains the given substring.
2928inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2929 HasSubstr(const internal::string& substring) {
2930 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
2931 substring));
2932}
2933
2934// Matches a string that starts with 'prefix' (case-sensitive).
2935inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
2936 StartsWith(const internal::string& prefix) {
2937 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
2938 prefix));
2939}
2940
2941// Matches a string that ends with 'suffix' (case-sensitive).
2942inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
2943 EndsWith(const internal::string& suffix) {
2944 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
2945 suffix));
2946}
2947
shiqiane35fdd92008-12-10 05:08:54 +00002948// Matches a string that fully matches regular expression 'regex'.
2949// The matcher takes ownership of 'regex'.
2950inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2951 const internal::RE* regex) {
2952 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2953}
2954inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2955 const internal::string& regex) {
2956 return MatchesRegex(new internal::RE(regex));
2957}
2958
2959// Matches a string that contains regular expression 'regex'.
2960// The matcher takes ownership of 'regex'.
2961inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2962 const internal::RE* regex) {
2963 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2964}
2965inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2966 const internal::string& regex) {
2967 return ContainsRegex(new internal::RE(regex));
2968}
2969
shiqiane35fdd92008-12-10 05:08:54 +00002970#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2971// Wide string matchers.
2972
2973// Matches a string equal to str.
2974inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2975 StrEq(const internal::wstring& str) {
2976 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2977 str, true, true));
2978}
2979
2980// Matches a string not equal to str.
2981inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2982 StrNe(const internal::wstring& str) {
2983 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2984 str, false, true));
2985}
2986
2987// Matches a string equal to str, ignoring case.
2988inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2989 StrCaseEq(const internal::wstring& str) {
2990 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2991 str, true, false));
2992}
2993
2994// Matches a string not equal to str, ignoring case.
2995inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2996 StrCaseNe(const internal::wstring& str) {
2997 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2998 str, false, false));
2999}
3000
3001// Creates a matcher that matches any wstring, std::wstring, or C wide string
3002// that contains the given substring.
3003inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
3004 HasSubstr(const internal::wstring& substring) {
3005 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
3006 substring));
3007}
3008
3009// Matches a string that starts with 'prefix' (case-sensitive).
3010inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
3011 StartsWith(const internal::wstring& prefix) {
3012 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
3013 prefix));
3014}
3015
3016// Matches a string that ends with 'suffix' (case-sensitive).
3017inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
3018 EndsWith(const internal::wstring& suffix) {
3019 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
3020 suffix));
3021}
3022
3023#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3024
3025// Creates a polymorphic matcher that matches a 2-tuple where the
3026// first field == the second field.
3027inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
3028
3029// Creates a polymorphic matcher that matches a 2-tuple where the
3030// first field >= the second field.
3031inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
3032
3033// Creates a polymorphic matcher that matches a 2-tuple where the
3034// first field > the second field.
3035inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
3036
3037// Creates a polymorphic matcher that matches a 2-tuple where the
3038// first field <= the second field.
3039inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
3040
3041// Creates a polymorphic matcher that matches a 2-tuple where the
3042// first field < the second field.
3043inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
3044
3045// Creates a polymorphic matcher that matches a 2-tuple where the
3046// first field != the second field.
3047inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
3048
3049// Creates a matcher that matches any value of type T that m doesn't
3050// match.
3051template <typename InnerMatcher>
3052inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
3053 return internal::NotMatcher<InnerMatcher>(m);
3054}
3055
shiqiane35fdd92008-12-10 05:08:54 +00003056// Returns a matcher that matches anything that satisfies the given
3057// predicate. The predicate can be any unary function or functor
3058// whose return type can be implicitly converted to bool.
3059template <typename Predicate>
3060inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
3061Truly(Predicate pred) {
3062 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
3063}
3064
zhanyong.wan6a896b52009-01-16 01:13:50 +00003065// Returns a matcher that matches an equal container.
3066// This matcher behaves like Eq(), but in the event of mismatch lists the
3067// values that are included in one container but not the other. (Duplicate
3068// values and order differences are not explained.)
3069template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00003070inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00003071 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00003072 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00003073 // This following line is for working around a bug in MSVC 8.0,
3074 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00003075 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00003076 return MakePolymorphicMatcher(
3077 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00003078}
3079
zhanyong.wan898725c2011-09-16 16:45:39 +00003080// Returns a matcher that matches a container that, when sorted using
3081// the given comparator, matches container_matcher.
3082template <typename Comparator, typename ContainerMatcher>
3083inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
3084WhenSortedBy(const Comparator& comparator,
3085 const ContainerMatcher& container_matcher) {
3086 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
3087 comparator, container_matcher);
3088}
3089
3090// Returns a matcher that matches a container that, when sorted using
3091// the < operator, matches container_matcher.
3092template <typename ContainerMatcher>
3093inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
3094WhenSorted(const ContainerMatcher& container_matcher) {
3095 return
3096 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
3097 internal::LessComparator(), container_matcher);
3098}
3099
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003100// Matches an STL-style container or a native array that contains the
3101// same number of elements as in rhs, where its i-th element and rhs's
3102// i-th element (as a pair) satisfy the given pair matcher, for all i.
3103// TupleMatcher must be able to be safely cast to Matcher<tuple<const
3104// T1&, const T2&> >, where T1 and T2 are the types of elements in the
3105// LHS container and the RHS container respectively.
3106template <typename TupleMatcher, typename Container>
3107inline internal::PointwiseMatcher<TupleMatcher,
3108 GTEST_REMOVE_CONST_(Container)>
3109Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
3110 // This following line is for working around a bug in MSVC 8.0,
3111 // which causes Container to be a const type sometimes.
3112 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
3113 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
3114 tuple_matcher, rhs);
3115}
3116
zhanyong.wanb8243162009-06-04 05:48:20 +00003117// Matches an STL-style container or a native array that contains at
3118// least one element matching the given value or matcher.
3119//
3120// Examples:
3121// ::std::set<int> page_ids;
3122// page_ids.insert(3);
3123// page_ids.insert(1);
3124// EXPECT_THAT(page_ids, Contains(1));
3125// EXPECT_THAT(page_ids, Contains(Gt(2)));
3126// EXPECT_THAT(page_ids, Not(Contains(4)));
3127//
3128// ::std::map<int, size_t> page_lengths;
3129// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00003130// EXPECT_THAT(page_lengths,
3131// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00003132//
3133// const char* user_ids[] = { "joe", "mike", "tom" };
3134// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
3135template <typename M>
3136inline internal::ContainsMatcher<M> Contains(M matcher) {
3137 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00003138}
3139
zhanyong.wan33605ba2010-04-22 23:37:47 +00003140// Matches an STL-style container or a native array that contains only
3141// elements matching the given value or matcher.
3142//
3143// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
3144// the messages are different.
3145//
3146// Examples:
3147// ::std::set<int> page_ids;
3148// // Each(m) matches an empty container, regardless of what m is.
3149// EXPECT_THAT(page_ids, Each(Eq(1)));
3150// EXPECT_THAT(page_ids, Each(Eq(77)));
3151//
3152// page_ids.insert(3);
3153// EXPECT_THAT(page_ids, Each(Gt(0)));
3154// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
3155// page_ids.insert(1);
3156// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
3157//
3158// ::std::map<int, size_t> page_lengths;
3159// page_lengths[1] = 100;
3160// page_lengths[2] = 200;
3161// page_lengths[3] = 300;
3162// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
3163// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
3164//
3165// const char* user_ids[] = { "joe", "mike", "tom" };
3166// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
3167template <typename M>
3168inline internal::EachMatcher<M> Each(M matcher) {
3169 return internal::EachMatcher<M>(matcher);
3170}
3171
zhanyong.wanb5937da2009-07-16 20:26:41 +00003172// Key(inner_matcher) matches an std::pair whose 'first' field matches
3173// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3174// std::map that contains at least one element whose key is >= 5.
3175template <typename M>
3176inline internal::KeyMatcher<M> Key(M inner_matcher) {
3177 return internal::KeyMatcher<M>(inner_matcher);
3178}
3179
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003180// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
3181// matches first_matcher and whose 'second' field matches second_matcher. For
3182// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
3183// to match a std::map<int, string> that contains exactly one element whose key
3184// is >= 5 and whose value equals "foo".
3185template <typename FirstMatcher, typename SecondMatcher>
3186inline internal::PairMatcher<FirstMatcher, SecondMatcher>
3187Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
3188 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
3189 first_matcher, second_matcher);
3190}
3191
shiqiane35fdd92008-12-10 05:08:54 +00003192// Returns a predicate that is satisfied by anything that matches the
3193// given matcher.
3194template <typename M>
3195inline internal::MatcherAsPredicate<M> Matches(M matcher) {
3196 return internal::MatcherAsPredicate<M>(matcher);
3197}
3198
zhanyong.wanb8243162009-06-04 05:48:20 +00003199// Returns true iff the value matches the matcher.
3200template <typename T, typename M>
3201inline bool Value(const T& value, M matcher) {
3202 return testing::Matches(matcher)(value);
3203}
3204
zhanyong.wan34b034c2010-03-05 21:23:23 +00003205// Matches the value against the given matcher and explains the match
3206// result to listener.
3207template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00003208inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00003209 M matcher, const T& value, MatchResultListener* listener) {
3210 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
3211}
3212
zhanyong.wanbf550852009-06-09 06:09:53 +00003213// AllArgs(m) is a synonym of m. This is useful in
3214//
3215// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
3216//
3217// which is easier to read than
3218//
3219// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
3220template <typename InnerMatcher>
3221inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
3222
shiqiane35fdd92008-12-10 05:08:54 +00003223// These macros allow using matchers to check values in Google Test
3224// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
3225// succeed iff the value matches the matcher. If the assertion fails,
3226// the value and the description of the matcher will be printed.
3227#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
3228 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3229#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
3230 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3231
3232} // namespace testing
3233
3234#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_