blob: 19bd551ab7a47ea5efe835f5b58c698970eae7d7 [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.wan83f6b082013-03-01 01:47:35 +0000115 // result to 'listener' if necessary (see the next paragraph), in
116 // the form of a non-restrictive relative clause ("which ...",
117 // "whose ...", etc) that describes x. For example, the
118 // MatchAndExplain() method of the Pointee(...) matcher should
119 // generate an explanation like "which points to ...".
120 //
121 // Implementations of MatchAndExplain() should add an explanation of
122 // the match result *if and only if* they can provide additional
123 // information that's not already present (or not obvious) in the
124 // print-out of x and the matcher's description. Whether the match
125 // succeeds is not a factor in deciding whether an explanation is
126 // needed, as sometimes the caller needs to print a failure message
127 // when the match succeeds (e.g. when the matcher is used inside
128 // Not()).
129 //
130 // For example, a "has at least 10 elements" matcher should explain
131 // what the actual element count is, regardless of the match result,
132 // as it is useful information to the reader; on the other hand, an
133 // "is empty" matcher probably only needs to explain what the actual
134 // size is when the match fails, as it's redundant to say that the
135 // size is 0 when the value is already known to be empty.
zhanyong.wan82113312010-01-08 21:55:40 +0000136 //
zhanyong.wandb22c222010-01-28 21:52:29 +0000137 // You should override this method when defining a new matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000138 //
139 // It's the responsibility of the caller (Google Mock) to guarantee
140 // that 'listener' is not NULL. This helps to simplify a matcher's
141 // implementation when it doesn't care about the performance, as it
142 // can talk to 'listener' without checking its validity first.
143 // However, in order to implement dummy listeners efficiently,
144 // listener->stream() may be NULL.
zhanyong.wandb22c222010-01-28 21:52:29 +0000145 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
shiqiane35fdd92008-12-10 05:08:54 +0000146
zhanyong.wana862f1d2010-03-15 21:23:04 +0000147 // Describes this matcher to an ostream. The function should print
148 // a verb phrase that describes the property a value matching this
149 // matcher should have. The subject of the verb phrase is the value
150 // being matched. For example, the DescribeTo() method of the Gt(7)
151 // matcher prints "is greater than 7".
shiqiane35fdd92008-12-10 05:08:54 +0000152 virtual void DescribeTo(::std::ostream* os) const = 0;
153
154 // Describes the negation of this matcher to an ostream. For
155 // example, if the description of this matcher is "is greater than
156 // 7", the negated description could be "is not greater than 7".
157 // You are not required to override this when implementing
158 // MatcherInterface, but it is highly advised so that your matcher
159 // can produce good error messages.
160 virtual void DescribeNegationTo(::std::ostream* os) const {
161 *os << "not (";
162 DescribeTo(os);
163 *os << ")";
164 }
shiqiane35fdd92008-12-10 05:08:54 +0000165};
166
167namespace internal {
168
zhanyong.wan82113312010-01-08 21:55:40 +0000169// A match result listener that ignores the explanation.
170class DummyMatchResultListener : public MatchResultListener {
171 public:
172 DummyMatchResultListener() : MatchResultListener(NULL) {}
173
174 private:
175 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
176};
177
178// A match result listener that forwards the explanation to a given
179// ostream. The difference between this and MatchResultListener is
180// that the former is concrete.
181class StreamMatchResultListener : public MatchResultListener {
182 public:
183 explicit StreamMatchResultListener(::std::ostream* os)
184 : MatchResultListener(os) {}
185
186 private:
187 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
188};
189
190// A match result listener that stores the explanation in a string.
191class StringMatchResultListener : public MatchResultListener {
192 public:
193 StringMatchResultListener() : MatchResultListener(&ss_) {}
194
195 // Returns the explanation heard so far.
196 internal::string str() const { return ss_.str(); }
197
198 private:
199 ::std::stringstream ss_;
200
201 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
202};
203
shiqiane35fdd92008-12-10 05:08:54 +0000204// An internal class for implementing Matcher<T>, which will derive
205// from it. We put functionalities common to all Matcher<T>
206// specializations here to avoid code duplication.
207template <typename T>
208class MatcherBase {
209 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000210 // Returns true iff the matcher matches x; also explains the match
211 // result to 'listener'.
212 bool MatchAndExplain(T x, MatchResultListener* listener) const {
213 return impl_->MatchAndExplain(x, listener);
214 }
215
shiqiane35fdd92008-12-10 05:08:54 +0000216 // Returns true iff this matcher matches x.
zhanyong.wan82113312010-01-08 21:55:40 +0000217 bool Matches(T x) const {
218 DummyMatchResultListener dummy;
219 return MatchAndExplain(x, &dummy);
220 }
shiqiane35fdd92008-12-10 05:08:54 +0000221
222 // Describes this matcher to an ostream.
223 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
224
225 // Describes the negation of this matcher to an ostream.
226 void DescribeNegationTo(::std::ostream* os) const {
227 impl_->DescribeNegationTo(os);
228 }
229
230 // Explains why x matches, or doesn't match, the matcher.
231 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000232 StreamMatchResultListener listener(os);
233 MatchAndExplain(x, &listener);
shiqiane35fdd92008-12-10 05:08:54 +0000234 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000235
shiqiane35fdd92008-12-10 05:08:54 +0000236 protected:
237 MatcherBase() {}
238
239 // Constructs a matcher from its implementation.
240 explicit MatcherBase(const MatcherInterface<T>* impl)
241 : impl_(impl) {}
242
243 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000244
shiqiane35fdd92008-12-10 05:08:54 +0000245 private:
246 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
247 // interfaces. The former dynamically allocates a chunk of memory
248 // to hold the reference count, while the latter tracks all
249 // references using a circular linked list without allocating
250 // memory. It has been observed that linked_ptr performs better in
251 // typical scenarios. However, shared_ptr can out-perform
252 // linked_ptr when there are many more uses of the copy constructor
253 // than the default constructor.
254 //
255 // If performance becomes a problem, we should see if using
256 // shared_ptr helps.
257 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
258};
259
shiqiane35fdd92008-12-10 05:08:54 +0000260} // namespace internal
261
262// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
263// object that can check whether a value of type T matches. The
264// implementation of Matcher<T> is just a linked_ptr to const
265// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
266// from Matcher!
267template <typename T>
268class Matcher : public internal::MatcherBase<T> {
269 public:
vladlosev88032d82010-11-17 23:29:21 +0000270 // Constructs a null matcher. Needed for storing Matcher objects in STL
271 // containers. A default-constructed matcher is not yet initialized. You
272 // cannot use it until a valid value has been assigned to it.
shiqiane35fdd92008-12-10 05:08:54 +0000273 Matcher() {}
274
275 // Constructs a matcher from its implementation.
276 explicit Matcher(const MatcherInterface<T>* impl)
277 : internal::MatcherBase<T>(impl) {}
278
zhanyong.wan18490652009-05-11 18:54:08 +0000279 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000280 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
281 Matcher(T value); // NOLINT
282};
283
284// The following two specializations allow the user to write str
285// instead of Eq(str) and "foo" instead of Eq("foo") when a string
286// matcher is expected.
287template <>
vladlosev587c1b32011-05-20 00:42:22 +0000288class GTEST_API_ Matcher<const internal::string&>
shiqiane35fdd92008-12-10 05:08:54 +0000289 : public internal::MatcherBase<const internal::string&> {
290 public:
291 Matcher() {}
292
293 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
294 : internal::MatcherBase<const 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
304template <>
vladlosev587c1b32011-05-20 00:42:22 +0000305class GTEST_API_ Matcher<internal::string>
shiqiane35fdd92008-12-10 05:08:54 +0000306 : public internal::MatcherBase<internal::string> {
307 public:
308 Matcher() {}
309
310 explicit Matcher(const MatcherInterface<internal::string>* impl)
311 : internal::MatcherBase<internal::string>(impl) {}
312
313 // Allows the user to write str instead of Eq(str) sometimes, where
314 // str is a string object.
315 Matcher(const internal::string& s); // NOLINT
316
317 // Allows the user to write "foo" instead of Eq("foo") sometimes.
318 Matcher(const char* s); // NOLINT
319};
320
321// The PolymorphicMatcher class template makes it easy to implement a
322// polymorphic matcher (i.e. a matcher that can match values of more
323// than one type, e.g. Eq(n) and NotNull()).
324//
zhanyong.wandb22c222010-01-28 21:52:29 +0000325// To define a polymorphic matcher, a user should provide an Impl
326// class that has a DescribeTo() method and a DescribeNegationTo()
327// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000328//
zhanyong.wandb22c222010-01-28 21:52:29 +0000329// bool MatchAndExplain(const Value& value,
330// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000331//
332// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000333template <class Impl>
334class PolymorphicMatcher {
335 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000336 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000337
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000338 // Returns a mutable reference to the underlying matcher
339 // implementation object.
340 Impl& mutable_impl() { return impl_; }
341
342 // Returns an immutable reference to the underlying matcher
343 // implementation object.
344 const Impl& impl() const { return impl_; }
345
shiqiane35fdd92008-12-10 05:08:54 +0000346 template <typename T>
347 operator Matcher<T>() const {
348 return Matcher<T>(new MonomorphicImpl<T>(impl_));
349 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000350
shiqiane35fdd92008-12-10 05:08:54 +0000351 private:
352 template <typename T>
353 class MonomorphicImpl : public MatcherInterface<T> {
354 public:
355 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
356
shiqiane35fdd92008-12-10 05:08:54 +0000357 virtual void DescribeTo(::std::ostream* os) const {
358 impl_.DescribeTo(os);
359 }
360
361 virtual void DescribeNegationTo(::std::ostream* os) const {
362 impl_.DescribeNegationTo(os);
363 }
364
zhanyong.wan82113312010-01-08 21:55:40 +0000365 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000366 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000367 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000368
shiqiane35fdd92008-12-10 05:08:54 +0000369 private:
370 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000371
372 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000373 };
374
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000375 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000376
377 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000378};
379
380// Creates a matcher from its implementation. This is easier to use
381// than the Matcher<T> constructor as it doesn't require you to
382// explicitly write the template argument, e.g.
383//
384// MakeMatcher(foo);
385// vs
386// Matcher<const string&>(foo);
387template <typename T>
388inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
389 return Matcher<T>(impl);
390};
391
392// Creates a polymorphic matcher from its implementation. This is
393// easier to use than the PolymorphicMatcher<Impl> constructor as it
394// doesn't require you to explicitly write the template argument, e.g.
395//
396// MakePolymorphicMatcher(foo);
397// vs
398// PolymorphicMatcher<TypeOfFoo>(foo);
399template <class Impl>
400inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
401 return PolymorphicMatcher<Impl>(impl);
402}
403
jgm79a367e2012-04-10 16:02:11 +0000404// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
405// and MUST NOT BE USED IN USER CODE!!!
406namespace internal {
407
408// The MatcherCastImpl class template is a helper for implementing
409// MatcherCast(). We need this helper in order to partially
410// specialize the implementation of MatcherCast() (C++ allows
411// class/struct templates to be partially specialized, but not
412// function templates.).
413
414// This general version is used when MatcherCast()'s argument is a
415// polymorphic matcher (i.e. something that can be converted to a
416// Matcher but is not one yet; for example, Eq(value)) or a value (for
417// example, "hello").
418template <typename T, typename M>
419class MatcherCastImpl {
420 public:
421 static Matcher<T> Cast(M polymorphic_matcher_or_value) {
422 // M can be a polymorhic matcher, in which case we want to use
423 // its conversion operator to create Matcher<T>. Or it can be a value
424 // that should be passed to the Matcher<T>'s constructor.
425 //
426 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
427 // polymorphic matcher because it'll be ambiguous if T has an implicit
428 // constructor from M (this usually happens when T has an implicit
429 // constructor from any type).
430 //
431 // It won't work to unconditionally implict_cast
432 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
433 // a user-defined conversion from M to T if one exists (assuming M is
434 // a value).
435 return CastImpl(
436 polymorphic_matcher_or_value,
437 BooleanConstant<
438 internal::ImplicitlyConvertible<M, Matcher<T> >::value>());
439 }
440
441 private:
442 static Matcher<T> CastImpl(M value, BooleanConstant<false>) {
443 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
444 // matcher. It must be a value then. Use direct initialization to create
445 // a matcher.
446 return Matcher<T>(ImplicitCast_<T>(value));
447 }
448
449 static Matcher<T> CastImpl(M polymorphic_matcher_or_value,
450 BooleanConstant<true>) {
451 // M is implicitly convertible to Matcher<T>, which means that either
452 // M is a polymorhpic matcher or Matcher<T> has an implicit constructor
453 // from M. In both cases using the implicit conversion will produce a
454 // matcher.
455 //
456 // Even if T has an implicit constructor from M, it won't be called because
457 // creating Matcher<T> would require a chain of two user-defined conversions
458 // (first to create T from M and then to create Matcher<T> from T).
459 return polymorphic_matcher_or_value;
460 }
461};
462
463// This more specialized version is used when MatcherCast()'s argument
464// is already a Matcher. This only compiles when type T can be
465// statically converted to type U.
466template <typename T, typename U>
467class MatcherCastImpl<T, Matcher<U> > {
468 public:
469 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
470 return Matcher<T>(new Impl(source_matcher));
471 }
472
473 private:
474 class Impl : public MatcherInterface<T> {
475 public:
476 explicit Impl(const Matcher<U>& source_matcher)
477 : source_matcher_(source_matcher) {}
478
479 // We delegate the matching logic to the source matcher.
480 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
481 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
482 }
483
484 virtual void DescribeTo(::std::ostream* os) const {
485 source_matcher_.DescribeTo(os);
486 }
487
488 virtual void DescribeNegationTo(::std::ostream* os) const {
489 source_matcher_.DescribeNegationTo(os);
490 }
491
492 private:
493 const Matcher<U> source_matcher_;
494
495 GTEST_DISALLOW_ASSIGN_(Impl);
496 };
497};
498
499// This even more specialized version is used for efficiently casting
500// a matcher to its own type.
501template <typename T>
502class MatcherCastImpl<T, Matcher<T> > {
503 public:
504 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
505};
506
507} // namespace internal
508
shiqiane35fdd92008-12-10 05:08:54 +0000509// In order to be safe and clear, casting between different matcher
510// types is done explicitly via MatcherCast<T>(m), which takes a
511// matcher m and returns a Matcher<T>. It compiles only when T can be
512// statically converted to the argument type of m.
513template <typename T, typename M>
jgm79a367e2012-04-10 16:02:11 +0000514inline Matcher<T> MatcherCast(M matcher) {
515 return internal::MatcherCastImpl<T, M>::Cast(matcher);
516}
shiqiane35fdd92008-12-10 05:08:54 +0000517
zhanyong.wan18490652009-05-11 18:54:08 +0000518// Implements SafeMatcherCast().
519//
zhanyong.wan95b12332009-09-25 18:55:50 +0000520// We use an intermediate class to do the actual safe casting as Nokia's
521// Symbian compiler cannot decide between
522// template <T, M> ... (M) and
523// template <T, U> ... (const Matcher<U>&)
524// for function templates but can for member function templates.
525template <typename T>
526class SafeMatcherCastImpl {
527 public:
jgm79a367e2012-04-10 16:02:11 +0000528 // This overload handles polymorphic matchers and values only since
529 // monomorphic matchers are handled by the next one.
zhanyong.wan95b12332009-09-25 18:55:50 +0000530 template <typename M>
jgm79a367e2012-04-10 16:02:11 +0000531 static inline Matcher<T> Cast(M polymorphic_matcher_or_value) {
532 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
zhanyong.wan95b12332009-09-25 18:55:50 +0000533 }
zhanyong.wan18490652009-05-11 18:54:08 +0000534
zhanyong.wan95b12332009-09-25 18:55:50 +0000535 // This overload handles monomorphic matchers.
536 //
537 // In general, if type T can be implicitly converted to type U, we can
538 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
539 // contravariant): just keep a copy of the original Matcher<U>, convert the
540 // argument from type T to U, and then pass it to the underlying Matcher<U>.
541 // The only exception is when U is a reference and T is not, as the
542 // underlying Matcher<U> may be interested in the argument's address, which
543 // is not preserved in the conversion from T to U.
544 template <typename U>
545 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
546 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000547 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000548 T_must_be_implicitly_convertible_to_U);
549 // Enforce that we are not converting a non-reference type T to a reference
550 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000551 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000552 internal::is_reference<T>::value || !internal::is_reference<U>::value,
553 cannot_convert_non_referentce_arg_to_reference);
554 // In case both T and U are arithmetic types, enforce that the
555 // conversion is not lossy.
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000556 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
557 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000558 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
559 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000560 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000561 kTIsOther || kUIsOther ||
562 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
563 conversion_of_arithmetic_types_must_be_lossless);
564 return MatcherCast<T>(matcher);
565 }
566};
567
568template <typename T, typename M>
569inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
570 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000571}
572
shiqiane35fdd92008-12-10 05:08:54 +0000573// A<T>() returns a matcher that matches any value of type T.
574template <typename T>
575Matcher<T> A();
576
577// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
578// and MUST NOT BE USED IN USER CODE!!!
579namespace internal {
580
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000581// If the explanation is not empty, prints it to the ostream.
582inline void PrintIfNotEmpty(const internal::string& explanation,
583 std::ostream* os) {
584 if (explanation != "" && os != NULL) {
585 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000586 }
587}
588
zhanyong.wan736baa82010-09-27 17:44:16 +0000589// Returns true if the given type name is easy to read by a human.
590// This is used to decide whether printing the type of a value might
591// be helpful.
592inline bool IsReadableTypeName(const string& type_name) {
593 // We consider a type name readable if it's short or doesn't contain
594 // a template or function type.
595 return (type_name.length() <= 20 ||
596 type_name.find_first_of("<(") == string::npos);
597}
598
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000599// Matches the value against the given matcher, prints the value and explains
600// the match result to the listener. Returns the match result.
601// 'listener' must not be NULL.
602// Value cannot be passed by const reference, because some matchers take a
603// non-const argument.
604template <typename Value, typename T>
605bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
606 MatchResultListener* listener) {
607 if (!listener->IsInterested()) {
608 // If the listener is not interested, we do not need to construct the
609 // inner explanation.
610 return matcher.Matches(value);
611 }
612
613 StringMatchResultListener inner_listener;
614 const bool match = matcher.MatchAndExplain(value, &inner_listener);
615
616 UniversalPrint(value, listener->stream());
zhanyong.wan736baa82010-09-27 17:44:16 +0000617#if GTEST_HAS_RTTI
618 const string& type_name = GetTypeName<Value>();
619 if (IsReadableTypeName(type_name))
620 *listener->stream() << " (of type " << type_name << ")";
621#endif
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000622 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000623
624 return match;
625}
626
shiqiane35fdd92008-12-10 05:08:54 +0000627// An internal helper class for doing compile-time loop on a tuple's
628// fields.
629template <size_t N>
630class TuplePrefix {
631 public:
632 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
633 // iff the first N fields of matcher_tuple matches the first N
634 // fields of value_tuple, respectively.
635 template <typename MatcherTuple, typename ValueTuple>
636 static bool Matches(const MatcherTuple& matcher_tuple,
637 const ValueTuple& value_tuple) {
638 using ::std::tr1::get;
639 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
640 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
641 }
642
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000643 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000644 // describes failures in matching the first N fields of matchers
645 // against the first N fields of values. If there is no failure,
646 // nothing will be streamed to os.
647 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000648 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
649 const ValueTuple& values,
650 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000651 using ::std::tr1::tuple_element;
652 using ::std::tr1::get;
653
654 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000655 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000656
657 // Then describes the failure (if any) in the (N - 1)-th (0-based)
658 // field.
659 typename tuple_element<N - 1, MatcherTuple>::type matcher =
660 get<N - 1>(matchers);
661 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
662 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000663 StringMatchResultListener listener;
664 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000665 // TODO(wan): include in the message the name of the parameter
666 // as used in MOCK_METHOD*() when possible.
667 *os << " Expected arg #" << N - 1 << ": ";
668 get<N - 1>(matchers).DescribeTo(os);
669 *os << "\n Actual: ";
670 // We remove the reference in type Value to prevent the
671 // universal printer from printing the address of value, which
672 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000673 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000674 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000675 internal::UniversalPrint(value, os);
676 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000677 *os << "\n";
678 }
679 }
680};
681
682// The base case.
683template <>
684class TuplePrefix<0> {
685 public:
686 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000687 static bool Matches(const MatcherTuple& /* matcher_tuple */,
688 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000689 return true;
690 }
691
692 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000693 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
694 const ValueTuple& /* values */,
695 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000696};
697
698// TupleMatches(matcher_tuple, value_tuple) returns true iff all
699// matchers in matcher_tuple match the corresponding fields in
700// value_tuple. It is a compiler error if matcher_tuple and
701// value_tuple have different number of fields or incompatible field
702// types.
703template <typename MatcherTuple, typename ValueTuple>
704bool TupleMatches(const MatcherTuple& matcher_tuple,
705 const ValueTuple& value_tuple) {
706 using ::std::tr1::tuple_size;
707 // Makes sure that matcher_tuple and value_tuple have the same
708 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000709 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000710 tuple_size<ValueTuple>::value,
711 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000712 return TuplePrefix<tuple_size<ValueTuple>::value>::
713 Matches(matcher_tuple, value_tuple);
714}
715
716// Describes failures in matching matchers against values. If there
717// is no failure, nothing will be streamed to os.
718template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000719void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
720 const ValueTuple& values,
721 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000722 using ::std::tr1::tuple_size;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000723 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000724 matchers, values, os);
725}
726
shiqiane35fdd92008-12-10 05:08:54 +0000727// Implements A<T>().
728template <typename T>
729class AnyMatcherImpl : public MatcherInterface<T> {
730 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000731 virtual bool MatchAndExplain(
732 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000733 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
734 virtual void DescribeNegationTo(::std::ostream* os) const {
735 // This is mostly for completeness' safe, as it's not very useful
736 // to write Not(A<bool>()). However we cannot completely rule out
737 // such a possibility, and it doesn't hurt to be prepared.
738 *os << "never matches";
739 }
740};
741
742// Implements _, a matcher that matches any value of any
743// type. This is a polymorphic matcher, so we need a template type
744// conversion operator to make it appearing as a Matcher<T> for any
745// type T.
746class AnythingMatcher {
747 public:
748 template <typename T>
749 operator Matcher<T>() const { return A<T>(); }
750};
751
752// Implements a matcher that compares a given value with a
753// pre-supplied value using one of the ==, <=, <, etc, operators. The
754// two values being compared don't have to have the same type.
755//
756// The matcher defined here is polymorphic (for example, Eq(5) can be
757// used to match an int, a short, a double, etc). Therefore we use
758// a template type conversion operator in the implementation.
759//
760// We define this as a macro in order to eliminate duplicated source
761// code.
762//
763// The following template definition assumes that the Rhs parameter is
764// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000765#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_( \
766 name, op, relation, negated_relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000767 template <typename Rhs> class name##Matcher { \
768 public: \
769 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
770 template <typename Lhs> \
771 operator Matcher<Lhs>() const { \
772 return MakeMatcher(new Impl<Lhs>(rhs_)); \
773 } \
774 private: \
775 template <typename Lhs> \
776 class Impl : public MatcherInterface<Lhs> { \
777 public: \
778 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
zhanyong.wan82113312010-01-08 21:55:40 +0000779 virtual bool MatchAndExplain(\
780 Lhs lhs, MatchResultListener* /* listener */) const { \
781 return lhs op rhs_; \
782 } \
shiqiane35fdd92008-12-10 05:08:54 +0000783 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000784 *os << relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000785 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000786 } \
787 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000788 *os << negated_relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000789 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000790 } \
791 private: \
792 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000793 GTEST_DISALLOW_ASSIGN_(Impl); \
shiqiane35fdd92008-12-10 05:08:54 +0000794 }; \
795 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000796 GTEST_DISALLOW_ASSIGN_(name##Matcher); \
shiqiane35fdd92008-12-10 05:08:54 +0000797 }
798
799// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
800// respectively.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000801GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "is equal to", "isn't equal to");
802GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "is >=", "isn't >=");
803GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "is >", "isn't >");
804GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "is <=", "isn't <=");
805GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "is <", "isn't <");
806GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "isn't equal to", "is equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000807
zhanyong.wane0d051e2009-02-19 00:33:37 +0000808#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000809
vladlosev79b83502009-11-18 00:43:37 +0000810// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000811// pointer that is NULL.
812class IsNullMatcher {
813 public:
vladlosev79b83502009-11-18 00:43:37 +0000814 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000815 bool MatchAndExplain(const Pointer& p,
816 MatchResultListener* /* listener */) const {
817 return GetRawPointer(p) == NULL;
818 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000819
820 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
821 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000822 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000823 }
824};
825
vladlosev79b83502009-11-18 00:43:37 +0000826// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000827// pointer that is not NULL.
828class NotNullMatcher {
829 public:
vladlosev79b83502009-11-18 00:43:37 +0000830 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000831 bool MatchAndExplain(const Pointer& p,
832 MatchResultListener* /* listener */) const {
833 return GetRawPointer(p) != NULL;
834 }
shiqiane35fdd92008-12-10 05:08:54 +0000835
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000836 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +0000837 void DescribeNegationTo(::std::ostream* os) const {
838 *os << "is NULL";
839 }
840};
841
842// Ref(variable) matches any argument that is a reference to
843// 'variable'. This matcher is polymorphic as it can match any
844// super type of the type of 'variable'.
845//
846// The RefMatcher template class implements Ref(variable). It can
847// only be instantiated with a reference type. This prevents a user
848// from mistakenly using Ref(x) to match a non-reference function
849// argument. For example, the following will righteously cause a
850// compiler error:
851//
852// int n;
853// Matcher<int> m1 = Ref(n); // This won't compile.
854// Matcher<int&> m2 = Ref(n); // This will compile.
855template <typename T>
856class RefMatcher;
857
858template <typename T>
859class RefMatcher<T&> {
860 // Google Mock is a generic framework and thus needs to support
861 // mocking any function types, including those that take non-const
862 // reference arguments. Therefore the template parameter T (and
863 // Super below) can be instantiated to either a const type or a
864 // non-const type.
865 public:
866 // RefMatcher() takes a T& instead of const T&, as we want the
867 // compiler to catch using Ref(const_value) as a matcher for a
868 // non-const reference.
869 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
870
871 template <typename Super>
872 operator Matcher<Super&>() const {
873 // By passing object_ (type T&) to Impl(), which expects a Super&,
874 // we make sure that Super is a super type of T. In particular,
875 // this catches using Ref(const_value) as a matcher for a
876 // non-const reference, as you cannot implicitly convert a const
877 // reference to a non-const reference.
878 return MakeMatcher(new Impl<Super>(object_));
879 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000880
shiqiane35fdd92008-12-10 05:08:54 +0000881 private:
882 template <typename Super>
883 class Impl : public MatcherInterface<Super&> {
884 public:
885 explicit Impl(Super& x) : object_(x) {} // NOLINT
886
zhanyong.wandb22c222010-01-28 21:52:29 +0000887 // MatchAndExplain() takes a Super& (as opposed to const Super&)
888 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +0000889 virtual bool MatchAndExplain(
890 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000891 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +0000892 return &x == &object_;
893 }
shiqiane35fdd92008-12-10 05:08:54 +0000894
895 virtual void DescribeTo(::std::ostream* os) const {
896 *os << "references the variable ";
897 UniversalPrinter<Super&>::Print(object_, os);
898 }
899
900 virtual void DescribeNegationTo(::std::ostream* os) const {
901 *os << "does not reference the variable ";
902 UniversalPrinter<Super&>::Print(object_, os);
903 }
904
shiqiane35fdd92008-12-10 05:08:54 +0000905 private:
906 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000907
908 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000909 };
910
911 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000912
913 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000914};
915
916// Polymorphic helper functions for narrow and wide string matchers.
917inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
918 return String::CaseInsensitiveCStringEquals(lhs, rhs);
919}
920
921inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
922 const wchar_t* rhs) {
923 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
924}
925
926// String comparison for narrow or wide strings that can have embedded NUL
927// characters.
928template <typename StringType>
929bool CaseInsensitiveStringEquals(const StringType& s1,
930 const StringType& s2) {
931 // Are the heads equal?
932 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
933 return false;
934 }
935
936 // Skip the equal heads.
937 const typename StringType::value_type nul = 0;
938 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
939
940 // Are we at the end of either s1 or s2?
941 if (i1 == StringType::npos || i2 == StringType::npos) {
942 return i1 == i2;
943 }
944
945 // Are the tails equal?
946 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
947}
948
949// String matchers.
950
951// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
952template <typename StringType>
953class StrEqualityMatcher {
954 public:
shiqiane35fdd92008-12-10 05:08:54 +0000955 StrEqualityMatcher(const StringType& str, bool expect_eq,
956 bool case_sensitive)
957 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
958
jgm38513a82012-11-15 15:50:36 +0000959 // Accepts pointer types, particularly:
960 // const char*
961 // char*
962 // const wchar_t*
963 // wchar_t*
964 template <typename CharType>
965 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +0000966 if (s == NULL) {
967 return !expect_eq_;
968 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000969 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000970 }
971
jgm38513a82012-11-15 15:50:36 +0000972 // Matches anything that can convert to StringType.
973 //
974 // This is a template, not just a plain function with const StringType&,
975 // because StringPiece has some interfering non-explicit constructors.
976 template <typename MatcheeStringType>
977 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +0000978 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +0000979 const StringType& s2(s);
980 const bool eq = case_sensitive_ ? s2 == string_ :
981 CaseInsensitiveStringEquals(s2, string_);
shiqiane35fdd92008-12-10 05:08:54 +0000982 return expect_eq_ == eq;
983 }
984
985 void DescribeTo(::std::ostream* os) const {
986 DescribeToHelper(expect_eq_, os);
987 }
988
989 void DescribeNegationTo(::std::ostream* os) const {
990 DescribeToHelper(!expect_eq_, os);
991 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000992
shiqiane35fdd92008-12-10 05:08:54 +0000993 private:
994 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000995 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +0000996 *os << "equal to ";
997 if (!case_sensitive_) {
998 *os << "(ignoring case) ";
999 }
vladloseve2e8ba42010-05-13 18:16:03 +00001000 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001001 }
1002
1003 const StringType string_;
1004 const bool expect_eq_;
1005 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001006
1007 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001008};
1009
1010// Implements the polymorphic HasSubstr(substring) matcher, which
1011// can be used as a Matcher<T> as long as T can be converted to a
1012// string.
1013template <typename StringType>
1014class HasSubstrMatcher {
1015 public:
shiqiane35fdd92008-12-10 05:08:54 +00001016 explicit HasSubstrMatcher(const StringType& substring)
1017 : substring_(substring) {}
1018
jgm38513a82012-11-15 15:50:36 +00001019 // Accepts pointer types, particularly:
1020 // const char*
1021 // char*
1022 // const wchar_t*
1023 // wchar_t*
1024 template <typename CharType>
1025 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001026 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001027 }
1028
jgm38513a82012-11-15 15:50:36 +00001029 // Matches anything that can convert to StringType.
1030 //
1031 // This is a template, not just a plain function with const StringType&,
1032 // because StringPiece has some interfering non-explicit constructors.
1033 template <typename MatcheeStringType>
1034 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001035 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001036 const StringType& s2(s);
1037 return s2.find(substring_) != StringType::npos;
shiqiane35fdd92008-12-10 05:08:54 +00001038 }
1039
1040 // Describes what this matcher matches.
1041 void DescribeTo(::std::ostream* os) const {
1042 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001043 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001044 }
1045
1046 void DescribeNegationTo(::std::ostream* os) const {
1047 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001048 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001049 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001050
shiqiane35fdd92008-12-10 05:08:54 +00001051 private:
1052 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001053
1054 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001055};
1056
1057// Implements the polymorphic StartsWith(substring) matcher, which
1058// can be used as a Matcher<T> as long as T can be converted to a
1059// string.
1060template <typename StringType>
1061class StartsWithMatcher {
1062 public:
shiqiane35fdd92008-12-10 05:08:54 +00001063 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1064 }
1065
jgm38513a82012-11-15 15:50:36 +00001066 // Accepts pointer types, particularly:
1067 // const char*
1068 // char*
1069 // const wchar_t*
1070 // wchar_t*
1071 template <typename CharType>
1072 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001073 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001074 }
1075
jgm38513a82012-11-15 15:50:36 +00001076 // Matches anything that can convert to StringType.
1077 //
1078 // This is a template, not just a plain function with const StringType&,
1079 // because StringPiece has some interfering non-explicit constructors.
1080 template <typename MatcheeStringType>
1081 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001082 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001083 const StringType& s2(s);
1084 return s2.length() >= prefix_.length() &&
1085 s2.substr(0, prefix_.length()) == prefix_;
shiqiane35fdd92008-12-10 05:08:54 +00001086 }
1087
1088 void DescribeTo(::std::ostream* os) const {
1089 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001090 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001091 }
1092
1093 void DescribeNegationTo(::std::ostream* os) const {
1094 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001095 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001096 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001097
shiqiane35fdd92008-12-10 05:08:54 +00001098 private:
1099 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001100
1101 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001102};
1103
1104// Implements the polymorphic EndsWith(substring) matcher, which
1105// can be used as a Matcher<T> as long as T can be converted to a
1106// string.
1107template <typename StringType>
1108class EndsWithMatcher {
1109 public:
shiqiane35fdd92008-12-10 05:08:54 +00001110 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1111
jgm38513a82012-11-15 15:50:36 +00001112 // Accepts pointer types, particularly:
1113 // const char*
1114 // char*
1115 // const wchar_t*
1116 // wchar_t*
1117 template <typename CharType>
1118 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001119 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001120 }
1121
jgm38513a82012-11-15 15:50:36 +00001122 // Matches anything that can convert to StringType.
1123 //
1124 // This is a template, not just a plain function with const StringType&,
1125 // because StringPiece has some interfering non-explicit constructors.
1126 template <typename MatcheeStringType>
1127 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001128 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001129 const StringType& s2(s);
1130 return s2.length() >= suffix_.length() &&
1131 s2.substr(s2.length() - suffix_.length()) == suffix_;
shiqiane35fdd92008-12-10 05:08:54 +00001132 }
1133
1134 void DescribeTo(::std::ostream* os) const {
1135 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001136 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001137 }
1138
1139 void DescribeNegationTo(::std::ostream* os) const {
1140 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001141 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001142 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001143
shiqiane35fdd92008-12-10 05:08:54 +00001144 private:
1145 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001146
1147 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001148};
1149
shiqiane35fdd92008-12-10 05:08:54 +00001150// Implements polymorphic matchers MatchesRegex(regex) and
1151// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1152// T can be converted to a string.
1153class MatchesRegexMatcher {
1154 public:
1155 MatchesRegexMatcher(const RE* regex, bool full_match)
1156 : regex_(regex), full_match_(full_match) {}
1157
jgm38513a82012-11-15 15:50:36 +00001158 // Accepts pointer types, particularly:
1159 // const char*
1160 // char*
1161 // const wchar_t*
1162 // wchar_t*
1163 template <typename CharType>
1164 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001165 return s != NULL && MatchAndExplain(internal::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001166 }
1167
jgm38513a82012-11-15 15:50:36 +00001168 // Matches anything that can convert to internal::string.
1169 //
1170 // This is a template, not just a plain function with const internal::string&,
1171 // because StringPiece has some interfering non-explicit constructors.
1172 template <class MatcheeStringType>
1173 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001174 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001175 const internal::string& s2(s);
1176 return full_match_ ? RE::FullMatch(s2, *regex_) :
1177 RE::PartialMatch(s2, *regex_);
shiqiane35fdd92008-12-10 05:08:54 +00001178 }
1179
1180 void DescribeTo(::std::ostream* os) const {
1181 *os << (full_match_ ? "matches" : "contains")
1182 << " regular expression ";
1183 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1184 }
1185
1186 void DescribeNegationTo(::std::ostream* os) const {
1187 *os << "doesn't " << (full_match_ ? "match" : "contain")
1188 << " regular expression ";
1189 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1190 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001191
shiqiane35fdd92008-12-10 05:08:54 +00001192 private:
1193 const internal::linked_ptr<const RE> regex_;
1194 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001195
1196 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001197};
1198
shiqiane35fdd92008-12-10 05:08:54 +00001199// Implements a matcher that compares the two fields of a 2-tuple
1200// using one of the ==, <=, <, etc, operators. The two fields being
1201// compared don't have to have the same type.
1202//
1203// The matcher defined here is polymorphic (for example, Eq() can be
1204// used to match a tuple<int, short>, a tuple<const long&, double>,
1205// etc). Therefore we use a template type conversion operator in the
1206// implementation.
1207//
1208// We define this as a macro in order to eliminate duplicated source
1209// code.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001210#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +00001211 class name##2Matcher { \
1212 public: \
1213 template <typename T1, typename T2> \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001214 operator Matcher< ::std::tr1::tuple<T1, T2> >() const { \
1215 return MakeMatcher(new Impl< ::std::tr1::tuple<T1, T2> >); \
1216 } \
1217 template <typename T1, typename T2> \
shiqiane35fdd92008-12-10 05:08:54 +00001218 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001219 return MakeMatcher(new Impl<const ::std::tr1::tuple<T1, T2>&>); \
shiqiane35fdd92008-12-10 05:08:54 +00001220 } \
1221 private: \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001222 template <typename Tuple> \
1223 class Impl : public MatcherInterface<Tuple> { \
shiqiane35fdd92008-12-10 05:08:54 +00001224 public: \
zhanyong.wan82113312010-01-08 21:55:40 +00001225 virtual bool MatchAndExplain( \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001226 Tuple args, \
zhanyong.wan82113312010-01-08 21:55:40 +00001227 MatchResultListener* /* listener */) const { \
shiqiane35fdd92008-12-10 05:08:54 +00001228 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
1229 } \
1230 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001231 *os << "are " relation; \
shiqiane35fdd92008-12-10 05:08:54 +00001232 } \
1233 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001234 *os << "aren't " relation; \
shiqiane35fdd92008-12-10 05:08:54 +00001235 } \
1236 }; \
1237 }
1238
1239// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001240GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "an equal pair");
1241GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1242 Ge, >=, "a pair where the first >= the second");
1243GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1244 Gt, >, "a pair where the first > the second");
1245GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1246 Le, <=, "a pair where the first <= the second");
1247GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1248 Lt, <, "a pair where the first < the second");
1249GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=, "an unequal pair");
shiqiane35fdd92008-12-10 05:08:54 +00001250
zhanyong.wane0d051e2009-02-19 00:33:37 +00001251#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +00001252
zhanyong.wanc6a41232009-05-13 23:38:40 +00001253// Implements the Not(...) matcher for a particular argument type T.
1254// We do not nest it inside the NotMatcher class template, as that
1255// will prevent different instantiations of NotMatcher from sharing
1256// the same NotMatcherImpl<T> class.
1257template <typename T>
1258class NotMatcherImpl : public MatcherInterface<T> {
1259 public:
1260 explicit NotMatcherImpl(const Matcher<T>& matcher)
1261 : matcher_(matcher) {}
1262
zhanyong.wan82113312010-01-08 21:55:40 +00001263 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1264 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001265 }
1266
1267 virtual void DescribeTo(::std::ostream* os) const {
1268 matcher_.DescribeNegationTo(os);
1269 }
1270
1271 virtual void DescribeNegationTo(::std::ostream* os) const {
1272 matcher_.DescribeTo(os);
1273 }
1274
zhanyong.wanc6a41232009-05-13 23:38:40 +00001275 private:
1276 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001277
1278 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001279};
1280
shiqiane35fdd92008-12-10 05:08:54 +00001281// Implements the Not(m) matcher, which matches a value that doesn't
1282// match matcher m.
1283template <typename InnerMatcher>
1284class NotMatcher {
1285 public:
1286 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1287
1288 // This template type conversion operator allows Not(m) to be used
1289 // to match any type m can match.
1290 template <typename T>
1291 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001292 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001293 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001294
shiqiane35fdd92008-12-10 05:08:54 +00001295 private:
shiqiane35fdd92008-12-10 05:08:54 +00001296 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001297
1298 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001299};
1300
zhanyong.wanc6a41232009-05-13 23:38:40 +00001301// Implements the AllOf(m1, m2) matcher for a particular argument type
1302// T. We do not nest it inside the BothOfMatcher class template, as
1303// that will prevent different instantiations of BothOfMatcher from
1304// sharing the same BothOfMatcherImpl<T> class.
1305template <typename T>
1306class BothOfMatcherImpl : public MatcherInterface<T> {
1307 public:
1308 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1309 : matcher1_(matcher1), matcher2_(matcher2) {}
1310
zhanyong.wanc6a41232009-05-13 23:38:40 +00001311 virtual void DescribeTo(::std::ostream* os) const {
1312 *os << "(";
1313 matcher1_.DescribeTo(os);
1314 *os << ") and (";
1315 matcher2_.DescribeTo(os);
1316 *os << ")";
1317 }
1318
1319 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001320 *os << "(";
1321 matcher1_.DescribeNegationTo(os);
1322 *os << ") or (";
1323 matcher2_.DescribeNegationTo(os);
1324 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001325 }
1326
zhanyong.wan82113312010-01-08 21:55:40 +00001327 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1328 // If either matcher1_ or matcher2_ doesn't match x, we only need
1329 // to explain why one of them fails.
1330 StringMatchResultListener listener1;
1331 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1332 *listener << listener1.str();
1333 return false;
1334 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001335
zhanyong.wan82113312010-01-08 21:55:40 +00001336 StringMatchResultListener listener2;
1337 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1338 *listener << listener2.str();
1339 return false;
1340 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001341
zhanyong.wan82113312010-01-08 21:55:40 +00001342 // Otherwise we need to explain why *both* of them match.
1343 const internal::string s1 = listener1.str();
1344 const internal::string s2 = listener2.str();
1345
1346 if (s1 == "") {
1347 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001348 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001349 *listener << s1;
1350 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001351 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001352 }
1353 }
zhanyong.wan82113312010-01-08 21:55:40 +00001354 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001355 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001356
zhanyong.wanc6a41232009-05-13 23:38:40 +00001357 private:
1358 const Matcher<T> matcher1_;
1359 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001360
1361 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001362};
1363
shiqiane35fdd92008-12-10 05:08:54 +00001364// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1365// matches a value that matches all of the matchers m_1, ..., and m_n.
1366template <typename Matcher1, typename Matcher2>
1367class BothOfMatcher {
1368 public:
1369 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1370 : matcher1_(matcher1), matcher2_(matcher2) {}
1371
1372 // This template type conversion operator allows a
1373 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1374 // both Matcher1 and Matcher2 can match.
1375 template <typename T>
1376 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001377 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1378 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001379 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001380
shiqiane35fdd92008-12-10 05:08:54 +00001381 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001382 Matcher1 matcher1_;
1383 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001384
1385 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001386};
shiqiane35fdd92008-12-10 05:08:54 +00001387
zhanyong.wanc6a41232009-05-13 23:38:40 +00001388// Implements the AnyOf(m1, m2) matcher for a particular argument type
1389// T. We do not nest it inside the AnyOfMatcher class template, as
1390// that will prevent different instantiations of AnyOfMatcher from
1391// sharing the same EitherOfMatcherImpl<T> class.
1392template <typename T>
1393class EitherOfMatcherImpl : public MatcherInterface<T> {
1394 public:
1395 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1396 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001397
zhanyong.wanc6a41232009-05-13 23:38:40 +00001398 virtual void DescribeTo(::std::ostream* os) const {
1399 *os << "(";
1400 matcher1_.DescribeTo(os);
1401 *os << ") or (";
1402 matcher2_.DescribeTo(os);
1403 *os << ")";
1404 }
shiqiane35fdd92008-12-10 05:08:54 +00001405
zhanyong.wanc6a41232009-05-13 23:38:40 +00001406 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001407 *os << "(";
1408 matcher1_.DescribeNegationTo(os);
1409 *os << ") and (";
1410 matcher2_.DescribeNegationTo(os);
1411 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001412 }
shiqiane35fdd92008-12-10 05:08:54 +00001413
zhanyong.wan82113312010-01-08 21:55:40 +00001414 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1415 // If either matcher1_ or matcher2_ matches x, we just need to
1416 // explain why *one* of them matches.
1417 StringMatchResultListener listener1;
1418 if (matcher1_.MatchAndExplain(x, &listener1)) {
1419 *listener << listener1.str();
1420 return true;
1421 }
1422
1423 StringMatchResultListener listener2;
1424 if (matcher2_.MatchAndExplain(x, &listener2)) {
1425 *listener << listener2.str();
1426 return true;
1427 }
1428
1429 // Otherwise we need to explain why *both* of them fail.
1430 const internal::string s1 = listener1.str();
1431 const internal::string s2 = listener2.str();
1432
1433 if (s1 == "") {
1434 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001435 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001436 *listener << s1;
1437 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001438 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001439 }
1440 }
zhanyong.wan82113312010-01-08 21:55:40 +00001441 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001442 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001443
zhanyong.wanc6a41232009-05-13 23:38:40 +00001444 private:
1445 const Matcher<T> matcher1_;
1446 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001447
1448 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001449};
1450
1451// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1452// matches a value that matches at least one of the matchers m_1, ...,
1453// and m_n.
1454template <typename Matcher1, typename Matcher2>
1455class EitherOfMatcher {
1456 public:
1457 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1458 : matcher1_(matcher1), matcher2_(matcher2) {}
1459
1460 // This template type conversion operator allows a
1461 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1462 // both Matcher1 and Matcher2 can match.
1463 template <typename T>
1464 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001465 return Matcher<T>(new EitherOfMatcherImpl<T>(
1466 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001467 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001468
shiqiane35fdd92008-12-10 05:08:54 +00001469 private:
shiqiane35fdd92008-12-10 05:08:54 +00001470 Matcher1 matcher1_;
1471 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001472
1473 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001474};
1475
1476// Used for implementing Truly(pred), which turns a predicate into a
1477// matcher.
1478template <typename Predicate>
1479class TrulyMatcher {
1480 public:
1481 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1482
1483 // This method template allows Truly(pred) to be used as a matcher
1484 // for type T where T is the argument type of predicate 'pred'. The
1485 // argument is passed by reference as the predicate may be
1486 // interested in the address of the argument.
1487 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001488 bool MatchAndExplain(T& x, // NOLINT
1489 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00001490 // Without the if-statement, MSVC sometimes warns about converting
1491 // a value to bool (warning 4800).
1492 //
1493 // We cannot write 'return !!predicate_(x);' as that doesn't work
1494 // when predicate_(x) returns a class convertible to bool but
1495 // having no operator!().
1496 if (predicate_(x))
1497 return true;
1498 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001499 }
1500
1501 void DescribeTo(::std::ostream* os) const {
1502 *os << "satisfies the given predicate";
1503 }
1504
1505 void DescribeNegationTo(::std::ostream* os) const {
1506 *os << "doesn't satisfy the given predicate";
1507 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001508
shiqiane35fdd92008-12-10 05:08:54 +00001509 private:
1510 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001511
1512 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001513};
1514
1515// Used for implementing Matches(matcher), which turns a matcher into
1516// a predicate.
1517template <typename M>
1518class MatcherAsPredicate {
1519 public:
1520 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1521
1522 // This template operator() allows Matches(m) to be used as a
1523 // predicate on type T where m is a matcher on type T.
1524 //
1525 // The argument x is passed by reference instead of by value, as
1526 // some matcher may be interested in its address (e.g. as in
1527 // Matches(Ref(n))(x)).
1528 template <typename T>
1529 bool operator()(const T& x) const {
1530 // We let matcher_ commit to a particular type here instead of
1531 // when the MatcherAsPredicate object was constructed. This
1532 // allows us to write Matches(m) where m is a polymorphic matcher
1533 // (e.g. Eq(5)).
1534 //
1535 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1536 // compile when matcher_ has type Matcher<const T&>; if we write
1537 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1538 // when matcher_ has type Matcher<T>; if we just write
1539 // matcher_.Matches(x), it won't compile when matcher_ is
1540 // polymorphic, e.g. Eq(5).
1541 //
1542 // MatcherCast<const T&>() is necessary for making the code work
1543 // in all of the above situations.
1544 return MatcherCast<const T&>(matcher_).Matches(x);
1545 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001546
shiqiane35fdd92008-12-10 05:08:54 +00001547 private:
1548 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001549
1550 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001551};
1552
1553// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1554// argument M must be a type that can be converted to a matcher.
1555template <typename M>
1556class PredicateFormatterFromMatcher {
1557 public:
1558 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1559
1560 // This template () operator allows a PredicateFormatterFromMatcher
1561 // object to act as a predicate-formatter suitable for using with
1562 // Google Test's EXPECT_PRED_FORMAT1() macro.
1563 template <typename T>
1564 AssertionResult operator()(const char* value_text, const T& x) const {
1565 // We convert matcher_ to a Matcher<const T&> *now* instead of
1566 // when the PredicateFormatterFromMatcher object was constructed,
1567 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1568 // know which type to instantiate it to until we actually see the
1569 // type of x here.
1570 //
1571 // We write MatcherCast<const T&>(matcher_) instead of
1572 // Matcher<const T&>(matcher_), as the latter won't compile when
1573 // matcher_ has type Matcher<T> (e.g. An<int>()).
1574 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001575 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001576 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001577 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001578
1579 ::std::stringstream ss;
1580 ss << "Value of: " << value_text << "\n"
1581 << "Expected: ";
1582 matcher.DescribeTo(&ss);
1583 ss << "\n Actual: " << listener.str();
1584 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001585 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001586
shiqiane35fdd92008-12-10 05:08:54 +00001587 private:
1588 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001589
1590 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001591};
1592
1593// A helper function for converting a matcher to a predicate-formatter
1594// without the user needing to explicitly write the type. This is
1595// used for implementing ASSERT_THAT() and EXPECT_THAT().
1596template <typename M>
1597inline PredicateFormatterFromMatcher<M>
1598MakePredicateFormatterFromMatcher(const M& matcher) {
1599 return PredicateFormatterFromMatcher<M>(matcher);
1600}
1601
1602// Implements the polymorphic floating point equality matcher, which
1603// matches two float values using ULP-based approximation. The
1604// template is meant to be instantiated with FloatType being either
1605// float or double.
1606template <typename FloatType>
1607class FloatingEqMatcher {
1608 public:
1609 // Constructor for FloatingEqMatcher.
1610 // The matcher's input will be compared with rhs. The matcher treats two
1611 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1612 // equality comparisons between NANs will always return false.
1613 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1614 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1615
1616 // Implements floating point equality matcher as a Matcher<T>.
1617 template <typename T>
1618 class Impl : public MatcherInterface<T> {
1619 public:
1620 Impl(FloatType rhs, bool nan_eq_nan) :
1621 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1622
zhanyong.wan82113312010-01-08 21:55:40 +00001623 virtual bool MatchAndExplain(T value,
1624 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001625 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1626
1627 // Compares NaNs first, if nan_eq_nan_ is true.
1628 if (nan_eq_nan_ && lhs.is_nan()) {
1629 return rhs.is_nan();
1630 }
1631
1632 return lhs.AlmostEquals(rhs);
1633 }
1634
1635 virtual void DescribeTo(::std::ostream* os) const {
1636 // os->precision() returns the previously set precision, which we
1637 // store to restore the ostream to its original configuration
1638 // after outputting.
1639 const ::std::streamsize old_precision = os->precision(
1640 ::std::numeric_limits<FloatType>::digits10 + 2);
1641 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1642 if (nan_eq_nan_) {
1643 *os << "is NaN";
1644 } else {
1645 *os << "never matches";
1646 }
1647 } else {
1648 *os << "is approximately " << rhs_;
1649 }
1650 os->precision(old_precision);
1651 }
1652
1653 virtual void DescribeNegationTo(::std::ostream* os) const {
1654 // As before, get original precision.
1655 const ::std::streamsize old_precision = os->precision(
1656 ::std::numeric_limits<FloatType>::digits10 + 2);
1657 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1658 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001659 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00001660 } else {
1661 *os << "is anything";
1662 }
1663 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001664 *os << "isn't approximately " << rhs_;
shiqiane35fdd92008-12-10 05:08:54 +00001665 }
1666 // Restore original precision.
1667 os->precision(old_precision);
1668 }
1669
1670 private:
1671 const FloatType rhs_;
1672 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001673
1674 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001675 };
1676
1677 // The following 3 type conversion operators allow FloatEq(rhs) and
1678 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1679 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1680 // (While Google's C++ coding style doesn't allow arguments passed
1681 // by non-const reference, we may see them in code not conforming to
1682 // the style. Therefore Google Mock needs to support them.)
1683 operator Matcher<FloatType>() const {
1684 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1685 }
1686
1687 operator Matcher<const FloatType&>() const {
1688 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1689 }
1690
1691 operator Matcher<FloatType&>() const {
1692 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1693 }
jgm79a367e2012-04-10 16:02:11 +00001694
shiqiane35fdd92008-12-10 05:08:54 +00001695 private:
1696 const FloatType rhs_;
1697 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001698
1699 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001700};
1701
1702// Implements the Pointee(m) matcher for matching a pointer whose
1703// pointee matches matcher m. The pointer can be either raw or smart.
1704template <typename InnerMatcher>
1705class PointeeMatcher {
1706 public:
1707 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1708
1709 // This type conversion operator template allows Pointee(m) to be
1710 // used as a matcher for any pointer type whose pointee type is
1711 // compatible with the inner matcher, where type Pointer can be
1712 // either a raw pointer or a smart pointer.
1713 //
1714 // The reason we do this instead of relying on
1715 // MakePolymorphicMatcher() is that the latter is not flexible
1716 // enough for implementing the DescribeTo() method of Pointee().
1717 template <typename Pointer>
1718 operator Matcher<Pointer>() const {
1719 return MakeMatcher(new Impl<Pointer>(matcher_));
1720 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001721
shiqiane35fdd92008-12-10 05:08:54 +00001722 private:
1723 // The monomorphic implementation that works for a particular pointer type.
1724 template <typename Pointer>
1725 class Impl : public MatcherInterface<Pointer> {
1726 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00001727 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
1728 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001729
1730 explicit Impl(const InnerMatcher& matcher)
1731 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1732
shiqiane35fdd92008-12-10 05:08:54 +00001733 virtual void DescribeTo(::std::ostream* os) const {
1734 *os << "points to a value that ";
1735 matcher_.DescribeTo(os);
1736 }
1737
1738 virtual void DescribeNegationTo(::std::ostream* os) const {
1739 *os << "does not point to a value that ";
1740 matcher_.DescribeTo(os);
1741 }
1742
zhanyong.wan82113312010-01-08 21:55:40 +00001743 virtual bool MatchAndExplain(Pointer pointer,
1744 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001745 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00001746 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001747
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001748 *listener << "which points to ";
1749 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001750 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001751
shiqiane35fdd92008-12-10 05:08:54 +00001752 private:
1753 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001754
1755 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001756 };
1757
1758 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001759
1760 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001761};
1762
1763// Implements the Field() matcher for matching a field (i.e. member
1764// variable) of an object.
1765template <typename Class, typename FieldType>
1766class FieldMatcher {
1767 public:
1768 FieldMatcher(FieldType Class::*field,
1769 const Matcher<const FieldType&>& matcher)
1770 : field_(field), matcher_(matcher) {}
1771
shiqiane35fdd92008-12-10 05:08:54 +00001772 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001773 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001774 matcher_.DescribeTo(os);
1775 }
1776
1777 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001778 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001779 matcher_.DescribeNegationTo(os);
1780 }
1781
zhanyong.wandb22c222010-01-28 21:52:29 +00001782 template <typename T>
1783 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
1784 return MatchAndExplainImpl(
1785 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00001786 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00001787 value, listener);
1788 }
1789
1790 private:
1791 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001792 // Symbian's C++ compiler choose which overload to use. Its type is
1793 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001794 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1795 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001796 *listener << "whose given field is ";
1797 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001798 }
1799
zhanyong.wandb22c222010-01-28 21:52:29 +00001800 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1801 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001802 if (p == NULL)
1803 return false;
1804
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001805 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001806 // Since *p has a field, it must be a class/struct/union type and
1807 // thus cannot be a pointer. Therefore we pass false_type() as
1808 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001809 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001810 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001811
shiqiane35fdd92008-12-10 05:08:54 +00001812 const FieldType Class::*field_;
1813 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001814
1815 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001816};
1817
shiqiane35fdd92008-12-10 05:08:54 +00001818// Implements the Property() matcher for matching a property
1819// (i.e. return value of a getter method) of an object.
1820template <typename Class, typename PropertyType>
1821class PropertyMatcher {
1822 public:
1823 // The property may have a reference type, so 'const PropertyType&'
1824 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00001825 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00001826 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00001827 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001828
1829 PropertyMatcher(PropertyType (Class::*property)() const,
1830 const Matcher<RefToConstProperty>& matcher)
1831 : property_(property), matcher_(matcher) {}
1832
shiqiane35fdd92008-12-10 05:08:54 +00001833 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001834 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001835 matcher_.DescribeTo(os);
1836 }
1837
1838 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001839 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001840 matcher_.DescribeNegationTo(os);
1841 }
1842
zhanyong.wandb22c222010-01-28 21:52:29 +00001843 template <typename T>
1844 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
1845 return MatchAndExplainImpl(
1846 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00001847 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00001848 value, listener);
1849 }
1850
1851 private:
1852 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001853 // Symbian's C++ compiler choose which overload to use. Its type is
1854 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001855 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1856 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001857 *listener << "whose given property is ";
1858 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
1859 // which takes a non-const reference as argument.
1860 RefToConstProperty result = (obj.*property_)();
1861 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001862 }
1863
zhanyong.wandb22c222010-01-28 21:52:29 +00001864 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1865 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001866 if (p == NULL)
1867 return false;
1868
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001869 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001870 // Since *p has a property method, it must be a class/struct/union
1871 // type and thus cannot be a pointer. Therefore we pass
1872 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001873 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001874 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001875
shiqiane35fdd92008-12-10 05:08:54 +00001876 PropertyType (Class::*property_)() const;
1877 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001878
1879 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001880};
1881
shiqiane35fdd92008-12-10 05:08:54 +00001882// Type traits specifying various features of different functors for ResultOf.
1883// The default template specifies features for functor objects.
1884// Functor classes have to typedef argument_type and result_type
1885// to be compatible with ResultOf.
1886template <typename Functor>
1887struct CallableTraits {
1888 typedef typename Functor::result_type ResultType;
1889 typedef Functor StorageType;
1890
zhanyong.wan32de5f52009-12-23 00:13:23 +00001891 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00001892 template <typename T>
1893 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1894};
1895
1896// Specialization for function pointers.
1897template <typename ArgType, typename ResType>
1898struct CallableTraits<ResType(*)(ArgType)> {
1899 typedef ResType ResultType;
1900 typedef ResType(*StorageType)(ArgType);
1901
1902 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001903 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00001904 << "NULL function pointer is passed into ResultOf().";
1905 }
1906 template <typename T>
1907 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1908 return (*f)(arg);
1909 }
1910};
1911
1912// Implements the ResultOf() matcher for matching a return value of a
1913// unary function of an object.
1914template <typename Callable>
1915class ResultOfMatcher {
1916 public:
1917 typedef typename CallableTraits<Callable>::ResultType ResultType;
1918
1919 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1920 : callable_(callable), matcher_(matcher) {
1921 CallableTraits<Callable>::CheckIsValid(callable_);
1922 }
1923
1924 template <typename T>
1925 operator Matcher<T>() const {
1926 return Matcher<T>(new Impl<T>(callable_, matcher_));
1927 }
1928
1929 private:
1930 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1931
1932 template <typename T>
1933 class Impl : public MatcherInterface<T> {
1934 public:
1935 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1936 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00001937
1938 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001939 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001940 matcher_.DescribeTo(os);
1941 }
1942
1943 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001944 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001945 matcher_.DescribeNegationTo(os);
1946 }
1947
zhanyong.wan82113312010-01-08 21:55:40 +00001948 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001949 *listener << "which is mapped by the given callable to ";
1950 // Cannot pass the return value (for example, int) to
1951 // MatchPrintAndExplain, which takes a non-const reference as argument.
1952 ResultType result =
1953 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
1954 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001955 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001956
shiqiane35fdd92008-12-10 05:08:54 +00001957 private:
1958 // Functors often define operator() as non-const method even though
1959 // they are actualy stateless. But we need to use them even when
1960 // 'this' is a const pointer. It's the user's responsibility not to
1961 // use stateful callables with ResultOf(), which does't guarantee
1962 // how many times the callable will be invoked.
1963 mutable CallableStorageType callable_;
1964 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001965
1966 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001967 }; // class Impl
1968
1969 const CallableStorageType callable_;
1970 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001971
1972 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001973};
1974
zhanyong.wan6a896b52009-01-16 01:13:50 +00001975// Implements an equality matcher for any STL-style container whose elements
1976// support ==. This matcher is like Eq(), but its failure explanations provide
1977// more detailed information that is useful when the container is used as a set.
1978// The failure message reports elements that are in one of the operands but not
1979// the other. The failure messages do not report duplicate or out-of-order
1980// elements in the containers (which don't properly matter to sets, but can
1981// occur if the containers are vectors or lists, for example).
1982//
1983// Uses the container's const_iterator, value_type, operator ==,
1984// begin(), and end().
1985template <typename Container>
1986class ContainerEqMatcher {
1987 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00001988 typedef internal::StlContainerView<Container> View;
1989 typedef typename View::type StlContainer;
1990 typedef typename View::const_reference StlContainerReference;
1991
1992 // We make a copy of rhs in case the elements in it are modified
1993 // after this matcher is created.
1994 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
1995 // Makes sure the user doesn't instantiate this class template
1996 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001997 (void)testing::StaticAssertTypeEq<Container,
1998 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00001999 }
2000
zhanyong.wan6a896b52009-01-16 01:13:50 +00002001 void DescribeTo(::std::ostream* os) const {
2002 *os << "equals ";
vladloseve2e8ba42010-05-13 18:16:03 +00002003 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002004 }
2005 void DescribeNegationTo(::std::ostream* os) const {
2006 *os << "does not equal ";
vladloseve2e8ba42010-05-13 18:16:03 +00002007 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002008 }
2009
zhanyong.wanb8243162009-06-04 05:48:20 +00002010 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00002011 bool MatchAndExplain(const LhsContainer& lhs,
2012 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002013 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00002014 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002015 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00002016 LhsView;
2017 typedef typename LhsView::type LhsStlContainer;
2018 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00002019 if (lhs_stl_container == rhs_)
2020 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002021
zhanyong.wane122e452010-01-12 09:03:52 +00002022 ::std::ostream* const os = listener->stream();
2023 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002024 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002025 bool printed_header = false;
2026 for (typename LhsStlContainer::const_iterator it =
2027 lhs_stl_container.begin();
2028 it != lhs_stl_container.end(); ++it) {
2029 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
2030 rhs_.end()) {
2031 if (printed_header) {
2032 *os << ", ";
2033 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002034 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002035 printed_header = true;
2036 }
vladloseve2e8ba42010-05-13 18:16:03 +00002037 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002038 }
zhanyong.wane122e452010-01-12 09:03:52 +00002039 }
2040
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002041 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002042 bool printed_header2 = false;
2043 for (typename StlContainer::const_iterator it = rhs_.begin();
2044 it != rhs_.end(); ++it) {
2045 if (internal::ArrayAwareFind(
2046 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2047 lhs_stl_container.end()) {
2048 if (printed_header2) {
2049 *os << ", ";
2050 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002051 *os << (printed_header ? ",\nand" : "which")
2052 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002053 printed_header2 = true;
2054 }
vladloseve2e8ba42010-05-13 18:16:03 +00002055 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002056 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002057 }
2058 }
2059
zhanyong.wane122e452010-01-12 09:03:52 +00002060 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002061 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002062
zhanyong.wan6a896b52009-01-16 01:13:50 +00002063 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00002064 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002065
2066 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002067};
2068
zhanyong.wan898725c2011-09-16 16:45:39 +00002069// A comparator functor that uses the < operator to compare two values.
2070struct LessComparator {
2071 template <typename T, typename U>
2072 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2073};
2074
2075// Implements WhenSortedBy(comparator, container_matcher).
2076template <typename Comparator, typename ContainerMatcher>
2077class WhenSortedByMatcher {
2078 public:
2079 WhenSortedByMatcher(const Comparator& comparator,
2080 const ContainerMatcher& matcher)
2081 : comparator_(comparator), matcher_(matcher) {}
2082
2083 template <typename LhsContainer>
2084 operator Matcher<LhsContainer>() const {
2085 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2086 }
2087
2088 template <typename LhsContainer>
2089 class Impl : public MatcherInterface<LhsContainer> {
2090 public:
2091 typedef internal::StlContainerView<
2092 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2093 typedef typename LhsView::type LhsStlContainer;
2094 typedef typename LhsView::const_reference LhsStlContainerReference;
2095 typedef typename LhsStlContainer::value_type LhsValue;
2096
2097 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2098 : comparator_(comparator), matcher_(matcher) {}
2099
2100 virtual void DescribeTo(::std::ostream* os) const {
2101 *os << "(when sorted) ";
2102 matcher_.DescribeTo(os);
2103 }
2104
2105 virtual void DescribeNegationTo(::std::ostream* os) const {
2106 *os << "(when sorted) ";
2107 matcher_.DescribeNegationTo(os);
2108 }
2109
2110 virtual bool MatchAndExplain(LhsContainer lhs,
2111 MatchResultListener* listener) const {
2112 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2113 std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2114 lhs_stl_container.end());
2115 std::sort(sorted_container.begin(), sorted_container.end(), comparator_);
2116
2117 if (!listener->IsInterested()) {
2118 // If the listener is not interested, we do not need to
2119 // construct the inner explanation.
2120 return matcher_.Matches(sorted_container);
2121 }
2122
2123 *listener << "which is ";
2124 UniversalPrint(sorted_container, listener->stream());
2125 *listener << " when sorted";
2126
2127 StringMatchResultListener inner_listener;
2128 const bool match = matcher_.MatchAndExplain(sorted_container,
2129 &inner_listener);
2130 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2131 return match;
2132 }
2133
2134 private:
2135 const Comparator comparator_;
2136 const Matcher<const std::vector<LhsValue>&> matcher_;
2137
2138 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2139 };
2140
2141 private:
2142 const Comparator comparator_;
2143 const ContainerMatcher matcher_;
2144
2145 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2146};
2147
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002148// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2149// must be able to be safely cast to Matcher<tuple<const T1&, const
2150// T2&> >, where T1 and T2 are the types of elements in the LHS
2151// container and the RHS container respectively.
2152template <typename TupleMatcher, typename RhsContainer>
2153class PointwiseMatcher {
2154 public:
2155 typedef internal::StlContainerView<RhsContainer> RhsView;
2156 typedef typename RhsView::type RhsStlContainer;
2157 typedef typename RhsStlContainer::value_type RhsValue;
2158
2159 // Like ContainerEq, we make a copy of rhs in case the elements in
2160 // it are modified after this matcher is created.
2161 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2162 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2163 // Makes sure the user doesn't instantiate this class template
2164 // with a const or reference type.
2165 (void)testing::StaticAssertTypeEq<RhsContainer,
2166 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2167 }
2168
2169 template <typename LhsContainer>
2170 operator Matcher<LhsContainer>() const {
2171 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2172 }
2173
2174 template <typename LhsContainer>
2175 class Impl : public MatcherInterface<LhsContainer> {
2176 public:
2177 typedef internal::StlContainerView<
2178 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2179 typedef typename LhsView::type LhsStlContainer;
2180 typedef typename LhsView::const_reference LhsStlContainerReference;
2181 typedef typename LhsStlContainer::value_type LhsValue;
2182 // We pass the LHS value and the RHS value to the inner matcher by
2183 // reference, as they may be expensive to copy. We must use tuple
2184 // instead of pair here, as a pair cannot hold references (C++ 98,
2185 // 20.2.2 [lib.pairs]).
2186 typedef std::tr1::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
2187
2188 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2189 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2190 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2191 rhs_(rhs) {}
2192
2193 virtual void DescribeTo(::std::ostream* os) const {
2194 *os << "contains " << rhs_.size()
2195 << " values, where each value and its corresponding value in ";
2196 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2197 *os << " ";
2198 mono_tuple_matcher_.DescribeTo(os);
2199 }
2200 virtual void DescribeNegationTo(::std::ostream* os) const {
2201 *os << "doesn't contain exactly " << rhs_.size()
2202 << " values, or contains a value x at some index i"
2203 << " where x and the i-th value of ";
2204 UniversalPrint(rhs_, os);
2205 *os << " ";
2206 mono_tuple_matcher_.DescribeNegationTo(os);
2207 }
2208
2209 virtual bool MatchAndExplain(LhsContainer lhs,
2210 MatchResultListener* listener) const {
2211 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2212 const size_t actual_size = lhs_stl_container.size();
2213 if (actual_size != rhs_.size()) {
2214 *listener << "which contains " << actual_size << " values";
2215 return false;
2216 }
2217
2218 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2219 typename RhsStlContainer::const_iterator right = rhs_.begin();
2220 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2221 const InnerMatcherArg value_pair(*left, *right);
2222
2223 if (listener->IsInterested()) {
2224 StringMatchResultListener inner_listener;
2225 if (!mono_tuple_matcher_.MatchAndExplain(
2226 value_pair, &inner_listener)) {
2227 *listener << "where the value pair (";
2228 UniversalPrint(*left, listener->stream());
2229 *listener << ", ";
2230 UniversalPrint(*right, listener->stream());
2231 *listener << ") at index #" << i << " don't match";
2232 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2233 return false;
2234 }
2235 } else {
2236 if (!mono_tuple_matcher_.Matches(value_pair))
2237 return false;
2238 }
2239 }
2240
2241 return true;
2242 }
2243
2244 private:
2245 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2246 const RhsStlContainer rhs_;
2247
2248 GTEST_DISALLOW_ASSIGN_(Impl);
2249 };
2250
2251 private:
2252 const TupleMatcher tuple_matcher_;
2253 const RhsStlContainer rhs_;
2254
2255 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2256};
2257
zhanyong.wan33605ba2010-04-22 23:37:47 +00002258// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002259template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002260class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002261 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002262 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002263 typedef StlContainerView<RawContainer> View;
2264 typedef typename View::type StlContainer;
2265 typedef typename View::const_reference StlContainerReference;
2266 typedef typename StlContainer::value_type Element;
2267
2268 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002269 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002270 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002271 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002272
zhanyong.wan33605ba2010-04-22 23:37:47 +00002273 // Checks whether:
2274 // * All elements in the container match, if all_elements_should_match.
2275 // * Any element in the container matches, if !all_elements_should_match.
2276 bool MatchAndExplainImpl(bool all_elements_should_match,
2277 Container container,
2278 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002279 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002280 size_t i = 0;
2281 for (typename StlContainer::const_iterator it = stl_container.begin();
2282 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002283 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00002284 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2285
2286 if (matches != all_elements_should_match) {
2287 *listener << "whose element #" << i
2288 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002289 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00002290 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00002291 }
2292 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00002293 return all_elements_should_match;
2294 }
2295
2296 protected:
2297 const Matcher<const Element&> inner_matcher_;
2298
2299 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2300};
2301
2302// Implements Contains(element_matcher) for the given argument type Container.
2303// Symmetric to EachMatcherImpl.
2304template <typename Container>
2305class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2306 public:
2307 template <typename InnerMatcher>
2308 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2309 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2310
2311 // Describes what this matcher does.
2312 virtual void DescribeTo(::std::ostream* os) const {
2313 *os << "contains at least one element that ";
2314 this->inner_matcher_.DescribeTo(os);
2315 }
2316
2317 virtual void DescribeNegationTo(::std::ostream* os) const {
2318 *os << "doesn't contain any element that ";
2319 this->inner_matcher_.DescribeTo(os);
2320 }
2321
2322 virtual bool MatchAndExplain(Container container,
2323 MatchResultListener* listener) const {
2324 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002325 }
2326
2327 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002328 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002329};
2330
zhanyong.wan33605ba2010-04-22 23:37:47 +00002331// Implements Each(element_matcher) for the given argument type Container.
2332// Symmetric to ContainsMatcherImpl.
2333template <typename Container>
2334class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2335 public:
2336 template <typename InnerMatcher>
2337 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2338 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2339
2340 // Describes what this matcher does.
2341 virtual void DescribeTo(::std::ostream* os) const {
2342 *os << "only contains elements that ";
2343 this->inner_matcher_.DescribeTo(os);
2344 }
2345
2346 virtual void DescribeNegationTo(::std::ostream* os) const {
2347 *os << "contains some element that ";
2348 this->inner_matcher_.DescribeNegationTo(os);
2349 }
2350
2351 virtual bool MatchAndExplain(Container container,
2352 MatchResultListener* listener) const {
2353 return this->MatchAndExplainImpl(true, container, listener);
2354 }
2355
2356 private:
2357 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2358};
2359
zhanyong.wanb8243162009-06-04 05:48:20 +00002360// Implements polymorphic Contains(element_matcher).
2361template <typename M>
2362class ContainsMatcher {
2363 public:
2364 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2365
2366 template <typename Container>
2367 operator Matcher<Container>() const {
2368 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2369 }
2370
2371 private:
2372 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002373
2374 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002375};
2376
zhanyong.wan33605ba2010-04-22 23:37:47 +00002377// Implements polymorphic Each(element_matcher).
2378template <typename M>
2379class EachMatcher {
2380 public:
2381 explicit EachMatcher(M m) : inner_matcher_(m) {}
2382
2383 template <typename Container>
2384 operator Matcher<Container>() const {
2385 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2386 }
2387
2388 private:
2389 const M inner_matcher_;
2390
2391 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2392};
2393
zhanyong.wanb5937da2009-07-16 20:26:41 +00002394// Implements Key(inner_matcher) for the given argument pair type.
2395// Key(inner_matcher) matches an std::pair whose 'first' field matches
2396// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2397// std::map that contains at least one element whose key is >= 5.
2398template <typename PairType>
2399class KeyMatcherImpl : public MatcherInterface<PairType> {
2400 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002401 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002402 typedef typename RawPairType::first_type KeyType;
2403
2404 template <typename InnerMatcher>
2405 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2406 : inner_matcher_(
2407 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2408 }
2409
2410 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002411 virtual bool MatchAndExplain(PairType key_value,
2412 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002413 StringMatchResultListener inner_listener;
2414 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2415 &inner_listener);
2416 const internal::string explanation = inner_listener.str();
2417 if (explanation != "") {
2418 *listener << "whose first field is a value " << explanation;
2419 }
2420 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002421 }
2422
2423 // Describes what this matcher does.
2424 virtual void DescribeTo(::std::ostream* os) const {
2425 *os << "has a key that ";
2426 inner_matcher_.DescribeTo(os);
2427 }
2428
2429 // Describes what the negation of this matcher does.
2430 virtual void DescribeNegationTo(::std::ostream* os) const {
2431 *os << "doesn't have a key that ";
2432 inner_matcher_.DescribeTo(os);
2433 }
2434
zhanyong.wanb5937da2009-07-16 20:26:41 +00002435 private:
2436 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002437
2438 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002439};
2440
2441// Implements polymorphic Key(matcher_for_key).
2442template <typename M>
2443class KeyMatcher {
2444 public:
2445 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2446
2447 template <typename PairType>
2448 operator Matcher<PairType>() const {
2449 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2450 }
2451
2452 private:
2453 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002454
2455 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002456};
2457
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002458// Implements Pair(first_matcher, second_matcher) for the given argument pair
2459// type with its two matchers. See Pair() function below.
2460template <typename PairType>
2461class PairMatcherImpl : public MatcherInterface<PairType> {
2462 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002463 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002464 typedef typename RawPairType::first_type FirstType;
2465 typedef typename RawPairType::second_type SecondType;
2466
2467 template <typename FirstMatcher, typename SecondMatcher>
2468 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2469 : first_matcher_(
2470 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2471 second_matcher_(
2472 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2473 }
2474
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002475 // Describes what this matcher does.
2476 virtual void DescribeTo(::std::ostream* os) const {
2477 *os << "has a first field that ";
2478 first_matcher_.DescribeTo(os);
2479 *os << ", and has a second field that ";
2480 second_matcher_.DescribeTo(os);
2481 }
2482
2483 // Describes what the negation of this matcher does.
2484 virtual void DescribeNegationTo(::std::ostream* os) const {
2485 *os << "has a first field that ";
2486 first_matcher_.DescribeNegationTo(os);
2487 *os << ", or has a second field that ";
2488 second_matcher_.DescribeNegationTo(os);
2489 }
2490
zhanyong.wan82113312010-01-08 21:55:40 +00002491 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2492 // matches second_matcher.
2493 virtual bool MatchAndExplain(PairType a_pair,
2494 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002495 if (!listener->IsInterested()) {
2496 // If the listener is not interested, we don't need to construct the
2497 // explanation.
2498 return first_matcher_.Matches(a_pair.first) &&
2499 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00002500 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002501 StringMatchResultListener first_inner_listener;
2502 if (!first_matcher_.MatchAndExplain(a_pair.first,
2503 &first_inner_listener)) {
2504 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002505 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002506 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002507 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002508 StringMatchResultListener second_inner_listener;
2509 if (!second_matcher_.MatchAndExplain(a_pair.second,
2510 &second_inner_listener)) {
2511 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002512 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002513 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002514 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002515 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
2516 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00002517 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002518 }
2519
2520 private:
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002521 void ExplainSuccess(const internal::string& first_explanation,
2522 const internal::string& second_explanation,
2523 MatchResultListener* listener) const {
2524 *listener << "whose both fields match";
2525 if (first_explanation != "") {
2526 *listener << ", where the first field is a value " << first_explanation;
2527 }
2528 if (second_explanation != "") {
2529 *listener << ", ";
2530 if (first_explanation != "") {
2531 *listener << "and ";
2532 } else {
2533 *listener << "where ";
2534 }
2535 *listener << "the second field is a value " << second_explanation;
2536 }
2537 }
2538
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002539 const Matcher<const FirstType&> first_matcher_;
2540 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002541
2542 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002543};
2544
2545// Implements polymorphic Pair(first_matcher, second_matcher).
2546template <typename FirstMatcher, typename SecondMatcher>
2547class PairMatcher {
2548 public:
2549 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2550 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2551
2552 template <typename PairType>
2553 operator Matcher<PairType> () const {
2554 return MakeMatcher(
2555 new PairMatcherImpl<PairType>(
2556 first_matcher_, second_matcher_));
2557 }
2558
2559 private:
2560 const FirstMatcher first_matcher_;
2561 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002562
2563 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002564};
2565
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002566// Implements ElementsAre() and ElementsAreArray().
2567template <typename Container>
2568class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2569 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002570 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002571 typedef internal::StlContainerView<RawContainer> View;
2572 typedef typename View::type StlContainer;
2573 typedef typename View::const_reference StlContainerReference;
2574 typedef typename StlContainer::value_type Element;
2575
2576 // Constructs the matcher from a sequence of element values or
2577 // element matchers.
2578 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00002579 ElementsAreMatcherImpl(InputIter first, InputIter last) {
2580 while (first != last) {
2581 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002582 }
2583 }
2584
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002585 // Describes what this matcher does.
2586 virtual void DescribeTo(::std::ostream* os) const {
2587 if (count() == 0) {
2588 *os << "is empty";
2589 } else if (count() == 1) {
2590 *os << "has 1 element that ";
2591 matchers_[0].DescribeTo(os);
2592 } else {
2593 *os << "has " << Elements(count()) << " where\n";
2594 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002595 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002596 matchers_[i].DescribeTo(os);
2597 if (i + 1 < count()) {
2598 *os << ",\n";
2599 }
2600 }
2601 }
2602 }
2603
2604 // Describes what the negation of this matcher does.
2605 virtual void DescribeNegationTo(::std::ostream* os) const {
2606 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002607 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002608 return;
2609 }
2610
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002611 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002612 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002613 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002614 matchers_[i].DescribeNegationTo(os);
2615 if (i + 1 < count()) {
2616 *os << ", or\n";
2617 }
2618 }
2619 }
2620
zhanyong.wan82113312010-01-08 21:55:40 +00002621 virtual bool MatchAndExplain(Container container,
2622 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002623 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002624 const size_t actual_count = stl_container.size();
2625 if (actual_count != count()) {
2626 // The element count doesn't match. If the container is empty,
2627 // there's no need to explain anything as Google Mock already
2628 // prints the empty container. Otherwise we just need to show
2629 // how many elements there actually are.
2630 if (actual_count != 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002631 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002632 }
zhanyong.wan82113312010-01-08 21:55:40 +00002633 return false;
2634 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002635
zhanyong.wan82113312010-01-08 21:55:40 +00002636 typename StlContainer::const_iterator it = stl_container.begin();
2637 // explanations[i] is the explanation of the element at index i.
2638 std::vector<internal::string> explanations(count());
2639 for (size_t i = 0; i != count(); ++it, ++i) {
2640 StringMatchResultListener s;
2641 if (matchers_[i].MatchAndExplain(*it, &s)) {
2642 explanations[i] = s.str();
2643 } else {
2644 // The container has the right size but the i-th element
2645 // doesn't match its expectation.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002646 *listener << "whose element #" << i << " doesn't match";
2647 PrintIfNotEmpty(s.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002648 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002649 }
2650 }
zhanyong.wan82113312010-01-08 21:55:40 +00002651
2652 // Every element matches its expectation. We need to explain why
2653 // (the obvious ones can be skipped).
zhanyong.wan82113312010-01-08 21:55:40 +00002654 bool reason_printed = false;
2655 for (size_t i = 0; i != count(); ++i) {
2656 const internal::string& s = explanations[i];
2657 if (!s.empty()) {
2658 if (reason_printed) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002659 *listener << ",\nand ";
zhanyong.wan82113312010-01-08 21:55:40 +00002660 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002661 *listener << "whose element #" << i << " matches, " << s;
zhanyong.wan82113312010-01-08 21:55:40 +00002662 reason_printed = true;
2663 }
2664 }
2665
2666 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002667 }
2668
2669 private:
2670 static Message Elements(size_t count) {
2671 return Message() << count << (count == 1 ? " element" : " elements");
2672 }
2673
2674 size_t count() const { return matchers_.size(); }
2675 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002676
2677 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002678};
2679
2680// Implements ElementsAre() of 0 arguments.
2681class ElementsAreMatcher0 {
2682 public:
2683 ElementsAreMatcher0() {}
2684
2685 template <typename Container>
2686 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002687 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002688 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2689 Element;
2690
2691 const Matcher<const Element&>* const matchers = NULL;
jgm38513a82012-11-15 15:50:36 +00002692 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers,
2693 matchers));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002694 }
2695};
2696
2697// Implements ElementsAreArray().
2698template <typename T>
2699class ElementsAreArrayMatcher {
2700 public:
jgm38513a82012-11-15 15:50:36 +00002701 template <typename Iter>
2702 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002703
2704 template <typename Container>
2705 operator Matcher<Container>() const {
jgm38513a82012-11-15 15:50:36 +00002706 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
2707 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002708 }
2709
2710 private:
jgm38513a82012-11-15 15:50:36 +00002711 const std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002712
2713 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002714};
2715
zhanyong.wanb4140802010-06-08 22:53:57 +00002716// Returns the description for a matcher defined using the MATCHER*()
2717// macro where the user-supplied description string is "", if
2718// 'negation' is false; otherwise returns the description of the
2719// negation of the matcher. 'param_values' contains a list of strings
2720// that are the print-out of the matcher's parameters.
vladlosev587c1b32011-05-20 00:42:22 +00002721GTEST_API_ string FormatMatcherDescription(bool negation,
2722 const char* matcher_name,
2723 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002724
shiqiane35fdd92008-12-10 05:08:54 +00002725} // namespace internal
2726
shiqiane35fdd92008-12-10 05:08:54 +00002727// _ is a matcher that matches anything of any type.
2728//
2729// This definition is fine as:
2730//
2731// 1. The C++ standard permits using the name _ in a namespace that
2732// is not the global namespace or ::std.
2733// 2. The AnythingMatcher class has no data member or constructor,
2734// so it's OK to create global variables of this type.
2735// 3. c-style has approved of using _ in this case.
2736const internal::AnythingMatcher _ = {};
2737// Creates a matcher that matches any value of the given type T.
2738template <typename T>
2739inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2740
2741// Creates a matcher that matches any value of the given type T.
2742template <typename T>
2743inline Matcher<T> An() { return A<T>(); }
2744
2745// Creates a polymorphic matcher that matches anything equal to x.
2746// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2747// wouldn't compile.
2748template <typename T>
2749inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2750
2751// Constructs a Matcher<T> from a 'value' of type T. The constructed
2752// matcher matches any value that's equal to 'value'.
2753template <typename T>
2754Matcher<T>::Matcher(T value) { *this = Eq(value); }
2755
2756// Creates a monomorphic matcher that matches anything with type Lhs
2757// and equal to rhs. A user may need to use this instead of Eq(...)
2758// in order to resolve an overloading ambiguity.
2759//
2760// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2761// or Matcher<T>(x), but more readable than the latter.
2762//
2763// We could define similar monomorphic matchers for other comparison
2764// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2765// it yet as those are used much less than Eq() in practice. A user
2766// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2767// for example.
2768template <typename Lhs, typename Rhs>
2769inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2770
2771// Creates a polymorphic matcher that matches anything >= x.
2772template <typename Rhs>
2773inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2774 return internal::GeMatcher<Rhs>(x);
2775}
2776
2777// Creates a polymorphic matcher that matches anything > x.
2778template <typename Rhs>
2779inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2780 return internal::GtMatcher<Rhs>(x);
2781}
2782
2783// Creates a polymorphic matcher that matches anything <= x.
2784template <typename Rhs>
2785inline internal::LeMatcher<Rhs> Le(Rhs x) {
2786 return internal::LeMatcher<Rhs>(x);
2787}
2788
2789// Creates a polymorphic matcher that matches anything < x.
2790template <typename Rhs>
2791inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2792 return internal::LtMatcher<Rhs>(x);
2793}
2794
2795// Creates a polymorphic matcher that matches anything != x.
2796template <typename Rhs>
2797inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2798 return internal::NeMatcher<Rhs>(x);
2799}
2800
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002801// Creates a polymorphic matcher that matches any NULL pointer.
2802inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2803 return MakePolymorphicMatcher(internal::IsNullMatcher());
2804}
2805
shiqiane35fdd92008-12-10 05:08:54 +00002806// Creates a polymorphic matcher that matches any non-NULL pointer.
2807// This is convenient as Not(NULL) doesn't compile (the compiler
2808// thinks that that expression is comparing a pointer with an integer).
2809inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2810 return MakePolymorphicMatcher(internal::NotNullMatcher());
2811}
2812
2813// Creates a polymorphic matcher that matches any argument that
2814// references variable x.
2815template <typename T>
2816inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2817 return internal::RefMatcher<T&>(x);
2818}
2819
2820// Creates a matcher that matches any double argument approximately
2821// equal to rhs, where two NANs are considered unequal.
2822inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2823 return internal::FloatingEqMatcher<double>(rhs, false);
2824}
2825
2826// Creates a matcher that matches any double argument approximately
2827// equal to rhs, including NaN values when rhs is NaN.
2828inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2829 return internal::FloatingEqMatcher<double>(rhs, true);
2830}
2831
2832// Creates a matcher that matches any float argument approximately
2833// equal to rhs, where two NANs are considered unequal.
2834inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2835 return internal::FloatingEqMatcher<float>(rhs, false);
2836}
2837
2838// Creates a matcher that matches any double argument approximately
2839// equal to rhs, including NaN values when rhs is NaN.
2840inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2841 return internal::FloatingEqMatcher<float>(rhs, true);
2842}
2843
2844// Creates a matcher that matches a pointer (raw or smart) that points
2845// to a value that matches inner_matcher.
2846template <typename InnerMatcher>
2847inline internal::PointeeMatcher<InnerMatcher> Pointee(
2848 const InnerMatcher& inner_matcher) {
2849 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2850}
2851
2852// Creates a matcher that matches an object whose given field matches
2853// 'matcher'. For example,
2854// Field(&Foo::number, Ge(5))
2855// matches a Foo object x iff x.number >= 5.
2856template <typename Class, typename FieldType, typename FieldMatcher>
2857inline PolymorphicMatcher<
2858 internal::FieldMatcher<Class, FieldType> > Field(
2859 FieldType Class::*field, const FieldMatcher& matcher) {
2860 return MakePolymorphicMatcher(
2861 internal::FieldMatcher<Class, FieldType>(
2862 field, MatcherCast<const FieldType&>(matcher)));
2863 // The call to MatcherCast() is required for supporting inner
2864 // matchers of compatible types. For example, it allows
2865 // Field(&Foo::bar, m)
2866 // to compile where bar is an int32 and m is a matcher for int64.
2867}
2868
2869// Creates a matcher that matches an object whose given property
2870// matches 'matcher'. For example,
2871// Property(&Foo::str, StartsWith("hi"))
2872// matches a Foo object x iff x.str() starts with "hi".
2873template <typename Class, typename PropertyType, typename PropertyMatcher>
2874inline PolymorphicMatcher<
2875 internal::PropertyMatcher<Class, PropertyType> > Property(
2876 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2877 return MakePolymorphicMatcher(
2878 internal::PropertyMatcher<Class, PropertyType>(
2879 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00002880 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002881 // The call to MatcherCast() is required for supporting inner
2882 // matchers of compatible types. For example, it allows
2883 // Property(&Foo::bar, m)
2884 // to compile where bar() returns an int32 and m is a matcher for int64.
2885}
2886
2887// Creates a matcher that matches an object iff the result of applying
2888// a callable to x matches 'matcher'.
2889// For example,
2890// ResultOf(f, StartsWith("hi"))
2891// matches a Foo object x iff f(x) starts with "hi".
2892// callable parameter can be a function, function pointer, or a functor.
2893// Callable has to satisfy the following conditions:
2894// * It is required to keep no state affecting the results of
2895// the calls on it and make no assumptions about how many calls
2896// will be made. Any state it keeps must be protected from the
2897// concurrent access.
2898// * If it is a function object, it has to define type result_type.
2899// We recommend deriving your functor classes from std::unary_function.
2900template <typename Callable, typename ResultOfMatcher>
2901internal::ResultOfMatcher<Callable> ResultOf(
2902 Callable callable, const ResultOfMatcher& matcher) {
2903 return internal::ResultOfMatcher<Callable>(
2904 callable,
2905 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2906 matcher));
2907 // The call to MatcherCast() is required for supporting inner
2908 // matchers of compatible types. For example, it allows
2909 // ResultOf(Function, m)
2910 // to compile where Function() returns an int32 and m is a matcher for int64.
2911}
2912
2913// String matchers.
2914
2915// Matches a string equal to str.
2916inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2917 StrEq(const internal::string& str) {
2918 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2919 str, true, true));
2920}
2921
2922// Matches a string not equal to str.
2923inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2924 StrNe(const internal::string& str) {
2925 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2926 str, false, true));
2927}
2928
2929// Matches a string equal to str, ignoring case.
2930inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2931 StrCaseEq(const internal::string& str) {
2932 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2933 str, true, false));
2934}
2935
2936// Matches a string not equal to str, ignoring case.
2937inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2938 StrCaseNe(const internal::string& str) {
2939 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2940 str, false, false));
2941}
2942
2943// Creates a matcher that matches any string, std::string, or C string
2944// that contains the given substring.
2945inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2946 HasSubstr(const internal::string& substring) {
2947 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
2948 substring));
2949}
2950
2951// Matches a string that starts with 'prefix' (case-sensitive).
2952inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
2953 StartsWith(const internal::string& prefix) {
2954 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
2955 prefix));
2956}
2957
2958// Matches a string that ends with 'suffix' (case-sensitive).
2959inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
2960 EndsWith(const internal::string& suffix) {
2961 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
2962 suffix));
2963}
2964
shiqiane35fdd92008-12-10 05:08:54 +00002965// Matches a string that fully matches regular expression 'regex'.
2966// The matcher takes ownership of 'regex'.
2967inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2968 const internal::RE* regex) {
2969 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2970}
2971inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2972 const internal::string& regex) {
2973 return MatchesRegex(new internal::RE(regex));
2974}
2975
2976// Matches a string that contains regular expression 'regex'.
2977// The matcher takes ownership of 'regex'.
2978inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2979 const internal::RE* regex) {
2980 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2981}
2982inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2983 const internal::string& regex) {
2984 return ContainsRegex(new internal::RE(regex));
2985}
2986
shiqiane35fdd92008-12-10 05:08:54 +00002987#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2988// Wide string matchers.
2989
2990// Matches a string equal to str.
2991inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2992 StrEq(const internal::wstring& str) {
2993 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2994 str, true, true));
2995}
2996
2997// Matches a string not equal to str.
2998inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2999 StrNe(const internal::wstring& str) {
3000 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3001 str, false, true));
3002}
3003
3004// Matches a string equal to str, ignoring case.
3005inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3006 StrCaseEq(const internal::wstring& str) {
3007 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3008 str, true, false));
3009}
3010
3011// Matches a string not equal to str, ignoring case.
3012inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3013 StrCaseNe(const internal::wstring& str) {
3014 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3015 str, false, false));
3016}
3017
3018// Creates a matcher that matches any wstring, std::wstring, or C wide string
3019// that contains the given substring.
3020inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
3021 HasSubstr(const internal::wstring& substring) {
3022 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
3023 substring));
3024}
3025
3026// Matches a string that starts with 'prefix' (case-sensitive).
3027inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
3028 StartsWith(const internal::wstring& prefix) {
3029 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
3030 prefix));
3031}
3032
3033// Matches a string that ends with 'suffix' (case-sensitive).
3034inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
3035 EndsWith(const internal::wstring& suffix) {
3036 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
3037 suffix));
3038}
3039
3040#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3041
3042// Creates a polymorphic matcher that matches a 2-tuple where the
3043// first field == the second field.
3044inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
3045
3046// Creates a polymorphic matcher that matches a 2-tuple where the
3047// first field >= the second field.
3048inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
3049
3050// Creates a polymorphic matcher that matches a 2-tuple where the
3051// first field > the second field.
3052inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
3053
3054// Creates a polymorphic matcher that matches a 2-tuple where the
3055// first field <= the second field.
3056inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
3057
3058// Creates a polymorphic matcher that matches a 2-tuple where the
3059// first field < the second field.
3060inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
3061
3062// Creates a polymorphic matcher that matches a 2-tuple where the
3063// first field != the second field.
3064inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
3065
3066// Creates a matcher that matches any value of type T that m doesn't
3067// match.
3068template <typename InnerMatcher>
3069inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
3070 return internal::NotMatcher<InnerMatcher>(m);
3071}
3072
shiqiane35fdd92008-12-10 05:08:54 +00003073// Returns a matcher that matches anything that satisfies the given
3074// predicate. The predicate can be any unary function or functor
3075// whose return type can be implicitly converted to bool.
3076template <typename Predicate>
3077inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
3078Truly(Predicate pred) {
3079 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
3080}
3081
zhanyong.wan6a896b52009-01-16 01:13:50 +00003082// Returns a matcher that matches an equal container.
3083// This matcher behaves like Eq(), but in the event of mismatch lists the
3084// values that are included in one container but not the other. (Duplicate
3085// values and order differences are not explained.)
3086template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00003087inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00003088 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00003089 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00003090 // This following line is for working around a bug in MSVC 8.0,
3091 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00003092 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00003093 return MakePolymorphicMatcher(
3094 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00003095}
3096
zhanyong.wan898725c2011-09-16 16:45:39 +00003097// Returns a matcher that matches a container that, when sorted using
3098// the given comparator, matches container_matcher.
3099template <typename Comparator, typename ContainerMatcher>
3100inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
3101WhenSortedBy(const Comparator& comparator,
3102 const ContainerMatcher& container_matcher) {
3103 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
3104 comparator, container_matcher);
3105}
3106
3107// Returns a matcher that matches a container that, when sorted using
3108// the < operator, matches container_matcher.
3109template <typename ContainerMatcher>
3110inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
3111WhenSorted(const ContainerMatcher& container_matcher) {
3112 return
3113 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
3114 internal::LessComparator(), container_matcher);
3115}
3116
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003117// Matches an STL-style container or a native array that contains the
3118// same number of elements as in rhs, where its i-th element and rhs's
3119// i-th element (as a pair) satisfy the given pair matcher, for all i.
3120// TupleMatcher must be able to be safely cast to Matcher<tuple<const
3121// T1&, const T2&> >, where T1 and T2 are the types of elements in the
3122// LHS container and the RHS container respectively.
3123template <typename TupleMatcher, typename Container>
3124inline internal::PointwiseMatcher<TupleMatcher,
3125 GTEST_REMOVE_CONST_(Container)>
3126Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
3127 // This following line is for working around a bug in MSVC 8.0,
3128 // which causes Container to be a const type sometimes.
3129 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
3130 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
3131 tuple_matcher, rhs);
3132}
3133
zhanyong.wanb8243162009-06-04 05:48:20 +00003134// Matches an STL-style container or a native array that contains at
3135// least one element matching the given value or matcher.
3136//
3137// Examples:
3138// ::std::set<int> page_ids;
3139// page_ids.insert(3);
3140// page_ids.insert(1);
3141// EXPECT_THAT(page_ids, Contains(1));
3142// EXPECT_THAT(page_ids, Contains(Gt(2)));
3143// EXPECT_THAT(page_ids, Not(Contains(4)));
3144//
3145// ::std::map<int, size_t> page_lengths;
3146// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00003147// EXPECT_THAT(page_lengths,
3148// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00003149//
3150// const char* user_ids[] = { "joe", "mike", "tom" };
3151// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
3152template <typename M>
3153inline internal::ContainsMatcher<M> Contains(M matcher) {
3154 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00003155}
3156
zhanyong.wan33605ba2010-04-22 23:37:47 +00003157// Matches an STL-style container or a native array that contains only
3158// elements matching the given value or matcher.
3159//
3160// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
3161// the messages are different.
3162//
3163// Examples:
3164// ::std::set<int> page_ids;
3165// // Each(m) matches an empty container, regardless of what m is.
3166// EXPECT_THAT(page_ids, Each(Eq(1)));
3167// EXPECT_THAT(page_ids, Each(Eq(77)));
3168//
3169// page_ids.insert(3);
3170// EXPECT_THAT(page_ids, Each(Gt(0)));
3171// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
3172// page_ids.insert(1);
3173// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
3174//
3175// ::std::map<int, size_t> page_lengths;
3176// page_lengths[1] = 100;
3177// page_lengths[2] = 200;
3178// page_lengths[3] = 300;
3179// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
3180// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
3181//
3182// const char* user_ids[] = { "joe", "mike", "tom" };
3183// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
3184template <typename M>
3185inline internal::EachMatcher<M> Each(M matcher) {
3186 return internal::EachMatcher<M>(matcher);
3187}
3188
zhanyong.wanb5937da2009-07-16 20:26:41 +00003189// Key(inner_matcher) matches an std::pair whose 'first' field matches
3190// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3191// std::map that contains at least one element whose key is >= 5.
3192template <typename M>
3193inline internal::KeyMatcher<M> Key(M inner_matcher) {
3194 return internal::KeyMatcher<M>(inner_matcher);
3195}
3196
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003197// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
3198// matches first_matcher and whose 'second' field matches second_matcher. For
3199// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
3200// to match a std::map<int, string> that contains exactly one element whose key
3201// is >= 5 and whose value equals "foo".
3202template <typename FirstMatcher, typename SecondMatcher>
3203inline internal::PairMatcher<FirstMatcher, SecondMatcher>
3204Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
3205 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
3206 first_matcher, second_matcher);
3207}
3208
shiqiane35fdd92008-12-10 05:08:54 +00003209// Returns a predicate that is satisfied by anything that matches the
3210// given matcher.
3211template <typename M>
3212inline internal::MatcherAsPredicate<M> Matches(M matcher) {
3213 return internal::MatcherAsPredicate<M>(matcher);
3214}
3215
zhanyong.wanb8243162009-06-04 05:48:20 +00003216// Returns true iff the value matches the matcher.
3217template <typename T, typename M>
3218inline bool Value(const T& value, M matcher) {
3219 return testing::Matches(matcher)(value);
3220}
3221
zhanyong.wan34b034c2010-03-05 21:23:23 +00003222// Matches the value against the given matcher and explains the match
3223// result to listener.
3224template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00003225inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00003226 M matcher, const T& value, MatchResultListener* listener) {
3227 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
3228}
3229
zhanyong.wanbf550852009-06-09 06:09:53 +00003230// AllArgs(m) is a synonym of m. This is useful in
3231//
3232// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
3233//
3234// which is easier to read than
3235//
3236// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
3237template <typename InnerMatcher>
3238inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
3239
shiqiane35fdd92008-12-10 05:08:54 +00003240// These macros allow using matchers to check values in Google Test
3241// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
3242// succeed iff the value matches the matcher. If the assertion fails,
3243// the value and the description of the matcher will be printed.
3244#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
3245 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3246#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
3247 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3248
3249} // namespace testing
3250
3251#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_