blob: d4977273c266617e6cf4a4838c46a844de07d844 [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 //
zhanyong.wanf4274522013-04-24 02:49:43 +00001616 // We write SafeMatcherCast<const T&>(matcher_) instead of
shiqiane35fdd92008-12-10 05:08:54 +00001617 // Matcher<const T&>(matcher_), as the latter won't compile when
1618 // matcher_ has type Matcher<T> (e.g. An<int>()).
zhanyong.wanf4274522013-04-24 02:49:43 +00001619 // We don't write MatcherCast<const T&> either, as that allows
1620 // potentially unsafe downcasting of the matcher argument.
1621 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001622 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001623 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001624 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001625
1626 ::std::stringstream ss;
1627 ss << "Value of: " << value_text << "\n"
1628 << "Expected: ";
1629 matcher.DescribeTo(&ss);
1630 ss << "\n Actual: " << listener.str();
1631 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001632 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001633
shiqiane35fdd92008-12-10 05:08:54 +00001634 private:
1635 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001636
1637 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001638};
1639
1640// A helper function for converting a matcher to a predicate-formatter
1641// without the user needing to explicitly write the type. This is
1642// used for implementing ASSERT_THAT() and EXPECT_THAT().
1643template <typename M>
1644inline PredicateFormatterFromMatcher<M>
1645MakePredicateFormatterFromMatcher(const M& matcher) {
1646 return PredicateFormatterFromMatcher<M>(matcher);
1647}
1648
1649// Implements the polymorphic floating point equality matcher, which
1650// matches two float values using ULP-based approximation. The
1651// template is meant to be instantiated with FloatType being either
1652// float or double.
1653template <typename FloatType>
1654class FloatingEqMatcher {
1655 public:
1656 // Constructor for FloatingEqMatcher.
1657 // The matcher's input will be compared with rhs. The matcher treats two
1658 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1659 // equality comparisons between NANs will always return false.
1660 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1661 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1662
1663 // Implements floating point equality matcher as a Matcher<T>.
1664 template <typename T>
1665 class Impl : public MatcherInterface<T> {
1666 public:
1667 Impl(FloatType rhs, bool nan_eq_nan) :
1668 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1669
zhanyong.wan82113312010-01-08 21:55:40 +00001670 virtual bool MatchAndExplain(T value,
1671 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001672 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1673
1674 // Compares NaNs first, if nan_eq_nan_ is true.
1675 if (nan_eq_nan_ && lhs.is_nan()) {
1676 return rhs.is_nan();
1677 }
1678
1679 return lhs.AlmostEquals(rhs);
1680 }
1681
1682 virtual void DescribeTo(::std::ostream* os) const {
1683 // os->precision() returns the previously set precision, which we
1684 // store to restore the ostream to its original configuration
1685 // after outputting.
1686 const ::std::streamsize old_precision = os->precision(
1687 ::std::numeric_limits<FloatType>::digits10 + 2);
1688 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1689 if (nan_eq_nan_) {
1690 *os << "is NaN";
1691 } else {
1692 *os << "never matches";
1693 }
1694 } else {
1695 *os << "is approximately " << rhs_;
1696 }
1697 os->precision(old_precision);
1698 }
1699
1700 virtual void DescribeNegationTo(::std::ostream* os) const {
1701 // As before, get original precision.
1702 const ::std::streamsize old_precision = os->precision(
1703 ::std::numeric_limits<FloatType>::digits10 + 2);
1704 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1705 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001706 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00001707 } else {
1708 *os << "is anything";
1709 }
1710 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001711 *os << "isn't approximately " << rhs_;
shiqiane35fdd92008-12-10 05:08:54 +00001712 }
1713 // Restore original precision.
1714 os->precision(old_precision);
1715 }
1716
1717 private:
1718 const FloatType rhs_;
1719 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001720
1721 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001722 };
1723
1724 // The following 3 type conversion operators allow FloatEq(rhs) and
1725 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1726 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1727 // (While Google's C++ coding style doesn't allow arguments passed
1728 // by non-const reference, we may see them in code not conforming to
1729 // the style. Therefore Google Mock needs to support them.)
1730 operator Matcher<FloatType>() const {
1731 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1732 }
1733
1734 operator Matcher<const FloatType&>() const {
1735 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1736 }
1737
1738 operator Matcher<FloatType&>() const {
1739 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1740 }
jgm79a367e2012-04-10 16:02:11 +00001741
shiqiane35fdd92008-12-10 05:08:54 +00001742 private:
1743 const FloatType rhs_;
1744 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001745
1746 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001747};
1748
1749// Implements the Pointee(m) matcher for matching a pointer whose
1750// pointee matches matcher m. The pointer can be either raw or smart.
1751template <typename InnerMatcher>
1752class PointeeMatcher {
1753 public:
1754 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1755
1756 // This type conversion operator template allows Pointee(m) to be
1757 // used as a matcher for any pointer type whose pointee type is
1758 // compatible with the inner matcher, where type Pointer can be
1759 // either a raw pointer or a smart pointer.
1760 //
1761 // The reason we do this instead of relying on
1762 // MakePolymorphicMatcher() is that the latter is not flexible
1763 // enough for implementing the DescribeTo() method of Pointee().
1764 template <typename Pointer>
1765 operator Matcher<Pointer>() const {
1766 return MakeMatcher(new Impl<Pointer>(matcher_));
1767 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001768
shiqiane35fdd92008-12-10 05:08:54 +00001769 private:
1770 // The monomorphic implementation that works for a particular pointer type.
1771 template <typename Pointer>
1772 class Impl : public MatcherInterface<Pointer> {
1773 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00001774 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
1775 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001776
1777 explicit Impl(const InnerMatcher& matcher)
1778 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1779
shiqiane35fdd92008-12-10 05:08:54 +00001780 virtual void DescribeTo(::std::ostream* os) const {
1781 *os << "points to a value that ";
1782 matcher_.DescribeTo(os);
1783 }
1784
1785 virtual void DescribeNegationTo(::std::ostream* os) const {
1786 *os << "does not point to a value that ";
1787 matcher_.DescribeTo(os);
1788 }
1789
zhanyong.wan82113312010-01-08 21:55:40 +00001790 virtual bool MatchAndExplain(Pointer pointer,
1791 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001792 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00001793 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001794
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001795 *listener << "which points to ";
1796 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001797 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001798
shiqiane35fdd92008-12-10 05:08:54 +00001799 private:
1800 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001801
1802 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001803 };
1804
1805 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001806
1807 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001808};
1809
1810// Implements the Field() matcher for matching a field (i.e. member
1811// variable) of an object.
1812template <typename Class, typename FieldType>
1813class FieldMatcher {
1814 public:
1815 FieldMatcher(FieldType Class::*field,
1816 const Matcher<const FieldType&>& matcher)
1817 : field_(field), matcher_(matcher) {}
1818
shiqiane35fdd92008-12-10 05:08:54 +00001819 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001820 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001821 matcher_.DescribeTo(os);
1822 }
1823
1824 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001825 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001826 matcher_.DescribeNegationTo(os);
1827 }
1828
zhanyong.wandb22c222010-01-28 21:52:29 +00001829 template <typename T>
1830 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
1831 return MatchAndExplainImpl(
1832 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00001833 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00001834 value, listener);
1835 }
1836
1837 private:
1838 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001839 // Symbian's C++ compiler choose which overload to use. Its type is
1840 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001841 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1842 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001843 *listener << "whose given field is ";
1844 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001845 }
1846
zhanyong.wandb22c222010-01-28 21:52:29 +00001847 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1848 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001849 if (p == NULL)
1850 return false;
1851
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001852 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001853 // Since *p has a field, it must be a class/struct/union type and
1854 // thus cannot be a pointer. Therefore we pass false_type() as
1855 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001856 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001857 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001858
shiqiane35fdd92008-12-10 05:08:54 +00001859 const FieldType Class::*field_;
1860 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001861
1862 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001863};
1864
shiqiane35fdd92008-12-10 05:08:54 +00001865// Implements the Property() matcher for matching a property
1866// (i.e. return value of a getter method) of an object.
1867template <typename Class, typename PropertyType>
1868class PropertyMatcher {
1869 public:
1870 // The property may have a reference type, so 'const PropertyType&'
1871 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00001872 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00001873 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00001874 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001875
1876 PropertyMatcher(PropertyType (Class::*property)() const,
1877 const Matcher<RefToConstProperty>& matcher)
1878 : property_(property), matcher_(matcher) {}
1879
shiqiane35fdd92008-12-10 05:08:54 +00001880 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001881 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001882 matcher_.DescribeTo(os);
1883 }
1884
1885 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001886 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001887 matcher_.DescribeNegationTo(os);
1888 }
1889
zhanyong.wandb22c222010-01-28 21:52:29 +00001890 template <typename T>
1891 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
1892 return MatchAndExplainImpl(
1893 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00001894 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00001895 value, listener);
1896 }
1897
1898 private:
1899 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001900 // Symbian's C++ compiler choose which overload to use. Its type is
1901 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001902 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1903 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001904 *listener << "whose given property is ";
1905 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
1906 // which takes a non-const reference as argument.
1907 RefToConstProperty result = (obj.*property_)();
1908 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001909 }
1910
zhanyong.wandb22c222010-01-28 21:52:29 +00001911 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1912 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001913 if (p == NULL)
1914 return false;
1915
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001916 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001917 // Since *p has a property method, it must be a class/struct/union
1918 // type and thus cannot be a pointer. Therefore we pass
1919 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001920 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001921 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001922
shiqiane35fdd92008-12-10 05:08:54 +00001923 PropertyType (Class::*property_)() const;
1924 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001925
1926 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001927};
1928
shiqiane35fdd92008-12-10 05:08:54 +00001929// Type traits specifying various features of different functors for ResultOf.
1930// The default template specifies features for functor objects.
1931// Functor classes have to typedef argument_type and result_type
1932// to be compatible with ResultOf.
1933template <typename Functor>
1934struct CallableTraits {
1935 typedef typename Functor::result_type ResultType;
1936 typedef Functor StorageType;
1937
zhanyong.wan32de5f52009-12-23 00:13:23 +00001938 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00001939 template <typename T>
1940 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1941};
1942
1943// Specialization for function pointers.
1944template <typename ArgType, typename ResType>
1945struct CallableTraits<ResType(*)(ArgType)> {
1946 typedef ResType ResultType;
1947 typedef ResType(*StorageType)(ArgType);
1948
1949 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001950 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00001951 << "NULL function pointer is passed into ResultOf().";
1952 }
1953 template <typename T>
1954 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1955 return (*f)(arg);
1956 }
1957};
1958
1959// Implements the ResultOf() matcher for matching a return value of a
1960// unary function of an object.
1961template <typename Callable>
1962class ResultOfMatcher {
1963 public:
1964 typedef typename CallableTraits<Callable>::ResultType ResultType;
1965
1966 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1967 : callable_(callable), matcher_(matcher) {
1968 CallableTraits<Callable>::CheckIsValid(callable_);
1969 }
1970
1971 template <typename T>
1972 operator Matcher<T>() const {
1973 return Matcher<T>(new Impl<T>(callable_, matcher_));
1974 }
1975
1976 private:
1977 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1978
1979 template <typename T>
1980 class Impl : public MatcherInterface<T> {
1981 public:
1982 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1983 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00001984
1985 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001986 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001987 matcher_.DescribeTo(os);
1988 }
1989
1990 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001991 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001992 matcher_.DescribeNegationTo(os);
1993 }
1994
zhanyong.wan82113312010-01-08 21:55:40 +00001995 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001996 *listener << "which is mapped by the given callable to ";
1997 // Cannot pass the return value (for example, int) to
1998 // MatchPrintAndExplain, which takes a non-const reference as argument.
1999 ResultType result =
2000 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2001 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00002002 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002003
shiqiane35fdd92008-12-10 05:08:54 +00002004 private:
2005 // Functors often define operator() as non-const method even though
2006 // they are actualy stateless. But we need to use them even when
2007 // 'this' is a const pointer. It's the user's responsibility not to
2008 // use stateful callables with ResultOf(), which does't guarantee
2009 // how many times the callable will be invoked.
2010 mutable CallableStorageType callable_;
2011 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002012
2013 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00002014 }; // class Impl
2015
2016 const CallableStorageType callable_;
2017 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002018
2019 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00002020};
2021
zhanyong.wana31d9ce2013-03-01 01:50:17 +00002022// Implements a matcher that checks the size of an STL-style container.
2023template <typename SizeMatcher>
2024class SizeIsMatcher {
2025 public:
2026 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2027 : size_matcher_(size_matcher) {
2028 }
2029
2030 template <typename Container>
2031 operator Matcher<Container>() const {
2032 return MakeMatcher(new Impl<Container>(size_matcher_));
2033 }
2034
2035 template <typename Container>
2036 class Impl : public MatcherInterface<Container> {
2037 public:
2038 typedef internal::StlContainerView<
2039 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2040 typedef typename ContainerView::type::size_type SizeType;
2041 explicit Impl(const SizeMatcher& size_matcher)
2042 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2043
2044 virtual void DescribeTo(::std::ostream* os) const {
2045 *os << "size ";
2046 size_matcher_.DescribeTo(os);
2047 }
2048 virtual void DescribeNegationTo(::std::ostream* os) const {
2049 *os << "size ";
2050 size_matcher_.DescribeNegationTo(os);
2051 }
2052
2053 virtual bool MatchAndExplain(Container container,
2054 MatchResultListener* listener) const {
2055 SizeType size = container.size();
2056 StringMatchResultListener size_listener;
2057 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2058 *listener
2059 << "whose size " << size << (result ? " matches" : " doesn't match");
2060 PrintIfNotEmpty(size_listener.str(), listener->stream());
2061 return result;
2062 }
2063
2064 private:
2065 const Matcher<SizeType> size_matcher_;
2066 GTEST_DISALLOW_ASSIGN_(Impl);
2067 };
2068
2069 private:
2070 const SizeMatcher size_matcher_;
2071 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2072};
2073
zhanyong.wan6a896b52009-01-16 01:13:50 +00002074// Implements an equality matcher for any STL-style container whose elements
2075// support ==. This matcher is like Eq(), but its failure explanations provide
2076// more detailed information that is useful when the container is used as a set.
2077// The failure message reports elements that are in one of the operands but not
2078// the other. The failure messages do not report duplicate or out-of-order
2079// elements in the containers (which don't properly matter to sets, but can
2080// occur if the containers are vectors or lists, for example).
2081//
2082// Uses the container's const_iterator, value_type, operator ==,
2083// begin(), and end().
2084template <typename Container>
2085class ContainerEqMatcher {
2086 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00002087 typedef internal::StlContainerView<Container> View;
2088 typedef typename View::type StlContainer;
2089 typedef typename View::const_reference StlContainerReference;
2090
2091 // We make a copy of rhs in case the elements in it are modified
2092 // after this matcher is created.
2093 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
2094 // Makes sure the user doesn't instantiate this class template
2095 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002096 (void)testing::StaticAssertTypeEq<Container,
2097 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00002098 }
2099
zhanyong.wan6a896b52009-01-16 01:13:50 +00002100 void DescribeTo(::std::ostream* os) const {
2101 *os << "equals ";
vladloseve2e8ba42010-05-13 18:16:03 +00002102 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002103 }
2104 void DescribeNegationTo(::std::ostream* os) const {
2105 *os << "does not equal ";
vladloseve2e8ba42010-05-13 18:16:03 +00002106 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002107 }
2108
zhanyong.wanb8243162009-06-04 05:48:20 +00002109 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00002110 bool MatchAndExplain(const LhsContainer& lhs,
2111 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002112 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00002113 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002114 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00002115 LhsView;
2116 typedef typename LhsView::type LhsStlContainer;
2117 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00002118 if (lhs_stl_container == rhs_)
2119 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002120
zhanyong.wane122e452010-01-12 09:03:52 +00002121 ::std::ostream* const os = listener->stream();
2122 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002123 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00002124 bool printed_header = false;
2125 for (typename LhsStlContainer::const_iterator it =
2126 lhs_stl_container.begin();
2127 it != lhs_stl_container.end(); ++it) {
2128 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
2129 rhs_.end()) {
2130 if (printed_header) {
2131 *os << ", ";
2132 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002133 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002134 printed_header = true;
2135 }
vladloseve2e8ba42010-05-13 18:16:03 +00002136 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002137 }
zhanyong.wane122e452010-01-12 09:03:52 +00002138 }
2139
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002140 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00002141 bool printed_header2 = false;
2142 for (typename StlContainer::const_iterator it = rhs_.begin();
2143 it != rhs_.end(); ++it) {
2144 if (internal::ArrayAwareFind(
2145 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2146 lhs_stl_container.end()) {
2147 if (printed_header2) {
2148 *os << ", ";
2149 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002150 *os << (printed_header ? ",\nand" : "which")
2151 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00002152 printed_header2 = true;
2153 }
vladloseve2e8ba42010-05-13 18:16:03 +00002154 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00002155 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002156 }
2157 }
2158
zhanyong.wane122e452010-01-12 09:03:52 +00002159 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002160 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002161
zhanyong.wan6a896b52009-01-16 01:13:50 +00002162 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00002163 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002164
2165 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002166};
2167
zhanyong.wan898725c2011-09-16 16:45:39 +00002168// A comparator functor that uses the < operator to compare two values.
2169struct LessComparator {
2170 template <typename T, typename U>
2171 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2172};
2173
2174// Implements WhenSortedBy(comparator, container_matcher).
2175template <typename Comparator, typename ContainerMatcher>
2176class WhenSortedByMatcher {
2177 public:
2178 WhenSortedByMatcher(const Comparator& comparator,
2179 const ContainerMatcher& matcher)
2180 : comparator_(comparator), matcher_(matcher) {}
2181
2182 template <typename LhsContainer>
2183 operator Matcher<LhsContainer>() const {
2184 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2185 }
2186
2187 template <typename LhsContainer>
2188 class Impl : public MatcherInterface<LhsContainer> {
2189 public:
2190 typedef internal::StlContainerView<
2191 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2192 typedef typename LhsView::type LhsStlContainer;
2193 typedef typename LhsView::const_reference LhsStlContainerReference;
zhanyong.wana9a59e02013-03-27 16:14:55 +00002194 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2195 // so that we can match associative containers.
2196 typedef typename RemoveConstFromKey<
2197 typename LhsStlContainer::value_type>::type LhsValue;
zhanyong.wan898725c2011-09-16 16:45:39 +00002198
2199 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2200 : comparator_(comparator), matcher_(matcher) {}
2201
2202 virtual void DescribeTo(::std::ostream* os) const {
2203 *os << "(when sorted) ";
2204 matcher_.DescribeTo(os);
2205 }
2206
2207 virtual void DescribeNegationTo(::std::ostream* os) const {
2208 *os << "(when sorted) ";
2209 matcher_.DescribeNegationTo(os);
2210 }
2211
2212 virtual bool MatchAndExplain(LhsContainer lhs,
2213 MatchResultListener* listener) const {
2214 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2215 std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2216 lhs_stl_container.end());
2217 std::sort(sorted_container.begin(), sorted_container.end(), comparator_);
2218
2219 if (!listener->IsInterested()) {
2220 // If the listener is not interested, we do not need to
2221 // construct the inner explanation.
2222 return matcher_.Matches(sorted_container);
2223 }
2224
2225 *listener << "which is ";
2226 UniversalPrint(sorted_container, listener->stream());
2227 *listener << " when sorted";
2228
2229 StringMatchResultListener inner_listener;
2230 const bool match = matcher_.MatchAndExplain(sorted_container,
2231 &inner_listener);
2232 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2233 return match;
2234 }
2235
2236 private:
2237 const Comparator comparator_;
2238 const Matcher<const std::vector<LhsValue>&> matcher_;
2239
2240 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2241 };
2242
2243 private:
2244 const Comparator comparator_;
2245 const ContainerMatcher matcher_;
2246
2247 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2248};
2249
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002250// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2251// must be able to be safely cast to Matcher<tuple<const T1&, const
2252// T2&> >, where T1 and T2 are the types of elements in the LHS
2253// container and the RHS container respectively.
2254template <typename TupleMatcher, typename RhsContainer>
2255class PointwiseMatcher {
2256 public:
2257 typedef internal::StlContainerView<RhsContainer> RhsView;
2258 typedef typename RhsView::type RhsStlContainer;
2259 typedef typename RhsStlContainer::value_type RhsValue;
2260
2261 // Like ContainerEq, we make a copy of rhs in case the elements in
2262 // it are modified after this matcher is created.
2263 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2264 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2265 // Makes sure the user doesn't instantiate this class template
2266 // with a const or reference type.
2267 (void)testing::StaticAssertTypeEq<RhsContainer,
2268 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2269 }
2270
2271 template <typename LhsContainer>
2272 operator Matcher<LhsContainer>() const {
2273 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2274 }
2275
2276 template <typename LhsContainer>
2277 class Impl : public MatcherInterface<LhsContainer> {
2278 public:
2279 typedef internal::StlContainerView<
2280 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2281 typedef typename LhsView::type LhsStlContainer;
2282 typedef typename LhsView::const_reference LhsStlContainerReference;
2283 typedef typename LhsStlContainer::value_type LhsValue;
2284 // We pass the LHS value and the RHS value to the inner matcher by
2285 // reference, as they may be expensive to copy. We must use tuple
2286 // instead of pair here, as a pair cannot hold references (C++ 98,
2287 // 20.2.2 [lib.pairs]).
2288 typedef std::tr1::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
2289
2290 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2291 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2292 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2293 rhs_(rhs) {}
2294
2295 virtual void DescribeTo(::std::ostream* os) const {
2296 *os << "contains " << rhs_.size()
2297 << " values, where each value and its corresponding value in ";
2298 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2299 *os << " ";
2300 mono_tuple_matcher_.DescribeTo(os);
2301 }
2302 virtual void DescribeNegationTo(::std::ostream* os) const {
2303 *os << "doesn't contain exactly " << rhs_.size()
2304 << " values, or contains a value x at some index i"
2305 << " where x and the i-th value of ";
2306 UniversalPrint(rhs_, os);
2307 *os << " ";
2308 mono_tuple_matcher_.DescribeNegationTo(os);
2309 }
2310
2311 virtual bool MatchAndExplain(LhsContainer lhs,
2312 MatchResultListener* listener) const {
2313 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2314 const size_t actual_size = lhs_stl_container.size();
2315 if (actual_size != rhs_.size()) {
2316 *listener << "which contains " << actual_size << " values";
2317 return false;
2318 }
2319
2320 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2321 typename RhsStlContainer::const_iterator right = rhs_.begin();
2322 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2323 const InnerMatcherArg value_pair(*left, *right);
2324
2325 if (listener->IsInterested()) {
2326 StringMatchResultListener inner_listener;
2327 if (!mono_tuple_matcher_.MatchAndExplain(
2328 value_pair, &inner_listener)) {
2329 *listener << "where the value pair (";
2330 UniversalPrint(*left, listener->stream());
2331 *listener << ", ";
2332 UniversalPrint(*right, listener->stream());
2333 *listener << ") at index #" << i << " don't match";
2334 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2335 return false;
2336 }
2337 } else {
2338 if (!mono_tuple_matcher_.Matches(value_pair))
2339 return false;
2340 }
2341 }
2342
2343 return true;
2344 }
2345
2346 private:
2347 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2348 const RhsStlContainer rhs_;
2349
2350 GTEST_DISALLOW_ASSIGN_(Impl);
2351 };
2352
2353 private:
2354 const TupleMatcher tuple_matcher_;
2355 const RhsStlContainer rhs_;
2356
2357 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2358};
2359
zhanyong.wan33605ba2010-04-22 23:37:47 +00002360// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002361template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002362class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002363 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002364 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002365 typedef StlContainerView<RawContainer> View;
2366 typedef typename View::type StlContainer;
2367 typedef typename View::const_reference StlContainerReference;
2368 typedef typename StlContainer::value_type Element;
2369
2370 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002371 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002372 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002373 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002374
zhanyong.wan33605ba2010-04-22 23:37:47 +00002375 // Checks whether:
2376 // * All elements in the container match, if all_elements_should_match.
2377 // * Any element in the container matches, if !all_elements_should_match.
2378 bool MatchAndExplainImpl(bool all_elements_should_match,
2379 Container container,
2380 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002381 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002382 size_t i = 0;
2383 for (typename StlContainer::const_iterator it = stl_container.begin();
2384 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002385 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00002386 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2387
2388 if (matches != all_elements_should_match) {
2389 *listener << "whose element #" << i
2390 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002391 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00002392 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00002393 }
2394 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00002395 return all_elements_should_match;
2396 }
2397
2398 protected:
2399 const Matcher<const Element&> inner_matcher_;
2400
2401 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2402};
2403
2404// Implements Contains(element_matcher) for the given argument type Container.
2405// Symmetric to EachMatcherImpl.
2406template <typename Container>
2407class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2408 public:
2409 template <typename InnerMatcher>
2410 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2411 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2412
2413 // Describes what this matcher does.
2414 virtual void DescribeTo(::std::ostream* os) const {
2415 *os << "contains at least one element that ";
2416 this->inner_matcher_.DescribeTo(os);
2417 }
2418
2419 virtual void DescribeNegationTo(::std::ostream* os) const {
2420 *os << "doesn't contain any element that ";
2421 this->inner_matcher_.DescribeTo(os);
2422 }
2423
2424 virtual bool MatchAndExplain(Container container,
2425 MatchResultListener* listener) const {
2426 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002427 }
2428
2429 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002430 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002431};
2432
zhanyong.wan33605ba2010-04-22 23:37:47 +00002433// Implements Each(element_matcher) for the given argument type Container.
2434// Symmetric to ContainsMatcherImpl.
2435template <typename Container>
2436class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2437 public:
2438 template <typename InnerMatcher>
2439 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2440 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2441
2442 // Describes what this matcher does.
2443 virtual void DescribeTo(::std::ostream* os) const {
2444 *os << "only contains elements that ";
2445 this->inner_matcher_.DescribeTo(os);
2446 }
2447
2448 virtual void DescribeNegationTo(::std::ostream* os) const {
2449 *os << "contains some element that ";
2450 this->inner_matcher_.DescribeNegationTo(os);
2451 }
2452
2453 virtual bool MatchAndExplain(Container container,
2454 MatchResultListener* listener) const {
2455 return this->MatchAndExplainImpl(true, container, listener);
2456 }
2457
2458 private:
2459 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2460};
2461
zhanyong.wanb8243162009-06-04 05:48:20 +00002462// Implements polymorphic Contains(element_matcher).
2463template <typename M>
2464class ContainsMatcher {
2465 public:
2466 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2467
2468 template <typename Container>
2469 operator Matcher<Container>() const {
2470 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2471 }
2472
2473 private:
2474 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002475
2476 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002477};
2478
zhanyong.wan33605ba2010-04-22 23:37:47 +00002479// Implements polymorphic Each(element_matcher).
2480template <typename M>
2481class EachMatcher {
2482 public:
2483 explicit EachMatcher(M m) : inner_matcher_(m) {}
2484
2485 template <typename Container>
2486 operator Matcher<Container>() const {
2487 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2488 }
2489
2490 private:
2491 const M inner_matcher_;
2492
2493 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2494};
2495
zhanyong.wanb5937da2009-07-16 20:26:41 +00002496// Implements Key(inner_matcher) for the given argument pair type.
2497// Key(inner_matcher) matches an std::pair whose 'first' field matches
2498// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2499// std::map that contains at least one element whose key is >= 5.
2500template <typename PairType>
2501class KeyMatcherImpl : public MatcherInterface<PairType> {
2502 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002503 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002504 typedef typename RawPairType::first_type KeyType;
2505
2506 template <typename InnerMatcher>
2507 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2508 : inner_matcher_(
2509 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2510 }
2511
2512 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002513 virtual bool MatchAndExplain(PairType key_value,
2514 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002515 StringMatchResultListener inner_listener;
2516 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2517 &inner_listener);
2518 const internal::string explanation = inner_listener.str();
2519 if (explanation != "") {
2520 *listener << "whose first field is a value " << explanation;
2521 }
2522 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002523 }
2524
2525 // Describes what this matcher does.
2526 virtual void DescribeTo(::std::ostream* os) const {
2527 *os << "has a key that ";
2528 inner_matcher_.DescribeTo(os);
2529 }
2530
2531 // Describes what the negation of this matcher does.
2532 virtual void DescribeNegationTo(::std::ostream* os) const {
2533 *os << "doesn't have a key that ";
2534 inner_matcher_.DescribeTo(os);
2535 }
2536
zhanyong.wanb5937da2009-07-16 20:26:41 +00002537 private:
2538 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002539
2540 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002541};
2542
2543// Implements polymorphic Key(matcher_for_key).
2544template <typename M>
2545class KeyMatcher {
2546 public:
2547 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2548
2549 template <typename PairType>
2550 operator Matcher<PairType>() const {
2551 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2552 }
2553
2554 private:
2555 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002556
2557 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002558};
2559
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002560// Implements Pair(first_matcher, second_matcher) for the given argument pair
2561// type with its two matchers. See Pair() function below.
2562template <typename PairType>
2563class PairMatcherImpl : public MatcherInterface<PairType> {
2564 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002565 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002566 typedef typename RawPairType::first_type FirstType;
2567 typedef typename RawPairType::second_type SecondType;
2568
2569 template <typename FirstMatcher, typename SecondMatcher>
2570 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2571 : first_matcher_(
2572 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2573 second_matcher_(
2574 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2575 }
2576
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002577 // Describes what this matcher does.
2578 virtual void DescribeTo(::std::ostream* os) const {
2579 *os << "has a first field that ";
2580 first_matcher_.DescribeTo(os);
2581 *os << ", and has a second field that ";
2582 second_matcher_.DescribeTo(os);
2583 }
2584
2585 // Describes what the negation of this matcher does.
2586 virtual void DescribeNegationTo(::std::ostream* os) const {
2587 *os << "has a first field that ";
2588 first_matcher_.DescribeNegationTo(os);
2589 *os << ", or has a second field that ";
2590 second_matcher_.DescribeNegationTo(os);
2591 }
2592
zhanyong.wan82113312010-01-08 21:55:40 +00002593 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2594 // matches second_matcher.
2595 virtual bool MatchAndExplain(PairType a_pair,
2596 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002597 if (!listener->IsInterested()) {
2598 // If the listener is not interested, we don't need to construct the
2599 // explanation.
2600 return first_matcher_.Matches(a_pair.first) &&
2601 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00002602 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002603 StringMatchResultListener first_inner_listener;
2604 if (!first_matcher_.MatchAndExplain(a_pair.first,
2605 &first_inner_listener)) {
2606 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002607 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002608 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002609 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002610 StringMatchResultListener second_inner_listener;
2611 if (!second_matcher_.MatchAndExplain(a_pair.second,
2612 &second_inner_listener)) {
2613 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002614 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002615 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002616 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002617 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
2618 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00002619 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002620 }
2621
2622 private:
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002623 void ExplainSuccess(const internal::string& first_explanation,
2624 const internal::string& second_explanation,
2625 MatchResultListener* listener) const {
2626 *listener << "whose both fields match";
2627 if (first_explanation != "") {
2628 *listener << ", where the first field is a value " << first_explanation;
2629 }
2630 if (second_explanation != "") {
2631 *listener << ", ";
2632 if (first_explanation != "") {
2633 *listener << "and ";
2634 } else {
2635 *listener << "where ";
2636 }
2637 *listener << "the second field is a value " << second_explanation;
2638 }
2639 }
2640
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002641 const Matcher<const FirstType&> first_matcher_;
2642 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002643
2644 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002645};
2646
2647// Implements polymorphic Pair(first_matcher, second_matcher).
2648template <typename FirstMatcher, typename SecondMatcher>
2649class PairMatcher {
2650 public:
2651 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2652 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2653
2654 template <typename PairType>
2655 operator Matcher<PairType> () const {
2656 return MakeMatcher(
2657 new PairMatcherImpl<PairType>(
2658 first_matcher_, second_matcher_));
2659 }
2660
2661 private:
2662 const FirstMatcher first_matcher_;
2663 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002664
2665 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002666};
2667
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002668// Implements ElementsAre() and ElementsAreArray().
2669template <typename Container>
2670class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2671 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002672 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002673 typedef internal::StlContainerView<RawContainer> View;
2674 typedef typename View::type StlContainer;
2675 typedef typename View::const_reference StlContainerReference;
2676 typedef typename StlContainer::value_type Element;
2677
2678 // Constructs the matcher from a sequence of element values or
2679 // element matchers.
2680 template <typename InputIter>
jgm38513a82012-11-15 15:50:36 +00002681 ElementsAreMatcherImpl(InputIter first, InputIter last) {
2682 while (first != last) {
2683 matchers_.push_back(MatcherCast<const Element&>(*first++));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002684 }
2685 }
2686
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002687 // Describes what this matcher does.
2688 virtual void DescribeTo(::std::ostream* os) const {
2689 if (count() == 0) {
2690 *os << "is empty";
2691 } else if (count() == 1) {
2692 *os << "has 1 element that ";
2693 matchers_[0].DescribeTo(os);
2694 } else {
2695 *os << "has " << Elements(count()) << " where\n";
2696 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002697 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002698 matchers_[i].DescribeTo(os);
2699 if (i + 1 < count()) {
2700 *os << ",\n";
2701 }
2702 }
2703 }
2704 }
2705
2706 // Describes what the negation of this matcher does.
2707 virtual void DescribeNegationTo(::std::ostream* os) const {
2708 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002709 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002710 return;
2711 }
2712
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002713 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002714 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002715 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002716 matchers_[i].DescribeNegationTo(os);
2717 if (i + 1 < count()) {
2718 *os << ", or\n";
2719 }
2720 }
2721 }
2722
zhanyong.wan82113312010-01-08 21:55:40 +00002723 virtual bool MatchAndExplain(Container container,
2724 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002725 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002726 const size_t actual_count = stl_container.size();
2727 if (actual_count != count()) {
2728 // The element count doesn't match. If the container is empty,
2729 // there's no need to explain anything as Google Mock already
2730 // prints the empty container. Otherwise we just need to show
2731 // how many elements there actually are.
2732 if (actual_count != 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002733 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002734 }
zhanyong.wan82113312010-01-08 21:55:40 +00002735 return false;
2736 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002737
zhanyong.wan82113312010-01-08 21:55:40 +00002738 typename StlContainer::const_iterator it = stl_container.begin();
2739 // explanations[i] is the explanation of the element at index i.
2740 std::vector<internal::string> explanations(count());
2741 for (size_t i = 0; i != count(); ++it, ++i) {
2742 StringMatchResultListener s;
2743 if (matchers_[i].MatchAndExplain(*it, &s)) {
2744 explanations[i] = s.str();
2745 } else {
2746 // The container has the right size but the i-th element
2747 // doesn't match its expectation.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002748 *listener << "whose element #" << i << " doesn't match";
2749 PrintIfNotEmpty(s.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002750 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002751 }
2752 }
zhanyong.wan82113312010-01-08 21:55:40 +00002753
2754 // Every element matches its expectation. We need to explain why
2755 // (the obvious ones can be skipped).
zhanyong.wan82113312010-01-08 21:55:40 +00002756 bool reason_printed = false;
2757 for (size_t i = 0; i != count(); ++i) {
2758 const internal::string& s = explanations[i];
2759 if (!s.empty()) {
2760 if (reason_printed) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002761 *listener << ",\nand ";
zhanyong.wan82113312010-01-08 21:55:40 +00002762 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002763 *listener << "whose element #" << i << " matches, " << s;
zhanyong.wan82113312010-01-08 21:55:40 +00002764 reason_printed = true;
2765 }
2766 }
2767
2768 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002769 }
2770
2771 private:
2772 static Message Elements(size_t count) {
2773 return Message() << count << (count == 1 ? " element" : " elements");
2774 }
2775
2776 size_t count() const { return matchers_.size(); }
2777 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002778
2779 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002780};
2781
2782// Implements ElementsAre() of 0 arguments.
2783class ElementsAreMatcher0 {
2784 public:
2785 ElementsAreMatcher0() {}
2786
2787 template <typename Container>
2788 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002789 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002790 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2791 Element;
2792
2793 const Matcher<const Element&>* const matchers = NULL;
jgm38513a82012-11-15 15:50:36 +00002794 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers,
2795 matchers));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002796 }
2797};
2798
2799// Implements ElementsAreArray().
2800template <typename T>
2801class ElementsAreArrayMatcher {
2802 public:
jgm38513a82012-11-15 15:50:36 +00002803 template <typename Iter>
2804 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002805
2806 template <typename Container>
2807 operator Matcher<Container>() const {
jgm38513a82012-11-15 15:50:36 +00002808 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
2809 matchers_.begin(), matchers_.end()));
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002810 }
2811
2812 private:
jgm38513a82012-11-15 15:50:36 +00002813 const std::vector<T> matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002814
2815 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002816};
2817
zhanyong.wanb4140802010-06-08 22:53:57 +00002818// Returns the description for a matcher defined using the MATCHER*()
2819// macro where the user-supplied description string is "", if
2820// 'negation' is false; otherwise returns the description of the
2821// negation of the matcher. 'param_values' contains a list of strings
2822// that are the print-out of the matcher's parameters.
vladlosev587c1b32011-05-20 00:42:22 +00002823GTEST_API_ string FormatMatcherDescription(bool negation,
2824 const char* matcher_name,
2825 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002826
shiqiane35fdd92008-12-10 05:08:54 +00002827} // namespace internal
2828
shiqiane35fdd92008-12-10 05:08:54 +00002829// _ is a matcher that matches anything of any type.
2830//
2831// This definition is fine as:
2832//
2833// 1. The C++ standard permits using the name _ in a namespace that
2834// is not the global namespace or ::std.
2835// 2. The AnythingMatcher class has no data member or constructor,
2836// so it's OK to create global variables of this type.
2837// 3. c-style has approved of using _ in this case.
2838const internal::AnythingMatcher _ = {};
2839// Creates a matcher that matches any value of the given type T.
2840template <typename T>
2841inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2842
2843// Creates a matcher that matches any value of the given type T.
2844template <typename T>
2845inline Matcher<T> An() { return A<T>(); }
2846
2847// Creates a polymorphic matcher that matches anything equal to x.
2848// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2849// wouldn't compile.
2850template <typename T>
2851inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2852
2853// Constructs a Matcher<T> from a 'value' of type T. The constructed
2854// matcher matches any value that's equal to 'value'.
2855template <typename T>
2856Matcher<T>::Matcher(T value) { *this = Eq(value); }
2857
2858// Creates a monomorphic matcher that matches anything with type Lhs
2859// and equal to rhs. A user may need to use this instead of Eq(...)
2860// in order to resolve an overloading ambiguity.
2861//
2862// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2863// or Matcher<T>(x), but more readable than the latter.
2864//
2865// We could define similar monomorphic matchers for other comparison
2866// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2867// it yet as those are used much less than Eq() in practice. A user
2868// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2869// for example.
2870template <typename Lhs, typename Rhs>
2871inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2872
2873// Creates a polymorphic matcher that matches anything >= x.
2874template <typename Rhs>
2875inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2876 return internal::GeMatcher<Rhs>(x);
2877}
2878
2879// Creates a polymorphic matcher that matches anything > x.
2880template <typename Rhs>
2881inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2882 return internal::GtMatcher<Rhs>(x);
2883}
2884
2885// Creates a polymorphic matcher that matches anything <= x.
2886template <typename Rhs>
2887inline internal::LeMatcher<Rhs> Le(Rhs x) {
2888 return internal::LeMatcher<Rhs>(x);
2889}
2890
2891// Creates a polymorphic matcher that matches anything < x.
2892template <typename Rhs>
2893inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2894 return internal::LtMatcher<Rhs>(x);
2895}
2896
2897// Creates a polymorphic matcher that matches anything != x.
2898template <typename Rhs>
2899inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2900 return internal::NeMatcher<Rhs>(x);
2901}
2902
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002903// Creates a polymorphic matcher that matches any NULL pointer.
2904inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2905 return MakePolymorphicMatcher(internal::IsNullMatcher());
2906}
2907
shiqiane35fdd92008-12-10 05:08:54 +00002908// Creates a polymorphic matcher that matches any non-NULL pointer.
2909// This is convenient as Not(NULL) doesn't compile (the compiler
2910// thinks that that expression is comparing a pointer with an integer).
2911inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2912 return MakePolymorphicMatcher(internal::NotNullMatcher());
2913}
2914
2915// Creates a polymorphic matcher that matches any argument that
2916// references variable x.
2917template <typename T>
2918inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2919 return internal::RefMatcher<T&>(x);
2920}
2921
2922// Creates a matcher that matches any double argument approximately
2923// equal to rhs, where two NANs are considered unequal.
2924inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2925 return internal::FloatingEqMatcher<double>(rhs, false);
2926}
2927
2928// Creates a matcher that matches any double argument approximately
2929// equal to rhs, including NaN values when rhs is NaN.
2930inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2931 return internal::FloatingEqMatcher<double>(rhs, true);
2932}
2933
2934// Creates a matcher that matches any float argument approximately
2935// equal to rhs, where two NANs are considered unequal.
2936inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2937 return internal::FloatingEqMatcher<float>(rhs, false);
2938}
2939
2940// Creates a matcher that matches any double argument approximately
2941// equal to rhs, including NaN values when rhs is NaN.
2942inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2943 return internal::FloatingEqMatcher<float>(rhs, true);
2944}
2945
2946// Creates a matcher that matches a pointer (raw or smart) that points
2947// to a value that matches inner_matcher.
2948template <typename InnerMatcher>
2949inline internal::PointeeMatcher<InnerMatcher> Pointee(
2950 const InnerMatcher& inner_matcher) {
2951 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2952}
2953
2954// Creates a matcher that matches an object whose given field matches
2955// 'matcher'. For example,
2956// Field(&Foo::number, Ge(5))
2957// matches a Foo object x iff x.number >= 5.
2958template <typename Class, typename FieldType, typename FieldMatcher>
2959inline PolymorphicMatcher<
2960 internal::FieldMatcher<Class, FieldType> > Field(
2961 FieldType Class::*field, const FieldMatcher& matcher) {
2962 return MakePolymorphicMatcher(
2963 internal::FieldMatcher<Class, FieldType>(
2964 field, MatcherCast<const FieldType&>(matcher)));
2965 // The call to MatcherCast() is required for supporting inner
2966 // matchers of compatible types. For example, it allows
2967 // Field(&Foo::bar, m)
2968 // to compile where bar is an int32 and m is a matcher for int64.
2969}
2970
2971// Creates a matcher that matches an object whose given property
2972// matches 'matcher'. For example,
2973// Property(&Foo::str, StartsWith("hi"))
2974// matches a Foo object x iff x.str() starts with "hi".
2975template <typename Class, typename PropertyType, typename PropertyMatcher>
2976inline PolymorphicMatcher<
2977 internal::PropertyMatcher<Class, PropertyType> > Property(
2978 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2979 return MakePolymorphicMatcher(
2980 internal::PropertyMatcher<Class, PropertyType>(
2981 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00002982 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002983 // The call to MatcherCast() is required for supporting inner
2984 // matchers of compatible types. For example, it allows
2985 // Property(&Foo::bar, m)
2986 // to compile where bar() returns an int32 and m is a matcher for int64.
2987}
2988
2989// Creates a matcher that matches an object iff the result of applying
2990// a callable to x matches 'matcher'.
2991// For example,
2992// ResultOf(f, StartsWith("hi"))
2993// matches a Foo object x iff f(x) starts with "hi".
2994// callable parameter can be a function, function pointer, or a functor.
2995// Callable has to satisfy the following conditions:
2996// * It is required to keep no state affecting the results of
2997// the calls on it and make no assumptions about how many calls
2998// will be made. Any state it keeps must be protected from the
2999// concurrent access.
3000// * If it is a function object, it has to define type result_type.
3001// We recommend deriving your functor classes from std::unary_function.
3002template <typename Callable, typename ResultOfMatcher>
3003internal::ResultOfMatcher<Callable> ResultOf(
3004 Callable callable, const ResultOfMatcher& matcher) {
3005 return internal::ResultOfMatcher<Callable>(
3006 callable,
3007 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
3008 matcher));
3009 // The call to MatcherCast() is required for supporting inner
3010 // matchers of compatible types. For example, it allows
3011 // ResultOf(Function, m)
3012 // to compile where Function() returns an int32 and m is a matcher for int64.
3013}
3014
3015// String matchers.
3016
3017// Matches a string equal to str.
3018inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3019 StrEq(const internal::string& str) {
3020 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3021 str, true, true));
3022}
3023
3024// Matches a string not equal to str.
3025inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3026 StrNe(const internal::string& str) {
3027 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3028 str, false, true));
3029}
3030
3031// Matches a string equal to str, ignoring case.
3032inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3033 StrCaseEq(const internal::string& str) {
3034 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3035 str, true, false));
3036}
3037
3038// Matches a string not equal to str, ignoring case.
3039inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3040 StrCaseNe(const internal::string& str) {
3041 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3042 str, false, false));
3043}
3044
3045// Creates a matcher that matches any string, std::string, or C string
3046// that contains the given substring.
3047inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
3048 HasSubstr(const internal::string& substring) {
3049 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
3050 substring));
3051}
3052
3053// Matches a string that starts with 'prefix' (case-sensitive).
3054inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
3055 StartsWith(const internal::string& prefix) {
3056 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
3057 prefix));
3058}
3059
3060// Matches a string that ends with 'suffix' (case-sensitive).
3061inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
3062 EndsWith(const internal::string& suffix) {
3063 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
3064 suffix));
3065}
3066
shiqiane35fdd92008-12-10 05:08:54 +00003067// Matches a string that fully matches regular expression 'regex'.
3068// The matcher takes ownership of 'regex'.
3069inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3070 const internal::RE* regex) {
3071 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
3072}
3073inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
3074 const internal::string& regex) {
3075 return MatchesRegex(new internal::RE(regex));
3076}
3077
3078// Matches a string that contains regular expression 'regex'.
3079// The matcher takes ownership of 'regex'.
3080inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
3081 const internal::RE* regex) {
3082 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
3083}
3084inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
3085 const internal::string& regex) {
3086 return ContainsRegex(new internal::RE(regex));
3087}
3088
shiqiane35fdd92008-12-10 05:08:54 +00003089#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3090// Wide string matchers.
3091
3092// Matches a string equal to str.
3093inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3094 StrEq(const internal::wstring& str) {
3095 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3096 str, true, true));
3097}
3098
3099// Matches a string not equal to str.
3100inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3101 StrNe(const internal::wstring& str) {
3102 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3103 str, false, true));
3104}
3105
3106// Matches a string equal to str, ignoring case.
3107inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3108 StrCaseEq(const internal::wstring& str) {
3109 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3110 str, true, false));
3111}
3112
3113// Matches a string not equal to str, ignoring case.
3114inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
3115 StrCaseNe(const internal::wstring& str) {
3116 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
3117 str, false, false));
3118}
3119
3120// Creates a matcher that matches any wstring, std::wstring, or C wide string
3121// that contains the given substring.
3122inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
3123 HasSubstr(const internal::wstring& substring) {
3124 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
3125 substring));
3126}
3127
3128// Matches a string that starts with 'prefix' (case-sensitive).
3129inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
3130 StartsWith(const internal::wstring& prefix) {
3131 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
3132 prefix));
3133}
3134
3135// Matches a string that ends with 'suffix' (case-sensitive).
3136inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
3137 EndsWith(const internal::wstring& suffix) {
3138 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
3139 suffix));
3140}
3141
3142#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
3143
3144// Creates a polymorphic matcher that matches a 2-tuple where the
3145// first field == the second field.
3146inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
3147
3148// Creates a polymorphic matcher that matches a 2-tuple where the
3149// first field >= the second field.
3150inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
3151
3152// Creates a polymorphic matcher that matches a 2-tuple where the
3153// first field > the second field.
3154inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
3155
3156// Creates a polymorphic matcher that matches a 2-tuple where the
3157// first field <= the second field.
3158inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
3159
3160// Creates a polymorphic matcher that matches a 2-tuple where the
3161// first field < the second field.
3162inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
3163
3164// Creates a polymorphic matcher that matches a 2-tuple where the
3165// first field != the second field.
3166inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
3167
3168// Creates a matcher that matches any value of type T that m doesn't
3169// match.
3170template <typename InnerMatcher>
3171inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
3172 return internal::NotMatcher<InnerMatcher>(m);
3173}
3174
shiqiane35fdd92008-12-10 05:08:54 +00003175// Returns a matcher that matches anything that satisfies the given
3176// predicate. The predicate can be any unary function or functor
3177// whose return type can be implicitly converted to bool.
3178template <typename Predicate>
3179inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
3180Truly(Predicate pred) {
3181 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
3182}
3183
zhanyong.wana31d9ce2013-03-01 01:50:17 +00003184// Returns a matcher that matches the container size. The container must
3185// support both size() and size_type which all STL-like containers provide.
3186// Note that the parameter 'size' can be a value of type size_type as well as
3187// matcher. For instance:
3188// EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
3189// EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
3190template <typename SizeMatcher>
3191inline internal::SizeIsMatcher<SizeMatcher>
3192SizeIs(const SizeMatcher& size_matcher) {
3193 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
3194}
3195
zhanyong.wan6a896b52009-01-16 01:13:50 +00003196// Returns a matcher that matches an equal container.
3197// This matcher behaves like Eq(), but in the event of mismatch lists the
3198// values that are included in one container but not the other. (Duplicate
3199// values and order differences are not explained.)
3200template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00003201inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00003202 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00003203 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00003204 // This following line is for working around a bug in MSVC 8.0,
3205 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00003206 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00003207 return MakePolymorphicMatcher(
3208 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00003209}
3210
zhanyong.wan898725c2011-09-16 16:45:39 +00003211// Returns a matcher that matches a container that, when sorted using
3212// the given comparator, matches container_matcher.
3213template <typename Comparator, typename ContainerMatcher>
3214inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
3215WhenSortedBy(const Comparator& comparator,
3216 const ContainerMatcher& container_matcher) {
3217 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
3218 comparator, container_matcher);
3219}
3220
3221// Returns a matcher that matches a container that, when sorted using
3222// the < operator, matches container_matcher.
3223template <typename ContainerMatcher>
3224inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
3225WhenSorted(const ContainerMatcher& container_matcher) {
3226 return
3227 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
3228 internal::LessComparator(), container_matcher);
3229}
3230
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003231// Matches an STL-style container or a native array that contains the
3232// same number of elements as in rhs, where its i-th element and rhs's
3233// i-th element (as a pair) satisfy the given pair matcher, for all i.
3234// TupleMatcher must be able to be safely cast to Matcher<tuple<const
3235// T1&, const T2&> >, where T1 and T2 are the types of elements in the
3236// LHS container and the RHS container respectively.
3237template <typename TupleMatcher, typename Container>
3238inline internal::PointwiseMatcher<TupleMatcher,
3239 GTEST_REMOVE_CONST_(Container)>
3240Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
3241 // This following line is for working around a bug in MSVC 8.0,
3242 // which causes Container to be a const type sometimes.
3243 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
3244 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
3245 tuple_matcher, rhs);
3246}
3247
zhanyong.wanb8243162009-06-04 05:48:20 +00003248// Matches an STL-style container or a native array that contains at
3249// least one element matching the given value or matcher.
3250//
3251// Examples:
3252// ::std::set<int> page_ids;
3253// page_ids.insert(3);
3254// page_ids.insert(1);
3255// EXPECT_THAT(page_ids, Contains(1));
3256// EXPECT_THAT(page_ids, Contains(Gt(2)));
3257// EXPECT_THAT(page_ids, Not(Contains(4)));
3258//
3259// ::std::map<int, size_t> page_lengths;
3260// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00003261// EXPECT_THAT(page_lengths,
3262// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00003263//
3264// const char* user_ids[] = { "joe", "mike", "tom" };
3265// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
3266template <typename M>
3267inline internal::ContainsMatcher<M> Contains(M matcher) {
3268 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00003269}
3270
zhanyong.wan33605ba2010-04-22 23:37:47 +00003271// Matches an STL-style container or a native array that contains only
3272// elements matching the given value or matcher.
3273//
3274// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
3275// the messages are different.
3276//
3277// Examples:
3278// ::std::set<int> page_ids;
3279// // Each(m) matches an empty container, regardless of what m is.
3280// EXPECT_THAT(page_ids, Each(Eq(1)));
3281// EXPECT_THAT(page_ids, Each(Eq(77)));
3282//
3283// page_ids.insert(3);
3284// EXPECT_THAT(page_ids, Each(Gt(0)));
3285// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
3286// page_ids.insert(1);
3287// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
3288//
3289// ::std::map<int, size_t> page_lengths;
3290// page_lengths[1] = 100;
3291// page_lengths[2] = 200;
3292// page_lengths[3] = 300;
3293// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
3294// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
3295//
3296// const char* user_ids[] = { "joe", "mike", "tom" };
3297// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
3298template <typename M>
3299inline internal::EachMatcher<M> Each(M matcher) {
3300 return internal::EachMatcher<M>(matcher);
3301}
3302
zhanyong.wanb5937da2009-07-16 20:26:41 +00003303// Key(inner_matcher) matches an std::pair whose 'first' field matches
3304// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3305// std::map that contains at least one element whose key is >= 5.
3306template <typename M>
3307inline internal::KeyMatcher<M> Key(M inner_matcher) {
3308 return internal::KeyMatcher<M>(inner_matcher);
3309}
3310
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003311// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
3312// matches first_matcher and whose 'second' field matches second_matcher. For
3313// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
3314// to match a std::map<int, string> that contains exactly one element whose key
3315// is >= 5 and whose value equals "foo".
3316template <typename FirstMatcher, typename SecondMatcher>
3317inline internal::PairMatcher<FirstMatcher, SecondMatcher>
3318Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
3319 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
3320 first_matcher, second_matcher);
3321}
3322
shiqiane35fdd92008-12-10 05:08:54 +00003323// Returns a predicate that is satisfied by anything that matches the
3324// given matcher.
3325template <typename M>
3326inline internal::MatcherAsPredicate<M> Matches(M matcher) {
3327 return internal::MatcherAsPredicate<M>(matcher);
3328}
3329
zhanyong.wanb8243162009-06-04 05:48:20 +00003330// Returns true iff the value matches the matcher.
3331template <typename T, typename M>
3332inline bool Value(const T& value, M matcher) {
3333 return testing::Matches(matcher)(value);
3334}
3335
zhanyong.wan34b034c2010-03-05 21:23:23 +00003336// Matches the value against the given matcher and explains the match
3337// result to listener.
3338template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00003339inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00003340 M matcher, const T& value, MatchResultListener* listener) {
3341 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
3342}
3343
zhanyong.wanbf550852009-06-09 06:09:53 +00003344// AllArgs(m) is a synonym of m. This is useful in
3345//
3346// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
3347//
3348// which is easier to read than
3349//
3350// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
3351template <typename InnerMatcher>
3352inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
3353
shiqiane35fdd92008-12-10 05:08:54 +00003354// These macros allow using matchers to check values in Google Test
3355// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
3356// succeed iff the value matches the matcher. If the assertion fails,
3357// the value and the description of the matcher will be printed.
3358#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
3359 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3360#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
3361 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3362
3363} // namespace testing
3364
3365#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_