blob: 09e469e5f6b96840f5bf4a1b206086d4b13572c0 [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(
1787 typename ::testing::internal::is_pointer<T>::type(), value, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001788}
1789
1790// Implements the Property() matcher for matching a property
1791// (i.e. return value of a getter method) of an object.
1792template <typename Class, typename PropertyType>
1793class PropertyMatcher {
1794 public:
1795 // The property may have a reference type, so 'const PropertyType&'
1796 // may cause double references and fail to compile. That's why we
1797 // need GMOCK_REFERENCE_TO_CONST, which works regardless of
1798 // PropertyType being a reference or not.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001799 typedef GMOCK_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001800
1801 PropertyMatcher(PropertyType (Class::*property)() const,
1802 const Matcher<RefToConstProperty>& matcher)
1803 : property_(property), matcher_(matcher) {}
1804
shiqiane35fdd92008-12-10 05:08:54 +00001805 void DescribeTo(::std::ostream* os) const {
1806 *os << "the given property ";
1807 matcher_.DescribeTo(os);
1808 }
1809
1810 void DescribeNegationTo(::std::ostream* os) const {
1811 *os << "the given property ";
1812 matcher_.DescribeNegationTo(os);
1813 }
1814
zhanyong.wan82113312010-01-08 21:55:40 +00001815 // The first argument of MatchAndExplain() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001816 // Symbian's C++ compiler choose which overload to use. Its type is
1817 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wan82113312010-01-08 21:55:40 +00001818 bool MatchAndExplain(false_type /* is_not_pointer */, const Class& obj,
1819 MatchResultListener* listener) const {
1820 StringMatchResultListener inner_listener;
1821 const bool match = matcher_.MatchAndExplain((obj.*property_)(),
1822 &inner_listener);
1823 const internal::string s = inner_listener.str();
shiqiane35fdd92008-12-10 05:08:54 +00001824 if (s != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00001825 *listener << "the given property " << s;
shiqiane35fdd92008-12-10 05:08:54 +00001826 }
zhanyong.wan82113312010-01-08 21:55:40 +00001827 return match;
shiqiane35fdd92008-12-10 05:08:54 +00001828 }
1829
zhanyong.wan82113312010-01-08 21:55:40 +00001830 bool MatchAndExplain(true_type /* is_pointer */, const Class* p,
1831 MatchResultListener* listener) const {
1832 if (p == NULL)
1833 return false;
1834
1835 // Since *p has a property method, it must be a class/struct/union
1836 // type and thus cannot be a pointer. Therefore we pass
1837 // false_type() as the first argument.
1838 return MatchAndExplain(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001839 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001840
shiqiane35fdd92008-12-10 05:08:54 +00001841 private:
1842 PropertyType (Class::*property_)() const;
1843 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001844
1845 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001846};
1847
zhanyong.wan82113312010-01-08 21:55:40 +00001848template <typename Class, typename PropertyType, typename T>
1849bool MatchAndExplain(const PropertyMatcher<Class, PropertyType>& matcher,
zhanyong.wane122e452010-01-12 09:03:52 +00001850 T& value, MatchResultListener* listener) {
zhanyong.wan82113312010-01-08 21:55:40 +00001851 return matcher.MatchAndExplain(
1852 typename ::testing::internal::is_pointer<T>::type(), value, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001853}
1854
1855// Type traits specifying various features of different functors for ResultOf.
1856// The default template specifies features for functor objects.
1857// Functor classes have to typedef argument_type and result_type
1858// to be compatible with ResultOf.
1859template <typename Functor>
1860struct CallableTraits {
1861 typedef typename Functor::result_type ResultType;
1862 typedef Functor StorageType;
1863
zhanyong.wan32de5f52009-12-23 00:13:23 +00001864 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00001865 template <typename T>
1866 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1867};
1868
1869// Specialization for function pointers.
1870template <typename ArgType, typename ResType>
1871struct CallableTraits<ResType(*)(ArgType)> {
1872 typedef ResType ResultType;
1873 typedef ResType(*StorageType)(ArgType);
1874
1875 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001876 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00001877 << "NULL function pointer is passed into ResultOf().";
1878 }
1879 template <typename T>
1880 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1881 return (*f)(arg);
1882 }
1883};
1884
1885// Implements the ResultOf() matcher for matching a return value of a
1886// unary function of an object.
1887template <typename Callable>
1888class ResultOfMatcher {
1889 public:
1890 typedef typename CallableTraits<Callable>::ResultType ResultType;
1891
1892 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1893 : callable_(callable), matcher_(matcher) {
1894 CallableTraits<Callable>::CheckIsValid(callable_);
1895 }
1896
1897 template <typename T>
1898 operator Matcher<T>() const {
1899 return Matcher<T>(new Impl<T>(callable_, matcher_));
1900 }
1901
1902 private:
1903 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1904
1905 template <typename T>
1906 class Impl : public MatcherInterface<T> {
1907 public:
1908 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1909 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00001910
1911 virtual void DescribeTo(::std::ostream* os) const {
1912 *os << "result of the given callable ";
1913 matcher_.DescribeTo(os);
1914 }
1915
1916 virtual void DescribeNegationTo(::std::ostream* os) const {
1917 *os << "result of the given callable ";
1918 matcher_.DescribeNegationTo(os);
1919 }
1920
zhanyong.wan82113312010-01-08 21:55:40 +00001921 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
1922 StringMatchResultListener inner_listener;
1923 const bool match = matcher_.MatchAndExplain(
shiqiane35fdd92008-12-10 05:08:54 +00001924 CallableTraits<Callable>::template Invoke<T>(callable_, obj),
zhanyong.wan82113312010-01-08 21:55:40 +00001925 &inner_listener);
1926
1927 const internal::string s = inner_listener.str();
shiqiane35fdd92008-12-10 05:08:54 +00001928 if (s != "")
zhanyong.wan82113312010-01-08 21:55:40 +00001929 *listener << "result of the given callable " << s;
1930
1931 return match;
shiqiane35fdd92008-12-10 05:08:54 +00001932 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001933
shiqiane35fdd92008-12-10 05:08:54 +00001934 private:
1935 // Functors often define operator() as non-const method even though
1936 // they are actualy stateless. But we need to use them even when
1937 // 'this' is a const pointer. It's the user's responsibility not to
1938 // use stateful callables with ResultOf(), which does't guarantee
1939 // how many times the callable will be invoked.
1940 mutable CallableStorageType callable_;
1941 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001942
1943 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001944 }; // class Impl
1945
1946 const CallableStorageType callable_;
1947 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001948
1949 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001950};
1951
1952// Explains the result of matching a value against a functor matcher.
1953template <typename T, typename Callable>
1954void ExplainMatchResultTo(const ResultOfMatcher<Callable>& matcher,
1955 T obj, ::std::ostream* os) {
1956 matcher.ExplainMatchResultTo(obj, os);
1957}
1958
zhanyong.wan6a896b52009-01-16 01:13:50 +00001959// Implements an equality matcher for any STL-style container whose elements
1960// support ==. This matcher is like Eq(), but its failure explanations provide
1961// more detailed information that is useful when the container is used as a set.
1962// The failure message reports elements that are in one of the operands but not
1963// the other. The failure messages do not report duplicate or out-of-order
1964// elements in the containers (which don't properly matter to sets, but can
1965// occur if the containers are vectors or lists, for example).
1966//
1967// Uses the container's const_iterator, value_type, operator ==,
1968// begin(), and end().
1969template <typename Container>
1970class ContainerEqMatcher {
1971 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00001972 typedef internal::StlContainerView<Container> View;
1973 typedef typename View::type StlContainer;
1974 typedef typename View::const_reference StlContainerReference;
1975
1976 // We make a copy of rhs in case the elements in it are modified
1977 // after this matcher is created.
1978 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
1979 // Makes sure the user doesn't instantiate this class template
1980 // with a const or reference type.
1981 testing::StaticAssertTypeEq<Container,
1982 GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))>();
1983 }
1984
zhanyong.wan6a896b52009-01-16 01:13:50 +00001985 void DescribeTo(::std::ostream* os) const {
1986 *os << "equals ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001987 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001988 }
1989 void DescribeNegationTo(::std::ostream* os) const {
1990 *os << "does not equal ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001991 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001992 }
1993
zhanyong.wanb8243162009-06-04 05:48:20 +00001994 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00001995 bool MatchAndExplain(const LhsContainer& lhs,
1996 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00001997 // GMOCK_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
1998 // that causes LhsContainer to be a const type sometimes.
1999 typedef internal::StlContainerView<GMOCK_REMOVE_CONST_(LhsContainer)>
2000 LhsView;
2001 typedef typename LhsView::type LhsStlContainer;
2002 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00002003 if (lhs_stl_container == rhs_)
2004 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002005
zhanyong.wane122e452010-01-12 09:03:52 +00002006 ::std::ostream* const os = listener->stream();
2007 if (os != NULL) {
2008 // Something is different. Check for missing values first.
2009 bool printed_header = false;
2010 for (typename LhsStlContainer::const_iterator it =
2011 lhs_stl_container.begin();
2012 it != lhs_stl_container.end(); ++it) {
2013 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
2014 rhs_.end()) {
2015 if (printed_header) {
2016 *os << ", ";
2017 } else {
2018 *os << "Only in actual: ";
2019 printed_header = true;
2020 }
2021 UniversalPrinter<typename LhsStlContainer::value_type>::Print(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002022 }
zhanyong.wane122e452010-01-12 09:03:52 +00002023 }
2024
2025 // Now check for extra values.
2026 bool printed_header2 = false;
2027 for (typename StlContainer::const_iterator it = rhs_.begin();
2028 it != rhs_.end(); ++it) {
2029 if (internal::ArrayAwareFind(
2030 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2031 lhs_stl_container.end()) {
2032 if (printed_header2) {
2033 *os << ", ";
2034 } else {
2035 *os << (printed_header ? "; not" : "Not") << " in actual: ";
2036 printed_header2 = true;
2037 }
2038 UniversalPrinter<typename StlContainer::value_type>::Print(*it, os);
2039 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00002040 }
2041 }
2042
zhanyong.wane122e452010-01-12 09:03:52 +00002043 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00002044 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002045
zhanyong.wan6a896b52009-01-16 01:13:50 +00002046 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00002047 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002048
2049 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002050};
2051
zhanyong.wanb8243162009-06-04 05:48:20 +00002052template <typename LhsContainer, typename Container>
zhanyong.wane122e452010-01-12 09:03:52 +00002053bool MatchAndExplain(const ContainerEqMatcher<Container>& matcher,
2054 LhsContainer& lhs,
2055 MatchResultListener* listener) {
2056 return matcher.MatchAndExplain(lhs, listener);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002057}
2058
zhanyong.wanb8243162009-06-04 05:48:20 +00002059// Implements Contains(element_matcher) for the given argument type Container.
2060template <typename Container>
2061class ContainsMatcherImpl : public MatcherInterface<Container> {
2062 public:
2063 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
2064 typedef StlContainerView<RawContainer> View;
2065 typedef typename View::type StlContainer;
2066 typedef typename View::const_reference StlContainerReference;
2067 typedef typename StlContainer::value_type Element;
2068
2069 template <typename InnerMatcher>
2070 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2071 : inner_matcher_(
2072 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
2073
zhanyong.wanb8243162009-06-04 05:48:20 +00002074 // Describes what this matcher does.
2075 virtual void DescribeTo(::std::ostream* os) const {
2076 *os << "contains at least one element that ";
2077 inner_matcher_.DescribeTo(os);
2078 }
2079
2080 // Describes what the negation of this matcher does.
2081 virtual void DescribeNegationTo(::std::ostream* os) const {
2082 *os << "doesn't contain any element that ";
2083 inner_matcher_.DescribeTo(os);
2084 }
2085
zhanyong.wan82113312010-01-08 21:55:40 +00002086 virtual bool MatchAndExplain(Container container,
2087 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002088 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002089 size_t i = 0;
2090 for (typename StlContainer::const_iterator it = stl_container.begin();
2091 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002092 if (inner_matcher_.Matches(*it)) {
zhanyong.wan82113312010-01-08 21:55:40 +00002093 *listener << "element " << i << " matches";
2094 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00002095 }
2096 }
zhanyong.wan82113312010-01-08 21:55:40 +00002097 return false;
zhanyong.wanb8243162009-06-04 05:48:20 +00002098 }
2099
2100 private:
2101 const Matcher<const Element&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002102
2103 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002104};
2105
2106// Implements polymorphic Contains(element_matcher).
2107template <typename M>
2108class ContainsMatcher {
2109 public:
2110 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2111
2112 template <typename Container>
2113 operator Matcher<Container>() const {
2114 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2115 }
2116
2117 private:
2118 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002119
2120 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002121};
2122
zhanyong.wanb5937da2009-07-16 20:26:41 +00002123// Implements Key(inner_matcher) for the given argument pair type.
2124// Key(inner_matcher) matches an std::pair whose 'first' field matches
2125// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2126// std::map that contains at least one element whose key is >= 5.
2127template <typename PairType>
2128class KeyMatcherImpl : public MatcherInterface<PairType> {
2129 public:
2130 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
2131 typedef typename RawPairType::first_type KeyType;
2132
2133 template <typename InnerMatcher>
2134 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2135 : inner_matcher_(
2136 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2137 }
2138
2139 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002140 virtual bool MatchAndExplain(PairType key_value,
2141 MatchResultListener* listener) const {
2142 return inner_matcher_.MatchAndExplain(key_value.first, listener);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002143 }
2144
2145 // Describes what this matcher does.
2146 virtual void DescribeTo(::std::ostream* os) const {
2147 *os << "has a key that ";
2148 inner_matcher_.DescribeTo(os);
2149 }
2150
2151 // Describes what the negation of this matcher does.
2152 virtual void DescribeNegationTo(::std::ostream* os) const {
2153 *os << "doesn't have a key that ";
2154 inner_matcher_.DescribeTo(os);
2155 }
2156
zhanyong.wanb5937da2009-07-16 20:26:41 +00002157 private:
2158 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002159
2160 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002161};
2162
2163// Implements polymorphic Key(matcher_for_key).
2164template <typename M>
2165class KeyMatcher {
2166 public:
2167 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2168
2169 template <typename PairType>
2170 operator Matcher<PairType>() const {
2171 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2172 }
2173
2174 private:
2175 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002176
2177 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002178};
2179
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002180// Implements Pair(first_matcher, second_matcher) for the given argument pair
2181// type with its two matchers. See Pair() function below.
2182template <typename PairType>
2183class PairMatcherImpl : public MatcherInterface<PairType> {
2184 public:
2185 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
2186 typedef typename RawPairType::first_type FirstType;
2187 typedef typename RawPairType::second_type SecondType;
2188
2189 template <typename FirstMatcher, typename SecondMatcher>
2190 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2191 : first_matcher_(
2192 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2193 second_matcher_(
2194 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2195 }
2196
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002197 // Describes what this matcher does.
2198 virtual void DescribeTo(::std::ostream* os) const {
2199 *os << "has a first field that ";
2200 first_matcher_.DescribeTo(os);
2201 *os << ", and has a second field that ";
2202 second_matcher_.DescribeTo(os);
2203 }
2204
2205 // Describes what the negation of this matcher does.
2206 virtual void DescribeNegationTo(::std::ostream* os) const {
2207 *os << "has a first field that ";
2208 first_matcher_.DescribeNegationTo(os);
2209 *os << ", or has a second field that ";
2210 second_matcher_.DescribeNegationTo(os);
2211 }
2212
zhanyong.wan82113312010-01-08 21:55:40 +00002213 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2214 // matches second_matcher.
2215 virtual bool MatchAndExplain(PairType a_pair,
2216 MatchResultListener* listener) const {
2217 StringMatchResultListener listener1;
2218 const bool match1 = first_matcher_.MatchAndExplain(a_pair.first,
2219 &listener1);
2220 internal::string s1 = listener1.str();
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002221 if (s1 != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00002222 s1 = "the first field " + s1;
2223 }
2224 if (!match1) {
2225 *listener << s1;
2226 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002227 }
2228
zhanyong.wan82113312010-01-08 21:55:40 +00002229 StringMatchResultListener listener2;
2230 const bool match2 = second_matcher_.MatchAndExplain(a_pair.second,
2231 &listener2);
2232 internal::string s2 = listener2.str();
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002233 if (s2 != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00002234 s2 = "the second field " + s2;
2235 }
2236 if (!match2) {
2237 *listener << s2;
2238 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002239 }
2240
zhanyong.wan82113312010-01-08 21:55:40 +00002241 *listener << s1;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002242 if (s1 != "" && s2 != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00002243 *listener << ", and ";
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002244 }
zhanyong.wan82113312010-01-08 21:55:40 +00002245 *listener << s2;
2246 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002247 }
2248
2249 private:
2250 const Matcher<const FirstType&> first_matcher_;
2251 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002252
2253 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002254};
2255
2256// Implements polymorphic Pair(first_matcher, second_matcher).
2257template <typename FirstMatcher, typename SecondMatcher>
2258class PairMatcher {
2259 public:
2260 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2261 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2262
2263 template <typename PairType>
2264 operator Matcher<PairType> () const {
2265 return MakeMatcher(
2266 new PairMatcherImpl<PairType>(
2267 first_matcher_, second_matcher_));
2268 }
2269
2270 private:
2271 const FirstMatcher first_matcher_;
2272 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002273
2274 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002275};
2276
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002277// Implements ElementsAre() and ElementsAreArray().
2278template <typename Container>
2279class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2280 public:
2281 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
2282 typedef internal::StlContainerView<RawContainer> View;
2283 typedef typename View::type StlContainer;
2284 typedef typename View::const_reference StlContainerReference;
2285 typedef typename StlContainer::value_type Element;
2286
2287 // Constructs the matcher from a sequence of element values or
2288 // element matchers.
2289 template <typename InputIter>
zhanyong.wan32de5f52009-12-23 00:13:23 +00002290 ElementsAreMatcherImpl(InputIter first, size_t a_count) {
2291 matchers_.reserve(a_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002292 InputIter it = first;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002293 for (size_t i = 0; i != a_count; ++i, ++it) {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002294 matchers_.push_back(MatcherCast<const Element&>(*it));
2295 }
2296 }
2297
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002298 // Describes what this matcher does.
2299 virtual void DescribeTo(::std::ostream* os) const {
2300 if (count() == 0) {
2301 *os << "is empty";
2302 } else if (count() == 1) {
2303 *os << "has 1 element that ";
2304 matchers_[0].DescribeTo(os);
2305 } else {
2306 *os << "has " << Elements(count()) << " where\n";
2307 for (size_t i = 0; i != count(); ++i) {
2308 *os << "element " << i << " ";
2309 matchers_[i].DescribeTo(os);
2310 if (i + 1 < count()) {
2311 *os << ",\n";
2312 }
2313 }
2314 }
2315 }
2316
2317 // Describes what the negation of this matcher does.
2318 virtual void DescribeNegationTo(::std::ostream* os) const {
2319 if (count() == 0) {
2320 *os << "is not empty";
2321 return;
2322 }
2323
2324 *os << "does not have " << Elements(count()) << ", or\n";
2325 for (size_t i = 0; i != count(); ++i) {
2326 *os << "element " << i << " ";
2327 matchers_[i].DescribeNegationTo(os);
2328 if (i + 1 < count()) {
2329 *os << ", or\n";
2330 }
2331 }
2332 }
2333
zhanyong.wan82113312010-01-08 21:55:40 +00002334 virtual bool MatchAndExplain(Container container,
2335 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002336 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002337 const size_t actual_count = stl_container.size();
2338 if (actual_count != count()) {
2339 // The element count doesn't match. If the container is empty,
2340 // there's no need to explain anything as Google Mock already
2341 // prints the empty container. Otherwise we just need to show
2342 // how many elements there actually are.
2343 if (actual_count != 0) {
2344 *listener << "has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002345 }
zhanyong.wan82113312010-01-08 21:55:40 +00002346 return false;
2347 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002348
zhanyong.wan82113312010-01-08 21:55:40 +00002349 typename StlContainer::const_iterator it = stl_container.begin();
2350 // explanations[i] is the explanation of the element at index i.
2351 std::vector<internal::string> explanations(count());
2352 for (size_t i = 0; i != count(); ++it, ++i) {
2353 StringMatchResultListener s;
2354 if (matchers_[i].MatchAndExplain(*it, &s)) {
2355 explanations[i] = s.str();
2356 } else {
2357 // The container has the right size but the i-th element
2358 // doesn't match its expectation.
2359 *listener << "element " << i << " doesn't match";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002360
zhanyong.wan82113312010-01-08 21:55:40 +00002361 StreamInParensAsNeeded(s.str(), listener->stream());
2362 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002363 }
2364 }
zhanyong.wan82113312010-01-08 21:55:40 +00002365
2366 // Every element matches its expectation. We need to explain why
2367 // (the obvious ones can be skipped).
2368
2369 bool reason_printed = false;
2370 for (size_t i = 0; i != count(); ++i) {
2371 const internal::string& s = explanations[i];
2372 if (!s.empty()) {
2373 if (reason_printed) {
2374 *listener << ",\n";
2375 }
2376 *listener << "element " << i << " " << s;
2377 reason_printed = true;
2378 }
2379 }
2380
2381 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002382 }
2383
2384 private:
2385 static Message Elements(size_t count) {
2386 return Message() << count << (count == 1 ? " element" : " elements");
2387 }
2388
2389 size_t count() const { return matchers_.size(); }
2390 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002391
2392 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002393};
2394
2395// Implements ElementsAre() of 0 arguments.
2396class ElementsAreMatcher0 {
2397 public:
2398 ElementsAreMatcher0() {}
2399
2400 template <typename Container>
2401 operator Matcher<Container>() const {
2402 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2403 RawContainer;
2404 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2405 Element;
2406
2407 const Matcher<const Element&>* const matchers = NULL;
2408 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 0));
2409 }
2410};
2411
2412// Implements ElementsAreArray().
2413template <typename T>
2414class ElementsAreArrayMatcher {
2415 public:
2416 ElementsAreArrayMatcher(const T* first, size_t count) :
2417 first_(first), count_(count) {}
2418
2419 template <typename Container>
2420 operator Matcher<Container>() const {
2421 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2422 RawContainer;
2423 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2424 Element;
2425
2426 return MakeMatcher(new ElementsAreMatcherImpl<Container>(first_, count_));
2427 }
2428
2429 private:
2430 const T* const first_;
2431 const size_t count_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002432
2433 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002434};
2435
2436// Constants denoting interpolations in a matcher description string.
2437const int kTupleInterpolation = -1; // "%(*)s"
2438const int kPercentInterpolation = -2; // "%%"
2439const int kInvalidInterpolation = -3; // "%" followed by invalid text
2440
2441// Records the location and content of an interpolation.
2442struct Interpolation {
2443 Interpolation(const char* start, const char* end, int param)
2444 : start_pos(start), end_pos(end), param_index(param) {}
2445
2446 // Points to the start of the interpolation (the '%' character).
2447 const char* start_pos;
2448 // Points to the first character after the interpolation.
2449 const char* end_pos;
2450 // 0-based index of the interpolated matcher parameter;
2451 // kTupleInterpolation for "%(*)s"; kPercentInterpolation for "%%".
2452 int param_index;
2453};
2454
2455typedef ::std::vector<Interpolation> Interpolations;
2456
2457// Parses a matcher description string and returns a vector of
2458// interpolations that appear in the string; generates non-fatal
2459// failures iff 'description' is an invalid matcher description.
2460// 'param_names' is a NULL-terminated array of parameter names in the
2461// order they appear in the MATCHER_P*() parameter list.
2462Interpolations ValidateMatcherDescription(
2463 const char* param_names[], const char* description);
2464
2465// Returns the actual matcher description, given the matcher name,
2466// user-supplied description template string, interpolations in the
2467// string, and the printed values of the matcher parameters.
2468string FormatMatcherDescription(
2469 const char* matcher_name, const char* description,
2470 const Interpolations& interp, const Strings& param_values);
2471
shiqiane35fdd92008-12-10 05:08:54 +00002472} // namespace internal
2473
2474// Implements MatcherCast().
2475template <typename T, typename M>
2476inline Matcher<T> MatcherCast(M matcher) {
2477 return internal::MatcherCastImpl<T, M>::Cast(matcher);
2478}
2479
2480// _ is a matcher that matches anything of any type.
2481//
2482// This definition is fine as:
2483//
2484// 1. The C++ standard permits using the name _ in a namespace that
2485// is not the global namespace or ::std.
2486// 2. The AnythingMatcher class has no data member or constructor,
2487// so it's OK to create global variables of this type.
2488// 3. c-style has approved of using _ in this case.
2489const internal::AnythingMatcher _ = {};
2490// Creates a matcher that matches any value of the given type T.
2491template <typename T>
2492inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2493
2494// Creates a matcher that matches any value of the given type T.
2495template <typename T>
2496inline Matcher<T> An() { return A<T>(); }
2497
2498// Creates a polymorphic matcher that matches anything equal to x.
2499// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2500// wouldn't compile.
2501template <typename T>
2502inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2503
2504// Constructs a Matcher<T> from a 'value' of type T. The constructed
2505// matcher matches any value that's equal to 'value'.
2506template <typename T>
2507Matcher<T>::Matcher(T value) { *this = Eq(value); }
2508
2509// Creates a monomorphic matcher that matches anything with type Lhs
2510// and equal to rhs. A user may need to use this instead of Eq(...)
2511// in order to resolve an overloading ambiguity.
2512//
2513// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2514// or Matcher<T>(x), but more readable than the latter.
2515//
2516// We could define similar monomorphic matchers for other comparison
2517// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2518// it yet as those are used much less than Eq() in practice. A user
2519// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2520// for example.
2521template <typename Lhs, typename Rhs>
2522inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2523
2524// Creates a polymorphic matcher that matches anything >= x.
2525template <typename Rhs>
2526inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2527 return internal::GeMatcher<Rhs>(x);
2528}
2529
2530// Creates a polymorphic matcher that matches anything > x.
2531template <typename Rhs>
2532inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2533 return internal::GtMatcher<Rhs>(x);
2534}
2535
2536// Creates a polymorphic matcher that matches anything <= x.
2537template <typename Rhs>
2538inline internal::LeMatcher<Rhs> Le(Rhs x) {
2539 return internal::LeMatcher<Rhs>(x);
2540}
2541
2542// Creates a polymorphic matcher that matches anything < x.
2543template <typename Rhs>
2544inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2545 return internal::LtMatcher<Rhs>(x);
2546}
2547
2548// Creates a polymorphic matcher that matches anything != x.
2549template <typename Rhs>
2550inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2551 return internal::NeMatcher<Rhs>(x);
2552}
2553
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002554// Creates a polymorphic matcher that matches any NULL pointer.
2555inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2556 return MakePolymorphicMatcher(internal::IsNullMatcher());
2557}
2558
shiqiane35fdd92008-12-10 05:08:54 +00002559// Creates a polymorphic matcher that matches any non-NULL pointer.
2560// This is convenient as Not(NULL) doesn't compile (the compiler
2561// thinks that that expression is comparing a pointer with an integer).
2562inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2563 return MakePolymorphicMatcher(internal::NotNullMatcher());
2564}
2565
2566// Creates a polymorphic matcher that matches any argument that
2567// references variable x.
2568template <typename T>
2569inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2570 return internal::RefMatcher<T&>(x);
2571}
2572
2573// Creates a matcher that matches any double argument approximately
2574// equal to rhs, where two NANs are considered unequal.
2575inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2576 return internal::FloatingEqMatcher<double>(rhs, false);
2577}
2578
2579// Creates a matcher that matches any double argument approximately
2580// equal to rhs, including NaN values when rhs is NaN.
2581inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2582 return internal::FloatingEqMatcher<double>(rhs, true);
2583}
2584
2585// Creates a matcher that matches any float argument approximately
2586// equal to rhs, where two NANs are considered unequal.
2587inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2588 return internal::FloatingEqMatcher<float>(rhs, false);
2589}
2590
2591// Creates a matcher that matches any double argument approximately
2592// equal to rhs, including NaN values when rhs is NaN.
2593inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2594 return internal::FloatingEqMatcher<float>(rhs, true);
2595}
2596
2597// Creates a matcher that matches a pointer (raw or smart) that points
2598// to a value that matches inner_matcher.
2599template <typename InnerMatcher>
2600inline internal::PointeeMatcher<InnerMatcher> Pointee(
2601 const InnerMatcher& inner_matcher) {
2602 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2603}
2604
2605// Creates a matcher that matches an object whose given field matches
2606// 'matcher'. For example,
2607// Field(&Foo::number, Ge(5))
2608// matches a Foo object x iff x.number >= 5.
2609template <typename Class, typename FieldType, typename FieldMatcher>
2610inline PolymorphicMatcher<
2611 internal::FieldMatcher<Class, FieldType> > Field(
2612 FieldType Class::*field, const FieldMatcher& matcher) {
2613 return MakePolymorphicMatcher(
2614 internal::FieldMatcher<Class, FieldType>(
2615 field, MatcherCast<const FieldType&>(matcher)));
2616 // The call to MatcherCast() is required for supporting inner
2617 // matchers of compatible types. For example, it allows
2618 // Field(&Foo::bar, m)
2619 // to compile where bar is an int32 and m is a matcher for int64.
2620}
2621
2622// Creates a matcher that matches an object whose given property
2623// matches 'matcher'. For example,
2624// Property(&Foo::str, StartsWith("hi"))
2625// matches a Foo object x iff x.str() starts with "hi".
2626template <typename Class, typename PropertyType, typename PropertyMatcher>
2627inline PolymorphicMatcher<
2628 internal::PropertyMatcher<Class, PropertyType> > Property(
2629 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2630 return MakePolymorphicMatcher(
2631 internal::PropertyMatcher<Class, PropertyType>(
2632 property,
zhanyong.wane0d051e2009-02-19 00:33:37 +00002633 MatcherCast<GMOCK_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002634 // The call to MatcherCast() is required for supporting inner
2635 // matchers of compatible types. For example, it allows
2636 // Property(&Foo::bar, m)
2637 // to compile where bar() returns an int32 and m is a matcher for int64.
2638}
2639
2640// Creates a matcher that matches an object iff the result of applying
2641// a callable to x matches 'matcher'.
2642// For example,
2643// ResultOf(f, StartsWith("hi"))
2644// matches a Foo object x iff f(x) starts with "hi".
2645// callable parameter can be a function, function pointer, or a functor.
2646// Callable has to satisfy the following conditions:
2647// * It is required to keep no state affecting the results of
2648// the calls on it and make no assumptions about how many calls
2649// will be made. Any state it keeps must be protected from the
2650// concurrent access.
2651// * If it is a function object, it has to define type result_type.
2652// We recommend deriving your functor classes from std::unary_function.
2653template <typename Callable, typename ResultOfMatcher>
2654internal::ResultOfMatcher<Callable> ResultOf(
2655 Callable callable, const ResultOfMatcher& matcher) {
2656 return internal::ResultOfMatcher<Callable>(
2657 callable,
2658 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2659 matcher));
2660 // The call to MatcherCast() is required for supporting inner
2661 // matchers of compatible types. For example, it allows
2662 // ResultOf(Function, m)
2663 // to compile where Function() returns an int32 and m is a matcher for int64.
2664}
2665
2666// String matchers.
2667
2668// Matches a string equal to str.
2669inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2670 StrEq(const internal::string& str) {
2671 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2672 str, true, true));
2673}
2674
2675// Matches a string not equal to str.
2676inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2677 StrNe(const internal::string& str) {
2678 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2679 str, false, true));
2680}
2681
2682// Matches a string equal to str, ignoring case.
2683inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2684 StrCaseEq(const internal::string& str) {
2685 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2686 str, true, false));
2687}
2688
2689// Matches a string not equal to str, ignoring case.
2690inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2691 StrCaseNe(const internal::string& str) {
2692 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2693 str, false, false));
2694}
2695
2696// Creates a matcher that matches any string, std::string, or C string
2697// that contains the given substring.
2698inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2699 HasSubstr(const internal::string& substring) {
2700 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
2701 substring));
2702}
2703
2704// Matches a string that starts with 'prefix' (case-sensitive).
2705inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
2706 StartsWith(const internal::string& prefix) {
2707 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
2708 prefix));
2709}
2710
2711// Matches a string that ends with 'suffix' (case-sensitive).
2712inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
2713 EndsWith(const internal::string& suffix) {
2714 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
2715 suffix));
2716}
2717
2718#ifdef GMOCK_HAS_REGEX
2719
2720// Matches a string that fully matches regular expression 'regex'.
2721// The matcher takes ownership of 'regex'.
2722inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2723 const internal::RE* regex) {
2724 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2725}
2726inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2727 const internal::string& regex) {
2728 return MatchesRegex(new internal::RE(regex));
2729}
2730
2731// Matches a string that contains regular expression 'regex'.
2732// The matcher takes ownership of 'regex'.
2733inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2734 const internal::RE* regex) {
2735 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2736}
2737inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2738 const internal::string& regex) {
2739 return ContainsRegex(new internal::RE(regex));
2740}
2741
2742#endif // GMOCK_HAS_REGEX
2743
2744#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2745// Wide string matchers.
2746
2747// Matches a string equal to str.
2748inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2749 StrEq(const internal::wstring& str) {
2750 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2751 str, true, true));
2752}
2753
2754// Matches a string not equal to str.
2755inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2756 StrNe(const internal::wstring& str) {
2757 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2758 str, false, true));
2759}
2760
2761// Matches a string equal to str, ignoring case.
2762inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2763 StrCaseEq(const internal::wstring& str) {
2764 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2765 str, true, false));
2766}
2767
2768// Matches a string not equal to str, ignoring case.
2769inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2770 StrCaseNe(const internal::wstring& str) {
2771 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2772 str, false, false));
2773}
2774
2775// Creates a matcher that matches any wstring, std::wstring, or C wide string
2776// that contains the given substring.
2777inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2778 HasSubstr(const internal::wstring& substring) {
2779 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2780 substring));
2781}
2782
2783// Matches a string that starts with 'prefix' (case-sensitive).
2784inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2785 StartsWith(const internal::wstring& prefix) {
2786 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2787 prefix));
2788}
2789
2790// Matches a string that ends with 'suffix' (case-sensitive).
2791inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2792 EndsWith(const internal::wstring& suffix) {
2793 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2794 suffix));
2795}
2796
2797#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2798
2799// Creates a polymorphic matcher that matches a 2-tuple where the
2800// first field == the second field.
2801inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2802
2803// Creates a polymorphic matcher that matches a 2-tuple where the
2804// first field >= the second field.
2805inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2806
2807// Creates a polymorphic matcher that matches a 2-tuple where the
2808// first field > the second field.
2809inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2810
2811// Creates a polymorphic matcher that matches a 2-tuple where the
2812// first field <= the second field.
2813inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2814
2815// Creates a polymorphic matcher that matches a 2-tuple where the
2816// first field < the second field.
2817inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2818
2819// Creates a polymorphic matcher that matches a 2-tuple where the
2820// first field != the second field.
2821inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2822
2823// Creates a matcher that matches any value of type T that m doesn't
2824// match.
2825template <typename InnerMatcher>
2826inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2827 return internal::NotMatcher<InnerMatcher>(m);
2828}
2829
2830// Creates a matcher that matches any value that matches all of the
2831// given matchers.
2832//
2833// For now we only support up to 5 matchers. Support for more
2834// matchers can be added as needed, or the user can use nested
2835// AllOf()s.
2836template <typename Matcher1, typename Matcher2>
2837inline internal::BothOfMatcher<Matcher1, Matcher2>
2838AllOf(Matcher1 m1, Matcher2 m2) {
2839 return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2);
2840}
2841
2842template <typename Matcher1, typename Matcher2, typename Matcher3>
2843inline internal::BothOfMatcher<Matcher1,
2844 internal::BothOfMatcher<Matcher2, Matcher3> >
2845AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2846 return AllOf(m1, AllOf(m2, m3));
2847}
2848
2849template <typename Matcher1, typename Matcher2, typename Matcher3,
2850 typename Matcher4>
2851inline internal::BothOfMatcher<Matcher1,
2852 internal::BothOfMatcher<Matcher2,
2853 internal::BothOfMatcher<Matcher3, Matcher4> > >
2854AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2855 return AllOf(m1, AllOf(m2, m3, m4));
2856}
2857
2858template <typename Matcher1, typename Matcher2, typename Matcher3,
2859 typename Matcher4, typename Matcher5>
2860inline internal::BothOfMatcher<Matcher1,
2861 internal::BothOfMatcher<Matcher2,
2862 internal::BothOfMatcher<Matcher3,
2863 internal::BothOfMatcher<Matcher4, Matcher5> > > >
2864AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2865 return AllOf(m1, AllOf(m2, m3, m4, m5));
2866}
2867
2868// Creates a matcher that matches any value that matches at least one
2869// of the given matchers.
2870//
2871// For now we only support up to 5 matchers. Support for more
2872// matchers can be added as needed, or the user can use nested
2873// AnyOf()s.
2874template <typename Matcher1, typename Matcher2>
2875inline internal::EitherOfMatcher<Matcher1, Matcher2>
2876AnyOf(Matcher1 m1, Matcher2 m2) {
2877 return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2);
2878}
2879
2880template <typename Matcher1, typename Matcher2, typename Matcher3>
2881inline internal::EitherOfMatcher<Matcher1,
2882 internal::EitherOfMatcher<Matcher2, Matcher3> >
2883AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2884 return AnyOf(m1, AnyOf(m2, m3));
2885}
2886
2887template <typename Matcher1, typename Matcher2, typename Matcher3,
2888 typename Matcher4>
2889inline internal::EitherOfMatcher<Matcher1,
2890 internal::EitherOfMatcher<Matcher2,
2891 internal::EitherOfMatcher<Matcher3, Matcher4> > >
2892AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2893 return AnyOf(m1, AnyOf(m2, m3, m4));
2894}
2895
2896template <typename Matcher1, typename Matcher2, typename Matcher3,
2897 typename Matcher4, typename Matcher5>
2898inline internal::EitherOfMatcher<Matcher1,
2899 internal::EitherOfMatcher<Matcher2,
2900 internal::EitherOfMatcher<Matcher3,
2901 internal::EitherOfMatcher<Matcher4, Matcher5> > > >
2902AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2903 return AnyOf(m1, AnyOf(m2, m3, m4, m5));
2904}
2905
2906// Returns a matcher that matches anything that satisfies the given
2907// predicate. The predicate can be any unary function or functor
2908// whose return type can be implicitly converted to bool.
2909template <typename Predicate>
2910inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
2911Truly(Predicate pred) {
2912 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
2913}
2914
zhanyong.wan6a896b52009-01-16 01:13:50 +00002915// Returns a matcher that matches an equal container.
2916// This matcher behaves like Eq(), but in the event of mismatch lists the
2917// values that are included in one container but not the other. (Duplicate
2918// values and order differences are not explained.)
2919template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00002920inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wanb8243162009-06-04 05:48:20 +00002921 GMOCK_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00002922 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002923 // This following line is for working around a bug in MSVC 8.0,
2924 // which causes Container to be a const type sometimes.
2925 typedef GMOCK_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00002926 return MakePolymorphicMatcher(
2927 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00002928}
2929
2930// Matches an STL-style container or a native array that contains at
2931// least one element matching the given value or matcher.
2932//
2933// Examples:
2934// ::std::set<int> page_ids;
2935// page_ids.insert(3);
2936// page_ids.insert(1);
2937// EXPECT_THAT(page_ids, Contains(1));
2938// EXPECT_THAT(page_ids, Contains(Gt(2)));
2939// EXPECT_THAT(page_ids, Not(Contains(4)));
2940//
2941// ::std::map<int, size_t> page_lengths;
2942// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00002943// EXPECT_THAT(page_lengths,
2944// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00002945//
2946// const char* user_ids[] = { "joe", "mike", "tom" };
2947// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
2948template <typename M>
2949inline internal::ContainsMatcher<M> Contains(M matcher) {
2950 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002951}
2952
zhanyong.wanb5937da2009-07-16 20:26:41 +00002953// Key(inner_matcher) matches an std::pair whose 'first' field matches
2954// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2955// std::map that contains at least one element whose key is >= 5.
2956template <typename M>
2957inline internal::KeyMatcher<M> Key(M inner_matcher) {
2958 return internal::KeyMatcher<M>(inner_matcher);
2959}
2960
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002961// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
2962// matches first_matcher and whose 'second' field matches second_matcher. For
2963// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
2964// to match a std::map<int, string> that contains exactly one element whose key
2965// is >= 5 and whose value equals "foo".
2966template <typename FirstMatcher, typename SecondMatcher>
2967inline internal::PairMatcher<FirstMatcher, SecondMatcher>
2968Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
2969 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
2970 first_matcher, second_matcher);
2971}
2972
shiqiane35fdd92008-12-10 05:08:54 +00002973// Returns a predicate that is satisfied by anything that matches the
2974// given matcher.
2975template <typename M>
2976inline internal::MatcherAsPredicate<M> Matches(M matcher) {
2977 return internal::MatcherAsPredicate<M>(matcher);
2978}
2979
zhanyong.wanb8243162009-06-04 05:48:20 +00002980// Returns true iff the value matches the matcher.
2981template <typename T, typename M>
2982inline bool Value(const T& value, M matcher) {
2983 return testing::Matches(matcher)(value);
2984}
2985
zhanyong.wanbf550852009-06-09 06:09:53 +00002986// AllArgs(m) is a synonym of m. This is useful in
2987//
2988// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
2989//
2990// which is easier to read than
2991//
2992// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
2993template <typename InnerMatcher>
2994inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
2995
shiqiane35fdd92008-12-10 05:08:54 +00002996// These macros allow using matchers to check values in Google Test
2997// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
2998// succeed iff the value matches the matcher. If the assertion fails,
2999// the value and the description of the matcher will be printed.
3000#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
3001 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3002#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
3003 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3004
3005} // namespace testing
3006
3007#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_