blob: 0512ef44b864d790ac66fb9a365399bb4c04fcdf [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.wan616180e2013-06-18 18:49:51 +000041#include <math.h>
zhanyong.wan6a896b52009-01-16 01:13:50 +000042#include <algorithm>
zhanyong.wan16cf4732009-05-14 20:55:30 +000043#include <limits>
shiqiane35fdd92008-12-10 05:08:54 +000044#include <ostream> // NOLINT
45#include <sstream>
46#include <string>
zhanyong.wanab5b77c2010-05-17 19:32:48 +000047#include <utility>
shiqiane35fdd92008-12-10 05:08:54 +000048#include <vector>
49
zhanyong.wan53e08c42010-09-14 05:38:21 +000050#include "gmock/internal/gmock-internal-utils.h"
51#include "gmock/internal/gmock-port.h"
52#include "gtest/gtest.h"
shiqiane35fdd92008-12-10 05:08:54 +000053
54namespace testing {
55
56// To implement a matcher Foo for type T, define:
57// 1. a class FooMatcherImpl that implements the
58// MatcherInterface<T> interface, and
59// 2. a factory function that creates a Matcher<T> object from a
60// FooMatcherImpl*.
61//
62// The two-level delegation design makes it possible to allow a user
63// to write "v" instead of "Eq(v)" where a Matcher is expected, which
64// is impossible if we pass matchers by pointers. It also eases
65// ownership management as Matcher objects can now be copied like
66// plain values.
67
zhanyong.wan82113312010-01-08 21:55:40 +000068// MatchResultListener is an abstract class. Its << operator can be
69// used by a matcher to explain why a value matches or doesn't match.
70//
71// TODO(wan@google.com): add method
72// bool InterestedInWhy(bool result) const;
73// to indicate whether the listener is interested in why the match
74// result is 'result'.
75class MatchResultListener {
76 public:
77 // Creates a listener object with the given underlying ostream. The
78 // listener does not own the ostream.
79 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
80 virtual ~MatchResultListener() = 0; // Makes this class abstract.
81
82 // Streams x to the underlying ostream; does nothing if the ostream
83 // is NULL.
84 template <typename T>
85 MatchResultListener& operator<<(const T& x) {
86 if (stream_ != NULL)
87 *stream_ << x;
88 return *this;
89 }
90
91 // Returns the underlying ostream.
92 ::std::ostream* stream() { return stream_; }
93
zhanyong.wana862f1d2010-03-15 21:23:04 +000094 // Returns true iff the listener is interested in an explanation of
95 // the match result. A matcher's MatchAndExplain() method can use
96 // this information to avoid generating the explanation when no one
97 // intends to hear it.
98 bool IsInterested() const { return stream_ != NULL; }
99
zhanyong.wan82113312010-01-08 21:55:40 +0000100 private:
101 ::std::ostream* const stream_;
102
103 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
104};
105
106inline MatchResultListener::~MatchResultListener() {
107}
108
shiqiane35fdd92008-12-10 05:08:54 +0000109// The implementation of a matcher.
110template <typename T>
111class MatcherInterface {
112 public:
113 virtual ~MatcherInterface() {}
114
zhanyong.wan82113312010-01-08 21:55:40 +0000115 // Returns true iff the matcher matches x; also explains the match
zhanyong.wan83f6b082013-03-01 01:47:35 +0000116 // result to 'listener' if necessary (see the next paragraph), in
117 // the form of a non-restrictive relative clause ("which ...",
118 // "whose ...", etc) that describes x. For example, the
119 // MatchAndExplain() method of the Pointee(...) matcher should
120 // generate an explanation like "which points to ...".
121 //
122 // Implementations of MatchAndExplain() should add an explanation of
123 // the match result *if and only if* they can provide additional
124 // information that's not already present (or not obvious) in the
125 // print-out of x and the matcher's description. Whether the match
126 // succeeds is not a factor in deciding whether an explanation is
127 // needed, as sometimes the caller needs to print a failure message
128 // when the match succeeds (e.g. when the matcher is used inside
129 // Not()).
130 //
131 // For example, a "has at least 10 elements" matcher should explain
132 // what the actual element count is, regardless of the match result,
133 // as it is useful information to the reader; on the other hand, an
134 // "is empty" matcher probably only needs to explain what the actual
135 // size is when the match fails, as it's redundant to say that the
136 // size is 0 when the value is already known to be empty.
zhanyong.wan82113312010-01-08 21:55:40 +0000137 //
zhanyong.wandb22c222010-01-28 21:52:29 +0000138 // You should override this method when defining a new matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000139 //
140 // It's the responsibility of the caller (Google Mock) to guarantee
141 // that 'listener' is not NULL. This helps to simplify a matcher's
142 // implementation when it doesn't care about the performance, as it
143 // can talk to 'listener' without checking its validity first.
144 // However, in order to implement dummy listeners efficiently,
145 // listener->stream() may be NULL.
zhanyong.wandb22c222010-01-28 21:52:29 +0000146 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
shiqiane35fdd92008-12-10 05:08:54 +0000147
zhanyong.wana862f1d2010-03-15 21:23:04 +0000148 // Describes this matcher to an ostream. The function should print
149 // a verb phrase that describes the property a value matching this
150 // matcher should have. The subject of the verb phrase is the value
151 // being matched. For example, the DescribeTo() method of the Gt(7)
152 // matcher prints "is greater than 7".
shiqiane35fdd92008-12-10 05:08:54 +0000153 virtual void DescribeTo(::std::ostream* os) const = 0;
154
155 // Describes the negation of this matcher to an ostream. For
156 // example, if the description of this matcher is "is greater than
157 // 7", the negated description could be "is not greater than 7".
158 // You are not required to override this when implementing
159 // MatcherInterface, but it is highly advised so that your matcher
160 // can produce good error messages.
161 virtual void DescribeNegationTo(::std::ostream* os) const {
162 *os << "not (";
163 DescribeTo(os);
164 *os << ")";
165 }
shiqiane35fdd92008-12-10 05:08:54 +0000166};
167
168namespace internal {
169
zhanyong.wan82113312010-01-08 21:55:40 +0000170// A match result listener that ignores the explanation.
171class DummyMatchResultListener : public MatchResultListener {
172 public:
173 DummyMatchResultListener() : MatchResultListener(NULL) {}
174
175 private:
176 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
177};
178
179// A match result listener that forwards the explanation to a given
180// ostream. The difference between this and MatchResultListener is
181// that the former is concrete.
182class StreamMatchResultListener : public MatchResultListener {
183 public:
184 explicit StreamMatchResultListener(::std::ostream* os)
185 : MatchResultListener(os) {}
186
187 private:
188 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
189};
190
191// A match result listener that stores the explanation in a string.
192class StringMatchResultListener : public MatchResultListener {
193 public:
194 StringMatchResultListener() : MatchResultListener(&ss_) {}
195
196 // Returns the explanation heard so far.
197 internal::string str() const { return ss_.str(); }
198
199 private:
200 ::std::stringstream ss_;
201
202 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
203};
204
shiqiane35fdd92008-12-10 05:08:54 +0000205// An internal class for implementing Matcher<T>, which will derive
206// from it. We put functionalities common to all Matcher<T>
207// specializations here to avoid code duplication.
208template <typename T>
209class MatcherBase {
210 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000211 // Returns true iff the matcher matches x; also explains the match
212 // result to 'listener'.
213 bool MatchAndExplain(T x, MatchResultListener* listener) const {
214 return impl_->MatchAndExplain(x, listener);
215 }
216
shiqiane35fdd92008-12-10 05:08:54 +0000217 // Returns true iff this matcher matches x.
zhanyong.wan82113312010-01-08 21:55:40 +0000218 bool Matches(T x) const {
219 DummyMatchResultListener dummy;
220 return MatchAndExplain(x, &dummy);
221 }
shiqiane35fdd92008-12-10 05:08:54 +0000222
223 // Describes this matcher to an ostream.
224 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
225
226 // Describes the negation of this matcher to an ostream.
227 void DescribeNegationTo(::std::ostream* os) const {
228 impl_->DescribeNegationTo(os);
229 }
230
231 // Explains why x matches, or doesn't match, the matcher.
232 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000233 StreamMatchResultListener listener(os);
234 MatchAndExplain(x, &listener);
shiqiane35fdd92008-12-10 05:08:54 +0000235 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000236
shiqiane35fdd92008-12-10 05:08:54 +0000237 protected:
238 MatcherBase() {}
239
240 // Constructs a matcher from its implementation.
241 explicit MatcherBase(const MatcherInterface<T>* impl)
242 : impl_(impl) {}
243
244 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000245
shiqiane35fdd92008-12-10 05:08:54 +0000246 private:
247 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
248 // interfaces. The former dynamically allocates a chunk of memory
249 // to hold the reference count, while the latter tracks all
250 // references using a circular linked list without allocating
251 // memory. It has been observed that linked_ptr performs better in
252 // typical scenarios. However, shared_ptr can out-perform
253 // linked_ptr when there are many more uses of the copy constructor
254 // than the default constructor.
255 //
256 // If performance becomes a problem, we should see if using
257 // shared_ptr helps.
258 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
259};
260
shiqiane35fdd92008-12-10 05:08:54 +0000261} // namespace internal
262
263// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
264// object that can check whether a value of type T matches. The
265// implementation of Matcher<T> is just a linked_ptr to const
266// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
267// from Matcher!
268template <typename T>
269class Matcher : public internal::MatcherBase<T> {
270 public:
vladlosev88032d82010-11-17 23:29:21 +0000271 // Constructs a null matcher. Needed for storing Matcher objects in STL
272 // containers. A default-constructed matcher is not yet initialized. You
273 // cannot use it until a valid value has been assigned to it.
shiqiane35fdd92008-12-10 05:08:54 +0000274 Matcher() {}
275
276 // Constructs a matcher from its implementation.
277 explicit Matcher(const MatcherInterface<T>* impl)
278 : internal::MatcherBase<T>(impl) {}
279
zhanyong.wan18490652009-05-11 18:54:08 +0000280 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000281 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
282 Matcher(T value); // NOLINT
283};
284
285// The following two specializations allow the user to write str
286// instead of Eq(str) and "foo" instead of Eq("foo") when a string
287// matcher is expected.
288template <>
vladlosev587c1b32011-05-20 00:42:22 +0000289class GTEST_API_ Matcher<const internal::string&>
shiqiane35fdd92008-12-10 05:08:54 +0000290 : public internal::MatcherBase<const internal::string&> {
291 public:
292 Matcher() {}
293
294 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
295 : internal::MatcherBase<const internal::string&>(impl) {}
296
297 // Allows the user to write str instead of Eq(str) sometimes, where
298 // str is a string object.
299 Matcher(const internal::string& s); // NOLINT
300
301 // Allows the user to write "foo" instead of Eq("foo") sometimes.
302 Matcher(const char* s); // NOLINT
303};
304
305template <>
vladlosev587c1b32011-05-20 00:42:22 +0000306class GTEST_API_ Matcher<internal::string>
shiqiane35fdd92008-12-10 05:08:54 +0000307 : public internal::MatcherBase<internal::string> {
308 public:
309 Matcher() {}
310
311 explicit Matcher(const MatcherInterface<internal::string>* impl)
312 : internal::MatcherBase<internal::string>(impl) {}
313
314 // Allows the user to write str instead of Eq(str) sometimes, where
315 // str is a string object.
316 Matcher(const internal::string& s); // NOLINT
317
318 // Allows the user to write "foo" instead of Eq("foo") sometimes.
319 Matcher(const char* s); // NOLINT
320};
321
zhanyong.wan1f122a02013-03-25 16:27:03 +0000322#if GTEST_HAS_STRING_PIECE_
323// The following two specializations allow the user to write str
324// instead of Eq(str) and "foo" instead of Eq("foo") when a StringPiece
325// matcher is expected.
326template <>
327class GTEST_API_ Matcher<const StringPiece&>
328 : public internal::MatcherBase<const StringPiece&> {
329 public:
330 Matcher() {}
331
332 explicit Matcher(const MatcherInterface<const StringPiece&>* impl)
333 : internal::MatcherBase<const StringPiece&>(impl) {}
334
335 // Allows the user to write str instead of Eq(str) sometimes, where
336 // str is a string object.
337 Matcher(const internal::string& s); // NOLINT
338
339 // Allows the user to write "foo" instead of Eq("foo") sometimes.
340 Matcher(const char* s); // NOLINT
341
342 // Allows the user to pass StringPieces directly.
343 Matcher(StringPiece s); // NOLINT
344};
345
346template <>
347class GTEST_API_ Matcher<StringPiece>
348 : public internal::MatcherBase<StringPiece> {
349 public:
350 Matcher() {}
351
352 explicit Matcher(const MatcherInterface<StringPiece>* impl)
353 : internal::MatcherBase<StringPiece>(impl) {}
354
355 // Allows the user to write str instead of Eq(str) sometimes, where
356 // str is a string object.
357 Matcher(const internal::string& s); // NOLINT
358
359 // Allows the user to write "foo" instead of Eq("foo") sometimes.
360 Matcher(const char* s); // NOLINT
361
362 // Allows the user to pass StringPieces directly.
363 Matcher(StringPiece s); // NOLINT
364};
365#endif // GTEST_HAS_STRING_PIECE_
366
shiqiane35fdd92008-12-10 05:08:54 +0000367// The PolymorphicMatcher class template makes it easy to implement a
368// polymorphic matcher (i.e. a matcher that can match values of more
369// than one type, e.g. Eq(n) and NotNull()).
370//
zhanyong.wandb22c222010-01-28 21:52:29 +0000371// To define a polymorphic matcher, a user should provide an Impl
372// class that has a DescribeTo() method and a DescribeNegationTo()
373// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000374//
zhanyong.wandb22c222010-01-28 21:52:29 +0000375// bool MatchAndExplain(const Value& value,
376// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000377//
378// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000379template <class Impl>
380class PolymorphicMatcher {
381 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000382 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000383
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000384 // Returns a mutable reference to the underlying matcher
385 // implementation object.
386 Impl& mutable_impl() { return impl_; }
387
388 // Returns an immutable reference to the underlying matcher
389 // implementation object.
390 const Impl& impl() const { return impl_; }
391
shiqiane35fdd92008-12-10 05:08:54 +0000392 template <typename T>
393 operator Matcher<T>() const {
394 return Matcher<T>(new MonomorphicImpl<T>(impl_));
395 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000396
shiqiane35fdd92008-12-10 05:08:54 +0000397 private:
398 template <typename T>
399 class MonomorphicImpl : public MatcherInterface<T> {
400 public:
401 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
402
shiqiane35fdd92008-12-10 05:08:54 +0000403 virtual void DescribeTo(::std::ostream* os) const {
404 impl_.DescribeTo(os);
405 }
406
407 virtual void DescribeNegationTo(::std::ostream* os) const {
408 impl_.DescribeNegationTo(os);
409 }
410
zhanyong.wan82113312010-01-08 21:55:40 +0000411 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000412 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000413 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000414
shiqiane35fdd92008-12-10 05:08:54 +0000415 private:
416 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000417
418 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000419 };
420
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000421 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000422
423 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000424};
425
426// Creates a matcher from its implementation. This is easier to use
427// than the Matcher<T> constructor as it doesn't require you to
428// explicitly write the template argument, e.g.
429//
430// MakeMatcher(foo);
431// vs
432// Matcher<const string&>(foo);
433template <typename T>
434inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
435 return Matcher<T>(impl);
zhanyong.wan2eab17b2013-03-08 17:53:24 +0000436}
shiqiane35fdd92008-12-10 05:08:54 +0000437
438// Creates a polymorphic matcher from its implementation. This is
439// easier to use than the PolymorphicMatcher<Impl> constructor as it
440// doesn't require you to explicitly write the template argument, e.g.
441//
442// MakePolymorphicMatcher(foo);
443// vs
444// PolymorphicMatcher<TypeOfFoo>(foo);
445template <class Impl>
446inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
447 return PolymorphicMatcher<Impl>(impl);
448}
449
jgm79a367e2012-04-10 16:02:11 +0000450// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
451// and MUST NOT BE USED IN USER CODE!!!
452namespace internal {
453
454// The MatcherCastImpl class template is a helper for implementing
455// MatcherCast(). We need this helper in order to partially
456// specialize the implementation of MatcherCast() (C++ allows
457// class/struct templates to be partially specialized, but not
458// function templates.).
459
460// This general version is used when MatcherCast()'s argument is a
461// polymorphic matcher (i.e. something that can be converted to a
462// Matcher but is not one yet; for example, Eq(value)) or a value (for
463// example, "hello").
464template <typename T, typename M>
465class MatcherCastImpl {
466 public:
467 static Matcher<T> Cast(M polymorphic_matcher_or_value) {
468 // M can be a polymorhic matcher, in which case we want to use
469 // its conversion operator to create Matcher<T>. Or it can be a value
470 // that should be passed to the Matcher<T>'s constructor.
471 //
472 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
473 // polymorphic matcher because it'll be ambiguous if T has an implicit
474 // constructor from M (this usually happens when T has an implicit
475 // constructor from any type).
476 //
477 // It won't work to unconditionally implict_cast
478 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
479 // a user-defined conversion from M to T if one exists (assuming M is
480 // a value).
481 return CastImpl(
482 polymorphic_matcher_or_value,
483 BooleanConstant<
484 internal::ImplicitlyConvertible<M, Matcher<T> >::value>());
485 }
486
487 private:
488 static Matcher<T> CastImpl(M value, BooleanConstant<false>) {
489 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
490 // matcher. It must be a value then. Use direct initialization to create
491 // a matcher.
492 return Matcher<T>(ImplicitCast_<T>(value));
493 }
494
495 static Matcher<T> CastImpl(M polymorphic_matcher_or_value,
496 BooleanConstant<true>) {
497 // M is implicitly convertible to Matcher<T>, which means that either
498 // M is a polymorhpic matcher or Matcher<T> has an implicit constructor
499 // from M. In both cases using the implicit conversion will produce a
500 // matcher.
501 //
502 // Even if T has an implicit constructor from M, it won't be called because
503 // creating Matcher<T> would require a chain of two user-defined conversions
504 // (first to create T from M and then to create Matcher<T> from T).
505 return polymorphic_matcher_or_value;
506 }
507};
508
509// This more specialized version is used when MatcherCast()'s argument
510// is already a Matcher. This only compiles when type T can be
511// statically converted to type U.
512template <typename T, typename U>
513class MatcherCastImpl<T, Matcher<U> > {
514 public:
515 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
516 return Matcher<T>(new Impl(source_matcher));
517 }
518
519 private:
520 class Impl : public MatcherInterface<T> {
521 public:
522 explicit Impl(const Matcher<U>& source_matcher)
523 : source_matcher_(source_matcher) {}
524
525 // We delegate the matching logic to the source matcher.
526 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
527 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
528 }
529
530 virtual void DescribeTo(::std::ostream* os) const {
531 source_matcher_.DescribeTo(os);
532 }
533
534 virtual void DescribeNegationTo(::std::ostream* os) const {
535 source_matcher_.DescribeNegationTo(os);
536 }
537
538 private:
539 const Matcher<U> source_matcher_;
540
541 GTEST_DISALLOW_ASSIGN_(Impl);
542 };
543};
544
545// This even more specialized version is used for efficiently casting
546// a matcher to its own type.
547template <typename T>
548class MatcherCastImpl<T, Matcher<T> > {
549 public:
550 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
551};
552
553} // namespace internal
554
shiqiane35fdd92008-12-10 05:08:54 +0000555// In order to be safe and clear, casting between different matcher
556// types is done explicitly via MatcherCast<T>(m), which takes a
557// matcher m and returns a Matcher<T>. It compiles only when T can be
558// statically converted to the argument type of m.
559template <typename T, typename M>
jgm79a367e2012-04-10 16:02:11 +0000560inline Matcher<T> MatcherCast(M matcher) {
561 return internal::MatcherCastImpl<T, M>::Cast(matcher);
562}
shiqiane35fdd92008-12-10 05:08:54 +0000563
zhanyong.wan18490652009-05-11 18:54:08 +0000564// Implements SafeMatcherCast().
565//
zhanyong.wan95b12332009-09-25 18:55:50 +0000566// We use an intermediate class to do the actual safe casting as Nokia's
567// Symbian compiler cannot decide between
568// template <T, M> ... (M) and
569// template <T, U> ... (const Matcher<U>&)
570// for function templates but can for member function templates.
571template <typename T>
572class SafeMatcherCastImpl {
573 public:
jgm79a367e2012-04-10 16:02:11 +0000574 // This overload handles polymorphic matchers and values only since
575 // monomorphic matchers are handled by the next one.
zhanyong.wan95b12332009-09-25 18:55:50 +0000576 template <typename M>
jgm79a367e2012-04-10 16:02:11 +0000577 static inline Matcher<T> Cast(M polymorphic_matcher_or_value) {
578 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
zhanyong.wan95b12332009-09-25 18:55:50 +0000579 }
zhanyong.wan18490652009-05-11 18:54:08 +0000580
zhanyong.wan95b12332009-09-25 18:55:50 +0000581 // This overload handles monomorphic matchers.
582 //
583 // In general, if type T can be implicitly converted to type U, we can
584 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
585 // contravariant): just keep a copy of the original Matcher<U>, convert the
586 // argument from type T to U, and then pass it to the underlying Matcher<U>.
587 // The only exception is when U is a reference and T is not, as the
588 // underlying Matcher<U> may be interested in the argument's address, which
589 // is not preserved in the conversion from T to U.
590 template <typename U>
591 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
592 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000593 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000594 T_must_be_implicitly_convertible_to_U);
595 // Enforce that we are not converting a non-reference type T to a reference
596 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000597 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000598 internal::is_reference<T>::value || !internal::is_reference<U>::value,
599 cannot_convert_non_referentce_arg_to_reference);
600 // In case both T and U are arithmetic types, enforce that the
601 // conversion is not lossy.
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000602 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
603 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000604 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
605 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000606 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000607 kTIsOther || kUIsOther ||
608 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
609 conversion_of_arithmetic_types_must_be_lossless);
610 return MatcherCast<T>(matcher);
611 }
612};
613
614template <typename T, typename M>
615inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
616 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000617}
618
shiqiane35fdd92008-12-10 05:08:54 +0000619// A<T>() returns a matcher that matches any value of type T.
620template <typename T>
621Matcher<T> A();
622
623// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
624// and MUST NOT BE USED IN USER CODE!!!
625namespace internal {
626
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000627// If the explanation is not empty, prints it to the ostream.
628inline void PrintIfNotEmpty(const internal::string& explanation,
629 std::ostream* os) {
630 if (explanation != "" && os != NULL) {
631 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000632 }
633}
634
zhanyong.wan736baa82010-09-27 17:44:16 +0000635// Returns true if the given type name is easy to read by a human.
636// This is used to decide whether printing the type of a value might
637// be helpful.
638inline bool IsReadableTypeName(const string& type_name) {
639 // We consider a type name readable if it's short or doesn't contain
640 // a template or function type.
641 return (type_name.length() <= 20 ||
642 type_name.find_first_of("<(") == string::npos);
643}
644
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000645// Matches the value against the given matcher, prints the value and explains
646// the match result to the listener. Returns the match result.
647// 'listener' must not be NULL.
648// Value cannot be passed by const reference, because some matchers take a
649// non-const argument.
650template <typename Value, typename T>
651bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
652 MatchResultListener* listener) {
653 if (!listener->IsInterested()) {
654 // If the listener is not interested, we do not need to construct the
655 // inner explanation.
656 return matcher.Matches(value);
657 }
658
659 StringMatchResultListener inner_listener;
660 const bool match = matcher.MatchAndExplain(value, &inner_listener);
661
662 UniversalPrint(value, listener->stream());
zhanyong.wan736baa82010-09-27 17:44:16 +0000663#if GTEST_HAS_RTTI
664 const string& type_name = GetTypeName<Value>();
665 if (IsReadableTypeName(type_name))
666 *listener->stream() << " (of type " << type_name << ")";
667#endif
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000668 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000669
670 return match;
671}
672
shiqiane35fdd92008-12-10 05:08:54 +0000673// An internal helper class for doing compile-time loop on a tuple's
674// fields.
675template <size_t N>
676class TuplePrefix {
677 public:
678 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
679 // iff the first N fields of matcher_tuple matches the first N
680 // fields of value_tuple, respectively.
681 template <typename MatcherTuple, typename ValueTuple>
682 static bool Matches(const MatcherTuple& matcher_tuple,
683 const ValueTuple& value_tuple) {
684 using ::std::tr1::get;
685 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
686 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
687 }
688
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000689 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000690 // describes failures in matching the first N fields of matchers
691 // against the first N fields of values. If there is no failure,
692 // nothing will be streamed to os.
693 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000694 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
695 const ValueTuple& values,
696 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000697 using ::std::tr1::tuple_element;
698 using ::std::tr1::get;
699
700 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000701 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000702
703 // Then describes the failure (if any) in the (N - 1)-th (0-based)
704 // field.
705 typename tuple_element<N - 1, MatcherTuple>::type matcher =
706 get<N - 1>(matchers);
707 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
708 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000709 StringMatchResultListener listener;
710 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000711 // TODO(wan): include in the message the name of the parameter
712 // as used in MOCK_METHOD*() when possible.
713 *os << " Expected arg #" << N - 1 << ": ";
714 get<N - 1>(matchers).DescribeTo(os);
715 *os << "\n Actual: ";
716 // We remove the reference in type Value to prevent the
717 // universal printer from printing the address of value, which
718 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000719 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000720 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000721 internal::UniversalPrint(value, os);
722 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000723 *os << "\n";
724 }
725 }
726};
727
728// The base case.
729template <>
730class TuplePrefix<0> {
731 public:
732 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000733 static bool Matches(const MatcherTuple& /* matcher_tuple */,
734 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000735 return true;
736 }
737
738 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000739 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
740 const ValueTuple& /* values */,
741 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000742};
743
744// TupleMatches(matcher_tuple, value_tuple) returns true iff all
745// matchers in matcher_tuple match the corresponding fields in
746// value_tuple. It is a compiler error if matcher_tuple and
747// value_tuple have different number of fields or incompatible field
748// types.
749template <typename MatcherTuple, typename ValueTuple>
750bool TupleMatches(const MatcherTuple& matcher_tuple,
751 const ValueTuple& value_tuple) {
752 using ::std::tr1::tuple_size;
753 // Makes sure that matcher_tuple and value_tuple have the same
754 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000755 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000756 tuple_size<ValueTuple>::value,
757 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000758 return TuplePrefix<tuple_size<ValueTuple>::value>::
759 Matches(matcher_tuple, value_tuple);
760}
761
762// Describes failures in matching matchers against values. If there
763// is no failure, nothing will be streamed to os.
764template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000765void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
766 const ValueTuple& values,
767 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000768 using ::std::tr1::tuple_size;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000769 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000770 matchers, values, os);
771}
772
shiqiane35fdd92008-12-10 05:08:54 +0000773// Implements A<T>().
774template <typename T>
775class AnyMatcherImpl : public MatcherInterface<T> {
776 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000777 virtual bool MatchAndExplain(
778 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000779 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
780 virtual void DescribeNegationTo(::std::ostream* os) const {
781 // This is mostly for completeness' safe, as it's not very useful
782 // to write Not(A<bool>()). However we cannot completely rule out
783 // such a possibility, and it doesn't hurt to be prepared.
784 *os << "never matches";
785 }
786};
787
788// Implements _, a matcher that matches any value of any
789// type. This is a polymorphic matcher, so we need a template type
790// conversion operator to make it appearing as a Matcher<T> for any
791// type T.
792class AnythingMatcher {
793 public:
794 template <typename T>
795 operator Matcher<T>() const { return A<T>(); }
796};
797
798// Implements a matcher that compares a given value with a
799// pre-supplied value using one of the ==, <=, <, etc, operators. The
800// two values being compared don't have to have the same type.
801//
802// The matcher defined here is polymorphic (for example, Eq(5) can be
803// used to match an int, a short, a double, etc). Therefore we use
804// a template type conversion operator in the implementation.
805//
806// We define this as a macro in order to eliminate duplicated source
807// code.
808//
809// The following template definition assumes that the Rhs parameter is
810// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000811#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_( \
812 name, op, relation, negated_relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000813 template <typename Rhs> class name##Matcher { \
814 public: \
815 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
816 template <typename Lhs> \
817 operator Matcher<Lhs>() const { \
818 return MakeMatcher(new Impl<Lhs>(rhs_)); \
819 } \
820 private: \
821 template <typename Lhs> \
822 class Impl : public MatcherInterface<Lhs> { \
823 public: \
824 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
zhanyong.wan82113312010-01-08 21:55:40 +0000825 virtual bool MatchAndExplain(\
826 Lhs lhs, MatchResultListener* /* listener */) const { \
827 return lhs op rhs_; \
828 } \
shiqiane35fdd92008-12-10 05:08:54 +0000829 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000830 *os << relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000831 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000832 } \
833 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000834 *os << negated_relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000835 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000836 } \
837 private: \
838 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000839 GTEST_DISALLOW_ASSIGN_(Impl); \
shiqiane35fdd92008-12-10 05:08:54 +0000840 }; \
841 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000842 GTEST_DISALLOW_ASSIGN_(name##Matcher); \
shiqiane35fdd92008-12-10 05:08:54 +0000843 }
844
845// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
846// respectively.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000847GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "is equal to", "isn't equal to");
848GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "is >=", "isn't >=");
849GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "is >", "isn't >");
850GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "is <=", "isn't <=");
851GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "is <", "isn't <");
852GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "isn't equal to", "is equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000853
zhanyong.wane0d051e2009-02-19 00:33:37 +0000854#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000855
vladlosev79b83502009-11-18 00:43:37 +0000856// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000857// pointer that is NULL.
858class IsNullMatcher {
859 public:
vladlosev79b83502009-11-18 00:43:37 +0000860 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000861 bool MatchAndExplain(const Pointer& p,
862 MatchResultListener* /* listener */) const {
863 return GetRawPointer(p) == NULL;
864 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000865
866 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
867 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000868 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000869 }
870};
871
vladlosev79b83502009-11-18 00:43:37 +0000872// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000873// pointer that is not NULL.
874class NotNullMatcher {
875 public:
vladlosev79b83502009-11-18 00:43:37 +0000876 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000877 bool MatchAndExplain(const Pointer& p,
878 MatchResultListener* /* listener */) const {
879 return GetRawPointer(p) != NULL;
880 }
shiqiane35fdd92008-12-10 05:08:54 +0000881
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000882 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +0000883 void DescribeNegationTo(::std::ostream* os) const {
884 *os << "is NULL";
885 }
886};
887
888// Ref(variable) matches any argument that is a reference to
889// 'variable'. This matcher is polymorphic as it can match any
890// super type of the type of 'variable'.
891//
892// The RefMatcher template class implements Ref(variable). It can
893// only be instantiated with a reference type. This prevents a user
894// from mistakenly using Ref(x) to match a non-reference function
895// argument. For example, the following will righteously cause a
896// compiler error:
897//
898// int n;
899// Matcher<int> m1 = Ref(n); // This won't compile.
900// Matcher<int&> m2 = Ref(n); // This will compile.
901template <typename T>
902class RefMatcher;
903
904template <typename T>
905class RefMatcher<T&> {
906 // Google Mock is a generic framework and thus needs to support
907 // mocking any function types, including those that take non-const
908 // reference arguments. Therefore the template parameter T (and
909 // Super below) can be instantiated to either a const type or a
910 // non-const type.
911 public:
912 // RefMatcher() takes a T& instead of const T&, as we want the
913 // compiler to catch using Ref(const_value) as a matcher for a
914 // non-const reference.
915 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
916
917 template <typename Super>
918 operator Matcher<Super&>() const {
919 // By passing object_ (type T&) to Impl(), which expects a Super&,
920 // we make sure that Super is a super type of T. In particular,
921 // this catches using Ref(const_value) as a matcher for a
922 // non-const reference, as you cannot implicitly convert a const
923 // reference to a non-const reference.
924 return MakeMatcher(new Impl<Super>(object_));
925 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000926
shiqiane35fdd92008-12-10 05:08:54 +0000927 private:
928 template <typename Super>
929 class Impl : public MatcherInterface<Super&> {
930 public:
931 explicit Impl(Super& x) : object_(x) {} // NOLINT
932
zhanyong.wandb22c222010-01-28 21:52:29 +0000933 // MatchAndExplain() takes a Super& (as opposed to const Super&)
934 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +0000935 virtual bool MatchAndExplain(
936 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000937 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +0000938 return &x == &object_;
939 }
shiqiane35fdd92008-12-10 05:08:54 +0000940
941 virtual void DescribeTo(::std::ostream* os) const {
942 *os << "references the variable ";
943 UniversalPrinter<Super&>::Print(object_, os);
944 }
945
946 virtual void DescribeNegationTo(::std::ostream* os) const {
947 *os << "does not reference the variable ";
948 UniversalPrinter<Super&>::Print(object_, os);
949 }
950
shiqiane35fdd92008-12-10 05:08:54 +0000951 private:
952 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000953
954 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000955 };
956
957 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000958
959 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000960};
961
962// Polymorphic helper functions for narrow and wide string matchers.
963inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
964 return String::CaseInsensitiveCStringEquals(lhs, rhs);
965}
966
967inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
968 const wchar_t* rhs) {
969 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
970}
971
972// String comparison for narrow or wide strings that can have embedded NUL
973// characters.
974template <typename StringType>
975bool CaseInsensitiveStringEquals(const StringType& s1,
976 const StringType& s2) {
977 // Are the heads equal?
978 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
979 return false;
980 }
981
982 // Skip the equal heads.
983 const typename StringType::value_type nul = 0;
984 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
985
986 // Are we at the end of either s1 or s2?
987 if (i1 == StringType::npos || i2 == StringType::npos) {
988 return i1 == i2;
989 }
990
991 // Are the tails equal?
992 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
993}
994
995// String matchers.
996
997// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
998template <typename StringType>
999class StrEqualityMatcher {
1000 public:
shiqiane35fdd92008-12-10 05:08:54 +00001001 StrEqualityMatcher(const StringType& str, bool expect_eq,
1002 bool case_sensitive)
1003 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1004
jgm38513a82012-11-15 15:50:36 +00001005 // Accepts pointer types, particularly:
1006 // const char*
1007 // char*
1008 // const wchar_t*
1009 // wchar_t*
1010 template <typename CharType>
1011 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001012 if (s == NULL) {
1013 return !expect_eq_;
1014 }
zhanyong.wandb22c222010-01-28 21:52:29 +00001015 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001016 }
1017
jgm38513a82012-11-15 15:50:36 +00001018 // Matches anything that can convert to StringType.
1019 //
1020 // This is a template, not just a plain function with const StringType&,
1021 // because StringPiece has some interfering non-explicit constructors.
1022 template <typename MatcheeStringType>
1023 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001024 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001025 const StringType& s2(s);
1026 const bool eq = case_sensitive_ ? s2 == string_ :
1027 CaseInsensitiveStringEquals(s2, string_);
shiqiane35fdd92008-12-10 05:08:54 +00001028 return expect_eq_ == eq;
1029 }
1030
1031 void DescribeTo(::std::ostream* os) const {
1032 DescribeToHelper(expect_eq_, os);
1033 }
1034
1035 void DescribeNegationTo(::std::ostream* os) const {
1036 DescribeToHelper(!expect_eq_, os);
1037 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001038
shiqiane35fdd92008-12-10 05:08:54 +00001039 private:
1040 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001041 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +00001042 *os << "equal to ";
1043 if (!case_sensitive_) {
1044 *os << "(ignoring case) ";
1045 }
vladloseve2e8ba42010-05-13 18:16:03 +00001046 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001047 }
1048
1049 const StringType string_;
1050 const bool expect_eq_;
1051 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001052
1053 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001054};
1055
1056// Implements the polymorphic HasSubstr(substring) matcher, which
1057// can be used as a Matcher<T> as long as T can be converted to a
1058// string.
1059template <typename StringType>
1060class HasSubstrMatcher {
1061 public:
shiqiane35fdd92008-12-10 05:08:54 +00001062 explicit HasSubstrMatcher(const StringType& substring)
1063 : substring_(substring) {}
1064
jgm38513a82012-11-15 15:50:36 +00001065 // Accepts pointer types, particularly:
1066 // const char*
1067 // char*
1068 // const wchar_t*
1069 // wchar_t*
1070 template <typename CharType>
1071 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001072 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001073 }
1074
jgm38513a82012-11-15 15:50:36 +00001075 // Matches anything that can convert to StringType.
1076 //
1077 // This is a template, not just a plain function with const StringType&,
1078 // because StringPiece has some interfering non-explicit constructors.
1079 template <typename MatcheeStringType>
1080 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001081 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001082 const StringType& s2(s);
1083 return s2.find(substring_) != StringType::npos;
shiqiane35fdd92008-12-10 05:08:54 +00001084 }
1085
1086 // Describes what this matcher matches.
1087 void DescribeTo(::std::ostream* os) const {
1088 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001089 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001090 }
1091
1092 void DescribeNegationTo(::std::ostream* os) const {
1093 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001094 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001095 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001096
shiqiane35fdd92008-12-10 05:08:54 +00001097 private:
1098 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001099
1100 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001101};
1102
1103// Implements the polymorphic StartsWith(substring) matcher, which
1104// can be used as a Matcher<T> as long as T can be converted to a
1105// string.
1106template <typename StringType>
1107class StartsWithMatcher {
1108 public:
shiqiane35fdd92008-12-10 05:08:54 +00001109 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1110 }
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() >= prefix_.length() &&
1131 s2.substr(0, prefix_.length()) == prefix_;
shiqiane35fdd92008-12-10 05:08:54 +00001132 }
1133
1134 void DescribeTo(::std::ostream* os) const {
1135 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001136 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001137 }
1138
1139 void DescribeNegationTo(::std::ostream* os) const {
1140 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001141 UniversalPrint(prefix_, 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 prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001146
1147 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001148};
1149
1150// Implements the polymorphic EndsWith(substring) matcher, which
1151// can be used as a Matcher<T> as long as T can be converted to a
1152// string.
1153template <typename StringType>
1154class EndsWithMatcher {
1155 public:
shiqiane35fdd92008-12-10 05:08:54 +00001156 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
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(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001166 }
1167
jgm38513a82012-11-15 15:50:36 +00001168 // Matches anything that can convert to StringType.
1169 //
1170 // This is a template, not just a plain function with const StringType&,
1171 // because StringPiece has some interfering non-explicit constructors.
1172 template <typename 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 StringType& s2(s);
1176 return s2.length() >= suffix_.length() &&
1177 s2.substr(s2.length() - suffix_.length()) == suffix_;
shiqiane35fdd92008-12-10 05:08:54 +00001178 }
1179
1180 void DescribeTo(::std::ostream* os) const {
1181 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001182 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001183 }
1184
1185 void DescribeNegationTo(::std::ostream* os) const {
1186 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001187 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001188 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001189
shiqiane35fdd92008-12-10 05:08:54 +00001190 private:
1191 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001192
1193 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001194};
1195
shiqiane35fdd92008-12-10 05:08:54 +00001196// Implements polymorphic matchers MatchesRegex(regex) and
1197// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1198// T can be converted to a string.
1199class MatchesRegexMatcher {
1200 public:
1201 MatchesRegexMatcher(const RE* regex, bool full_match)
1202 : regex_(regex), full_match_(full_match) {}
1203
jgm38513a82012-11-15 15:50:36 +00001204 // Accepts pointer types, particularly:
1205 // const char*
1206 // char*
1207 // const wchar_t*
1208 // wchar_t*
1209 template <typename CharType>
1210 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001211 return s != NULL && MatchAndExplain(internal::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001212 }
1213
jgm38513a82012-11-15 15:50:36 +00001214 // Matches anything that can convert to internal::string.
1215 //
1216 // This is a template, not just a plain function with const internal::string&,
1217 // because StringPiece has some interfering non-explicit constructors.
1218 template <class MatcheeStringType>
1219 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001220 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001221 const internal::string& s2(s);
1222 return full_match_ ? RE::FullMatch(s2, *regex_) :
1223 RE::PartialMatch(s2, *regex_);
shiqiane35fdd92008-12-10 05:08:54 +00001224 }
1225
1226 void DescribeTo(::std::ostream* os) const {
1227 *os << (full_match_ ? "matches" : "contains")
1228 << " regular expression ";
1229 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1230 }
1231
1232 void DescribeNegationTo(::std::ostream* os) const {
1233 *os << "doesn't " << (full_match_ ? "match" : "contain")
1234 << " regular expression ";
1235 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1236 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001237
shiqiane35fdd92008-12-10 05:08:54 +00001238 private:
1239 const internal::linked_ptr<const RE> regex_;
1240 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001241
1242 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001243};
1244
shiqiane35fdd92008-12-10 05:08:54 +00001245// Implements a matcher that compares the two fields of a 2-tuple
1246// using one of the ==, <=, <, etc, operators. The two fields being
1247// compared don't have to have the same type.
1248//
1249// The matcher defined here is polymorphic (for example, Eq() can be
1250// used to match a tuple<int, short>, a tuple<const long&, double>,
1251// etc). Therefore we use a template type conversion operator in the
1252// implementation.
1253//
1254// We define this as a macro in order to eliminate duplicated source
1255// code.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001256#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +00001257 class name##2Matcher { \
1258 public: \
1259 template <typename T1, typename T2> \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001260 operator Matcher< ::std::tr1::tuple<T1, T2> >() const { \
1261 return MakeMatcher(new Impl< ::std::tr1::tuple<T1, T2> >); \
1262 } \
1263 template <typename T1, typename T2> \
shiqiane35fdd92008-12-10 05:08:54 +00001264 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001265 return MakeMatcher(new Impl<const ::std::tr1::tuple<T1, T2>&>); \
shiqiane35fdd92008-12-10 05:08:54 +00001266 } \
1267 private: \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001268 template <typename Tuple> \
1269 class Impl : public MatcherInterface<Tuple> { \
shiqiane35fdd92008-12-10 05:08:54 +00001270 public: \
zhanyong.wan82113312010-01-08 21:55:40 +00001271 virtual bool MatchAndExplain( \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001272 Tuple args, \
zhanyong.wan82113312010-01-08 21:55:40 +00001273 MatchResultListener* /* listener */) const { \
shiqiane35fdd92008-12-10 05:08:54 +00001274 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
1275 } \
1276 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001277 *os << "are " relation; \
shiqiane35fdd92008-12-10 05:08:54 +00001278 } \
1279 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001280 *os << "aren't " relation; \
shiqiane35fdd92008-12-10 05:08:54 +00001281 } \
1282 }; \
1283 }
1284
1285// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001286GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "an equal pair");
1287GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1288 Ge, >=, "a pair where the first >= the second");
1289GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1290 Gt, >, "a pair where the first > the second");
1291GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1292 Le, <=, "a pair where the first <= the second");
1293GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1294 Lt, <, "a pair where the first < the second");
1295GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=, "an unequal pair");
shiqiane35fdd92008-12-10 05:08:54 +00001296
zhanyong.wane0d051e2009-02-19 00:33:37 +00001297#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +00001298
zhanyong.wanc6a41232009-05-13 23:38:40 +00001299// Implements the Not(...) matcher for a particular argument type T.
1300// We do not nest it inside the NotMatcher class template, as that
1301// will prevent different instantiations of NotMatcher from sharing
1302// the same NotMatcherImpl<T> class.
1303template <typename T>
1304class NotMatcherImpl : public MatcherInterface<T> {
1305 public:
1306 explicit NotMatcherImpl(const Matcher<T>& matcher)
1307 : matcher_(matcher) {}
1308
zhanyong.wan82113312010-01-08 21:55:40 +00001309 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1310 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001311 }
1312
1313 virtual void DescribeTo(::std::ostream* os) const {
1314 matcher_.DescribeNegationTo(os);
1315 }
1316
1317 virtual void DescribeNegationTo(::std::ostream* os) const {
1318 matcher_.DescribeTo(os);
1319 }
1320
zhanyong.wanc6a41232009-05-13 23:38:40 +00001321 private:
1322 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001323
1324 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001325};
1326
shiqiane35fdd92008-12-10 05:08:54 +00001327// Implements the Not(m) matcher, which matches a value that doesn't
1328// match matcher m.
1329template <typename InnerMatcher>
1330class NotMatcher {
1331 public:
1332 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1333
1334 // This template type conversion operator allows Not(m) to be used
1335 // to match any type m can match.
1336 template <typename T>
1337 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001338 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001339 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001340
shiqiane35fdd92008-12-10 05:08:54 +00001341 private:
shiqiane35fdd92008-12-10 05:08:54 +00001342 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001343
1344 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001345};
1346
zhanyong.wanc6a41232009-05-13 23:38:40 +00001347// Implements the AllOf(m1, m2) matcher for a particular argument type
1348// T. We do not nest it inside the BothOfMatcher class template, as
1349// that will prevent different instantiations of BothOfMatcher from
1350// sharing the same BothOfMatcherImpl<T> class.
1351template <typename T>
1352class BothOfMatcherImpl : public MatcherInterface<T> {
1353 public:
1354 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1355 : matcher1_(matcher1), matcher2_(matcher2) {}
1356
zhanyong.wanc6a41232009-05-13 23:38:40 +00001357 virtual void DescribeTo(::std::ostream* os) const {
1358 *os << "(";
1359 matcher1_.DescribeTo(os);
1360 *os << ") and (";
1361 matcher2_.DescribeTo(os);
1362 *os << ")";
1363 }
1364
1365 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001366 *os << "(";
1367 matcher1_.DescribeNegationTo(os);
1368 *os << ") or (";
1369 matcher2_.DescribeNegationTo(os);
1370 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001371 }
1372
zhanyong.wan82113312010-01-08 21:55:40 +00001373 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1374 // If either matcher1_ or matcher2_ doesn't match x, we only need
1375 // to explain why one of them fails.
1376 StringMatchResultListener listener1;
1377 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1378 *listener << listener1.str();
1379 return false;
1380 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001381
zhanyong.wan82113312010-01-08 21:55:40 +00001382 StringMatchResultListener listener2;
1383 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1384 *listener << listener2.str();
1385 return false;
1386 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001387
zhanyong.wan82113312010-01-08 21:55:40 +00001388 // Otherwise we need to explain why *both* of them match.
1389 const internal::string s1 = listener1.str();
1390 const internal::string s2 = listener2.str();
1391
1392 if (s1 == "") {
1393 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001394 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001395 *listener << s1;
1396 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001397 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001398 }
1399 }
zhanyong.wan82113312010-01-08 21:55:40 +00001400 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001401 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001402
zhanyong.wanc6a41232009-05-13 23:38:40 +00001403 private:
1404 const Matcher<T> matcher1_;
1405 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001406
1407 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001408};
1409
zhanyong.wan616180e2013-06-18 18:49:51 +00001410#if GTEST_LANG_CXX11
1411// MatcherList provides mechanisms for storing a variable number of matchers in
1412// a list structure (ListType) and creating a combining matcher from such a
1413// list.
1414// The template is defined recursively using the following template paramters:
1415// * kSize is the length of the MatcherList.
1416// * Head is the type of the first matcher of the list.
1417// * Tail denotes the types of the remaining matchers of the list.
1418template <int kSize, typename Head, typename... Tail>
1419struct MatcherList {
1420 typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
1421 typedef pair<Head, typename MatcherListTail::ListType> ListType;
1422
1423 // BuildList stores variadic type values in a nested pair structure.
1424 // Example:
1425 // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
1426 // the corresponding result of type pair<int, pair<string, float>>.
1427 static ListType BuildList(const Head& matcher, const Tail&... tail) {
1428 return ListType(matcher, MatcherListTail::BuildList(tail...));
1429 }
1430
1431 // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
1432 // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
1433 // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
1434 // constructor taking two Matcher<T>s as input.
1435 template <typename T, template <typename /* T */> class CombiningMatcher>
1436 static Matcher<T> CreateMatcher(const ListType& matchers) {
1437 return Matcher<T>(new CombiningMatcher<T>(
1438 SafeMatcherCast<T>(matchers.first),
1439 MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
1440 matchers.second)));
1441 }
1442};
1443
1444// The following defines the base case for the recursive definition of
1445// MatcherList.
1446template <typename Matcher1, typename Matcher2>
1447struct MatcherList<2, Matcher1, Matcher2> {
1448 typedef pair<Matcher1, Matcher2> ListType;
1449
1450 static ListType BuildList(const Matcher1& matcher1,
1451 const Matcher2& matcher2) {
1452 return pair<Matcher1, Matcher2>(matcher1, matcher2);
1453 }
1454
1455 template <typename T, template <typename /* T */> class CombiningMatcher>
1456 static Matcher<T> CreateMatcher(const ListType& matchers) {
1457 return Matcher<T>(new CombiningMatcher<T>(
1458 SafeMatcherCast<T>(matchers.first),
1459 SafeMatcherCast<T>(matchers.second)));
1460 }
1461};
1462
1463// VariadicMatcher is used for the variadic implementation of
1464// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1465// CombiningMatcher<T> is used to recursively combine the provided matchers
1466// (of type Args...).
1467template <template <typename T> class CombiningMatcher, typename... Args>
1468class VariadicMatcher {
1469 public:
1470 VariadicMatcher(const Args&... matchers) // NOLINT
1471 : matchers_(MatcherListType::BuildList(matchers...)) {}
1472
1473 // This template type conversion operator allows an
1474 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1475 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1476 template <typename T>
1477 operator Matcher<T>() const {
1478 return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
1479 matchers_);
1480 }
1481
1482 private:
1483 typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
1484
1485 const typename MatcherListType::ListType matchers_;
1486
1487 GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1488};
1489
1490template <typename... Args>
1491using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
1492
1493#endif // GTEST_LANG_CXX11
1494
shiqiane35fdd92008-12-10 05:08:54 +00001495// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1496// matches a value that matches all of the matchers m_1, ..., and m_n.
1497template <typename Matcher1, typename Matcher2>
1498class BothOfMatcher {
1499 public:
1500 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1501 : matcher1_(matcher1), matcher2_(matcher2) {}
1502
1503 // This template type conversion operator allows a
1504 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1505 // both Matcher1 and Matcher2 can match.
1506 template <typename T>
1507 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001508 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1509 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001510 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001511
shiqiane35fdd92008-12-10 05:08:54 +00001512 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001513 Matcher1 matcher1_;
1514 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001515
1516 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001517};
shiqiane35fdd92008-12-10 05:08:54 +00001518
zhanyong.wanc6a41232009-05-13 23:38:40 +00001519// Implements the AnyOf(m1, m2) matcher for a particular argument type
1520// T. We do not nest it inside the AnyOfMatcher class template, as
1521// that will prevent different instantiations of AnyOfMatcher from
1522// sharing the same EitherOfMatcherImpl<T> class.
1523template <typename T>
1524class EitherOfMatcherImpl : public MatcherInterface<T> {
1525 public:
1526 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1527 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001528
zhanyong.wanc6a41232009-05-13 23:38:40 +00001529 virtual void DescribeTo(::std::ostream* os) const {
1530 *os << "(";
1531 matcher1_.DescribeTo(os);
1532 *os << ") or (";
1533 matcher2_.DescribeTo(os);
1534 *os << ")";
1535 }
shiqiane35fdd92008-12-10 05:08:54 +00001536
zhanyong.wanc6a41232009-05-13 23:38:40 +00001537 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001538 *os << "(";
1539 matcher1_.DescribeNegationTo(os);
1540 *os << ") and (";
1541 matcher2_.DescribeNegationTo(os);
1542 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001543 }
shiqiane35fdd92008-12-10 05:08:54 +00001544
zhanyong.wan82113312010-01-08 21:55:40 +00001545 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1546 // If either matcher1_ or matcher2_ matches x, we just need to
1547 // explain why *one* of them matches.
1548 StringMatchResultListener listener1;
1549 if (matcher1_.MatchAndExplain(x, &listener1)) {
1550 *listener << listener1.str();
1551 return true;
1552 }
1553
1554 StringMatchResultListener listener2;
1555 if (matcher2_.MatchAndExplain(x, &listener2)) {
1556 *listener << listener2.str();
1557 return true;
1558 }
1559
1560 // Otherwise we need to explain why *both* of them fail.
1561 const internal::string s1 = listener1.str();
1562 const internal::string s2 = listener2.str();
1563
1564 if (s1 == "") {
1565 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001566 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001567 *listener << s1;
1568 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001569 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001570 }
1571 }
zhanyong.wan82113312010-01-08 21:55:40 +00001572 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001573 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001574
zhanyong.wanc6a41232009-05-13 23:38:40 +00001575 private:
1576 const Matcher<T> matcher1_;
1577 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001578
1579 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001580};
1581
zhanyong.wan616180e2013-06-18 18:49:51 +00001582#if GTEST_LANG_CXX11
1583// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1584template <typename... Args>
1585using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
1586
1587#endif // GTEST_LANG_CXX11
1588
shiqiane35fdd92008-12-10 05:08:54 +00001589// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1590// matches a value that matches at least one of the matchers m_1, ...,
1591// and m_n.
1592template <typename Matcher1, typename Matcher2>
1593class EitherOfMatcher {
1594 public:
1595 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1596 : matcher1_(matcher1), matcher2_(matcher2) {}
1597
1598 // This template type conversion operator allows a
1599 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1600 // both Matcher1 and Matcher2 can match.
1601 template <typename T>
1602 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001603 return Matcher<T>(new EitherOfMatcherImpl<T>(
1604 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001605 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001606
shiqiane35fdd92008-12-10 05:08:54 +00001607 private:
shiqiane35fdd92008-12-10 05:08:54 +00001608 Matcher1 matcher1_;
1609 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001610
1611 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001612};
1613
1614// Used for implementing Truly(pred), which turns a predicate into a
1615// matcher.
1616template <typename Predicate>
1617class TrulyMatcher {
1618 public:
1619 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1620
1621 // This method template allows Truly(pred) to be used as a matcher
1622 // for type T where T is the argument type of predicate 'pred'. The
1623 // argument is passed by reference as the predicate may be
1624 // interested in the address of the argument.
1625 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001626 bool MatchAndExplain(T& x, // NOLINT
1627 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00001628 // Without the if-statement, MSVC sometimes warns about converting
1629 // a value to bool (warning 4800).
1630 //
1631 // We cannot write 'return !!predicate_(x);' as that doesn't work
1632 // when predicate_(x) returns a class convertible to bool but
1633 // having no operator!().
1634 if (predicate_(x))
1635 return true;
1636 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001637 }
1638
1639 void DescribeTo(::std::ostream* os) const {
1640 *os << "satisfies the given predicate";
1641 }
1642
1643 void DescribeNegationTo(::std::ostream* os) const {
1644 *os << "doesn't satisfy the given predicate";
1645 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001646
shiqiane35fdd92008-12-10 05:08:54 +00001647 private:
1648 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001649
1650 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001651};
1652
1653// Used for implementing Matches(matcher), which turns a matcher into
1654// a predicate.
1655template <typename M>
1656class MatcherAsPredicate {
1657 public:
1658 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1659
1660 // This template operator() allows Matches(m) to be used as a
1661 // predicate on type T where m is a matcher on type T.
1662 //
1663 // The argument x is passed by reference instead of by value, as
1664 // some matcher may be interested in its address (e.g. as in
1665 // Matches(Ref(n))(x)).
1666 template <typename T>
1667 bool operator()(const T& x) const {
1668 // We let matcher_ commit to a particular type here instead of
1669 // when the MatcherAsPredicate object was constructed. This
1670 // allows us to write Matches(m) where m is a polymorphic matcher
1671 // (e.g. Eq(5)).
1672 //
1673 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1674 // compile when matcher_ has type Matcher<const T&>; if we write
1675 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1676 // when matcher_ has type Matcher<T>; if we just write
1677 // matcher_.Matches(x), it won't compile when matcher_ is
1678 // polymorphic, e.g. Eq(5).
1679 //
1680 // MatcherCast<const T&>() is necessary for making the code work
1681 // in all of the above situations.
1682 return MatcherCast<const T&>(matcher_).Matches(x);
1683 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001684
shiqiane35fdd92008-12-10 05:08:54 +00001685 private:
1686 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001687
1688 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001689};
1690
1691// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1692// argument M must be a type that can be converted to a matcher.
1693template <typename M>
1694class PredicateFormatterFromMatcher {
1695 public:
1696 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1697
1698 // This template () operator allows a PredicateFormatterFromMatcher
1699 // object to act as a predicate-formatter suitable for using with
1700 // Google Test's EXPECT_PRED_FORMAT1() macro.
1701 template <typename T>
1702 AssertionResult operator()(const char* value_text, const T& x) const {
1703 // We convert matcher_ to a Matcher<const T&> *now* instead of
1704 // when the PredicateFormatterFromMatcher object was constructed,
1705 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1706 // know which type to instantiate it to until we actually see the
1707 // type of x here.
1708 //
zhanyong.wanf4274522013-04-24 02:49:43 +00001709 // We write SafeMatcherCast<const T&>(matcher_) instead of
shiqiane35fdd92008-12-10 05:08:54 +00001710 // Matcher<const T&>(matcher_), as the latter won't compile when
1711 // matcher_ has type Matcher<T> (e.g. An<int>()).
zhanyong.wanf4274522013-04-24 02:49:43 +00001712 // We don't write MatcherCast<const T&> either, as that allows
1713 // potentially unsafe downcasting of the matcher argument.
1714 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001715 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001716 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001717 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001718
1719 ::std::stringstream ss;
1720 ss << "Value of: " << value_text << "\n"
1721 << "Expected: ";
1722 matcher.DescribeTo(&ss);
1723 ss << "\n Actual: " << listener.str();
1724 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001725 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001726
shiqiane35fdd92008-12-10 05:08:54 +00001727 private:
1728 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001729
1730 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001731};
1732
1733// A helper function for converting a matcher to a predicate-formatter
1734// without the user needing to explicitly write the type. This is
1735// used for implementing ASSERT_THAT() and EXPECT_THAT().
1736template <typename M>
1737inline PredicateFormatterFromMatcher<M>
1738MakePredicateFormatterFromMatcher(const M& matcher) {
1739 return PredicateFormatterFromMatcher<M>(matcher);
1740}
1741
zhanyong.wan616180e2013-06-18 18:49:51 +00001742// Implements the polymorphic floating point equality matcher, which matches
1743// two float values using ULP-based approximation or, optionally, a
1744// user-specified epsilon. The template is meant to be instantiated with
1745// FloatType being either float or double.
shiqiane35fdd92008-12-10 05:08:54 +00001746template <typename FloatType>
1747class FloatingEqMatcher {
1748 public:
1749 // Constructor for FloatingEqMatcher.
1750 // The matcher's input will be compared with rhs. The matcher treats two
1751 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
zhanyong.wan616180e2013-06-18 18:49:51 +00001752 // equality comparisons between NANs will always return false. We specify a
1753 // negative max_abs_error_ term to indicate that ULP-based approximation will
1754 // be used for comparison.
shiqiane35fdd92008-12-10 05:08:54 +00001755 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
zhanyong.wan616180e2013-06-18 18:49:51 +00001756 rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
1757 }
1758
1759 // Constructor that supports a user-specified max_abs_error that will be used
1760 // for comparison instead of ULP-based approximation. The max absolute
1761 // should be non-negative.
1762 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan, FloatType max_abs_error) :
1763 rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) {
1764 GTEST_CHECK_(max_abs_error >= 0)
1765 << ", where max_abs_error is" << max_abs_error;
1766 }
shiqiane35fdd92008-12-10 05:08:54 +00001767
1768 // Implements floating point equality matcher as a Matcher<T>.
1769 template <typename T>
1770 class Impl : public MatcherInterface<T> {
1771 public:
zhanyong.wan616180e2013-06-18 18:49:51 +00001772 Impl(FloatType rhs, bool nan_eq_nan, FloatType max_abs_error) :
1773 rhs_(rhs), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) {}
shiqiane35fdd92008-12-10 05:08:54 +00001774
zhanyong.wan82113312010-01-08 21:55:40 +00001775 virtual bool MatchAndExplain(T value,
1776 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001777 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1778
1779 // Compares NaNs first, if nan_eq_nan_ is true.
zhanyong.wan616180e2013-06-18 18:49:51 +00001780 if (lhs.is_nan() || rhs.is_nan()) {
1781 if (lhs.is_nan() && rhs.is_nan()) {
1782 return nan_eq_nan_;
1783 }
1784 // One is nan; the other is not nan.
1785 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001786 }
zhanyong.wan616180e2013-06-18 18:49:51 +00001787 if (HasMaxAbsError()) {
1788 // We perform an equality check so that inf will match inf, regardless
1789 // of error bounds. If the result of value - rhs_ would result in
1790 // overflow or if either value is inf, the default result is infinity,
1791 // which should only match if max_abs_error_ is also infinity.
1792 return value == rhs_ || fabs(value - rhs_) <= max_abs_error_;
1793 } else {
1794 return lhs.AlmostEquals(rhs);
1795 }
shiqiane35fdd92008-12-10 05:08:54 +00001796 }
1797
1798 virtual void DescribeTo(::std::ostream* os) const {
1799 // os->precision() returns the previously set precision, which we
1800 // store to restore the ostream to its original configuration
1801 // after outputting.
1802 const ::std::streamsize old_precision = os->precision(
1803 ::std::numeric_limits<FloatType>::digits10 + 2);
1804 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1805 if (nan_eq_nan_) {
1806 *os << "is NaN";
1807 } else {
1808 *os << "never matches";
1809 }
1810 } else {
1811 *os << "is approximately " << rhs_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001812 if (HasMaxAbsError()) {
1813 *os << " (absolute error <= " << max_abs_error_ << ")";
1814 }
shiqiane35fdd92008-12-10 05:08:54 +00001815 }
1816 os->precision(old_precision);
1817 }
1818
1819 virtual void DescribeNegationTo(::std::ostream* os) const {
1820 // As before, get original precision.
1821 const ::std::streamsize old_precision = os->precision(
1822 ::std::numeric_limits<FloatType>::digits10 + 2);
1823 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1824 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001825 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00001826 } else {
1827 *os << "is anything";
1828 }
1829 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001830 *os << "isn't approximately " << rhs_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001831 if (HasMaxAbsError()) {
1832 *os << " (absolute error > " << max_abs_error_ << ")";
1833 }
shiqiane35fdd92008-12-10 05:08:54 +00001834 }
1835 // Restore original precision.
1836 os->precision(old_precision);
1837 }
1838
1839 private:
zhanyong.wan616180e2013-06-18 18:49:51 +00001840 bool HasMaxAbsError() const {
1841 return max_abs_error_ >= 0;
1842 }
1843
shiqiane35fdd92008-12-10 05:08:54 +00001844 const FloatType rhs_;
1845 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001846 // max_abs_error will be used for value comparison when >= 0.
1847 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001848
1849 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001850 };
1851
1852 // The following 3 type conversion operators allow FloatEq(rhs) and
1853 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1854 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1855 // (While Google's C++ coding style doesn't allow arguments passed
1856 // by non-const reference, we may see them in code not conforming to
1857 // the style. Therefore Google Mock needs to support them.)
1858 operator Matcher<FloatType>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00001859 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00001860 }
1861
1862 operator Matcher<const FloatType&>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00001863 return MakeMatcher(
1864 new Impl<const FloatType&>(rhs_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00001865 }
1866
1867 operator Matcher<FloatType&>() const {
zhanyong.wan616180e2013-06-18 18:49:51 +00001868 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_, max_abs_error_));
shiqiane35fdd92008-12-10 05:08:54 +00001869 }
jgm79a367e2012-04-10 16:02:11 +00001870
shiqiane35fdd92008-12-10 05:08:54 +00001871 private:
1872 const FloatType rhs_;
1873 const bool nan_eq_nan_;
zhanyong.wan616180e2013-06-18 18:49:51 +00001874 // max_abs_error will be used for value comparison when >= 0.
1875 const FloatType max_abs_error_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001876
1877 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001878};
1879
1880// Implements the Pointee(m) matcher for matching a pointer whose
1881// pointee matches matcher m. The pointer can be either raw or smart.
1882template <typename InnerMatcher>
1883class PointeeMatcher {
1884 public:
1885 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1886
1887 // This type conversion operator template allows Pointee(m) to be
1888 // used as a matcher for any pointer type whose pointee type is
1889 // compatible with the inner matcher, where type Pointer can be
1890 // either a raw pointer or a smart pointer.
1891 //
1892 // The reason we do this instead of relying on
1893 // MakePolymorphicMatcher() is that the latter is not flexible
1894 // enough for implementing the DescribeTo() method of Pointee().
1895 template <typename Pointer>
1896 operator Matcher<Pointer>() const {
1897 return MakeMatcher(new Impl<Pointer>(matcher_));
1898 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001899
shiqiane35fdd92008-12-10 05:08:54 +00001900 private:
1901 // The monomorphic implementation that works for a particular pointer type.
1902 template <typename Pointer>
1903 class Impl : public MatcherInterface<Pointer> {
1904 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00001905 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
1906 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001907
1908 explicit Impl(const InnerMatcher& matcher)
1909 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1910
shiqiane35fdd92008-12-10 05:08:54 +00001911 virtual void DescribeTo(::std::ostream* os) const {
1912 *os << "points to a value that ";
1913 matcher_.DescribeTo(os);
1914 }
1915
1916 virtual void DescribeNegationTo(::std::ostream* os) const {
1917 *os << "does not point to a value that ";
1918 matcher_.DescribeTo(os);
1919 }
1920
zhanyong.wan82113312010-01-08 21:55:40 +00001921 virtual bool MatchAndExplain(Pointer pointer,
1922 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001923 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00001924 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001925
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001926 *listener << "which points to ";
1927 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001928 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001929
shiqiane35fdd92008-12-10 05:08:54 +00001930 private:
1931 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001932
1933 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001934 };
1935
1936 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001937
1938 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001939};
1940
1941// Implements the Field() matcher for matching a field (i.e. member
1942// variable) of an object.
1943template <typename Class, typename FieldType>
1944class FieldMatcher {
1945 public:
1946 FieldMatcher(FieldType Class::*field,
1947 const Matcher<const FieldType&>& matcher)
1948 : field_(field), matcher_(matcher) {}
1949
shiqiane35fdd92008-12-10 05:08:54 +00001950 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001951 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001952 matcher_.DescribeTo(os);
1953 }
1954
1955 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001956 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001957 matcher_.DescribeNegationTo(os);
1958 }
1959
zhanyong.wandb22c222010-01-28 21:52:29 +00001960 template <typename T>
1961 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
1962 return MatchAndExplainImpl(
1963 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00001964 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00001965 value, listener);
1966 }
1967
1968 private:
1969 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001970 // Symbian's C++ compiler choose which overload to use. Its type is
1971 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001972 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1973 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001974 *listener << "whose given field is ";
1975 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001976 }
1977
zhanyong.wandb22c222010-01-28 21:52:29 +00001978 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1979 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001980 if (p == NULL)
1981 return false;
1982
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001983 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001984 // Since *p has a field, it must be a class/struct/union type and
1985 // thus cannot be a pointer. Therefore we pass false_type() as
1986 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001987 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001988 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001989
shiqiane35fdd92008-12-10 05:08:54 +00001990 const FieldType Class::*field_;
1991 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001992
1993 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001994};
1995
shiqiane35fdd92008-12-10 05:08:54 +00001996// Implements the Property() matcher for matching a property
1997// (i.e. return value of a getter method) of an object.
1998template <typename Class, typename PropertyType>
1999class PropertyMatcher {
2000 public:
2001 // The property may have a reference type, so 'const PropertyType&'
2002 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00002003 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00002004 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00002005 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00002006
2007 PropertyMatcher(PropertyType (Class::*property)() const,
2008 const Matcher<RefToConstProperty>& matcher)
2009 : property_(property), matcher_(matcher) {}
2010
shiqiane35fdd92008-12-10 05:08:54 +00002011 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002012 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002013 matcher_.DescribeTo(os);
2014 }
2015
2016 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002017 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00002018 matcher_.DescribeNegationTo(os);
2019 }
2020
zhanyong.wandb22c222010-01-28 21:52:29 +00002021 template <typename T>
2022 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2023 return MatchAndExplainImpl(
2024 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00002025 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00002026 value, listener);
2027 }
2028
2029 private:
2030 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00002031 // Symbian's C++ compiler choose which overload to use. Its type is
2032 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00002033 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2034 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002035 *listener << "whose given property is ";
2036 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2037 // which takes a non-const reference as argument.
2038 RefToConstProperty result = (obj.*property_)();
2039 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002040 }
2041
zhanyong.wandb22c222010-01-28 21:52:29 +00002042 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2043 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00002044 if (p == NULL)
2045 return false;
2046
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002047 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00002048 // Since *p has a property method, it must be a class/struct/union
2049 // type and thus cannot be a pointer. Therefore we pass
2050 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00002051 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002052 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002053
shiqiane35fdd92008-12-10 05:08:54 +00002054 PropertyType (Class::*property_)() const;
2055 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002056
2057 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002058};
2059
shiqiane35fdd92008-12-10 05:08:54 +00002060// Type traits specifying various features of different functors for ResultOf.
2061// The default template specifies features for functor objects.
2062// Functor classes have to typedef argument_type and result_type
2063// to be compatible with ResultOf.
2064template <typename Functor>
2065struct CallableTraits {
2066 typedef typename Functor::result_type ResultType;
2067 typedef Functor StorageType;
2068
zhanyong.wan32de5f52009-12-23 00:13:23 +00002069 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00002070 template <typename T>
2071 static ResultType Invoke(Functor f, T arg) { return f(arg); }
2072};
2073
2074// Specialization for function pointers.
2075template <typename ArgType, typename ResType>
2076struct CallableTraits<ResType(*)(ArgType)> {
2077 typedef ResType ResultType;
2078 typedef ResType(*StorageType)(ArgType);
2079
2080 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002081 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00002082 << "NULL function pointer is passed into ResultOf().";
2083 }
2084 template <typename T>
2085 static ResType Invoke(ResType(*f)(ArgType), T arg) {
2086 return (*f)(arg);
2087 }
2088};
2089
2090// Implements the ResultOf() matcher for matching a return value of a
2091// unary function of an object.
2092template <typename Callable>
2093class ResultOfMatcher {
2094 public:
2095 typedef typename CallableTraits<Callable>::ResultType ResultType;
2096
2097 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
2098 : callable_(callable), matcher_(matcher) {
2099 CallableTraits<Callable>::CheckIsValid(callable_);
2100 }
2101
2102 template <typename T>
2103 operator Matcher<T>() const {
2104 return Matcher<T>(new Impl<T>(callable_, matcher_));
2105 }
2106
2107 private:
2108 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2109
2110 template <typename T>
2111 class Impl : public MatcherInterface<T> {
2112 public:
2113 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
2114 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00002115
2116 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002117 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002118 matcher_.DescribeTo(os);
2119 }
2120
2121 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002122 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00002123 matcher_.DescribeNegationTo(os);
2124 }
2125
zhanyong.wan82113312010-01-08 21:55:40 +00002126 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002127 *listener << "which is mapped by the given callable to ";
2128 // Cannot pass the return value (for example, int) to
2129 // MatchPrintAndExplain, which takes a non-const reference as argument.
2130 ResultType result =
2131 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2132 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002133 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002134
shiqiane35fdd92008-12-10 05:08:54 +00002135 private:
2136 // Functors often define operator() as non-const method even though
2137 // they are actualy stateless. But we need to use them even when
2138 // 'this' is a const pointer. It's the user's responsibility not to
2139 // use stateful callables with ResultOf(), which does't guarantee
2140 // how many times the callable will be invoked.
2141 mutable CallableStorageType callable_;
2142 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002143
2144 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002145 }; // class Impl
2146
2147 const CallableStorageType callable_;
2148 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002149
2150 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002151};
2152
zhanyong.wana31d9ce2013-03-01 01:50:17 +00002153// Implements a matcher that checks the size of an STL-style container.
2154template <typename SizeMatcher>
2155class SizeIsMatcher {
2156 public:
2157 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2158 : size_matcher_(size_matcher) {
2159 }
2160
2161 template <typename Container>
2162 operator Matcher<Container>() const {
2163 return MakeMatcher(new Impl<Container>(size_matcher_));
2164 }
2165
2166 template <typename Container>
2167 class Impl : public MatcherInterface<Container> {
2168 public:
2169 typedef internal::StlContainerView<
2170 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2171 typedef typename ContainerView::type::size_type SizeType;
2172 explicit Impl(const SizeMatcher& size_matcher)
2173 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2174
2175 virtual void DescribeTo(::std::ostream* os) const {
2176 *os << "size ";
2177 size_matcher_.DescribeTo(os);
2178 }
2179 virtual void DescribeNegationTo(::std::ostream* os) const {
2180 *os << "size ";
2181 size_matcher_.DescribeNegationTo(os);
2182 }
2183
2184 virtual bool MatchAndExplain(Container container,
2185 MatchResultListener* listener) const {
2186 SizeType size = container.size();
2187 StringMatchResultListener size_listener;
2188 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2189 *listener
2190 << "whose size " << size << (result ? " matches" : " doesn't match");
2191 PrintIfNotEmpty(size_listener.str(), listener->stream());
2192 return result;
2193 }
2194
2195 private:
2196 const Matcher<SizeType> size_matcher_;
2197 GTEST_DISALLOW_ASSIGN_(Impl);
2198 };
2199
2200 private:
2201 const SizeMatcher size_matcher_;
2202 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2203};
2204
zhanyong.wan6a896b52009-01-16 01:13:50 +00002205// Implements an equality matcher for any STL-style container whose elements
2206// support ==. This matcher is like Eq(), but its failure explanations provide
2207// more detailed information that is useful when the container is used as a set.
2208// The failure message reports elements that are in one of the operands but not
2209// the other. The failure messages do not report duplicate or out-of-order
2210// elements in the containers (which don't properly matter to sets, but can
2211// occur if the containers are vectors or lists, for example).
2212//
2213// Uses the container's const_iterator, value_type, operator ==,
2214// begin(), and end().
2215template <typename Container>
2216class ContainerEqMatcher {
2217 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00002218 typedef internal::StlContainerView<Container> View;
2219 typedef typename View::type StlContainer;
2220 typedef typename View::const_reference StlContainerReference;
2221
2222 // We make a copy of rhs in case the elements in it are modified
2223 // after this matcher is created.
2224 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
2225 // Makes sure the user doesn't instantiate this class template
2226 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002227 (void)testing::StaticAssertTypeEq<Container,
2228 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00002229 }
2230
zhanyong.wan6a896b52009-01-16 01:13:50 +00002231 void DescribeTo(::std::ostream* os) const {
2232 *os << "equals ";
vladloseve2e8ba42010-05-13 18:16:03 +00002233 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002234 }
2235 void DescribeNegationTo(::std::ostream* os) const {
2236 *os << "does not equal ";
vladloseve2e8ba42010-05-13 18:16:03 +00002237 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002238 }
2239
zhanyong.wanb8243162009-06-04 05:48:20 +00002240 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00002241 bool MatchAndExplain(const LhsContainer& lhs,
2242 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002243 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00002244 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002245 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00002246 LhsView;
2247 typedef typename LhsView::type LhsStlContainer;
2248 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00002249 if (lhs_stl_container == rhs_)
2250 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002251
zhanyong.wane122e452010-01-12 09:03:52 +00002252 ::std::ostream* const os = listener->stream();
2253 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002254 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002255 bool printed_header = false;
2256 for (typename LhsStlContainer::const_iterator it =
2257 lhs_stl_container.begin();
2258 it != lhs_stl_container.end(); ++it) {
2259 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
2260 rhs_.end()) {
2261 if (printed_header) {
2262 *os << ", ";
2263 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002264 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002265 printed_header = true;
2266 }
vladloseve2e8ba42010-05-13 18:16:03 +00002267 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002268 }
zhanyong.wane122e452010-01-12 09:03:52 +00002269 }
2270
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002271 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002272 bool printed_header2 = false;
2273 for (typename StlContainer::const_iterator it = rhs_.begin();
2274 it != rhs_.end(); ++it) {
2275 if (internal::ArrayAwareFind(
2276 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2277 lhs_stl_container.end()) {
2278 if (printed_header2) {
2279 *os << ", ";
2280 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002281 *os << (printed_header ? ",\nand" : "which")
2282 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002283 printed_header2 = true;
2284 }
vladloseve2e8ba42010-05-13 18:16:03 +00002285 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002286 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002287 }
2288 }
2289
zhanyong.wane122e452010-01-12 09:03:52 +00002290 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002291 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002292
zhanyong.wan6a896b52009-01-16 01:13:50 +00002293 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00002294 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002295
2296 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002297};
2298
zhanyong.wan898725c2011-09-16 16:45:39 +00002299// A comparator functor that uses the < operator to compare two values.
2300struct LessComparator {
2301 template <typename T, typename U>
2302 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2303};
2304
2305// Implements WhenSortedBy(comparator, container_matcher).
2306template <typename Comparator, typename ContainerMatcher>
2307class WhenSortedByMatcher {
2308 public:
2309 WhenSortedByMatcher(const Comparator& comparator,
2310 const ContainerMatcher& matcher)
2311 : comparator_(comparator), matcher_(matcher) {}
2312
2313 template <typename LhsContainer>
2314 operator Matcher<LhsContainer>() const {
2315 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2316 }
2317
2318 template <typename LhsContainer>
2319 class Impl : public MatcherInterface<LhsContainer> {
2320 public:
2321 typedef internal::StlContainerView<
2322 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2323 typedef typename LhsView::type LhsStlContainer;
2324 typedef typename LhsView::const_reference LhsStlContainerReference;
zhanyong.wana9a59e02013-03-27 16:14:55 +00002325 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2326 // so that we can match associative containers.
2327 typedef typename RemoveConstFromKey<
2328 typename LhsStlContainer::value_type>::type LhsValue;
zhanyong.wan898725c2011-09-16 16:45:39 +00002329
2330 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2331 : comparator_(comparator), matcher_(matcher) {}
2332
2333 virtual void DescribeTo(::std::ostream* os) const {
2334 *os << "(when sorted) ";
2335 matcher_.DescribeTo(os);
2336 }
2337
2338 virtual void DescribeNegationTo(::std::ostream* os) const {
2339 *os << "(when sorted) ";
2340 matcher_.DescribeNegationTo(os);
2341 }
2342
2343 virtual bool MatchAndExplain(LhsContainer lhs,
2344 MatchResultListener* listener) const {
2345 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2346 std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2347 lhs_stl_container.end());
2348 std::sort(sorted_container.begin(), sorted_container.end(), comparator_);
2349
2350 if (!listener->IsInterested()) {
2351 // If the listener is not interested, we do not need to
2352 // construct the inner explanation.
2353 return matcher_.Matches(sorted_container);
2354 }
2355
2356 *listener << "which is ";
2357 UniversalPrint(sorted_container, listener->stream());
2358 *listener << " when sorted";
2359
2360 StringMatchResultListener inner_listener;
2361 const bool match = matcher_.MatchAndExplain(sorted_container,
2362 &inner_listener);
2363 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2364 return match;
2365 }
2366
2367 private:
2368 const Comparator comparator_;
2369 const Matcher<const std::vector<LhsValue>&> matcher_;
2370
2371 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2372 };
2373
2374 private:
2375 const Comparator comparator_;
2376 const ContainerMatcher matcher_;
2377
2378 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2379};
2380
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002381// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2382// must be able to be safely cast to Matcher<tuple<const T1&, const
2383// T2&> >, where T1 and T2 are the types of elements in the LHS
2384// container and the RHS container respectively.
2385template <typename TupleMatcher, typename RhsContainer>
2386class PointwiseMatcher {
2387 public:
2388 typedef internal::StlContainerView<RhsContainer> RhsView;
2389 typedef typename RhsView::type RhsStlContainer;
2390 typedef typename RhsStlContainer::value_type RhsValue;
2391
2392 // Like ContainerEq, we make a copy of rhs in case the elements in
2393 // it are modified after this matcher is created.
2394 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2395 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2396 // Makes sure the user doesn't instantiate this class template
2397 // with a const or reference type.
2398 (void)testing::StaticAssertTypeEq<RhsContainer,
2399 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2400 }
2401
2402 template <typename LhsContainer>
2403 operator Matcher<LhsContainer>() const {
2404 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2405 }
2406
2407 template <typename LhsContainer>
2408 class Impl : public MatcherInterface<LhsContainer> {
2409 public:
2410 typedef internal::StlContainerView<
2411 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2412 typedef typename LhsView::type LhsStlContainer;
2413 typedef typename LhsView::const_reference LhsStlContainerReference;
2414 typedef typename LhsStlContainer::value_type LhsValue;
2415 // We pass the LHS value and the RHS value to the inner matcher by
2416 // reference, as they may be expensive to copy. We must use tuple
2417 // instead of pair here, as a pair cannot hold references (C++ 98,
2418 // 20.2.2 [lib.pairs]).
2419 typedef std::tr1::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
2420
2421 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2422 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2423 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2424 rhs_(rhs) {}
2425
2426 virtual void DescribeTo(::std::ostream* os) const {
2427 *os << "contains " << rhs_.size()
2428 << " values, where each value and its corresponding value in ";
2429 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2430 *os << " ";
2431 mono_tuple_matcher_.DescribeTo(os);
2432 }
2433 virtual void DescribeNegationTo(::std::ostream* os) const {
2434 *os << "doesn't contain exactly " << rhs_.size()
2435 << " values, or contains a value x at some index i"
2436 << " where x and the i-th value of ";
2437 UniversalPrint(rhs_, os);
2438 *os << " ";
2439 mono_tuple_matcher_.DescribeNegationTo(os);
2440 }
2441
2442 virtual bool MatchAndExplain(LhsContainer lhs,
2443 MatchResultListener* listener) const {
2444 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2445 const size_t actual_size = lhs_stl_container.size();
2446 if (actual_size != rhs_.size()) {
2447 *listener << "which contains " << actual_size << " values";
2448 return false;
2449 }
2450
2451 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2452 typename RhsStlContainer::const_iterator right = rhs_.begin();
2453 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2454 const InnerMatcherArg value_pair(*left, *right);
2455
2456 if (listener->IsInterested()) {
2457 StringMatchResultListener inner_listener;
2458 if (!mono_tuple_matcher_.MatchAndExplain(
2459 value_pair, &inner_listener)) {
2460 *listener << "where the value pair (";
2461 UniversalPrint(*left, listener->stream());
2462 *listener << ", ";
2463 UniversalPrint(*right, listener->stream());
2464 *listener << ") at index #" << i << " don't match";
2465 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2466 return false;
2467 }
2468 } else {
2469 if (!mono_tuple_matcher_.Matches(value_pair))
2470 return false;
2471 }
2472 }
2473
2474 return true;
2475 }
2476
2477 private:
2478 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2479 const RhsStlContainer rhs_;
2480
2481 GTEST_DISALLOW_ASSIGN_(Impl);
2482 };
2483
2484 private:
2485 const TupleMatcher tuple_matcher_;
2486 const RhsStlContainer rhs_;
2487
2488 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2489};
2490
zhanyong.wan33605ba2010-04-22 23:37:47 +00002491// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002492template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002493class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002494 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002495 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002496 typedef StlContainerView<RawContainer> View;
2497 typedef typename View::type StlContainer;
2498 typedef typename View::const_reference StlContainerReference;
2499 typedef typename StlContainer::value_type Element;
2500
2501 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002502 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002503 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002504 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002505
zhanyong.wan33605ba2010-04-22 23:37:47 +00002506 // Checks whether:
2507 // * All elements in the container match, if all_elements_should_match.
2508 // * Any element in the container matches, if !all_elements_should_match.
2509 bool MatchAndExplainImpl(bool all_elements_should_match,
2510 Container container,
2511 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002512 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002513 size_t i = 0;
2514 for (typename StlContainer::const_iterator it = stl_container.begin();
2515 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002516 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00002517 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2518
2519 if (matches != all_elements_should_match) {
2520 *listener << "whose element #" << i
2521 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002522 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00002523 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00002524 }
2525 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00002526 return all_elements_should_match;
2527 }
2528
2529 protected:
2530 const Matcher<const Element&> inner_matcher_;
2531
2532 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2533};
2534
2535// Implements Contains(element_matcher) for the given argument type Container.
2536// Symmetric to EachMatcherImpl.
2537template <typename Container>
2538class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2539 public:
2540 template <typename InnerMatcher>
2541 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2542 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2543
2544 // Describes what this matcher does.
2545 virtual void DescribeTo(::std::ostream* os) const {
2546 *os << "contains at least one element that ";
2547 this->inner_matcher_.DescribeTo(os);
2548 }
2549
2550 virtual void DescribeNegationTo(::std::ostream* os) const {
2551 *os << "doesn't contain any element that ";
2552 this->inner_matcher_.DescribeTo(os);
2553 }
2554
2555 virtual bool MatchAndExplain(Container container,
2556 MatchResultListener* listener) const {
2557 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002558 }
2559
2560 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002561 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002562};
2563
zhanyong.wan33605ba2010-04-22 23:37:47 +00002564// Implements Each(element_matcher) for the given argument type Container.
2565// Symmetric to ContainsMatcherImpl.
2566template <typename Container>
2567class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2568 public:
2569 template <typename InnerMatcher>
2570 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2571 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2572
2573 // Describes what this matcher does.
2574 virtual void DescribeTo(::std::ostream* os) const {
2575 *os << "only contains elements that ";
2576 this->inner_matcher_.DescribeTo(os);
2577 }
2578
2579 virtual void DescribeNegationTo(::std::ostream* os) const {
2580 *os << "contains some element that ";
2581 this->inner_matcher_.DescribeNegationTo(os);
2582 }
2583
2584 virtual bool MatchAndExplain(Container container,
2585 MatchResultListener* listener) const {
2586 return this->MatchAndExplainImpl(true, container, listener);
2587 }
2588
2589 private:
2590 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2591};
2592
zhanyong.wanb8243162009-06-04 05:48:20 +00002593// Implements polymorphic Contains(element_matcher).
2594template <typename M>
2595class ContainsMatcher {
2596 public:
2597 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2598
2599 template <typename Container>
2600 operator Matcher<Container>() const {
2601 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2602 }
2603
2604 private:
2605 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002606
2607 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002608};
2609
zhanyong.wan33605ba2010-04-22 23:37:47 +00002610// Implements polymorphic Each(element_matcher).
2611template <typename M>
2612class EachMatcher {
2613 public:
2614 explicit EachMatcher(M m) : inner_matcher_(m) {}
2615
2616 template <typename Container>
2617 operator Matcher<Container>() const {
2618 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2619 }
2620
2621 private:
2622 const M inner_matcher_;
2623
2624 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2625};
2626
zhanyong.wanb5937da2009-07-16 20:26:41 +00002627// Implements Key(inner_matcher) for the given argument pair type.
2628// Key(inner_matcher) matches an std::pair whose 'first' field matches
2629// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2630// std::map that contains at least one element whose key is >= 5.
2631template <typename PairType>
2632class KeyMatcherImpl : public MatcherInterface<PairType> {
2633 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002634 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002635 typedef typename RawPairType::first_type KeyType;
2636
2637 template <typename InnerMatcher>
2638 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2639 : inner_matcher_(
2640 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2641 }
2642
2643 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002644 virtual bool MatchAndExplain(PairType key_value,
2645 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002646 StringMatchResultListener inner_listener;
2647 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2648 &inner_listener);
2649 const internal::string explanation = inner_listener.str();
2650 if (explanation != "") {
2651 *listener << "whose first field is a value " << explanation;
2652 }
2653 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002654 }
2655
2656 // Describes what this matcher does.
2657 virtual void DescribeTo(::std::ostream* os) const {
2658 *os << "has a key that ";
2659 inner_matcher_.DescribeTo(os);
2660 }
2661
2662 // Describes what the negation of this matcher does.
2663 virtual void DescribeNegationTo(::std::ostream* os) const {
2664 *os << "doesn't have a key that ";
2665 inner_matcher_.DescribeTo(os);
2666 }
2667
zhanyong.wanb5937da2009-07-16 20:26:41 +00002668 private:
2669 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002670
2671 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002672};
2673
2674// Implements polymorphic Key(matcher_for_key).
2675template <typename M>
2676class KeyMatcher {
2677 public:
2678 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2679
2680 template <typename PairType>
2681 operator Matcher<PairType>() const {
2682 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2683 }
2684
2685 private:
2686 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002687
2688 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002689};
2690
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002691// Implements Pair(first_matcher, second_matcher) for the given argument pair
2692// type with its two matchers. See Pair() function below.
2693template <typename PairType>
2694class PairMatcherImpl : public MatcherInterface<PairType> {
2695 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002696 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002697 typedef typename RawPairType::first_type FirstType;
2698 typedef typename RawPairType::second_type SecondType;
2699
2700 template <typename FirstMatcher, typename SecondMatcher>
2701 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2702 : first_matcher_(
2703 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2704 second_matcher_(
2705 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2706 }
2707
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002708 // Describes what this matcher does.
2709 virtual void DescribeTo(::std::ostream* os) const {
2710 *os << "has a first field that ";
2711 first_matcher_.DescribeTo(os);
2712 *os << ", and has a second field that ";
2713 second_matcher_.DescribeTo(os);
2714 }
2715
2716 // Describes what the negation of this matcher does.
2717 virtual void DescribeNegationTo(::std::ostream* os) const {
2718 *os << "has a first field that ";
2719 first_matcher_.DescribeNegationTo(os);
2720 *os << ", or has a second field that ";
2721 second_matcher_.DescribeNegationTo(os);
2722 }
2723
zhanyong.wan82113312010-01-08 21:55:40 +00002724 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2725 // matches second_matcher.
2726 virtual bool MatchAndExplain(PairType a_pair,
2727 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002728 if (!listener->IsInterested()) {
2729 // If the listener is not interested, we don't need to construct the
2730 // explanation.
2731 return first_matcher_.Matches(a_pair.first) &&
2732 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00002733 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002734 StringMatchResultListener first_inner_listener;
2735 if (!first_matcher_.MatchAndExplain(a_pair.first,
2736 &first_inner_listener)) {
2737 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002738 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002739 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002740 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002741 StringMatchResultListener second_inner_listener;
2742 if (!second_matcher_.MatchAndExplain(a_pair.second,
2743 &second_inner_listener)) {
2744 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002745 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002746 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002747 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002748 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
2749 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00002750 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002751 }
2752
2753 private:
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002754 void ExplainSuccess(const internal::string& first_explanation,
2755 const internal::string& second_explanation,
2756 MatchResultListener* listener) const {
2757 *listener << "whose both fields match";
2758 if (first_explanation != "") {
2759 *listener << ", where the first field is a value " << first_explanation;
2760 }
2761 if (second_explanation != "") {
2762 *listener << ", ";
2763 if (first_explanation != "") {
2764 *listener << "and ";
2765 } else {
2766 *listener << "where ";
2767 }
2768 *listener << "the second field is a value " << second_explanation;
2769 }
2770 }
2771
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002772 const Matcher<const FirstType&> first_matcher_;
2773 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002774
2775 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002776};
2777
2778// Implements polymorphic Pair(first_matcher, second_matcher).
2779template <typename FirstMatcher, typename SecondMatcher>
2780class PairMatcher {
2781 public:
2782 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2783 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2784
2785 template <typename PairType>
2786 operator Matcher<PairType> () const {
2787 return MakeMatcher(
2788 new PairMatcherImpl<PairType>(
2789 first_matcher_, second_matcher_));
2790 }
2791
2792 private:
2793 const FirstMatcher first_matcher_;
2794 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002795
2796 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002797};
2798
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002799// Implements ElementsAre() and ElementsAreArray().
2800template <typename Container>
2801class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2802 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002803 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002804 typedef internal::StlContainerView<RawContainer> View;
2805 typedef typename View::type StlContainer;
2806 typedef typename View::const_reference StlContainerReference;
2807 typedef typename StlContainer::value_type Element;
2808
2809 // Constructs the matcher from a sequence of element values or
2810 // element matchers.
2811 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00002812 ElementsAreMatcherImpl(InputIter first, InputIter last) {
2813 while (first != last) {
2814 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002815 }
2816 }
2817
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002818 // Describes what this matcher does.
2819 virtual void DescribeTo(::std::ostream* os) const {
2820 if (count() == 0) {
2821 *os << "is empty";
2822 } else if (count() == 1) {
2823 *os << "has 1 element that ";
2824 matchers_[0].DescribeTo(os);
2825 } else {
2826 *os << "has " << Elements(count()) << " where\n";
2827 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002828 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002829 matchers_[i].DescribeTo(os);
2830 if (i + 1 < count()) {
2831 *os << ",\n";
2832 }
2833 }
2834 }
2835 }
2836
2837 // Describes what the negation of this matcher does.
2838 virtual void DescribeNegationTo(::std::ostream* os) const {
2839 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002840 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002841 return;
2842 }
2843
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002844 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002845 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002846 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002847 matchers_[i].DescribeNegationTo(os);
2848 if (i + 1 < count()) {
2849 *os << ", or\n";
2850 }
2851 }
2852 }
2853
zhanyong.wan82113312010-01-08 21:55:40 +00002854 virtual bool MatchAndExplain(Container container,
2855 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002856 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002857 const size_t actual_count = stl_container.size();
2858 if (actual_count != count()) {
2859 // The element count doesn't match. If the container is empty,
2860 // there's no need to explain anything as Google Mock already
2861 // prints the empty container. Otherwise we just need to show
2862 // how many elements there actually are.
2863 if (actual_count != 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002864 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002865 }
zhanyong.wan82113312010-01-08 21:55:40 +00002866 return false;
2867 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002868
zhanyong.wan82113312010-01-08 21:55:40 +00002869 typename StlContainer::const_iterator it = stl_container.begin();
2870 // explanations[i] is the explanation of the element at index i.
2871 std::vector<internal::string> explanations(count());
2872 for (size_t i = 0; i != count(); ++it, ++i) {
2873 StringMatchResultListener s;
2874 if (matchers_[i].MatchAndExplain(*it, &s)) {
2875 explanations[i] = s.str();
2876 } else {
2877 // The container has the right size but the i-th element
2878 // doesn't match its expectation.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002879 *listener << "whose element #" << i << " doesn't match";
2880 PrintIfNotEmpty(s.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002881 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002882 }
2883 }
zhanyong.wan82113312010-01-08 21:55:40 +00002884
2885 // Every element matches its expectation. We need to explain why
2886 // (the obvious ones can be skipped).
zhanyong.wan82113312010-01-08 21:55:40 +00002887 bool reason_printed = false;
2888 for (size_t i = 0; i != count(); ++i) {
2889 const internal::string& s = explanations[i];
2890 if (!s.empty()) {
2891 if (reason_printed) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002892 *listener << ",\nand ";
zhanyong.wan82113312010-01-08 21:55:40 +00002893 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002894 *listener << "whose element #" << i << " matches, " << s;
zhanyong.wan82113312010-01-08 21:55:40 +00002895 reason_printed = true;
2896 }
2897 }
2898
2899 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002900 }
2901
2902 private:
2903 static Message Elements(size_t count) {
2904 return Message() << count << (count == 1 ? " element" : " elements");
2905 }
2906
2907 size_t count() const { return matchers_.size(); }
2908 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002909
2910 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002911};
2912
2913// Implements ElementsAre() of 0 arguments.
2914class ElementsAreMatcher0 {
2915 public:
2916 ElementsAreMatcher0() {}
2917
2918 template <typename Container>
2919 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002920 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002921 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2922 Element;
2923
2924 const Matcher<const Element&>* const matchers = NULL;
jgm38513a82012-11-15 15:50:36 +00002925 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers,
2926 matchers));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002927 }
2928};
2929
2930// Implements ElementsAreArray().
2931template <typename T>
2932class ElementsAreArrayMatcher {
2933 public:
jgm38513a82012-11-15 15:50:36 +00002934 template <typename Iter>
2935 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002936
2937 template <typename Container>
2938 operator Matcher<Container>() const {
jgm38513a82012-11-15 15:50:36 +00002939 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
2940 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002941 }
2942
2943 private:
jgm38513a82012-11-15 15:50:36 +00002944 const std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002945
2946 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002947};
2948
zhanyong.wanb4140802010-06-08 22:53:57 +00002949// Returns the description for a matcher defined using the MATCHER*()
2950// macro where the user-supplied description string is "", if
2951// 'negation' is false; otherwise returns the description of the
2952// negation of the matcher. 'param_values' contains a list of strings
2953// that are the print-out of the matcher's parameters.
vladlosev587c1b32011-05-20 00:42:22 +00002954GTEST_API_ string FormatMatcherDescription(bool negation,
2955 const char* matcher_name,
2956 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002957
shiqiane35fdd92008-12-10 05:08:54 +00002958} // namespace internal
2959
shiqiane35fdd92008-12-10 05:08:54 +00002960// _ is a matcher that matches anything of any type.
2961//
2962// This definition is fine as:
2963//
2964// 1. The C++ standard permits using the name _ in a namespace that
2965// is not the global namespace or ::std.
2966// 2. The AnythingMatcher class has no data member or constructor,
2967// so it's OK to create global variables of this type.
2968// 3. c-style has approved of using _ in this case.
2969const internal::AnythingMatcher _ = {};
2970// Creates a matcher that matches any value of the given type T.
2971template <typename T>
2972inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2973
2974// Creates a matcher that matches any value of the given type T.
2975template <typename T>
2976inline Matcher<T> An() { return A<T>(); }
2977
2978// Creates a polymorphic matcher that matches anything equal to x.
2979// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2980// wouldn't compile.
2981template <typename T>
2982inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2983
2984// Constructs a Matcher<T> from a 'value' of type T. The constructed
2985// matcher matches any value that's equal to 'value'.
2986template <typename T>
2987Matcher<T>::Matcher(T value) { *this = Eq(value); }
2988
2989// Creates a monomorphic matcher that matches anything with type Lhs
2990// and equal to rhs. A user may need to use this instead of Eq(...)
2991// in order to resolve an overloading ambiguity.
2992//
2993// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2994// or Matcher<T>(x), but more readable than the latter.
2995//
2996// We could define similar monomorphic matchers for other comparison
2997// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2998// it yet as those are used much less than Eq() in practice. A user
2999// can always write Matcher<T>(Lt(5)) to be explicit about the type,
3000// for example.
3001template <typename Lhs, typename Rhs>
3002inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
3003
3004// Creates a polymorphic matcher that matches anything >= x.
3005template <typename Rhs>
3006inline internal::GeMatcher<Rhs> Ge(Rhs x) {
3007 return internal::GeMatcher<Rhs>(x);
3008}
3009
3010// Creates a polymorphic matcher that matches anything > x.
3011template <typename Rhs>
3012inline internal::GtMatcher<Rhs> Gt(Rhs x) {
3013 return internal::GtMatcher<Rhs>(x);
3014}
3015
3016// Creates a polymorphic matcher that matches anything <= x.
3017template <typename Rhs>
3018inline internal::LeMatcher<Rhs> Le(Rhs x) {
3019 return internal::LeMatcher<Rhs>(x);
3020}
3021
3022// Creates a polymorphic matcher that matches anything < x.
3023template <typename Rhs>
3024inline internal::LtMatcher<Rhs> Lt(Rhs x) {
3025 return internal::LtMatcher<Rhs>(x);
3026}
3027
3028// Creates a polymorphic matcher that matches anything != x.
3029template <typename Rhs>
3030inline internal::NeMatcher<Rhs> Ne(Rhs x) {
3031 return internal::NeMatcher<Rhs>(x);
3032}
3033
zhanyong.wan2d970ee2009-09-24 21:41:36 +00003034// Creates a polymorphic matcher that matches any NULL pointer.
3035inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
3036 return MakePolymorphicMatcher(internal::IsNullMatcher());
3037}
3038
shiqiane35fdd92008-12-10 05:08:54 +00003039// Creates a polymorphic matcher that matches any non-NULL pointer.
3040// This is convenient as Not(NULL) doesn't compile (the compiler
3041// thinks that that expression is comparing a pointer with an integer).
3042inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
3043 return MakePolymorphicMatcher(internal::NotNullMatcher());
3044}
3045
3046// Creates a polymorphic matcher that matches any argument that
3047// references variable x.
3048template <typename T>
3049inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
3050 return internal::RefMatcher<T&>(x);
3051}
3052
3053// Creates a matcher that matches any double argument approximately
3054// equal to rhs, where two NANs are considered unequal.
3055inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
3056 return internal::FloatingEqMatcher<double>(rhs, false);
3057}
3058
3059// Creates a matcher that matches any double argument approximately
3060// equal to rhs, including NaN values when rhs is NaN.
3061inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
3062 return internal::FloatingEqMatcher<double>(rhs, true);
3063}
3064
zhanyong.wan616180e2013-06-18 18:49:51 +00003065// Creates a matcher that matches any double argument approximately equal to
3066// rhs, up to the specified max absolute error bound, where two NANs are
3067// considered unequal. The max absolute error bound must be non-negative.
3068inline internal::FloatingEqMatcher<double> DoubleNear(
3069 double rhs, double max_abs_error) {
3070 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
3071}
3072
3073// Creates a matcher that matches any double argument approximately equal to
3074// rhs, up to the specified max absolute error bound, including NaN values when
3075// rhs is NaN. The max absolute error bound must be non-negative.
3076inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
3077 double rhs, double max_abs_error) {
3078 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
3079}
3080
shiqiane35fdd92008-12-10 05:08:54 +00003081// Creates a matcher that matches any float argument approximately
3082// equal to rhs, where two NANs are considered unequal.
3083inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
3084 return internal::FloatingEqMatcher<float>(rhs, false);
3085}
3086
zhanyong.wan616180e2013-06-18 18:49:51 +00003087// Creates a matcher that matches any float argument approximately
shiqiane35fdd92008-12-10 05:08:54 +00003088// equal to rhs, including NaN values when rhs is NaN.
3089inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
3090 return internal::FloatingEqMatcher<float>(rhs, true);
3091}
3092
zhanyong.wan616180e2013-06-18 18:49:51 +00003093// Creates a matcher that matches any float argument approximately equal to
3094// rhs, up to the specified max absolute error bound, where two NANs are
3095// considered unequal. The max absolute error bound must be non-negative.
3096inline internal::FloatingEqMatcher<float> FloatNear(
3097 float rhs, float max_abs_error) {
3098 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
3099}
3100
3101// Creates a matcher that matches any float argument approximately equal to
3102// rhs, up to the specified max absolute error bound, including NaN values when
3103// rhs is NaN. The max absolute error bound must be non-negative.
3104inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
3105 float rhs, float max_abs_error) {
3106 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
3107}
3108
shiqiane35fdd92008-12-10 05:08:54 +00003109// Creates a matcher that matches a pointer (raw or smart) that points
3110// to a value that matches inner_matcher.
3111template <typename InnerMatcher>
3112inline internal::PointeeMatcher<InnerMatcher> Pointee(
3113 const InnerMatcher& inner_matcher) {
3114 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
3115}
3116
3117// Creates a matcher that matches an object whose given field matches
3118// 'matcher'. For example,
3119// Field(&Foo::number, Ge(5))
3120// matches a Foo object x iff x.number >= 5.
3121template <typename Class, typename FieldType, typename FieldMatcher>
3122inline PolymorphicMatcher<
3123 internal::FieldMatcher<Class, FieldType> > Field(
3124 FieldType Class::*field, const FieldMatcher& matcher) {
3125 return MakePolymorphicMatcher(
3126 internal::FieldMatcher<Class, FieldType>(
3127 field, MatcherCast<const FieldType&>(matcher)));
3128 // The call to MatcherCast() is required for supporting inner
3129 // matchers of compatible types. For example, it allows
3130 // Field(&Foo::bar, m)
3131 // to compile where bar is an int32 and m is a matcher for int64.
3132}
3133
3134// Creates a matcher that matches an object whose given property
3135// matches 'matcher'. For example,
3136// Property(&Foo::str, StartsWith("hi"))
3137// matches a Foo object x iff x.str() starts with "hi".
3138template <typename Class, typename PropertyType, typename PropertyMatcher>
3139inline PolymorphicMatcher<
3140 internal::PropertyMatcher<Class, PropertyType> > Property(
3141 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
3142 return MakePolymorphicMatcher(
3143 internal::PropertyMatcher<Class, PropertyType>(
3144 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00003145 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00003146 // The call to MatcherCast() is required for supporting inner
3147 // matchers of compatible types. For example, it allows
3148 // Property(&Foo::bar, m)
3149 // to compile where bar() returns an int32 and m is a matcher for int64.
3150}
3151
3152// Creates a matcher that matches an object iff the result of applying
3153// a callable to x matches 'matcher'.
3154// For example,
3155// ResultOf(f, StartsWith("hi"))
3156// matches a Foo object x iff f(x) starts with "hi".
3157// callable parameter can be a function, function pointer, or a functor.
3158// Callable has to satisfy the following conditions:
3159// * It is required to keep no state affecting the results of
3160// the calls on it and make no assumptions about how many calls
3161// will be made. Any state it keeps must be protected from the
3162// concurrent access.
3163// * If it is a function object, it has to define type result_type.
3164// We recommend deriving your functor classes from std::unary_function.
3165template <typename Callable, typename ResultOfMatcher>
3166internal::ResultOfMatcher<Callable> ResultOf(
3167 Callable callable, const ResultOfMatcher& matcher) {
3168 return internal::ResultOfMatcher<Callable>(
3169 callable,
3170 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
3171 matcher));
3172 // The call to MatcherCast() is required for supporting inner
3173 // matchers of compatible types. For example, it allows
3174 // ResultOf(Function, m)
3175 // to compile where Function() returns an int32 and m is a matcher for int64.
3176}
3177
3178// String matchers.
3179
3180// Matches a string equal to str.
3181inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3182 StrEq(const internal::string& str) {
3183 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3184 str, true, true));
3185}
3186
3187// Matches a string not equal to str.
3188inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3189 StrNe(const internal::string& str) {
3190 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3191 str, false, true));
3192}
3193
3194// Matches a string equal to str, ignoring case.
3195inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3196 StrCaseEq(const internal::string& str) {
3197 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3198 str, true, false));
3199}
3200
3201// Matches a string not equal to str, ignoring case.
3202inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3203 StrCaseNe(const internal::string& str) {
3204 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3205 str, false, false));
3206}
3207
3208// Creates a matcher that matches any string, std::string, or C string
3209// that contains the given substring.
3210inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
3211 HasSubstr(const internal::string& substring) {
3212 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
3213 substring));
3214}
3215
3216// Matches a string that starts with 'prefix' (case-sensitive).
3217inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
3218 StartsWith(const internal::string& prefix) {
3219 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
3220 prefix));
3221}
3222
3223// Matches a string that ends with 'suffix' (case-sensitive).
3224inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
3225 EndsWith(const internal::string& suffix) {
3226 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
3227 suffix));
3228}
3229
shiqiane35fdd92008-12-10 05:08:54 +00003230// Matches a string that fully matches regular expression 'regex'.
3231// The matcher takes ownership of 'regex'.
3232inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3233 const internal::RE* regex) {
3234 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
3235}
3236inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3237 const internal::string& regex) {
3238 return MatchesRegex(new internal::RE(regex));
3239}
3240
3241// Matches a string that contains regular expression 'regex'.
3242// The matcher takes ownership of 'regex'.
3243inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
3244 const internal::RE* regex) {
3245 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
3246}
3247inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
3248 const internal::string& regex) {
3249 return ContainsRegex(new internal::RE(regex));
3250}
3251
shiqiane35fdd92008-12-10 05:08:54 +00003252#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3253// Wide string matchers.
3254
3255// Matches a string equal to str.
3256inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3257 StrEq(const internal::wstring& str) {
3258 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3259 str, true, true));
3260}
3261
3262// Matches a string not equal to str.
3263inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3264 StrNe(const internal::wstring& str) {
3265 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3266 str, false, true));
3267}
3268
3269// Matches a string equal to str, ignoring case.
3270inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3271 StrCaseEq(const internal::wstring& str) {
3272 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3273 str, true, false));
3274}
3275
3276// Matches a string not equal to str, ignoring case.
3277inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3278 StrCaseNe(const internal::wstring& str) {
3279 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3280 str, false, false));
3281}
3282
3283// Creates a matcher that matches any wstring, std::wstring, or C wide string
3284// that contains the given substring.
3285inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
3286 HasSubstr(const internal::wstring& substring) {
3287 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
3288 substring));
3289}
3290
3291// Matches a string that starts with 'prefix' (case-sensitive).
3292inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
3293 StartsWith(const internal::wstring& prefix) {
3294 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
3295 prefix));
3296}
3297
3298// Matches a string that ends with 'suffix' (case-sensitive).
3299inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
3300 EndsWith(const internal::wstring& suffix) {
3301 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
3302 suffix));
3303}
3304
3305#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3306
3307// Creates a polymorphic matcher that matches a 2-tuple where the
3308// first field == the second field.
3309inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
3310
3311// Creates a polymorphic matcher that matches a 2-tuple where the
3312// first field >= the second field.
3313inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
3314
3315// Creates a polymorphic matcher that matches a 2-tuple where the
3316// first field > the second field.
3317inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
3318
3319// Creates a polymorphic matcher that matches a 2-tuple where the
3320// first field <= the second field.
3321inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
3322
3323// Creates a polymorphic matcher that matches a 2-tuple where the
3324// first field < the second field.
3325inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
3326
3327// Creates a polymorphic matcher that matches a 2-tuple where the
3328// first field != the second field.
3329inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
3330
3331// Creates a matcher that matches any value of type T that m doesn't
3332// match.
3333template <typename InnerMatcher>
3334inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
3335 return internal::NotMatcher<InnerMatcher>(m);
3336}
3337
shiqiane35fdd92008-12-10 05:08:54 +00003338// Returns a matcher that matches anything that satisfies the given
3339// predicate. The predicate can be any unary function or functor
3340// whose return type can be implicitly converted to bool.
3341template <typename Predicate>
3342inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
3343Truly(Predicate pred) {
3344 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
3345}
3346
zhanyong.wana31d9ce2013-03-01 01:50:17 +00003347// Returns a matcher that matches the container size. The container must
3348// support both size() and size_type which all STL-like containers provide.
3349// Note that the parameter 'size' can be a value of type size_type as well as
3350// matcher. For instance:
3351// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
3352// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
3353template <typename SizeMatcher>
3354inline internal::SizeIsMatcher<SizeMatcher>
3355SizeIs(const SizeMatcher& size_matcher) {
3356 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
3357}
3358
zhanyong.wan6a896b52009-01-16 01:13:50 +00003359// Returns a matcher that matches an equal container.
3360// This matcher behaves like Eq(), but in the event of mismatch lists the
3361// values that are included in one container but not the other. (Duplicate
3362// values and order differences are not explained.)
3363template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00003364inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00003365 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00003366 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00003367 // This following line is for working around a bug in MSVC 8.0,
3368 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00003369 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00003370 return MakePolymorphicMatcher(
3371 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00003372}
3373
zhanyong.wan898725c2011-09-16 16:45:39 +00003374// Returns a matcher that matches a container that, when sorted using
3375// the given comparator, matches container_matcher.
3376template <typename Comparator, typename ContainerMatcher>
3377inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
3378WhenSortedBy(const Comparator& comparator,
3379 const ContainerMatcher& container_matcher) {
3380 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
3381 comparator, container_matcher);
3382}
3383
3384// Returns a matcher that matches a container that, when sorted using
3385// the < operator, matches container_matcher.
3386template <typename ContainerMatcher>
3387inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
3388WhenSorted(const ContainerMatcher& container_matcher) {
3389 return
3390 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
3391 internal::LessComparator(), container_matcher);
3392}
3393
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003394// Matches an STL-style container or a native array that contains the
3395// same number of elements as in rhs, where its i-th element and rhs's
3396// i-th element (as a pair) satisfy the given pair matcher, for all i.
3397// TupleMatcher must be able to be safely cast to Matcher<tuple<const
3398// T1&, const T2&> >, where T1 and T2 are the types of elements in the
3399// LHS container and the RHS container respectively.
3400template <typename TupleMatcher, typename Container>
3401inline internal::PointwiseMatcher<TupleMatcher,
3402 GTEST_REMOVE_CONST_(Container)>
3403Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
3404 // This following line is for working around a bug in MSVC 8.0,
3405 // which causes Container to be a const type sometimes.
3406 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
3407 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
3408 tuple_matcher, rhs);
3409}
3410
zhanyong.wanb8243162009-06-04 05:48:20 +00003411// Matches an STL-style container or a native array that contains at
3412// least one element matching the given value or matcher.
3413//
3414// Examples:
3415// ::std::set<int> page_ids;
3416// page_ids.insert(3);
3417// page_ids.insert(1);
3418// EXPECT_THAT(page_ids, Contains(1));
3419// EXPECT_THAT(page_ids, Contains(Gt(2)));
3420// EXPECT_THAT(page_ids, Not(Contains(4)));
3421//
3422// ::std::map<int, size_t> page_lengths;
3423// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00003424// EXPECT_THAT(page_lengths,
3425// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00003426//
3427// const char* user_ids[] = { "joe", "mike", "tom" };
3428// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
3429template <typename M>
3430inline internal::ContainsMatcher<M> Contains(M matcher) {
3431 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00003432}
3433
zhanyong.wan33605ba2010-04-22 23:37:47 +00003434// Matches an STL-style container or a native array that contains only
3435// elements matching the given value or matcher.
3436//
3437// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
3438// the messages are different.
3439//
3440// Examples:
3441// ::std::set<int> page_ids;
3442// // Each(m) matches an empty container, regardless of what m is.
3443// EXPECT_THAT(page_ids, Each(Eq(1)));
3444// EXPECT_THAT(page_ids, Each(Eq(77)));
3445//
3446// page_ids.insert(3);
3447// EXPECT_THAT(page_ids, Each(Gt(0)));
3448// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
3449// page_ids.insert(1);
3450// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
3451//
3452// ::std::map<int, size_t> page_lengths;
3453// page_lengths[1] = 100;
3454// page_lengths[2] = 200;
3455// page_lengths[3] = 300;
3456// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
3457// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
3458//
3459// const char* user_ids[] = { "joe", "mike", "tom" };
3460// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
3461template <typename M>
3462inline internal::EachMatcher<M> Each(M matcher) {
3463 return internal::EachMatcher<M>(matcher);
3464}
3465
zhanyong.wanb5937da2009-07-16 20:26:41 +00003466// Key(inner_matcher) matches an std::pair whose 'first' field matches
3467// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3468// std::map that contains at least one element whose key is >= 5.
3469template <typename M>
3470inline internal::KeyMatcher<M> Key(M inner_matcher) {
3471 return internal::KeyMatcher<M>(inner_matcher);
3472}
3473
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003474// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
3475// matches first_matcher and whose 'second' field matches second_matcher. For
3476// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
3477// to match a std::map<int, string> that contains exactly one element whose key
3478// is >= 5 and whose value equals "foo".
3479template <typename FirstMatcher, typename SecondMatcher>
3480inline internal::PairMatcher<FirstMatcher, SecondMatcher>
3481Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
3482 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
3483 first_matcher, second_matcher);
3484}
3485
shiqiane35fdd92008-12-10 05:08:54 +00003486// Returns a predicate that is satisfied by anything that matches the
3487// given matcher.
3488template <typename M>
3489inline internal::MatcherAsPredicate<M> Matches(M matcher) {
3490 return internal::MatcherAsPredicate<M>(matcher);
3491}
3492
zhanyong.wanb8243162009-06-04 05:48:20 +00003493// Returns true iff the value matches the matcher.
3494template <typename T, typename M>
3495inline bool Value(const T& value, M matcher) {
3496 return testing::Matches(matcher)(value);
3497}
3498
zhanyong.wan34b034c2010-03-05 21:23:23 +00003499// Matches the value against the given matcher and explains the match
3500// result to listener.
3501template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00003502inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00003503 M matcher, const T& value, MatchResultListener* listener) {
3504 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
3505}
3506
zhanyong.wan616180e2013-06-18 18:49:51 +00003507#if GTEST_LANG_CXX11
3508// Define variadic matcher versions. They are overloaded in
3509// gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
3510template <typename... Args>
3511inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
3512 return internal::AllOfMatcher<Args...>(matchers...);
3513}
3514
3515template <typename... Args>
3516inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
3517 return internal::AnyOfMatcher<Args...>(matchers...);
3518}
3519
3520#endif // GTEST_LANG_CXX11
3521
zhanyong.wanbf550852009-06-09 06:09:53 +00003522// AllArgs(m) is a synonym of m. This is useful in
3523//
3524// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
3525//
3526// which is easier to read than
3527//
3528// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
3529template <typename InnerMatcher>
3530inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
3531
shiqiane35fdd92008-12-10 05:08:54 +00003532// These macros allow using matchers to check values in Google Test
3533// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
3534// succeed iff the value matches the matcher. If the assertion fails,
3535// the value and the description of the matcher will be printed.
3536#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
3537 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3538#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
3539 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3540
3541} // namespace testing
3542
3543#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_