blob: ceb73fddbe9718d847a605a7ef1a6649bc748472 [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;
2192 typedef typename LhsStlContainer::value_type LhsValue;
2193
2194 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2195 : comparator_(comparator), matcher_(matcher) {}
2196
2197 virtual void DescribeTo(::std::ostream* os) const {
2198 *os << "(when sorted) ";
2199 matcher_.DescribeTo(os);
2200 }
2201
2202 virtual void DescribeNegationTo(::std::ostream* os) const {
2203 *os << "(when sorted) ";
2204 matcher_.DescribeNegationTo(os);
2205 }
2206
2207 virtual bool MatchAndExplain(LhsContainer lhs,
2208 MatchResultListener* listener) const {
2209 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2210 std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2211 lhs_stl_container.end());
2212 std::sort(sorted_container.begin(), sorted_container.end(), comparator_);
2213
2214 if (!listener->IsInterested()) {
2215 // If the listener is not interested, we do not need to
2216 // construct the inner explanation.
2217 return matcher_.Matches(sorted_container);
2218 }
2219
2220 *listener << "which is ";
2221 UniversalPrint(sorted_container, listener->stream());
2222 *listener << " when sorted";
2223
2224 StringMatchResultListener inner_listener;
2225 const bool match = matcher_.MatchAndExplain(sorted_container,
2226 &inner_listener);
2227 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2228 return match;
2229 }
2230
2231 private:
2232 const Comparator comparator_;
2233 const Matcher<const std::vector<LhsValue>&> matcher_;
2234
2235 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2236 };
2237
2238 private:
2239 const Comparator comparator_;
2240 const ContainerMatcher matcher_;
2241
2242 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2243};
2244
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002245// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2246// must be able to be safely cast to Matcher<tuple<const T1&, const
2247// T2&> >, where T1 and T2 are the types of elements in the LHS
2248// container and the RHS container respectively.
2249template <typename TupleMatcher, typename RhsContainer>
2250class PointwiseMatcher {
2251 public:
2252 typedef internal::StlContainerView<RhsContainer> RhsView;
2253 typedef typename RhsView::type RhsStlContainer;
2254 typedef typename RhsStlContainer::value_type RhsValue;
2255
2256 // Like ContainerEq, we make a copy of rhs in case the elements in
2257 // it are modified after this matcher is created.
2258 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2259 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2260 // Makes sure the user doesn't instantiate this class template
2261 // with a const or reference type.
2262 (void)testing::StaticAssertTypeEq<RhsContainer,
2263 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2264 }
2265
2266 template <typename LhsContainer>
2267 operator Matcher<LhsContainer>() const {
2268 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2269 }
2270
2271 template <typename LhsContainer>
2272 class Impl : public MatcherInterface<LhsContainer> {
2273 public:
2274 typedef internal::StlContainerView<
2275 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2276 typedef typename LhsView::type LhsStlContainer;
2277 typedef typename LhsView::const_reference LhsStlContainerReference;
2278 typedef typename LhsStlContainer::value_type LhsValue;
2279 // We pass the LHS value and the RHS value to the inner matcher by
2280 // reference, as they may be expensive to copy. We must use tuple
2281 // instead of pair here, as a pair cannot hold references (C++ 98,
2282 // 20.2.2 [lib.pairs]).
2283 typedef std::tr1::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
2284
2285 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2286 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2287 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2288 rhs_(rhs) {}
2289
2290 virtual void DescribeTo(::std::ostream* os) const {
2291 *os << "contains " << rhs_.size()
2292 << " values, where each value and its corresponding value in ";
2293 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2294 *os << " ";
2295 mono_tuple_matcher_.DescribeTo(os);
2296 }
2297 virtual void DescribeNegationTo(::std::ostream* os) const {
2298 *os << "doesn't contain exactly " << rhs_.size()
2299 << " values, or contains a value x at some index i"
2300 << " where x and the i-th value of ";
2301 UniversalPrint(rhs_, os);
2302 *os << " ";
2303 mono_tuple_matcher_.DescribeNegationTo(os);
2304 }
2305
2306 virtual bool MatchAndExplain(LhsContainer lhs,
2307 MatchResultListener* listener) const {
2308 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2309 const size_t actual_size = lhs_stl_container.size();
2310 if (actual_size != rhs_.size()) {
2311 *listener << "which contains " << actual_size << " values";
2312 return false;
2313 }
2314
2315 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2316 typename RhsStlContainer::const_iterator right = rhs_.begin();
2317 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2318 const InnerMatcherArg value_pair(*left, *right);
2319
2320 if (listener->IsInterested()) {
2321 StringMatchResultListener inner_listener;
2322 if (!mono_tuple_matcher_.MatchAndExplain(
2323 value_pair, &inner_listener)) {
2324 *listener << "where the value pair (";
2325 UniversalPrint(*left, listener->stream());
2326 *listener << ", ";
2327 UniversalPrint(*right, listener->stream());
2328 *listener << ") at index #" << i << " don't match";
2329 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2330 return false;
2331 }
2332 } else {
2333 if (!mono_tuple_matcher_.Matches(value_pair))
2334 return false;
2335 }
2336 }
2337
2338 return true;
2339 }
2340
2341 private:
2342 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2343 const RhsStlContainer rhs_;
2344
2345 GTEST_DISALLOW_ASSIGN_(Impl);
2346 };
2347
2348 private:
2349 const TupleMatcher tuple_matcher_;
2350 const RhsStlContainer rhs_;
2351
2352 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2353};
2354
zhanyong.wan33605ba2010-04-22 23:37:47 +00002355// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002356template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002357class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002358 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002359 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002360 typedef StlContainerView<RawContainer> View;
2361 typedef typename View::type StlContainer;
2362 typedef typename View::const_reference StlContainerReference;
2363 typedef typename StlContainer::value_type Element;
2364
2365 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002366 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002367 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002368 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002369
zhanyong.wan33605ba2010-04-22 23:37:47 +00002370 // Checks whether:
2371 // * All elements in the container match, if all_elements_should_match.
2372 // * Any element in the container matches, if !all_elements_should_match.
2373 bool MatchAndExplainImpl(bool all_elements_should_match,
2374 Container container,
2375 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002376 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002377 size_t i = 0;
2378 for (typename StlContainer::const_iterator it = stl_container.begin();
2379 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002380 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00002381 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2382
2383 if (matches != all_elements_should_match) {
2384 *listener << "whose element #" << i
2385 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002386 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00002387 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00002388 }
2389 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00002390 return all_elements_should_match;
2391 }
2392
2393 protected:
2394 const Matcher<const Element&> inner_matcher_;
2395
2396 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2397};
2398
2399// Implements Contains(element_matcher) for the given argument type Container.
2400// Symmetric to EachMatcherImpl.
2401template <typename Container>
2402class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2403 public:
2404 template <typename InnerMatcher>
2405 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2406 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2407
2408 // Describes what this matcher does.
2409 virtual void DescribeTo(::std::ostream* os) const {
2410 *os << "contains at least one element that ";
2411 this->inner_matcher_.DescribeTo(os);
2412 }
2413
2414 virtual void DescribeNegationTo(::std::ostream* os) const {
2415 *os << "doesn't contain any element that ";
2416 this->inner_matcher_.DescribeTo(os);
2417 }
2418
2419 virtual bool MatchAndExplain(Container container,
2420 MatchResultListener* listener) const {
2421 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002422 }
2423
2424 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002425 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002426};
2427
zhanyong.wan33605ba2010-04-22 23:37:47 +00002428// Implements Each(element_matcher) for the given argument type Container.
2429// Symmetric to ContainsMatcherImpl.
2430template <typename Container>
2431class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2432 public:
2433 template <typename InnerMatcher>
2434 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2435 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2436
2437 // Describes what this matcher does.
2438 virtual void DescribeTo(::std::ostream* os) const {
2439 *os << "only contains elements that ";
2440 this->inner_matcher_.DescribeTo(os);
2441 }
2442
2443 virtual void DescribeNegationTo(::std::ostream* os) const {
2444 *os << "contains some element that ";
2445 this->inner_matcher_.DescribeNegationTo(os);
2446 }
2447
2448 virtual bool MatchAndExplain(Container container,
2449 MatchResultListener* listener) const {
2450 return this->MatchAndExplainImpl(true, container, listener);
2451 }
2452
2453 private:
2454 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2455};
2456
zhanyong.wanb8243162009-06-04 05:48:20 +00002457// Implements polymorphic Contains(element_matcher).
2458template <typename M>
2459class ContainsMatcher {
2460 public:
2461 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2462
2463 template <typename Container>
2464 operator Matcher<Container>() const {
2465 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2466 }
2467
2468 private:
2469 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002470
2471 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002472};
2473
zhanyong.wan33605ba2010-04-22 23:37:47 +00002474// Implements polymorphic Each(element_matcher).
2475template <typename M>
2476class EachMatcher {
2477 public:
2478 explicit EachMatcher(M m) : inner_matcher_(m) {}
2479
2480 template <typename Container>
2481 operator Matcher<Container>() const {
2482 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2483 }
2484
2485 private:
2486 const M inner_matcher_;
2487
2488 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2489};
2490
zhanyong.wanb5937da2009-07-16 20:26:41 +00002491// Implements Key(inner_matcher) for the given argument pair type.
2492// Key(inner_matcher) matches an std::pair whose 'first' field matches
2493// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2494// std::map that contains at least one element whose key is >= 5.
2495template <typename PairType>
2496class KeyMatcherImpl : public MatcherInterface<PairType> {
2497 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002498 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002499 typedef typename RawPairType::first_type KeyType;
2500
2501 template <typename InnerMatcher>
2502 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2503 : inner_matcher_(
2504 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2505 }
2506
2507 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002508 virtual bool MatchAndExplain(PairType key_value,
2509 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002510 StringMatchResultListener inner_listener;
2511 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2512 &inner_listener);
2513 const internal::string explanation = inner_listener.str();
2514 if (explanation != "") {
2515 *listener << "whose first field is a value " << explanation;
2516 }
2517 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002518 }
2519
2520 // Describes what this matcher does.
2521 virtual void DescribeTo(::std::ostream* os) const {
2522 *os << "has a key that ";
2523 inner_matcher_.DescribeTo(os);
2524 }
2525
2526 // Describes what the negation of this matcher does.
2527 virtual void DescribeNegationTo(::std::ostream* os) const {
2528 *os << "doesn't have a key that ";
2529 inner_matcher_.DescribeTo(os);
2530 }
2531
zhanyong.wanb5937da2009-07-16 20:26:41 +00002532 private:
2533 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002534
2535 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002536};
2537
2538// Implements polymorphic Key(matcher_for_key).
2539template <typename M>
2540class KeyMatcher {
2541 public:
2542 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2543
2544 template <typename PairType>
2545 operator Matcher<PairType>() const {
2546 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2547 }
2548
2549 private:
2550 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002551
2552 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002553};
2554
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002555// Implements Pair(first_matcher, second_matcher) for the given argument pair
2556// type with its two matchers. See Pair() function below.
2557template <typename PairType>
2558class PairMatcherImpl : public MatcherInterface<PairType> {
2559 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002560 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002561 typedef typename RawPairType::first_type FirstType;
2562 typedef typename RawPairType::second_type SecondType;
2563
2564 template <typename FirstMatcher, typename SecondMatcher>
2565 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2566 : first_matcher_(
2567 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2568 second_matcher_(
2569 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2570 }
2571
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002572 // Describes what this matcher does.
2573 virtual void DescribeTo(::std::ostream* os) const {
2574 *os << "has a first field that ";
2575 first_matcher_.DescribeTo(os);
2576 *os << ", and has a second field that ";
2577 second_matcher_.DescribeTo(os);
2578 }
2579
2580 // Describes what the negation of this matcher does.
2581 virtual void DescribeNegationTo(::std::ostream* os) const {
2582 *os << "has a first field that ";
2583 first_matcher_.DescribeNegationTo(os);
2584 *os << ", or has a second field that ";
2585 second_matcher_.DescribeNegationTo(os);
2586 }
2587
zhanyong.wan82113312010-01-08 21:55:40 +00002588 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2589 // matches second_matcher.
2590 virtual bool MatchAndExplain(PairType a_pair,
2591 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002592 if (!listener->IsInterested()) {
2593 // If the listener is not interested, we don't need to construct the
2594 // explanation.
2595 return first_matcher_.Matches(a_pair.first) &&
2596 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00002597 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002598 StringMatchResultListener first_inner_listener;
2599 if (!first_matcher_.MatchAndExplain(a_pair.first,
2600 &first_inner_listener)) {
2601 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002602 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002603 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002604 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002605 StringMatchResultListener second_inner_listener;
2606 if (!second_matcher_.MatchAndExplain(a_pair.second,
2607 &second_inner_listener)) {
2608 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002609 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002610 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002611 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002612 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
2613 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00002614 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002615 }
2616
2617 private:
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002618 void ExplainSuccess(const internal::string& first_explanation,
2619 const internal::string& second_explanation,
2620 MatchResultListener* listener) const {
2621 *listener << "whose both fields match";
2622 if (first_explanation != "") {
2623 *listener << ", where the first field is a value " << first_explanation;
2624 }
2625 if (second_explanation != "") {
2626 *listener << ", ";
2627 if (first_explanation != "") {
2628 *listener << "and ";
2629 } else {
2630 *listener << "where ";
2631 }
2632 *listener << "the second field is a value " << second_explanation;
2633 }
2634 }
2635
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002636 const Matcher<const FirstType&> first_matcher_;
2637 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002638
2639 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002640};
2641
2642// Implements polymorphic Pair(first_matcher, second_matcher).
2643template <typename FirstMatcher, typename SecondMatcher>
2644class PairMatcher {
2645 public:
2646 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2647 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2648
2649 template <typename PairType>
2650 operator Matcher<PairType> () const {
2651 return MakeMatcher(
2652 new PairMatcherImpl<PairType>(
2653 first_matcher_, second_matcher_));
2654 }
2655
2656 private:
2657 const FirstMatcher first_matcher_;
2658 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002659
2660 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002661};
2662
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002663// Implements ElementsAre() and ElementsAreArray().
2664template <typename Container>
2665class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2666 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002667 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002668 typedef internal::StlContainerView<RawContainer> View;
2669 typedef typename View::type StlContainer;
2670 typedef typename View::const_reference StlContainerReference;
2671 typedef typename StlContainer::value_type Element;
2672
2673 // Constructs the matcher from a sequence of element values or
2674 // element matchers.
2675 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00002676 ElementsAreMatcherImpl(InputIter first, InputIter last) {
2677 while (first != last) {
2678 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002679 }
2680 }
2681
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002682 // Describes what this matcher does.
2683 virtual void DescribeTo(::std::ostream* os) const {
2684 if (count() == 0) {
2685 *os << "is empty";
2686 } else if (count() == 1) {
2687 *os << "has 1 element that ";
2688 matchers_[0].DescribeTo(os);
2689 } else {
2690 *os << "has " << Elements(count()) << " where\n";
2691 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002692 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002693 matchers_[i].DescribeTo(os);
2694 if (i + 1 < count()) {
2695 *os << ",\n";
2696 }
2697 }
2698 }
2699 }
2700
2701 // Describes what the negation of this matcher does.
2702 virtual void DescribeNegationTo(::std::ostream* os) const {
2703 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002704 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002705 return;
2706 }
2707
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002708 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002709 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002710 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002711 matchers_[i].DescribeNegationTo(os);
2712 if (i + 1 < count()) {
2713 *os << ", or\n";
2714 }
2715 }
2716 }
2717
zhanyong.wan82113312010-01-08 21:55:40 +00002718 virtual bool MatchAndExplain(Container container,
2719 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002720 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002721 const size_t actual_count = stl_container.size();
2722 if (actual_count != count()) {
2723 // The element count doesn't match. If the container is empty,
2724 // there's no need to explain anything as Google Mock already
2725 // prints the empty container. Otherwise we just need to show
2726 // how many elements there actually are.
2727 if (actual_count != 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002728 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002729 }
zhanyong.wan82113312010-01-08 21:55:40 +00002730 return false;
2731 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002732
zhanyong.wan82113312010-01-08 21:55:40 +00002733 typename StlContainer::const_iterator it = stl_container.begin();
2734 // explanations[i] is the explanation of the element at index i.
2735 std::vector<internal::string> explanations(count());
2736 for (size_t i = 0; i != count(); ++it, ++i) {
2737 StringMatchResultListener s;
2738 if (matchers_[i].MatchAndExplain(*it, &s)) {
2739 explanations[i] = s.str();
2740 } else {
2741 // The container has the right size but the i-th element
2742 // doesn't match its expectation.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002743 *listener << "whose element #" << i << " doesn't match";
2744 PrintIfNotEmpty(s.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002745 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002746 }
2747 }
zhanyong.wan82113312010-01-08 21:55:40 +00002748
2749 // Every element matches its expectation. We need to explain why
2750 // (the obvious ones can be skipped).
zhanyong.wan82113312010-01-08 21:55:40 +00002751 bool reason_printed = false;
2752 for (size_t i = 0; i != count(); ++i) {
2753 const internal::string& s = explanations[i];
2754 if (!s.empty()) {
2755 if (reason_printed) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002756 *listener << ",\nand ";
zhanyong.wan82113312010-01-08 21:55:40 +00002757 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002758 *listener << "whose element #" << i << " matches, " << s;
zhanyong.wan82113312010-01-08 21:55:40 +00002759 reason_printed = true;
2760 }
2761 }
2762
2763 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002764 }
2765
2766 private:
2767 static Message Elements(size_t count) {
2768 return Message() << count << (count == 1 ? " element" : " elements");
2769 }
2770
2771 size_t count() const { return matchers_.size(); }
2772 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002773
2774 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002775};
2776
2777// Implements ElementsAre() of 0 arguments.
2778class ElementsAreMatcher0 {
2779 public:
2780 ElementsAreMatcher0() {}
2781
2782 template <typename Container>
2783 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002784 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002785 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2786 Element;
2787
2788 const Matcher<const Element&>* const matchers = NULL;
jgm38513a82012-11-15 15:50:36 +00002789 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers,
2790 matchers));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002791 }
2792};
2793
2794// Implements ElementsAreArray().
2795template <typename T>
2796class ElementsAreArrayMatcher {
2797 public:
jgm38513a82012-11-15 15:50:36 +00002798 template <typename Iter>
2799 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002800
2801 template <typename Container>
2802 operator Matcher<Container>() const {
jgm38513a82012-11-15 15:50:36 +00002803 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
2804 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002805 }
2806
2807 private:
jgm38513a82012-11-15 15:50:36 +00002808 const std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002809
2810 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002811};
2812
zhanyong.wanb4140802010-06-08 22:53:57 +00002813// Returns the description for a matcher defined using the MATCHER*()
2814// macro where the user-supplied description string is "", if
2815// 'negation' is false; otherwise returns the description of the
2816// negation of the matcher. 'param_values' contains a list of strings
2817// that are the print-out of the matcher's parameters.
vladlosev587c1b32011-05-20 00:42:22 +00002818GTEST_API_ string FormatMatcherDescription(bool negation,
2819 const char* matcher_name,
2820 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002821
shiqiane35fdd92008-12-10 05:08:54 +00002822} // namespace internal
2823
shiqiane35fdd92008-12-10 05:08:54 +00002824// _ is a matcher that matches anything of any type.
2825//
2826// This definition is fine as:
2827//
2828// 1. The C++ standard permits using the name _ in a namespace that
2829// is not the global namespace or ::std.
2830// 2. The AnythingMatcher class has no data member or constructor,
2831// so it's OK to create global variables of this type.
2832// 3. c-style has approved of using _ in this case.
2833const internal::AnythingMatcher _ = {};
2834// Creates a matcher that matches any value of the given type T.
2835template <typename T>
2836inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2837
2838// Creates a matcher that matches any value of the given type T.
2839template <typename T>
2840inline Matcher<T> An() { return A<T>(); }
2841
2842// Creates a polymorphic matcher that matches anything equal to x.
2843// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2844// wouldn't compile.
2845template <typename T>
2846inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2847
2848// Constructs a Matcher<T> from a 'value' of type T. The constructed
2849// matcher matches any value that's equal to 'value'.
2850template <typename T>
2851Matcher<T>::Matcher(T value) { *this = Eq(value); }
2852
2853// Creates a monomorphic matcher that matches anything with type Lhs
2854// and equal to rhs. A user may need to use this instead of Eq(...)
2855// in order to resolve an overloading ambiguity.
2856//
2857// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2858// or Matcher<T>(x), but more readable than the latter.
2859//
2860// We could define similar monomorphic matchers for other comparison
2861// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2862// it yet as those are used much less than Eq() in practice. A user
2863// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2864// for example.
2865template <typename Lhs, typename Rhs>
2866inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2867
2868// Creates a polymorphic matcher that matches anything >= x.
2869template <typename Rhs>
2870inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2871 return internal::GeMatcher<Rhs>(x);
2872}
2873
2874// Creates a polymorphic matcher that matches anything > x.
2875template <typename Rhs>
2876inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2877 return internal::GtMatcher<Rhs>(x);
2878}
2879
2880// Creates a polymorphic matcher that matches anything <= x.
2881template <typename Rhs>
2882inline internal::LeMatcher<Rhs> Le(Rhs x) {
2883 return internal::LeMatcher<Rhs>(x);
2884}
2885
2886// Creates a polymorphic matcher that matches anything < x.
2887template <typename Rhs>
2888inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2889 return internal::LtMatcher<Rhs>(x);
2890}
2891
2892// Creates a polymorphic matcher that matches anything != x.
2893template <typename Rhs>
2894inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2895 return internal::NeMatcher<Rhs>(x);
2896}
2897
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002898// Creates a polymorphic matcher that matches any NULL pointer.
2899inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2900 return MakePolymorphicMatcher(internal::IsNullMatcher());
2901}
2902
shiqiane35fdd92008-12-10 05:08:54 +00002903// Creates a polymorphic matcher that matches any non-NULL pointer.
2904// This is convenient as Not(NULL) doesn't compile (the compiler
2905// thinks that that expression is comparing a pointer with an integer).
2906inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2907 return MakePolymorphicMatcher(internal::NotNullMatcher());
2908}
2909
2910// Creates a polymorphic matcher that matches any argument that
2911// references variable x.
2912template <typename T>
2913inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2914 return internal::RefMatcher<T&>(x);
2915}
2916
2917// Creates a matcher that matches any double argument approximately
2918// equal to rhs, where two NANs are considered unequal.
2919inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2920 return internal::FloatingEqMatcher<double>(rhs, false);
2921}
2922
2923// Creates a matcher that matches any double argument approximately
2924// equal to rhs, including NaN values when rhs is NaN.
2925inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2926 return internal::FloatingEqMatcher<double>(rhs, true);
2927}
2928
2929// Creates a matcher that matches any float argument approximately
2930// equal to rhs, where two NANs are considered unequal.
2931inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2932 return internal::FloatingEqMatcher<float>(rhs, false);
2933}
2934
2935// Creates a matcher that matches any double argument approximately
2936// equal to rhs, including NaN values when rhs is NaN.
2937inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2938 return internal::FloatingEqMatcher<float>(rhs, true);
2939}
2940
2941// Creates a matcher that matches a pointer (raw or smart) that points
2942// to a value that matches inner_matcher.
2943template <typename InnerMatcher>
2944inline internal::PointeeMatcher<InnerMatcher> Pointee(
2945 const InnerMatcher& inner_matcher) {
2946 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2947}
2948
2949// Creates a matcher that matches an object whose given field matches
2950// 'matcher'. For example,
2951// Field(&Foo::number, Ge(5))
2952// matches a Foo object x iff x.number >= 5.
2953template <typename Class, typename FieldType, typename FieldMatcher>
2954inline PolymorphicMatcher<
2955 internal::FieldMatcher<Class, FieldType> > Field(
2956 FieldType Class::*field, const FieldMatcher& matcher) {
2957 return MakePolymorphicMatcher(
2958 internal::FieldMatcher<Class, FieldType>(
2959 field, MatcherCast<const FieldType&>(matcher)));
2960 // The call to MatcherCast() is required for supporting inner
2961 // matchers of compatible types. For example, it allows
2962 // Field(&Foo::bar, m)
2963 // to compile where bar is an int32 and m is a matcher for int64.
2964}
2965
2966// Creates a matcher that matches an object whose given property
2967// matches 'matcher'. For example,
2968// Property(&Foo::str, StartsWith("hi"))
2969// matches a Foo object x iff x.str() starts with "hi".
2970template <typename Class, typename PropertyType, typename PropertyMatcher>
2971inline PolymorphicMatcher<
2972 internal::PropertyMatcher<Class, PropertyType> > Property(
2973 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2974 return MakePolymorphicMatcher(
2975 internal::PropertyMatcher<Class, PropertyType>(
2976 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00002977 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002978 // The call to MatcherCast() is required for supporting inner
2979 // matchers of compatible types. For example, it allows
2980 // Property(&Foo::bar, m)
2981 // to compile where bar() returns an int32 and m is a matcher for int64.
2982}
2983
2984// Creates a matcher that matches an object iff the result of applying
2985// a callable to x matches 'matcher'.
2986// For example,
2987// ResultOf(f, StartsWith("hi"))
2988// matches a Foo object x iff f(x) starts with "hi".
2989// callable parameter can be a function, function pointer, or a functor.
2990// Callable has to satisfy the following conditions:
2991// * It is required to keep no state affecting the results of
2992// the calls on it and make no assumptions about how many calls
2993// will be made. Any state it keeps must be protected from the
2994// concurrent access.
2995// * If it is a function object, it has to define type result_type.
2996// We recommend deriving your functor classes from std::unary_function.
2997template <typename Callable, typename ResultOfMatcher>
2998internal::ResultOfMatcher<Callable> ResultOf(
2999 Callable callable, const ResultOfMatcher& matcher) {
3000 return internal::ResultOfMatcher<Callable>(
3001 callable,
3002 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
3003 matcher));
3004 // The call to MatcherCast() is required for supporting inner
3005 // matchers of compatible types. For example, it allows
3006 // ResultOf(Function, m)
3007 // to compile where Function() returns an int32 and m is a matcher for int64.
3008}
3009
3010// String matchers.
3011
3012// Matches a string equal to str.
3013inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3014 StrEq(const internal::string& str) {
3015 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3016 str, true, true));
3017}
3018
3019// Matches a string not equal to str.
3020inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3021 StrNe(const internal::string& str) {
3022 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3023 str, false, true));
3024}
3025
3026// Matches a string equal to str, ignoring case.
3027inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3028 StrCaseEq(const internal::string& str) {
3029 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3030 str, true, false));
3031}
3032
3033// Matches a string not equal to str, ignoring case.
3034inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3035 StrCaseNe(const internal::string& str) {
3036 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3037 str, false, false));
3038}
3039
3040// Creates a matcher that matches any string, std::string, or C string
3041// that contains the given substring.
3042inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
3043 HasSubstr(const internal::string& substring) {
3044 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
3045 substring));
3046}
3047
3048// Matches a string that starts with 'prefix' (case-sensitive).
3049inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
3050 StartsWith(const internal::string& prefix) {
3051 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
3052 prefix));
3053}
3054
3055// Matches a string that ends with 'suffix' (case-sensitive).
3056inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
3057 EndsWith(const internal::string& suffix) {
3058 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
3059 suffix));
3060}
3061
shiqiane35fdd92008-12-10 05:08:54 +00003062// Matches a string that fully matches regular expression 'regex'.
3063// The matcher takes ownership of 'regex'.
3064inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3065 const internal::RE* regex) {
3066 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
3067}
3068inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3069 const internal::string& regex) {
3070 return MatchesRegex(new internal::RE(regex));
3071}
3072
3073// Matches a string that contains regular expression 'regex'.
3074// The matcher takes ownership of 'regex'.
3075inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
3076 const internal::RE* regex) {
3077 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
3078}
3079inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
3080 const internal::string& regex) {
3081 return ContainsRegex(new internal::RE(regex));
3082}
3083
shiqiane35fdd92008-12-10 05:08:54 +00003084#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3085// Wide string matchers.
3086
3087// Matches a string equal to str.
3088inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3089 StrEq(const internal::wstring& str) {
3090 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3091 str, true, true));
3092}
3093
3094// Matches a string not equal to str.
3095inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3096 StrNe(const internal::wstring& str) {
3097 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3098 str, false, true));
3099}
3100
3101// Matches a string equal to str, ignoring case.
3102inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3103 StrCaseEq(const internal::wstring& str) {
3104 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3105 str, true, false));
3106}
3107
3108// Matches a string not equal to str, ignoring case.
3109inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3110 StrCaseNe(const internal::wstring& str) {
3111 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3112 str, false, false));
3113}
3114
3115// Creates a matcher that matches any wstring, std::wstring, or C wide string
3116// that contains the given substring.
3117inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
3118 HasSubstr(const internal::wstring& substring) {
3119 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
3120 substring));
3121}
3122
3123// Matches a string that starts with 'prefix' (case-sensitive).
3124inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
3125 StartsWith(const internal::wstring& prefix) {
3126 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
3127 prefix));
3128}
3129
3130// Matches a string that ends with 'suffix' (case-sensitive).
3131inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
3132 EndsWith(const internal::wstring& suffix) {
3133 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
3134 suffix));
3135}
3136
3137#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3138
3139// Creates a polymorphic matcher that matches a 2-tuple where the
3140// first field == the second field.
3141inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
3142
3143// Creates a polymorphic matcher that matches a 2-tuple where the
3144// first field >= the second field.
3145inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
3146
3147// Creates a polymorphic matcher that matches a 2-tuple where the
3148// first field > the second field.
3149inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
3150
3151// Creates a polymorphic matcher that matches a 2-tuple where the
3152// first field <= the second field.
3153inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
3154
3155// Creates a polymorphic matcher that matches a 2-tuple where the
3156// first field < the second field.
3157inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
3158
3159// Creates a polymorphic matcher that matches a 2-tuple where the
3160// first field != the second field.
3161inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
3162
3163// Creates a matcher that matches any value of type T that m doesn't
3164// match.
3165template <typename InnerMatcher>
3166inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
3167 return internal::NotMatcher<InnerMatcher>(m);
3168}
3169
shiqiane35fdd92008-12-10 05:08:54 +00003170// Returns a matcher that matches anything that satisfies the given
3171// predicate. The predicate can be any unary function or functor
3172// whose return type can be implicitly converted to bool.
3173template <typename Predicate>
3174inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
3175Truly(Predicate pred) {
3176 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
3177}
3178
zhanyong.wana31d9ce2013-03-01 01:50:17 +00003179// Returns a matcher that matches the container size. The container must
3180// support both size() and size_type which all STL-like containers provide.
3181// Note that the parameter 'size' can be a value of type size_type as well as
3182// matcher. For instance:
3183// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
3184// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
3185template <typename SizeMatcher>
3186inline internal::SizeIsMatcher<SizeMatcher>
3187SizeIs(const SizeMatcher& size_matcher) {
3188 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
3189}
3190
zhanyong.wan6a896b52009-01-16 01:13:50 +00003191// Returns a matcher that matches an equal container.
3192// This matcher behaves like Eq(), but in the event of mismatch lists the
3193// values that are included in one container but not the other. (Duplicate
3194// values and order differences are not explained.)
3195template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00003196inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00003197 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00003198 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00003199 // This following line is for working around a bug in MSVC 8.0,
3200 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00003201 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00003202 return MakePolymorphicMatcher(
3203 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00003204}
3205
zhanyong.wan898725c2011-09-16 16:45:39 +00003206// Returns a matcher that matches a container that, when sorted using
3207// the given comparator, matches container_matcher.
3208template <typename Comparator, typename ContainerMatcher>
3209inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
3210WhenSortedBy(const Comparator& comparator,
3211 const ContainerMatcher& container_matcher) {
3212 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
3213 comparator, container_matcher);
3214}
3215
3216// Returns a matcher that matches a container that, when sorted using
3217// the < operator, matches container_matcher.
3218template <typename ContainerMatcher>
3219inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
3220WhenSorted(const ContainerMatcher& container_matcher) {
3221 return
3222 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
3223 internal::LessComparator(), container_matcher);
3224}
3225
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003226// Matches an STL-style container or a native array that contains the
3227// same number of elements as in rhs, where its i-th element and rhs's
3228// i-th element (as a pair) satisfy the given pair matcher, for all i.
3229// TupleMatcher must be able to be safely cast to Matcher<tuple<const
3230// T1&, const T2&> >, where T1 and T2 are the types of elements in the
3231// LHS container and the RHS container respectively.
3232template <typename TupleMatcher, typename Container>
3233inline internal::PointwiseMatcher<TupleMatcher,
3234 GTEST_REMOVE_CONST_(Container)>
3235Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
3236 // This following line is for working around a bug in MSVC 8.0,
3237 // which causes Container to be a const type sometimes.
3238 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
3239 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
3240 tuple_matcher, rhs);
3241}
3242
zhanyong.wanb8243162009-06-04 05:48:20 +00003243// Matches an STL-style container or a native array that contains at
3244// least one element matching the given value or matcher.
3245//
3246// Examples:
3247// ::std::set<int> page_ids;
3248// page_ids.insert(3);
3249// page_ids.insert(1);
3250// EXPECT_THAT(page_ids, Contains(1));
3251// EXPECT_THAT(page_ids, Contains(Gt(2)));
3252// EXPECT_THAT(page_ids, Not(Contains(4)));
3253//
3254// ::std::map<int, size_t> page_lengths;
3255// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00003256// EXPECT_THAT(page_lengths,
3257// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00003258//
3259// const char* user_ids[] = { "joe", "mike", "tom" };
3260// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
3261template <typename M>
3262inline internal::ContainsMatcher<M> Contains(M matcher) {
3263 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00003264}
3265
zhanyong.wan33605ba2010-04-22 23:37:47 +00003266// Matches an STL-style container or a native array that contains only
3267// elements matching the given value or matcher.
3268//
3269// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
3270// the messages are different.
3271//
3272// Examples:
3273// ::std::set<int> page_ids;
3274// // Each(m) matches an empty container, regardless of what m is.
3275// EXPECT_THAT(page_ids, Each(Eq(1)));
3276// EXPECT_THAT(page_ids, Each(Eq(77)));
3277//
3278// page_ids.insert(3);
3279// EXPECT_THAT(page_ids, Each(Gt(0)));
3280// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
3281// page_ids.insert(1);
3282// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
3283//
3284// ::std::map<int, size_t> page_lengths;
3285// page_lengths[1] = 100;
3286// page_lengths[2] = 200;
3287// page_lengths[3] = 300;
3288// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
3289// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
3290//
3291// const char* user_ids[] = { "joe", "mike", "tom" };
3292// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
3293template <typename M>
3294inline internal::EachMatcher<M> Each(M matcher) {
3295 return internal::EachMatcher<M>(matcher);
3296}
3297
zhanyong.wanb5937da2009-07-16 20:26:41 +00003298// Key(inner_matcher) matches an std::pair whose 'first' field matches
3299// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3300// std::map that contains at least one element whose key is >= 5.
3301template <typename M>
3302inline internal::KeyMatcher<M> Key(M inner_matcher) {
3303 return internal::KeyMatcher<M>(inner_matcher);
3304}
3305
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003306// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
3307// matches first_matcher and whose 'second' field matches second_matcher. For
3308// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
3309// to match a std::map<int, string> that contains exactly one element whose key
3310// is >= 5 and whose value equals "foo".
3311template <typename FirstMatcher, typename SecondMatcher>
3312inline internal::PairMatcher<FirstMatcher, SecondMatcher>
3313Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
3314 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
3315 first_matcher, second_matcher);
3316}
3317
shiqiane35fdd92008-12-10 05:08:54 +00003318// Returns a predicate that is satisfied by anything that matches the
3319// given matcher.
3320template <typename M>
3321inline internal::MatcherAsPredicate<M> Matches(M matcher) {
3322 return internal::MatcherAsPredicate<M>(matcher);
3323}
3324
zhanyong.wanb8243162009-06-04 05:48:20 +00003325// Returns true iff the value matches the matcher.
3326template <typename T, typename M>
3327inline bool Value(const T& value, M matcher) {
3328 return testing::Matches(matcher)(value);
3329}
3330
zhanyong.wan34b034c2010-03-05 21:23:23 +00003331// Matches the value against the given matcher and explains the match
3332// result to listener.
3333template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00003334inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00003335 M matcher, const T& value, MatchResultListener* listener) {
3336 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
3337}
3338
zhanyong.wanbf550852009-06-09 06:09:53 +00003339// AllArgs(m) is a synonym of m. This is useful in
3340//
3341// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
3342//
3343// which is easier to read than
3344//
3345// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
3346template <typename InnerMatcher>
3347inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
3348
shiqiane35fdd92008-12-10 05:08:54 +00003349// These macros allow using matchers to check values in Google Test
3350// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
3351// succeed iff the value matches the matcher. If the assertion fails,
3352// the value and the description of the matcher will be printed.
3353#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
3354 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3355#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
3356 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3357
3358} // namespace testing
3359
3360#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_