blob: dc93468ce34c7fa810e7d8489cfffe74bd717c7d [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.wana31d9ce2013-03-01 01:50:17 +00001975// Implements a matcher that checks the size of an STL-style container.
1976template <typename SizeMatcher>
1977class SizeIsMatcher {
1978 public:
1979 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
1980 : size_matcher_(size_matcher) {
1981 }
1982
1983 template <typename Container>
1984 operator Matcher<Container>() const {
1985 return MakeMatcher(new Impl<Container>(size_matcher_));
1986 }
1987
1988 template <typename Container>
1989 class Impl : public MatcherInterface<Container> {
1990 public:
1991 typedef internal::StlContainerView<
1992 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
1993 typedef typename ContainerView::type::size_type SizeType;
1994 explicit Impl(const SizeMatcher& size_matcher)
1995 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
1996
1997 virtual void DescribeTo(::std::ostream* os) const {
1998 *os << "size ";
1999 size_matcher_.DescribeTo(os);
2000 }
2001 virtual void DescribeNegationTo(::std::ostream* os) const {
2002 *os << "size ";
2003 size_matcher_.DescribeNegationTo(os);
2004 }
2005
2006 virtual bool MatchAndExplain(Container container,
2007 MatchResultListener* listener) const {
2008 SizeType size = container.size();
2009 StringMatchResultListener size_listener;
2010 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2011 *listener
2012 << "whose size " << size << (result ? " matches" : " doesn't match");
2013 PrintIfNotEmpty(size_listener.str(), listener->stream());
2014 return result;
2015 }
2016
2017 private:
2018 const Matcher<SizeType> size_matcher_;
2019 GTEST_DISALLOW_ASSIGN_(Impl);
2020 };
2021
2022 private:
2023 const SizeMatcher size_matcher_;
2024 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2025};
2026
zhanyong.wan6a896b52009-01-16 01:13:50 +00002027// Implements an equality matcher for any STL-style container whose elements
2028// support ==. This matcher is like Eq(), but its failure explanations provide
2029// more detailed information that is useful when the container is used as a set.
2030// The failure message reports elements that are in one of the operands but not
2031// the other. The failure messages do not report duplicate or out-of-order
2032// elements in the containers (which don't properly matter to sets, but can
2033// occur if the containers are vectors or lists, for example).
2034//
2035// Uses the container's const_iterator, value_type, operator ==,
2036// begin(), and end().
2037template <typename Container>
2038class ContainerEqMatcher {
2039 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00002040 typedef internal::StlContainerView<Container> View;
2041 typedef typename View::type StlContainer;
2042 typedef typename View::const_reference StlContainerReference;
2043
2044 // We make a copy of rhs in case the elements in it are modified
2045 // after this matcher is created.
2046 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
2047 // Makes sure the user doesn't instantiate this class template
2048 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002049 (void)testing::StaticAssertTypeEq<Container,
2050 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00002051 }
2052
zhanyong.wan6a896b52009-01-16 01:13:50 +00002053 void DescribeTo(::std::ostream* os) const {
2054 *os << "equals ";
vladloseve2e8ba42010-05-13 18:16:03 +00002055 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002056 }
2057 void DescribeNegationTo(::std::ostream* os) const {
2058 *os << "does not equal ";
vladloseve2e8ba42010-05-13 18:16:03 +00002059 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002060 }
2061
zhanyong.wanb8243162009-06-04 05:48:20 +00002062 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00002063 bool MatchAndExplain(const LhsContainer& lhs,
2064 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002065 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00002066 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002067 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00002068 LhsView;
2069 typedef typename LhsView::type LhsStlContainer;
2070 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00002071 if (lhs_stl_container == rhs_)
2072 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002073
zhanyong.wane122e452010-01-12 09:03:52 +00002074 ::std::ostream* const os = listener->stream();
2075 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002076 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002077 bool printed_header = false;
2078 for (typename LhsStlContainer::const_iterator it =
2079 lhs_stl_container.begin();
2080 it != lhs_stl_container.end(); ++it) {
2081 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
2082 rhs_.end()) {
2083 if (printed_header) {
2084 *os << ", ";
2085 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002086 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002087 printed_header = true;
2088 }
vladloseve2e8ba42010-05-13 18:16:03 +00002089 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002090 }
zhanyong.wane122e452010-01-12 09:03:52 +00002091 }
2092
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002093 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002094 bool printed_header2 = false;
2095 for (typename StlContainer::const_iterator it = rhs_.begin();
2096 it != rhs_.end(); ++it) {
2097 if (internal::ArrayAwareFind(
2098 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2099 lhs_stl_container.end()) {
2100 if (printed_header2) {
2101 *os << ", ";
2102 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002103 *os << (printed_header ? ",\nand" : "which")
2104 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002105 printed_header2 = true;
2106 }
vladloseve2e8ba42010-05-13 18:16:03 +00002107 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002108 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002109 }
2110 }
2111
zhanyong.wane122e452010-01-12 09:03:52 +00002112 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002113 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002114
zhanyong.wan6a896b52009-01-16 01:13:50 +00002115 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00002116 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002117
2118 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002119};
2120
zhanyong.wan898725c2011-09-16 16:45:39 +00002121// A comparator functor that uses the < operator to compare two values.
2122struct LessComparator {
2123 template <typename T, typename U>
2124 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2125};
2126
2127// Implements WhenSortedBy(comparator, container_matcher).
2128template <typename Comparator, typename ContainerMatcher>
2129class WhenSortedByMatcher {
2130 public:
2131 WhenSortedByMatcher(const Comparator& comparator,
2132 const ContainerMatcher& matcher)
2133 : comparator_(comparator), matcher_(matcher) {}
2134
2135 template <typename LhsContainer>
2136 operator Matcher<LhsContainer>() const {
2137 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2138 }
2139
2140 template <typename LhsContainer>
2141 class Impl : public MatcherInterface<LhsContainer> {
2142 public:
2143 typedef internal::StlContainerView<
2144 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2145 typedef typename LhsView::type LhsStlContainer;
2146 typedef typename LhsView::const_reference LhsStlContainerReference;
2147 typedef typename LhsStlContainer::value_type LhsValue;
2148
2149 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2150 : comparator_(comparator), matcher_(matcher) {}
2151
2152 virtual void DescribeTo(::std::ostream* os) const {
2153 *os << "(when sorted) ";
2154 matcher_.DescribeTo(os);
2155 }
2156
2157 virtual void DescribeNegationTo(::std::ostream* os) const {
2158 *os << "(when sorted) ";
2159 matcher_.DescribeNegationTo(os);
2160 }
2161
2162 virtual bool MatchAndExplain(LhsContainer lhs,
2163 MatchResultListener* listener) const {
2164 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2165 std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2166 lhs_stl_container.end());
2167 std::sort(sorted_container.begin(), sorted_container.end(), comparator_);
2168
2169 if (!listener->IsInterested()) {
2170 // If the listener is not interested, we do not need to
2171 // construct the inner explanation.
2172 return matcher_.Matches(sorted_container);
2173 }
2174
2175 *listener << "which is ";
2176 UniversalPrint(sorted_container, listener->stream());
2177 *listener << " when sorted";
2178
2179 StringMatchResultListener inner_listener;
2180 const bool match = matcher_.MatchAndExplain(sorted_container,
2181 &inner_listener);
2182 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2183 return match;
2184 }
2185
2186 private:
2187 const Comparator comparator_;
2188 const Matcher<const std::vector<LhsValue>&> matcher_;
2189
2190 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2191 };
2192
2193 private:
2194 const Comparator comparator_;
2195 const ContainerMatcher matcher_;
2196
2197 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2198};
2199
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002200// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2201// must be able to be safely cast to Matcher<tuple<const T1&, const
2202// T2&> >, where T1 and T2 are the types of elements in the LHS
2203// container and the RHS container respectively.
2204template <typename TupleMatcher, typename RhsContainer>
2205class PointwiseMatcher {
2206 public:
2207 typedef internal::StlContainerView<RhsContainer> RhsView;
2208 typedef typename RhsView::type RhsStlContainer;
2209 typedef typename RhsStlContainer::value_type RhsValue;
2210
2211 // Like ContainerEq, we make a copy of rhs in case the elements in
2212 // it are modified after this matcher is created.
2213 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2214 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2215 // Makes sure the user doesn't instantiate this class template
2216 // with a const or reference type.
2217 (void)testing::StaticAssertTypeEq<RhsContainer,
2218 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2219 }
2220
2221 template <typename LhsContainer>
2222 operator Matcher<LhsContainer>() const {
2223 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2224 }
2225
2226 template <typename LhsContainer>
2227 class Impl : public MatcherInterface<LhsContainer> {
2228 public:
2229 typedef internal::StlContainerView<
2230 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2231 typedef typename LhsView::type LhsStlContainer;
2232 typedef typename LhsView::const_reference LhsStlContainerReference;
2233 typedef typename LhsStlContainer::value_type LhsValue;
2234 // We pass the LHS value and the RHS value to the inner matcher by
2235 // reference, as they may be expensive to copy. We must use tuple
2236 // instead of pair here, as a pair cannot hold references (C++ 98,
2237 // 20.2.2 [lib.pairs]).
2238 typedef std::tr1::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
2239
2240 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2241 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2242 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2243 rhs_(rhs) {}
2244
2245 virtual void DescribeTo(::std::ostream* os) const {
2246 *os << "contains " << rhs_.size()
2247 << " values, where each value and its corresponding value in ";
2248 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2249 *os << " ";
2250 mono_tuple_matcher_.DescribeTo(os);
2251 }
2252 virtual void DescribeNegationTo(::std::ostream* os) const {
2253 *os << "doesn't contain exactly " << rhs_.size()
2254 << " values, or contains a value x at some index i"
2255 << " where x and the i-th value of ";
2256 UniversalPrint(rhs_, os);
2257 *os << " ";
2258 mono_tuple_matcher_.DescribeNegationTo(os);
2259 }
2260
2261 virtual bool MatchAndExplain(LhsContainer lhs,
2262 MatchResultListener* listener) const {
2263 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2264 const size_t actual_size = lhs_stl_container.size();
2265 if (actual_size != rhs_.size()) {
2266 *listener << "which contains " << actual_size << " values";
2267 return false;
2268 }
2269
2270 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2271 typename RhsStlContainer::const_iterator right = rhs_.begin();
2272 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2273 const InnerMatcherArg value_pair(*left, *right);
2274
2275 if (listener->IsInterested()) {
2276 StringMatchResultListener inner_listener;
2277 if (!mono_tuple_matcher_.MatchAndExplain(
2278 value_pair, &inner_listener)) {
2279 *listener << "where the value pair (";
2280 UniversalPrint(*left, listener->stream());
2281 *listener << ", ";
2282 UniversalPrint(*right, listener->stream());
2283 *listener << ") at index #" << i << " don't match";
2284 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2285 return false;
2286 }
2287 } else {
2288 if (!mono_tuple_matcher_.Matches(value_pair))
2289 return false;
2290 }
2291 }
2292
2293 return true;
2294 }
2295
2296 private:
2297 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2298 const RhsStlContainer rhs_;
2299
2300 GTEST_DISALLOW_ASSIGN_(Impl);
2301 };
2302
2303 private:
2304 const TupleMatcher tuple_matcher_;
2305 const RhsStlContainer rhs_;
2306
2307 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2308};
2309
zhanyong.wan33605ba2010-04-22 23:37:47 +00002310// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002311template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002312class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002313 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002314 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002315 typedef StlContainerView<RawContainer> View;
2316 typedef typename View::type StlContainer;
2317 typedef typename View::const_reference StlContainerReference;
2318 typedef typename StlContainer::value_type Element;
2319
2320 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002321 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002322 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002323 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002324
zhanyong.wan33605ba2010-04-22 23:37:47 +00002325 // Checks whether:
2326 // * All elements in the container match, if all_elements_should_match.
2327 // * Any element in the container matches, if !all_elements_should_match.
2328 bool MatchAndExplainImpl(bool all_elements_should_match,
2329 Container container,
2330 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002331 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002332 size_t i = 0;
2333 for (typename StlContainer::const_iterator it = stl_container.begin();
2334 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002335 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00002336 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2337
2338 if (matches != all_elements_should_match) {
2339 *listener << "whose element #" << i
2340 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002341 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00002342 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00002343 }
2344 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00002345 return all_elements_should_match;
2346 }
2347
2348 protected:
2349 const Matcher<const Element&> inner_matcher_;
2350
2351 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2352};
2353
2354// Implements Contains(element_matcher) for the given argument type Container.
2355// Symmetric to EachMatcherImpl.
2356template <typename Container>
2357class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2358 public:
2359 template <typename InnerMatcher>
2360 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2361 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2362
2363 // Describes what this matcher does.
2364 virtual void DescribeTo(::std::ostream* os) const {
2365 *os << "contains at least one element that ";
2366 this->inner_matcher_.DescribeTo(os);
2367 }
2368
2369 virtual void DescribeNegationTo(::std::ostream* os) const {
2370 *os << "doesn't contain any element that ";
2371 this->inner_matcher_.DescribeTo(os);
2372 }
2373
2374 virtual bool MatchAndExplain(Container container,
2375 MatchResultListener* listener) const {
2376 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002377 }
2378
2379 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002380 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002381};
2382
zhanyong.wan33605ba2010-04-22 23:37:47 +00002383// Implements Each(element_matcher) for the given argument type Container.
2384// Symmetric to ContainsMatcherImpl.
2385template <typename Container>
2386class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2387 public:
2388 template <typename InnerMatcher>
2389 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2390 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2391
2392 // Describes what this matcher does.
2393 virtual void DescribeTo(::std::ostream* os) const {
2394 *os << "only contains elements that ";
2395 this->inner_matcher_.DescribeTo(os);
2396 }
2397
2398 virtual void DescribeNegationTo(::std::ostream* os) const {
2399 *os << "contains some element that ";
2400 this->inner_matcher_.DescribeNegationTo(os);
2401 }
2402
2403 virtual bool MatchAndExplain(Container container,
2404 MatchResultListener* listener) const {
2405 return this->MatchAndExplainImpl(true, container, listener);
2406 }
2407
2408 private:
2409 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2410};
2411
zhanyong.wanb8243162009-06-04 05:48:20 +00002412// Implements polymorphic Contains(element_matcher).
2413template <typename M>
2414class ContainsMatcher {
2415 public:
2416 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2417
2418 template <typename Container>
2419 operator Matcher<Container>() const {
2420 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2421 }
2422
2423 private:
2424 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002425
2426 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002427};
2428
zhanyong.wan33605ba2010-04-22 23:37:47 +00002429// Implements polymorphic Each(element_matcher).
2430template <typename M>
2431class EachMatcher {
2432 public:
2433 explicit EachMatcher(M m) : inner_matcher_(m) {}
2434
2435 template <typename Container>
2436 operator Matcher<Container>() const {
2437 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2438 }
2439
2440 private:
2441 const M inner_matcher_;
2442
2443 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2444};
2445
zhanyong.wanb5937da2009-07-16 20:26:41 +00002446// Implements Key(inner_matcher) for the given argument pair type.
2447// Key(inner_matcher) matches an std::pair whose 'first' field matches
2448// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2449// std::map that contains at least one element whose key is >= 5.
2450template <typename PairType>
2451class KeyMatcherImpl : public MatcherInterface<PairType> {
2452 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002453 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002454 typedef typename RawPairType::first_type KeyType;
2455
2456 template <typename InnerMatcher>
2457 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2458 : inner_matcher_(
2459 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2460 }
2461
2462 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002463 virtual bool MatchAndExplain(PairType key_value,
2464 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002465 StringMatchResultListener inner_listener;
2466 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2467 &inner_listener);
2468 const internal::string explanation = inner_listener.str();
2469 if (explanation != "") {
2470 *listener << "whose first field is a value " << explanation;
2471 }
2472 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002473 }
2474
2475 // Describes what this matcher does.
2476 virtual void DescribeTo(::std::ostream* os) const {
2477 *os << "has a key that ";
2478 inner_matcher_.DescribeTo(os);
2479 }
2480
2481 // Describes what the negation of this matcher does.
2482 virtual void DescribeNegationTo(::std::ostream* os) const {
2483 *os << "doesn't have a key that ";
2484 inner_matcher_.DescribeTo(os);
2485 }
2486
zhanyong.wanb5937da2009-07-16 20:26:41 +00002487 private:
2488 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002489
2490 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002491};
2492
2493// Implements polymorphic Key(matcher_for_key).
2494template <typename M>
2495class KeyMatcher {
2496 public:
2497 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2498
2499 template <typename PairType>
2500 operator Matcher<PairType>() const {
2501 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2502 }
2503
2504 private:
2505 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002506
2507 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002508};
2509
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002510// Implements Pair(first_matcher, second_matcher) for the given argument pair
2511// type with its two matchers. See Pair() function below.
2512template <typename PairType>
2513class PairMatcherImpl : public MatcherInterface<PairType> {
2514 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002515 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002516 typedef typename RawPairType::first_type FirstType;
2517 typedef typename RawPairType::second_type SecondType;
2518
2519 template <typename FirstMatcher, typename SecondMatcher>
2520 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2521 : first_matcher_(
2522 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2523 second_matcher_(
2524 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2525 }
2526
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002527 // Describes what this matcher does.
2528 virtual void DescribeTo(::std::ostream* os) const {
2529 *os << "has a first field that ";
2530 first_matcher_.DescribeTo(os);
2531 *os << ", and has a second field that ";
2532 second_matcher_.DescribeTo(os);
2533 }
2534
2535 // Describes what the negation of this matcher does.
2536 virtual void DescribeNegationTo(::std::ostream* os) const {
2537 *os << "has a first field that ";
2538 first_matcher_.DescribeNegationTo(os);
2539 *os << ", or has a second field that ";
2540 second_matcher_.DescribeNegationTo(os);
2541 }
2542
zhanyong.wan82113312010-01-08 21:55:40 +00002543 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2544 // matches second_matcher.
2545 virtual bool MatchAndExplain(PairType a_pair,
2546 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002547 if (!listener->IsInterested()) {
2548 // If the listener is not interested, we don't need to construct the
2549 // explanation.
2550 return first_matcher_.Matches(a_pair.first) &&
2551 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00002552 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002553 StringMatchResultListener first_inner_listener;
2554 if (!first_matcher_.MatchAndExplain(a_pair.first,
2555 &first_inner_listener)) {
2556 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002557 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002558 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002559 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002560 StringMatchResultListener second_inner_listener;
2561 if (!second_matcher_.MatchAndExplain(a_pair.second,
2562 &second_inner_listener)) {
2563 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002564 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002565 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002566 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002567 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
2568 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00002569 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002570 }
2571
2572 private:
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002573 void ExplainSuccess(const internal::string& first_explanation,
2574 const internal::string& second_explanation,
2575 MatchResultListener* listener) const {
2576 *listener << "whose both fields match";
2577 if (first_explanation != "") {
2578 *listener << ", where the first field is a value " << first_explanation;
2579 }
2580 if (second_explanation != "") {
2581 *listener << ", ";
2582 if (first_explanation != "") {
2583 *listener << "and ";
2584 } else {
2585 *listener << "where ";
2586 }
2587 *listener << "the second field is a value " << second_explanation;
2588 }
2589 }
2590
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002591 const Matcher<const FirstType&> first_matcher_;
2592 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002593
2594 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002595};
2596
2597// Implements polymorphic Pair(first_matcher, second_matcher).
2598template <typename FirstMatcher, typename SecondMatcher>
2599class PairMatcher {
2600 public:
2601 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2602 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2603
2604 template <typename PairType>
2605 operator Matcher<PairType> () const {
2606 return MakeMatcher(
2607 new PairMatcherImpl<PairType>(
2608 first_matcher_, second_matcher_));
2609 }
2610
2611 private:
2612 const FirstMatcher first_matcher_;
2613 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002614
2615 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002616};
2617
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002618// Implements ElementsAre() and ElementsAreArray().
2619template <typename Container>
2620class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2621 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002622 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002623 typedef internal::StlContainerView<RawContainer> View;
2624 typedef typename View::type StlContainer;
2625 typedef typename View::const_reference StlContainerReference;
2626 typedef typename StlContainer::value_type Element;
2627
2628 // Constructs the matcher from a sequence of element values or
2629 // element matchers.
2630 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00002631 ElementsAreMatcherImpl(InputIter first, InputIter last) {
2632 while (first != last) {
2633 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002634 }
2635 }
2636
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002637 // Describes what this matcher does.
2638 virtual void DescribeTo(::std::ostream* os) const {
2639 if (count() == 0) {
2640 *os << "is empty";
2641 } else if (count() == 1) {
2642 *os << "has 1 element that ";
2643 matchers_[0].DescribeTo(os);
2644 } else {
2645 *os << "has " << Elements(count()) << " where\n";
2646 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002647 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002648 matchers_[i].DescribeTo(os);
2649 if (i + 1 < count()) {
2650 *os << ",\n";
2651 }
2652 }
2653 }
2654 }
2655
2656 // Describes what the negation of this matcher does.
2657 virtual void DescribeNegationTo(::std::ostream* os) const {
2658 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002659 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002660 return;
2661 }
2662
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002663 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002664 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002665 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002666 matchers_[i].DescribeNegationTo(os);
2667 if (i + 1 < count()) {
2668 *os << ", or\n";
2669 }
2670 }
2671 }
2672
zhanyong.wan82113312010-01-08 21:55:40 +00002673 virtual bool MatchAndExplain(Container container,
2674 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002675 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002676 const size_t actual_count = stl_container.size();
2677 if (actual_count != count()) {
2678 // The element count doesn't match. If the container is empty,
2679 // there's no need to explain anything as Google Mock already
2680 // prints the empty container. Otherwise we just need to show
2681 // how many elements there actually are.
2682 if (actual_count != 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002683 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002684 }
zhanyong.wan82113312010-01-08 21:55:40 +00002685 return false;
2686 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002687
zhanyong.wan82113312010-01-08 21:55:40 +00002688 typename StlContainer::const_iterator it = stl_container.begin();
2689 // explanations[i] is the explanation of the element at index i.
2690 std::vector<internal::string> explanations(count());
2691 for (size_t i = 0; i != count(); ++it, ++i) {
2692 StringMatchResultListener s;
2693 if (matchers_[i].MatchAndExplain(*it, &s)) {
2694 explanations[i] = s.str();
2695 } else {
2696 // The container has the right size but the i-th element
2697 // doesn't match its expectation.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002698 *listener << "whose element #" << i << " doesn't match";
2699 PrintIfNotEmpty(s.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002700 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002701 }
2702 }
zhanyong.wan82113312010-01-08 21:55:40 +00002703
2704 // Every element matches its expectation. We need to explain why
2705 // (the obvious ones can be skipped).
zhanyong.wan82113312010-01-08 21:55:40 +00002706 bool reason_printed = false;
2707 for (size_t i = 0; i != count(); ++i) {
2708 const internal::string& s = explanations[i];
2709 if (!s.empty()) {
2710 if (reason_printed) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002711 *listener << ",\nand ";
zhanyong.wan82113312010-01-08 21:55:40 +00002712 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002713 *listener << "whose element #" << i << " matches, " << s;
zhanyong.wan82113312010-01-08 21:55:40 +00002714 reason_printed = true;
2715 }
2716 }
2717
2718 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002719 }
2720
2721 private:
2722 static Message Elements(size_t count) {
2723 return Message() << count << (count == 1 ? " element" : " elements");
2724 }
2725
2726 size_t count() const { return matchers_.size(); }
2727 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002728
2729 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002730};
2731
2732// Implements ElementsAre() of 0 arguments.
2733class ElementsAreMatcher0 {
2734 public:
2735 ElementsAreMatcher0() {}
2736
2737 template <typename Container>
2738 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002739 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002740 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2741 Element;
2742
2743 const Matcher<const Element&>* const matchers = NULL;
jgm38513a82012-11-15 15:50:36 +00002744 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers,
2745 matchers));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002746 }
2747};
2748
2749// Implements ElementsAreArray().
2750template <typename T>
2751class ElementsAreArrayMatcher {
2752 public:
jgm38513a82012-11-15 15:50:36 +00002753 template <typename Iter>
2754 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002755
2756 template <typename Container>
2757 operator Matcher<Container>() const {
jgm38513a82012-11-15 15:50:36 +00002758 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
2759 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002760 }
2761
2762 private:
jgm38513a82012-11-15 15:50:36 +00002763 const std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002764
2765 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002766};
2767
zhanyong.wanb4140802010-06-08 22:53:57 +00002768// Returns the description for a matcher defined using the MATCHER*()
2769// macro where the user-supplied description string is "", if
2770// 'negation' is false; otherwise returns the description of the
2771// negation of the matcher. 'param_values' contains a list of strings
2772// that are the print-out of the matcher's parameters.
vladlosev587c1b32011-05-20 00:42:22 +00002773GTEST_API_ string FormatMatcherDescription(bool negation,
2774 const char* matcher_name,
2775 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002776
shiqiane35fdd92008-12-10 05:08:54 +00002777} // namespace internal
2778
shiqiane35fdd92008-12-10 05:08:54 +00002779// _ is a matcher that matches anything of any type.
2780//
2781// This definition is fine as:
2782//
2783// 1. The C++ standard permits using the name _ in a namespace that
2784// is not the global namespace or ::std.
2785// 2. The AnythingMatcher class has no data member or constructor,
2786// so it's OK to create global variables of this type.
2787// 3. c-style has approved of using _ in this case.
2788const internal::AnythingMatcher _ = {};
2789// Creates a matcher that matches any value of the given type T.
2790template <typename T>
2791inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2792
2793// Creates a matcher that matches any value of the given type T.
2794template <typename T>
2795inline Matcher<T> An() { return A<T>(); }
2796
2797// Creates a polymorphic matcher that matches anything equal to x.
2798// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2799// wouldn't compile.
2800template <typename T>
2801inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2802
2803// Constructs a Matcher<T> from a 'value' of type T. The constructed
2804// matcher matches any value that's equal to 'value'.
2805template <typename T>
2806Matcher<T>::Matcher(T value) { *this = Eq(value); }
2807
2808// Creates a monomorphic matcher that matches anything with type Lhs
2809// and equal to rhs. A user may need to use this instead of Eq(...)
2810// in order to resolve an overloading ambiguity.
2811//
2812// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2813// or Matcher<T>(x), but more readable than the latter.
2814//
2815// We could define similar monomorphic matchers for other comparison
2816// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2817// it yet as those are used much less than Eq() in practice. A user
2818// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2819// for example.
2820template <typename Lhs, typename Rhs>
2821inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2822
2823// Creates a polymorphic matcher that matches anything >= x.
2824template <typename Rhs>
2825inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2826 return internal::GeMatcher<Rhs>(x);
2827}
2828
2829// Creates a polymorphic matcher that matches anything > x.
2830template <typename Rhs>
2831inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2832 return internal::GtMatcher<Rhs>(x);
2833}
2834
2835// Creates a polymorphic matcher that matches anything <= x.
2836template <typename Rhs>
2837inline internal::LeMatcher<Rhs> Le(Rhs x) {
2838 return internal::LeMatcher<Rhs>(x);
2839}
2840
2841// Creates a polymorphic matcher that matches anything < x.
2842template <typename Rhs>
2843inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2844 return internal::LtMatcher<Rhs>(x);
2845}
2846
2847// Creates a polymorphic matcher that matches anything != x.
2848template <typename Rhs>
2849inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2850 return internal::NeMatcher<Rhs>(x);
2851}
2852
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002853// Creates a polymorphic matcher that matches any NULL pointer.
2854inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2855 return MakePolymorphicMatcher(internal::IsNullMatcher());
2856}
2857
shiqiane35fdd92008-12-10 05:08:54 +00002858// Creates a polymorphic matcher that matches any non-NULL pointer.
2859// This is convenient as Not(NULL) doesn't compile (the compiler
2860// thinks that that expression is comparing a pointer with an integer).
2861inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2862 return MakePolymorphicMatcher(internal::NotNullMatcher());
2863}
2864
2865// Creates a polymorphic matcher that matches any argument that
2866// references variable x.
2867template <typename T>
2868inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2869 return internal::RefMatcher<T&>(x);
2870}
2871
2872// Creates a matcher that matches any double argument approximately
2873// equal to rhs, where two NANs are considered unequal.
2874inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2875 return internal::FloatingEqMatcher<double>(rhs, false);
2876}
2877
2878// Creates a matcher that matches any double argument approximately
2879// equal to rhs, including NaN values when rhs is NaN.
2880inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2881 return internal::FloatingEqMatcher<double>(rhs, true);
2882}
2883
2884// Creates a matcher that matches any float argument approximately
2885// equal to rhs, where two NANs are considered unequal.
2886inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2887 return internal::FloatingEqMatcher<float>(rhs, false);
2888}
2889
2890// Creates a matcher that matches any double argument approximately
2891// equal to rhs, including NaN values when rhs is NaN.
2892inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2893 return internal::FloatingEqMatcher<float>(rhs, true);
2894}
2895
2896// Creates a matcher that matches a pointer (raw or smart) that points
2897// to a value that matches inner_matcher.
2898template <typename InnerMatcher>
2899inline internal::PointeeMatcher<InnerMatcher> Pointee(
2900 const InnerMatcher& inner_matcher) {
2901 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2902}
2903
2904// Creates a matcher that matches an object whose given field matches
2905// 'matcher'. For example,
2906// Field(&Foo::number, Ge(5))
2907// matches a Foo object x iff x.number >= 5.
2908template <typename Class, typename FieldType, typename FieldMatcher>
2909inline PolymorphicMatcher<
2910 internal::FieldMatcher<Class, FieldType> > Field(
2911 FieldType Class::*field, const FieldMatcher& matcher) {
2912 return MakePolymorphicMatcher(
2913 internal::FieldMatcher<Class, FieldType>(
2914 field, MatcherCast<const FieldType&>(matcher)));
2915 // The call to MatcherCast() is required for supporting inner
2916 // matchers of compatible types. For example, it allows
2917 // Field(&Foo::bar, m)
2918 // to compile where bar is an int32 and m is a matcher for int64.
2919}
2920
2921// Creates a matcher that matches an object whose given property
2922// matches 'matcher'. For example,
2923// Property(&Foo::str, StartsWith("hi"))
2924// matches a Foo object x iff x.str() starts with "hi".
2925template <typename Class, typename PropertyType, typename PropertyMatcher>
2926inline PolymorphicMatcher<
2927 internal::PropertyMatcher<Class, PropertyType> > Property(
2928 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2929 return MakePolymorphicMatcher(
2930 internal::PropertyMatcher<Class, PropertyType>(
2931 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00002932 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002933 // The call to MatcherCast() is required for supporting inner
2934 // matchers of compatible types. For example, it allows
2935 // Property(&Foo::bar, m)
2936 // to compile where bar() returns an int32 and m is a matcher for int64.
2937}
2938
2939// Creates a matcher that matches an object iff the result of applying
2940// a callable to x matches 'matcher'.
2941// For example,
2942// ResultOf(f, StartsWith("hi"))
2943// matches a Foo object x iff f(x) starts with "hi".
2944// callable parameter can be a function, function pointer, or a functor.
2945// Callable has to satisfy the following conditions:
2946// * It is required to keep no state affecting the results of
2947// the calls on it and make no assumptions about how many calls
2948// will be made. Any state it keeps must be protected from the
2949// concurrent access.
2950// * If it is a function object, it has to define type result_type.
2951// We recommend deriving your functor classes from std::unary_function.
2952template <typename Callable, typename ResultOfMatcher>
2953internal::ResultOfMatcher<Callable> ResultOf(
2954 Callable callable, const ResultOfMatcher& matcher) {
2955 return internal::ResultOfMatcher<Callable>(
2956 callable,
2957 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2958 matcher));
2959 // The call to MatcherCast() is required for supporting inner
2960 // matchers of compatible types. For example, it allows
2961 // ResultOf(Function, m)
2962 // to compile where Function() returns an int32 and m is a matcher for int64.
2963}
2964
2965// String matchers.
2966
2967// Matches a string equal to str.
2968inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2969 StrEq(const internal::string& str) {
2970 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2971 str, true, true));
2972}
2973
2974// Matches a string not equal to str.
2975inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2976 StrNe(const internal::string& str) {
2977 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2978 str, false, true));
2979}
2980
2981// Matches a string equal to str, ignoring case.
2982inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2983 StrCaseEq(const internal::string& str) {
2984 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2985 str, true, false));
2986}
2987
2988// Matches a string not equal to str, ignoring case.
2989inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2990 StrCaseNe(const internal::string& str) {
2991 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2992 str, false, false));
2993}
2994
2995// Creates a matcher that matches any string, std::string, or C string
2996// that contains the given substring.
2997inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2998 HasSubstr(const internal::string& substring) {
2999 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
3000 substring));
3001}
3002
3003// Matches a string that starts with 'prefix' (case-sensitive).
3004inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
3005 StartsWith(const internal::string& prefix) {
3006 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
3007 prefix));
3008}
3009
3010// Matches a string that ends with 'suffix' (case-sensitive).
3011inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
3012 EndsWith(const internal::string& suffix) {
3013 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
3014 suffix));
3015}
3016
shiqiane35fdd92008-12-10 05:08:54 +00003017// Matches a string that fully matches regular expression 'regex'.
3018// The matcher takes ownership of 'regex'.
3019inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3020 const internal::RE* regex) {
3021 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
3022}
3023inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3024 const internal::string& regex) {
3025 return MatchesRegex(new internal::RE(regex));
3026}
3027
3028// Matches a string that contains regular expression 'regex'.
3029// The matcher takes ownership of 'regex'.
3030inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
3031 const internal::RE* regex) {
3032 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
3033}
3034inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
3035 const internal::string& regex) {
3036 return ContainsRegex(new internal::RE(regex));
3037}
3038
shiqiane35fdd92008-12-10 05:08:54 +00003039#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3040// Wide string matchers.
3041
3042// Matches a string equal to str.
3043inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3044 StrEq(const internal::wstring& str) {
3045 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3046 str, true, true));
3047}
3048
3049// Matches a string not equal to str.
3050inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3051 StrNe(const internal::wstring& str) {
3052 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3053 str, false, true));
3054}
3055
3056// Matches a string equal to str, ignoring case.
3057inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3058 StrCaseEq(const internal::wstring& str) {
3059 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3060 str, true, false));
3061}
3062
3063// Matches a string not equal to str, ignoring case.
3064inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3065 StrCaseNe(const internal::wstring& str) {
3066 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3067 str, false, false));
3068}
3069
3070// Creates a matcher that matches any wstring, std::wstring, or C wide string
3071// that contains the given substring.
3072inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
3073 HasSubstr(const internal::wstring& substring) {
3074 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
3075 substring));
3076}
3077
3078// Matches a string that starts with 'prefix' (case-sensitive).
3079inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
3080 StartsWith(const internal::wstring& prefix) {
3081 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
3082 prefix));
3083}
3084
3085// Matches a string that ends with 'suffix' (case-sensitive).
3086inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
3087 EndsWith(const internal::wstring& suffix) {
3088 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
3089 suffix));
3090}
3091
3092#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3093
3094// Creates a polymorphic matcher that matches a 2-tuple where the
3095// first field == the second field.
3096inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
3097
3098// Creates a polymorphic matcher that matches a 2-tuple where the
3099// first field >= the second field.
3100inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
3101
3102// Creates a polymorphic matcher that matches a 2-tuple where the
3103// first field > the second field.
3104inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
3105
3106// Creates a polymorphic matcher that matches a 2-tuple where the
3107// first field <= the second field.
3108inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
3109
3110// Creates a polymorphic matcher that matches a 2-tuple where the
3111// first field < the second field.
3112inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
3113
3114// Creates a polymorphic matcher that matches a 2-tuple where the
3115// first field != the second field.
3116inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
3117
3118// Creates a matcher that matches any value of type T that m doesn't
3119// match.
3120template <typename InnerMatcher>
3121inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
3122 return internal::NotMatcher<InnerMatcher>(m);
3123}
3124
shiqiane35fdd92008-12-10 05:08:54 +00003125// Returns a matcher that matches anything that satisfies the given
3126// predicate. The predicate can be any unary function or functor
3127// whose return type can be implicitly converted to bool.
3128template <typename Predicate>
3129inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
3130Truly(Predicate pred) {
3131 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
3132}
3133
zhanyong.wana31d9ce2013-03-01 01:50:17 +00003134// Returns a matcher that matches the container size. The container must
3135// support both size() and size_type which all STL-like containers provide.
3136// Note that the parameter 'size' can be a value of type size_type as well as
3137// matcher. For instance:
3138// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
3139// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
3140template <typename SizeMatcher>
3141inline internal::SizeIsMatcher<SizeMatcher>
3142SizeIs(const SizeMatcher& size_matcher) {
3143 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
3144}
3145
zhanyong.wan6a896b52009-01-16 01:13:50 +00003146// Returns a matcher that matches an equal container.
3147// This matcher behaves like Eq(), but in the event of mismatch lists the
3148// values that are included in one container but not the other. (Duplicate
3149// values and order differences are not explained.)
3150template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00003151inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00003152 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00003153 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00003154 // This following line is for working around a bug in MSVC 8.0,
3155 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00003156 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00003157 return MakePolymorphicMatcher(
3158 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00003159}
3160
zhanyong.wan898725c2011-09-16 16:45:39 +00003161// Returns a matcher that matches a container that, when sorted using
3162// the given comparator, matches container_matcher.
3163template <typename Comparator, typename ContainerMatcher>
3164inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
3165WhenSortedBy(const Comparator& comparator,
3166 const ContainerMatcher& container_matcher) {
3167 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
3168 comparator, container_matcher);
3169}
3170
3171// Returns a matcher that matches a container that, when sorted using
3172// the < operator, matches container_matcher.
3173template <typename ContainerMatcher>
3174inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
3175WhenSorted(const ContainerMatcher& container_matcher) {
3176 return
3177 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
3178 internal::LessComparator(), container_matcher);
3179}
3180
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003181// Matches an STL-style container or a native array that contains the
3182// same number of elements as in rhs, where its i-th element and rhs's
3183// i-th element (as a pair) satisfy the given pair matcher, for all i.
3184// TupleMatcher must be able to be safely cast to Matcher<tuple<const
3185// T1&, const T2&> >, where T1 and T2 are the types of elements in the
3186// LHS container and the RHS container respectively.
3187template <typename TupleMatcher, typename Container>
3188inline internal::PointwiseMatcher<TupleMatcher,
3189 GTEST_REMOVE_CONST_(Container)>
3190Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
3191 // This following line is for working around a bug in MSVC 8.0,
3192 // which causes Container to be a const type sometimes.
3193 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
3194 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
3195 tuple_matcher, rhs);
3196}
3197
zhanyong.wanb8243162009-06-04 05:48:20 +00003198// Matches an STL-style container or a native array that contains at
3199// least one element matching the given value or matcher.
3200//
3201// Examples:
3202// ::std::set<int> page_ids;
3203// page_ids.insert(3);
3204// page_ids.insert(1);
3205// EXPECT_THAT(page_ids, Contains(1));
3206// EXPECT_THAT(page_ids, Contains(Gt(2)));
3207// EXPECT_THAT(page_ids, Not(Contains(4)));
3208//
3209// ::std::map<int, size_t> page_lengths;
3210// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00003211// EXPECT_THAT(page_lengths,
3212// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00003213//
3214// const char* user_ids[] = { "joe", "mike", "tom" };
3215// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
3216template <typename M>
3217inline internal::ContainsMatcher<M> Contains(M matcher) {
3218 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00003219}
3220
zhanyong.wan33605ba2010-04-22 23:37:47 +00003221// Matches an STL-style container or a native array that contains only
3222// elements matching the given value or matcher.
3223//
3224// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
3225// the messages are different.
3226//
3227// Examples:
3228// ::std::set<int> page_ids;
3229// // Each(m) matches an empty container, regardless of what m is.
3230// EXPECT_THAT(page_ids, Each(Eq(1)));
3231// EXPECT_THAT(page_ids, Each(Eq(77)));
3232//
3233// page_ids.insert(3);
3234// EXPECT_THAT(page_ids, Each(Gt(0)));
3235// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
3236// page_ids.insert(1);
3237// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
3238//
3239// ::std::map<int, size_t> page_lengths;
3240// page_lengths[1] = 100;
3241// page_lengths[2] = 200;
3242// page_lengths[3] = 300;
3243// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
3244// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
3245//
3246// const char* user_ids[] = { "joe", "mike", "tom" };
3247// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
3248template <typename M>
3249inline internal::EachMatcher<M> Each(M matcher) {
3250 return internal::EachMatcher<M>(matcher);
3251}
3252
zhanyong.wanb5937da2009-07-16 20:26:41 +00003253// Key(inner_matcher) matches an std::pair whose 'first' field matches
3254// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3255// std::map that contains at least one element whose key is >= 5.
3256template <typename M>
3257inline internal::KeyMatcher<M> Key(M inner_matcher) {
3258 return internal::KeyMatcher<M>(inner_matcher);
3259}
3260
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003261// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
3262// matches first_matcher and whose 'second' field matches second_matcher. For
3263// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
3264// to match a std::map<int, string> that contains exactly one element whose key
3265// is >= 5 and whose value equals "foo".
3266template <typename FirstMatcher, typename SecondMatcher>
3267inline internal::PairMatcher<FirstMatcher, SecondMatcher>
3268Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
3269 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
3270 first_matcher, second_matcher);
3271}
3272
shiqiane35fdd92008-12-10 05:08:54 +00003273// Returns a predicate that is satisfied by anything that matches the
3274// given matcher.
3275template <typename M>
3276inline internal::MatcherAsPredicate<M> Matches(M matcher) {
3277 return internal::MatcherAsPredicate<M>(matcher);
3278}
3279
zhanyong.wanb8243162009-06-04 05:48:20 +00003280// Returns true iff the value matches the matcher.
3281template <typename T, typename M>
3282inline bool Value(const T& value, M matcher) {
3283 return testing::Matches(matcher)(value);
3284}
3285
zhanyong.wan34b034c2010-03-05 21:23:23 +00003286// Matches the value against the given matcher and explains the match
3287// result to listener.
3288template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00003289inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00003290 M matcher, const T& value, MatchResultListener* listener) {
3291 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
3292}
3293
zhanyong.wanbf550852009-06-09 06:09:53 +00003294// AllArgs(m) is a synonym of m. This is useful in
3295//
3296// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
3297//
3298// which is easier to read than
3299//
3300// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
3301template <typename InnerMatcher>
3302inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
3303
shiqiane35fdd92008-12-10 05:08:54 +00003304// These macros allow using matchers to check values in Google Test
3305// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
3306// succeed iff the value matches the matcher. If the assertion fails,
3307// the value and the description of the matcher will be printed.
3308#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
3309 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3310#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
3311 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3312
3313} // namespace testing
3314
3315#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_