blob: 962cfde9fdb95bf4b35c1a9f0ff8b5460bcf789b [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements some commonly used argument matchers. More
35// matchers can be defined by the user implementing the
36// MatcherInterface<T> interface if necessary.
37
38#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
39#define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
40
zhanyong.wan6a896b52009-01-16 01:13:50 +000041#include <algorithm>
zhanyong.wan16cf4732009-05-14 20:55:30 +000042#include <limits>
shiqiane35fdd92008-12-10 05:08:54 +000043#include <ostream> // NOLINT
44#include <sstream>
45#include <string>
zhanyong.wanab5b77c2010-05-17 19:32:48 +000046#include <utility>
shiqiane35fdd92008-12-10 05:08:54 +000047#include <vector>
48
zhanyong.wan53e08c42010-09-14 05:38:21 +000049#include "gmock/internal/gmock-internal-utils.h"
50#include "gmock/internal/gmock-port.h"
51#include "gtest/gtest.h"
shiqiane35fdd92008-12-10 05:08:54 +000052
53namespace testing {
54
55// To implement a matcher Foo for type T, define:
56// 1. a class FooMatcherImpl that implements the
57// MatcherInterface<T> interface, and
58// 2. a factory function that creates a Matcher<T> object from a
59// FooMatcherImpl*.
60//
61// The two-level delegation design makes it possible to allow a user
62// to write "v" instead of "Eq(v)" where a Matcher is expected, which
63// is impossible if we pass matchers by pointers. It also eases
64// ownership management as Matcher objects can now be copied like
65// plain values.
66
zhanyong.wan82113312010-01-08 21:55:40 +000067// MatchResultListener is an abstract class. Its << operator can be
68// used by a matcher to explain why a value matches or doesn't match.
69//
70// TODO(wan@google.com): add method
71// bool InterestedInWhy(bool result) const;
72// to indicate whether the listener is interested in why the match
73// result is 'result'.
74class MatchResultListener {
75 public:
76 // Creates a listener object with the given underlying ostream. The
77 // listener does not own the ostream.
78 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
79 virtual ~MatchResultListener() = 0; // Makes this class abstract.
80
81 // Streams x to the underlying ostream; does nothing if the ostream
82 // is NULL.
83 template <typename T>
84 MatchResultListener& operator<<(const T& x) {
85 if (stream_ != NULL)
86 *stream_ << x;
87 return *this;
88 }
89
90 // Returns the underlying ostream.
91 ::std::ostream* stream() { return stream_; }
92
zhanyong.wana862f1d2010-03-15 21:23:04 +000093 // Returns true iff the listener is interested in an explanation of
94 // the match result. A matcher's MatchAndExplain() method can use
95 // this information to avoid generating the explanation when no one
96 // intends to hear it.
97 bool IsInterested() const { return stream_ != NULL; }
98
zhanyong.wan82113312010-01-08 21:55:40 +000099 private:
100 ::std::ostream* const stream_;
101
102 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
103};
104
105inline MatchResultListener::~MatchResultListener() {
106}
107
shiqiane35fdd92008-12-10 05:08:54 +0000108// The implementation of a matcher.
109template <typename T>
110class MatcherInterface {
111 public:
112 virtual ~MatcherInterface() {}
113
zhanyong.wan82113312010-01-08 21:55:40 +0000114 // Returns true iff the matcher matches x; also explains the match
zhanyong.wan83f6b082013-03-01 01:47:35 +0000115 // result to 'listener' if necessary (see the next paragraph), in
116 // the form of a non-restrictive relative clause ("which ...",
117 // "whose ...", etc) that describes x. For example, the
118 // MatchAndExplain() method of the Pointee(...) matcher should
119 // generate an explanation like "which points to ...".
120 //
121 // Implementations of MatchAndExplain() should add an explanation of
122 // the match result *if and only if* they can provide additional
123 // information that's not already present (or not obvious) in the
124 // print-out of x and the matcher's description. Whether the match
125 // succeeds is not a factor in deciding whether an explanation is
126 // needed, as sometimes the caller needs to print a failure message
127 // when the match succeeds (e.g. when the matcher is used inside
128 // Not()).
129 //
130 // For example, a "has at least 10 elements" matcher should explain
131 // what the actual element count is, regardless of the match result,
132 // as it is useful information to the reader; on the other hand, an
133 // "is empty" matcher probably only needs to explain what the actual
134 // size is when the match fails, as it's redundant to say that the
135 // size is 0 when the value is already known to be empty.
zhanyong.wan82113312010-01-08 21:55:40 +0000136 //
zhanyong.wandb22c222010-01-28 21:52:29 +0000137 // You should override this method when defining a new matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000138 //
139 // It's the responsibility of the caller (Google Mock) to guarantee
140 // that 'listener' is not NULL. This helps to simplify a matcher's
141 // implementation when it doesn't care about the performance, as it
142 // can talk to 'listener' without checking its validity first.
143 // However, in order to implement dummy listeners efficiently,
144 // listener->stream() may be NULL.
zhanyong.wandb22c222010-01-28 21:52:29 +0000145 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
shiqiane35fdd92008-12-10 05:08:54 +0000146
zhanyong.wana862f1d2010-03-15 21:23:04 +0000147 // Describes this matcher to an ostream. The function should print
148 // a verb phrase that describes the property a value matching this
149 // matcher should have. The subject of the verb phrase is the value
150 // being matched. For example, the DescribeTo() method of the Gt(7)
151 // matcher prints "is greater than 7".
shiqiane35fdd92008-12-10 05:08:54 +0000152 virtual void DescribeTo(::std::ostream* os) const = 0;
153
154 // Describes the negation of this matcher to an ostream. For
155 // example, if the description of this matcher is "is greater than
156 // 7", the negated description could be "is not greater than 7".
157 // You are not required to override this when implementing
158 // MatcherInterface, but it is highly advised so that your matcher
159 // can produce good error messages.
160 virtual void DescribeNegationTo(::std::ostream* os) const {
161 *os << "not (";
162 DescribeTo(os);
163 *os << ")";
164 }
shiqiane35fdd92008-12-10 05:08:54 +0000165};
166
167namespace internal {
168
zhanyong.wan82113312010-01-08 21:55:40 +0000169// A match result listener that ignores the explanation.
170class DummyMatchResultListener : public MatchResultListener {
171 public:
172 DummyMatchResultListener() : MatchResultListener(NULL) {}
173
174 private:
175 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
176};
177
178// A match result listener that forwards the explanation to a given
179// ostream. The difference between this and MatchResultListener is
180// that the former is concrete.
181class StreamMatchResultListener : public MatchResultListener {
182 public:
183 explicit StreamMatchResultListener(::std::ostream* os)
184 : MatchResultListener(os) {}
185
186 private:
187 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
188};
189
190// A match result listener that stores the explanation in a string.
191class StringMatchResultListener : public MatchResultListener {
192 public:
193 StringMatchResultListener() : MatchResultListener(&ss_) {}
194
195 // Returns the explanation heard so far.
196 internal::string str() const { return ss_.str(); }
197
198 private:
199 ::std::stringstream ss_;
200
201 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
202};
203
shiqiane35fdd92008-12-10 05:08:54 +0000204// An internal class for implementing Matcher<T>, which will derive
205// from it. We put functionalities common to all Matcher<T>
206// specializations here to avoid code duplication.
207template <typename T>
208class MatcherBase {
209 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000210 // Returns true iff the matcher matches x; also explains the match
211 // result to 'listener'.
212 bool MatchAndExplain(T x, MatchResultListener* listener) const {
213 return impl_->MatchAndExplain(x, listener);
214 }
215
shiqiane35fdd92008-12-10 05:08:54 +0000216 // Returns true iff this matcher matches x.
zhanyong.wan82113312010-01-08 21:55:40 +0000217 bool Matches(T x) const {
218 DummyMatchResultListener dummy;
219 return MatchAndExplain(x, &dummy);
220 }
shiqiane35fdd92008-12-10 05:08:54 +0000221
222 // Describes this matcher to an ostream.
223 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
224
225 // Describes the negation of this matcher to an ostream.
226 void DescribeNegationTo(::std::ostream* os) const {
227 impl_->DescribeNegationTo(os);
228 }
229
230 // Explains why x matches, or doesn't match, the matcher.
231 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000232 StreamMatchResultListener listener(os);
233 MatchAndExplain(x, &listener);
shiqiane35fdd92008-12-10 05:08:54 +0000234 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000235
shiqiane35fdd92008-12-10 05:08:54 +0000236 protected:
237 MatcherBase() {}
238
239 // Constructs a matcher from its implementation.
240 explicit MatcherBase(const MatcherInterface<T>* impl)
241 : impl_(impl) {}
242
243 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000244
shiqiane35fdd92008-12-10 05:08:54 +0000245 private:
246 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
247 // interfaces. The former dynamically allocates a chunk of memory
248 // to hold the reference count, while the latter tracks all
249 // references using a circular linked list without allocating
250 // memory. It has been observed that linked_ptr performs better in
251 // typical scenarios. However, shared_ptr can out-perform
252 // linked_ptr when there are many more uses of the copy constructor
253 // than the default constructor.
254 //
255 // If performance becomes a problem, we should see if using
256 // shared_ptr helps.
257 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
258};
259
shiqiane35fdd92008-12-10 05:08:54 +0000260} // namespace internal
261
262// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
263// object that can check whether a value of type T matches. The
264// implementation of Matcher<T> is just a linked_ptr to const
265// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
266// from Matcher!
267template <typename T>
268class Matcher : public internal::MatcherBase<T> {
269 public:
vladlosev88032d82010-11-17 23:29:21 +0000270 // Constructs a null matcher. Needed for storing Matcher objects in STL
271 // containers. A default-constructed matcher is not yet initialized. You
272 // cannot use it until a valid value has been assigned to it.
shiqiane35fdd92008-12-10 05:08:54 +0000273 Matcher() {}
274
275 // Constructs a matcher from its implementation.
276 explicit Matcher(const MatcherInterface<T>* impl)
277 : internal::MatcherBase<T>(impl) {}
278
zhanyong.wan18490652009-05-11 18:54:08 +0000279 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000280 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
281 Matcher(T value); // NOLINT
282};
283
284// The following two specializations allow the user to write str
285// instead of Eq(str) and "foo" instead of Eq("foo") when a string
286// matcher is expected.
287template <>
vladlosev587c1b32011-05-20 00:42:22 +0000288class GTEST_API_ Matcher<const internal::string&>
shiqiane35fdd92008-12-10 05:08:54 +0000289 : public internal::MatcherBase<const internal::string&> {
290 public:
291 Matcher() {}
292
293 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
294 : internal::MatcherBase<const internal::string&>(impl) {}
295
296 // Allows the user to write str instead of Eq(str) sometimes, where
297 // str is a string object.
298 Matcher(const internal::string& s); // NOLINT
299
300 // Allows the user to write "foo" instead of Eq("foo") sometimes.
301 Matcher(const char* s); // NOLINT
302};
303
304template <>
vladlosev587c1b32011-05-20 00:42:22 +0000305class GTEST_API_ Matcher<internal::string>
shiqiane35fdd92008-12-10 05:08:54 +0000306 : public internal::MatcherBase<internal::string> {
307 public:
308 Matcher() {}
309
310 explicit Matcher(const MatcherInterface<internal::string>* impl)
311 : internal::MatcherBase<internal::string>(impl) {}
312
313 // Allows the user to write str instead of Eq(str) sometimes, where
314 // str is a string object.
315 Matcher(const internal::string& s); // NOLINT
316
317 // Allows the user to write "foo" instead of Eq("foo") sometimes.
318 Matcher(const char* s); // NOLINT
319};
320
zhanyong.wan1f122a02013-03-25 16:27:03 +0000321#if GTEST_HAS_STRING_PIECE_
322// The following two specializations allow the user to write str
323// instead of Eq(str) and "foo" instead of Eq("foo") when a StringPiece
324// matcher is expected.
325template <>
326class GTEST_API_ Matcher<const StringPiece&>
327 : public internal::MatcherBase<const StringPiece&> {
328 public:
329 Matcher() {}
330
331 explicit Matcher(const MatcherInterface<const StringPiece&>* impl)
332 : internal::MatcherBase<const StringPiece&>(impl) {}
333
334 // Allows the user to write str instead of Eq(str) sometimes, where
335 // str is a string object.
336 Matcher(const internal::string& s); // NOLINT
337
338 // Allows the user to write "foo" instead of Eq("foo") sometimes.
339 Matcher(const char* s); // NOLINT
340
341 // Allows the user to pass StringPieces directly.
342 Matcher(StringPiece s); // NOLINT
343};
344
345template <>
346class GTEST_API_ Matcher<StringPiece>
347 : public internal::MatcherBase<StringPiece> {
348 public:
349 Matcher() {}
350
351 explicit Matcher(const MatcherInterface<StringPiece>* impl)
352 : internal::MatcherBase<StringPiece>(impl) {}
353
354 // Allows the user to write str instead of Eq(str) sometimes, where
355 // str is a string object.
356 Matcher(const internal::string& s); // NOLINT
357
358 // Allows the user to write "foo" instead of Eq("foo") sometimes.
359 Matcher(const char* s); // NOLINT
360
361 // Allows the user to pass StringPieces directly.
362 Matcher(StringPiece s); // NOLINT
363};
364#endif // GTEST_HAS_STRING_PIECE_
365
shiqiane35fdd92008-12-10 05:08:54 +0000366// The PolymorphicMatcher class template makes it easy to implement a
367// polymorphic matcher (i.e. a matcher that can match values of more
368// than one type, e.g. Eq(n) and NotNull()).
369//
zhanyong.wandb22c222010-01-28 21:52:29 +0000370// To define a polymorphic matcher, a user should provide an Impl
371// class that has a DescribeTo() method and a DescribeNegationTo()
372// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000373//
zhanyong.wandb22c222010-01-28 21:52:29 +0000374// bool MatchAndExplain(const Value& value,
375// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000376//
377// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000378template <class Impl>
379class PolymorphicMatcher {
380 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000381 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000382
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000383 // Returns a mutable reference to the underlying matcher
384 // implementation object.
385 Impl& mutable_impl() { return impl_; }
386
387 // Returns an immutable reference to the underlying matcher
388 // implementation object.
389 const Impl& impl() const { return impl_; }
390
shiqiane35fdd92008-12-10 05:08:54 +0000391 template <typename T>
392 operator Matcher<T>() const {
393 return Matcher<T>(new MonomorphicImpl<T>(impl_));
394 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000395
shiqiane35fdd92008-12-10 05:08:54 +0000396 private:
397 template <typename T>
398 class MonomorphicImpl : public MatcherInterface<T> {
399 public:
400 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
401
shiqiane35fdd92008-12-10 05:08:54 +0000402 virtual void DescribeTo(::std::ostream* os) const {
403 impl_.DescribeTo(os);
404 }
405
406 virtual void DescribeNegationTo(::std::ostream* os) const {
407 impl_.DescribeNegationTo(os);
408 }
409
zhanyong.wan82113312010-01-08 21:55:40 +0000410 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000411 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000412 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000413
shiqiane35fdd92008-12-10 05:08:54 +0000414 private:
415 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000416
417 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000418 };
419
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000420 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000421
422 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000423};
424
425// Creates a matcher from its implementation. This is easier to use
426// than the Matcher<T> constructor as it doesn't require you to
427// explicitly write the template argument, e.g.
428//
429// MakeMatcher(foo);
430// vs
431// Matcher<const string&>(foo);
432template <typename T>
433inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
434 return Matcher<T>(impl);
zhanyong.wan2eab17b2013-03-08 17:53:24 +0000435}
shiqiane35fdd92008-12-10 05:08:54 +0000436
437// Creates a polymorphic matcher from its implementation. This is
438// easier to use than the PolymorphicMatcher<Impl> constructor as it
439// doesn't require you to explicitly write the template argument, e.g.
440//
441// MakePolymorphicMatcher(foo);
442// vs
443// PolymorphicMatcher<TypeOfFoo>(foo);
444template <class Impl>
445inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
446 return PolymorphicMatcher<Impl>(impl);
447}
448
jgm79a367e2012-04-10 16:02:11 +0000449// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
450// and MUST NOT BE USED IN USER CODE!!!
451namespace internal {
452
453// The MatcherCastImpl class template is a helper for implementing
454// MatcherCast(). We need this helper in order to partially
455// specialize the implementation of MatcherCast() (C++ allows
456// class/struct templates to be partially specialized, but not
457// function templates.).
458
459// This general version is used when MatcherCast()'s argument is a
460// polymorphic matcher (i.e. something that can be converted to a
461// Matcher but is not one yet; for example, Eq(value)) or a value (for
462// example, "hello").
463template <typename T, typename M>
464class MatcherCastImpl {
465 public:
466 static Matcher<T> Cast(M polymorphic_matcher_or_value) {
467 // M can be a polymorhic matcher, in which case we want to use
468 // its conversion operator to create Matcher<T>. Or it can be a value
469 // that should be passed to the Matcher<T>'s constructor.
470 //
471 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
472 // polymorphic matcher because it'll be ambiguous if T has an implicit
473 // constructor from M (this usually happens when T has an implicit
474 // constructor from any type).
475 //
476 // It won't work to unconditionally implict_cast
477 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
478 // a user-defined conversion from M to T if one exists (assuming M is
479 // a value).
480 return CastImpl(
481 polymorphic_matcher_or_value,
482 BooleanConstant<
483 internal::ImplicitlyConvertible<M, Matcher<T> >::value>());
484 }
485
486 private:
487 static Matcher<T> CastImpl(M value, BooleanConstant<false>) {
488 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
489 // matcher. It must be a value then. Use direct initialization to create
490 // a matcher.
491 return Matcher<T>(ImplicitCast_<T>(value));
492 }
493
494 static Matcher<T> CastImpl(M polymorphic_matcher_or_value,
495 BooleanConstant<true>) {
496 // M is implicitly convertible to Matcher<T>, which means that either
497 // M is a polymorhpic matcher or Matcher<T> has an implicit constructor
498 // from M. In both cases using the implicit conversion will produce a
499 // matcher.
500 //
501 // Even if T has an implicit constructor from M, it won't be called because
502 // creating Matcher<T> would require a chain of two user-defined conversions
503 // (first to create T from M and then to create Matcher<T> from T).
504 return polymorphic_matcher_or_value;
505 }
506};
507
508// This more specialized version is used when MatcherCast()'s argument
509// is already a Matcher. This only compiles when type T can be
510// statically converted to type U.
511template <typename T, typename U>
512class MatcherCastImpl<T, Matcher<U> > {
513 public:
514 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
515 return Matcher<T>(new Impl(source_matcher));
516 }
517
518 private:
519 class Impl : public MatcherInterface<T> {
520 public:
521 explicit Impl(const Matcher<U>& source_matcher)
522 : source_matcher_(source_matcher) {}
523
524 // We delegate the matching logic to the source matcher.
525 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
526 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
527 }
528
529 virtual void DescribeTo(::std::ostream* os) const {
530 source_matcher_.DescribeTo(os);
531 }
532
533 virtual void DescribeNegationTo(::std::ostream* os) const {
534 source_matcher_.DescribeNegationTo(os);
535 }
536
537 private:
538 const Matcher<U> source_matcher_;
539
540 GTEST_DISALLOW_ASSIGN_(Impl);
541 };
542};
543
544// This even more specialized version is used for efficiently casting
545// a matcher to its own type.
546template <typename T>
547class MatcherCastImpl<T, Matcher<T> > {
548 public:
549 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
550};
551
552} // namespace internal
553
shiqiane35fdd92008-12-10 05:08:54 +0000554// In order to be safe and clear, casting between different matcher
555// types is done explicitly via MatcherCast<T>(m), which takes a
556// matcher m and returns a Matcher<T>. It compiles only when T can be
557// statically converted to the argument type of m.
558template <typename T, typename M>
jgm79a367e2012-04-10 16:02:11 +0000559inline Matcher<T> MatcherCast(M matcher) {
560 return internal::MatcherCastImpl<T, M>::Cast(matcher);
561}
shiqiane35fdd92008-12-10 05:08:54 +0000562
zhanyong.wan18490652009-05-11 18:54:08 +0000563// Implements SafeMatcherCast().
564//
zhanyong.wan95b12332009-09-25 18:55:50 +0000565// We use an intermediate class to do the actual safe casting as Nokia's
566// Symbian compiler cannot decide between
567// template <T, M> ... (M) and
568// template <T, U> ... (const Matcher<U>&)
569// for function templates but can for member function templates.
570template <typename T>
571class SafeMatcherCastImpl {
572 public:
jgm79a367e2012-04-10 16:02:11 +0000573 // This overload handles polymorphic matchers and values only since
574 // monomorphic matchers are handled by the next one.
zhanyong.wan95b12332009-09-25 18:55:50 +0000575 template <typename M>
jgm79a367e2012-04-10 16:02:11 +0000576 static inline Matcher<T> Cast(M polymorphic_matcher_or_value) {
577 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
zhanyong.wan95b12332009-09-25 18:55:50 +0000578 }
zhanyong.wan18490652009-05-11 18:54:08 +0000579
zhanyong.wan95b12332009-09-25 18:55:50 +0000580 // This overload handles monomorphic matchers.
581 //
582 // In general, if type T can be implicitly converted to type U, we can
583 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
584 // contravariant): just keep a copy of the original Matcher<U>, convert the
585 // argument from type T to U, and then pass it to the underlying Matcher<U>.
586 // The only exception is when U is a reference and T is not, as the
587 // underlying Matcher<U> may be interested in the argument's address, which
588 // is not preserved in the conversion from T to U.
589 template <typename U>
590 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
591 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000592 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000593 T_must_be_implicitly_convertible_to_U);
594 // Enforce that we are not converting a non-reference type T to a reference
595 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000596 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000597 internal::is_reference<T>::value || !internal::is_reference<U>::value,
598 cannot_convert_non_referentce_arg_to_reference);
599 // In case both T and U are arithmetic types, enforce that the
600 // conversion is not lossy.
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000601 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
602 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000603 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
604 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000605 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000606 kTIsOther || kUIsOther ||
607 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
608 conversion_of_arithmetic_types_must_be_lossless);
609 return MatcherCast<T>(matcher);
610 }
611};
612
613template <typename T, typename M>
614inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
615 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000616}
617
shiqiane35fdd92008-12-10 05:08:54 +0000618// A<T>() returns a matcher that matches any value of type T.
619template <typename T>
620Matcher<T> A();
621
622// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
623// and MUST NOT BE USED IN USER CODE!!!
624namespace internal {
625
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000626// If the explanation is not empty, prints it to the ostream.
627inline void PrintIfNotEmpty(const internal::string& explanation,
628 std::ostream* os) {
629 if (explanation != "" && os != NULL) {
630 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000631 }
632}
633
zhanyong.wan736baa82010-09-27 17:44:16 +0000634// Returns true if the given type name is easy to read by a human.
635// This is used to decide whether printing the type of a value might
636// be helpful.
637inline bool IsReadableTypeName(const string& type_name) {
638 // We consider a type name readable if it's short or doesn't contain
639 // a template or function type.
640 return (type_name.length() <= 20 ||
641 type_name.find_first_of("<(") == string::npos);
642}
643
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000644// Matches the value against the given matcher, prints the value and explains
645// the match result to the listener. Returns the match result.
646// 'listener' must not be NULL.
647// Value cannot be passed by const reference, because some matchers take a
648// non-const argument.
649template <typename Value, typename T>
650bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
651 MatchResultListener* listener) {
652 if (!listener->IsInterested()) {
653 // If the listener is not interested, we do not need to construct the
654 // inner explanation.
655 return matcher.Matches(value);
656 }
657
658 StringMatchResultListener inner_listener;
659 const bool match = matcher.MatchAndExplain(value, &inner_listener);
660
661 UniversalPrint(value, listener->stream());
zhanyong.wan736baa82010-09-27 17:44:16 +0000662#if GTEST_HAS_RTTI
663 const string& type_name = GetTypeName<Value>();
664 if (IsReadableTypeName(type_name))
665 *listener->stream() << " (of type " << type_name << ")";
666#endif
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000667 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000668
669 return match;
670}
671
shiqiane35fdd92008-12-10 05:08:54 +0000672// An internal helper class for doing compile-time loop on a tuple's
673// fields.
674template <size_t N>
675class TuplePrefix {
676 public:
677 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
678 // iff the first N fields of matcher_tuple matches the first N
679 // fields of value_tuple, respectively.
680 template <typename MatcherTuple, typename ValueTuple>
681 static bool Matches(const MatcherTuple& matcher_tuple,
682 const ValueTuple& value_tuple) {
683 using ::std::tr1::get;
684 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
685 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
686 }
687
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000688 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000689 // describes failures in matching the first N fields of matchers
690 // against the first N fields of values. If there is no failure,
691 // nothing will be streamed to os.
692 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000693 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
694 const ValueTuple& values,
695 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000696 using ::std::tr1::tuple_element;
697 using ::std::tr1::get;
698
699 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000700 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000701
702 // Then describes the failure (if any) in the (N - 1)-th (0-based)
703 // field.
704 typename tuple_element<N - 1, MatcherTuple>::type matcher =
705 get<N - 1>(matchers);
706 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
707 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000708 StringMatchResultListener listener;
709 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000710 // TODO(wan): include in the message the name of the parameter
711 // as used in MOCK_METHOD*() when possible.
712 *os << " Expected arg #" << N - 1 << ": ";
713 get<N - 1>(matchers).DescribeTo(os);
714 *os << "\n Actual: ";
715 // We remove the reference in type Value to prevent the
716 // universal printer from printing the address of value, which
717 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000718 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000719 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000720 internal::UniversalPrint(value, os);
721 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000722 *os << "\n";
723 }
724 }
725};
726
727// The base case.
728template <>
729class TuplePrefix<0> {
730 public:
731 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000732 static bool Matches(const MatcherTuple& /* matcher_tuple */,
733 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000734 return true;
735 }
736
737 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000738 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
739 const ValueTuple& /* values */,
740 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000741};
742
743// TupleMatches(matcher_tuple, value_tuple) returns true iff all
744// matchers in matcher_tuple match the corresponding fields in
745// value_tuple. It is a compiler error if matcher_tuple and
746// value_tuple have different number of fields or incompatible field
747// types.
748template <typename MatcherTuple, typename ValueTuple>
749bool TupleMatches(const MatcherTuple& matcher_tuple,
750 const ValueTuple& value_tuple) {
751 using ::std::tr1::tuple_size;
752 // Makes sure that matcher_tuple and value_tuple have the same
753 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000754 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000755 tuple_size<ValueTuple>::value,
756 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000757 return TuplePrefix<tuple_size<ValueTuple>::value>::
758 Matches(matcher_tuple, value_tuple);
759}
760
761// Describes failures in matching matchers against values. If there
762// is no failure, nothing will be streamed to os.
763template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000764void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
765 const ValueTuple& values,
766 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000767 using ::std::tr1::tuple_size;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000768 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000769 matchers, values, os);
770}
771
shiqiane35fdd92008-12-10 05:08:54 +0000772// Implements A<T>().
773template <typename T>
774class AnyMatcherImpl : public MatcherInterface<T> {
775 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000776 virtual bool MatchAndExplain(
777 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000778 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
779 virtual void DescribeNegationTo(::std::ostream* os) const {
780 // This is mostly for completeness' safe, as it's not very useful
781 // to write Not(A<bool>()). However we cannot completely rule out
782 // such a possibility, and it doesn't hurt to be prepared.
783 *os << "never matches";
784 }
785};
786
787// Implements _, a matcher that matches any value of any
788// type. This is a polymorphic matcher, so we need a template type
789// conversion operator to make it appearing as a Matcher<T> for any
790// type T.
791class AnythingMatcher {
792 public:
793 template <typename T>
794 operator Matcher<T>() const { return A<T>(); }
795};
796
797// Implements a matcher that compares a given value with a
798// pre-supplied value using one of the ==, <=, <, etc, operators. The
799// two values being compared don't have to have the same type.
800//
801// The matcher defined here is polymorphic (for example, Eq(5) can be
802// used to match an int, a short, a double, etc). Therefore we use
803// a template type conversion operator in the implementation.
804//
805// We define this as a macro in order to eliminate duplicated source
806// code.
807//
808// The following template definition assumes that the Rhs parameter is
809// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000810#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_( \
811 name, op, relation, negated_relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000812 template <typename Rhs> class name##Matcher { \
813 public: \
814 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
815 template <typename Lhs> \
816 operator Matcher<Lhs>() const { \
817 return MakeMatcher(new Impl<Lhs>(rhs_)); \
818 } \
819 private: \
820 template <typename Lhs> \
821 class Impl : public MatcherInterface<Lhs> { \
822 public: \
823 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
zhanyong.wan82113312010-01-08 21:55:40 +0000824 virtual bool MatchAndExplain(\
825 Lhs lhs, MatchResultListener* /* listener */) const { \
826 return lhs op rhs_; \
827 } \
shiqiane35fdd92008-12-10 05:08:54 +0000828 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000829 *os << relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000830 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000831 } \
832 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000833 *os << negated_relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000834 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000835 } \
836 private: \
837 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000838 GTEST_DISALLOW_ASSIGN_(Impl); \
shiqiane35fdd92008-12-10 05:08:54 +0000839 }; \
840 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000841 GTEST_DISALLOW_ASSIGN_(name##Matcher); \
shiqiane35fdd92008-12-10 05:08:54 +0000842 }
843
844// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
845// respectively.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000846GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "is equal to", "isn't equal to");
847GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "is >=", "isn't >=");
848GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "is >", "isn't >");
849GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "is <=", "isn't <=");
850GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "is <", "isn't <");
851GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "isn't equal to", "is equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000852
zhanyong.wane0d051e2009-02-19 00:33:37 +0000853#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000854
vladlosev79b83502009-11-18 00:43:37 +0000855// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000856// pointer that is NULL.
857class IsNullMatcher {
858 public:
vladlosev79b83502009-11-18 00:43:37 +0000859 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000860 bool MatchAndExplain(const Pointer& p,
861 MatchResultListener* /* listener */) const {
862 return GetRawPointer(p) == NULL;
863 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000864
865 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
866 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000867 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000868 }
869};
870
vladlosev79b83502009-11-18 00:43:37 +0000871// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000872// pointer that is not NULL.
873class NotNullMatcher {
874 public:
vladlosev79b83502009-11-18 00:43:37 +0000875 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000876 bool MatchAndExplain(const Pointer& p,
877 MatchResultListener* /* listener */) const {
878 return GetRawPointer(p) != NULL;
879 }
shiqiane35fdd92008-12-10 05:08:54 +0000880
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000881 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +0000882 void DescribeNegationTo(::std::ostream* os) const {
883 *os << "is NULL";
884 }
885};
886
887// Ref(variable) matches any argument that is a reference to
888// 'variable'. This matcher is polymorphic as it can match any
889// super type of the type of 'variable'.
890//
891// The RefMatcher template class implements Ref(variable). It can
892// only be instantiated with a reference type. This prevents a user
893// from mistakenly using Ref(x) to match a non-reference function
894// argument. For example, the following will righteously cause a
895// compiler error:
896//
897// int n;
898// Matcher<int> m1 = Ref(n); // This won't compile.
899// Matcher<int&> m2 = Ref(n); // This will compile.
900template <typename T>
901class RefMatcher;
902
903template <typename T>
904class RefMatcher<T&> {
905 // Google Mock is a generic framework and thus needs to support
906 // mocking any function types, including those that take non-const
907 // reference arguments. Therefore the template parameter T (and
908 // Super below) can be instantiated to either a const type or a
909 // non-const type.
910 public:
911 // RefMatcher() takes a T& instead of const T&, as we want the
912 // compiler to catch using Ref(const_value) as a matcher for a
913 // non-const reference.
914 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
915
916 template <typename Super>
917 operator Matcher<Super&>() const {
918 // By passing object_ (type T&) to Impl(), which expects a Super&,
919 // we make sure that Super is a super type of T. In particular,
920 // this catches using Ref(const_value) as a matcher for a
921 // non-const reference, as you cannot implicitly convert a const
922 // reference to a non-const reference.
923 return MakeMatcher(new Impl<Super>(object_));
924 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000925
shiqiane35fdd92008-12-10 05:08:54 +0000926 private:
927 template <typename Super>
928 class Impl : public MatcherInterface<Super&> {
929 public:
930 explicit Impl(Super& x) : object_(x) {} // NOLINT
931
zhanyong.wandb22c222010-01-28 21:52:29 +0000932 // MatchAndExplain() takes a Super& (as opposed to const Super&)
933 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +0000934 virtual bool MatchAndExplain(
935 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000936 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +0000937 return &x == &object_;
938 }
shiqiane35fdd92008-12-10 05:08:54 +0000939
940 virtual void DescribeTo(::std::ostream* os) const {
941 *os << "references the variable ";
942 UniversalPrinter<Super&>::Print(object_, os);
943 }
944
945 virtual void DescribeNegationTo(::std::ostream* os) const {
946 *os << "does not reference the variable ";
947 UniversalPrinter<Super&>::Print(object_, os);
948 }
949
shiqiane35fdd92008-12-10 05:08:54 +0000950 private:
951 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000952
953 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000954 };
955
956 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000957
958 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000959};
960
961// Polymorphic helper functions for narrow and wide string matchers.
962inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
963 return String::CaseInsensitiveCStringEquals(lhs, rhs);
964}
965
966inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
967 const wchar_t* rhs) {
968 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
969}
970
971// String comparison for narrow or wide strings that can have embedded NUL
972// characters.
973template <typename StringType>
974bool CaseInsensitiveStringEquals(const StringType& s1,
975 const StringType& s2) {
976 // Are the heads equal?
977 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
978 return false;
979 }
980
981 // Skip the equal heads.
982 const typename StringType::value_type nul = 0;
983 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
984
985 // Are we at the end of either s1 or s2?
986 if (i1 == StringType::npos || i2 == StringType::npos) {
987 return i1 == i2;
988 }
989
990 // Are the tails equal?
991 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
992}
993
994// String matchers.
995
996// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
997template <typename StringType>
998class StrEqualityMatcher {
999 public:
shiqiane35fdd92008-12-10 05:08:54 +00001000 StrEqualityMatcher(const StringType& str, bool expect_eq,
1001 bool case_sensitive)
1002 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1003
jgm38513a82012-11-15 15:50:36 +00001004 // Accepts pointer types, particularly:
1005 // const char*
1006 // char*
1007 // const wchar_t*
1008 // wchar_t*
1009 template <typename CharType>
1010 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001011 if (s == NULL) {
1012 return !expect_eq_;
1013 }
zhanyong.wandb22c222010-01-28 21:52:29 +00001014 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001015 }
1016
jgm38513a82012-11-15 15:50:36 +00001017 // Matches anything that can convert to StringType.
1018 //
1019 // This is a template, not just a plain function with const StringType&,
1020 // because StringPiece has some interfering non-explicit constructors.
1021 template <typename MatcheeStringType>
1022 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001023 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001024 const StringType& s2(s);
1025 const bool eq = case_sensitive_ ? s2 == string_ :
1026 CaseInsensitiveStringEquals(s2, string_);
shiqiane35fdd92008-12-10 05:08:54 +00001027 return expect_eq_ == eq;
1028 }
1029
1030 void DescribeTo(::std::ostream* os) const {
1031 DescribeToHelper(expect_eq_, os);
1032 }
1033
1034 void DescribeNegationTo(::std::ostream* os) const {
1035 DescribeToHelper(!expect_eq_, os);
1036 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001037
shiqiane35fdd92008-12-10 05:08:54 +00001038 private:
1039 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001040 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +00001041 *os << "equal to ";
1042 if (!case_sensitive_) {
1043 *os << "(ignoring case) ";
1044 }
vladloseve2e8ba42010-05-13 18:16:03 +00001045 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001046 }
1047
1048 const StringType string_;
1049 const bool expect_eq_;
1050 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001051
1052 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001053};
1054
1055// Implements the polymorphic HasSubstr(substring) matcher, which
1056// can be used as a Matcher<T> as long as T can be converted to a
1057// string.
1058template <typename StringType>
1059class HasSubstrMatcher {
1060 public:
shiqiane35fdd92008-12-10 05:08:54 +00001061 explicit HasSubstrMatcher(const StringType& substring)
1062 : substring_(substring) {}
1063
jgm38513a82012-11-15 15:50:36 +00001064 // Accepts pointer types, particularly:
1065 // const char*
1066 // char*
1067 // const wchar_t*
1068 // wchar_t*
1069 template <typename CharType>
1070 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001071 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001072 }
1073
jgm38513a82012-11-15 15:50:36 +00001074 // Matches anything that can convert to StringType.
1075 //
1076 // This is a template, not just a plain function with const StringType&,
1077 // because StringPiece has some interfering non-explicit constructors.
1078 template <typename MatcheeStringType>
1079 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001080 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001081 const StringType& s2(s);
1082 return s2.find(substring_) != StringType::npos;
shiqiane35fdd92008-12-10 05:08:54 +00001083 }
1084
1085 // Describes what this matcher matches.
1086 void DescribeTo(::std::ostream* os) const {
1087 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001088 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001089 }
1090
1091 void DescribeNegationTo(::std::ostream* os) const {
1092 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +00001093 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001094 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001095
shiqiane35fdd92008-12-10 05:08:54 +00001096 private:
1097 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001098
1099 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001100};
1101
1102// Implements the polymorphic StartsWith(substring) matcher, which
1103// can be used as a Matcher<T> as long as T can be converted to a
1104// string.
1105template <typename StringType>
1106class StartsWithMatcher {
1107 public:
shiqiane35fdd92008-12-10 05:08:54 +00001108 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1109 }
1110
jgm38513a82012-11-15 15:50:36 +00001111 // Accepts pointer types, particularly:
1112 // const char*
1113 // char*
1114 // const wchar_t*
1115 // wchar_t*
1116 template <typename CharType>
1117 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001118 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001119 }
1120
jgm38513a82012-11-15 15:50:36 +00001121 // Matches anything that can convert to StringType.
1122 //
1123 // This is a template, not just a plain function with const StringType&,
1124 // because StringPiece has some interfering non-explicit constructors.
1125 template <typename MatcheeStringType>
1126 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001127 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001128 const StringType& s2(s);
1129 return s2.length() >= prefix_.length() &&
1130 s2.substr(0, prefix_.length()) == prefix_;
shiqiane35fdd92008-12-10 05:08:54 +00001131 }
1132
1133 void DescribeTo(::std::ostream* os) const {
1134 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001135 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001136 }
1137
1138 void DescribeNegationTo(::std::ostream* os) const {
1139 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001140 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001141 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001142
shiqiane35fdd92008-12-10 05:08:54 +00001143 private:
1144 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001145
1146 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001147};
1148
1149// Implements the polymorphic EndsWith(substring) matcher, which
1150// can be used as a Matcher<T> as long as T can be converted to a
1151// string.
1152template <typename StringType>
1153class EndsWithMatcher {
1154 public:
shiqiane35fdd92008-12-10 05:08:54 +00001155 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1156
jgm38513a82012-11-15 15:50:36 +00001157 // Accepts pointer types, particularly:
1158 // const char*
1159 // char*
1160 // const wchar_t*
1161 // wchar_t*
1162 template <typename CharType>
1163 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001164 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001165 }
1166
jgm38513a82012-11-15 15:50:36 +00001167 // Matches anything that can convert to StringType.
1168 //
1169 // This is a template, not just a plain function with const StringType&,
1170 // because StringPiece has some interfering non-explicit constructors.
1171 template <typename MatcheeStringType>
1172 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001173 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001174 const StringType& s2(s);
1175 return s2.length() >= suffix_.length() &&
1176 s2.substr(s2.length() - suffix_.length()) == suffix_;
shiqiane35fdd92008-12-10 05:08:54 +00001177 }
1178
1179 void DescribeTo(::std::ostream* os) const {
1180 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001181 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001182 }
1183
1184 void DescribeNegationTo(::std::ostream* os) const {
1185 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001186 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001187 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001188
shiqiane35fdd92008-12-10 05:08:54 +00001189 private:
1190 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001191
1192 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001193};
1194
shiqiane35fdd92008-12-10 05:08:54 +00001195// Implements polymorphic matchers MatchesRegex(regex) and
1196// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1197// T can be converted to a string.
1198class MatchesRegexMatcher {
1199 public:
1200 MatchesRegexMatcher(const RE* regex, bool full_match)
1201 : regex_(regex), full_match_(full_match) {}
1202
jgm38513a82012-11-15 15:50:36 +00001203 // Accepts pointer types, particularly:
1204 // const char*
1205 // char*
1206 // const wchar_t*
1207 // wchar_t*
1208 template <typename CharType>
1209 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +00001210 return s != NULL && MatchAndExplain(internal::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001211 }
1212
jgm38513a82012-11-15 15:50:36 +00001213 // Matches anything that can convert to internal::string.
1214 //
1215 // This is a template, not just a plain function with const internal::string&,
1216 // because StringPiece has some interfering non-explicit constructors.
1217 template <class MatcheeStringType>
1218 bool MatchAndExplain(const MatcheeStringType& s,
zhanyong.wandb22c222010-01-28 21:52:29 +00001219 MatchResultListener* /* listener */) const {
jgm38513a82012-11-15 15:50:36 +00001220 const internal::string& s2(s);
1221 return full_match_ ? RE::FullMatch(s2, *regex_) :
1222 RE::PartialMatch(s2, *regex_);
shiqiane35fdd92008-12-10 05:08:54 +00001223 }
1224
1225 void DescribeTo(::std::ostream* os) const {
1226 *os << (full_match_ ? "matches" : "contains")
1227 << " regular expression ";
1228 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1229 }
1230
1231 void DescribeNegationTo(::std::ostream* os) const {
1232 *os << "doesn't " << (full_match_ ? "match" : "contain")
1233 << " regular expression ";
1234 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1235 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001236
shiqiane35fdd92008-12-10 05:08:54 +00001237 private:
1238 const internal::linked_ptr<const RE> regex_;
1239 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001240
1241 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001242};
1243
shiqiane35fdd92008-12-10 05:08:54 +00001244// Implements a matcher that compares the two fields of a 2-tuple
1245// using one of the ==, <=, <, etc, operators. The two fields being
1246// compared don't have to have the same type.
1247//
1248// The matcher defined here is polymorphic (for example, Eq() can be
1249// used to match a tuple<int, short>, a tuple<const long&, double>,
1250// etc). Therefore we use a template type conversion operator in the
1251// implementation.
1252//
1253// We define this as a macro in order to eliminate duplicated source
1254// code.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001255#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +00001256 class name##2Matcher { \
1257 public: \
1258 template <typename T1, typename T2> \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001259 operator Matcher< ::std::tr1::tuple<T1, T2> >() const { \
1260 return MakeMatcher(new Impl< ::std::tr1::tuple<T1, T2> >); \
1261 } \
1262 template <typename T1, typename T2> \
shiqiane35fdd92008-12-10 05:08:54 +00001263 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001264 return MakeMatcher(new Impl<const ::std::tr1::tuple<T1, T2>&>); \
shiqiane35fdd92008-12-10 05:08:54 +00001265 } \
1266 private: \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001267 template <typename Tuple> \
1268 class Impl : public MatcherInterface<Tuple> { \
shiqiane35fdd92008-12-10 05:08:54 +00001269 public: \
zhanyong.wan82113312010-01-08 21:55:40 +00001270 virtual bool MatchAndExplain( \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001271 Tuple args, \
zhanyong.wan82113312010-01-08 21:55:40 +00001272 MatchResultListener* /* listener */) const { \
shiqiane35fdd92008-12-10 05:08:54 +00001273 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
1274 } \
1275 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001276 *os << "are " relation; \
shiqiane35fdd92008-12-10 05:08:54 +00001277 } \
1278 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001279 *os << "aren't " relation; \
shiqiane35fdd92008-12-10 05:08:54 +00001280 } \
1281 }; \
1282 }
1283
1284// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001285GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "an equal pair");
1286GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1287 Ge, >=, "a pair where the first >= the second");
1288GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1289 Gt, >, "a pair where the first > the second");
1290GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1291 Le, <=, "a pair where the first <= the second");
1292GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1293 Lt, <, "a pair where the first < the second");
1294GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=, "an unequal pair");
shiqiane35fdd92008-12-10 05:08:54 +00001295
zhanyong.wane0d051e2009-02-19 00:33:37 +00001296#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +00001297
zhanyong.wanc6a41232009-05-13 23:38:40 +00001298// Implements the Not(...) matcher for a particular argument type T.
1299// We do not nest it inside the NotMatcher class template, as that
1300// will prevent different instantiations of NotMatcher from sharing
1301// the same NotMatcherImpl<T> class.
1302template <typename T>
1303class NotMatcherImpl : public MatcherInterface<T> {
1304 public:
1305 explicit NotMatcherImpl(const Matcher<T>& matcher)
1306 : matcher_(matcher) {}
1307
zhanyong.wan82113312010-01-08 21:55:40 +00001308 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1309 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001310 }
1311
1312 virtual void DescribeTo(::std::ostream* os) const {
1313 matcher_.DescribeNegationTo(os);
1314 }
1315
1316 virtual void DescribeNegationTo(::std::ostream* os) const {
1317 matcher_.DescribeTo(os);
1318 }
1319
zhanyong.wanc6a41232009-05-13 23:38:40 +00001320 private:
1321 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001322
1323 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001324};
1325
shiqiane35fdd92008-12-10 05:08:54 +00001326// Implements the Not(m) matcher, which matches a value that doesn't
1327// match matcher m.
1328template <typename InnerMatcher>
1329class NotMatcher {
1330 public:
1331 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1332
1333 // This template type conversion operator allows Not(m) to be used
1334 // to match any type m can match.
1335 template <typename T>
1336 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001337 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001338 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001339
shiqiane35fdd92008-12-10 05:08:54 +00001340 private:
shiqiane35fdd92008-12-10 05:08:54 +00001341 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001342
1343 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001344};
1345
zhanyong.wanc6a41232009-05-13 23:38:40 +00001346// Implements the AllOf(m1, m2) matcher for a particular argument type
1347// T. We do not nest it inside the BothOfMatcher class template, as
1348// that will prevent different instantiations of BothOfMatcher from
1349// sharing the same BothOfMatcherImpl<T> class.
1350template <typename T>
1351class BothOfMatcherImpl : public MatcherInterface<T> {
1352 public:
1353 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1354 : matcher1_(matcher1), matcher2_(matcher2) {}
1355
zhanyong.wanc6a41232009-05-13 23:38:40 +00001356 virtual void DescribeTo(::std::ostream* os) const {
1357 *os << "(";
1358 matcher1_.DescribeTo(os);
1359 *os << ") and (";
1360 matcher2_.DescribeTo(os);
1361 *os << ")";
1362 }
1363
1364 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001365 *os << "(";
1366 matcher1_.DescribeNegationTo(os);
1367 *os << ") or (";
1368 matcher2_.DescribeNegationTo(os);
1369 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001370 }
1371
zhanyong.wan82113312010-01-08 21:55:40 +00001372 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1373 // If either matcher1_ or matcher2_ doesn't match x, we only need
1374 // to explain why one of them fails.
1375 StringMatchResultListener listener1;
1376 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1377 *listener << listener1.str();
1378 return false;
1379 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001380
zhanyong.wan82113312010-01-08 21:55:40 +00001381 StringMatchResultListener listener2;
1382 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1383 *listener << listener2.str();
1384 return false;
1385 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001386
zhanyong.wan82113312010-01-08 21:55:40 +00001387 // Otherwise we need to explain why *both* of them match.
1388 const internal::string s1 = listener1.str();
1389 const internal::string s2 = listener2.str();
1390
1391 if (s1 == "") {
1392 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001393 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001394 *listener << s1;
1395 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001396 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001397 }
1398 }
zhanyong.wan82113312010-01-08 21:55:40 +00001399 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001400 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001401
zhanyong.wanc6a41232009-05-13 23:38:40 +00001402 private:
1403 const Matcher<T> matcher1_;
1404 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001405
1406 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001407};
1408
shiqiane35fdd92008-12-10 05:08:54 +00001409// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1410// matches a value that matches all of the matchers m_1, ..., and m_n.
1411template <typename Matcher1, typename Matcher2>
1412class BothOfMatcher {
1413 public:
1414 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1415 : matcher1_(matcher1), matcher2_(matcher2) {}
1416
1417 // This template type conversion operator allows a
1418 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1419 // both Matcher1 and Matcher2 can match.
1420 template <typename T>
1421 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001422 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1423 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001424 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001425
shiqiane35fdd92008-12-10 05:08:54 +00001426 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001427 Matcher1 matcher1_;
1428 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001429
1430 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001431};
shiqiane35fdd92008-12-10 05:08:54 +00001432
zhanyong.wanc6a41232009-05-13 23:38:40 +00001433// Implements the AnyOf(m1, m2) matcher for a particular argument type
1434// T. We do not nest it inside the AnyOfMatcher class template, as
1435// that will prevent different instantiations of AnyOfMatcher from
1436// sharing the same EitherOfMatcherImpl<T> class.
1437template <typename T>
1438class EitherOfMatcherImpl : public MatcherInterface<T> {
1439 public:
1440 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1441 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001442
zhanyong.wanc6a41232009-05-13 23:38:40 +00001443 virtual void DescribeTo(::std::ostream* os) const {
1444 *os << "(";
1445 matcher1_.DescribeTo(os);
1446 *os << ") or (";
1447 matcher2_.DescribeTo(os);
1448 *os << ")";
1449 }
shiqiane35fdd92008-12-10 05:08:54 +00001450
zhanyong.wanc6a41232009-05-13 23:38:40 +00001451 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001452 *os << "(";
1453 matcher1_.DescribeNegationTo(os);
1454 *os << ") and (";
1455 matcher2_.DescribeNegationTo(os);
1456 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001457 }
shiqiane35fdd92008-12-10 05:08:54 +00001458
zhanyong.wan82113312010-01-08 21:55:40 +00001459 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1460 // If either matcher1_ or matcher2_ matches x, we just need to
1461 // explain why *one* of them matches.
1462 StringMatchResultListener listener1;
1463 if (matcher1_.MatchAndExplain(x, &listener1)) {
1464 *listener << listener1.str();
1465 return true;
1466 }
1467
1468 StringMatchResultListener listener2;
1469 if (matcher2_.MatchAndExplain(x, &listener2)) {
1470 *listener << listener2.str();
1471 return true;
1472 }
1473
1474 // Otherwise we need to explain why *both* of them fail.
1475 const internal::string s1 = listener1.str();
1476 const internal::string s2 = listener2.str();
1477
1478 if (s1 == "") {
1479 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001480 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001481 *listener << s1;
1482 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001483 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001484 }
1485 }
zhanyong.wan82113312010-01-08 21:55:40 +00001486 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001487 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001488
zhanyong.wanc6a41232009-05-13 23:38:40 +00001489 private:
1490 const Matcher<T> matcher1_;
1491 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001492
1493 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001494};
1495
1496// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1497// matches a value that matches at least one of the matchers m_1, ...,
1498// and m_n.
1499template <typename Matcher1, typename Matcher2>
1500class EitherOfMatcher {
1501 public:
1502 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1503 : matcher1_(matcher1), matcher2_(matcher2) {}
1504
1505 // This template type conversion operator allows a
1506 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1507 // both Matcher1 and Matcher2 can match.
1508 template <typename T>
1509 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001510 return Matcher<T>(new EitherOfMatcherImpl<T>(
1511 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001512 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001513
shiqiane35fdd92008-12-10 05:08:54 +00001514 private:
shiqiane35fdd92008-12-10 05:08:54 +00001515 Matcher1 matcher1_;
1516 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001517
1518 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001519};
1520
1521// Used for implementing Truly(pred), which turns a predicate into a
1522// matcher.
1523template <typename Predicate>
1524class TrulyMatcher {
1525 public:
1526 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1527
1528 // This method template allows Truly(pred) to be used as a matcher
1529 // for type T where T is the argument type of predicate 'pred'. The
1530 // argument is passed by reference as the predicate may be
1531 // interested in the address of the argument.
1532 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001533 bool MatchAndExplain(T& x, // NOLINT
1534 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00001535 // Without the if-statement, MSVC sometimes warns about converting
1536 // a value to bool (warning 4800).
1537 //
1538 // We cannot write 'return !!predicate_(x);' as that doesn't work
1539 // when predicate_(x) returns a class convertible to bool but
1540 // having no operator!().
1541 if (predicate_(x))
1542 return true;
1543 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001544 }
1545
1546 void DescribeTo(::std::ostream* os) const {
1547 *os << "satisfies the given predicate";
1548 }
1549
1550 void DescribeNegationTo(::std::ostream* os) const {
1551 *os << "doesn't satisfy the given predicate";
1552 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001553
shiqiane35fdd92008-12-10 05:08:54 +00001554 private:
1555 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001556
1557 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001558};
1559
1560// Used for implementing Matches(matcher), which turns a matcher into
1561// a predicate.
1562template <typename M>
1563class MatcherAsPredicate {
1564 public:
1565 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1566
1567 // This template operator() allows Matches(m) to be used as a
1568 // predicate on type T where m is a matcher on type T.
1569 //
1570 // The argument x is passed by reference instead of by value, as
1571 // some matcher may be interested in its address (e.g. as in
1572 // Matches(Ref(n))(x)).
1573 template <typename T>
1574 bool operator()(const T& x) const {
1575 // We let matcher_ commit to a particular type here instead of
1576 // when the MatcherAsPredicate object was constructed. This
1577 // allows us to write Matches(m) where m is a polymorphic matcher
1578 // (e.g. Eq(5)).
1579 //
1580 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1581 // compile when matcher_ has type Matcher<const T&>; if we write
1582 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1583 // when matcher_ has type Matcher<T>; if we just write
1584 // matcher_.Matches(x), it won't compile when matcher_ is
1585 // polymorphic, e.g. Eq(5).
1586 //
1587 // MatcherCast<const T&>() is necessary for making the code work
1588 // in all of the above situations.
1589 return MatcherCast<const T&>(matcher_).Matches(x);
1590 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001591
shiqiane35fdd92008-12-10 05:08:54 +00001592 private:
1593 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001594
1595 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001596};
1597
1598// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1599// argument M must be a type that can be converted to a matcher.
1600template <typename M>
1601class PredicateFormatterFromMatcher {
1602 public:
1603 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1604
1605 // This template () operator allows a PredicateFormatterFromMatcher
1606 // object to act as a predicate-formatter suitable for using with
1607 // Google Test's EXPECT_PRED_FORMAT1() macro.
1608 template <typename T>
1609 AssertionResult operator()(const char* value_text, const T& x) const {
1610 // We convert matcher_ to a Matcher<const T&> *now* instead of
1611 // when the PredicateFormatterFromMatcher object was constructed,
1612 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1613 // know which type to instantiate it to until we actually see the
1614 // type of x here.
1615 //
1616 // We write MatcherCast<const T&>(matcher_) instead of
1617 // Matcher<const T&>(matcher_), as the latter won't compile when
1618 // matcher_ has type Matcher<T> (e.g. An<int>()).
1619 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001620 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001621 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001622 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001623
1624 ::std::stringstream ss;
1625 ss << "Value of: " << value_text << "\n"
1626 << "Expected: ";
1627 matcher.DescribeTo(&ss);
1628 ss << "\n Actual: " << listener.str();
1629 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001630 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001631
shiqiane35fdd92008-12-10 05:08:54 +00001632 private:
1633 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001634
1635 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001636};
1637
1638// A helper function for converting a matcher to a predicate-formatter
1639// without the user needing to explicitly write the type. This is
1640// used for implementing ASSERT_THAT() and EXPECT_THAT().
1641template <typename M>
1642inline PredicateFormatterFromMatcher<M>
1643MakePredicateFormatterFromMatcher(const M& matcher) {
1644 return PredicateFormatterFromMatcher<M>(matcher);
1645}
1646
1647// Implements the polymorphic floating point equality matcher, which
1648// matches two float values using ULP-based approximation. The
1649// template is meant to be instantiated with FloatType being either
1650// float or double.
1651template <typename FloatType>
1652class FloatingEqMatcher {
1653 public:
1654 // Constructor for FloatingEqMatcher.
1655 // The matcher's input will be compared with rhs. The matcher treats two
1656 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1657 // equality comparisons between NANs will always return false.
1658 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1659 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1660
1661 // Implements floating point equality matcher as a Matcher<T>.
1662 template <typename T>
1663 class Impl : public MatcherInterface<T> {
1664 public:
1665 Impl(FloatType rhs, bool nan_eq_nan) :
1666 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1667
zhanyong.wan82113312010-01-08 21:55:40 +00001668 virtual bool MatchAndExplain(T value,
1669 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001670 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1671
1672 // Compares NaNs first, if nan_eq_nan_ is true.
1673 if (nan_eq_nan_ && lhs.is_nan()) {
1674 return rhs.is_nan();
1675 }
1676
1677 return lhs.AlmostEquals(rhs);
1678 }
1679
1680 virtual void DescribeTo(::std::ostream* os) const {
1681 // os->precision() returns the previously set precision, which we
1682 // store to restore the ostream to its original configuration
1683 // after outputting.
1684 const ::std::streamsize old_precision = os->precision(
1685 ::std::numeric_limits<FloatType>::digits10 + 2);
1686 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1687 if (nan_eq_nan_) {
1688 *os << "is NaN";
1689 } else {
1690 *os << "never matches";
1691 }
1692 } else {
1693 *os << "is approximately " << rhs_;
1694 }
1695 os->precision(old_precision);
1696 }
1697
1698 virtual void DescribeNegationTo(::std::ostream* os) const {
1699 // As before, get original precision.
1700 const ::std::streamsize old_precision = os->precision(
1701 ::std::numeric_limits<FloatType>::digits10 + 2);
1702 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1703 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001704 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00001705 } else {
1706 *os << "is anything";
1707 }
1708 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001709 *os << "isn't approximately " << rhs_;
shiqiane35fdd92008-12-10 05:08:54 +00001710 }
1711 // Restore original precision.
1712 os->precision(old_precision);
1713 }
1714
1715 private:
1716 const FloatType rhs_;
1717 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001718
1719 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001720 };
1721
1722 // The following 3 type conversion operators allow FloatEq(rhs) and
1723 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1724 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1725 // (While Google's C++ coding style doesn't allow arguments passed
1726 // by non-const reference, we may see them in code not conforming to
1727 // the style. Therefore Google Mock needs to support them.)
1728 operator Matcher<FloatType>() const {
1729 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1730 }
1731
1732 operator Matcher<const FloatType&>() const {
1733 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1734 }
1735
1736 operator Matcher<FloatType&>() const {
1737 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1738 }
jgm79a367e2012-04-10 16:02:11 +00001739
shiqiane35fdd92008-12-10 05:08:54 +00001740 private:
1741 const FloatType rhs_;
1742 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001743
1744 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001745};
1746
1747// Implements the Pointee(m) matcher for matching a pointer whose
1748// pointee matches matcher m. The pointer can be either raw or smart.
1749template <typename InnerMatcher>
1750class PointeeMatcher {
1751 public:
1752 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1753
1754 // This type conversion operator template allows Pointee(m) to be
1755 // used as a matcher for any pointer type whose pointee type is
1756 // compatible with the inner matcher, where type Pointer can be
1757 // either a raw pointer or a smart pointer.
1758 //
1759 // The reason we do this instead of relying on
1760 // MakePolymorphicMatcher() is that the latter is not flexible
1761 // enough for implementing the DescribeTo() method of Pointee().
1762 template <typename Pointer>
1763 operator Matcher<Pointer>() const {
1764 return MakeMatcher(new Impl<Pointer>(matcher_));
1765 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001766
shiqiane35fdd92008-12-10 05:08:54 +00001767 private:
1768 // The monomorphic implementation that works for a particular pointer type.
1769 template <typename Pointer>
1770 class Impl : public MatcherInterface<Pointer> {
1771 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00001772 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
1773 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001774
1775 explicit Impl(const InnerMatcher& matcher)
1776 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1777
shiqiane35fdd92008-12-10 05:08:54 +00001778 virtual void DescribeTo(::std::ostream* os) const {
1779 *os << "points to a value that ";
1780 matcher_.DescribeTo(os);
1781 }
1782
1783 virtual void DescribeNegationTo(::std::ostream* os) const {
1784 *os << "does not point to a value that ";
1785 matcher_.DescribeTo(os);
1786 }
1787
zhanyong.wan82113312010-01-08 21:55:40 +00001788 virtual bool MatchAndExplain(Pointer pointer,
1789 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001790 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00001791 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001792
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001793 *listener << "which points to ";
1794 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001795 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001796
shiqiane35fdd92008-12-10 05:08:54 +00001797 private:
1798 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001799
1800 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001801 };
1802
1803 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001804
1805 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001806};
1807
1808// Implements the Field() matcher for matching a field (i.e. member
1809// variable) of an object.
1810template <typename Class, typename FieldType>
1811class FieldMatcher {
1812 public:
1813 FieldMatcher(FieldType Class::*field,
1814 const Matcher<const FieldType&>& matcher)
1815 : field_(field), matcher_(matcher) {}
1816
shiqiane35fdd92008-12-10 05:08:54 +00001817 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001818 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001819 matcher_.DescribeTo(os);
1820 }
1821
1822 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001823 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001824 matcher_.DescribeNegationTo(os);
1825 }
1826
zhanyong.wandb22c222010-01-28 21:52:29 +00001827 template <typename T>
1828 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
1829 return MatchAndExplainImpl(
1830 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00001831 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00001832 value, listener);
1833 }
1834
1835 private:
1836 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001837 // Symbian's C++ compiler choose which overload to use. Its type is
1838 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001839 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1840 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001841 *listener << "whose given field is ";
1842 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001843 }
1844
zhanyong.wandb22c222010-01-28 21:52:29 +00001845 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1846 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001847 if (p == NULL)
1848 return false;
1849
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001850 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001851 // Since *p has a field, it must be a class/struct/union type and
1852 // thus cannot be a pointer. Therefore we pass false_type() as
1853 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001854 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001855 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001856
shiqiane35fdd92008-12-10 05:08:54 +00001857 const FieldType Class::*field_;
1858 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001859
1860 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001861};
1862
shiqiane35fdd92008-12-10 05:08:54 +00001863// Implements the Property() matcher for matching a property
1864// (i.e. return value of a getter method) of an object.
1865template <typename Class, typename PropertyType>
1866class PropertyMatcher {
1867 public:
1868 // The property may have a reference type, so 'const PropertyType&'
1869 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00001870 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00001871 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00001872 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001873
1874 PropertyMatcher(PropertyType (Class::*property)() const,
1875 const Matcher<RefToConstProperty>& matcher)
1876 : property_(property), matcher_(matcher) {}
1877
shiqiane35fdd92008-12-10 05:08:54 +00001878 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001879 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001880 matcher_.DescribeTo(os);
1881 }
1882
1883 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001884 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001885 matcher_.DescribeNegationTo(os);
1886 }
1887
zhanyong.wandb22c222010-01-28 21:52:29 +00001888 template <typename T>
1889 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
1890 return MatchAndExplainImpl(
1891 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00001892 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00001893 value, listener);
1894 }
1895
1896 private:
1897 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001898 // Symbian's C++ compiler choose which overload to use. Its type is
1899 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001900 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1901 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001902 *listener << "whose given property is ";
1903 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
1904 // which takes a non-const reference as argument.
1905 RefToConstProperty result = (obj.*property_)();
1906 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001907 }
1908
zhanyong.wandb22c222010-01-28 21:52:29 +00001909 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1910 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001911 if (p == NULL)
1912 return false;
1913
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001914 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001915 // Since *p has a property method, it must be a class/struct/union
1916 // type and thus cannot be a pointer. Therefore we pass
1917 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001918 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001919 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001920
shiqiane35fdd92008-12-10 05:08:54 +00001921 PropertyType (Class::*property_)() const;
1922 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001923
1924 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001925};
1926
shiqiane35fdd92008-12-10 05:08:54 +00001927// Type traits specifying various features of different functors for ResultOf.
1928// The default template specifies features for functor objects.
1929// Functor classes have to typedef argument_type and result_type
1930// to be compatible with ResultOf.
1931template <typename Functor>
1932struct CallableTraits {
1933 typedef typename Functor::result_type ResultType;
1934 typedef Functor StorageType;
1935
zhanyong.wan32de5f52009-12-23 00:13:23 +00001936 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00001937 template <typename T>
1938 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1939};
1940
1941// Specialization for function pointers.
1942template <typename ArgType, typename ResType>
1943struct CallableTraits<ResType(*)(ArgType)> {
1944 typedef ResType ResultType;
1945 typedef ResType(*StorageType)(ArgType);
1946
1947 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001948 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00001949 << "NULL function pointer is passed into ResultOf().";
1950 }
1951 template <typename T>
1952 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1953 return (*f)(arg);
1954 }
1955};
1956
1957// Implements the ResultOf() matcher for matching a return value of a
1958// unary function of an object.
1959template <typename Callable>
1960class ResultOfMatcher {
1961 public:
1962 typedef typename CallableTraits<Callable>::ResultType ResultType;
1963
1964 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1965 : callable_(callable), matcher_(matcher) {
1966 CallableTraits<Callable>::CheckIsValid(callable_);
1967 }
1968
1969 template <typename T>
1970 operator Matcher<T>() const {
1971 return Matcher<T>(new Impl<T>(callable_, matcher_));
1972 }
1973
1974 private:
1975 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1976
1977 template <typename T>
1978 class Impl : public MatcherInterface<T> {
1979 public:
1980 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1981 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00001982
1983 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001984 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001985 matcher_.DescribeTo(os);
1986 }
1987
1988 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001989 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001990 matcher_.DescribeNegationTo(os);
1991 }
1992
zhanyong.wan82113312010-01-08 21:55:40 +00001993 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001994 *listener << "which is mapped by the given callable to ";
1995 // Cannot pass the return value (for example, int) to
1996 // MatchPrintAndExplain, which takes a non-const reference as argument.
1997 ResultType result =
1998 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
1999 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002000 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002001
shiqiane35fdd92008-12-10 05:08:54 +00002002 private:
2003 // Functors often define operator() as non-const method even though
2004 // they are actualy stateless. But we need to use them even when
2005 // 'this' is a const pointer. It's the user's responsibility not to
2006 // use stateful callables with ResultOf(), which does't guarantee
2007 // how many times the callable will be invoked.
2008 mutable CallableStorageType callable_;
2009 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002010
2011 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002012 }; // class Impl
2013
2014 const CallableStorageType callable_;
2015 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002016
2017 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002018};
2019
zhanyong.wana31d9ce2013-03-01 01:50:17 +00002020// Implements a matcher that checks the size of an STL-style container.
2021template <typename SizeMatcher>
2022class SizeIsMatcher {
2023 public:
2024 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2025 : size_matcher_(size_matcher) {
2026 }
2027
2028 template <typename Container>
2029 operator Matcher<Container>() const {
2030 return MakeMatcher(new Impl<Container>(size_matcher_));
2031 }
2032
2033 template <typename Container>
2034 class Impl : public MatcherInterface<Container> {
2035 public:
2036 typedef internal::StlContainerView<
2037 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2038 typedef typename ContainerView::type::size_type SizeType;
2039 explicit Impl(const SizeMatcher& size_matcher)
2040 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2041
2042 virtual void DescribeTo(::std::ostream* os) const {
2043 *os << "size ";
2044 size_matcher_.DescribeTo(os);
2045 }
2046 virtual void DescribeNegationTo(::std::ostream* os) const {
2047 *os << "size ";
2048 size_matcher_.DescribeNegationTo(os);
2049 }
2050
2051 virtual bool MatchAndExplain(Container container,
2052 MatchResultListener* listener) const {
2053 SizeType size = container.size();
2054 StringMatchResultListener size_listener;
2055 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2056 *listener
2057 << "whose size " << size << (result ? " matches" : " doesn't match");
2058 PrintIfNotEmpty(size_listener.str(), listener->stream());
2059 return result;
2060 }
2061
2062 private:
2063 const Matcher<SizeType> size_matcher_;
2064 GTEST_DISALLOW_ASSIGN_(Impl);
2065 };
2066
2067 private:
2068 const SizeMatcher size_matcher_;
2069 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2070};
2071
zhanyong.wan6a896b52009-01-16 01:13:50 +00002072// Implements an equality matcher for any STL-style container whose elements
2073// support ==. This matcher is like Eq(), but its failure explanations provide
2074// more detailed information that is useful when the container is used as a set.
2075// The failure message reports elements that are in one of the operands but not
2076// the other. The failure messages do not report duplicate or out-of-order
2077// elements in the containers (which don't properly matter to sets, but can
2078// occur if the containers are vectors or lists, for example).
2079//
2080// Uses the container's const_iterator, value_type, operator ==,
2081// begin(), and end().
2082template <typename Container>
2083class ContainerEqMatcher {
2084 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00002085 typedef internal::StlContainerView<Container> View;
2086 typedef typename View::type StlContainer;
2087 typedef typename View::const_reference StlContainerReference;
2088
2089 // We make a copy of rhs in case the elements in it are modified
2090 // after this matcher is created.
2091 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
2092 // Makes sure the user doesn't instantiate this class template
2093 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002094 (void)testing::StaticAssertTypeEq<Container,
2095 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00002096 }
2097
zhanyong.wan6a896b52009-01-16 01:13:50 +00002098 void DescribeTo(::std::ostream* os) const {
2099 *os << "equals ";
vladloseve2e8ba42010-05-13 18:16:03 +00002100 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002101 }
2102 void DescribeNegationTo(::std::ostream* os) const {
2103 *os << "does not equal ";
vladloseve2e8ba42010-05-13 18:16:03 +00002104 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002105 }
2106
zhanyong.wanb8243162009-06-04 05:48:20 +00002107 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00002108 bool MatchAndExplain(const LhsContainer& lhs,
2109 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002110 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00002111 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002112 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00002113 LhsView;
2114 typedef typename LhsView::type LhsStlContainer;
2115 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00002116 if (lhs_stl_container == rhs_)
2117 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002118
zhanyong.wane122e452010-01-12 09:03:52 +00002119 ::std::ostream* const os = listener->stream();
2120 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002121 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002122 bool printed_header = false;
2123 for (typename LhsStlContainer::const_iterator it =
2124 lhs_stl_container.begin();
2125 it != lhs_stl_container.end(); ++it) {
2126 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
2127 rhs_.end()) {
2128 if (printed_header) {
2129 *os << ", ";
2130 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002131 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002132 printed_header = true;
2133 }
vladloseve2e8ba42010-05-13 18:16:03 +00002134 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002135 }
zhanyong.wane122e452010-01-12 09:03:52 +00002136 }
2137
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002138 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002139 bool printed_header2 = false;
2140 for (typename StlContainer::const_iterator it = rhs_.begin();
2141 it != rhs_.end(); ++it) {
2142 if (internal::ArrayAwareFind(
2143 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2144 lhs_stl_container.end()) {
2145 if (printed_header2) {
2146 *os << ", ";
2147 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002148 *os << (printed_header ? ",\nand" : "which")
2149 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002150 printed_header2 = true;
2151 }
vladloseve2e8ba42010-05-13 18:16:03 +00002152 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002153 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002154 }
2155 }
2156
zhanyong.wane122e452010-01-12 09:03:52 +00002157 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002158 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002159
zhanyong.wan6a896b52009-01-16 01:13:50 +00002160 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00002161 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002162
2163 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002164};
2165
zhanyong.wan898725c2011-09-16 16:45:39 +00002166// A comparator functor that uses the < operator to compare two values.
2167struct LessComparator {
2168 template <typename T, typename U>
2169 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2170};
2171
2172// Implements WhenSortedBy(comparator, container_matcher).
2173template <typename Comparator, typename ContainerMatcher>
2174class WhenSortedByMatcher {
2175 public:
2176 WhenSortedByMatcher(const Comparator& comparator,
2177 const ContainerMatcher& matcher)
2178 : comparator_(comparator), matcher_(matcher) {}
2179
2180 template <typename LhsContainer>
2181 operator Matcher<LhsContainer>() const {
2182 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2183 }
2184
2185 template <typename LhsContainer>
2186 class Impl : public MatcherInterface<LhsContainer> {
2187 public:
2188 typedef internal::StlContainerView<
2189 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2190 typedef typename LhsView::type LhsStlContainer;
2191 typedef typename LhsView::const_reference LhsStlContainerReference;
zhanyong.wana9a59e02013-03-27 16:14:55 +00002192 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2193 // so that we can match associative containers.
2194 typedef typename RemoveConstFromKey<
2195 typename LhsStlContainer::value_type>::type LhsValue;
zhanyong.wan898725c2011-09-16 16:45:39 +00002196
2197 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2198 : comparator_(comparator), matcher_(matcher) {}
2199
2200 virtual void DescribeTo(::std::ostream* os) const {
2201 *os << "(when sorted) ";
2202 matcher_.DescribeTo(os);
2203 }
2204
2205 virtual void DescribeNegationTo(::std::ostream* os) const {
2206 *os << "(when sorted) ";
2207 matcher_.DescribeNegationTo(os);
2208 }
2209
2210 virtual bool MatchAndExplain(LhsContainer lhs,
2211 MatchResultListener* listener) const {
2212 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2213 std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2214 lhs_stl_container.end());
2215 std::sort(sorted_container.begin(), sorted_container.end(), comparator_);
2216
2217 if (!listener->IsInterested()) {
2218 // If the listener is not interested, we do not need to
2219 // construct the inner explanation.
2220 return matcher_.Matches(sorted_container);
2221 }
2222
2223 *listener << "which is ";
2224 UniversalPrint(sorted_container, listener->stream());
2225 *listener << " when sorted";
2226
2227 StringMatchResultListener inner_listener;
2228 const bool match = matcher_.MatchAndExplain(sorted_container,
2229 &inner_listener);
2230 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2231 return match;
2232 }
2233
2234 private:
2235 const Comparator comparator_;
2236 const Matcher<const std::vector<LhsValue>&> matcher_;
2237
2238 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2239 };
2240
2241 private:
2242 const Comparator comparator_;
2243 const ContainerMatcher matcher_;
2244
2245 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2246};
2247
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002248// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2249// must be able to be safely cast to Matcher<tuple<const T1&, const
2250// T2&> >, where T1 and T2 are the types of elements in the LHS
2251// container and the RHS container respectively.
2252template <typename TupleMatcher, typename RhsContainer>
2253class PointwiseMatcher {
2254 public:
2255 typedef internal::StlContainerView<RhsContainer> RhsView;
2256 typedef typename RhsView::type RhsStlContainer;
2257 typedef typename RhsStlContainer::value_type RhsValue;
2258
2259 // Like ContainerEq, we make a copy of rhs in case the elements in
2260 // it are modified after this matcher is created.
2261 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2262 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2263 // Makes sure the user doesn't instantiate this class template
2264 // with a const or reference type.
2265 (void)testing::StaticAssertTypeEq<RhsContainer,
2266 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2267 }
2268
2269 template <typename LhsContainer>
2270 operator Matcher<LhsContainer>() const {
2271 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2272 }
2273
2274 template <typename LhsContainer>
2275 class Impl : public MatcherInterface<LhsContainer> {
2276 public:
2277 typedef internal::StlContainerView<
2278 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2279 typedef typename LhsView::type LhsStlContainer;
2280 typedef typename LhsView::const_reference LhsStlContainerReference;
2281 typedef typename LhsStlContainer::value_type LhsValue;
2282 // We pass the LHS value and the RHS value to the inner matcher by
2283 // reference, as they may be expensive to copy. We must use tuple
2284 // instead of pair here, as a pair cannot hold references (C++ 98,
2285 // 20.2.2 [lib.pairs]).
2286 typedef std::tr1::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
2287
2288 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2289 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2290 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2291 rhs_(rhs) {}
2292
2293 virtual void DescribeTo(::std::ostream* os) const {
2294 *os << "contains " << rhs_.size()
2295 << " values, where each value and its corresponding value in ";
2296 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2297 *os << " ";
2298 mono_tuple_matcher_.DescribeTo(os);
2299 }
2300 virtual void DescribeNegationTo(::std::ostream* os) const {
2301 *os << "doesn't contain exactly " << rhs_.size()
2302 << " values, or contains a value x at some index i"
2303 << " where x and the i-th value of ";
2304 UniversalPrint(rhs_, os);
2305 *os << " ";
2306 mono_tuple_matcher_.DescribeNegationTo(os);
2307 }
2308
2309 virtual bool MatchAndExplain(LhsContainer lhs,
2310 MatchResultListener* listener) const {
2311 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2312 const size_t actual_size = lhs_stl_container.size();
2313 if (actual_size != rhs_.size()) {
2314 *listener << "which contains " << actual_size << " values";
2315 return false;
2316 }
2317
2318 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2319 typename RhsStlContainer::const_iterator right = rhs_.begin();
2320 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2321 const InnerMatcherArg value_pair(*left, *right);
2322
2323 if (listener->IsInterested()) {
2324 StringMatchResultListener inner_listener;
2325 if (!mono_tuple_matcher_.MatchAndExplain(
2326 value_pair, &inner_listener)) {
2327 *listener << "where the value pair (";
2328 UniversalPrint(*left, listener->stream());
2329 *listener << ", ";
2330 UniversalPrint(*right, listener->stream());
2331 *listener << ") at index #" << i << " don't match";
2332 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2333 return false;
2334 }
2335 } else {
2336 if (!mono_tuple_matcher_.Matches(value_pair))
2337 return false;
2338 }
2339 }
2340
2341 return true;
2342 }
2343
2344 private:
2345 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2346 const RhsStlContainer rhs_;
2347
2348 GTEST_DISALLOW_ASSIGN_(Impl);
2349 };
2350
2351 private:
2352 const TupleMatcher tuple_matcher_;
2353 const RhsStlContainer rhs_;
2354
2355 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2356};
2357
zhanyong.wan33605ba2010-04-22 23:37:47 +00002358// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002359template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002360class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002361 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002362 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002363 typedef StlContainerView<RawContainer> View;
2364 typedef typename View::type StlContainer;
2365 typedef typename View::const_reference StlContainerReference;
2366 typedef typename StlContainer::value_type Element;
2367
2368 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002369 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002370 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002371 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002372
zhanyong.wan33605ba2010-04-22 23:37:47 +00002373 // Checks whether:
2374 // * All elements in the container match, if all_elements_should_match.
2375 // * Any element in the container matches, if !all_elements_should_match.
2376 bool MatchAndExplainImpl(bool all_elements_should_match,
2377 Container container,
2378 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002379 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002380 size_t i = 0;
2381 for (typename StlContainer::const_iterator it = stl_container.begin();
2382 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002383 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00002384 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2385
2386 if (matches != all_elements_should_match) {
2387 *listener << "whose element #" << i
2388 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002389 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00002390 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00002391 }
2392 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00002393 return all_elements_should_match;
2394 }
2395
2396 protected:
2397 const Matcher<const Element&> inner_matcher_;
2398
2399 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2400};
2401
2402// Implements Contains(element_matcher) for the given argument type Container.
2403// Symmetric to EachMatcherImpl.
2404template <typename Container>
2405class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2406 public:
2407 template <typename InnerMatcher>
2408 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2409 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2410
2411 // Describes what this matcher does.
2412 virtual void DescribeTo(::std::ostream* os) const {
2413 *os << "contains at least one element that ";
2414 this->inner_matcher_.DescribeTo(os);
2415 }
2416
2417 virtual void DescribeNegationTo(::std::ostream* os) const {
2418 *os << "doesn't contain any element that ";
2419 this->inner_matcher_.DescribeTo(os);
2420 }
2421
2422 virtual bool MatchAndExplain(Container container,
2423 MatchResultListener* listener) const {
2424 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002425 }
2426
2427 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002428 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002429};
2430
zhanyong.wan33605ba2010-04-22 23:37:47 +00002431// Implements Each(element_matcher) for the given argument type Container.
2432// Symmetric to ContainsMatcherImpl.
2433template <typename Container>
2434class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2435 public:
2436 template <typename InnerMatcher>
2437 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2438 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2439
2440 // Describes what this matcher does.
2441 virtual void DescribeTo(::std::ostream* os) const {
2442 *os << "only contains elements that ";
2443 this->inner_matcher_.DescribeTo(os);
2444 }
2445
2446 virtual void DescribeNegationTo(::std::ostream* os) const {
2447 *os << "contains some element that ";
2448 this->inner_matcher_.DescribeNegationTo(os);
2449 }
2450
2451 virtual bool MatchAndExplain(Container container,
2452 MatchResultListener* listener) const {
2453 return this->MatchAndExplainImpl(true, container, listener);
2454 }
2455
2456 private:
2457 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2458};
2459
zhanyong.wanb8243162009-06-04 05:48:20 +00002460// Implements polymorphic Contains(element_matcher).
2461template <typename M>
2462class ContainsMatcher {
2463 public:
2464 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2465
2466 template <typename Container>
2467 operator Matcher<Container>() const {
2468 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2469 }
2470
2471 private:
2472 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002473
2474 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002475};
2476
zhanyong.wan33605ba2010-04-22 23:37:47 +00002477// Implements polymorphic Each(element_matcher).
2478template <typename M>
2479class EachMatcher {
2480 public:
2481 explicit EachMatcher(M m) : inner_matcher_(m) {}
2482
2483 template <typename Container>
2484 operator Matcher<Container>() const {
2485 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2486 }
2487
2488 private:
2489 const M inner_matcher_;
2490
2491 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2492};
2493
zhanyong.wanb5937da2009-07-16 20:26:41 +00002494// Implements Key(inner_matcher) for the given argument pair type.
2495// Key(inner_matcher) matches an std::pair whose 'first' field matches
2496// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2497// std::map that contains at least one element whose key is >= 5.
2498template <typename PairType>
2499class KeyMatcherImpl : public MatcherInterface<PairType> {
2500 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002501 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002502 typedef typename RawPairType::first_type KeyType;
2503
2504 template <typename InnerMatcher>
2505 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2506 : inner_matcher_(
2507 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2508 }
2509
2510 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002511 virtual bool MatchAndExplain(PairType key_value,
2512 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002513 StringMatchResultListener inner_listener;
2514 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2515 &inner_listener);
2516 const internal::string explanation = inner_listener.str();
2517 if (explanation != "") {
2518 *listener << "whose first field is a value " << explanation;
2519 }
2520 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002521 }
2522
2523 // Describes what this matcher does.
2524 virtual void DescribeTo(::std::ostream* os) const {
2525 *os << "has a key that ";
2526 inner_matcher_.DescribeTo(os);
2527 }
2528
2529 // Describes what the negation of this matcher does.
2530 virtual void DescribeNegationTo(::std::ostream* os) const {
2531 *os << "doesn't have a key that ";
2532 inner_matcher_.DescribeTo(os);
2533 }
2534
zhanyong.wanb5937da2009-07-16 20:26:41 +00002535 private:
2536 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002537
2538 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002539};
2540
2541// Implements polymorphic Key(matcher_for_key).
2542template <typename M>
2543class KeyMatcher {
2544 public:
2545 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2546
2547 template <typename PairType>
2548 operator Matcher<PairType>() const {
2549 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2550 }
2551
2552 private:
2553 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002554
2555 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002556};
2557
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002558// Implements Pair(first_matcher, second_matcher) for the given argument pair
2559// type with its two matchers. See Pair() function below.
2560template <typename PairType>
2561class PairMatcherImpl : public MatcherInterface<PairType> {
2562 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002563 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002564 typedef typename RawPairType::first_type FirstType;
2565 typedef typename RawPairType::second_type SecondType;
2566
2567 template <typename FirstMatcher, typename SecondMatcher>
2568 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2569 : first_matcher_(
2570 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2571 second_matcher_(
2572 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2573 }
2574
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002575 // Describes what this matcher does.
2576 virtual void DescribeTo(::std::ostream* os) const {
2577 *os << "has a first field that ";
2578 first_matcher_.DescribeTo(os);
2579 *os << ", and has a second field that ";
2580 second_matcher_.DescribeTo(os);
2581 }
2582
2583 // Describes what the negation of this matcher does.
2584 virtual void DescribeNegationTo(::std::ostream* os) const {
2585 *os << "has a first field that ";
2586 first_matcher_.DescribeNegationTo(os);
2587 *os << ", or has a second field that ";
2588 second_matcher_.DescribeNegationTo(os);
2589 }
2590
zhanyong.wan82113312010-01-08 21:55:40 +00002591 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2592 // matches second_matcher.
2593 virtual bool MatchAndExplain(PairType a_pair,
2594 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002595 if (!listener->IsInterested()) {
2596 // If the listener is not interested, we don't need to construct the
2597 // explanation.
2598 return first_matcher_.Matches(a_pair.first) &&
2599 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00002600 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002601 StringMatchResultListener first_inner_listener;
2602 if (!first_matcher_.MatchAndExplain(a_pair.first,
2603 &first_inner_listener)) {
2604 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002605 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002606 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002607 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002608 StringMatchResultListener second_inner_listener;
2609 if (!second_matcher_.MatchAndExplain(a_pair.second,
2610 &second_inner_listener)) {
2611 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002612 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002613 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002614 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002615 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
2616 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00002617 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002618 }
2619
2620 private:
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002621 void ExplainSuccess(const internal::string& first_explanation,
2622 const internal::string& second_explanation,
2623 MatchResultListener* listener) const {
2624 *listener << "whose both fields match";
2625 if (first_explanation != "") {
2626 *listener << ", where the first field is a value " << first_explanation;
2627 }
2628 if (second_explanation != "") {
2629 *listener << ", ";
2630 if (first_explanation != "") {
2631 *listener << "and ";
2632 } else {
2633 *listener << "where ";
2634 }
2635 *listener << "the second field is a value " << second_explanation;
2636 }
2637 }
2638
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002639 const Matcher<const FirstType&> first_matcher_;
2640 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002641
2642 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002643};
2644
2645// Implements polymorphic Pair(first_matcher, second_matcher).
2646template <typename FirstMatcher, typename SecondMatcher>
2647class PairMatcher {
2648 public:
2649 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2650 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2651
2652 template <typename PairType>
2653 operator Matcher<PairType> () const {
2654 return MakeMatcher(
2655 new PairMatcherImpl<PairType>(
2656 first_matcher_, second_matcher_));
2657 }
2658
2659 private:
2660 const FirstMatcher first_matcher_;
2661 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002662
2663 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002664};
2665
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002666// Implements ElementsAre() and ElementsAreArray().
2667template <typename Container>
2668class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2669 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002670 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002671 typedef internal::StlContainerView<RawContainer> View;
2672 typedef typename View::type StlContainer;
2673 typedef typename View::const_reference StlContainerReference;
2674 typedef typename StlContainer::value_type Element;
2675
2676 // Constructs the matcher from a sequence of element values or
2677 // element matchers.
2678 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00002679 ElementsAreMatcherImpl(InputIter first, InputIter last) {
2680 while (first != last) {
2681 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002682 }
2683 }
2684
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002685 // Describes what this matcher does.
2686 virtual void DescribeTo(::std::ostream* os) const {
2687 if (count() == 0) {
2688 *os << "is empty";
2689 } else if (count() == 1) {
2690 *os << "has 1 element that ";
2691 matchers_[0].DescribeTo(os);
2692 } else {
2693 *os << "has " << Elements(count()) << " where\n";
2694 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002695 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002696 matchers_[i].DescribeTo(os);
2697 if (i + 1 < count()) {
2698 *os << ",\n";
2699 }
2700 }
2701 }
2702 }
2703
2704 // Describes what the negation of this matcher does.
2705 virtual void DescribeNegationTo(::std::ostream* os) const {
2706 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002707 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002708 return;
2709 }
2710
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002711 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002712 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002713 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002714 matchers_[i].DescribeNegationTo(os);
2715 if (i + 1 < count()) {
2716 *os << ", or\n";
2717 }
2718 }
2719 }
2720
zhanyong.wan82113312010-01-08 21:55:40 +00002721 virtual bool MatchAndExplain(Container container,
2722 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002723 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002724 const size_t actual_count = stl_container.size();
2725 if (actual_count != count()) {
2726 // The element count doesn't match. If the container is empty,
2727 // there's no need to explain anything as Google Mock already
2728 // prints the empty container. Otherwise we just need to show
2729 // how many elements there actually are.
2730 if (actual_count != 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002731 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002732 }
zhanyong.wan82113312010-01-08 21:55:40 +00002733 return false;
2734 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002735
zhanyong.wan82113312010-01-08 21:55:40 +00002736 typename StlContainer::const_iterator it = stl_container.begin();
2737 // explanations[i] is the explanation of the element at index i.
2738 std::vector<internal::string> explanations(count());
2739 for (size_t i = 0; i != count(); ++it, ++i) {
2740 StringMatchResultListener s;
2741 if (matchers_[i].MatchAndExplain(*it, &s)) {
2742 explanations[i] = s.str();
2743 } else {
2744 // The container has the right size but the i-th element
2745 // doesn't match its expectation.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002746 *listener << "whose element #" << i << " doesn't match";
2747 PrintIfNotEmpty(s.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002748 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002749 }
2750 }
zhanyong.wan82113312010-01-08 21:55:40 +00002751
2752 // Every element matches its expectation. We need to explain why
2753 // (the obvious ones can be skipped).
zhanyong.wan82113312010-01-08 21:55:40 +00002754 bool reason_printed = false;
2755 for (size_t i = 0; i != count(); ++i) {
2756 const internal::string& s = explanations[i];
2757 if (!s.empty()) {
2758 if (reason_printed) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002759 *listener << ",\nand ";
zhanyong.wan82113312010-01-08 21:55:40 +00002760 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002761 *listener << "whose element #" << i << " matches, " << s;
zhanyong.wan82113312010-01-08 21:55:40 +00002762 reason_printed = true;
2763 }
2764 }
2765
2766 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002767 }
2768
2769 private:
2770 static Message Elements(size_t count) {
2771 return Message() << count << (count == 1 ? " element" : " elements");
2772 }
2773
2774 size_t count() const { return matchers_.size(); }
2775 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002776
2777 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002778};
2779
2780// Implements ElementsAre() of 0 arguments.
2781class ElementsAreMatcher0 {
2782 public:
2783 ElementsAreMatcher0() {}
2784
2785 template <typename Container>
2786 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002787 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002788 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2789 Element;
2790
2791 const Matcher<const Element&>* const matchers = NULL;
jgm38513a82012-11-15 15:50:36 +00002792 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers,
2793 matchers));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002794 }
2795};
2796
2797// Implements ElementsAreArray().
2798template <typename T>
2799class ElementsAreArrayMatcher {
2800 public:
jgm38513a82012-11-15 15:50:36 +00002801 template <typename Iter>
2802 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002803
2804 template <typename Container>
2805 operator Matcher<Container>() const {
jgm38513a82012-11-15 15:50:36 +00002806 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
2807 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002808 }
2809
2810 private:
jgm38513a82012-11-15 15:50:36 +00002811 const std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002812
2813 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002814};
2815
zhanyong.wanb4140802010-06-08 22:53:57 +00002816// Returns the description for a matcher defined using the MATCHER*()
2817// macro where the user-supplied description string is "", if
2818// 'negation' is false; otherwise returns the description of the
2819// negation of the matcher. 'param_values' contains a list of strings
2820// that are the print-out of the matcher's parameters.
vladlosev587c1b32011-05-20 00:42:22 +00002821GTEST_API_ string FormatMatcherDescription(bool negation,
2822 const char* matcher_name,
2823 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002824
shiqiane35fdd92008-12-10 05:08:54 +00002825} // namespace internal
2826
shiqiane35fdd92008-12-10 05:08:54 +00002827// _ is a matcher that matches anything of any type.
2828//
2829// This definition is fine as:
2830//
2831// 1. The C++ standard permits using the name _ in a namespace that
2832// is not the global namespace or ::std.
2833// 2. The AnythingMatcher class has no data member or constructor,
2834// so it's OK to create global variables of this type.
2835// 3. c-style has approved of using _ in this case.
2836const internal::AnythingMatcher _ = {};
2837// Creates a matcher that matches any value of the given type T.
2838template <typename T>
2839inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2840
2841// Creates a matcher that matches any value of the given type T.
2842template <typename T>
2843inline Matcher<T> An() { return A<T>(); }
2844
2845// Creates a polymorphic matcher that matches anything equal to x.
2846// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2847// wouldn't compile.
2848template <typename T>
2849inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2850
2851// Constructs a Matcher<T> from a 'value' of type T. The constructed
2852// matcher matches any value that's equal to 'value'.
2853template <typename T>
2854Matcher<T>::Matcher(T value) { *this = Eq(value); }
2855
2856// Creates a monomorphic matcher that matches anything with type Lhs
2857// and equal to rhs. A user may need to use this instead of Eq(...)
2858// in order to resolve an overloading ambiguity.
2859//
2860// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2861// or Matcher<T>(x), but more readable than the latter.
2862//
2863// We could define similar monomorphic matchers for other comparison
2864// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2865// it yet as those are used much less than Eq() in practice. A user
2866// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2867// for example.
2868template <typename Lhs, typename Rhs>
2869inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2870
2871// Creates a polymorphic matcher that matches anything >= x.
2872template <typename Rhs>
2873inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2874 return internal::GeMatcher<Rhs>(x);
2875}
2876
2877// Creates a polymorphic matcher that matches anything > x.
2878template <typename Rhs>
2879inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2880 return internal::GtMatcher<Rhs>(x);
2881}
2882
2883// Creates a polymorphic matcher that matches anything <= x.
2884template <typename Rhs>
2885inline internal::LeMatcher<Rhs> Le(Rhs x) {
2886 return internal::LeMatcher<Rhs>(x);
2887}
2888
2889// Creates a polymorphic matcher that matches anything < x.
2890template <typename Rhs>
2891inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2892 return internal::LtMatcher<Rhs>(x);
2893}
2894
2895// Creates a polymorphic matcher that matches anything != x.
2896template <typename Rhs>
2897inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2898 return internal::NeMatcher<Rhs>(x);
2899}
2900
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002901// Creates a polymorphic matcher that matches any NULL pointer.
2902inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2903 return MakePolymorphicMatcher(internal::IsNullMatcher());
2904}
2905
shiqiane35fdd92008-12-10 05:08:54 +00002906// Creates a polymorphic matcher that matches any non-NULL pointer.
2907// This is convenient as Not(NULL) doesn't compile (the compiler
2908// thinks that that expression is comparing a pointer with an integer).
2909inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2910 return MakePolymorphicMatcher(internal::NotNullMatcher());
2911}
2912
2913// Creates a polymorphic matcher that matches any argument that
2914// references variable x.
2915template <typename T>
2916inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2917 return internal::RefMatcher<T&>(x);
2918}
2919
2920// Creates a matcher that matches any double argument approximately
2921// equal to rhs, where two NANs are considered unequal.
2922inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2923 return internal::FloatingEqMatcher<double>(rhs, false);
2924}
2925
2926// Creates a matcher that matches any double argument approximately
2927// equal to rhs, including NaN values when rhs is NaN.
2928inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2929 return internal::FloatingEqMatcher<double>(rhs, true);
2930}
2931
2932// Creates a matcher that matches any float argument approximately
2933// equal to rhs, where two NANs are considered unequal.
2934inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2935 return internal::FloatingEqMatcher<float>(rhs, false);
2936}
2937
2938// Creates a matcher that matches any double argument approximately
2939// equal to rhs, including NaN values when rhs is NaN.
2940inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2941 return internal::FloatingEqMatcher<float>(rhs, true);
2942}
2943
2944// Creates a matcher that matches a pointer (raw or smart) that points
2945// to a value that matches inner_matcher.
2946template <typename InnerMatcher>
2947inline internal::PointeeMatcher<InnerMatcher> Pointee(
2948 const InnerMatcher& inner_matcher) {
2949 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2950}
2951
2952// Creates a matcher that matches an object whose given field matches
2953// 'matcher'. For example,
2954// Field(&Foo::number, Ge(5))
2955// matches a Foo object x iff x.number >= 5.
2956template <typename Class, typename FieldType, typename FieldMatcher>
2957inline PolymorphicMatcher<
2958 internal::FieldMatcher<Class, FieldType> > Field(
2959 FieldType Class::*field, const FieldMatcher& matcher) {
2960 return MakePolymorphicMatcher(
2961 internal::FieldMatcher<Class, FieldType>(
2962 field, MatcherCast<const FieldType&>(matcher)));
2963 // The call to MatcherCast() is required for supporting inner
2964 // matchers of compatible types. For example, it allows
2965 // Field(&Foo::bar, m)
2966 // to compile where bar is an int32 and m is a matcher for int64.
2967}
2968
2969// Creates a matcher that matches an object whose given property
2970// matches 'matcher'. For example,
2971// Property(&Foo::str, StartsWith("hi"))
2972// matches a Foo object x iff x.str() starts with "hi".
2973template <typename Class, typename PropertyType, typename PropertyMatcher>
2974inline PolymorphicMatcher<
2975 internal::PropertyMatcher<Class, PropertyType> > Property(
2976 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2977 return MakePolymorphicMatcher(
2978 internal::PropertyMatcher<Class, PropertyType>(
2979 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00002980 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002981 // The call to MatcherCast() is required for supporting inner
2982 // matchers of compatible types. For example, it allows
2983 // Property(&Foo::bar, m)
2984 // to compile where bar() returns an int32 and m is a matcher for int64.
2985}
2986
2987// Creates a matcher that matches an object iff the result of applying
2988// a callable to x matches 'matcher'.
2989// For example,
2990// ResultOf(f, StartsWith("hi"))
2991// matches a Foo object x iff f(x) starts with "hi".
2992// callable parameter can be a function, function pointer, or a functor.
2993// Callable has to satisfy the following conditions:
2994// * It is required to keep no state affecting the results of
2995// the calls on it and make no assumptions about how many calls
2996// will be made. Any state it keeps must be protected from the
2997// concurrent access.
2998// * If it is a function object, it has to define type result_type.
2999// We recommend deriving your functor classes from std::unary_function.
3000template <typename Callable, typename ResultOfMatcher>
3001internal::ResultOfMatcher<Callable> ResultOf(
3002 Callable callable, const ResultOfMatcher& matcher) {
3003 return internal::ResultOfMatcher<Callable>(
3004 callable,
3005 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
3006 matcher));
3007 // The call to MatcherCast() is required for supporting inner
3008 // matchers of compatible types. For example, it allows
3009 // ResultOf(Function, m)
3010 // to compile where Function() returns an int32 and m is a matcher for int64.
3011}
3012
3013// String matchers.
3014
3015// Matches a string equal to str.
3016inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3017 StrEq(const internal::string& str) {
3018 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3019 str, true, true));
3020}
3021
3022// Matches a string not equal to str.
3023inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3024 StrNe(const internal::string& str) {
3025 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3026 str, false, true));
3027}
3028
3029// Matches a string equal to str, ignoring case.
3030inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3031 StrCaseEq(const internal::string& str) {
3032 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3033 str, true, false));
3034}
3035
3036// Matches a string not equal to str, ignoring case.
3037inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3038 StrCaseNe(const internal::string& str) {
3039 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3040 str, false, false));
3041}
3042
3043// Creates a matcher that matches any string, std::string, or C string
3044// that contains the given substring.
3045inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
3046 HasSubstr(const internal::string& substring) {
3047 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
3048 substring));
3049}
3050
3051// Matches a string that starts with 'prefix' (case-sensitive).
3052inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
3053 StartsWith(const internal::string& prefix) {
3054 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
3055 prefix));
3056}
3057
3058// Matches a string that ends with 'suffix' (case-sensitive).
3059inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
3060 EndsWith(const internal::string& suffix) {
3061 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
3062 suffix));
3063}
3064
shiqiane35fdd92008-12-10 05:08:54 +00003065// Matches a string that fully matches regular expression 'regex'.
3066// The matcher takes ownership of 'regex'.
3067inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3068 const internal::RE* regex) {
3069 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
3070}
3071inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3072 const internal::string& regex) {
3073 return MatchesRegex(new internal::RE(regex));
3074}
3075
3076// Matches a string that contains regular expression 'regex'.
3077// The matcher takes ownership of 'regex'.
3078inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
3079 const internal::RE* regex) {
3080 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
3081}
3082inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
3083 const internal::string& regex) {
3084 return ContainsRegex(new internal::RE(regex));
3085}
3086
shiqiane35fdd92008-12-10 05:08:54 +00003087#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3088// Wide string matchers.
3089
3090// Matches a string equal to str.
3091inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3092 StrEq(const internal::wstring& str) {
3093 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3094 str, true, true));
3095}
3096
3097// Matches a string not equal to str.
3098inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3099 StrNe(const internal::wstring& str) {
3100 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3101 str, false, true));
3102}
3103
3104// Matches a string equal to str, ignoring case.
3105inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3106 StrCaseEq(const internal::wstring& str) {
3107 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3108 str, true, false));
3109}
3110
3111// Matches a string not equal to str, ignoring case.
3112inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3113 StrCaseNe(const internal::wstring& str) {
3114 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3115 str, false, false));
3116}
3117
3118// Creates a matcher that matches any wstring, std::wstring, or C wide string
3119// that contains the given substring.
3120inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
3121 HasSubstr(const internal::wstring& substring) {
3122 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
3123 substring));
3124}
3125
3126// Matches a string that starts with 'prefix' (case-sensitive).
3127inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
3128 StartsWith(const internal::wstring& prefix) {
3129 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
3130 prefix));
3131}
3132
3133// Matches a string that ends with 'suffix' (case-sensitive).
3134inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
3135 EndsWith(const internal::wstring& suffix) {
3136 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
3137 suffix));
3138}
3139
3140#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3141
3142// Creates a polymorphic matcher that matches a 2-tuple where the
3143// first field == the second field.
3144inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
3145
3146// Creates a polymorphic matcher that matches a 2-tuple where the
3147// first field >= the second field.
3148inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
3149
3150// Creates a polymorphic matcher that matches a 2-tuple where the
3151// first field > the second field.
3152inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
3153
3154// Creates a polymorphic matcher that matches a 2-tuple where the
3155// first field <= the second field.
3156inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
3157
3158// Creates a polymorphic matcher that matches a 2-tuple where the
3159// first field < the second field.
3160inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
3161
3162// Creates a polymorphic matcher that matches a 2-tuple where the
3163// first field != the second field.
3164inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
3165
3166// Creates a matcher that matches any value of type T that m doesn't
3167// match.
3168template <typename InnerMatcher>
3169inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
3170 return internal::NotMatcher<InnerMatcher>(m);
3171}
3172
shiqiane35fdd92008-12-10 05:08:54 +00003173// Returns a matcher that matches anything that satisfies the given
3174// predicate. The predicate can be any unary function or functor
3175// whose return type can be implicitly converted to bool.
3176template <typename Predicate>
3177inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
3178Truly(Predicate pred) {
3179 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
3180}
3181
zhanyong.wana31d9ce2013-03-01 01:50:17 +00003182// Returns a matcher that matches the container size. The container must
3183// support both size() and size_type which all STL-like containers provide.
3184// Note that the parameter 'size' can be a value of type size_type as well as
3185// matcher. For instance:
3186// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
3187// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
3188template <typename SizeMatcher>
3189inline internal::SizeIsMatcher<SizeMatcher>
3190SizeIs(const SizeMatcher& size_matcher) {
3191 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
3192}
3193
zhanyong.wan6a896b52009-01-16 01:13:50 +00003194// Returns a matcher that matches an equal container.
3195// This matcher behaves like Eq(), but in the event of mismatch lists the
3196// values that are included in one container but not the other. (Duplicate
3197// values and order differences are not explained.)
3198template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00003199inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00003200 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00003201 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00003202 // This following line is for working around a bug in MSVC 8.0,
3203 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00003204 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00003205 return MakePolymorphicMatcher(
3206 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00003207}
3208
zhanyong.wan898725c2011-09-16 16:45:39 +00003209// Returns a matcher that matches a container that, when sorted using
3210// the given comparator, matches container_matcher.
3211template <typename Comparator, typename ContainerMatcher>
3212inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
3213WhenSortedBy(const Comparator& comparator,
3214 const ContainerMatcher& container_matcher) {
3215 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
3216 comparator, container_matcher);
3217}
3218
3219// Returns a matcher that matches a container that, when sorted using
3220// the < operator, matches container_matcher.
3221template <typename ContainerMatcher>
3222inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
3223WhenSorted(const ContainerMatcher& container_matcher) {
3224 return
3225 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
3226 internal::LessComparator(), container_matcher);
3227}
3228
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003229// Matches an STL-style container or a native array that contains the
3230// same number of elements as in rhs, where its i-th element and rhs's
3231// i-th element (as a pair) satisfy the given pair matcher, for all i.
3232// TupleMatcher must be able to be safely cast to Matcher<tuple<const
3233// T1&, const T2&> >, where T1 and T2 are the types of elements in the
3234// LHS container and the RHS container respectively.
3235template <typename TupleMatcher, typename Container>
3236inline internal::PointwiseMatcher<TupleMatcher,
3237 GTEST_REMOVE_CONST_(Container)>
3238Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
3239 // This following line is for working around a bug in MSVC 8.0,
3240 // which causes Container to be a const type sometimes.
3241 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
3242 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
3243 tuple_matcher, rhs);
3244}
3245
zhanyong.wanb8243162009-06-04 05:48:20 +00003246// Matches an STL-style container or a native array that contains at
3247// least one element matching the given value or matcher.
3248//
3249// Examples:
3250// ::std::set<int> page_ids;
3251// page_ids.insert(3);
3252// page_ids.insert(1);
3253// EXPECT_THAT(page_ids, Contains(1));
3254// EXPECT_THAT(page_ids, Contains(Gt(2)));
3255// EXPECT_THAT(page_ids, Not(Contains(4)));
3256//
3257// ::std::map<int, size_t> page_lengths;
3258// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00003259// EXPECT_THAT(page_lengths,
3260// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00003261//
3262// const char* user_ids[] = { "joe", "mike", "tom" };
3263// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
3264template <typename M>
3265inline internal::ContainsMatcher<M> Contains(M matcher) {
3266 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00003267}
3268
zhanyong.wan33605ba2010-04-22 23:37:47 +00003269// Matches an STL-style container or a native array that contains only
3270// elements matching the given value or matcher.
3271//
3272// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
3273// the messages are different.
3274//
3275// Examples:
3276// ::std::set<int> page_ids;
3277// // Each(m) matches an empty container, regardless of what m is.
3278// EXPECT_THAT(page_ids, Each(Eq(1)));
3279// EXPECT_THAT(page_ids, Each(Eq(77)));
3280//
3281// page_ids.insert(3);
3282// EXPECT_THAT(page_ids, Each(Gt(0)));
3283// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
3284// page_ids.insert(1);
3285// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
3286//
3287// ::std::map<int, size_t> page_lengths;
3288// page_lengths[1] = 100;
3289// page_lengths[2] = 200;
3290// page_lengths[3] = 300;
3291// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
3292// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
3293//
3294// const char* user_ids[] = { "joe", "mike", "tom" };
3295// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
3296template <typename M>
3297inline internal::EachMatcher<M> Each(M matcher) {
3298 return internal::EachMatcher<M>(matcher);
3299}
3300
zhanyong.wanb5937da2009-07-16 20:26:41 +00003301// Key(inner_matcher) matches an std::pair whose 'first' field matches
3302// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3303// std::map that contains at least one element whose key is >= 5.
3304template <typename M>
3305inline internal::KeyMatcher<M> Key(M inner_matcher) {
3306 return internal::KeyMatcher<M>(inner_matcher);
3307}
3308
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003309// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
3310// matches first_matcher and whose 'second' field matches second_matcher. For
3311// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
3312// to match a std::map<int, string> that contains exactly one element whose key
3313// is >= 5 and whose value equals "foo".
3314template <typename FirstMatcher, typename SecondMatcher>
3315inline internal::PairMatcher<FirstMatcher, SecondMatcher>
3316Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
3317 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
3318 first_matcher, second_matcher);
3319}
3320
shiqiane35fdd92008-12-10 05:08:54 +00003321// Returns a predicate that is satisfied by anything that matches the
3322// given matcher.
3323template <typename M>
3324inline internal::MatcherAsPredicate<M> Matches(M matcher) {
3325 return internal::MatcherAsPredicate<M>(matcher);
3326}
3327
zhanyong.wanb8243162009-06-04 05:48:20 +00003328// Returns true iff the value matches the matcher.
3329template <typename T, typename M>
3330inline bool Value(const T& value, M matcher) {
3331 return testing::Matches(matcher)(value);
3332}
3333
zhanyong.wan34b034c2010-03-05 21:23:23 +00003334// Matches the value against the given matcher and explains the match
3335// result to listener.
3336template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00003337inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00003338 M matcher, const T& value, MatchResultListener* listener) {
3339 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
3340}
3341
zhanyong.wanbf550852009-06-09 06:09:53 +00003342// AllArgs(m) is a synonym of m. This is useful in
3343//
3344// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
3345//
3346// which is easier to read than
3347//
3348// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
3349template <typename InnerMatcher>
3350inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
3351
shiqiane35fdd92008-12-10 05:08:54 +00003352// These macros allow using matchers to check values in Google Test
3353// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
3354// succeed iff the value matches the matcher. If the assertion fails,
3355// the value and the description of the matcher will be printed.
3356#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
3357 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3358#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
3359 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3360
3361} // namespace testing
3362
3363#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_