blob: 9c457730b3b479f33fbb17350ce864c8b5e2e1ed [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>
46#include <vector>
47
48#include <gmock/gmock-printers.h>
49#include <gmock/internal/gmock-internal-utils.h>
50#include <gmock/internal/gmock-port.h>
51#include <gtest/gtest.h>
52
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
93 private:
94 ::std::ostream* const stream_;
95
96 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
97};
98
99inline MatchResultListener::~MatchResultListener() {
100}
101
shiqiane35fdd92008-12-10 05:08:54 +0000102// The implementation of a matcher.
103template <typename T>
104class MatcherInterface {
105 public:
106 virtual ~MatcherInterface() {}
107
zhanyong.wan82113312010-01-08 21:55:40 +0000108 // Returns true iff the matcher matches x; also explains the match
109 // result to 'listener'.
110 //
111 // You should override this method when defining a new matcher. For
112 // backward compatibility, we provide a default implementation that
113 // just forwards to the old, deprecated matcher API (Matches() and
114 // ExplainMatchResultTo()).
115 //
116 // It's the responsibility of the caller (Google Mock) to guarantee
117 // that 'listener' is not NULL. This helps to simplify a matcher's
118 // implementation when it doesn't care about the performance, as it
119 // can talk to 'listener' without checking its validity first.
120 // However, in order to implement dummy listeners efficiently,
121 // listener->stream() may be NULL.
122 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
123 const bool match = Matches(x);
124 if (listener->stream() != NULL) {
125 ExplainMatchResultTo(x, listener->stream());
126 }
127 return match;
128 }
129
130 // DEPRECATED. This method will be removed. Override
131 // MatchAndExplain() instead.
132 //
shiqiane35fdd92008-12-10 05:08:54 +0000133 // Returns true iff the matcher matches x.
zhanyong.wan82113312010-01-08 21:55:40 +0000134 virtual bool Matches(T /* x */) const { return false; }
shiqiane35fdd92008-12-10 05:08:54 +0000135
136 // Describes this matcher to an ostream.
137 virtual void DescribeTo(::std::ostream* os) const = 0;
138
139 // Describes the negation of this matcher to an ostream. For
140 // example, if the description of this matcher is "is greater than
141 // 7", the negated description could be "is not greater than 7".
142 // You are not required to override this when implementing
143 // MatcherInterface, but it is highly advised so that your matcher
144 // can produce good error messages.
145 virtual void DescribeNegationTo(::std::ostream* os) const {
146 *os << "not (";
147 DescribeTo(os);
148 *os << ")";
149 }
150
zhanyong.wan82113312010-01-08 21:55:40 +0000151 // DEPRECATED. This method will be removed. Override
152 // MatchAndExplain() instead.
153 //
shiqiane35fdd92008-12-10 05:08:54 +0000154 // Explains why x matches, or doesn't match, the matcher. Override
155 // this to provide any additional information that helps a user
156 // understand the match result.
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000157 virtual void ExplainMatchResultTo(T /* x */, ::std::ostream* /* os */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000158 // By default, nothing more needs to be explained, as Google Mock
159 // has already printed the value of x when this function is
160 // called.
161 }
162};
163
164namespace internal {
165
zhanyong.wan82113312010-01-08 21:55:40 +0000166// A match result listener that ignores the explanation.
167class DummyMatchResultListener : public MatchResultListener {
168 public:
169 DummyMatchResultListener() : MatchResultListener(NULL) {}
170
171 private:
172 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
173};
174
175// A match result listener that forwards the explanation to a given
176// ostream. The difference between this and MatchResultListener is
177// that the former is concrete.
178class StreamMatchResultListener : public MatchResultListener {
179 public:
180 explicit StreamMatchResultListener(::std::ostream* os)
181 : MatchResultListener(os) {}
182
183 private:
184 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
185};
186
187// A match result listener that stores the explanation in a string.
188class StringMatchResultListener : public MatchResultListener {
189 public:
190 StringMatchResultListener() : MatchResultListener(&ss_) {}
191
192 // Returns the explanation heard so far.
193 internal::string str() const { return ss_.str(); }
194
195 private:
196 ::std::stringstream ss_;
197
198 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
199};
200
shiqiane35fdd92008-12-10 05:08:54 +0000201// An internal class for implementing Matcher<T>, which will derive
202// from it. We put functionalities common to all Matcher<T>
203// specializations here to avoid code duplication.
204template <typename T>
205class MatcherBase {
206 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000207 // Returns true iff the matcher matches x; also explains the match
208 // result to 'listener'.
209 bool MatchAndExplain(T x, MatchResultListener* listener) const {
210 return impl_->MatchAndExplain(x, listener);
211 }
212
shiqiane35fdd92008-12-10 05:08:54 +0000213 // Returns true iff this matcher matches x.
zhanyong.wan82113312010-01-08 21:55:40 +0000214 bool Matches(T x) const {
215 DummyMatchResultListener dummy;
216 return MatchAndExplain(x, &dummy);
217 }
shiqiane35fdd92008-12-10 05:08:54 +0000218
219 // Describes this matcher to an ostream.
220 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
221
222 // Describes the negation of this matcher to an ostream.
223 void DescribeNegationTo(::std::ostream* os) const {
224 impl_->DescribeNegationTo(os);
225 }
226
227 // Explains why x matches, or doesn't match, the matcher.
228 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000229 StreamMatchResultListener listener(os);
230 MatchAndExplain(x, &listener);
shiqiane35fdd92008-12-10 05:08:54 +0000231 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000232
shiqiane35fdd92008-12-10 05:08:54 +0000233 protected:
234 MatcherBase() {}
235
236 // Constructs a matcher from its implementation.
237 explicit MatcherBase(const MatcherInterface<T>* impl)
238 : impl_(impl) {}
239
240 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000241
shiqiane35fdd92008-12-10 05:08:54 +0000242 private:
243 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
244 // interfaces. The former dynamically allocates a chunk of memory
245 // to hold the reference count, while the latter tracks all
246 // references using a circular linked list without allocating
247 // memory. It has been observed that linked_ptr performs better in
248 // typical scenarios. However, shared_ptr can out-perform
249 // linked_ptr when there are many more uses of the copy constructor
250 // than the default constructor.
251 //
252 // If performance becomes a problem, we should see if using
253 // shared_ptr helps.
254 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
255};
256
257// The default implementation of ExplainMatchResultTo() for
258// polymorphic matchers.
259template <typename PolymorphicMatcherImpl, typename T>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000260inline void ExplainMatchResultTo(const PolymorphicMatcherImpl& /* impl */,
261 const T& /* x */,
262 ::std::ostream* /* os */) {
shiqiane35fdd92008-12-10 05:08:54 +0000263 // By default, nothing more needs to be said, as Google Mock already
264 // prints the value of x elsewhere.
265}
266
zhanyong.wan82113312010-01-08 21:55:40 +0000267// The default implementation of MatchAndExplain() for polymorphic
zhanyong.wane122e452010-01-12 09:03:52 +0000268// matchers. The type of argument x cannot be const T&, in case
269// impl.Matches() takes a non-const reference.
zhanyong.wan82113312010-01-08 21:55:40 +0000270template <typename PolymorphicMatcherImpl, typename T>
271inline bool MatchAndExplain(const PolymorphicMatcherImpl& impl,
zhanyong.wane122e452010-01-12 09:03:52 +0000272 T& x,
zhanyong.wan82113312010-01-08 21:55:40 +0000273 MatchResultListener* listener) {
274 const bool match = impl.Matches(x);
275
276 ::std::ostream* const os = listener->stream();
277 if (os != NULL) {
278 using ::testing::internal::ExplainMatchResultTo;
279 // When resolving the following call, both
280 // ::testing::internal::ExplainMatchResultTo() and
281 // foo::ExplainMatchResultTo() are considered, where foo is the
282 // namespace where class PolymorphicMatcherImpl is defined.
283 ExplainMatchResultTo(impl, x, os);
284 }
285
286 return match;
287}
288
shiqiane35fdd92008-12-10 05:08:54 +0000289} // namespace internal
290
291// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
292// object that can check whether a value of type T matches. The
293// implementation of Matcher<T> is just a linked_ptr to const
294// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
295// from Matcher!
296template <typename T>
297class Matcher : public internal::MatcherBase<T> {
298 public:
299 // Constructs a null matcher. Needed for storing Matcher objects in
300 // STL containers.
301 Matcher() {}
302
303 // Constructs a matcher from its implementation.
304 explicit Matcher(const MatcherInterface<T>* impl)
305 : internal::MatcherBase<T>(impl) {}
306
zhanyong.wan18490652009-05-11 18:54:08 +0000307 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000308 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
309 Matcher(T value); // NOLINT
310};
311
312// The following two specializations allow the user to write str
313// instead of Eq(str) and "foo" instead of Eq("foo") when a string
314// matcher is expected.
315template <>
316class Matcher<const internal::string&>
317 : public internal::MatcherBase<const internal::string&> {
318 public:
319 Matcher() {}
320
321 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
322 : internal::MatcherBase<const internal::string&>(impl) {}
323
324 // Allows the user to write str instead of Eq(str) sometimes, where
325 // str is a string object.
326 Matcher(const internal::string& s); // NOLINT
327
328 // Allows the user to write "foo" instead of Eq("foo") sometimes.
329 Matcher(const char* s); // NOLINT
330};
331
332template <>
333class Matcher<internal::string>
334 : public internal::MatcherBase<internal::string> {
335 public:
336 Matcher() {}
337
338 explicit Matcher(const MatcherInterface<internal::string>* impl)
339 : internal::MatcherBase<internal::string>(impl) {}
340
341 // Allows the user to write str instead of Eq(str) sometimes, where
342 // str is a string object.
343 Matcher(const internal::string& s); // NOLINT
344
345 // Allows the user to write "foo" instead of Eq("foo") sometimes.
346 Matcher(const char* s); // NOLINT
347};
348
349// The PolymorphicMatcher class template makes it easy to implement a
350// polymorphic matcher (i.e. a matcher that can match values of more
351// than one type, e.g. Eq(n) and NotNull()).
352//
zhanyong.wan82113312010-01-08 21:55:40 +0000353// To define a polymorphic matcher in the old, deprecated way, a user
354// first provides an Impl class that has a Matches() method, a
355// DescribeTo() method, and a DescribeNegationTo() method. The
356// Matches() method is usually a method template (such that it works
357// with multiple types). Then the user creates the polymorphic
358// matcher using MakePolymorphicMatcher(). To provide additional
359// explanation to the match result, define a FREE function (or
360// function template)
shiqiane35fdd92008-12-10 05:08:54 +0000361//
362// void ExplainMatchResultTo(const Impl& matcher, const Value& value,
363// ::std::ostream* os);
364//
zhanyong.wan82113312010-01-08 21:55:40 +0000365// in the SAME NAME SPACE where Impl is defined.
366//
367// The new, recommended way to define a polymorphic matcher is to
368// provide an Impl class that has a DescribeTo() method and a
369// DescribeNegationTo() method, and define a FREE function (or
370// function template)
371//
372// bool MatchAndExplain(const Impl& matcher, const Value& value,
373// MatchResultListener* listener);
374//
375// in the SAME NAME SPACE where Impl is defined.
376//
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 {
shiqiane35fdd92008-12-10 05:08:54 +0000411 // C++ uses Argument-Dependent Look-up (aka Koenig Look-up) to
zhanyong.wan82113312010-01-08 21:55:40 +0000412 // resolve the call to MatchAndExplain() here. This means that
413 // if there's a MatchAndExplain() function defined in the name
414 // space where class Impl is defined, it will be picked by the
415 // compiler as the better match. Otherwise the default
416 // implementation of it in ::testing::internal will be picked.
417 using ::testing::internal::MatchAndExplain;
418 return MatchAndExplain(impl_, x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000419 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000420
shiqiane35fdd92008-12-10 05:08:54 +0000421 private:
422 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000423
424 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000425 };
426
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000427 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000428
429 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000430};
431
432// Creates a matcher from its implementation. This is easier to use
433// than the Matcher<T> constructor as it doesn't require you to
434// explicitly write the template argument, e.g.
435//
436// MakeMatcher(foo);
437// vs
438// Matcher<const string&>(foo);
439template <typename T>
440inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
441 return Matcher<T>(impl);
442};
443
444// Creates a polymorphic matcher from its implementation. This is
445// easier to use than the PolymorphicMatcher<Impl> constructor as it
446// doesn't require you to explicitly write the template argument, e.g.
447//
448// MakePolymorphicMatcher(foo);
449// vs
450// PolymorphicMatcher<TypeOfFoo>(foo);
451template <class Impl>
452inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
453 return PolymorphicMatcher<Impl>(impl);
454}
455
456// In order to be safe and clear, casting between different matcher
457// types is done explicitly via MatcherCast<T>(m), which takes a
458// matcher m and returns a Matcher<T>. It compiles only when T can be
459// statically converted to the argument type of m.
460template <typename T, typename M>
461Matcher<T> MatcherCast(M m);
462
zhanyong.wan18490652009-05-11 18:54:08 +0000463// Implements SafeMatcherCast().
464//
zhanyong.wan95b12332009-09-25 18:55:50 +0000465// We use an intermediate class to do the actual safe casting as Nokia's
466// Symbian compiler cannot decide between
467// template <T, M> ... (M) and
468// template <T, U> ... (const Matcher<U>&)
469// for function templates but can for member function templates.
470template <typename T>
471class SafeMatcherCastImpl {
472 public:
473 // This overload handles polymorphic matchers only since monomorphic
474 // matchers are handled by the next one.
475 template <typename M>
476 static inline Matcher<T> Cast(M polymorphic_matcher) {
477 return Matcher<T>(polymorphic_matcher);
478 }
zhanyong.wan18490652009-05-11 18:54:08 +0000479
zhanyong.wan95b12332009-09-25 18:55:50 +0000480 // This overload handles monomorphic matchers.
481 //
482 // In general, if type T can be implicitly converted to type U, we can
483 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
484 // contravariant): just keep a copy of the original Matcher<U>, convert the
485 // argument from type T to U, and then pass it to the underlying Matcher<U>.
486 // The only exception is when U is a reference and T is not, as the
487 // underlying Matcher<U> may be interested in the argument's address, which
488 // is not preserved in the conversion from T to U.
489 template <typename U>
490 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
491 // Enforce that T can be implicitly converted to U.
492 GMOCK_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
493 T_must_be_implicitly_convertible_to_U);
494 // Enforce that we are not converting a non-reference type T to a reference
495 // type U.
496 GMOCK_COMPILE_ASSERT_(
497 internal::is_reference<T>::value || !internal::is_reference<U>::value,
498 cannot_convert_non_referentce_arg_to_reference);
499 // In case both T and U are arithmetic types, enforce that the
500 // conversion is not lossy.
501 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(T)) RawT;
502 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(U)) RawU;
503 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
504 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
505 GMOCK_COMPILE_ASSERT_(
506 kTIsOther || kUIsOther ||
507 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
508 conversion_of_arithmetic_types_must_be_lossless);
509 return MatcherCast<T>(matcher);
510 }
511};
512
513template <typename T, typename M>
514inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
515 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000516}
517
shiqiane35fdd92008-12-10 05:08:54 +0000518// A<T>() returns a matcher that matches any value of type T.
519template <typename T>
520Matcher<T> A();
521
522// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
523// and MUST NOT BE USED IN USER CODE!!!
524namespace internal {
525
zhanyong.wan82113312010-01-08 21:55:40 +0000526// If the given string is not empty and os is not NULL, wraps the
527// string inside a pair of parentheses and streams the result to os.
528inline void StreamInParensAsNeeded(const internal::string& str,
529 ::std::ostream* os) {
530 if (!str.empty() && os != NULL) {
531 *os << " (" << str << ")";
shiqiane35fdd92008-12-10 05:08:54 +0000532 }
533}
534
535// An internal helper class for doing compile-time loop on a tuple's
536// fields.
537template <size_t N>
538class TuplePrefix {
539 public:
540 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
541 // iff the first N fields of matcher_tuple matches the first N
542 // fields of value_tuple, respectively.
543 template <typename MatcherTuple, typename ValueTuple>
544 static bool Matches(const MatcherTuple& matcher_tuple,
545 const ValueTuple& value_tuple) {
546 using ::std::tr1::get;
547 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
548 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
549 }
550
551 // TuplePrefix<N>::DescribeMatchFailuresTo(matchers, values, os)
552 // describes failures in matching the first N fields of matchers
553 // against the first N fields of values. If there is no failure,
554 // nothing will be streamed to os.
555 template <typename MatcherTuple, typename ValueTuple>
556 static void DescribeMatchFailuresTo(const MatcherTuple& matchers,
557 const ValueTuple& values,
558 ::std::ostream* os) {
559 using ::std::tr1::tuple_element;
560 using ::std::tr1::get;
561
562 // First, describes failures in the first N - 1 fields.
563 TuplePrefix<N - 1>::DescribeMatchFailuresTo(matchers, values, os);
564
565 // Then describes the failure (if any) in the (N - 1)-th (0-based)
566 // field.
567 typename tuple_element<N - 1, MatcherTuple>::type matcher =
568 get<N - 1>(matchers);
569 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
570 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000571 StringMatchResultListener listener;
572 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000573 // TODO(wan): include in the message the name of the parameter
574 // as used in MOCK_METHOD*() when possible.
575 *os << " Expected arg #" << N - 1 << ": ";
576 get<N - 1>(matchers).DescribeTo(os);
577 *os << "\n Actual: ";
578 // We remove the reference in type Value to prevent the
579 // universal printer from printing the address of value, which
580 // isn't interesting to the user most of the time. The
581 // matcher's ExplainMatchResultTo() method handles the case when
582 // the address is interesting.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000583 internal::UniversalPrinter<GMOCK_REMOVE_REFERENCE_(Value)>::
shiqiane35fdd92008-12-10 05:08:54 +0000584 Print(value, os);
zhanyong.wan82113312010-01-08 21:55:40 +0000585
586 StreamInParensAsNeeded(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000587 *os << "\n";
588 }
589 }
590};
591
592// The base case.
593template <>
594class TuplePrefix<0> {
595 public:
596 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000597 static bool Matches(const MatcherTuple& /* matcher_tuple */,
598 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000599 return true;
600 }
601
602 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000603 static void DescribeMatchFailuresTo(const MatcherTuple& /* matchers */,
604 const ValueTuple& /* values */,
605 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000606};
607
608// TupleMatches(matcher_tuple, value_tuple) returns true iff all
609// matchers in matcher_tuple match the corresponding fields in
610// value_tuple. It is a compiler error if matcher_tuple and
611// value_tuple have different number of fields or incompatible field
612// types.
613template <typename MatcherTuple, typename ValueTuple>
614bool TupleMatches(const MatcherTuple& matcher_tuple,
615 const ValueTuple& value_tuple) {
616 using ::std::tr1::tuple_size;
617 // Makes sure that matcher_tuple and value_tuple have the same
618 // number of fields.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000619 GMOCK_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
620 tuple_size<ValueTuple>::value,
621 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000622 return TuplePrefix<tuple_size<ValueTuple>::value>::
623 Matches(matcher_tuple, value_tuple);
624}
625
626// Describes failures in matching matchers against values. If there
627// is no failure, nothing will be streamed to os.
628template <typename MatcherTuple, typename ValueTuple>
629void DescribeMatchFailureTupleTo(const MatcherTuple& matchers,
630 const ValueTuple& values,
631 ::std::ostream* os) {
632 using ::std::tr1::tuple_size;
633 TuplePrefix<tuple_size<MatcherTuple>::value>::DescribeMatchFailuresTo(
634 matchers, values, os);
635}
636
637// The MatcherCastImpl class template is a helper for implementing
638// MatcherCast(). We need this helper in order to partially
639// specialize the implementation of MatcherCast() (C++ allows
640// class/struct templates to be partially specialized, but not
641// function templates.).
642
643// This general version is used when MatcherCast()'s argument is a
644// polymorphic matcher (i.e. something that can be converted to a
645// Matcher but is not one yet; for example, Eq(value)).
646template <typename T, typename M>
647class MatcherCastImpl {
648 public:
649 static Matcher<T> Cast(M polymorphic_matcher) {
650 return Matcher<T>(polymorphic_matcher);
651 }
652};
653
654// This more specialized version is used when MatcherCast()'s argument
655// is already a Matcher. This only compiles when type T can be
656// statically converted to type U.
657template <typename T, typename U>
658class MatcherCastImpl<T, Matcher<U> > {
659 public:
660 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
661 return Matcher<T>(new Impl(source_matcher));
662 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000663
shiqiane35fdd92008-12-10 05:08:54 +0000664 private:
665 class Impl : public MatcherInterface<T> {
666 public:
667 explicit Impl(const Matcher<U>& source_matcher)
668 : source_matcher_(source_matcher) {}
669
670 // We delegate the matching logic to the source matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000671 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
672 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000673 }
674
675 virtual void DescribeTo(::std::ostream* os) const {
676 source_matcher_.DescribeTo(os);
677 }
678
679 virtual void DescribeNegationTo(::std::ostream* os) const {
680 source_matcher_.DescribeNegationTo(os);
681 }
682
shiqiane35fdd92008-12-10 05:08:54 +0000683 private:
684 const Matcher<U> source_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000685
686 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000687 };
688};
689
690// This even more specialized version is used for efficiently casting
691// a matcher to its own type.
692template <typename T>
693class MatcherCastImpl<T, Matcher<T> > {
694 public:
695 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
696};
697
698// Implements A<T>().
699template <typename T>
700class AnyMatcherImpl : public MatcherInterface<T> {
701 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000702 virtual bool MatchAndExplain(
703 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000704 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
705 virtual void DescribeNegationTo(::std::ostream* os) const {
706 // This is mostly for completeness' safe, as it's not very useful
707 // to write Not(A<bool>()). However we cannot completely rule out
708 // such a possibility, and it doesn't hurt to be prepared.
709 *os << "never matches";
710 }
711};
712
713// Implements _, a matcher that matches any value of any
714// type. This is a polymorphic matcher, so we need a template type
715// conversion operator to make it appearing as a Matcher<T> for any
716// type T.
717class AnythingMatcher {
718 public:
719 template <typename T>
720 operator Matcher<T>() const { return A<T>(); }
721};
722
723// Implements a matcher that compares a given value with a
724// pre-supplied value using one of the ==, <=, <, etc, operators. The
725// two values being compared don't have to have the same type.
726//
727// The matcher defined here is polymorphic (for example, Eq(5) can be
728// used to match an int, a short, a double, etc). Therefore we use
729// a template type conversion operator in the implementation.
730//
731// We define this as a macro in order to eliminate duplicated source
732// code.
733//
734// The following template definition assumes that the Rhs parameter is
735// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wane0d051e2009-02-19 00:33:37 +0000736#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000737 template <typename Rhs> class name##Matcher { \
738 public: \
739 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
740 template <typename Lhs> \
741 operator Matcher<Lhs>() const { \
742 return MakeMatcher(new Impl<Lhs>(rhs_)); \
743 } \
744 private: \
745 template <typename Lhs> \
746 class Impl : public MatcherInterface<Lhs> { \
747 public: \
748 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
zhanyong.wan82113312010-01-08 21:55:40 +0000749 virtual bool MatchAndExplain(\
750 Lhs lhs, MatchResultListener* /* listener */) const { \
751 return lhs op rhs_; \
752 } \
shiqiane35fdd92008-12-10 05:08:54 +0000753 virtual void DescribeTo(::std::ostream* os) const { \
754 *os << "is " relation " "; \
755 UniversalPrinter<Rhs>::Print(rhs_, os); \
756 } \
757 virtual void DescribeNegationTo(::std::ostream* os) const { \
758 *os << "is not " relation " "; \
759 UniversalPrinter<Rhs>::Print(rhs_, os); \
760 } \
761 private: \
762 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000763 GTEST_DISALLOW_ASSIGN_(Impl); \
shiqiane35fdd92008-12-10 05:08:54 +0000764 }; \
765 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000766 GTEST_DISALLOW_ASSIGN_(name##Matcher); \
shiqiane35fdd92008-12-10 05:08:54 +0000767 }
768
769// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
770// respectively.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000771GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "equal to");
772GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "greater than or equal to");
773GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "greater than");
774GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "less than or equal to");
775GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "less than");
776GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "not equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000777
zhanyong.wane0d051e2009-02-19 00:33:37 +0000778#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000779
vladlosev79b83502009-11-18 00:43:37 +0000780// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000781// pointer that is NULL.
782class IsNullMatcher {
783 public:
vladlosev79b83502009-11-18 00:43:37 +0000784 template <typename Pointer>
785 bool Matches(const Pointer& p) const { return GetRawPointer(p) == NULL; }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000786
787 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
788 void DescribeNegationTo(::std::ostream* os) const {
789 *os << "is not NULL";
790 }
791};
792
zhanyong.wane122e452010-01-12 09:03:52 +0000793template <typename Pointer>
794bool MatchAndExplain(const IsNullMatcher& impl, Pointer& p,
795 MatchResultListener* /* listener */) {
796 return impl.Matches(p);
797}
798
vladlosev79b83502009-11-18 00:43:37 +0000799// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000800// pointer that is not NULL.
801class NotNullMatcher {
802 public:
vladlosev79b83502009-11-18 00:43:37 +0000803 template <typename Pointer>
804 bool Matches(const Pointer& p) const { return GetRawPointer(p) != NULL; }
shiqiane35fdd92008-12-10 05:08:54 +0000805
806 void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; }
807 void DescribeNegationTo(::std::ostream* os) const {
808 *os << "is NULL";
809 }
810};
811
zhanyong.wane122e452010-01-12 09:03:52 +0000812template <typename Pointer>
813bool MatchAndExplain(const NotNullMatcher& impl, Pointer& p,
814 MatchResultListener* /* listener */) {
815 return impl.Matches(p);
816}
817
shiqiane35fdd92008-12-10 05:08:54 +0000818// Ref(variable) matches any argument that is a reference to
819// 'variable'. This matcher is polymorphic as it can match any
820// super type of the type of 'variable'.
821//
822// The RefMatcher template class implements Ref(variable). It can
823// only be instantiated with a reference type. This prevents a user
824// from mistakenly using Ref(x) to match a non-reference function
825// argument. For example, the following will righteously cause a
826// compiler error:
827//
828// int n;
829// Matcher<int> m1 = Ref(n); // This won't compile.
830// Matcher<int&> m2 = Ref(n); // This will compile.
831template <typename T>
832class RefMatcher;
833
834template <typename T>
835class RefMatcher<T&> {
836 // Google Mock is a generic framework and thus needs to support
837 // mocking any function types, including those that take non-const
838 // reference arguments. Therefore the template parameter T (and
839 // Super below) can be instantiated to either a const type or a
840 // non-const type.
841 public:
842 // RefMatcher() takes a T& instead of const T&, as we want the
843 // compiler to catch using Ref(const_value) as a matcher for a
844 // non-const reference.
845 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
846
847 template <typename Super>
848 operator Matcher<Super&>() const {
849 // By passing object_ (type T&) to Impl(), which expects a Super&,
850 // we make sure that Super is a super type of T. In particular,
851 // this catches using Ref(const_value) as a matcher for a
852 // non-const reference, as you cannot implicitly convert a const
853 // reference to a non-const reference.
854 return MakeMatcher(new Impl<Super>(object_));
855 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000856
shiqiane35fdd92008-12-10 05:08:54 +0000857 private:
858 template <typename Super>
859 class Impl : public MatcherInterface<Super&> {
860 public:
861 explicit Impl(Super& x) : object_(x) {} // NOLINT
862
863 // Matches() takes a Super& (as opposed to const Super&) in
864 // order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +0000865 virtual bool MatchAndExplain(
866 Super& x, MatchResultListener* listener) const {
867 *listener << "is located @" << static_cast<const void*>(&x);
868 return &x == &object_;
869 }
shiqiane35fdd92008-12-10 05:08:54 +0000870
871 virtual void DescribeTo(::std::ostream* os) const {
872 *os << "references the variable ";
873 UniversalPrinter<Super&>::Print(object_, os);
874 }
875
876 virtual void DescribeNegationTo(::std::ostream* os) const {
877 *os << "does not reference the variable ";
878 UniversalPrinter<Super&>::Print(object_, os);
879 }
880
shiqiane35fdd92008-12-10 05:08:54 +0000881 private:
882 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000883
884 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000885 };
886
887 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000888
889 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000890};
891
892// Polymorphic helper functions for narrow and wide string matchers.
893inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
894 return String::CaseInsensitiveCStringEquals(lhs, rhs);
895}
896
897inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
898 const wchar_t* rhs) {
899 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
900}
901
902// String comparison for narrow or wide strings that can have embedded NUL
903// characters.
904template <typename StringType>
905bool CaseInsensitiveStringEquals(const StringType& s1,
906 const StringType& s2) {
907 // Are the heads equal?
908 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
909 return false;
910 }
911
912 // Skip the equal heads.
913 const typename StringType::value_type nul = 0;
914 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
915
916 // Are we at the end of either s1 or s2?
917 if (i1 == StringType::npos || i2 == StringType::npos) {
918 return i1 == i2;
919 }
920
921 // Are the tails equal?
922 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
923}
924
925// String matchers.
926
927// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
928template <typename StringType>
929class StrEqualityMatcher {
930 public:
931 typedef typename StringType::const_pointer ConstCharPointer;
932
933 StrEqualityMatcher(const StringType& str, bool expect_eq,
934 bool case_sensitive)
935 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
936
937 // When expect_eq_ is true, returns true iff s is equal to string_;
938 // otherwise returns true iff s is not equal to string_.
939 bool Matches(ConstCharPointer s) const {
940 if (s == NULL) {
941 return !expect_eq_;
942 }
943 return Matches(StringType(s));
944 }
945
946 bool Matches(const StringType& s) const {
947 const bool eq = case_sensitive_ ? s == string_ :
948 CaseInsensitiveStringEquals(s, string_);
949 return expect_eq_ == eq;
950 }
951
952 void DescribeTo(::std::ostream* os) const {
953 DescribeToHelper(expect_eq_, os);
954 }
955
956 void DescribeNegationTo(::std::ostream* os) const {
957 DescribeToHelper(!expect_eq_, os);
958 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000959
shiqiane35fdd92008-12-10 05:08:54 +0000960 private:
961 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
962 *os << "is ";
963 if (!expect_eq) {
964 *os << "not ";
965 }
966 *os << "equal to ";
967 if (!case_sensitive_) {
968 *os << "(ignoring case) ";
969 }
970 UniversalPrinter<StringType>::Print(string_, os);
971 }
972
973 const StringType string_;
974 const bool expect_eq_;
975 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000976
977 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000978};
979
zhanyong.wane122e452010-01-12 09:03:52 +0000980template <typename StringType, typename T>
981bool MatchAndExplain(const StrEqualityMatcher<StringType>& impl, T& s,
982 MatchResultListener* /* listener */) {
983 return impl.Matches(s);
984}
985
shiqiane35fdd92008-12-10 05:08:54 +0000986// Implements the polymorphic HasSubstr(substring) matcher, which
987// can be used as a Matcher<T> as long as T can be converted to a
988// string.
989template <typename StringType>
990class HasSubstrMatcher {
991 public:
992 typedef typename StringType::const_pointer ConstCharPointer;
993
994 explicit HasSubstrMatcher(const StringType& substring)
995 : substring_(substring) {}
996
997 // These overloaded methods allow HasSubstr(substring) to be used as a
998 // Matcher<T> as long as T can be converted to string. Returns true
999 // iff s contains substring_ as a substring.
1000 bool Matches(ConstCharPointer s) const {
1001 return s != NULL && Matches(StringType(s));
1002 }
1003
1004 bool Matches(const StringType& s) const {
1005 return s.find(substring_) != StringType::npos;
1006 }
1007
1008 // Describes what this matcher matches.
1009 void DescribeTo(::std::ostream* os) const {
1010 *os << "has substring ";
1011 UniversalPrinter<StringType>::Print(substring_, os);
1012 }
1013
1014 void DescribeNegationTo(::std::ostream* os) const {
1015 *os << "has no substring ";
1016 UniversalPrinter<StringType>::Print(substring_, os);
1017 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001018
shiqiane35fdd92008-12-10 05:08:54 +00001019 private:
1020 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001021
1022 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001023};
1024
zhanyong.wane122e452010-01-12 09:03:52 +00001025template <typename StringType, typename T>
1026bool MatchAndExplain(const HasSubstrMatcher<StringType>& impl, T& s,
1027 MatchResultListener* /* listener */) {
1028 return impl.Matches(s);
1029}
1030
shiqiane35fdd92008-12-10 05:08:54 +00001031// Implements the polymorphic StartsWith(substring) matcher, which
1032// can be used as a Matcher<T> as long as T can be converted to a
1033// string.
1034template <typename StringType>
1035class StartsWithMatcher {
1036 public:
1037 typedef typename StringType::const_pointer ConstCharPointer;
1038
1039 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1040 }
1041
1042 // These overloaded methods allow StartsWith(prefix) to be used as a
1043 // Matcher<T> as long as T can be converted to string. Returns true
1044 // iff s starts with prefix_.
1045 bool Matches(ConstCharPointer s) const {
1046 return s != NULL && Matches(StringType(s));
1047 }
1048
1049 bool Matches(const StringType& s) const {
1050 return s.length() >= prefix_.length() &&
1051 s.substr(0, prefix_.length()) == prefix_;
1052 }
1053
1054 void DescribeTo(::std::ostream* os) const {
1055 *os << "starts with ";
1056 UniversalPrinter<StringType>::Print(prefix_, os);
1057 }
1058
1059 void DescribeNegationTo(::std::ostream* os) const {
1060 *os << "doesn't start with ";
1061 UniversalPrinter<StringType>::Print(prefix_, os);
1062 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001063
shiqiane35fdd92008-12-10 05:08:54 +00001064 private:
1065 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001066
1067 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001068};
1069
zhanyong.wane122e452010-01-12 09:03:52 +00001070template <typename StringType, typename T>
1071bool MatchAndExplain(const StartsWithMatcher<StringType>& impl, T& s,
1072 MatchResultListener* /* listener */) {
1073 return impl.Matches(s);
1074}
1075
shiqiane35fdd92008-12-10 05:08:54 +00001076// Implements the polymorphic EndsWith(substring) matcher, which
1077// can be used as a Matcher<T> as long as T can be converted to a
1078// string.
1079template <typename StringType>
1080class EndsWithMatcher {
1081 public:
1082 typedef typename StringType::const_pointer ConstCharPointer;
1083
1084 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1085
1086 // These overloaded methods allow EndsWith(suffix) to be used as a
1087 // Matcher<T> as long as T can be converted to string. Returns true
1088 // iff s ends with suffix_.
1089 bool Matches(ConstCharPointer s) const {
1090 return s != NULL && Matches(StringType(s));
1091 }
1092
1093 bool Matches(const StringType& s) const {
1094 return s.length() >= suffix_.length() &&
1095 s.substr(s.length() - suffix_.length()) == suffix_;
1096 }
1097
1098 void DescribeTo(::std::ostream* os) const {
1099 *os << "ends with ";
1100 UniversalPrinter<StringType>::Print(suffix_, os);
1101 }
1102
1103 void DescribeNegationTo(::std::ostream* os) const {
1104 *os << "doesn't end with ";
1105 UniversalPrinter<StringType>::Print(suffix_, os);
1106 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001107
shiqiane35fdd92008-12-10 05:08:54 +00001108 private:
1109 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001110
1111 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001112};
1113
zhanyong.wane122e452010-01-12 09:03:52 +00001114template <typename StringType, typename T>
1115bool MatchAndExplain(const EndsWithMatcher<StringType>& impl, T& s,
1116 MatchResultListener* /* listener */) {
1117 return impl.Matches(s);
1118}
1119
shiqiane35fdd92008-12-10 05:08:54 +00001120// Implements polymorphic matchers MatchesRegex(regex) and
1121// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1122// T can be converted to a string.
1123class MatchesRegexMatcher {
1124 public:
1125 MatchesRegexMatcher(const RE* regex, bool full_match)
1126 : regex_(regex), full_match_(full_match) {}
1127
1128 // These overloaded methods allow MatchesRegex(regex) to be used as
1129 // a Matcher<T> as long as T can be converted to string. Returns
1130 // true iff s matches regular expression regex. When full_match_ is
1131 // true, a full match is done; otherwise a partial match is done.
1132 bool Matches(const char* s) const {
1133 return s != NULL && Matches(internal::string(s));
1134 }
1135
1136 bool Matches(const internal::string& s) const {
1137 return full_match_ ? RE::FullMatch(s, *regex_) :
1138 RE::PartialMatch(s, *regex_);
1139 }
1140
1141 void DescribeTo(::std::ostream* os) const {
1142 *os << (full_match_ ? "matches" : "contains")
1143 << " regular expression ";
1144 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1145 }
1146
1147 void DescribeNegationTo(::std::ostream* os) const {
1148 *os << "doesn't " << (full_match_ ? "match" : "contain")
1149 << " regular expression ";
1150 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1151 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001152
shiqiane35fdd92008-12-10 05:08:54 +00001153 private:
1154 const internal::linked_ptr<const RE> regex_;
1155 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001156
1157 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001158};
1159
zhanyong.wane122e452010-01-12 09:03:52 +00001160template <typename T>
1161bool MatchAndExplain(const MatchesRegexMatcher& impl, T& s,
1162 MatchResultListener* /* listener */) {
1163 return impl.Matches(s);
1164}
1165
shiqiane35fdd92008-12-10 05:08:54 +00001166// Implements a matcher that compares the two fields of a 2-tuple
1167// using one of the ==, <=, <, etc, operators. The two fields being
1168// compared don't have to have the same type.
1169//
1170// The matcher defined here is polymorphic (for example, Eq() can be
1171// used to match a tuple<int, short>, a tuple<const long&, double>,
1172// etc). Therefore we use a template type conversion operator in the
1173// implementation.
1174//
1175// We define this as a macro in order to eliminate duplicated source
1176// code.
zhanyong.wan2661c682009-06-09 05:42:12 +00001177#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op) \
shiqiane35fdd92008-12-10 05:08:54 +00001178 class name##2Matcher { \
1179 public: \
1180 template <typename T1, typename T2> \
1181 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
1182 return MakeMatcher(new Impl<T1, T2>); \
1183 } \
1184 private: \
1185 template <typename T1, typename T2> \
1186 class Impl : public MatcherInterface<const ::std::tr1::tuple<T1, T2>&> { \
1187 public: \
zhanyong.wan82113312010-01-08 21:55:40 +00001188 virtual bool MatchAndExplain( \
1189 const ::std::tr1::tuple<T1, T2>& args, \
1190 MatchResultListener* /* listener */) const { \
shiqiane35fdd92008-12-10 05:08:54 +00001191 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
1192 } \
1193 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +00001194 *os << "are a pair (x, y) where x " #op " y"; \
shiqiane35fdd92008-12-10 05:08:54 +00001195 } \
1196 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +00001197 *os << "are a pair (x, y) where x " #op " y is false"; \
shiqiane35fdd92008-12-10 05:08:54 +00001198 } \
1199 }; \
1200 }
1201
1202// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wan2661c682009-06-09 05:42:12 +00001203GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==);
1204GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ge, >=);
1205GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Gt, >);
1206GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Le, <=);
1207GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Lt, <);
1208GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=);
shiqiane35fdd92008-12-10 05:08:54 +00001209
zhanyong.wane0d051e2009-02-19 00:33:37 +00001210#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +00001211
zhanyong.wanc6a41232009-05-13 23:38:40 +00001212// Implements the Not(...) matcher for a particular argument type T.
1213// We do not nest it inside the NotMatcher class template, as that
1214// will prevent different instantiations of NotMatcher from sharing
1215// the same NotMatcherImpl<T> class.
1216template <typename T>
1217class NotMatcherImpl : public MatcherInterface<T> {
1218 public:
1219 explicit NotMatcherImpl(const Matcher<T>& matcher)
1220 : matcher_(matcher) {}
1221
zhanyong.wan82113312010-01-08 21:55:40 +00001222 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1223 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001224 }
1225
1226 virtual void DescribeTo(::std::ostream* os) const {
1227 matcher_.DescribeNegationTo(os);
1228 }
1229
1230 virtual void DescribeNegationTo(::std::ostream* os) const {
1231 matcher_.DescribeTo(os);
1232 }
1233
zhanyong.wanc6a41232009-05-13 23:38:40 +00001234 private:
1235 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001236
1237 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001238};
1239
shiqiane35fdd92008-12-10 05:08:54 +00001240// Implements the Not(m) matcher, which matches a value that doesn't
1241// match matcher m.
1242template <typename InnerMatcher>
1243class NotMatcher {
1244 public:
1245 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1246
1247 // This template type conversion operator allows Not(m) to be used
1248 // to match any type m can match.
1249 template <typename T>
1250 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001251 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001252 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001253
shiqiane35fdd92008-12-10 05:08:54 +00001254 private:
shiqiane35fdd92008-12-10 05:08:54 +00001255 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001256
1257 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001258};
1259
zhanyong.wanc6a41232009-05-13 23:38:40 +00001260// Implements the AllOf(m1, m2) matcher for a particular argument type
1261// T. We do not nest it inside the BothOfMatcher class template, as
1262// that will prevent different instantiations of BothOfMatcher from
1263// sharing the same BothOfMatcherImpl<T> class.
1264template <typename T>
1265class BothOfMatcherImpl : public MatcherInterface<T> {
1266 public:
1267 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1268 : matcher1_(matcher1), matcher2_(matcher2) {}
1269
zhanyong.wanc6a41232009-05-13 23:38:40 +00001270 virtual void DescribeTo(::std::ostream* os) const {
1271 *os << "(";
1272 matcher1_.DescribeTo(os);
1273 *os << ") and (";
1274 matcher2_.DescribeTo(os);
1275 *os << ")";
1276 }
1277
1278 virtual void DescribeNegationTo(::std::ostream* os) const {
1279 *os << "not ";
1280 DescribeTo(os);
1281 }
1282
zhanyong.wan82113312010-01-08 21:55:40 +00001283 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1284 // If either matcher1_ or matcher2_ doesn't match x, we only need
1285 // to explain why one of them fails.
1286 StringMatchResultListener listener1;
1287 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1288 *listener << listener1.str();
1289 return false;
1290 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001291
zhanyong.wan82113312010-01-08 21:55:40 +00001292 StringMatchResultListener listener2;
1293 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1294 *listener << listener2.str();
1295 return false;
1296 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001297
zhanyong.wan82113312010-01-08 21:55:40 +00001298 // Otherwise we need to explain why *both* of them match.
1299 const internal::string s1 = listener1.str();
1300 const internal::string s2 = listener2.str();
1301
1302 if (s1 == "") {
1303 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001304 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001305 *listener << s1;
1306 if (s2 != "") {
1307 *listener << "; " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001308 }
1309 }
zhanyong.wan82113312010-01-08 21:55:40 +00001310 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001311 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001312
zhanyong.wanc6a41232009-05-13 23:38:40 +00001313 private:
1314 const Matcher<T> matcher1_;
1315 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001316
1317 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001318};
1319
shiqiane35fdd92008-12-10 05:08:54 +00001320// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1321// matches a value that matches all of the matchers m_1, ..., and m_n.
1322template <typename Matcher1, typename Matcher2>
1323class BothOfMatcher {
1324 public:
1325 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1326 : matcher1_(matcher1), matcher2_(matcher2) {}
1327
1328 // This template type conversion operator allows a
1329 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1330 // both Matcher1 and Matcher2 can match.
1331 template <typename T>
1332 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001333 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1334 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001335 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001336
shiqiane35fdd92008-12-10 05:08:54 +00001337 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001338 Matcher1 matcher1_;
1339 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001340
1341 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001342};
shiqiane35fdd92008-12-10 05:08:54 +00001343
zhanyong.wanc6a41232009-05-13 23:38:40 +00001344// Implements the AnyOf(m1, m2) matcher for a particular argument type
1345// T. We do not nest it inside the AnyOfMatcher class template, as
1346// that will prevent different instantiations of AnyOfMatcher from
1347// sharing the same EitherOfMatcherImpl<T> class.
1348template <typename T>
1349class EitherOfMatcherImpl : public MatcherInterface<T> {
1350 public:
1351 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1352 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001353
zhanyong.wanc6a41232009-05-13 23:38:40 +00001354 virtual void DescribeTo(::std::ostream* os) const {
1355 *os << "(";
1356 matcher1_.DescribeTo(os);
1357 *os << ") or (";
1358 matcher2_.DescribeTo(os);
1359 *os << ")";
1360 }
shiqiane35fdd92008-12-10 05:08:54 +00001361
zhanyong.wanc6a41232009-05-13 23:38:40 +00001362 virtual void DescribeNegationTo(::std::ostream* os) const {
1363 *os << "not ";
1364 DescribeTo(os);
1365 }
shiqiane35fdd92008-12-10 05:08:54 +00001366
zhanyong.wan82113312010-01-08 21:55:40 +00001367 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1368 // If either matcher1_ or matcher2_ matches x, we just need to
1369 // explain why *one* of them matches.
1370 StringMatchResultListener listener1;
1371 if (matcher1_.MatchAndExplain(x, &listener1)) {
1372 *listener << listener1.str();
1373 return true;
1374 }
1375
1376 StringMatchResultListener listener2;
1377 if (matcher2_.MatchAndExplain(x, &listener2)) {
1378 *listener << listener2.str();
1379 return true;
1380 }
1381
1382 // Otherwise we need to explain why *both* of them fail.
1383 const internal::string s1 = listener1.str();
1384 const internal::string s2 = listener2.str();
1385
1386 if (s1 == "") {
1387 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001388 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001389 *listener << s1;
1390 if (s2 != "") {
1391 *listener << "; " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001392 }
1393 }
zhanyong.wan82113312010-01-08 21:55:40 +00001394 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001395 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001396
zhanyong.wanc6a41232009-05-13 23:38:40 +00001397 private:
1398 const Matcher<T> matcher1_;
1399 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001400
1401 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001402};
1403
1404// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1405// matches a value that matches at least one of the matchers m_1, ...,
1406// and m_n.
1407template <typename Matcher1, typename Matcher2>
1408class EitherOfMatcher {
1409 public:
1410 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1411 : matcher1_(matcher1), matcher2_(matcher2) {}
1412
1413 // This template type conversion operator allows a
1414 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1415 // both Matcher1 and Matcher2 can match.
1416 template <typename T>
1417 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001418 return Matcher<T>(new EitherOfMatcherImpl<T>(
1419 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001420 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001421
shiqiane35fdd92008-12-10 05:08:54 +00001422 private:
shiqiane35fdd92008-12-10 05:08:54 +00001423 Matcher1 matcher1_;
1424 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001425
1426 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001427};
1428
1429// Used for implementing Truly(pred), which turns a predicate into a
1430// matcher.
1431template <typename Predicate>
1432class TrulyMatcher {
1433 public:
1434 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1435
1436 // This method template allows Truly(pred) to be used as a matcher
1437 // for type T where T is the argument type of predicate 'pred'. The
1438 // argument is passed by reference as the predicate may be
1439 // interested in the address of the argument.
1440 template <typename T>
zhanyong.wan16cf4732009-05-14 20:55:30 +00001441 bool Matches(T& x) const { // NOLINT
zhanyong.wan652540a2009-02-23 23:37:29 +00001442#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001443 // MSVC warns about converting a value into bool (warning 4800).
1444#pragma warning(push) // Saves the current warning state.
1445#pragma warning(disable:4800) // Temporarily disables warning 4800.
1446#endif // GTEST_OS_WINDOWS
1447 return predicate_(x);
zhanyong.wan652540a2009-02-23 23:37:29 +00001448#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001449#pragma warning(pop) // Restores the warning state.
1450#endif // GTEST_OS_WINDOWS
1451 }
1452
1453 void DescribeTo(::std::ostream* os) const {
1454 *os << "satisfies the given predicate";
1455 }
1456
1457 void DescribeNegationTo(::std::ostream* os) const {
1458 *os << "doesn't satisfy the given predicate";
1459 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001460
shiqiane35fdd92008-12-10 05:08:54 +00001461 private:
1462 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001463
1464 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001465};
1466
zhanyong.wane122e452010-01-12 09:03:52 +00001467template <typename Predicate, typename T>
1468bool MatchAndExplain(const TrulyMatcher<Predicate>& impl, T& x,
1469 MatchResultListener* /* listener */) {
1470 return impl.Matches(x);
1471}
1472
shiqiane35fdd92008-12-10 05:08:54 +00001473// Used for implementing Matches(matcher), which turns a matcher into
1474// a predicate.
1475template <typename M>
1476class MatcherAsPredicate {
1477 public:
1478 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1479
1480 // This template operator() allows Matches(m) to be used as a
1481 // predicate on type T where m is a matcher on type T.
1482 //
1483 // The argument x is passed by reference instead of by value, as
1484 // some matcher may be interested in its address (e.g. as in
1485 // Matches(Ref(n))(x)).
1486 template <typename T>
1487 bool operator()(const T& x) const {
1488 // We let matcher_ commit to a particular type here instead of
1489 // when the MatcherAsPredicate object was constructed. This
1490 // allows us to write Matches(m) where m is a polymorphic matcher
1491 // (e.g. Eq(5)).
1492 //
1493 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1494 // compile when matcher_ has type Matcher<const T&>; if we write
1495 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1496 // when matcher_ has type Matcher<T>; if we just write
1497 // matcher_.Matches(x), it won't compile when matcher_ is
1498 // polymorphic, e.g. Eq(5).
1499 //
1500 // MatcherCast<const T&>() is necessary for making the code work
1501 // in all of the above situations.
1502 return MatcherCast<const T&>(matcher_).Matches(x);
1503 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001504
shiqiane35fdd92008-12-10 05:08:54 +00001505 private:
1506 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001507
1508 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001509};
1510
1511// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1512// argument M must be a type that can be converted to a matcher.
1513template <typename M>
1514class PredicateFormatterFromMatcher {
1515 public:
1516 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1517
1518 // This template () operator allows a PredicateFormatterFromMatcher
1519 // object to act as a predicate-formatter suitable for using with
1520 // Google Test's EXPECT_PRED_FORMAT1() macro.
1521 template <typename T>
1522 AssertionResult operator()(const char* value_text, const T& x) const {
1523 // We convert matcher_ to a Matcher<const T&> *now* instead of
1524 // when the PredicateFormatterFromMatcher object was constructed,
1525 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1526 // know which type to instantiate it to until we actually see the
1527 // type of x here.
1528 //
1529 // We write MatcherCast<const T&>(matcher_) instead of
1530 // Matcher<const T&>(matcher_), as the latter won't compile when
1531 // matcher_ has type Matcher<T> (e.g. An<int>()).
1532 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001533 StringMatchResultListener listener;
1534 if (matcher.MatchAndExplain(x, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +00001535 return AssertionSuccess();
1536 } else {
1537 ::std::stringstream ss;
1538 ss << "Value of: " << value_text << "\n"
1539 << "Expected: ";
1540 matcher.DescribeTo(&ss);
1541 ss << "\n Actual: ";
1542 UniversalPrinter<T>::Print(x, &ss);
zhanyong.wan82113312010-01-08 21:55:40 +00001543 StreamInParensAsNeeded(listener.str(), &ss);
shiqiane35fdd92008-12-10 05:08:54 +00001544 return AssertionFailure(Message() << ss.str());
1545 }
1546 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001547
shiqiane35fdd92008-12-10 05:08:54 +00001548 private:
1549 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001550
1551 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001552};
1553
1554// A helper function for converting a matcher to a predicate-formatter
1555// without the user needing to explicitly write the type. This is
1556// used for implementing ASSERT_THAT() and EXPECT_THAT().
1557template <typename M>
1558inline PredicateFormatterFromMatcher<M>
1559MakePredicateFormatterFromMatcher(const M& matcher) {
1560 return PredicateFormatterFromMatcher<M>(matcher);
1561}
1562
1563// Implements the polymorphic floating point equality matcher, which
1564// matches two float values using ULP-based approximation. The
1565// template is meant to be instantiated with FloatType being either
1566// float or double.
1567template <typename FloatType>
1568class FloatingEqMatcher {
1569 public:
1570 // Constructor for FloatingEqMatcher.
1571 // The matcher's input will be compared with rhs. The matcher treats two
1572 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1573 // equality comparisons between NANs will always return false.
1574 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1575 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1576
1577 // Implements floating point equality matcher as a Matcher<T>.
1578 template <typename T>
1579 class Impl : public MatcherInterface<T> {
1580 public:
1581 Impl(FloatType rhs, bool nan_eq_nan) :
1582 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1583
zhanyong.wan82113312010-01-08 21:55:40 +00001584 virtual bool MatchAndExplain(T value,
1585 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001586 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1587
1588 // Compares NaNs first, if nan_eq_nan_ is true.
1589 if (nan_eq_nan_ && lhs.is_nan()) {
1590 return rhs.is_nan();
1591 }
1592
1593 return lhs.AlmostEquals(rhs);
1594 }
1595
1596 virtual void DescribeTo(::std::ostream* os) const {
1597 // os->precision() returns the previously set precision, which we
1598 // store to restore the ostream to its original configuration
1599 // after outputting.
1600 const ::std::streamsize old_precision = os->precision(
1601 ::std::numeric_limits<FloatType>::digits10 + 2);
1602 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1603 if (nan_eq_nan_) {
1604 *os << "is NaN";
1605 } else {
1606 *os << "never matches";
1607 }
1608 } else {
1609 *os << "is approximately " << rhs_;
1610 }
1611 os->precision(old_precision);
1612 }
1613
1614 virtual void DescribeNegationTo(::std::ostream* os) const {
1615 // As before, get original precision.
1616 const ::std::streamsize old_precision = os->precision(
1617 ::std::numeric_limits<FloatType>::digits10 + 2);
1618 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1619 if (nan_eq_nan_) {
1620 *os << "is not NaN";
1621 } else {
1622 *os << "is anything";
1623 }
1624 } else {
1625 *os << "is not approximately " << rhs_;
1626 }
1627 // Restore original precision.
1628 os->precision(old_precision);
1629 }
1630
1631 private:
1632 const FloatType rhs_;
1633 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001634
1635 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001636 };
1637
1638 // The following 3 type conversion operators allow FloatEq(rhs) and
1639 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1640 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1641 // (While Google's C++ coding style doesn't allow arguments passed
1642 // by non-const reference, we may see them in code not conforming to
1643 // the style. Therefore Google Mock needs to support them.)
1644 operator Matcher<FloatType>() const {
1645 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1646 }
1647
1648 operator Matcher<const FloatType&>() const {
1649 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1650 }
1651
1652 operator Matcher<FloatType&>() const {
1653 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1654 }
1655 private:
1656 const FloatType rhs_;
1657 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001658
1659 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001660};
1661
1662// Implements the Pointee(m) matcher for matching a pointer whose
1663// pointee matches matcher m. The pointer can be either raw or smart.
1664template <typename InnerMatcher>
1665class PointeeMatcher {
1666 public:
1667 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1668
1669 // This type conversion operator template allows Pointee(m) to be
1670 // used as a matcher for any pointer type whose pointee type is
1671 // compatible with the inner matcher, where type Pointer can be
1672 // either a raw pointer or a smart pointer.
1673 //
1674 // The reason we do this instead of relying on
1675 // MakePolymorphicMatcher() is that the latter is not flexible
1676 // enough for implementing the DescribeTo() method of Pointee().
1677 template <typename Pointer>
1678 operator Matcher<Pointer>() const {
1679 return MakeMatcher(new Impl<Pointer>(matcher_));
1680 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001681
shiqiane35fdd92008-12-10 05:08:54 +00001682 private:
1683 // The monomorphic implementation that works for a particular pointer type.
1684 template <typename Pointer>
1685 class Impl : public MatcherInterface<Pointer> {
1686 public:
zhanyong.wane0d051e2009-02-19 00:33:37 +00001687 typedef typename PointeeOf<GMOCK_REMOVE_CONST_( // NOLINT
1688 GMOCK_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001689
1690 explicit Impl(const InnerMatcher& matcher)
1691 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1692
shiqiane35fdd92008-12-10 05:08:54 +00001693 virtual void DescribeTo(::std::ostream* os) const {
1694 *os << "points to a value that ";
1695 matcher_.DescribeTo(os);
1696 }
1697
1698 virtual void DescribeNegationTo(::std::ostream* os) const {
1699 *os << "does not point to a value that ";
1700 matcher_.DescribeTo(os);
1701 }
1702
zhanyong.wan82113312010-01-08 21:55:40 +00001703 virtual bool MatchAndExplain(Pointer pointer,
1704 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001705 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00001706 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001707
zhanyong.wan82113312010-01-08 21:55:40 +00001708 StringMatchResultListener inner_listener;
1709 const bool match = matcher_.MatchAndExplain(*pointer, &inner_listener);
1710 const internal::string s = inner_listener.str();
shiqiane35fdd92008-12-10 05:08:54 +00001711 if (s != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00001712 *listener << "points to a value that " << s;
shiqiane35fdd92008-12-10 05:08:54 +00001713 }
zhanyong.wan82113312010-01-08 21:55:40 +00001714 return match;
shiqiane35fdd92008-12-10 05:08:54 +00001715 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001716
shiqiane35fdd92008-12-10 05:08:54 +00001717 private:
1718 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001719
1720 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001721 };
1722
1723 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001724
1725 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001726};
1727
1728// Implements the Field() matcher for matching a field (i.e. member
1729// variable) of an object.
1730template <typename Class, typename FieldType>
1731class FieldMatcher {
1732 public:
1733 FieldMatcher(FieldType Class::*field,
1734 const Matcher<const FieldType&>& matcher)
1735 : field_(field), matcher_(matcher) {}
1736
shiqiane35fdd92008-12-10 05:08:54 +00001737 void DescribeTo(::std::ostream* os) const {
1738 *os << "the given field ";
1739 matcher_.DescribeTo(os);
1740 }
1741
1742 void DescribeNegationTo(::std::ostream* os) const {
1743 *os << "the given field ";
1744 matcher_.DescribeNegationTo(os);
1745 }
1746
zhanyong.wan82113312010-01-08 21:55:40 +00001747 // The first argument of MatchAndExplain() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001748 // Symbian's C++ compiler choose which overload to use. Its type is
1749 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wan82113312010-01-08 21:55:40 +00001750 bool MatchAndExplain(false_type /* is_not_pointer */, const Class& obj,
1751 MatchResultListener* listener) const {
1752 StringMatchResultListener inner_listener;
1753 const bool match = matcher_.MatchAndExplain(obj.*field_, &inner_listener);
1754 const internal::string s = inner_listener.str();
shiqiane35fdd92008-12-10 05:08:54 +00001755 if (s != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00001756 *listener << "the given field " << s;
shiqiane35fdd92008-12-10 05:08:54 +00001757 }
zhanyong.wan82113312010-01-08 21:55:40 +00001758 return match;
shiqiane35fdd92008-12-10 05:08:54 +00001759 }
1760
zhanyong.wan82113312010-01-08 21:55:40 +00001761 bool MatchAndExplain(true_type /* is_pointer */, const Class* p,
1762 MatchResultListener* listener) const {
1763 if (p == NULL)
1764 return false;
1765
1766 // Since *p has a field, it must be a class/struct/union type and
1767 // thus cannot be a pointer. Therefore we pass false_type() as
1768 // the first argument.
1769 return MatchAndExplain(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001770 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001771
shiqiane35fdd92008-12-10 05:08:54 +00001772 private:
1773 const FieldType Class::*field_;
1774 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001775
1776 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001777};
1778
zhanyong.wan18490652009-05-11 18:54:08 +00001779template <typename Class, typename FieldType, typename T>
zhanyong.wan82113312010-01-08 21:55:40 +00001780bool MatchAndExplain(const FieldMatcher<Class, FieldType>& matcher,
zhanyong.wane122e452010-01-12 09:03:52 +00001781 T& value, MatchResultListener* listener) {
zhanyong.wan82113312010-01-08 21:55:40 +00001782 return matcher.MatchAndExplain(
zhanyong.wan6953a722010-01-13 05:15:07 +00001783 typename ::testing::internal::is_pointer<GMOCK_REMOVE_CONST_(T)>::type(),
1784 value, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001785}
1786
1787// Implements the Property() matcher for matching a property
1788// (i.e. return value of a getter method) of an object.
1789template <typename Class, typename PropertyType>
1790class PropertyMatcher {
1791 public:
1792 // The property may have a reference type, so 'const PropertyType&'
1793 // may cause double references and fail to compile. That's why we
1794 // need GMOCK_REFERENCE_TO_CONST, which works regardless of
1795 // PropertyType being a reference or not.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001796 typedef GMOCK_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001797
1798 PropertyMatcher(PropertyType (Class::*property)() const,
1799 const Matcher<RefToConstProperty>& matcher)
1800 : property_(property), matcher_(matcher) {}
1801
shiqiane35fdd92008-12-10 05:08:54 +00001802 void DescribeTo(::std::ostream* os) const {
1803 *os << "the given property ";
1804 matcher_.DescribeTo(os);
1805 }
1806
1807 void DescribeNegationTo(::std::ostream* os) const {
1808 *os << "the given property ";
1809 matcher_.DescribeNegationTo(os);
1810 }
1811
zhanyong.wan82113312010-01-08 21:55:40 +00001812 // The first argument of MatchAndExplain() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001813 // Symbian's C++ compiler choose which overload to use. Its type is
1814 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wan82113312010-01-08 21:55:40 +00001815 bool MatchAndExplain(false_type /* is_not_pointer */, const Class& obj,
1816 MatchResultListener* listener) const {
1817 StringMatchResultListener inner_listener;
1818 const bool match = matcher_.MatchAndExplain((obj.*property_)(),
1819 &inner_listener);
1820 const internal::string s = inner_listener.str();
shiqiane35fdd92008-12-10 05:08:54 +00001821 if (s != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00001822 *listener << "the given property " << s;
shiqiane35fdd92008-12-10 05:08:54 +00001823 }
zhanyong.wan82113312010-01-08 21:55:40 +00001824 return match;
shiqiane35fdd92008-12-10 05:08:54 +00001825 }
1826
zhanyong.wan82113312010-01-08 21:55:40 +00001827 bool MatchAndExplain(true_type /* is_pointer */, const Class* p,
1828 MatchResultListener* listener) const {
1829 if (p == NULL)
1830 return false;
1831
1832 // Since *p has a property method, it must be a class/struct/union
1833 // type and thus cannot be a pointer. Therefore we pass
1834 // false_type() as the first argument.
1835 return MatchAndExplain(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001836 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001837
shiqiane35fdd92008-12-10 05:08:54 +00001838 private:
1839 PropertyType (Class::*property_)() const;
1840 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001841
1842 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001843};
1844
zhanyong.wan82113312010-01-08 21:55:40 +00001845template <typename Class, typename PropertyType, typename T>
1846bool MatchAndExplain(const PropertyMatcher<Class, PropertyType>& matcher,
zhanyong.wane122e452010-01-12 09:03:52 +00001847 T& value, MatchResultListener* listener) {
zhanyong.wan82113312010-01-08 21:55:40 +00001848 return matcher.MatchAndExplain(
zhanyong.wan6953a722010-01-13 05:15:07 +00001849 typename ::testing::internal::is_pointer<GMOCK_REMOVE_CONST_(T)>::type(),
1850 value, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001851}
1852
1853// Type traits specifying various features of different functors for ResultOf.
1854// The default template specifies features for functor objects.
1855// Functor classes have to typedef argument_type and result_type
1856// to be compatible with ResultOf.
1857template <typename Functor>
1858struct CallableTraits {
1859 typedef typename Functor::result_type ResultType;
1860 typedef Functor StorageType;
1861
zhanyong.wan32de5f52009-12-23 00:13:23 +00001862 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00001863 template <typename T>
1864 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1865};
1866
1867// Specialization for function pointers.
1868template <typename ArgType, typename ResType>
1869struct CallableTraits<ResType(*)(ArgType)> {
1870 typedef ResType ResultType;
1871 typedef ResType(*StorageType)(ArgType);
1872
1873 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001874 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00001875 << "NULL function pointer is passed into ResultOf().";
1876 }
1877 template <typename T>
1878 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1879 return (*f)(arg);
1880 }
1881};
1882
1883// Implements the ResultOf() matcher for matching a return value of a
1884// unary function of an object.
1885template <typename Callable>
1886class ResultOfMatcher {
1887 public:
1888 typedef typename CallableTraits<Callable>::ResultType ResultType;
1889
1890 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1891 : callable_(callable), matcher_(matcher) {
1892 CallableTraits<Callable>::CheckIsValid(callable_);
1893 }
1894
1895 template <typename T>
1896 operator Matcher<T>() const {
1897 return Matcher<T>(new Impl<T>(callable_, matcher_));
1898 }
1899
1900 private:
1901 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1902
1903 template <typename T>
1904 class Impl : public MatcherInterface<T> {
1905 public:
1906 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1907 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00001908
1909 virtual void DescribeTo(::std::ostream* os) const {
1910 *os << "result of the given callable ";
1911 matcher_.DescribeTo(os);
1912 }
1913
1914 virtual void DescribeNegationTo(::std::ostream* os) const {
1915 *os << "result of the given callable ";
1916 matcher_.DescribeNegationTo(os);
1917 }
1918
zhanyong.wan82113312010-01-08 21:55:40 +00001919 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
1920 StringMatchResultListener inner_listener;
1921 const bool match = matcher_.MatchAndExplain(
shiqiane35fdd92008-12-10 05:08:54 +00001922 CallableTraits<Callable>::template Invoke<T>(callable_, obj),
zhanyong.wan82113312010-01-08 21:55:40 +00001923 &inner_listener);
1924
1925 const internal::string s = inner_listener.str();
shiqiane35fdd92008-12-10 05:08:54 +00001926 if (s != "")
zhanyong.wan82113312010-01-08 21:55:40 +00001927 *listener << "result of the given callable " << s;
1928
1929 return match;
shiqiane35fdd92008-12-10 05:08:54 +00001930 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001931
shiqiane35fdd92008-12-10 05:08:54 +00001932 private:
1933 // Functors often define operator() as non-const method even though
1934 // they are actualy stateless. But we need to use them even when
1935 // 'this' is a const pointer. It's the user's responsibility not to
1936 // use stateful callables with ResultOf(), which does't guarantee
1937 // how many times the callable will be invoked.
1938 mutable CallableStorageType callable_;
1939 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001940
1941 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001942 }; // class Impl
1943
1944 const CallableStorageType callable_;
1945 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001946
1947 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001948};
1949
1950// Explains the result of matching a value against a functor matcher.
1951template <typename T, typename Callable>
1952void ExplainMatchResultTo(const ResultOfMatcher<Callable>& matcher,
1953 T obj, ::std::ostream* os) {
1954 matcher.ExplainMatchResultTo(obj, os);
1955}
1956
zhanyong.wan6a896b52009-01-16 01:13:50 +00001957// Implements an equality matcher for any STL-style container whose elements
1958// support ==. This matcher is like Eq(), but its failure explanations provide
1959// more detailed information that is useful when the container is used as a set.
1960// The failure message reports elements that are in one of the operands but not
1961// the other. The failure messages do not report duplicate or out-of-order
1962// elements in the containers (which don't properly matter to sets, but can
1963// occur if the containers are vectors or lists, for example).
1964//
1965// Uses the container's const_iterator, value_type, operator ==,
1966// begin(), and end().
1967template <typename Container>
1968class ContainerEqMatcher {
1969 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00001970 typedef internal::StlContainerView<Container> View;
1971 typedef typename View::type StlContainer;
1972 typedef typename View::const_reference StlContainerReference;
1973
1974 // We make a copy of rhs in case the elements in it are modified
1975 // after this matcher is created.
1976 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
1977 // Makes sure the user doesn't instantiate this class template
1978 // with a const or reference type.
1979 testing::StaticAssertTypeEq<Container,
1980 GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))>();
1981 }
1982
zhanyong.wan6a896b52009-01-16 01:13:50 +00001983 void DescribeTo(::std::ostream* os) const {
1984 *os << "equals ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001985 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001986 }
1987 void DescribeNegationTo(::std::ostream* os) const {
1988 *os << "does not equal ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001989 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001990 }
1991
zhanyong.wanb8243162009-06-04 05:48:20 +00001992 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00001993 bool MatchAndExplain(const LhsContainer& lhs,
1994 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00001995 // GMOCK_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
1996 // that causes LhsContainer to be a const type sometimes.
1997 typedef internal::StlContainerView<GMOCK_REMOVE_CONST_(LhsContainer)>
1998 LhsView;
1999 typedef typename LhsView::type LhsStlContainer;
2000 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00002001 if (lhs_stl_container == rhs_)
2002 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002003
zhanyong.wane122e452010-01-12 09:03:52 +00002004 ::std::ostream* const os = listener->stream();
2005 if (os != NULL) {
2006 // Something is different. Check for missing values first.
2007 bool printed_header = false;
2008 for (typename LhsStlContainer::const_iterator it =
2009 lhs_stl_container.begin();
2010 it != lhs_stl_container.end(); ++it) {
2011 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
2012 rhs_.end()) {
2013 if (printed_header) {
2014 *os << ", ";
2015 } else {
2016 *os << "Only in actual: ";
2017 printed_header = true;
2018 }
zhanyong.wan6953a722010-01-13 05:15:07 +00002019 UniversalPrinter<typename LhsStlContainer::value_type>::
2020 Print(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002021 }
zhanyong.wane122e452010-01-12 09:03:52 +00002022 }
2023
2024 // Now check for extra values.
2025 bool printed_header2 = false;
2026 for (typename StlContainer::const_iterator it = rhs_.begin();
2027 it != rhs_.end(); ++it) {
2028 if (internal::ArrayAwareFind(
2029 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2030 lhs_stl_container.end()) {
2031 if (printed_header2) {
2032 *os << ", ";
2033 } else {
2034 *os << (printed_header ? "; not" : "Not") << " in actual: ";
2035 printed_header2 = true;
2036 }
2037 UniversalPrinter<typename StlContainer::value_type>::Print(*it, os);
2038 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002039 }
2040 }
2041
zhanyong.wane122e452010-01-12 09:03:52 +00002042 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002043 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002044
zhanyong.wan6a896b52009-01-16 01:13:50 +00002045 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00002046 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002047
2048 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002049};
2050
zhanyong.wanb8243162009-06-04 05:48:20 +00002051template <typename LhsContainer, typename Container>
zhanyong.wane122e452010-01-12 09:03:52 +00002052bool MatchAndExplain(const ContainerEqMatcher<Container>& matcher,
2053 LhsContainer& lhs,
2054 MatchResultListener* listener) {
2055 return matcher.MatchAndExplain(lhs, listener);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002056}
2057
zhanyong.wanb8243162009-06-04 05:48:20 +00002058// Implements Contains(element_matcher) for the given argument type Container.
2059template <typename Container>
2060class ContainsMatcherImpl : public MatcherInterface<Container> {
2061 public:
2062 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
2063 typedef StlContainerView<RawContainer> View;
2064 typedef typename View::type StlContainer;
2065 typedef typename View::const_reference StlContainerReference;
2066 typedef typename StlContainer::value_type Element;
2067
2068 template <typename InnerMatcher>
2069 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2070 : inner_matcher_(
2071 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
2072
zhanyong.wanb8243162009-06-04 05:48:20 +00002073 // Describes what this matcher does.
2074 virtual void DescribeTo(::std::ostream* os) const {
2075 *os << "contains at least one element that ";
2076 inner_matcher_.DescribeTo(os);
2077 }
2078
2079 // Describes what the negation of this matcher does.
2080 virtual void DescribeNegationTo(::std::ostream* os) const {
2081 *os << "doesn't contain any element that ";
2082 inner_matcher_.DescribeTo(os);
2083 }
2084
zhanyong.wan82113312010-01-08 21:55:40 +00002085 virtual bool MatchAndExplain(Container container,
2086 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002087 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002088 size_t i = 0;
2089 for (typename StlContainer::const_iterator it = stl_container.begin();
2090 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002091 if (inner_matcher_.Matches(*it)) {
zhanyong.wan82113312010-01-08 21:55:40 +00002092 *listener << "element " << i << " matches";
2093 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002094 }
2095 }
zhanyong.wan82113312010-01-08 21:55:40 +00002096 return false;
zhanyong.wanb8243162009-06-04 05:48:20 +00002097 }
2098
2099 private:
2100 const Matcher<const Element&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002101
2102 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002103};
2104
2105// Implements polymorphic Contains(element_matcher).
2106template <typename M>
2107class ContainsMatcher {
2108 public:
2109 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2110
2111 template <typename Container>
2112 operator Matcher<Container>() const {
2113 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2114 }
2115
2116 private:
2117 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002118
2119 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002120};
2121
zhanyong.wanb5937da2009-07-16 20:26:41 +00002122// Implements Key(inner_matcher) for the given argument pair type.
2123// Key(inner_matcher) matches an std::pair whose 'first' field matches
2124// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2125// std::map that contains at least one element whose key is >= 5.
2126template <typename PairType>
2127class KeyMatcherImpl : public MatcherInterface<PairType> {
2128 public:
2129 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
2130 typedef typename RawPairType::first_type KeyType;
2131
2132 template <typename InnerMatcher>
2133 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2134 : inner_matcher_(
2135 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2136 }
2137
2138 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002139 virtual bool MatchAndExplain(PairType key_value,
2140 MatchResultListener* listener) const {
2141 return inner_matcher_.MatchAndExplain(key_value.first, listener);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002142 }
2143
2144 // Describes what this matcher does.
2145 virtual void DescribeTo(::std::ostream* os) const {
2146 *os << "has a key that ";
2147 inner_matcher_.DescribeTo(os);
2148 }
2149
2150 // Describes what the negation of this matcher does.
2151 virtual void DescribeNegationTo(::std::ostream* os) const {
2152 *os << "doesn't have a key that ";
2153 inner_matcher_.DescribeTo(os);
2154 }
2155
zhanyong.wanb5937da2009-07-16 20:26:41 +00002156 private:
2157 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002158
2159 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002160};
2161
2162// Implements polymorphic Key(matcher_for_key).
2163template <typename M>
2164class KeyMatcher {
2165 public:
2166 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2167
2168 template <typename PairType>
2169 operator Matcher<PairType>() const {
2170 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2171 }
2172
2173 private:
2174 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002175
2176 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002177};
2178
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002179// Implements Pair(first_matcher, second_matcher) for the given argument pair
2180// type with its two matchers. See Pair() function below.
2181template <typename PairType>
2182class PairMatcherImpl : public MatcherInterface<PairType> {
2183 public:
2184 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
2185 typedef typename RawPairType::first_type FirstType;
2186 typedef typename RawPairType::second_type SecondType;
2187
2188 template <typename FirstMatcher, typename SecondMatcher>
2189 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2190 : first_matcher_(
2191 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2192 second_matcher_(
2193 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2194 }
2195
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002196 // Describes what this matcher does.
2197 virtual void DescribeTo(::std::ostream* os) const {
2198 *os << "has a first field that ";
2199 first_matcher_.DescribeTo(os);
2200 *os << ", and has a second field that ";
2201 second_matcher_.DescribeTo(os);
2202 }
2203
2204 // Describes what the negation of this matcher does.
2205 virtual void DescribeNegationTo(::std::ostream* os) const {
2206 *os << "has a first field that ";
2207 first_matcher_.DescribeNegationTo(os);
2208 *os << ", or has a second field that ";
2209 second_matcher_.DescribeNegationTo(os);
2210 }
2211
zhanyong.wan82113312010-01-08 21:55:40 +00002212 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2213 // matches second_matcher.
2214 virtual bool MatchAndExplain(PairType a_pair,
2215 MatchResultListener* listener) const {
2216 StringMatchResultListener listener1;
2217 const bool match1 = first_matcher_.MatchAndExplain(a_pair.first,
2218 &listener1);
2219 internal::string s1 = listener1.str();
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002220 if (s1 != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00002221 s1 = "the first field " + s1;
2222 }
2223 if (!match1) {
2224 *listener << s1;
2225 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002226 }
2227
zhanyong.wan82113312010-01-08 21:55:40 +00002228 StringMatchResultListener listener2;
2229 const bool match2 = second_matcher_.MatchAndExplain(a_pair.second,
2230 &listener2);
2231 internal::string s2 = listener2.str();
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002232 if (s2 != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00002233 s2 = "the second field " + s2;
2234 }
2235 if (!match2) {
2236 *listener << s2;
2237 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002238 }
2239
zhanyong.wan82113312010-01-08 21:55:40 +00002240 *listener << s1;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002241 if (s1 != "" && s2 != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00002242 *listener << ", and ";
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002243 }
zhanyong.wan82113312010-01-08 21:55:40 +00002244 *listener << s2;
2245 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002246 }
2247
2248 private:
2249 const Matcher<const FirstType&> first_matcher_;
2250 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002251
2252 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002253};
2254
2255// Implements polymorphic Pair(first_matcher, second_matcher).
2256template <typename FirstMatcher, typename SecondMatcher>
2257class PairMatcher {
2258 public:
2259 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2260 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2261
2262 template <typename PairType>
2263 operator Matcher<PairType> () const {
2264 return MakeMatcher(
2265 new PairMatcherImpl<PairType>(
2266 first_matcher_, second_matcher_));
2267 }
2268
2269 private:
2270 const FirstMatcher first_matcher_;
2271 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002272
2273 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002274};
2275
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002276// Implements ElementsAre() and ElementsAreArray().
2277template <typename Container>
2278class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2279 public:
2280 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
2281 typedef internal::StlContainerView<RawContainer> View;
2282 typedef typename View::type StlContainer;
2283 typedef typename View::const_reference StlContainerReference;
2284 typedef typename StlContainer::value_type Element;
2285
2286 // Constructs the matcher from a sequence of element values or
2287 // element matchers.
2288 template <typename InputIter>
zhanyong.wan32de5f52009-12-23 00:13:23 +00002289 ElementsAreMatcherImpl(InputIter first, size_t a_count) {
2290 matchers_.reserve(a_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002291 InputIter it = first;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002292 for (size_t i = 0; i != a_count; ++i, ++it) {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002293 matchers_.push_back(MatcherCast<const Element&>(*it));
2294 }
2295 }
2296
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002297 // Describes what this matcher does.
2298 virtual void DescribeTo(::std::ostream* os) const {
2299 if (count() == 0) {
2300 *os << "is empty";
2301 } else if (count() == 1) {
2302 *os << "has 1 element that ";
2303 matchers_[0].DescribeTo(os);
2304 } else {
2305 *os << "has " << Elements(count()) << " where\n";
2306 for (size_t i = 0; i != count(); ++i) {
2307 *os << "element " << i << " ";
2308 matchers_[i].DescribeTo(os);
2309 if (i + 1 < count()) {
2310 *os << ",\n";
2311 }
2312 }
2313 }
2314 }
2315
2316 // Describes what the negation of this matcher does.
2317 virtual void DescribeNegationTo(::std::ostream* os) const {
2318 if (count() == 0) {
2319 *os << "is not empty";
2320 return;
2321 }
2322
2323 *os << "does not have " << Elements(count()) << ", or\n";
2324 for (size_t i = 0; i != count(); ++i) {
2325 *os << "element " << i << " ";
2326 matchers_[i].DescribeNegationTo(os);
2327 if (i + 1 < count()) {
2328 *os << ", or\n";
2329 }
2330 }
2331 }
2332
zhanyong.wan82113312010-01-08 21:55:40 +00002333 virtual bool MatchAndExplain(Container container,
2334 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002335 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002336 const size_t actual_count = stl_container.size();
2337 if (actual_count != count()) {
2338 // The element count doesn't match. If the container is empty,
2339 // there's no need to explain anything as Google Mock already
2340 // prints the empty container. Otherwise we just need to show
2341 // how many elements there actually are.
2342 if (actual_count != 0) {
2343 *listener << "has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002344 }
zhanyong.wan82113312010-01-08 21:55:40 +00002345 return false;
2346 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002347
zhanyong.wan82113312010-01-08 21:55:40 +00002348 typename StlContainer::const_iterator it = stl_container.begin();
2349 // explanations[i] is the explanation of the element at index i.
2350 std::vector<internal::string> explanations(count());
2351 for (size_t i = 0; i != count(); ++it, ++i) {
2352 StringMatchResultListener s;
2353 if (matchers_[i].MatchAndExplain(*it, &s)) {
2354 explanations[i] = s.str();
2355 } else {
2356 // The container has the right size but the i-th element
2357 // doesn't match its expectation.
2358 *listener << "element " << i << " doesn't match";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002359
zhanyong.wan82113312010-01-08 21:55:40 +00002360 StreamInParensAsNeeded(s.str(), listener->stream());
2361 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002362 }
2363 }
zhanyong.wan82113312010-01-08 21:55:40 +00002364
2365 // Every element matches its expectation. We need to explain why
2366 // (the obvious ones can be skipped).
2367
2368 bool reason_printed = false;
2369 for (size_t i = 0; i != count(); ++i) {
2370 const internal::string& s = explanations[i];
2371 if (!s.empty()) {
2372 if (reason_printed) {
2373 *listener << ",\n";
2374 }
2375 *listener << "element " << i << " " << s;
2376 reason_printed = true;
2377 }
2378 }
2379
2380 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002381 }
2382
2383 private:
2384 static Message Elements(size_t count) {
2385 return Message() << count << (count == 1 ? " element" : " elements");
2386 }
2387
2388 size_t count() const { return matchers_.size(); }
2389 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002390
2391 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002392};
2393
2394// Implements ElementsAre() of 0 arguments.
2395class ElementsAreMatcher0 {
2396 public:
2397 ElementsAreMatcher0() {}
2398
2399 template <typename Container>
2400 operator Matcher<Container>() const {
2401 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2402 RawContainer;
2403 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2404 Element;
2405
2406 const Matcher<const Element&>* const matchers = NULL;
2407 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 0));
2408 }
2409};
2410
2411// Implements ElementsAreArray().
2412template <typename T>
2413class ElementsAreArrayMatcher {
2414 public:
2415 ElementsAreArrayMatcher(const T* first, size_t count) :
2416 first_(first), count_(count) {}
2417
2418 template <typename Container>
2419 operator Matcher<Container>() const {
2420 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2421 RawContainer;
2422 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2423 Element;
2424
2425 return MakeMatcher(new ElementsAreMatcherImpl<Container>(first_, count_));
2426 }
2427
2428 private:
2429 const T* const first_;
2430 const size_t count_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002431
2432 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002433};
2434
2435// Constants denoting interpolations in a matcher description string.
2436const int kTupleInterpolation = -1; // "%(*)s"
2437const int kPercentInterpolation = -2; // "%%"
2438const int kInvalidInterpolation = -3; // "%" followed by invalid text
2439
2440// Records the location and content of an interpolation.
2441struct Interpolation {
2442 Interpolation(const char* start, const char* end, int param)
2443 : start_pos(start), end_pos(end), param_index(param) {}
2444
2445 // Points to the start of the interpolation (the '%' character).
2446 const char* start_pos;
2447 // Points to the first character after the interpolation.
2448 const char* end_pos;
2449 // 0-based index of the interpolated matcher parameter;
2450 // kTupleInterpolation for "%(*)s"; kPercentInterpolation for "%%".
2451 int param_index;
2452};
2453
2454typedef ::std::vector<Interpolation> Interpolations;
2455
2456// Parses a matcher description string and returns a vector of
2457// interpolations that appear in the string; generates non-fatal
2458// failures iff 'description' is an invalid matcher description.
2459// 'param_names' is a NULL-terminated array of parameter names in the
2460// order they appear in the MATCHER_P*() parameter list.
2461Interpolations ValidateMatcherDescription(
2462 const char* param_names[], const char* description);
2463
2464// Returns the actual matcher description, given the matcher name,
2465// user-supplied description template string, interpolations in the
2466// string, and the printed values of the matcher parameters.
2467string FormatMatcherDescription(
2468 const char* matcher_name, const char* description,
2469 const Interpolations& interp, const Strings& param_values);
2470
shiqiane35fdd92008-12-10 05:08:54 +00002471} // namespace internal
2472
2473// Implements MatcherCast().
2474template <typename T, typename M>
2475inline Matcher<T> MatcherCast(M matcher) {
2476 return internal::MatcherCastImpl<T, M>::Cast(matcher);
2477}
2478
2479// _ is a matcher that matches anything of any type.
2480//
2481// This definition is fine as:
2482//
2483// 1. The C++ standard permits using the name _ in a namespace that
2484// is not the global namespace or ::std.
2485// 2. The AnythingMatcher class has no data member or constructor,
2486// so it's OK to create global variables of this type.
2487// 3. c-style has approved of using _ in this case.
2488const internal::AnythingMatcher _ = {};
2489// Creates a matcher that matches any value of the given type T.
2490template <typename T>
2491inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2492
2493// Creates a matcher that matches any value of the given type T.
2494template <typename T>
2495inline Matcher<T> An() { return A<T>(); }
2496
2497// Creates a polymorphic matcher that matches anything equal to x.
2498// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2499// wouldn't compile.
2500template <typename T>
2501inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2502
2503// Constructs a Matcher<T> from a 'value' of type T. The constructed
2504// matcher matches any value that's equal to 'value'.
2505template <typename T>
2506Matcher<T>::Matcher(T value) { *this = Eq(value); }
2507
2508// Creates a monomorphic matcher that matches anything with type Lhs
2509// and equal to rhs. A user may need to use this instead of Eq(...)
2510// in order to resolve an overloading ambiguity.
2511//
2512// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2513// or Matcher<T>(x), but more readable than the latter.
2514//
2515// We could define similar monomorphic matchers for other comparison
2516// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2517// it yet as those are used much less than Eq() in practice. A user
2518// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2519// for example.
2520template <typename Lhs, typename Rhs>
2521inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2522
2523// Creates a polymorphic matcher that matches anything >= x.
2524template <typename Rhs>
2525inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2526 return internal::GeMatcher<Rhs>(x);
2527}
2528
2529// Creates a polymorphic matcher that matches anything > x.
2530template <typename Rhs>
2531inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2532 return internal::GtMatcher<Rhs>(x);
2533}
2534
2535// Creates a polymorphic matcher that matches anything <= x.
2536template <typename Rhs>
2537inline internal::LeMatcher<Rhs> Le(Rhs x) {
2538 return internal::LeMatcher<Rhs>(x);
2539}
2540
2541// Creates a polymorphic matcher that matches anything < x.
2542template <typename Rhs>
2543inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2544 return internal::LtMatcher<Rhs>(x);
2545}
2546
2547// Creates a polymorphic matcher that matches anything != x.
2548template <typename Rhs>
2549inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2550 return internal::NeMatcher<Rhs>(x);
2551}
2552
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002553// Creates a polymorphic matcher that matches any NULL pointer.
2554inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2555 return MakePolymorphicMatcher(internal::IsNullMatcher());
2556}
2557
shiqiane35fdd92008-12-10 05:08:54 +00002558// Creates a polymorphic matcher that matches any non-NULL pointer.
2559// This is convenient as Not(NULL) doesn't compile (the compiler
2560// thinks that that expression is comparing a pointer with an integer).
2561inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2562 return MakePolymorphicMatcher(internal::NotNullMatcher());
2563}
2564
2565// Creates a polymorphic matcher that matches any argument that
2566// references variable x.
2567template <typename T>
2568inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2569 return internal::RefMatcher<T&>(x);
2570}
2571
2572// Creates a matcher that matches any double argument approximately
2573// equal to rhs, where two NANs are considered unequal.
2574inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2575 return internal::FloatingEqMatcher<double>(rhs, false);
2576}
2577
2578// Creates a matcher that matches any double argument approximately
2579// equal to rhs, including NaN values when rhs is NaN.
2580inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2581 return internal::FloatingEqMatcher<double>(rhs, true);
2582}
2583
2584// Creates a matcher that matches any float argument approximately
2585// equal to rhs, where two NANs are considered unequal.
2586inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2587 return internal::FloatingEqMatcher<float>(rhs, false);
2588}
2589
2590// Creates a matcher that matches any double argument approximately
2591// equal to rhs, including NaN values when rhs is NaN.
2592inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2593 return internal::FloatingEqMatcher<float>(rhs, true);
2594}
2595
2596// Creates a matcher that matches a pointer (raw or smart) that points
2597// to a value that matches inner_matcher.
2598template <typename InnerMatcher>
2599inline internal::PointeeMatcher<InnerMatcher> Pointee(
2600 const InnerMatcher& inner_matcher) {
2601 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2602}
2603
2604// Creates a matcher that matches an object whose given field matches
2605// 'matcher'. For example,
2606// Field(&Foo::number, Ge(5))
2607// matches a Foo object x iff x.number >= 5.
2608template <typename Class, typename FieldType, typename FieldMatcher>
2609inline PolymorphicMatcher<
2610 internal::FieldMatcher<Class, FieldType> > Field(
2611 FieldType Class::*field, const FieldMatcher& matcher) {
2612 return MakePolymorphicMatcher(
2613 internal::FieldMatcher<Class, FieldType>(
2614 field, MatcherCast<const FieldType&>(matcher)));
2615 // The call to MatcherCast() is required for supporting inner
2616 // matchers of compatible types. For example, it allows
2617 // Field(&Foo::bar, m)
2618 // to compile where bar is an int32 and m is a matcher for int64.
2619}
2620
2621// Creates a matcher that matches an object whose given property
2622// matches 'matcher'. For example,
2623// Property(&Foo::str, StartsWith("hi"))
2624// matches a Foo object x iff x.str() starts with "hi".
2625template <typename Class, typename PropertyType, typename PropertyMatcher>
2626inline PolymorphicMatcher<
2627 internal::PropertyMatcher<Class, PropertyType> > Property(
2628 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2629 return MakePolymorphicMatcher(
2630 internal::PropertyMatcher<Class, PropertyType>(
2631 property,
zhanyong.wane0d051e2009-02-19 00:33:37 +00002632 MatcherCast<GMOCK_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002633 // The call to MatcherCast() is required for supporting inner
2634 // matchers of compatible types. For example, it allows
2635 // Property(&Foo::bar, m)
2636 // to compile where bar() returns an int32 and m is a matcher for int64.
2637}
2638
2639// Creates a matcher that matches an object iff the result of applying
2640// a callable to x matches 'matcher'.
2641// For example,
2642// ResultOf(f, StartsWith("hi"))
2643// matches a Foo object x iff f(x) starts with "hi".
2644// callable parameter can be a function, function pointer, or a functor.
2645// Callable has to satisfy the following conditions:
2646// * It is required to keep no state affecting the results of
2647// the calls on it and make no assumptions about how many calls
2648// will be made. Any state it keeps must be protected from the
2649// concurrent access.
2650// * If it is a function object, it has to define type result_type.
2651// We recommend deriving your functor classes from std::unary_function.
2652template <typename Callable, typename ResultOfMatcher>
2653internal::ResultOfMatcher<Callable> ResultOf(
2654 Callable callable, const ResultOfMatcher& matcher) {
2655 return internal::ResultOfMatcher<Callable>(
2656 callable,
2657 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2658 matcher));
2659 // The call to MatcherCast() is required for supporting inner
2660 // matchers of compatible types. For example, it allows
2661 // ResultOf(Function, m)
2662 // to compile where Function() returns an int32 and m is a matcher for int64.
2663}
2664
2665// String matchers.
2666
2667// Matches a string equal to str.
2668inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2669 StrEq(const internal::string& str) {
2670 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2671 str, true, true));
2672}
2673
2674// Matches a string not equal to str.
2675inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2676 StrNe(const internal::string& str) {
2677 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2678 str, false, true));
2679}
2680
2681// Matches a string equal to str, ignoring case.
2682inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2683 StrCaseEq(const internal::string& str) {
2684 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2685 str, true, false));
2686}
2687
2688// Matches a string not equal to str, ignoring case.
2689inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2690 StrCaseNe(const internal::string& str) {
2691 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2692 str, false, false));
2693}
2694
2695// Creates a matcher that matches any string, std::string, or C string
2696// that contains the given substring.
2697inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2698 HasSubstr(const internal::string& substring) {
2699 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
2700 substring));
2701}
2702
2703// Matches a string that starts with 'prefix' (case-sensitive).
2704inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
2705 StartsWith(const internal::string& prefix) {
2706 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
2707 prefix));
2708}
2709
2710// Matches a string that ends with 'suffix' (case-sensitive).
2711inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
2712 EndsWith(const internal::string& suffix) {
2713 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
2714 suffix));
2715}
2716
shiqiane35fdd92008-12-10 05:08:54 +00002717// Matches a string that fully matches regular expression 'regex'.
2718// The matcher takes ownership of 'regex'.
2719inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2720 const internal::RE* regex) {
2721 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2722}
2723inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2724 const internal::string& regex) {
2725 return MatchesRegex(new internal::RE(regex));
2726}
2727
2728// Matches a string that contains regular expression 'regex'.
2729// The matcher takes ownership of 'regex'.
2730inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2731 const internal::RE* regex) {
2732 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2733}
2734inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2735 const internal::string& regex) {
2736 return ContainsRegex(new internal::RE(regex));
2737}
2738
shiqiane35fdd92008-12-10 05:08:54 +00002739#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2740// Wide string matchers.
2741
2742// Matches a string equal to str.
2743inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2744 StrEq(const internal::wstring& str) {
2745 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2746 str, true, true));
2747}
2748
2749// Matches a string not equal to str.
2750inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2751 StrNe(const internal::wstring& str) {
2752 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2753 str, false, true));
2754}
2755
2756// Matches a string equal to str, ignoring case.
2757inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2758 StrCaseEq(const internal::wstring& str) {
2759 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2760 str, true, false));
2761}
2762
2763// Matches a string not equal to str, ignoring case.
2764inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2765 StrCaseNe(const internal::wstring& str) {
2766 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2767 str, false, false));
2768}
2769
2770// Creates a matcher that matches any wstring, std::wstring, or C wide string
2771// that contains the given substring.
2772inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2773 HasSubstr(const internal::wstring& substring) {
2774 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2775 substring));
2776}
2777
2778// Matches a string that starts with 'prefix' (case-sensitive).
2779inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2780 StartsWith(const internal::wstring& prefix) {
2781 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2782 prefix));
2783}
2784
2785// Matches a string that ends with 'suffix' (case-sensitive).
2786inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2787 EndsWith(const internal::wstring& suffix) {
2788 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2789 suffix));
2790}
2791
2792#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2793
2794// Creates a polymorphic matcher that matches a 2-tuple where the
2795// first field == the second field.
2796inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2797
2798// Creates a polymorphic matcher that matches a 2-tuple where the
2799// first field >= the second field.
2800inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2801
2802// Creates a polymorphic matcher that matches a 2-tuple where the
2803// first field > the second field.
2804inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2805
2806// Creates a polymorphic matcher that matches a 2-tuple where the
2807// first field <= the second field.
2808inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2809
2810// Creates a polymorphic matcher that matches a 2-tuple where the
2811// first field < the second field.
2812inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2813
2814// Creates a polymorphic matcher that matches a 2-tuple where the
2815// first field != the second field.
2816inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2817
2818// Creates a matcher that matches any value of type T that m doesn't
2819// match.
2820template <typename InnerMatcher>
2821inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2822 return internal::NotMatcher<InnerMatcher>(m);
2823}
2824
2825// Creates a matcher that matches any value that matches all of the
2826// given matchers.
2827//
2828// For now we only support up to 5 matchers. Support for more
2829// matchers can be added as needed, or the user can use nested
2830// AllOf()s.
2831template <typename Matcher1, typename Matcher2>
2832inline internal::BothOfMatcher<Matcher1, Matcher2>
2833AllOf(Matcher1 m1, Matcher2 m2) {
2834 return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2);
2835}
2836
2837template <typename Matcher1, typename Matcher2, typename Matcher3>
2838inline internal::BothOfMatcher<Matcher1,
2839 internal::BothOfMatcher<Matcher2, Matcher3> >
2840AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2841 return AllOf(m1, AllOf(m2, m3));
2842}
2843
2844template <typename Matcher1, typename Matcher2, typename Matcher3,
2845 typename Matcher4>
2846inline internal::BothOfMatcher<Matcher1,
2847 internal::BothOfMatcher<Matcher2,
2848 internal::BothOfMatcher<Matcher3, Matcher4> > >
2849AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2850 return AllOf(m1, AllOf(m2, m3, m4));
2851}
2852
2853template <typename Matcher1, typename Matcher2, typename Matcher3,
2854 typename Matcher4, typename Matcher5>
2855inline internal::BothOfMatcher<Matcher1,
2856 internal::BothOfMatcher<Matcher2,
2857 internal::BothOfMatcher<Matcher3,
2858 internal::BothOfMatcher<Matcher4, Matcher5> > > >
2859AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2860 return AllOf(m1, AllOf(m2, m3, m4, m5));
2861}
2862
2863// Creates a matcher that matches any value that matches at least one
2864// of the given matchers.
2865//
2866// For now we only support up to 5 matchers. Support for more
2867// matchers can be added as needed, or the user can use nested
2868// AnyOf()s.
2869template <typename Matcher1, typename Matcher2>
2870inline internal::EitherOfMatcher<Matcher1, Matcher2>
2871AnyOf(Matcher1 m1, Matcher2 m2) {
2872 return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2);
2873}
2874
2875template <typename Matcher1, typename Matcher2, typename Matcher3>
2876inline internal::EitherOfMatcher<Matcher1,
2877 internal::EitherOfMatcher<Matcher2, Matcher3> >
2878AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2879 return AnyOf(m1, AnyOf(m2, m3));
2880}
2881
2882template <typename Matcher1, typename Matcher2, typename Matcher3,
2883 typename Matcher4>
2884inline internal::EitherOfMatcher<Matcher1,
2885 internal::EitherOfMatcher<Matcher2,
2886 internal::EitherOfMatcher<Matcher3, Matcher4> > >
2887AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2888 return AnyOf(m1, AnyOf(m2, m3, m4));
2889}
2890
2891template <typename Matcher1, typename Matcher2, typename Matcher3,
2892 typename Matcher4, typename Matcher5>
2893inline internal::EitherOfMatcher<Matcher1,
2894 internal::EitherOfMatcher<Matcher2,
2895 internal::EitherOfMatcher<Matcher3,
2896 internal::EitherOfMatcher<Matcher4, Matcher5> > > >
2897AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2898 return AnyOf(m1, AnyOf(m2, m3, m4, m5));
2899}
2900
2901// Returns a matcher that matches anything that satisfies the given
2902// predicate. The predicate can be any unary function or functor
2903// whose return type can be implicitly converted to bool.
2904template <typename Predicate>
2905inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
2906Truly(Predicate pred) {
2907 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
2908}
2909
zhanyong.wan6a896b52009-01-16 01:13:50 +00002910// Returns a matcher that matches an equal container.
2911// This matcher behaves like Eq(), but in the event of mismatch lists the
2912// values that are included in one container but not the other. (Duplicate
2913// values and order differences are not explained.)
2914template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00002915inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wanb8243162009-06-04 05:48:20 +00002916 GMOCK_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00002917 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002918 // This following line is for working around a bug in MSVC 8.0,
2919 // which causes Container to be a const type sometimes.
2920 typedef GMOCK_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00002921 return MakePolymorphicMatcher(
2922 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00002923}
2924
2925// Matches an STL-style container or a native array that contains at
2926// least one element matching the given value or matcher.
2927//
2928// Examples:
2929// ::std::set<int> page_ids;
2930// page_ids.insert(3);
2931// page_ids.insert(1);
2932// EXPECT_THAT(page_ids, Contains(1));
2933// EXPECT_THAT(page_ids, Contains(Gt(2)));
2934// EXPECT_THAT(page_ids, Not(Contains(4)));
2935//
2936// ::std::map<int, size_t> page_lengths;
2937// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00002938// EXPECT_THAT(page_lengths,
2939// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00002940//
2941// const char* user_ids[] = { "joe", "mike", "tom" };
2942// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
2943template <typename M>
2944inline internal::ContainsMatcher<M> Contains(M matcher) {
2945 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002946}
2947
zhanyong.wanb5937da2009-07-16 20:26:41 +00002948// Key(inner_matcher) matches an std::pair whose 'first' field matches
2949// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2950// std::map that contains at least one element whose key is >= 5.
2951template <typename M>
2952inline internal::KeyMatcher<M> Key(M inner_matcher) {
2953 return internal::KeyMatcher<M>(inner_matcher);
2954}
2955
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002956// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
2957// matches first_matcher and whose 'second' field matches second_matcher. For
2958// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
2959// to match a std::map<int, string> that contains exactly one element whose key
2960// is >= 5 and whose value equals "foo".
2961template <typename FirstMatcher, typename SecondMatcher>
2962inline internal::PairMatcher<FirstMatcher, SecondMatcher>
2963Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
2964 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
2965 first_matcher, second_matcher);
2966}
2967
shiqiane35fdd92008-12-10 05:08:54 +00002968// Returns a predicate that is satisfied by anything that matches the
2969// given matcher.
2970template <typename M>
2971inline internal::MatcherAsPredicate<M> Matches(M matcher) {
2972 return internal::MatcherAsPredicate<M>(matcher);
2973}
2974
zhanyong.wanb8243162009-06-04 05:48:20 +00002975// Returns true iff the value matches the matcher.
2976template <typename T, typename M>
2977inline bool Value(const T& value, M matcher) {
2978 return testing::Matches(matcher)(value);
2979}
2980
zhanyong.wanbf550852009-06-09 06:09:53 +00002981// AllArgs(m) is a synonym of m. This is useful in
2982//
2983// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
2984//
2985// which is easier to read than
2986//
2987// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
2988template <typename InnerMatcher>
2989inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
2990
shiqiane35fdd92008-12-10 05:08:54 +00002991// These macros allow using matchers to check values in Google Test
2992// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
2993// succeed iff the value matches the matcher. If the assertion fails,
2994// the value and the description of the matcher will be printed.
2995#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
2996 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2997#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
2998 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2999
3000} // namespace testing
3001
3002#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_