blob: f6e877d2d19179dfc7fb9463912e2b8866aa4967 [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#if GMOCK_HAS_REGEX
1121
1122// Implements polymorphic matchers MatchesRegex(regex) and
1123// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1124// T can be converted to a string.
1125class MatchesRegexMatcher {
1126 public:
1127 MatchesRegexMatcher(const RE* regex, bool full_match)
1128 : regex_(regex), full_match_(full_match) {}
1129
1130 // These overloaded methods allow MatchesRegex(regex) to be used as
1131 // a Matcher<T> as long as T can be converted to string. Returns
1132 // true iff s matches regular expression regex. When full_match_ is
1133 // true, a full match is done; otherwise a partial match is done.
1134 bool Matches(const char* s) const {
1135 return s != NULL && Matches(internal::string(s));
1136 }
1137
1138 bool Matches(const internal::string& s) const {
1139 return full_match_ ? RE::FullMatch(s, *regex_) :
1140 RE::PartialMatch(s, *regex_);
1141 }
1142
1143 void DescribeTo(::std::ostream* os) const {
1144 *os << (full_match_ ? "matches" : "contains")
1145 << " regular expression ";
1146 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1147 }
1148
1149 void DescribeNegationTo(::std::ostream* os) const {
1150 *os << "doesn't " << (full_match_ ? "match" : "contain")
1151 << " regular expression ";
1152 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1153 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001154
shiqiane35fdd92008-12-10 05:08:54 +00001155 private:
1156 const internal::linked_ptr<const RE> regex_;
1157 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001158
1159 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001160};
1161
zhanyong.wane122e452010-01-12 09:03:52 +00001162template <typename T>
1163bool MatchAndExplain(const MatchesRegexMatcher& impl, T& s,
1164 MatchResultListener* /* listener */) {
1165 return impl.Matches(s);
1166}
1167
shiqiane35fdd92008-12-10 05:08:54 +00001168#endif // GMOCK_HAS_REGEX
1169
1170// Implements a matcher that compares the two fields of a 2-tuple
1171// using one of the ==, <=, <, etc, operators. The two fields being
1172// compared don't have to have the same type.
1173//
1174// The matcher defined here is polymorphic (for example, Eq() can be
1175// used to match a tuple<int, short>, a tuple<const long&, double>,
1176// etc). Therefore we use a template type conversion operator in the
1177// implementation.
1178//
1179// We define this as a macro in order to eliminate duplicated source
1180// code.
zhanyong.wan2661c682009-06-09 05:42:12 +00001181#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op) \
shiqiane35fdd92008-12-10 05:08:54 +00001182 class name##2Matcher { \
1183 public: \
1184 template <typename T1, typename T2> \
1185 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
1186 return MakeMatcher(new Impl<T1, T2>); \
1187 } \
1188 private: \
1189 template <typename T1, typename T2> \
1190 class Impl : public MatcherInterface<const ::std::tr1::tuple<T1, T2>&> { \
1191 public: \
zhanyong.wan82113312010-01-08 21:55:40 +00001192 virtual bool MatchAndExplain( \
1193 const ::std::tr1::tuple<T1, T2>& args, \
1194 MatchResultListener* /* listener */) const { \
shiqiane35fdd92008-12-10 05:08:54 +00001195 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
1196 } \
1197 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +00001198 *os << "are a pair (x, y) where x " #op " y"; \
shiqiane35fdd92008-12-10 05:08:54 +00001199 } \
1200 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +00001201 *os << "are a pair (x, y) where x " #op " y is false"; \
shiqiane35fdd92008-12-10 05:08:54 +00001202 } \
1203 }; \
1204 }
1205
1206// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wan2661c682009-06-09 05:42:12 +00001207GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==);
1208GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ge, >=);
1209GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Gt, >);
1210GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Le, <=);
1211GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Lt, <);
1212GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=);
shiqiane35fdd92008-12-10 05:08:54 +00001213
zhanyong.wane0d051e2009-02-19 00:33:37 +00001214#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +00001215
zhanyong.wanc6a41232009-05-13 23:38:40 +00001216// Implements the Not(...) matcher for a particular argument type T.
1217// We do not nest it inside the NotMatcher class template, as that
1218// will prevent different instantiations of NotMatcher from sharing
1219// the same NotMatcherImpl<T> class.
1220template <typename T>
1221class NotMatcherImpl : public MatcherInterface<T> {
1222 public:
1223 explicit NotMatcherImpl(const Matcher<T>& matcher)
1224 : matcher_(matcher) {}
1225
zhanyong.wan82113312010-01-08 21:55:40 +00001226 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1227 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001228 }
1229
1230 virtual void DescribeTo(::std::ostream* os) const {
1231 matcher_.DescribeNegationTo(os);
1232 }
1233
1234 virtual void DescribeNegationTo(::std::ostream* os) const {
1235 matcher_.DescribeTo(os);
1236 }
1237
zhanyong.wanc6a41232009-05-13 23:38:40 +00001238 private:
1239 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001240
1241 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001242};
1243
shiqiane35fdd92008-12-10 05:08:54 +00001244// Implements the Not(m) matcher, which matches a value that doesn't
1245// match matcher m.
1246template <typename InnerMatcher>
1247class NotMatcher {
1248 public:
1249 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1250
1251 // This template type conversion operator allows Not(m) to be used
1252 // to match any type m can match.
1253 template <typename T>
1254 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001255 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001256 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001257
shiqiane35fdd92008-12-10 05:08:54 +00001258 private:
shiqiane35fdd92008-12-10 05:08:54 +00001259 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001260
1261 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001262};
1263
zhanyong.wanc6a41232009-05-13 23:38:40 +00001264// Implements the AllOf(m1, m2) matcher for a particular argument type
1265// T. We do not nest it inside the BothOfMatcher class template, as
1266// that will prevent different instantiations of BothOfMatcher from
1267// sharing the same BothOfMatcherImpl<T> class.
1268template <typename T>
1269class BothOfMatcherImpl : public MatcherInterface<T> {
1270 public:
1271 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1272 : matcher1_(matcher1), matcher2_(matcher2) {}
1273
zhanyong.wanc6a41232009-05-13 23:38:40 +00001274 virtual void DescribeTo(::std::ostream* os) const {
1275 *os << "(";
1276 matcher1_.DescribeTo(os);
1277 *os << ") and (";
1278 matcher2_.DescribeTo(os);
1279 *os << ")";
1280 }
1281
1282 virtual void DescribeNegationTo(::std::ostream* os) const {
1283 *os << "not ";
1284 DescribeTo(os);
1285 }
1286
zhanyong.wan82113312010-01-08 21:55:40 +00001287 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1288 // If either matcher1_ or matcher2_ doesn't match x, we only need
1289 // to explain why one of them fails.
1290 StringMatchResultListener listener1;
1291 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1292 *listener << listener1.str();
1293 return false;
1294 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001295
zhanyong.wan82113312010-01-08 21:55:40 +00001296 StringMatchResultListener listener2;
1297 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1298 *listener << listener2.str();
1299 return false;
1300 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001301
zhanyong.wan82113312010-01-08 21:55:40 +00001302 // Otherwise we need to explain why *both* of them match.
1303 const internal::string s1 = listener1.str();
1304 const internal::string s2 = listener2.str();
1305
1306 if (s1 == "") {
1307 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001308 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001309 *listener << s1;
1310 if (s2 != "") {
1311 *listener << "; " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001312 }
1313 }
zhanyong.wan82113312010-01-08 21:55:40 +00001314 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001315 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001316
zhanyong.wanc6a41232009-05-13 23:38:40 +00001317 private:
1318 const Matcher<T> matcher1_;
1319 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001320
1321 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001322};
1323
shiqiane35fdd92008-12-10 05:08:54 +00001324// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1325// matches a value that matches all of the matchers m_1, ..., and m_n.
1326template <typename Matcher1, typename Matcher2>
1327class BothOfMatcher {
1328 public:
1329 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1330 : matcher1_(matcher1), matcher2_(matcher2) {}
1331
1332 // This template type conversion operator allows a
1333 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1334 // both Matcher1 and Matcher2 can match.
1335 template <typename T>
1336 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001337 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1338 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001339 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001340
shiqiane35fdd92008-12-10 05:08:54 +00001341 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001342 Matcher1 matcher1_;
1343 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001344
1345 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001346};
shiqiane35fdd92008-12-10 05:08:54 +00001347
zhanyong.wanc6a41232009-05-13 23:38:40 +00001348// Implements the AnyOf(m1, m2) matcher for a particular argument type
1349// T. We do not nest it inside the AnyOfMatcher class template, as
1350// that will prevent different instantiations of AnyOfMatcher from
1351// sharing the same EitherOfMatcherImpl<T> class.
1352template <typename T>
1353class EitherOfMatcherImpl : public MatcherInterface<T> {
1354 public:
1355 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1356 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001357
zhanyong.wanc6a41232009-05-13 23:38:40 +00001358 virtual void DescribeTo(::std::ostream* os) const {
1359 *os << "(";
1360 matcher1_.DescribeTo(os);
1361 *os << ") or (";
1362 matcher2_.DescribeTo(os);
1363 *os << ")";
1364 }
shiqiane35fdd92008-12-10 05:08:54 +00001365
zhanyong.wanc6a41232009-05-13 23:38:40 +00001366 virtual void DescribeNegationTo(::std::ostream* os) const {
1367 *os << "not ";
1368 DescribeTo(os);
1369 }
shiqiane35fdd92008-12-10 05:08:54 +00001370
zhanyong.wan82113312010-01-08 21:55:40 +00001371 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1372 // If either matcher1_ or matcher2_ matches x, we just need to
1373 // explain why *one* of them matches.
1374 StringMatchResultListener listener1;
1375 if (matcher1_.MatchAndExplain(x, &listener1)) {
1376 *listener << listener1.str();
1377 return true;
1378 }
1379
1380 StringMatchResultListener listener2;
1381 if (matcher2_.MatchAndExplain(x, &listener2)) {
1382 *listener << listener2.str();
1383 return true;
1384 }
1385
1386 // Otherwise we need to explain why *both* of them fail.
1387 const internal::string s1 = listener1.str();
1388 const internal::string s2 = listener2.str();
1389
1390 if (s1 == "") {
1391 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001392 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001393 *listener << s1;
1394 if (s2 != "") {
1395 *listener << "; " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001396 }
1397 }
zhanyong.wan82113312010-01-08 21:55:40 +00001398 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001399 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001400
zhanyong.wanc6a41232009-05-13 23:38:40 +00001401 private:
1402 const Matcher<T> matcher1_;
1403 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001404
1405 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001406};
1407
1408// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1409// matches a value that matches at least one of the matchers m_1, ...,
1410// and m_n.
1411template <typename Matcher1, typename Matcher2>
1412class EitherOfMatcher {
1413 public:
1414 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1415 : matcher1_(matcher1), matcher2_(matcher2) {}
1416
1417 // This template type conversion operator allows a
1418 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1419 // both Matcher1 and Matcher2 can match.
1420 template <typename T>
1421 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001422 return Matcher<T>(new EitherOfMatcherImpl<T>(
1423 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001424 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001425
shiqiane35fdd92008-12-10 05:08:54 +00001426 private:
shiqiane35fdd92008-12-10 05:08:54 +00001427 Matcher1 matcher1_;
1428 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001429
1430 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001431};
1432
1433// Used for implementing Truly(pred), which turns a predicate into a
1434// matcher.
1435template <typename Predicate>
1436class TrulyMatcher {
1437 public:
1438 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1439
1440 // This method template allows Truly(pred) to be used as a matcher
1441 // for type T where T is the argument type of predicate 'pred'. The
1442 // argument is passed by reference as the predicate may be
1443 // interested in the address of the argument.
1444 template <typename T>
zhanyong.wan16cf4732009-05-14 20:55:30 +00001445 bool Matches(T& x) const { // NOLINT
zhanyong.wan652540a2009-02-23 23:37:29 +00001446#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001447 // MSVC warns about converting a value into bool (warning 4800).
1448#pragma warning(push) // Saves the current warning state.
1449#pragma warning(disable:4800) // Temporarily disables warning 4800.
1450#endif // GTEST_OS_WINDOWS
1451 return predicate_(x);
zhanyong.wan652540a2009-02-23 23:37:29 +00001452#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001453#pragma warning(pop) // Restores the warning state.
1454#endif // GTEST_OS_WINDOWS
1455 }
1456
1457 void DescribeTo(::std::ostream* os) const {
1458 *os << "satisfies the given predicate";
1459 }
1460
1461 void DescribeNegationTo(::std::ostream* os) const {
1462 *os << "doesn't satisfy the given predicate";
1463 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001464
shiqiane35fdd92008-12-10 05:08:54 +00001465 private:
1466 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001467
1468 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001469};
1470
zhanyong.wane122e452010-01-12 09:03:52 +00001471template <typename Predicate, typename T>
1472bool MatchAndExplain(const TrulyMatcher<Predicate>& impl, T& x,
1473 MatchResultListener* /* listener */) {
1474 return impl.Matches(x);
1475}
1476
shiqiane35fdd92008-12-10 05:08:54 +00001477// Used for implementing Matches(matcher), which turns a matcher into
1478// a predicate.
1479template <typename M>
1480class MatcherAsPredicate {
1481 public:
1482 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1483
1484 // This template operator() allows Matches(m) to be used as a
1485 // predicate on type T where m is a matcher on type T.
1486 //
1487 // The argument x is passed by reference instead of by value, as
1488 // some matcher may be interested in its address (e.g. as in
1489 // Matches(Ref(n))(x)).
1490 template <typename T>
1491 bool operator()(const T& x) const {
1492 // We let matcher_ commit to a particular type here instead of
1493 // when the MatcherAsPredicate object was constructed. This
1494 // allows us to write Matches(m) where m is a polymorphic matcher
1495 // (e.g. Eq(5)).
1496 //
1497 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1498 // compile when matcher_ has type Matcher<const T&>; if we write
1499 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1500 // when matcher_ has type Matcher<T>; if we just write
1501 // matcher_.Matches(x), it won't compile when matcher_ is
1502 // polymorphic, e.g. Eq(5).
1503 //
1504 // MatcherCast<const T&>() is necessary for making the code work
1505 // in all of the above situations.
1506 return MatcherCast<const T&>(matcher_).Matches(x);
1507 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001508
shiqiane35fdd92008-12-10 05:08:54 +00001509 private:
1510 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001511
1512 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001513};
1514
1515// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1516// argument M must be a type that can be converted to a matcher.
1517template <typename M>
1518class PredicateFormatterFromMatcher {
1519 public:
1520 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1521
1522 // This template () operator allows a PredicateFormatterFromMatcher
1523 // object to act as a predicate-formatter suitable for using with
1524 // Google Test's EXPECT_PRED_FORMAT1() macro.
1525 template <typename T>
1526 AssertionResult operator()(const char* value_text, const T& x) const {
1527 // We convert matcher_ to a Matcher<const T&> *now* instead of
1528 // when the PredicateFormatterFromMatcher object was constructed,
1529 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1530 // know which type to instantiate it to until we actually see the
1531 // type of x here.
1532 //
1533 // We write MatcherCast<const T&>(matcher_) instead of
1534 // Matcher<const T&>(matcher_), as the latter won't compile when
1535 // matcher_ has type Matcher<T> (e.g. An<int>()).
1536 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001537 StringMatchResultListener listener;
1538 if (matcher.MatchAndExplain(x, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +00001539 return AssertionSuccess();
1540 } else {
1541 ::std::stringstream ss;
1542 ss << "Value of: " << value_text << "\n"
1543 << "Expected: ";
1544 matcher.DescribeTo(&ss);
1545 ss << "\n Actual: ";
1546 UniversalPrinter<T>::Print(x, &ss);
zhanyong.wan82113312010-01-08 21:55:40 +00001547 StreamInParensAsNeeded(listener.str(), &ss);
shiqiane35fdd92008-12-10 05:08:54 +00001548 return AssertionFailure(Message() << ss.str());
1549 }
1550 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001551
shiqiane35fdd92008-12-10 05:08:54 +00001552 private:
1553 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001554
1555 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001556};
1557
1558// A helper function for converting a matcher to a predicate-formatter
1559// without the user needing to explicitly write the type. This is
1560// used for implementing ASSERT_THAT() and EXPECT_THAT().
1561template <typename M>
1562inline PredicateFormatterFromMatcher<M>
1563MakePredicateFormatterFromMatcher(const M& matcher) {
1564 return PredicateFormatterFromMatcher<M>(matcher);
1565}
1566
1567// Implements the polymorphic floating point equality matcher, which
1568// matches two float values using ULP-based approximation. The
1569// template is meant to be instantiated with FloatType being either
1570// float or double.
1571template <typename FloatType>
1572class FloatingEqMatcher {
1573 public:
1574 // Constructor for FloatingEqMatcher.
1575 // The matcher's input will be compared with rhs. The matcher treats two
1576 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1577 // equality comparisons between NANs will always return false.
1578 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1579 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1580
1581 // Implements floating point equality matcher as a Matcher<T>.
1582 template <typename T>
1583 class Impl : public MatcherInterface<T> {
1584 public:
1585 Impl(FloatType rhs, bool nan_eq_nan) :
1586 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1587
zhanyong.wan82113312010-01-08 21:55:40 +00001588 virtual bool MatchAndExplain(T value,
1589 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001590 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1591
1592 // Compares NaNs first, if nan_eq_nan_ is true.
1593 if (nan_eq_nan_ && lhs.is_nan()) {
1594 return rhs.is_nan();
1595 }
1596
1597 return lhs.AlmostEquals(rhs);
1598 }
1599
1600 virtual void DescribeTo(::std::ostream* os) const {
1601 // os->precision() returns the previously set precision, which we
1602 // store to restore the ostream to its original configuration
1603 // after outputting.
1604 const ::std::streamsize old_precision = os->precision(
1605 ::std::numeric_limits<FloatType>::digits10 + 2);
1606 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1607 if (nan_eq_nan_) {
1608 *os << "is NaN";
1609 } else {
1610 *os << "never matches";
1611 }
1612 } else {
1613 *os << "is approximately " << rhs_;
1614 }
1615 os->precision(old_precision);
1616 }
1617
1618 virtual void DescribeNegationTo(::std::ostream* os) const {
1619 // As before, get original precision.
1620 const ::std::streamsize old_precision = os->precision(
1621 ::std::numeric_limits<FloatType>::digits10 + 2);
1622 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1623 if (nan_eq_nan_) {
1624 *os << "is not NaN";
1625 } else {
1626 *os << "is anything";
1627 }
1628 } else {
1629 *os << "is not approximately " << rhs_;
1630 }
1631 // Restore original precision.
1632 os->precision(old_precision);
1633 }
1634
1635 private:
1636 const FloatType rhs_;
1637 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001638
1639 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001640 };
1641
1642 // The following 3 type conversion operators allow FloatEq(rhs) and
1643 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1644 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1645 // (While Google's C++ coding style doesn't allow arguments passed
1646 // by non-const reference, we may see them in code not conforming to
1647 // the style. Therefore Google Mock needs to support them.)
1648 operator Matcher<FloatType>() const {
1649 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1650 }
1651
1652 operator Matcher<const FloatType&>() const {
1653 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1654 }
1655
1656 operator Matcher<FloatType&>() const {
1657 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1658 }
1659 private:
1660 const FloatType rhs_;
1661 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001662
1663 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001664};
1665
1666// Implements the Pointee(m) matcher for matching a pointer whose
1667// pointee matches matcher m. The pointer can be either raw or smart.
1668template <typename InnerMatcher>
1669class PointeeMatcher {
1670 public:
1671 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1672
1673 // This type conversion operator template allows Pointee(m) to be
1674 // used as a matcher for any pointer type whose pointee type is
1675 // compatible with the inner matcher, where type Pointer can be
1676 // either a raw pointer or a smart pointer.
1677 //
1678 // The reason we do this instead of relying on
1679 // MakePolymorphicMatcher() is that the latter is not flexible
1680 // enough for implementing the DescribeTo() method of Pointee().
1681 template <typename Pointer>
1682 operator Matcher<Pointer>() const {
1683 return MakeMatcher(new Impl<Pointer>(matcher_));
1684 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001685
shiqiane35fdd92008-12-10 05:08:54 +00001686 private:
1687 // The monomorphic implementation that works for a particular pointer type.
1688 template <typename Pointer>
1689 class Impl : public MatcherInterface<Pointer> {
1690 public:
zhanyong.wane0d051e2009-02-19 00:33:37 +00001691 typedef typename PointeeOf<GMOCK_REMOVE_CONST_( // NOLINT
1692 GMOCK_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001693
1694 explicit Impl(const InnerMatcher& matcher)
1695 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1696
shiqiane35fdd92008-12-10 05:08:54 +00001697 virtual void DescribeTo(::std::ostream* os) const {
1698 *os << "points to a value that ";
1699 matcher_.DescribeTo(os);
1700 }
1701
1702 virtual void DescribeNegationTo(::std::ostream* os) const {
1703 *os << "does not point to a value that ";
1704 matcher_.DescribeTo(os);
1705 }
1706
zhanyong.wan82113312010-01-08 21:55:40 +00001707 virtual bool MatchAndExplain(Pointer pointer,
1708 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001709 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00001710 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001711
zhanyong.wan82113312010-01-08 21:55:40 +00001712 StringMatchResultListener inner_listener;
1713 const bool match = matcher_.MatchAndExplain(*pointer, &inner_listener);
1714 const internal::string s = inner_listener.str();
shiqiane35fdd92008-12-10 05:08:54 +00001715 if (s != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00001716 *listener << "points to a value that " << s;
shiqiane35fdd92008-12-10 05:08:54 +00001717 }
zhanyong.wan82113312010-01-08 21:55:40 +00001718 return match;
shiqiane35fdd92008-12-10 05:08:54 +00001719 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001720
shiqiane35fdd92008-12-10 05:08:54 +00001721 private:
1722 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001723
1724 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001725 };
1726
1727 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001728
1729 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001730};
1731
1732// Implements the Field() matcher for matching a field (i.e. member
1733// variable) of an object.
1734template <typename Class, typename FieldType>
1735class FieldMatcher {
1736 public:
1737 FieldMatcher(FieldType Class::*field,
1738 const Matcher<const FieldType&>& matcher)
1739 : field_(field), matcher_(matcher) {}
1740
shiqiane35fdd92008-12-10 05:08:54 +00001741 void DescribeTo(::std::ostream* os) const {
1742 *os << "the given field ";
1743 matcher_.DescribeTo(os);
1744 }
1745
1746 void DescribeNegationTo(::std::ostream* os) const {
1747 *os << "the given field ";
1748 matcher_.DescribeNegationTo(os);
1749 }
1750
zhanyong.wan82113312010-01-08 21:55:40 +00001751 // The first argument of MatchAndExplain() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001752 // Symbian's C++ compiler choose which overload to use. Its type is
1753 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wan82113312010-01-08 21:55:40 +00001754 bool MatchAndExplain(false_type /* is_not_pointer */, const Class& obj,
1755 MatchResultListener* listener) const {
1756 StringMatchResultListener inner_listener;
1757 const bool match = matcher_.MatchAndExplain(obj.*field_, &inner_listener);
1758 const internal::string s = inner_listener.str();
shiqiane35fdd92008-12-10 05:08:54 +00001759 if (s != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00001760 *listener << "the given field " << s;
shiqiane35fdd92008-12-10 05:08:54 +00001761 }
zhanyong.wan82113312010-01-08 21:55:40 +00001762 return match;
shiqiane35fdd92008-12-10 05:08:54 +00001763 }
1764
zhanyong.wan82113312010-01-08 21:55:40 +00001765 bool MatchAndExplain(true_type /* is_pointer */, const Class* p,
1766 MatchResultListener* listener) const {
1767 if (p == NULL)
1768 return false;
1769
1770 // Since *p has a field, it must be a class/struct/union type and
1771 // thus cannot be a pointer. Therefore we pass false_type() as
1772 // the first argument.
1773 return MatchAndExplain(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001774 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001775
shiqiane35fdd92008-12-10 05:08:54 +00001776 private:
1777 const FieldType Class::*field_;
1778 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001779
1780 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001781};
1782
zhanyong.wan18490652009-05-11 18:54:08 +00001783template <typename Class, typename FieldType, typename T>
zhanyong.wan82113312010-01-08 21:55:40 +00001784bool MatchAndExplain(const FieldMatcher<Class, FieldType>& matcher,
zhanyong.wane122e452010-01-12 09:03:52 +00001785 T& value, MatchResultListener* listener) {
zhanyong.wan82113312010-01-08 21:55:40 +00001786 return matcher.MatchAndExplain(
zhanyong.wan6953a722010-01-13 05:15:07 +00001787 typename ::testing::internal::is_pointer<GMOCK_REMOVE_CONST_(T)>::type(),
1788 value, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001789}
1790
1791// Implements the Property() matcher for matching a property
1792// (i.e. return value of a getter method) of an object.
1793template <typename Class, typename PropertyType>
1794class PropertyMatcher {
1795 public:
1796 // The property may have a reference type, so 'const PropertyType&'
1797 // may cause double references and fail to compile. That's why we
1798 // need GMOCK_REFERENCE_TO_CONST, which works regardless of
1799 // PropertyType being a reference or not.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001800 typedef GMOCK_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001801
1802 PropertyMatcher(PropertyType (Class::*property)() const,
1803 const Matcher<RefToConstProperty>& matcher)
1804 : property_(property), matcher_(matcher) {}
1805
shiqiane35fdd92008-12-10 05:08:54 +00001806 void DescribeTo(::std::ostream* os) const {
1807 *os << "the given property ";
1808 matcher_.DescribeTo(os);
1809 }
1810
1811 void DescribeNegationTo(::std::ostream* os) const {
1812 *os << "the given property ";
1813 matcher_.DescribeNegationTo(os);
1814 }
1815
zhanyong.wan82113312010-01-08 21:55:40 +00001816 // The first argument of MatchAndExplain() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001817 // Symbian's C++ compiler choose which overload to use. Its type is
1818 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wan82113312010-01-08 21:55:40 +00001819 bool MatchAndExplain(false_type /* is_not_pointer */, const Class& obj,
1820 MatchResultListener* listener) const {
1821 StringMatchResultListener inner_listener;
1822 const bool match = matcher_.MatchAndExplain((obj.*property_)(),
1823 &inner_listener);
1824 const internal::string s = inner_listener.str();
shiqiane35fdd92008-12-10 05:08:54 +00001825 if (s != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00001826 *listener << "the given property " << s;
shiqiane35fdd92008-12-10 05:08:54 +00001827 }
zhanyong.wan82113312010-01-08 21:55:40 +00001828 return match;
shiqiane35fdd92008-12-10 05:08:54 +00001829 }
1830
zhanyong.wan82113312010-01-08 21:55:40 +00001831 bool MatchAndExplain(true_type /* is_pointer */, const Class* p,
1832 MatchResultListener* listener) const {
1833 if (p == NULL)
1834 return false;
1835
1836 // Since *p has a property method, it must be a class/struct/union
1837 // type and thus cannot be a pointer. Therefore we pass
1838 // false_type() as the first argument.
1839 return MatchAndExplain(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001840 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001841
shiqiane35fdd92008-12-10 05:08:54 +00001842 private:
1843 PropertyType (Class::*property_)() const;
1844 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001845
1846 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001847};
1848
zhanyong.wan82113312010-01-08 21:55:40 +00001849template <typename Class, typename PropertyType, typename T>
1850bool MatchAndExplain(const PropertyMatcher<Class, PropertyType>& matcher,
zhanyong.wane122e452010-01-12 09:03:52 +00001851 T& value, MatchResultListener* listener) {
zhanyong.wan82113312010-01-08 21:55:40 +00001852 return matcher.MatchAndExplain(
zhanyong.wan6953a722010-01-13 05:15:07 +00001853 typename ::testing::internal::is_pointer<GMOCK_REMOVE_CONST_(T)>::type(),
1854 value, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001855}
1856
1857// Type traits specifying various features of different functors for ResultOf.
1858// The default template specifies features for functor objects.
1859// Functor classes have to typedef argument_type and result_type
1860// to be compatible with ResultOf.
1861template <typename Functor>
1862struct CallableTraits {
1863 typedef typename Functor::result_type ResultType;
1864 typedef Functor StorageType;
1865
zhanyong.wan32de5f52009-12-23 00:13:23 +00001866 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00001867 template <typename T>
1868 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1869};
1870
1871// Specialization for function pointers.
1872template <typename ArgType, typename ResType>
1873struct CallableTraits<ResType(*)(ArgType)> {
1874 typedef ResType ResultType;
1875 typedef ResType(*StorageType)(ArgType);
1876
1877 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001878 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00001879 << "NULL function pointer is passed into ResultOf().";
1880 }
1881 template <typename T>
1882 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1883 return (*f)(arg);
1884 }
1885};
1886
1887// Implements the ResultOf() matcher for matching a return value of a
1888// unary function of an object.
1889template <typename Callable>
1890class ResultOfMatcher {
1891 public:
1892 typedef typename CallableTraits<Callable>::ResultType ResultType;
1893
1894 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1895 : callable_(callable), matcher_(matcher) {
1896 CallableTraits<Callable>::CheckIsValid(callable_);
1897 }
1898
1899 template <typename T>
1900 operator Matcher<T>() const {
1901 return Matcher<T>(new Impl<T>(callable_, matcher_));
1902 }
1903
1904 private:
1905 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1906
1907 template <typename T>
1908 class Impl : public MatcherInterface<T> {
1909 public:
1910 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1911 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00001912
1913 virtual void DescribeTo(::std::ostream* os) const {
1914 *os << "result of the given callable ";
1915 matcher_.DescribeTo(os);
1916 }
1917
1918 virtual void DescribeNegationTo(::std::ostream* os) const {
1919 *os << "result of the given callable ";
1920 matcher_.DescribeNegationTo(os);
1921 }
1922
zhanyong.wan82113312010-01-08 21:55:40 +00001923 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
1924 StringMatchResultListener inner_listener;
1925 const bool match = matcher_.MatchAndExplain(
shiqiane35fdd92008-12-10 05:08:54 +00001926 CallableTraits<Callable>::template Invoke<T>(callable_, obj),
zhanyong.wan82113312010-01-08 21:55:40 +00001927 &inner_listener);
1928
1929 const internal::string s = inner_listener.str();
shiqiane35fdd92008-12-10 05:08:54 +00001930 if (s != "")
zhanyong.wan82113312010-01-08 21:55:40 +00001931 *listener << "result of the given callable " << s;
1932
1933 return match;
shiqiane35fdd92008-12-10 05:08:54 +00001934 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001935
shiqiane35fdd92008-12-10 05:08:54 +00001936 private:
1937 // Functors often define operator() as non-const method even though
1938 // they are actualy stateless. But we need to use them even when
1939 // 'this' is a const pointer. It's the user's responsibility not to
1940 // use stateful callables with ResultOf(), which does't guarantee
1941 // how many times the callable will be invoked.
1942 mutable CallableStorageType callable_;
1943 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001944
1945 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001946 }; // class Impl
1947
1948 const CallableStorageType callable_;
1949 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001950
1951 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001952};
1953
1954// Explains the result of matching a value against a functor matcher.
1955template <typename T, typename Callable>
1956void ExplainMatchResultTo(const ResultOfMatcher<Callable>& matcher,
1957 T obj, ::std::ostream* os) {
1958 matcher.ExplainMatchResultTo(obj, os);
1959}
1960
zhanyong.wan6a896b52009-01-16 01:13:50 +00001961// Implements an equality matcher for any STL-style container whose elements
1962// support ==. This matcher is like Eq(), but its failure explanations provide
1963// more detailed information that is useful when the container is used as a set.
1964// The failure message reports elements that are in one of the operands but not
1965// the other. The failure messages do not report duplicate or out-of-order
1966// elements in the containers (which don't properly matter to sets, but can
1967// occur if the containers are vectors or lists, for example).
1968//
1969// Uses the container's const_iterator, value_type, operator ==,
1970// begin(), and end().
1971template <typename Container>
1972class ContainerEqMatcher {
1973 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00001974 typedef internal::StlContainerView<Container> View;
1975 typedef typename View::type StlContainer;
1976 typedef typename View::const_reference StlContainerReference;
1977
1978 // We make a copy of rhs in case the elements in it are modified
1979 // after this matcher is created.
1980 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
1981 // Makes sure the user doesn't instantiate this class template
1982 // with a const or reference type.
1983 testing::StaticAssertTypeEq<Container,
1984 GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))>();
1985 }
1986
zhanyong.wan6a896b52009-01-16 01:13:50 +00001987 void DescribeTo(::std::ostream* os) const {
1988 *os << "equals ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001989 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001990 }
1991 void DescribeNegationTo(::std::ostream* os) const {
1992 *os << "does not equal ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001993 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001994 }
1995
zhanyong.wanb8243162009-06-04 05:48:20 +00001996 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00001997 bool MatchAndExplain(const LhsContainer& lhs,
1998 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00001999 // GMOCK_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
2000 // that causes LhsContainer to be a const type sometimes.
2001 typedef internal::StlContainerView<GMOCK_REMOVE_CONST_(LhsContainer)>
2002 LhsView;
2003 typedef typename LhsView::type LhsStlContainer;
2004 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00002005 if (lhs_stl_container == rhs_)
2006 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002007
zhanyong.wane122e452010-01-12 09:03:52 +00002008 ::std::ostream* const os = listener->stream();
2009 if (os != NULL) {
2010 // Something is different. Check for missing values first.
2011 bool printed_header = false;
2012 for (typename LhsStlContainer::const_iterator it =
2013 lhs_stl_container.begin();
2014 it != lhs_stl_container.end(); ++it) {
2015 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
2016 rhs_.end()) {
2017 if (printed_header) {
2018 *os << ", ";
2019 } else {
2020 *os << "Only in actual: ";
2021 printed_header = true;
2022 }
zhanyong.wan6953a722010-01-13 05:15:07 +00002023 UniversalPrinter<typename LhsStlContainer::value_type>::
2024 Print(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002025 }
zhanyong.wane122e452010-01-12 09:03:52 +00002026 }
2027
2028 // Now check for extra values.
2029 bool printed_header2 = false;
2030 for (typename StlContainer::const_iterator it = rhs_.begin();
2031 it != rhs_.end(); ++it) {
2032 if (internal::ArrayAwareFind(
2033 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2034 lhs_stl_container.end()) {
2035 if (printed_header2) {
2036 *os << ", ";
2037 } else {
2038 *os << (printed_header ? "; not" : "Not") << " in actual: ";
2039 printed_header2 = true;
2040 }
2041 UniversalPrinter<typename StlContainer::value_type>::Print(*it, os);
2042 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002043 }
2044 }
2045
zhanyong.wane122e452010-01-12 09:03:52 +00002046 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002047 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002048
zhanyong.wan6a896b52009-01-16 01:13:50 +00002049 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00002050 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002051
2052 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002053};
2054
zhanyong.wanb8243162009-06-04 05:48:20 +00002055template <typename LhsContainer, typename Container>
zhanyong.wane122e452010-01-12 09:03:52 +00002056bool MatchAndExplain(const ContainerEqMatcher<Container>& matcher,
2057 LhsContainer& lhs,
2058 MatchResultListener* listener) {
2059 return matcher.MatchAndExplain(lhs, listener);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002060}
2061
zhanyong.wanb8243162009-06-04 05:48:20 +00002062// Implements Contains(element_matcher) for the given argument type Container.
2063template <typename Container>
2064class ContainsMatcherImpl : public MatcherInterface<Container> {
2065 public:
2066 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
2067 typedef StlContainerView<RawContainer> View;
2068 typedef typename View::type StlContainer;
2069 typedef typename View::const_reference StlContainerReference;
2070 typedef typename StlContainer::value_type Element;
2071
2072 template <typename InnerMatcher>
2073 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2074 : inner_matcher_(
2075 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
2076
zhanyong.wanb8243162009-06-04 05:48:20 +00002077 // Describes what this matcher does.
2078 virtual void DescribeTo(::std::ostream* os) const {
2079 *os << "contains at least one element that ";
2080 inner_matcher_.DescribeTo(os);
2081 }
2082
2083 // Describes what the negation of this matcher does.
2084 virtual void DescribeNegationTo(::std::ostream* os) const {
2085 *os << "doesn't contain any element that ";
2086 inner_matcher_.DescribeTo(os);
2087 }
2088
zhanyong.wan82113312010-01-08 21:55:40 +00002089 virtual bool MatchAndExplain(Container container,
2090 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002091 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002092 size_t i = 0;
2093 for (typename StlContainer::const_iterator it = stl_container.begin();
2094 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002095 if (inner_matcher_.Matches(*it)) {
zhanyong.wan82113312010-01-08 21:55:40 +00002096 *listener << "element " << i << " matches";
2097 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002098 }
2099 }
zhanyong.wan82113312010-01-08 21:55:40 +00002100 return false;
zhanyong.wanb8243162009-06-04 05:48:20 +00002101 }
2102
2103 private:
2104 const Matcher<const Element&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002105
2106 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002107};
2108
2109// Implements polymorphic Contains(element_matcher).
2110template <typename M>
2111class ContainsMatcher {
2112 public:
2113 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2114
2115 template <typename Container>
2116 operator Matcher<Container>() const {
2117 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2118 }
2119
2120 private:
2121 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002122
2123 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002124};
2125
zhanyong.wanb5937da2009-07-16 20:26:41 +00002126// Implements Key(inner_matcher) for the given argument pair type.
2127// Key(inner_matcher) matches an std::pair whose 'first' field matches
2128// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2129// std::map that contains at least one element whose key is >= 5.
2130template <typename PairType>
2131class KeyMatcherImpl : public MatcherInterface<PairType> {
2132 public:
2133 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
2134 typedef typename RawPairType::first_type KeyType;
2135
2136 template <typename InnerMatcher>
2137 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2138 : inner_matcher_(
2139 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2140 }
2141
2142 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002143 virtual bool MatchAndExplain(PairType key_value,
2144 MatchResultListener* listener) const {
2145 return inner_matcher_.MatchAndExplain(key_value.first, listener);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002146 }
2147
2148 // Describes what this matcher does.
2149 virtual void DescribeTo(::std::ostream* os) const {
2150 *os << "has a key that ";
2151 inner_matcher_.DescribeTo(os);
2152 }
2153
2154 // Describes what the negation of this matcher does.
2155 virtual void DescribeNegationTo(::std::ostream* os) const {
2156 *os << "doesn't have a key that ";
2157 inner_matcher_.DescribeTo(os);
2158 }
2159
zhanyong.wanb5937da2009-07-16 20:26:41 +00002160 private:
2161 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002162
2163 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002164};
2165
2166// Implements polymorphic Key(matcher_for_key).
2167template <typename M>
2168class KeyMatcher {
2169 public:
2170 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2171
2172 template <typename PairType>
2173 operator Matcher<PairType>() const {
2174 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2175 }
2176
2177 private:
2178 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002179
2180 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002181};
2182
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002183// Implements Pair(first_matcher, second_matcher) for the given argument pair
2184// type with its two matchers. See Pair() function below.
2185template <typename PairType>
2186class PairMatcherImpl : public MatcherInterface<PairType> {
2187 public:
2188 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
2189 typedef typename RawPairType::first_type FirstType;
2190 typedef typename RawPairType::second_type SecondType;
2191
2192 template <typename FirstMatcher, typename SecondMatcher>
2193 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2194 : first_matcher_(
2195 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2196 second_matcher_(
2197 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2198 }
2199
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002200 // Describes what this matcher does.
2201 virtual void DescribeTo(::std::ostream* os) const {
2202 *os << "has a first field that ";
2203 first_matcher_.DescribeTo(os);
2204 *os << ", and has a second field that ";
2205 second_matcher_.DescribeTo(os);
2206 }
2207
2208 // Describes what the negation of this matcher does.
2209 virtual void DescribeNegationTo(::std::ostream* os) const {
2210 *os << "has a first field that ";
2211 first_matcher_.DescribeNegationTo(os);
2212 *os << ", or has a second field that ";
2213 second_matcher_.DescribeNegationTo(os);
2214 }
2215
zhanyong.wan82113312010-01-08 21:55:40 +00002216 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2217 // matches second_matcher.
2218 virtual bool MatchAndExplain(PairType a_pair,
2219 MatchResultListener* listener) const {
2220 StringMatchResultListener listener1;
2221 const bool match1 = first_matcher_.MatchAndExplain(a_pair.first,
2222 &listener1);
2223 internal::string s1 = listener1.str();
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002224 if (s1 != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00002225 s1 = "the first field " + s1;
2226 }
2227 if (!match1) {
2228 *listener << s1;
2229 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002230 }
2231
zhanyong.wan82113312010-01-08 21:55:40 +00002232 StringMatchResultListener listener2;
2233 const bool match2 = second_matcher_.MatchAndExplain(a_pair.second,
2234 &listener2);
2235 internal::string s2 = listener2.str();
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002236 if (s2 != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00002237 s2 = "the second field " + s2;
2238 }
2239 if (!match2) {
2240 *listener << s2;
2241 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002242 }
2243
zhanyong.wan82113312010-01-08 21:55:40 +00002244 *listener << s1;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002245 if (s1 != "" && s2 != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00002246 *listener << ", and ";
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002247 }
zhanyong.wan82113312010-01-08 21:55:40 +00002248 *listener << s2;
2249 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002250 }
2251
2252 private:
2253 const Matcher<const FirstType&> first_matcher_;
2254 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002255
2256 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002257};
2258
2259// Implements polymorphic Pair(first_matcher, second_matcher).
2260template <typename FirstMatcher, typename SecondMatcher>
2261class PairMatcher {
2262 public:
2263 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2264 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2265
2266 template <typename PairType>
2267 operator Matcher<PairType> () const {
2268 return MakeMatcher(
2269 new PairMatcherImpl<PairType>(
2270 first_matcher_, second_matcher_));
2271 }
2272
2273 private:
2274 const FirstMatcher first_matcher_;
2275 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002276
2277 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002278};
2279
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002280// Implements ElementsAre() and ElementsAreArray().
2281template <typename Container>
2282class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2283 public:
2284 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
2285 typedef internal::StlContainerView<RawContainer> View;
2286 typedef typename View::type StlContainer;
2287 typedef typename View::const_reference StlContainerReference;
2288 typedef typename StlContainer::value_type Element;
2289
2290 // Constructs the matcher from a sequence of element values or
2291 // element matchers.
2292 template <typename InputIter>
zhanyong.wan32de5f52009-12-23 00:13:23 +00002293 ElementsAreMatcherImpl(InputIter first, size_t a_count) {
2294 matchers_.reserve(a_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002295 InputIter it = first;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002296 for (size_t i = 0; i != a_count; ++i, ++it) {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002297 matchers_.push_back(MatcherCast<const Element&>(*it));
2298 }
2299 }
2300
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002301 // Describes what this matcher does.
2302 virtual void DescribeTo(::std::ostream* os) const {
2303 if (count() == 0) {
2304 *os << "is empty";
2305 } else if (count() == 1) {
2306 *os << "has 1 element that ";
2307 matchers_[0].DescribeTo(os);
2308 } else {
2309 *os << "has " << Elements(count()) << " where\n";
2310 for (size_t i = 0; i != count(); ++i) {
2311 *os << "element " << i << " ";
2312 matchers_[i].DescribeTo(os);
2313 if (i + 1 < count()) {
2314 *os << ",\n";
2315 }
2316 }
2317 }
2318 }
2319
2320 // Describes what the negation of this matcher does.
2321 virtual void DescribeNegationTo(::std::ostream* os) const {
2322 if (count() == 0) {
2323 *os << "is not empty";
2324 return;
2325 }
2326
2327 *os << "does not have " << Elements(count()) << ", or\n";
2328 for (size_t i = 0; i != count(); ++i) {
2329 *os << "element " << i << " ";
2330 matchers_[i].DescribeNegationTo(os);
2331 if (i + 1 < count()) {
2332 *os << ", or\n";
2333 }
2334 }
2335 }
2336
zhanyong.wan82113312010-01-08 21:55:40 +00002337 virtual bool MatchAndExplain(Container container,
2338 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002339 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002340 const size_t actual_count = stl_container.size();
2341 if (actual_count != count()) {
2342 // The element count doesn't match. If the container is empty,
2343 // there's no need to explain anything as Google Mock already
2344 // prints the empty container. Otherwise we just need to show
2345 // how many elements there actually are.
2346 if (actual_count != 0) {
2347 *listener << "has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002348 }
zhanyong.wan82113312010-01-08 21:55:40 +00002349 return false;
2350 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002351
zhanyong.wan82113312010-01-08 21:55:40 +00002352 typename StlContainer::const_iterator it = stl_container.begin();
2353 // explanations[i] is the explanation of the element at index i.
2354 std::vector<internal::string> explanations(count());
2355 for (size_t i = 0; i != count(); ++it, ++i) {
2356 StringMatchResultListener s;
2357 if (matchers_[i].MatchAndExplain(*it, &s)) {
2358 explanations[i] = s.str();
2359 } else {
2360 // The container has the right size but the i-th element
2361 // doesn't match its expectation.
2362 *listener << "element " << i << " doesn't match";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002363
zhanyong.wan82113312010-01-08 21:55:40 +00002364 StreamInParensAsNeeded(s.str(), listener->stream());
2365 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002366 }
2367 }
zhanyong.wan82113312010-01-08 21:55:40 +00002368
2369 // Every element matches its expectation. We need to explain why
2370 // (the obvious ones can be skipped).
2371
2372 bool reason_printed = false;
2373 for (size_t i = 0; i != count(); ++i) {
2374 const internal::string& s = explanations[i];
2375 if (!s.empty()) {
2376 if (reason_printed) {
2377 *listener << ",\n";
2378 }
2379 *listener << "element " << i << " " << s;
2380 reason_printed = true;
2381 }
2382 }
2383
2384 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002385 }
2386
2387 private:
2388 static Message Elements(size_t count) {
2389 return Message() << count << (count == 1 ? " element" : " elements");
2390 }
2391
2392 size_t count() const { return matchers_.size(); }
2393 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002394
2395 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002396};
2397
2398// Implements ElementsAre() of 0 arguments.
2399class ElementsAreMatcher0 {
2400 public:
2401 ElementsAreMatcher0() {}
2402
2403 template <typename Container>
2404 operator Matcher<Container>() const {
2405 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2406 RawContainer;
2407 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2408 Element;
2409
2410 const Matcher<const Element&>* const matchers = NULL;
2411 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 0));
2412 }
2413};
2414
2415// Implements ElementsAreArray().
2416template <typename T>
2417class ElementsAreArrayMatcher {
2418 public:
2419 ElementsAreArrayMatcher(const T* first, size_t count) :
2420 first_(first), count_(count) {}
2421
2422 template <typename Container>
2423 operator Matcher<Container>() const {
2424 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2425 RawContainer;
2426 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2427 Element;
2428
2429 return MakeMatcher(new ElementsAreMatcherImpl<Container>(first_, count_));
2430 }
2431
2432 private:
2433 const T* const first_;
2434 const size_t count_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002435
2436 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002437};
2438
2439// Constants denoting interpolations in a matcher description string.
2440const int kTupleInterpolation = -1; // "%(*)s"
2441const int kPercentInterpolation = -2; // "%%"
2442const int kInvalidInterpolation = -3; // "%" followed by invalid text
2443
2444// Records the location and content of an interpolation.
2445struct Interpolation {
2446 Interpolation(const char* start, const char* end, int param)
2447 : start_pos(start), end_pos(end), param_index(param) {}
2448
2449 // Points to the start of the interpolation (the '%' character).
2450 const char* start_pos;
2451 // Points to the first character after the interpolation.
2452 const char* end_pos;
2453 // 0-based index of the interpolated matcher parameter;
2454 // kTupleInterpolation for "%(*)s"; kPercentInterpolation for "%%".
2455 int param_index;
2456};
2457
2458typedef ::std::vector<Interpolation> Interpolations;
2459
2460// Parses a matcher description string and returns a vector of
2461// interpolations that appear in the string; generates non-fatal
2462// failures iff 'description' is an invalid matcher description.
2463// 'param_names' is a NULL-terminated array of parameter names in the
2464// order they appear in the MATCHER_P*() parameter list.
2465Interpolations ValidateMatcherDescription(
2466 const char* param_names[], const char* description);
2467
2468// Returns the actual matcher description, given the matcher name,
2469// user-supplied description template string, interpolations in the
2470// string, and the printed values of the matcher parameters.
2471string FormatMatcherDescription(
2472 const char* matcher_name, const char* description,
2473 const Interpolations& interp, const Strings& param_values);
2474
shiqiane35fdd92008-12-10 05:08:54 +00002475} // namespace internal
2476
2477// Implements MatcherCast().
2478template <typename T, typename M>
2479inline Matcher<T> MatcherCast(M matcher) {
2480 return internal::MatcherCastImpl<T, M>::Cast(matcher);
2481}
2482
2483// _ is a matcher that matches anything of any type.
2484//
2485// This definition is fine as:
2486//
2487// 1. The C++ standard permits using the name _ in a namespace that
2488// is not the global namespace or ::std.
2489// 2. The AnythingMatcher class has no data member or constructor,
2490// so it's OK to create global variables of this type.
2491// 3. c-style has approved of using _ in this case.
2492const internal::AnythingMatcher _ = {};
2493// Creates a matcher that matches any value of the given type T.
2494template <typename T>
2495inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2496
2497// Creates a matcher that matches any value of the given type T.
2498template <typename T>
2499inline Matcher<T> An() { return A<T>(); }
2500
2501// Creates a polymorphic matcher that matches anything equal to x.
2502// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2503// wouldn't compile.
2504template <typename T>
2505inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2506
2507// Constructs a Matcher<T> from a 'value' of type T. The constructed
2508// matcher matches any value that's equal to 'value'.
2509template <typename T>
2510Matcher<T>::Matcher(T value) { *this = Eq(value); }
2511
2512// Creates a monomorphic matcher that matches anything with type Lhs
2513// and equal to rhs. A user may need to use this instead of Eq(...)
2514// in order to resolve an overloading ambiguity.
2515//
2516// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2517// or Matcher<T>(x), but more readable than the latter.
2518//
2519// We could define similar monomorphic matchers for other comparison
2520// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2521// it yet as those are used much less than Eq() in practice. A user
2522// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2523// for example.
2524template <typename Lhs, typename Rhs>
2525inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2526
2527// Creates a polymorphic matcher that matches anything >= x.
2528template <typename Rhs>
2529inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2530 return internal::GeMatcher<Rhs>(x);
2531}
2532
2533// Creates a polymorphic matcher that matches anything > x.
2534template <typename Rhs>
2535inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2536 return internal::GtMatcher<Rhs>(x);
2537}
2538
2539// Creates a polymorphic matcher that matches anything <= x.
2540template <typename Rhs>
2541inline internal::LeMatcher<Rhs> Le(Rhs x) {
2542 return internal::LeMatcher<Rhs>(x);
2543}
2544
2545// Creates a polymorphic matcher that matches anything < x.
2546template <typename Rhs>
2547inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2548 return internal::LtMatcher<Rhs>(x);
2549}
2550
2551// Creates a polymorphic matcher that matches anything != x.
2552template <typename Rhs>
2553inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2554 return internal::NeMatcher<Rhs>(x);
2555}
2556
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002557// Creates a polymorphic matcher that matches any NULL pointer.
2558inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2559 return MakePolymorphicMatcher(internal::IsNullMatcher());
2560}
2561
shiqiane35fdd92008-12-10 05:08:54 +00002562// Creates a polymorphic matcher that matches any non-NULL pointer.
2563// This is convenient as Not(NULL) doesn't compile (the compiler
2564// thinks that that expression is comparing a pointer with an integer).
2565inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2566 return MakePolymorphicMatcher(internal::NotNullMatcher());
2567}
2568
2569// Creates a polymorphic matcher that matches any argument that
2570// references variable x.
2571template <typename T>
2572inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2573 return internal::RefMatcher<T&>(x);
2574}
2575
2576// Creates a matcher that matches any double argument approximately
2577// equal to rhs, where two NANs are considered unequal.
2578inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2579 return internal::FloatingEqMatcher<double>(rhs, false);
2580}
2581
2582// Creates a matcher that matches any double argument approximately
2583// equal to rhs, including NaN values when rhs is NaN.
2584inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2585 return internal::FloatingEqMatcher<double>(rhs, true);
2586}
2587
2588// Creates a matcher that matches any float argument approximately
2589// equal to rhs, where two NANs are considered unequal.
2590inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2591 return internal::FloatingEqMatcher<float>(rhs, false);
2592}
2593
2594// Creates a matcher that matches any double argument approximately
2595// equal to rhs, including NaN values when rhs is NaN.
2596inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2597 return internal::FloatingEqMatcher<float>(rhs, true);
2598}
2599
2600// Creates a matcher that matches a pointer (raw or smart) that points
2601// to a value that matches inner_matcher.
2602template <typename InnerMatcher>
2603inline internal::PointeeMatcher<InnerMatcher> Pointee(
2604 const InnerMatcher& inner_matcher) {
2605 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2606}
2607
2608// Creates a matcher that matches an object whose given field matches
2609// 'matcher'. For example,
2610// Field(&Foo::number, Ge(5))
2611// matches a Foo object x iff x.number >= 5.
2612template <typename Class, typename FieldType, typename FieldMatcher>
2613inline PolymorphicMatcher<
2614 internal::FieldMatcher<Class, FieldType> > Field(
2615 FieldType Class::*field, const FieldMatcher& matcher) {
2616 return MakePolymorphicMatcher(
2617 internal::FieldMatcher<Class, FieldType>(
2618 field, MatcherCast<const FieldType&>(matcher)));
2619 // The call to MatcherCast() is required for supporting inner
2620 // matchers of compatible types. For example, it allows
2621 // Field(&Foo::bar, m)
2622 // to compile where bar is an int32 and m is a matcher for int64.
2623}
2624
2625// Creates a matcher that matches an object whose given property
2626// matches 'matcher'. For example,
2627// Property(&Foo::str, StartsWith("hi"))
2628// matches a Foo object x iff x.str() starts with "hi".
2629template <typename Class, typename PropertyType, typename PropertyMatcher>
2630inline PolymorphicMatcher<
2631 internal::PropertyMatcher<Class, PropertyType> > Property(
2632 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2633 return MakePolymorphicMatcher(
2634 internal::PropertyMatcher<Class, PropertyType>(
2635 property,
zhanyong.wane0d051e2009-02-19 00:33:37 +00002636 MatcherCast<GMOCK_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002637 // The call to MatcherCast() is required for supporting inner
2638 // matchers of compatible types. For example, it allows
2639 // Property(&Foo::bar, m)
2640 // to compile where bar() returns an int32 and m is a matcher for int64.
2641}
2642
2643// Creates a matcher that matches an object iff the result of applying
2644// a callable to x matches 'matcher'.
2645// For example,
2646// ResultOf(f, StartsWith("hi"))
2647// matches a Foo object x iff f(x) starts with "hi".
2648// callable parameter can be a function, function pointer, or a functor.
2649// Callable has to satisfy the following conditions:
2650// * It is required to keep no state affecting the results of
2651// the calls on it and make no assumptions about how many calls
2652// will be made. Any state it keeps must be protected from the
2653// concurrent access.
2654// * If it is a function object, it has to define type result_type.
2655// We recommend deriving your functor classes from std::unary_function.
2656template <typename Callable, typename ResultOfMatcher>
2657internal::ResultOfMatcher<Callable> ResultOf(
2658 Callable callable, const ResultOfMatcher& matcher) {
2659 return internal::ResultOfMatcher<Callable>(
2660 callable,
2661 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2662 matcher));
2663 // The call to MatcherCast() is required for supporting inner
2664 // matchers of compatible types. For example, it allows
2665 // ResultOf(Function, m)
2666 // to compile where Function() returns an int32 and m is a matcher for int64.
2667}
2668
2669// String matchers.
2670
2671// Matches a string equal to str.
2672inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2673 StrEq(const internal::string& str) {
2674 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2675 str, true, true));
2676}
2677
2678// Matches a string not equal to str.
2679inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2680 StrNe(const internal::string& str) {
2681 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2682 str, false, true));
2683}
2684
2685// Matches a string equal to str, ignoring case.
2686inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2687 StrCaseEq(const internal::string& str) {
2688 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2689 str, true, false));
2690}
2691
2692// Matches a string not equal to str, ignoring case.
2693inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2694 StrCaseNe(const internal::string& str) {
2695 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2696 str, false, false));
2697}
2698
2699// Creates a matcher that matches any string, std::string, or C string
2700// that contains the given substring.
2701inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2702 HasSubstr(const internal::string& substring) {
2703 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
2704 substring));
2705}
2706
2707// Matches a string that starts with 'prefix' (case-sensitive).
2708inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
2709 StartsWith(const internal::string& prefix) {
2710 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
2711 prefix));
2712}
2713
2714// Matches a string that ends with 'suffix' (case-sensitive).
2715inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
2716 EndsWith(const internal::string& suffix) {
2717 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
2718 suffix));
2719}
2720
2721#ifdef GMOCK_HAS_REGEX
2722
2723// Matches a string that fully matches regular expression 'regex'.
2724// The matcher takes ownership of 'regex'.
2725inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2726 const internal::RE* regex) {
2727 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2728}
2729inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2730 const internal::string& regex) {
2731 return MatchesRegex(new internal::RE(regex));
2732}
2733
2734// Matches a string that contains regular expression 'regex'.
2735// The matcher takes ownership of 'regex'.
2736inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2737 const internal::RE* regex) {
2738 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2739}
2740inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2741 const internal::string& regex) {
2742 return ContainsRegex(new internal::RE(regex));
2743}
2744
2745#endif // GMOCK_HAS_REGEX
2746
2747#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2748// Wide string matchers.
2749
2750// Matches a string equal to str.
2751inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2752 StrEq(const internal::wstring& str) {
2753 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2754 str, true, true));
2755}
2756
2757// Matches a string not equal to str.
2758inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2759 StrNe(const internal::wstring& str) {
2760 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2761 str, false, true));
2762}
2763
2764// Matches a string equal to str, ignoring case.
2765inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2766 StrCaseEq(const internal::wstring& str) {
2767 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2768 str, true, false));
2769}
2770
2771// Matches a string not equal to str, ignoring case.
2772inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2773 StrCaseNe(const internal::wstring& str) {
2774 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2775 str, false, false));
2776}
2777
2778// Creates a matcher that matches any wstring, std::wstring, or C wide string
2779// that contains the given substring.
2780inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2781 HasSubstr(const internal::wstring& substring) {
2782 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2783 substring));
2784}
2785
2786// Matches a string that starts with 'prefix' (case-sensitive).
2787inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2788 StartsWith(const internal::wstring& prefix) {
2789 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2790 prefix));
2791}
2792
2793// Matches a string that ends with 'suffix' (case-sensitive).
2794inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2795 EndsWith(const internal::wstring& suffix) {
2796 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2797 suffix));
2798}
2799
2800#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2801
2802// Creates a polymorphic matcher that matches a 2-tuple where the
2803// first field == the second field.
2804inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2805
2806// Creates a polymorphic matcher that matches a 2-tuple where the
2807// first field >= the second field.
2808inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2809
2810// Creates a polymorphic matcher that matches a 2-tuple where the
2811// first field > the second field.
2812inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2813
2814// Creates a polymorphic matcher that matches a 2-tuple where the
2815// first field <= the second field.
2816inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2817
2818// Creates a polymorphic matcher that matches a 2-tuple where the
2819// first field < the second field.
2820inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2821
2822// Creates a polymorphic matcher that matches a 2-tuple where the
2823// first field != the second field.
2824inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2825
2826// Creates a matcher that matches any value of type T that m doesn't
2827// match.
2828template <typename InnerMatcher>
2829inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2830 return internal::NotMatcher<InnerMatcher>(m);
2831}
2832
2833// Creates a matcher that matches any value that matches all of the
2834// given matchers.
2835//
2836// For now we only support up to 5 matchers. Support for more
2837// matchers can be added as needed, or the user can use nested
2838// AllOf()s.
2839template <typename Matcher1, typename Matcher2>
2840inline internal::BothOfMatcher<Matcher1, Matcher2>
2841AllOf(Matcher1 m1, Matcher2 m2) {
2842 return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2);
2843}
2844
2845template <typename Matcher1, typename Matcher2, typename Matcher3>
2846inline internal::BothOfMatcher<Matcher1,
2847 internal::BothOfMatcher<Matcher2, Matcher3> >
2848AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2849 return AllOf(m1, AllOf(m2, m3));
2850}
2851
2852template <typename Matcher1, typename Matcher2, typename Matcher3,
2853 typename Matcher4>
2854inline internal::BothOfMatcher<Matcher1,
2855 internal::BothOfMatcher<Matcher2,
2856 internal::BothOfMatcher<Matcher3, Matcher4> > >
2857AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2858 return AllOf(m1, AllOf(m2, m3, m4));
2859}
2860
2861template <typename Matcher1, typename Matcher2, typename Matcher3,
2862 typename Matcher4, typename Matcher5>
2863inline internal::BothOfMatcher<Matcher1,
2864 internal::BothOfMatcher<Matcher2,
2865 internal::BothOfMatcher<Matcher3,
2866 internal::BothOfMatcher<Matcher4, Matcher5> > > >
2867AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2868 return AllOf(m1, AllOf(m2, m3, m4, m5));
2869}
2870
2871// Creates a matcher that matches any value that matches at least one
2872// of the given matchers.
2873//
2874// For now we only support up to 5 matchers. Support for more
2875// matchers can be added as needed, or the user can use nested
2876// AnyOf()s.
2877template <typename Matcher1, typename Matcher2>
2878inline internal::EitherOfMatcher<Matcher1, Matcher2>
2879AnyOf(Matcher1 m1, Matcher2 m2) {
2880 return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2);
2881}
2882
2883template <typename Matcher1, typename Matcher2, typename Matcher3>
2884inline internal::EitherOfMatcher<Matcher1,
2885 internal::EitherOfMatcher<Matcher2, Matcher3> >
2886AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2887 return AnyOf(m1, AnyOf(m2, m3));
2888}
2889
2890template <typename Matcher1, typename Matcher2, typename Matcher3,
2891 typename Matcher4>
2892inline internal::EitherOfMatcher<Matcher1,
2893 internal::EitherOfMatcher<Matcher2,
2894 internal::EitherOfMatcher<Matcher3, Matcher4> > >
2895AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2896 return AnyOf(m1, AnyOf(m2, m3, m4));
2897}
2898
2899template <typename Matcher1, typename Matcher2, typename Matcher3,
2900 typename Matcher4, typename Matcher5>
2901inline internal::EitherOfMatcher<Matcher1,
2902 internal::EitherOfMatcher<Matcher2,
2903 internal::EitherOfMatcher<Matcher3,
2904 internal::EitherOfMatcher<Matcher4, Matcher5> > > >
2905AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2906 return AnyOf(m1, AnyOf(m2, m3, m4, m5));
2907}
2908
2909// Returns a matcher that matches anything that satisfies the given
2910// predicate. The predicate can be any unary function or functor
2911// whose return type can be implicitly converted to bool.
2912template <typename Predicate>
2913inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
2914Truly(Predicate pred) {
2915 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
2916}
2917
zhanyong.wan6a896b52009-01-16 01:13:50 +00002918// Returns a matcher that matches an equal container.
2919// This matcher behaves like Eq(), but in the event of mismatch lists the
2920// values that are included in one container but not the other. (Duplicate
2921// values and order differences are not explained.)
2922template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00002923inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wanb8243162009-06-04 05:48:20 +00002924 GMOCK_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00002925 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002926 // This following line is for working around a bug in MSVC 8.0,
2927 // which causes Container to be a const type sometimes.
2928 typedef GMOCK_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00002929 return MakePolymorphicMatcher(
2930 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00002931}
2932
2933// Matches an STL-style container or a native array that contains at
2934// least one element matching the given value or matcher.
2935//
2936// Examples:
2937// ::std::set<int> page_ids;
2938// page_ids.insert(3);
2939// page_ids.insert(1);
2940// EXPECT_THAT(page_ids, Contains(1));
2941// EXPECT_THAT(page_ids, Contains(Gt(2)));
2942// EXPECT_THAT(page_ids, Not(Contains(4)));
2943//
2944// ::std::map<int, size_t> page_lengths;
2945// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00002946// EXPECT_THAT(page_lengths,
2947// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00002948//
2949// const char* user_ids[] = { "joe", "mike", "tom" };
2950// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
2951template <typename M>
2952inline internal::ContainsMatcher<M> Contains(M matcher) {
2953 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002954}
2955
zhanyong.wanb5937da2009-07-16 20:26:41 +00002956// Key(inner_matcher) matches an std::pair whose 'first' field matches
2957// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2958// std::map that contains at least one element whose key is >= 5.
2959template <typename M>
2960inline internal::KeyMatcher<M> Key(M inner_matcher) {
2961 return internal::KeyMatcher<M>(inner_matcher);
2962}
2963
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002964// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
2965// matches first_matcher and whose 'second' field matches second_matcher. For
2966// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
2967// to match a std::map<int, string> that contains exactly one element whose key
2968// is >= 5 and whose value equals "foo".
2969template <typename FirstMatcher, typename SecondMatcher>
2970inline internal::PairMatcher<FirstMatcher, SecondMatcher>
2971Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
2972 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
2973 first_matcher, second_matcher);
2974}
2975
shiqiane35fdd92008-12-10 05:08:54 +00002976// Returns a predicate that is satisfied by anything that matches the
2977// given matcher.
2978template <typename M>
2979inline internal::MatcherAsPredicate<M> Matches(M matcher) {
2980 return internal::MatcherAsPredicate<M>(matcher);
2981}
2982
zhanyong.wanb8243162009-06-04 05:48:20 +00002983// Returns true iff the value matches the matcher.
2984template <typename T, typename M>
2985inline bool Value(const T& value, M matcher) {
2986 return testing::Matches(matcher)(value);
2987}
2988
zhanyong.wanbf550852009-06-09 06:09:53 +00002989// AllArgs(m) is a synonym of m. This is useful in
2990//
2991// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
2992//
2993// which is easier to read than
2994//
2995// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
2996template <typename InnerMatcher>
2997inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
2998
shiqiane35fdd92008-12-10 05:08:54 +00002999// These macros allow using matchers to check values in Google Test
3000// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
3001// succeed iff the value matches the matcher. If the assertion fails,
3002// the value and the description of the matcher will be printed.
3003#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
3004 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3005#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
3006 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3007
3008} // namespace testing
3009
3010#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_