blob: 8dba440a320ccea38ef440147b7fd7e08a7374c9 [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
zhanyong.wana862f1d2010-03-15 21:23:04 +000093 // Returns true iff the listener is interested in an explanation of
94 // the match result. A matcher's MatchAndExplain() method can use
95 // this information to avoid generating the explanation when no one
96 // intends to hear it.
97 bool IsInterested() const { return stream_ != NULL; }
98
zhanyong.wan82113312010-01-08 21:55:40 +000099 private:
100 ::std::ostream* const stream_;
101
102 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
103};
104
105inline MatchResultListener::~MatchResultListener() {
106}
107
shiqiane35fdd92008-12-10 05:08:54 +0000108// The implementation of a matcher.
109template <typename T>
110class MatcherInterface {
111 public:
112 virtual ~MatcherInterface() {}
113
zhanyong.wan82113312010-01-08 21:55:40 +0000114 // Returns true iff the matcher matches x; also explains the match
zhanyong.wana862f1d2010-03-15 21:23:04 +0000115 // result to 'listener', in the form of a non-restrictive relative
116 // clause ("which ...", "whose ...", etc) that describes x. For
117 // example, the MatchAndExplain() method of the Pointee(...) matcher
118 // should generate an explanation like "which points to ...".
zhanyong.wan82113312010-01-08 21:55:40 +0000119 //
zhanyong.wandb22c222010-01-28 21:52:29 +0000120 // You should override this method when defining a new matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000121 //
122 // It's the responsibility of the caller (Google Mock) to guarantee
123 // that 'listener' is not NULL. This helps to simplify a matcher's
124 // implementation when it doesn't care about the performance, as it
125 // can talk to 'listener' without checking its validity first.
126 // However, in order to implement dummy listeners efficiently,
127 // listener->stream() may be NULL.
zhanyong.wandb22c222010-01-28 21:52:29 +0000128 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
shiqiane35fdd92008-12-10 05:08:54 +0000129
zhanyong.wana862f1d2010-03-15 21:23:04 +0000130 // Describes this matcher to an ostream. The function should print
131 // a verb phrase that describes the property a value matching this
132 // matcher should have. The subject of the verb phrase is the value
133 // being matched. For example, the DescribeTo() method of the Gt(7)
134 // matcher prints "is greater than 7".
shiqiane35fdd92008-12-10 05:08:54 +0000135 virtual void DescribeTo(::std::ostream* os) const = 0;
136
137 // Describes the negation of this matcher to an ostream. For
138 // example, if the description of this matcher is "is greater than
139 // 7", the negated description could be "is not greater than 7".
140 // You are not required to override this when implementing
141 // MatcherInterface, but it is highly advised so that your matcher
142 // can produce good error messages.
143 virtual void DescribeNegationTo(::std::ostream* os) const {
144 *os << "not (";
145 DescribeTo(os);
146 *os << ")";
147 }
shiqiane35fdd92008-12-10 05:08:54 +0000148};
149
150namespace internal {
151
zhanyong.wan82113312010-01-08 21:55:40 +0000152// A match result listener that ignores the explanation.
153class DummyMatchResultListener : public MatchResultListener {
154 public:
155 DummyMatchResultListener() : MatchResultListener(NULL) {}
156
157 private:
158 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
159};
160
161// A match result listener that forwards the explanation to a given
162// ostream. The difference between this and MatchResultListener is
163// that the former is concrete.
164class StreamMatchResultListener : public MatchResultListener {
165 public:
166 explicit StreamMatchResultListener(::std::ostream* os)
167 : MatchResultListener(os) {}
168
169 private:
170 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
171};
172
173// A match result listener that stores the explanation in a string.
174class StringMatchResultListener : public MatchResultListener {
175 public:
176 StringMatchResultListener() : MatchResultListener(&ss_) {}
177
178 // Returns the explanation heard so far.
179 internal::string str() const { return ss_.str(); }
180
181 private:
182 ::std::stringstream ss_;
183
184 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
185};
186
shiqiane35fdd92008-12-10 05:08:54 +0000187// An internal class for implementing Matcher<T>, which will derive
188// from it. We put functionalities common to all Matcher<T>
189// specializations here to avoid code duplication.
190template <typename T>
191class MatcherBase {
192 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000193 // Returns true iff the matcher matches x; also explains the match
194 // result to 'listener'.
195 bool MatchAndExplain(T x, MatchResultListener* listener) const {
196 return impl_->MatchAndExplain(x, listener);
197 }
198
shiqiane35fdd92008-12-10 05:08:54 +0000199 // Returns true iff this matcher matches x.
zhanyong.wan82113312010-01-08 21:55:40 +0000200 bool Matches(T x) const {
201 DummyMatchResultListener dummy;
202 return MatchAndExplain(x, &dummy);
203 }
shiqiane35fdd92008-12-10 05:08:54 +0000204
205 // Describes this matcher to an ostream.
206 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
207
208 // Describes the negation of this matcher to an ostream.
209 void DescribeNegationTo(::std::ostream* os) const {
210 impl_->DescribeNegationTo(os);
211 }
212
213 // Explains why x matches, or doesn't match, the matcher.
214 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000215 StreamMatchResultListener listener(os);
216 MatchAndExplain(x, &listener);
shiqiane35fdd92008-12-10 05:08:54 +0000217 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000218
shiqiane35fdd92008-12-10 05:08:54 +0000219 protected:
220 MatcherBase() {}
221
222 // Constructs a matcher from its implementation.
223 explicit MatcherBase(const MatcherInterface<T>* impl)
224 : impl_(impl) {}
225
226 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000227
shiqiane35fdd92008-12-10 05:08:54 +0000228 private:
229 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
230 // interfaces. The former dynamically allocates a chunk of memory
231 // to hold the reference count, while the latter tracks all
232 // references using a circular linked list without allocating
233 // memory. It has been observed that linked_ptr performs better in
234 // typical scenarios. However, shared_ptr can out-perform
235 // linked_ptr when there are many more uses of the copy constructor
236 // than the default constructor.
237 //
238 // If performance becomes a problem, we should see if using
239 // shared_ptr helps.
240 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
241};
242
shiqiane35fdd92008-12-10 05:08:54 +0000243} // namespace internal
244
245// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
246// object that can check whether a value of type T matches. The
247// implementation of Matcher<T> is just a linked_ptr to const
248// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
249// from Matcher!
250template <typename T>
251class Matcher : public internal::MatcherBase<T> {
252 public:
253 // Constructs a null matcher. Needed for storing Matcher objects in
254 // STL containers.
255 Matcher() {}
256
257 // Constructs a matcher from its implementation.
258 explicit Matcher(const MatcherInterface<T>* impl)
259 : internal::MatcherBase<T>(impl) {}
260
zhanyong.wan18490652009-05-11 18:54:08 +0000261 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000262 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
263 Matcher(T value); // NOLINT
264};
265
266// The following two specializations allow the user to write str
267// instead of Eq(str) and "foo" instead of Eq("foo") when a string
268// matcher is expected.
269template <>
270class Matcher<const internal::string&>
271 : public internal::MatcherBase<const internal::string&> {
272 public:
273 Matcher() {}
274
275 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
276 : internal::MatcherBase<const internal::string&>(impl) {}
277
278 // Allows the user to write str instead of Eq(str) sometimes, where
279 // str is a string object.
280 Matcher(const internal::string& s); // NOLINT
281
282 // Allows the user to write "foo" instead of Eq("foo") sometimes.
283 Matcher(const char* s); // NOLINT
284};
285
286template <>
287class Matcher<internal::string>
288 : public internal::MatcherBase<internal::string> {
289 public:
290 Matcher() {}
291
292 explicit Matcher(const MatcherInterface<internal::string>* impl)
293 : internal::MatcherBase<internal::string>(impl) {}
294
295 // Allows the user to write str instead of Eq(str) sometimes, where
296 // str is a string object.
297 Matcher(const internal::string& s); // NOLINT
298
299 // Allows the user to write "foo" instead of Eq("foo") sometimes.
300 Matcher(const char* s); // NOLINT
301};
302
303// The PolymorphicMatcher class template makes it easy to implement a
304// polymorphic matcher (i.e. a matcher that can match values of more
305// than one type, e.g. Eq(n) and NotNull()).
306//
zhanyong.wandb22c222010-01-28 21:52:29 +0000307// To define a polymorphic matcher, a user should provide an Impl
308// class that has a DescribeTo() method and a DescribeNegationTo()
309// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000310//
zhanyong.wandb22c222010-01-28 21:52:29 +0000311// bool MatchAndExplain(const Value& value,
312// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000313//
314// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000315template <class Impl>
316class PolymorphicMatcher {
317 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000318 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000319
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000320 // Returns a mutable reference to the underlying matcher
321 // implementation object.
322 Impl& mutable_impl() { return impl_; }
323
324 // Returns an immutable reference to the underlying matcher
325 // implementation object.
326 const Impl& impl() const { return impl_; }
327
shiqiane35fdd92008-12-10 05:08:54 +0000328 template <typename T>
329 operator Matcher<T>() const {
330 return Matcher<T>(new MonomorphicImpl<T>(impl_));
331 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000332
shiqiane35fdd92008-12-10 05:08:54 +0000333 private:
334 template <typename T>
335 class MonomorphicImpl : public MatcherInterface<T> {
336 public:
337 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
338
shiqiane35fdd92008-12-10 05:08:54 +0000339 virtual void DescribeTo(::std::ostream* os) const {
340 impl_.DescribeTo(os);
341 }
342
343 virtual void DescribeNegationTo(::std::ostream* os) const {
344 impl_.DescribeNegationTo(os);
345 }
346
zhanyong.wan82113312010-01-08 21:55:40 +0000347 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000348 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000349 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000350
shiqiane35fdd92008-12-10 05:08:54 +0000351 private:
352 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000353
354 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000355 };
356
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000357 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000358
359 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000360};
361
362// Creates a matcher from its implementation. This is easier to use
363// than the Matcher<T> constructor as it doesn't require you to
364// explicitly write the template argument, e.g.
365//
366// MakeMatcher(foo);
367// vs
368// Matcher<const string&>(foo);
369template <typename T>
370inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
371 return Matcher<T>(impl);
372};
373
374// Creates a polymorphic matcher from its implementation. This is
375// easier to use than the PolymorphicMatcher<Impl> constructor as it
376// doesn't require you to explicitly write the template argument, e.g.
377//
378// MakePolymorphicMatcher(foo);
379// vs
380// PolymorphicMatcher<TypeOfFoo>(foo);
381template <class Impl>
382inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
383 return PolymorphicMatcher<Impl>(impl);
384}
385
386// In order to be safe and clear, casting between different matcher
387// types is done explicitly via MatcherCast<T>(m), which takes a
388// matcher m and returns a Matcher<T>. It compiles only when T can be
389// statically converted to the argument type of m.
390template <typename T, typename M>
391Matcher<T> MatcherCast(M m);
392
zhanyong.wan18490652009-05-11 18:54:08 +0000393// Implements SafeMatcherCast().
394//
zhanyong.wan95b12332009-09-25 18:55:50 +0000395// We use an intermediate class to do the actual safe casting as Nokia's
396// Symbian compiler cannot decide between
397// template <T, M> ... (M) and
398// template <T, U> ... (const Matcher<U>&)
399// for function templates but can for member function templates.
400template <typename T>
401class SafeMatcherCastImpl {
402 public:
403 // This overload handles polymorphic matchers only since monomorphic
404 // matchers are handled by the next one.
405 template <typename M>
406 static inline Matcher<T> Cast(M polymorphic_matcher) {
407 return Matcher<T>(polymorphic_matcher);
408 }
zhanyong.wan18490652009-05-11 18:54:08 +0000409
zhanyong.wan95b12332009-09-25 18:55:50 +0000410 // This overload handles monomorphic matchers.
411 //
412 // In general, if type T can be implicitly converted to type U, we can
413 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
414 // contravariant): just keep a copy of the original Matcher<U>, convert the
415 // argument from type T to U, and then pass it to the underlying Matcher<U>.
416 // The only exception is when U is a reference and T is not, as the
417 // underlying Matcher<U> may be interested in the argument's address, which
418 // is not preserved in the conversion from T to U.
419 template <typename U>
420 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
421 // Enforce that T can be implicitly converted to U.
422 GMOCK_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
423 T_must_be_implicitly_convertible_to_U);
424 // Enforce that we are not converting a non-reference type T to a reference
425 // type U.
426 GMOCK_COMPILE_ASSERT_(
427 internal::is_reference<T>::value || !internal::is_reference<U>::value,
428 cannot_convert_non_referentce_arg_to_reference);
429 // In case both T and U are arithmetic types, enforce that the
430 // conversion is not lossy.
431 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(T)) RawT;
432 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(U)) RawU;
433 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
434 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
435 GMOCK_COMPILE_ASSERT_(
436 kTIsOther || kUIsOther ||
437 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
438 conversion_of_arithmetic_types_must_be_lossless);
439 return MatcherCast<T>(matcher);
440 }
441};
442
443template <typename T, typename M>
444inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
445 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000446}
447
shiqiane35fdd92008-12-10 05:08:54 +0000448// A<T>() returns a matcher that matches any value of type T.
449template <typename T>
450Matcher<T> A();
451
452// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
453// and MUST NOT BE USED IN USER CODE!!!
454namespace internal {
455
zhanyong.wan82113312010-01-08 21:55:40 +0000456// If the given string is not empty and os is not NULL, wraps the
457// string inside a pair of parentheses and streams the result to os.
458inline void StreamInParensAsNeeded(const internal::string& str,
459 ::std::ostream* os) {
460 if (!str.empty() && os != NULL) {
461 *os << " (" << str << ")";
shiqiane35fdd92008-12-10 05:08:54 +0000462 }
463}
464
465// An internal helper class for doing compile-time loop on a tuple's
466// fields.
467template <size_t N>
468class TuplePrefix {
469 public:
470 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
471 // iff the first N fields of matcher_tuple matches the first N
472 // fields of value_tuple, respectively.
473 template <typename MatcherTuple, typename ValueTuple>
474 static bool Matches(const MatcherTuple& matcher_tuple,
475 const ValueTuple& value_tuple) {
476 using ::std::tr1::get;
477 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
478 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
479 }
480
481 // TuplePrefix<N>::DescribeMatchFailuresTo(matchers, values, os)
482 // describes failures in matching the first N fields of matchers
483 // against the first N fields of values. If there is no failure,
484 // nothing will be streamed to os.
485 template <typename MatcherTuple, typename ValueTuple>
486 static void DescribeMatchFailuresTo(const MatcherTuple& matchers,
487 const ValueTuple& values,
488 ::std::ostream* os) {
489 using ::std::tr1::tuple_element;
490 using ::std::tr1::get;
491
492 // First, describes failures in the first N - 1 fields.
493 TuplePrefix<N - 1>::DescribeMatchFailuresTo(matchers, values, os);
494
495 // Then describes the failure (if any) in the (N - 1)-th (0-based)
496 // field.
497 typename tuple_element<N - 1, MatcherTuple>::type matcher =
498 get<N - 1>(matchers);
499 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
500 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000501 StringMatchResultListener listener;
502 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000503 // TODO(wan): include in the message the name of the parameter
504 // as used in MOCK_METHOD*() when possible.
505 *os << " Expected arg #" << N - 1 << ": ";
506 get<N - 1>(matchers).DescribeTo(os);
507 *os << "\n Actual: ";
508 // We remove the reference in type Value to prevent the
509 // universal printer from printing the address of value, which
510 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000511 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000512 // the address is interesting.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000513 internal::UniversalPrinter<GMOCK_REMOVE_REFERENCE_(Value)>::
shiqiane35fdd92008-12-10 05:08:54 +0000514 Print(value, os);
zhanyong.wan82113312010-01-08 21:55:40 +0000515
516 StreamInParensAsNeeded(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000517 *os << "\n";
518 }
519 }
520};
521
522// The base case.
523template <>
524class TuplePrefix<0> {
525 public:
526 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000527 static bool Matches(const MatcherTuple& /* matcher_tuple */,
528 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000529 return true;
530 }
531
532 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000533 static void DescribeMatchFailuresTo(const MatcherTuple& /* matchers */,
534 const ValueTuple& /* values */,
535 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000536};
537
538// TupleMatches(matcher_tuple, value_tuple) returns true iff all
539// matchers in matcher_tuple match the corresponding fields in
540// value_tuple. It is a compiler error if matcher_tuple and
541// value_tuple have different number of fields or incompatible field
542// types.
543template <typename MatcherTuple, typename ValueTuple>
544bool TupleMatches(const MatcherTuple& matcher_tuple,
545 const ValueTuple& value_tuple) {
546 using ::std::tr1::tuple_size;
547 // Makes sure that matcher_tuple and value_tuple have the same
548 // number of fields.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000549 GMOCK_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
550 tuple_size<ValueTuple>::value,
551 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000552 return TuplePrefix<tuple_size<ValueTuple>::value>::
553 Matches(matcher_tuple, value_tuple);
554}
555
556// Describes failures in matching matchers against values. If there
557// is no failure, nothing will be streamed to os.
558template <typename MatcherTuple, typename ValueTuple>
559void DescribeMatchFailureTupleTo(const MatcherTuple& matchers,
560 const ValueTuple& values,
561 ::std::ostream* os) {
562 using ::std::tr1::tuple_size;
563 TuplePrefix<tuple_size<MatcherTuple>::value>::DescribeMatchFailuresTo(
564 matchers, values, os);
565}
566
567// The MatcherCastImpl class template is a helper for implementing
568// MatcherCast(). We need this helper in order to partially
569// specialize the implementation of MatcherCast() (C++ allows
570// class/struct templates to be partially specialized, but not
571// function templates.).
572
573// This general version is used when MatcherCast()'s argument is a
574// polymorphic matcher (i.e. something that can be converted to a
575// Matcher but is not one yet; for example, Eq(value)).
576template <typename T, typename M>
577class MatcherCastImpl {
578 public:
579 static Matcher<T> Cast(M polymorphic_matcher) {
580 return Matcher<T>(polymorphic_matcher);
581 }
582};
583
584// This more specialized version is used when MatcherCast()'s argument
585// is already a Matcher. This only compiles when type T can be
586// statically converted to type U.
587template <typename T, typename U>
588class MatcherCastImpl<T, Matcher<U> > {
589 public:
590 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
591 return Matcher<T>(new Impl(source_matcher));
592 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000593
shiqiane35fdd92008-12-10 05:08:54 +0000594 private:
595 class Impl : public MatcherInterface<T> {
596 public:
597 explicit Impl(const Matcher<U>& source_matcher)
598 : source_matcher_(source_matcher) {}
599
600 // We delegate the matching logic to the source matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000601 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
602 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000603 }
604
605 virtual void DescribeTo(::std::ostream* os) const {
606 source_matcher_.DescribeTo(os);
607 }
608
609 virtual void DescribeNegationTo(::std::ostream* os) const {
610 source_matcher_.DescribeNegationTo(os);
611 }
612
shiqiane35fdd92008-12-10 05:08:54 +0000613 private:
614 const Matcher<U> source_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000615
616 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000617 };
618};
619
620// This even more specialized version is used for efficiently casting
621// a matcher to its own type.
622template <typename T>
623class MatcherCastImpl<T, Matcher<T> > {
624 public:
625 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
626};
627
628// Implements A<T>().
629template <typename T>
630class AnyMatcherImpl : public MatcherInterface<T> {
631 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000632 virtual bool MatchAndExplain(
633 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000634 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
635 virtual void DescribeNegationTo(::std::ostream* os) const {
636 // This is mostly for completeness' safe, as it's not very useful
637 // to write Not(A<bool>()). However we cannot completely rule out
638 // such a possibility, and it doesn't hurt to be prepared.
639 *os << "never matches";
640 }
641};
642
643// Implements _, a matcher that matches any value of any
644// type. This is a polymorphic matcher, so we need a template type
645// conversion operator to make it appearing as a Matcher<T> for any
646// type T.
647class AnythingMatcher {
648 public:
649 template <typename T>
650 operator Matcher<T>() const { return A<T>(); }
651};
652
653// Implements a matcher that compares a given value with a
654// pre-supplied value using one of the ==, <=, <, etc, operators. The
655// two values being compared don't have to have the same type.
656//
657// The matcher defined here is polymorphic (for example, Eq(5) can be
658// used to match an int, a short, a double, etc). Therefore we use
659// a template type conversion operator in the implementation.
660//
661// We define this as a macro in order to eliminate duplicated source
662// code.
663//
664// The following template definition assumes that the Rhs parameter is
665// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wane0d051e2009-02-19 00:33:37 +0000666#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000667 template <typename Rhs> class name##Matcher { \
668 public: \
669 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
670 template <typename Lhs> \
671 operator Matcher<Lhs>() const { \
672 return MakeMatcher(new Impl<Lhs>(rhs_)); \
673 } \
674 private: \
675 template <typename Lhs> \
676 class Impl : public MatcherInterface<Lhs> { \
677 public: \
678 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
zhanyong.wan82113312010-01-08 21:55:40 +0000679 virtual bool MatchAndExplain(\
680 Lhs lhs, MatchResultListener* /* listener */) const { \
681 return lhs op rhs_; \
682 } \
shiqiane35fdd92008-12-10 05:08:54 +0000683 virtual void DescribeTo(::std::ostream* os) const { \
684 *os << "is " relation " "; \
685 UniversalPrinter<Rhs>::Print(rhs_, os); \
686 } \
687 virtual void DescribeNegationTo(::std::ostream* os) const { \
688 *os << "is not " relation " "; \
689 UniversalPrinter<Rhs>::Print(rhs_, os); \
690 } \
691 private: \
692 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000693 GTEST_DISALLOW_ASSIGN_(Impl); \
shiqiane35fdd92008-12-10 05:08:54 +0000694 }; \
695 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000696 GTEST_DISALLOW_ASSIGN_(name##Matcher); \
shiqiane35fdd92008-12-10 05:08:54 +0000697 }
698
699// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
700// respectively.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000701GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "equal to");
702GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "greater than or equal to");
703GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "greater than");
704GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "less than or equal to");
705GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "less than");
706GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "not equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000707
zhanyong.wane0d051e2009-02-19 00:33:37 +0000708#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000709
vladlosev79b83502009-11-18 00:43:37 +0000710// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000711// pointer that is NULL.
712class IsNullMatcher {
713 public:
vladlosev79b83502009-11-18 00:43:37 +0000714 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000715 bool MatchAndExplain(const Pointer& p,
716 MatchResultListener* /* listener */) const {
717 return GetRawPointer(p) == NULL;
718 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000719
720 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
721 void DescribeNegationTo(::std::ostream* os) const {
722 *os << "is not NULL";
723 }
724};
725
vladlosev79b83502009-11-18 00:43:37 +0000726// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000727// pointer that is not NULL.
728class NotNullMatcher {
729 public:
vladlosev79b83502009-11-18 00:43:37 +0000730 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000731 bool MatchAndExplain(const Pointer& p,
732 MatchResultListener* /* listener */) const {
733 return GetRawPointer(p) != NULL;
734 }
shiqiane35fdd92008-12-10 05:08:54 +0000735
736 void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; }
737 void DescribeNegationTo(::std::ostream* os) const {
738 *os << "is NULL";
739 }
740};
741
742// Ref(variable) matches any argument that is a reference to
743// 'variable'. This matcher is polymorphic as it can match any
744// super type of the type of 'variable'.
745//
746// The RefMatcher template class implements Ref(variable). It can
747// only be instantiated with a reference type. This prevents a user
748// from mistakenly using Ref(x) to match a non-reference function
749// argument. For example, the following will righteously cause a
750// compiler error:
751//
752// int n;
753// Matcher<int> m1 = Ref(n); // This won't compile.
754// Matcher<int&> m2 = Ref(n); // This will compile.
755template <typename T>
756class RefMatcher;
757
758template <typename T>
759class RefMatcher<T&> {
760 // Google Mock is a generic framework and thus needs to support
761 // mocking any function types, including those that take non-const
762 // reference arguments. Therefore the template parameter T (and
763 // Super below) can be instantiated to either a const type or a
764 // non-const type.
765 public:
766 // RefMatcher() takes a T& instead of const T&, as we want the
767 // compiler to catch using Ref(const_value) as a matcher for a
768 // non-const reference.
769 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
770
771 template <typename Super>
772 operator Matcher<Super&>() const {
773 // By passing object_ (type T&) to Impl(), which expects a Super&,
774 // we make sure that Super is a super type of T. In particular,
775 // this catches using Ref(const_value) as a matcher for a
776 // non-const reference, as you cannot implicitly convert a const
777 // reference to a non-const reference.
778 return MakeMatcher(new Impl<Super>(object_));
779 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000780
shiqiane35fdd92008-12-10 05:08:54 +0000781 private:
782 template <typename Super>
783 class Impl : public MatcherInterface<Super&> {
784 public:
785 explicit Impl(Super& x) : object_(x) {} // NOLINT
786
zhanyong.wandb22c222010-01-28 21:52:29 +0000787 // MatchAndExplain() takes a Super& (as opposed to const Super&)
788 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +0000789 virtual bool MatchAndExplain(
790 Super& x, MatchResultListener* listener) const {
791 *listener << "is located @" << static_cast<const void*>(&x);
792 return &x == &object_;
793 }
shiqiane35fdd92008-12-10 05:08:54 +0000794
795 virtual void DescribeTo(::std::ostream* os) const {
796 *os << "references the variable ";
797 UniversalPrinter<Super&>::Print(object_, os);
798 }
799
800 virtual void DescribeNegationTo(::std::ostream* os) const {
801 *os << "does not reference the variable ";
802 UniversalPrinter<Super&>::Print(object_, os);
803 }
804
shiqiane35fdd92008-12-10 05:08:54 +0000805 private:
806 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000807
808 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000809 };
810
811 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000812
813 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000814};
815
816// Polymorphic helper functions for narrow and wide string matchers.
817inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
818 return String::CaseInsensitiveCStringEquals(lhs, rhs);
819}
820
821inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
822 const wchar_t* rhs) {
823 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
824}
825
826// String comparison for narrow or wide strings that can have embedded NUL
827// characters.
828template <typename StringType>
829bool CaseInsensitiveStringEquals(const StringType& s1,
830 const StringType& s2) {
831 // Are the heads equal?
832 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
833 return false;
834 }
835
836 // Skip the equal heads.
837 const typename StringType::value_type nul = 0;
838 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
839
840 // Are we at the end of either s1 or s2?
841 if (i1 == StringType::npos || i2 == StringType::npos) {
842 return i1 == i2;
843 }
844
845 // Are the tails equal?
846 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
847}
848
849// String matchers.
850
851// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
852template <typename StringType>
853class StrEqualityMatcher {
854 public:
855 typedef typename StringType::const_pointer ConstCharPointer;
856
857 StrEqualityMatcher(const StringType& str, bool expect_eq,
858 bool case_sensitive)
859 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
860
861 // When expect_eq_ is true, returns true iff s is equal to string_;
862 // otherwise returns true iff s is not equal to string_.
zhanyong.wandb22c222010-01-28 21:52:29 +0000863 bool MatchAndExplain(ConstCharPointer s,
864 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +0000865 if (s == NULL) {
866 return !expect_eq_;
867 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000868 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000869 }
870
zhanyong.wandb22c222010-01-28 21:52:29 +0000871 bool MatchAndExplain(const StringType& s,
872 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000873 const bool eq = case_sensitive_ ? s == string_ :
874 CaseInsensitiveStringEquals(s, string_);
875 return expect_eq_ == eq;
876 }
877
878 void DescribeTo(::std::ostream* os) const {
879 DescribeToHelper(expect_eq_, os);
880 }
881
882 void DescribeNegationTo(::std::ostream* os) const {
883 DescribeToHelper(!expect_eq_, os);
884 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000885
shiqiane35fdd92008-12-10 05:08:54 +0000886 private:
887 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
888 *os << "is ";
889 if (!expect_eq) {
890 *os << "not ";
891 }
892 *os << "equal to ";
893 if (!case_sensitive_) {
894 *os << "(ignoring case) ";
895 }
896 UniversalPrinter<StringType>::Print(string_, os);
897 }
898
899 const StringType string_;
900 const bool expect_eq_;
901 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000902
903 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000904};
905
906// Implements the polymorphic HasSubstr(substring) matcher, which
907// can be used as a Matcher<T> as long as T can be converted to a
908// string.
909template <typename StringType>
910class HasSubstrMatcher {
911 public:
912 typedef typename StringType::const_pointer ConstCharPointer;
913
914 explicit HasSubstrMatcher(const StringType& substring)
915 : substring_(substring) {}
916
917 // These overloaded methods allow HasSubstr(substring) to be used as a
918 // Matcher<T> as long as T can be converted to string. Returns true
919 // iff s contains substring_ as a substring.
zhanyong.wandb22c222010-01-28 21:52:29 +0000920 bool MatchAndExplain(ConstCharPointer s,
921 MatchResultListener* listener) const {
922 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000923 }
924
zhanyong.wandb22c222010-01-28 21:52:29 +0000925 bool MatchAndExplain(const StringType& s,
926 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000927 return s.find(substring_) != StringType::npos;
928 }
929
930 // Describes what this matcher matches.
931 void DescribeTo(::std::ostream* os) const {
932 *os << "has substring ";
933 UniversalPrinter<StringType>::Print(substring_, os);
934 }
935
936 void DescribeNegationTo(::std::ostream* os) const {
937 *os << "has no substring ";
938 UniversalPrinter<StringType>::Print(substring_, os);
939 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000940
shiqiane35fdd92008-12-10 05:08:54 +0000941 private:
942 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000943
944 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000945};
946
947// Implements the polymorphic StartsWith(substring) matcher, which
948// can be used as a Matcher<T> as long as T can be converted to a
949// string.
950template <typename StringType>
951class StartsWithMatcher {
952 public:
953 typedef typename StringType::const_pointer ConstCharPointer;
954
955 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
956 }
957
958 // These overloaded methods allow StartsWith(prefix) to be used as a
959 // Matcher<T> as long as T can be converted to string. Returns true
960 // iff s starts with prefix_.
zhanyong.wandb22c222010-01-28 21:52:29 +0000961 bool MatchAndExplain(ConstCharPointer s,
962 MatchResultListener* listener) const {
963 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000964 }
965
zhanyong.wandb22c222010-01-28 21:52:29 +0000966 bool MatchAndExplain(const StringType& s,
967 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000968 return s.length() >= prefix_.length() &&
969 s.substr(0, prefix_.length()) == prefix_;
970 }
971
972 void DescribeTo(::std::ostream* os) const {
973 *os << "starts with ";
974 UniversalPrinter<StringType>::Print(prefix_, os);
975 }
976
977 void DescribeNegationTo(::std::ostream* os) const {
978 *os << "doesn't start with ";
979 UniversalPrinter<StringType>::Print(prefix_, os);
980 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000981
shiqiane35fdd92008-12-10 05:08:54 +0000982 private:
983 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000984
985 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000986};
987
988// Implements the polymorphic EndsWith(substring) matcher, which
989// can be used as a Matcher<T> as long as T can be converted to a
990// string.
991template <typename StringType>
992class EndsWithMatcher {
993 public:
994 typedef typename StringType::const_pointer ConstCharPointer;
995
996 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
997
998 // These overloaded methods allow EndsWith(suffix) to be used as a
999 // Matcher<T> as long as T can be converted to string. Returns true
1000 // iff s ends with suffix_.
zhanyong.wandb22c222010-01-28 21:52:29 +00001001 bool MatchAndExplain(ConstCharPointer s,
1002 MatchResultListener* listener) const {
1003 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001004 }
1005
zhanyong.wandb22c222010-01-28 21:52:29 +00001006 bool MatchAndExplain(const StringType& s,
1007 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001008 return s.length() >= suffix_.length() &&
1009 s.substr(s.length() - suffix_.length()) == suffix_;
1010 }
1011
1012 void DescribeTo(::std::ostream* os) const {
1013 *os << "ends with ";
1014 UniversalPrinter<StringType>::Print(suffix_, os);
1015 }
1016
1017 void DescribeNegationTo(::std::ostream* os) const {
1018 *os << "doesn't end with ";
1019 UniversalPrinter<StringType>::Print(suffix_, os);
1020 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001021
shiqiane35fdd92008-12-10 05:08:54 +00001022 private:
1023 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001024
1025 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001026};
1027
shiqiane35fdd92008-12-10 05:08:54 +00001028// Implements polymorphic matchers MatchesRegex(regex) and
1029// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1030// T can be converted to a string.
1031class MatchesRegexMatcher {
1032 public:
1033 MatchesRegexMatcher(const RE* regex, bool full_match)
1034 : regex_(regex), full_match_(full_match) {}
1035
1036 // These overloaded methods allow MatchesRegex(regex) to be used as
1037 // a Matcher<T> as long as T can be converted to string. Returns
1038 // true iff s matches regular expression regex. When full_match_ is
1039 // true, a full match is done; otherwise a partial match is done.
zhanyong.wandb22c222010-01-28 21:52:29 +00001040 bool MatchAndExplain(const char* s,
1041 MatchResultListener* listener) const {
1042 return s != NULL && MatchAndExplain(internal::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001043 }
1044
zhanyong.wandb22c222010-01-28 21:52:29 +00001045 bool MatchAndExplain(const internal::string& s,
1046 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001047 return full_match_ ? RE::FullMatch(s, *regex_) :
1048 RE::PartialMatch(s, *regex_);
1049 }
1050
1051 void DescribeTo(::std::ostream* os) const {
1052 *os << (full_match_ ? "matches" : "contains")
1053 << " regular expression ";
1054 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1055 }
1056
1057 void DescribeNegationTo(::std::ostream* os) const {
1058 *os << "doesn't " << (full_match_ ? "match" : "contain")
1059 << " regular expression ";
1060 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1061 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001062
shiqiane35fdd92008-12-10 05:08:54 +00001063 private:
1064 const internal::linked_ptr<const RE> regex_;
1065 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001066
1067 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001068};
1069
shiqiane35fdd92008-12-10 05:08:54 +00001070// Implements a matcher that compares the two fields of a 2-tuple
1071// using one of the ==, <=, <, etc, operators. The two fields being
1072// compared don't have to have the same type.
1073//
1074// The matcher defined here is polymorphic (for example, Eq() can be
1075// used to match a tuple<int, short>, a tuple<const long&, double>,
1076// etc). Therefore we use a template type conversion operator in the
1077// implementation.
1078//
1079// We define this as a macro in order to eliminate duplicated source
1080// code.
zhanyong.wan2661c682009-06-09 05:42:12 +00001081#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op) \
shiqiane35fdd92008-12-10 05:08:54 +00001082 class name##2Matcher { \
1083 public: \
1084 template <typename T1, typename T2> \
1085 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
1086 return MakeMatcher(new Impl<T1, T2>); \
1087 } \
1088 private: \
1089 template <typename T1, typename T2> \
1090 class Impl : public MatcherInterface<const ::std::tr1::tuple<T1, T2>&> { \
1091 public: \
zhanyong.wan82113312010-01-08 21:55:40 +00001092 virtual bool MatchAndExplain( \
1093 const ::std::tr1::tuple<T1, T2>& args, \
1094 MatchResultListener* /* listener */) const { \
shiqiane35fdd92008-12-10 05:08:54 +00001095 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
1096 } \
1097 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +00001098 *os << "are a pair (x, y) where x " #op " y"; \
shiqiane35fdd92008-12-10 05:08:54 +00001099 } \
1100 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +00001101 *os << "are a pair (x, y) where x " #op " y is false"; \
shiqiane35fdd92008-12-10 05:08:54 +00001102 } \
1103 }; \
1104 }
1105
1106// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wan2661c682009-06-09 05:42:12 +00001107GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==);
1108GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ge, >=);
1109GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Gt, >);
1110GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Le, <=);
1111GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Lt, <);
1112GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=);
shiqiane35fdd92008-12-10 05:08:54 +00001113
zhanyong.wane0d051e2009-02-19 00:33:37 +00001114#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +00001115
zhanyong.wanc6a41232009-05-13 23:38:40 +00001116// Implements the Not(...) matcher for a particular argument type T.
1117// We do not nest it inside the NotMatcher class template, as that
1118// will prevent different instantiations of NotMatcher from sharing
1119// the same NotMatcherImpl<T> class.
1120template <typename T>
1121class NotMatcherImpl : public MatcherInterface<T> {
1122 public:
1123 explicit NotMatcherImpl(const Matcher<T>& matcher)
1124 : matcher_(matcher) {}
1125
zhanyong.wan82113312010-01-08 21:55:40 +00001126 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1127 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001128 }
1129
1130 virtual void DescribeTo(::std::ostream* os) const {
1131 matcher_.DescribeNegationTo(os);
1132 }
1133
1134 virtual void DescribeNegationTo(::std::ostream* os) const {
1135 matcher_.DescribeTo(os);
1136 }
1137
zhanyong.wanc6a41232009-05-13 23:38:40 +00001138 private:
1139 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001140
1141 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001142};
1143
shiqiane35fdd92008-12-10 05:08:54 +00001144// Implements the Not(m) matcher, which matches a value that doesn't
1145// match matcher m.
1146template <typename InnerMatcher>
1147class NotMatcher {
1148 public:
1149 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1150
1151 // This template type conversion operator allows Not(m) to be used
1152 // to match any type m can match.
1153 template <typename T>
1154 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001155 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001156 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001157
shiqiane35fdd92008-12-10 05:08:54 +00001158 private:
shiqiane35fdd92008-12-10 05:08:54 +00001159 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001160
1161 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001162};
1163
zhanyong.wanc6a41232009-05-13 23:38:40 +00001164// Implements the AllOf(m1, m2) matcher for a particular argument type
1165// T. We do not nest it inside the BothOfMatcher class template, as
1166// that will prevent different instantiations of BothOfMatcher from
1167// sharing the same BothOfMatcherImpl<T> class.
1168template <typename T>
1169class BothOfMatcherImpl : public MatcherInterface<T> {
1170 public:
1171 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1172 : matcher1_(matcher1), matcher2_(matcher2) {}
1173
zhanyong.wanc6a41232009-05-13 23:38:40 +00001174 virtual void DescribeTo(::std::ostream* os) const {
1175 *os << "(";
1176 matcher1_.DescribeTo(os);
1177 *os << ") and (";
1178 matcher2_.DescribeTo(os);
1179 *os << ")";
1180 }
1181
1182 virtual void DescribeNegationTo(::std::ostream* os) const {
1183 *os << "not ";
1184 DescribeTo(os);
1185 }
1186
zhanyong.wan82113312010-01-08 21:55:40 +00001187 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1188 // If either matcher1_ or matcher2_ doesn't match x, we only need
1189 // to explain why one of them fails.
1190 StringMatchResultListener listener1;
1191 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1192 *listener << listener1.str();
1193 return false;
1194 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001195
zhanyong.wan82113312010-01-08 21:55:40 +00001196 StringMatchResultListener listener2;
1197 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1198 *listener << listener2.str();
1199 return false;
1200 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001201
zhanyong.wan82113312010-01-08 21:55:40 +00001202 // Otherwise we need to explain why *both* of them match.
1203 const internal::string s1 = listener1.str();
1204 const internal::string s2 = listener2.str();
1205
1206 if (s1 == "") {
1207 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001208 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001209 *listener << s1;
1210 if (s2 != "") {
1211 *listener << "; " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001212 }
1213 }
zhanyong.wan82113312010-01-08 21:55:40 +00001214 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001215 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001216
zhanyong.wanc6a41232009-05-13 23:38:40 +00001217 private:
1218 const Matcher<T> matcher1_;
1219 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001220
1221 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001222};
1223
shiqiane35fdd92008-12-10 05:08:54 +00001224// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1225// matches a value that matches all of the matchers m_1, ..., and m_n.
1226template <typename Matcher1, typename Matcher2>
1227class BothOfMatcher {
1228 public:
1229 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1230 : matcher1_(matcher1), matcher2_(matcher2) {}
1231
1232 // This template type conversion operator allows a
1233 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1234 // both Matcher1 and Matcher2 can match.
1235 template <typename T>
1236 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001237 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1238 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001239 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001240
shiqiane35fdd92008-12-10 05:08:54 +00001241 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001242 Matcher1 matcher1_;
1243 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001244
1245 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001246};
shiqiane35fdd92008-12-10 05:08:54 +00001247
zhanyong.wanc6a41232009-05-13 23:38:40 +00001248// Implements the AnyOf(m1, m2) matcher for a particular argument type
1249// T. We do not nest it inside the AnyOfMatcher class template, as
1250// that will prevent different instantiations of AnyOfMatcher from
1251// sharing the same EitherOfMatcherImpl<T> class.
1252template <typename T>
1253class EitherOfMatcherImpl : public MatcherInterface<T> {
1254 public:
1255 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1256 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001257
zhanyong.wanc6a41232009-05-13 23:38:40 +00001258 virtual void DescribeTo(::std::ostream* os) const {
1259 *os << "(";
1260 matcher1_.DescribeTo(os);
1261 *os << ") or (";
1262 matcher2_.DescribeTo(os);
1263 *os << ")";
1264 }
shiqiane35fdd92008-12-10 05:08:54 +00001265
zhanyong.wanc6a41232009-05-13 23:38:40 +00001266 virtual void DescribeNegationTo(::std::ostream* os) const {
1267 *os << "not ";
1268 DescribeTo(os);
1269 }
shiqiane35fdd92008-12-10 05:08:54 +00001270
zhanyong.wan82113312010-01-08 21:55:40 +00001271 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1272 // If either matcher1_ or matcher2_ matches x, we just need to
1273 // explain why *one* of them matches.
1274 StringMatchResultListener listener1;
1275 if (matcher1_.MatchAndExplain(x, &listener1)) {
1276 *listener << listener1.str();
1277 return true;
1278 }
1279
1280 StringMatchResultListener listener2;
1281 if (matcher2_.MatchAndExplain(x, &listener2)) {
1282 *listener << listener2.str();
1283 return true;
1284 }
1285
1286 // Otherwise we need to explain why *both* of them fail.
1287 const internal::string s1 = listener1.str();
1288 const internal::string s2 = listener2.str();
1289
1290 if (s1 == "") {
1291 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001292 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001293 *listener << s1;
1294 if (s2 != "") {
1295 *listener << "; " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001296 }
1297 }
zhanyong.wan82113312010-01-08 21:55:40 +00001298 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001299 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001300
zhanyong.wanc6a41232009-05-13 23:38:40 +00001301 private:
1302 const Matcher<T> matcher1_;
1303 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001304
1305 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001306};
1307
1308// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1309// matches a value that matches at least one of the matchers m_1, ...,
1310// and m_n.
1311template <typename Matcher1, typename Matcher2>
1312class EitherOfMatcher {
1313 public:
1314 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1315 : matcher1_(matcher1), matcher2_(matcher2) {}
1316
1317 // This template type conversion operator allows a
1318 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1319 // both Matcher1 and Matcher2 can match.
1320 template <typename T>
1321 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001322 return Matcher<T>(new EitherOfMatcherImpl<T>(
1323 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001324 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001325
shiqiane35fdd92008-12-10 05:08:54 +00001326 private:
shiqiane35fdd92008-12-10 05:08:54 +00001327 Matcher1 matcher1_;
1328 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001329
1330 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001331};
1332
1333// Used for implementing Truly(pred), which turns a predicate into a
1334// matcher.
1335template <typename Predicate>
1336class TrulyMatcher {
1337 public:
1338 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1339
1340 // This method template allows Truly(pred) to be used as a matcher
1341 // for type T where T is the argument type of predicate 'pred'. The
1342 // argument is passed by reference as the predicate may be
1343 // interested in the address of the argument.
1344 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001345 bool MatchAndExplain(T& x, // NOLINT
1346 MatchResultListener* /* listener */) const {
zhanyong.wan652540a2009-02-23 23:37:29 +00001347#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001348 // MSVC warns about converting a value into bool (warning 4800).
1349#pragma warning(push) // Saves the current warning state.
1350#pragma warning(disable:4800) // Temporarily disables warning 4800.
1351#endif // GTEST_OS_WINDOWS
1352 return predicate_(x);
zhanyong.wan652540a2009-02-23 23:37:29 +00001353#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001354#pragma warning(pop) // Restores the warning state.
1355#endif // GTEST_OS_WINDOWS
1356 }
1357
1358 void DescribeTo(::std::ostream* os) const {
1359 *os << "satisfies the given predicate";
1360 }
1361
1362 void DescribeNegationTo(::std::ostream* os) const {
1363 *os << "doesn't satisfy the given predicate";
1364 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001365
shiqiane35fdd92008-12-10 05:08:54 +00001366 private:
1367 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001368
1369 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001370};
1371
1372// Used for implementing Matches(matcher), which turns a matcher into
1373// a predicate.
1374template <typename M>
1375class MatcherAsPredicate {
1376 public:
1377 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1378
1379 // This template operator() allows Matches(m) to be used as a
1380 // predicate on type T where m is a matcher on type T.
1381 //
1382 // The argument x is passed by reference instead of by value, as
1383 // some matcher may be interested in its address (e.g. as in
1384 // Matches(Ref(n))(x)).
1385 template <typename T>
1386 bool operator()(const T& x) const {
1387 // We let matcher_ commit to a particular type here instead of
1388 // when the MatcherAsPredicate object was constructed. This
1389 // allows us to write Matches(m) where m is a polymorphic matcher
1390 // (e.g. Eq(5)).
1391 //
1392 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1393 // compile when matcher_ has type Matcher<const T&>; if we write
1394 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1395 // when matcher_ has type Matcher<T>; if we just write
1396 // matcher_.Matches(x), it won't compile when matcher_ is
1397 // polymorphic, e.g. Eq(5).
1398 //
1399 // MatcherCast<const T&>() is necessary for making the code work
1400 // in all of the above situations.
1401 return MatcherCast<const T&>(matcher_).Matches(x);
1402 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001403
shiqiane35fdd92008-12-10 05:08:54 +00001404 private:
1405 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001406
1407 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001408};
1409
1410// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1411// argument M must be a type that can be converted to a matcher.
1412template <typename M>
1413class PredicateFormatterFromMatcher {
1414 public:
1415 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1416
1417 // This template () operator allows a PredicateFormatterFromMatcher
1418 // object to act as a predicate-formatter suitable for using with
1419 // Google Test's EXPECT_PRED_FORMAT1() macro.
1420 template <typename T>
1421 AssertionResult operator()(const char* value_text, const T& x) const {
1422 // We convert matcher_ to a Matcher<const T&> *now* instead of
1423 // when the PredicateFormatterFromMatcher object was constructed,
1424 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1425 // know which type to instantiate it to until we actually see the
1426 // type of x here.
1427 //
1428 // We write MatcherCast<const T&>(matcher_) instead of
1429 // Matcher<const T&>(matcher_), as the latter won't compile when
1430 // matcher_ has type Matcher<T> (e.g. An<int>()).
1431 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001432 StringMatchResultListener listener;
1433 if (matcher.MatchAndExplain(x, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +00001434 return AssertionSuccess();
1435 } else {
1436 ::std::stringstream ss;
1437 ss << "Value of: " << value_text << "\n"
1438 << "Expected: ";
1439 matcher.DescribeTo(&ss);
1440 ss << "\n Actual: ";
1441 UniversalPrinter<T>::Print(x, &ss);
zhanyong.wan82113312010-01-08 21:55:40 +00001442 StreamInParensAsNeeded(listener.str(), &ss);
shiqiane35fdd92008-12-10 05:08:54 +00001443 return AssertionFailure(Message() << ss.str());
1444 }
1445 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001446
shiqiane35fdd92008-12-10 05:08:54 +00001447 private:
1448 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001449
1450 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001451};
1452
1453// A helper function for converting a matcher to a predicate-formatter
1454// without the user needing to explicitly write the type. This is
1455// used for implementing ASSERT_THAT() and EXPECT_THAT().
1456template <typename M>
1457inline PredicateFormatterFromMatcher<M>
1458MakePredicateFormatterFromMatcher(const M& matcher) {
1459 return PredicateFormatterFromMatcher<M>(matcher);
1460}
1461
1462// Implements the polymorphic floating point equality matcher, which
1463// matches two float values using ULP-based approximation. The
1464// template is meant to be instantiated with FloatType being either
1465// float or double.
1466template <typename FloatType>
1467class FloatingEqMatcher {
1468 public:
1469 // Constructor for FloatingEqMatcher.
1470 // The matcher's input will be compared with rhs. The matcher treats two
1471 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1472 // equality comparisons between NANs will always return false.
1473 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1474 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1475
1476 // Implements floating point equality matcher as a Matcher<T>.
1477 template <typename T>
1478 class Impl : public MatcherInterface<T> {
1479 public:
1480 Impl(FloatType rhs, bool nan_eq_nan) :
1481 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1482
zhanyong.wan82113312010-01-08 21:55:40 +00001483 virtual bool MatchAndExplain(T value,
1484 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001485 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1486
1487 // Compares NaNs first, if nan_eq_nan_ is true.
1488 if (nan_eq_nan_ && lhs.is_nan()) {
1489 return rhs.is_nan();
1490 }
1491
1492 return lhs.AlmostEquals(rhs);
1493 }
1494
1495 virtual void DescribeTo(::std::ostream* os) const {
1496 // os->precision() returns the previously set precision, which we
1497 // store to restore the ostream to its original configuration
1498 // after outputting.
1499 const ::std::streamsize old_precision = os->precision(
1500 ::std::numeric_limits<FloatType>::digits10 + 2);
1501 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1502 if (nan_eq_nan_) {
1503 *os << "is NaN";
1504 } else {
1505 *os << "never matches";
1506 }
1507 } else {
1508 *os << "is approximately " << rhs_;
1509 }
1510 os->precision(old_precision);
1511 }
1512
1513 virtual void DescribeNegationTo(::std::ostream* os) const {
1514 // As before, get original precision.
1515 const ::std::streamsize old_precision = os->precision(
1516 ::std::numeric_limits<FloatType>::digits10 + 2);
1517 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1518 if (nan_eq_nan_) {
1519 *os << "is not NaN";
1520 } else {
1521 *os << "is anything";
1522 }
1523 } else {
1524 *os << "is not approximately " << rhs_;
1525 }
1526 // Restore original precision.
1527 os->precision(old_precision);
1528 }
1529
1530 private:
1531 const FloatType rhs_;
1532 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001533
1534 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001535 };
1536
1537 // The following 3 type conversion operators allow FloatEq(rhs) and
1538 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1539 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1540 // (While Google's C++ coding style doesn't allow arguments passed
1541 // by non-const reference, we may see them in code not conforming to
1542 // the style. Therefore Google Mock needs to support them.)
1543 operator Matcher<FloatType>() const {
1544 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1545 }
1546
1547 operator Matcher<const FloatType&>() const {
1548 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1549 }
1550
1551 operator Matcher<FloatType&>() const {
1552 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1553 }
1554 private:
1555 const FloatType rhs_;
1556 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001557
1558 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001559};
1560
1561// Implements the Pointee(m) matcher for matching a pointer whose
1562// pointee matches matcher m. The pointer can be either raw or smart.
1563template <typename InnerMatcher>
1564class PointeeMatcher {
1565 public:
1566 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1567
1568 // This type conversion operator template allows Pointee(m) to be
1569 // used as a matcher for any pointer type whose pointee type is
1570 // compatible with the inner matcher, where type Pointer can be
1571 // either a raw pointer or a smart pointer.
1572 //
1573 // The reason we do this instead of relying on
1574 // MakePolymorphicMatcher() is that the latter is not flexible
1575 // enough for implementing the DescribeTo() method of Pointee().
1576 template <typename Pointer>
1577 operator Matcher<Pointer>() const {
1578 return MakeMatcher(new Impl<Pointer>(matcher_));
1579 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001580
shiqiane35fdd92008-12-10 05:08:54 +00001581 private:
1582 // The monomorphic implementation that works for a particular pointer type.
1583 template <typename Pointer>
1584 class Impl : public MatcherInterface<Pointer> {
1585 public:
zhanyong.wane0d051e2009-02-19 00:33:37 +00001586 typedef typename PointeeOf<GMOCK_REMOVE_CONST_( // NOLINT
1587 GMOCK_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001588
1589 explicit Impl(const InnerMatcher& matcher)
1590 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1591
shiqiane35fdd92008-12-10 05:08:54 +00001592 virtual void DescribeTo(::std::ostream* os) const {
1593 *os << "points to a value that ";
1594 matcher_.DescribeTo(os);
1595 }
1596
1597 virtual void DescribeNegationTo(::std::ostream* os) const {
1598 *os << "does not point to a value that ";
1599 matcher_.DescribeTo(os);
1600 }
1601
zhanyong.wan82113312010-01-08 21:55:40 +00001602 virtual bool MatchAndExplain(Pointer pointer,
1603 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001604 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00001605 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001606
zhanyong.wan82113312010-01-08 21:55:40 +00001607 StringMatchResultListener inner_listener;
1608 const bool match = matcher_.MatchAndExplain(*pointer, &inner_listener);
1609 const internal::string s = inner_listener.str();
shiqiane35fdd92008-12-10 05:08:54 +00001610 if (s != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00001611 *listener << "points to a value that " << s;
shiqiane35fdd92008-12-10 05:08:54 +00001612 }
zhanyong.wan82113312010-01-08 21:55:40 +00001613 return match;
shiqiane35fdd92008-12-10 05:08:54 +00001614 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001615
shiqiane35fdd92008-12-10 05:08:54 +00001616 private:
1617 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001618
1619 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001620 };
1621
1622 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001623
1624 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001625};
1626
1627// Implements the Field() matcher for matching a field (i.e. member
1628// variable) of an object.
1629template <typename Class, typename FieldType>
1630class FieldMatcher {
1631 public:
1632 FieldMatcher(FieldType Class::*field,
1633 const Matcher<const FieldType&>& matcher)
1634 : field_(field), matcher_(matcher) {}
1635
shiqiane35fdd92008-12-10 05:08:54 +00001636 void DescribeTo(::std::ostream* os) const {
1637 *os << "the given field ";
1638 matcher_.DescribeTo(os);
1639 }
1640
1641 void DescribeNegationTo(::std::ostream* os) const {
1642 *os << "the given field ";
1643 matcher_.DescribeNegationTo(os);
1644 }
1645
zhanyong.wandb22c222010-01-28 21:52:29 +00001646 template <typename T>
1647 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
1648 return MatchAndExplainImpl(
1649 typename ::testing::internal::
1650 is_pointer<GMOCK_REMOVE_CONST_(T)>::type(),
1651 value, listener);
1652 }
1653
1654 private:
1655 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001656 // Symbian's C++ compiler choose which overload to use. Its type is
1657 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001658 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1659 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001660 StringMatchResultListener inner_listener;
1661 const bool match = matcher_.MatchAndExplain(obj.*field_, &inner_listener);
1662 const internal::string s = inner_listener.str();
shiqiane35fdd92008-12-10 05:08:54 +00001663 if (s != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00001664 *listener << "the given field " << s;
shiqiane35fdd92008-12-10 05:08:54 +00001665 }
zhanyong.wan82113312010-01-08 21:55:40 +00001666 return match;
shiqiane35fdd92008-12-10 05:08:54 +00001667 }
1668
zhanyong.wandb22c222010-01-28 21:52:29 +00001669 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1670 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001671 if (p == NULL)
1672 return false;
1673
1674 // Since *p has a field, it must be a class/struct/union type and
1675 // thus cannot be a pointer. Therefore we pass false_type() as
1676 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001677 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001678 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001679
shiqiane35fdd92008-12-10 05:08:54 +00001680 const FieldType Class::*field_;
1681 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001682
1683 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001684};
1685
shiqiane35fdd92008-12-10 05:08:54 +00001686// Implements the Property() matcher for matching a property
1687// (i.e. return value of a getter method) of an object.
1688template <typename Class, typename PropertyType>
1689class PropertyMatcher {
1690 public:
1691 // The property may have a reference type, so 'const PropertyType&'
1692 // may cause double references and fail to compile. That's why we
1693 // need GMOCK_REFERENCE_TO_CONST, which works regardless of
1694 // PropertyType being a reference or not.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001695 typedef GMOCK_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001696
1697 PropertyMatcher(PropertyType (Class::*property)() const,
1698 const Matcher<RefToConstProperty>& matcher)
1699 : property_(property), matcher_(matcher) {}
1700
shiqiane35fdd92008-12-10 05:08:54 +00001701 void DescribeTo(::std::ostream* os) const {
1702 *os << "the given property ";
1703 matcher_.DescribeTo(os);
1704 }
1705
1706 void DescribeNegationTo(::std::ostream* os) const {
1707 *os << "the given property ";
1708 matcher_.DescribeNegationTo(os);
1709 }
1710
zhanyong.wandb22c222010-01-28 21:52:29 +00001711 template <typename T>
1712 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
1713 return MatchAndExplainImpl(
1714 typename ::testing::internal::
1715 is_pointer<GMOCK_REMOVE_CONST_(T)>::type(),
1716 value, listener);
1717 }
1718
1719 private:
1720 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001721 // Symbian's C++ compiler choose which overload to use. Its type is
1722 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001723 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1724 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001725 StringMatchResultListener inner_listener;
1726 const bool match = matcher_.MatchAndExplain((obj.*property_)(),
1727 &inner_listener);
1728 const internal::string s = inner_listener.str();
shiqiane35fdd92008-12-10 05:08:54 +00001729 if (s != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00001730 *listener << "the given property " << s;
shiqiane35fdd92008-12-10 05:08:54 +00001731 }
zhanyong.wan82113312010-01-08 21:55:40 +00001732 return match;
shiqiane35fdd92008-12-10 05:08:54 +00001733 }
1734
zhanyong.wandb22c222010-01-28 21:52:29 +00001735 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1736 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001737 if (p == NULL)
1738 return false;
1739
1740 // Since *p has a property method, it must be a class/struct/union
1741 // type and thus cannot be a pointer. Therefore we pass
1742 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001743 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001744 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001745
shiqiane35fdd92008-12-10 05:08:54 +00001746 PropertyType (Class::*property_)() const;
1747 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001748
1749 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001750};
1751
shiqiane35fdd92008-12-10 05:08:54 +00001752// Type traits specifying various features of different functors for ResultOf.
1753// The default template specifies features for functor objects.
1754// Functor classes have to typedef argument_type and result_type
1755// to be compatible with ResultOf.
1756template <typename Functor>
1757struct CallableTraits {
1758 typedef typename Functor::result_type ResultType;
1759 typedef Functor StorageType;
1760
zhanyong.wan32de5f52009-12-23 00:13:23 +00001761 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00001762 template <typename T>
1763 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1764};
1765
1766// Specialization for function pointers.
1767template <typename ArgType, typename ResType>
1768struct CallableTraits<ResType(*)(ArgType)> {
1769 typedef ResType ResultType;
1770 typedef ResType(*StorageType)(ArgType);
1771
1772 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001773 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00001774 << "NULL function pointer is passed into ResultOf().";
1775 }
1776 template <typename T>
1777 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1778 return (*f)(arg);
1779 }
1780};
1781
1782// Implements the ResultOf() matcher for matching a return value of a
1783// unary function of an object.
1784template <typename Callable>
1785class ResultOfMatcher {
1786 public:
1787 typedef typename CallableTraits<Callable>::ResultType ResultType;
1788
1789 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1790 : callable_(callable), matcher_(matcher) {
1791 CallableTraits<Callable>::CheckIsValid(callable_);
1792 }
1793
1794 template <typename T>
1795 operator Matcher<T>() const {
1796 return Matcher<T>(new Impl<T>(callable_, matcher_));
1797 }
1798
1799 private:
1800 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1801
1802 template <typename T>
1803 class Impl : public MatcherInterface<T> {
1804 public:
1805 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1806 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00001807
1808 virtual void DescribeTo(::std::ostream* os) const {
1809 *os << "result of the given callable ";
1810 matcher_.DescribeTo(os);
1811 }
1812
1813 virtual void DescribeNegationTo(::std::ostream* os) const {
1814 *os << "result of the given callable ";
1815 matcher_.DescribeNegationTo(os);
1816 }
1817
zhanyong.wan82113312010-01-08 21:55:40 +00001818 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
1819 StringMatchResultListener inner_listener;
1820 const bool match = matcher_.MatchAndExplain(
shiqiane35fdd92008-12-10 05:08:54 +00001821 CallableTraits<Callable>::template Invoke<T>(callable_, obj),
zhanyong.wan82113312010-01-08 21:55:40 +00001822 &inner_listener);
1823
1824 const internal::string s = inner_listener.str();
shiqiane35fdd92008-12-10 05:08:54 +00001825 if (s != "")
zhanyong.wan82113312010-01-08 21:55:40 +00001826 *listener << "result of the given callable " << s;
1827
1828 return match;
shiqiane35fdd92008-12-10 05:08:54 +00001829 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001830
shiqiane35fdd92008-12-10 05:08:54 +00001831 private:
1832 // Functors often define operator() as non-const method even though
1833 // they are actualy stateless. But we need to use them even when
1834 // 'this' is a const pointer. It's the user's responsibility not to
1835 // use stateful callables with ResultOf(), which does't guarantee
1836 // how many times the callable will be invoked.
1837 mutable CallableStorageType callable_;
1838 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001839
1840 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001841 }; // class Impl
1842
1843 const CallableStorageType callable_;
1844 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001845
1846 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001847};
1848
zhanyong.wan6a896b52009-01-16 01:13:50 +00001849// Implements an equality matcher for any STL-style container whose elements
1850// support ==. This matcher is like Eq(), but its failure explanations provide
1851// more detailed information that is useful when the container is used as a set.
1852// The failure message reports elements that are in one of the operands but not
1853// the other. The failure messages do not report duplicate or out-of-order
1854// elements in the containers (which don't properly matter to sets, but can
1855// occur if the containers are vectors or lists, for example).
1856//
1857// Uses the container's const_iterator, value_type, operator ==,
1858// begin(), and end().
1859template <typename Container>
1860class ContainerEqMatcher {
1861 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00001862 typedef internal::StlContainerView<Container> View;
1863 typedef typename View::type StlContainer;
1864 typedef typename View::const_reference StlContainerReference;
1865
1866 // We make a copy of rhs in case the elements in it are modified
1867 // after this matcher is created.
1868 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
1869 // Makes sure the user doesn't instantiate this class template
1870 // with a const or reference type.
1871 testing::StaticAssertTypeEq<Container,
1872 GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))>();
1873 }
1874
zhanyong.wan6a896b52009-01-16 01:13:50 +00001875 void DescribeTo(::std::ostream* os) const {
1876 *os << "equals ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001877 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001878 }
1879 void DescribeNegationTo(::std::ostream* os) const {
1880 *os << "does not equal ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001881 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001882 }
1883
zhanyong.wanb8243162009-06-04 05:48:20 +00001884 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00001885 bool MatchAndExplain(const LhsContainer& lhs,
1886 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00001887 // GMOCK_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
1888 // that causes LhsContainer to be a const type sometimes.
1889 typedef internal::StlContainerView<GMOCK_REMOVE_CONST_(LhsContainer)>
1890 LhsView;
1891 typedef typename LhsView::type LhsStlContainer;
1892 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00001893 if (lhs_stl_container == rhs_)
1894 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00001895
zhanyong.wane122e452010-01-12 09:03:52 +00001896 ::std::ostream* const os = listener->stream();
1897 if (os != NULL) {
1898 // Something is different. Check for missing values first.
1899 bool printed_header = false;
1900 for (typename LhsStlContainer::const_iterator it =
1901 lhs_stl_container.begin();
1902 it != lhs_stl_container.end(); ++it) {
1903 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
1904 rhs_.end()) {
1905 if (printed_header) {
1906 *os << ", ";
1907 } else {
1908 *os << "Only in actual: ";
1909 printed_header = true;
1910 }
zhanyong.wan6953a722010-01-13 05:15:07 +00001911 UniversalPrinter<typename LhsStlContainer::value_type>::
1912 Print(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001913 }
zhanyong.wane122e452010-01-12 09:03:52 +00001914 }
1915
1916 // Now check for extra values.
1917 bool printed_header2 = false;
1918 for (typename StlContainer::const_iterator it = rhs_.begin();
1919 it != rhs_.end(); ++it) {
1920 if (internal::ArrayAwareFind(
1921 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
1922 lhs_stl_container.end()) {
1923 if (printed_header2) {
1924 *os << ", ";
1925 } else {
1926 *os << (printed_header ? "; not" : "Not") << " in actual: ";
1927 printed_header2 = true;
1928 }
1929 UniversalPrinter<typename StlContainer::value_type>::Print(*it, os);
1930 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00001931 }
1932 }
1933
zhanyong.wane122e452010-01-12 09:03:52 +00001934 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00001935 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001936
zhanyong.wan6a896b52009-01-16 01:13:50 +00001937 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00001938 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001939
1940 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001941};
1942
zhanyong.wanb8243162009-06-04 05:48:20 +00001943// Implements Contains(element_matcher) for the given argument type Container.
1944template <typename Container>
1945class ContainsMatcherImpl : public MatcherInterface<Container> {
1946 public:
1947 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
1948 typedef StlContainerView<RawContainer> View;
1949 typedef typename View::type StlContainer;
1950 typedef typename View::const_reference StlContainerReference;
1951 typedef typename StlContainer::value_type Element;
1952
1953 template <typename InnerMatcher>
1954 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
1955 : inner_matcher_(
1956 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
1957
zhanyong.wanb8243162009-06-04 05:48:20 +00001958 // Describes what this matcher does.
1959 virtual void DescribeTo(::std::ostream* os) const {
1960 *os << "contains at least one element that ";
1961 inner_matcher_.DescribeTo(os);
1962 }
1963
1964 // Describes what the negation of this matcher does.
1965 virtual void DescribeNegationTo(::std::ostream* os) const {
1966 *os << "doesn't contain any element that ";
1967 inner_matcher_.DescribeTo(os);
1968 }
1969
zhanyong.wan82113312010-01-08 21:55:40 +00001970 virtual bool MatchAndExplain(Container container,
1971 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00001972 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00001973 size_t i = 0;
1974 for (typename StlContainer::const_iterator it = stl_container.begin();
1975 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb8243162009-06-04 05:48:20 +00001976 if (inner_matcher_.Matches(*it)) {
zhanyong.wan82113312010-01-08 21:55:40 +00001977 *listener << "element " << i << " matches";
1978 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00001979 }
1980 }
zhanyong.wan82113312010-01-08 21:55:40 +00001981 return false;
zhanyong.wanb8243162009-06-04 05:48:20 +00001982 }
1983
1984 private:
1985 const Matcher<const Element&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001986
1987 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00001988};
1989
1990// Implements polymorphic Contains(element_matcher).
1991template <typename M>
1992class ContainsMatcher {
1993 public:
1994 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
1995
1996 template <typename Container>
1997 operator Matcher<Container>() const {
1998 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
1999 }
2000
2001 private:
2002 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002003
2004 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002005};
2006
zhanyong.wanb5937da2009-07-16 20:26:41 +00002007// Implements Key(inner_matcher) for the given argument pair type.
2008// Key(inner_matcher) matches an std::pair whose 'first' field matches
2009// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2010// std::map that contains at least one element whose key is >= 5.
2011template <typename PairType>
2012class KeyMatcherImpl : public MatcherInterface<PairType> {
2013 public:
2014 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
2015 typedef typename RawPairType::first_type KeyType;
2016
2017 template <typename InnerMatcher>
2018 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2019 : inner_matcher_(
2020 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2021 }
2022
2023 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002024 virtual bool MatchAndExplain(PairType key_value,
2025 MatchResultListener* listener) const {
2026 return inner_matcher_.MatchAndExplain(key_value.first, listener);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002027 }
2028
2029 // Describes what this matcher does.
2030 virtual void DescribeTo(::std::ostream* os) const {
2031 *os << "has a key that ";
2032 inner_matcher_.DescribeTo(os);
2033 }
2034
2035 // Describes what the negation of this matcher does.
2036 virtual void DescribeNegationTo(::std::ostream* os) const {
2037 *os << "doesn't have a key that ";
2038 inner_matcher_.DescribeTo(os);
2039 }
2040
zhanyong.wanb5937da2009-07-16 20:26:41 +00002041 private:
2042 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002043
2044 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002045};
2046
2047// Implements polymorphic Key(matcher_for_key).
2048template <typename M>
2049class KeyMatcher {
2050 public:
2051 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2052
2053 template <typename PairType>
2054 operator Matcher<PairType>() const {
2055 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2056 }
2057
2058 private:
2059 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002060
2061 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002062};
2063
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002064// Implements Pair(first_matcher, second_matcher) for the given argument pair
2065// type with its two matchers. See Pair() function below.
2066template <typename PairType>
2067class PairMatcherImpl : public MatcherInterface<PairType> {
2068 public:
2069 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
2070 typedef typename RawPairType::first_type FirstType;
2071 typedef typename RawPairType::second_type SecondType;
2072
2073 template <typename FirstMatcher, typename SecondMatcher>
2074 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2075 : first_matcher_(
2076 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2077 second_matcher_(
2078 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2079 }
2080
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002081 // Describes what this matcher does.
2082 virtual void DescribeTo(::std::ostream* os) const {
2083 *os << "has a first field that ";
2084 first_matcher_.DescribeTo(os);
2085 *os << ", and has a second field that ";
2086 second_matcher_.DescribeTo(os);
2087 }
2088
2089 // Describes what the negation of this matcher does.
2090 virtual void DescribeNegationTo(::std::ostream* os) const {
2091 *os << "has a first field that ";
2092 first_matcher_.DescribeNegationTo(os);
2093 *os << ", or has a second field that ";
2094 second_matcher_.DescribeNegationTo(os);
2095 }
2096
zhanyong.wan82113312010-01-08 21:55:40 +00002097 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2098 // matches second_matcher.
2099 virtual bool MatchAndExplain(PairType a_pair,
2100 MatchResultListener* listener) const {
2101 StringMatchResultListener listener1;
2102 const bool match1 = first_matcher_.MatchAndExplain(a_pair.first,
2103 &listener1);
2104 internal::string s1 = listener1.str();
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002105 if (s1 != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00002106 s1 = "the first field " + s1;
2107 }
2108 if (!match1) {
2109 *listener << s1;
2110 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002111 }
2112
zhanyong.wan82113312010-01-08 21:55:40 +00002113 StringMatchResultListener listener2;
2114 const bool match2 = second_matcher_.MatchAndExplain(a_pair.second,
2115 &listener2);
2116 internal::string s2 = listener2.str();
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002117 if (s2 != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00002118 s2 = "the second field " + s2;
2119 }
2120 if (!match2) {
2121 *listener << s2;
2122 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002123 }
2124
zhanyong.wan82113312010-01-08 21:55:40 +00002125 *listener << s1;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002126 if (s1 != "" && s2 != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00002127 *listener << ", and ";
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002128 }
zhanyong.wan82113312010-01-08 21:55:40 +00002129 *listener << s2;
2130 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002131 }
2132
2133 private:
2134 const Matcher<const FirstType&> first_matcher_;
2135 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002136
2137 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002138};
2139
2140// Implements polymorphic Pair(first_matcher, second_matcher).
2141template <typename FirstMatcher, typename SecondMatcher>
2142class PairMatcher {
2143 public:
2144 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2145 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2146
2147 template <typename PairType>
2148 operator Matcher<PairType> () const {
2149 return MakeMatcher(
2150 new PairMatcherImpl<PairType>(
2151 first_matcher_, second_matcher_));
2152 }
2153
2154 private:
2155 const FirstMatcher first_matcher_;
2156 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002157
2158 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002159};
2160
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002161// Implements ElementsAre() and ElementsAreArray().
2162template <typename Container>
2163class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2164 public:
2165 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
2166 typedef internal::StlContainerView<RawContainer> View;
2167 typedef typename View::type StlContainer;
2168 typedef typename View::const_reference StlContainerReference;
2169 typedef typename StlContainer::value_type Element;
2170
2171 // Constructs the matcher from a sequence of element values or
2172 // element matchers.
2173 template <typename InputIter>
zhanyong.wan32de5f52009-12-23 00:13:23 +00002174 ElementsAreMatcherImpl(InputIter first, size_t a_count) {
2175 matchers_.reserve(a_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002176 InputIter it = first;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002177 for (size_t i = 0; i != a_count; ++i, ++it) {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002178 matchers_.push_back(MatcherCast<const Element&>(*it));
2179 }
2180 }
2181
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002182 // Describes what this matcher does.
2183 virtual void DescribeTo(::std::ostream* os) const {
2184 if (count() == 0) {
2185 *os << "is empty";
2186 } else if (count() == 1) {
2187 *os << "has 1 element that ";
2188 matchers_[0].DescribeTo(os);
2189 } else {
2190 *os << "has " << Elements(count()) << " where\n";
2191 for (size_t i = 0; i != count(); ++i) {
2192 *os << "element " << i << " ";
2193 matchers_[i].DescribeTo(os);
2194 if (i + 1 < count()) {
2195 *os << ",\n";
2196 }
2197 }
2198 }
2199 }
2200
2201 // Describes what the negation of this matcher does.
2202 virtual void DescribeNegationTo(::std::ostream* os) const {
2203 if (count() == 0) {
2204 *os << "is not empty";
2205 return;
2206 }
2207
2208 *os << "does not have " << Elements(count()) << ", or\n";
2209 for (size_t i = 0; i != count(); ++i) {
2210 *os << "element " << i << " ";
2211 matchers_[i].DescribeNegationTo(os);
2212 if (i + 1 < count()) {
2213 *os << ", or\n";
2214 }
2215 }
2216 }
2217
zhanyong.wan82113312010-01-08 21:55:40 +00002218 virtual bool MatchAndExplain(Container container,
2219 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002220 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002221 const size_t actual_count = stl_container.size();
2222 if (actual_count != count()) {
2223 // The element count doesn't match. If the container is empty,
2224 // there's no need to explain anything as Google Mock already
2225 // prints the empty container. Otherwise we just need to show
2226 // how many elements there actually are.
2227 if (actual_count != 0) {
2228 *listener << "has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002229 }
zhanyong.wan82113312010-01-08 21:55:40 +00002230 return false;
2231 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002232
zhanyong.wan82113312010-01-08 21:55:40 +00002233 typename StlContainer::const_iterator it = stl_container.begin();
2234 // explanations[i] is the explanation of the element at index i.
2235 std::vector<internal::string> explanations(count());
2236 for (size_t i = 0; i != count(); ++it, ++i) {
2237 StringMatchResultListener s;
2238 if (matchers_[i].MatchAndExplain(*it, &s)) {
2239 explanations[i] = s.str();
2240 } else {
2241 // The container has the right size but the i-th element
2242 // doesn't match its expectation.
2243 *listener << "element " << i << " doesn't match";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002244
zhanyong.wan82113312010-01-08 21:55:40 +00002245 StreamInParensAsNeeded(s.str(), listener->stream());
2246 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002247 }
2248 }
zhanyong.wan82113312010-01-08 21:55:40 +00002249
2250 // Every element matches its expectation. We need to explain why
2251 // (the obvious ones can be skipped).
2252
2253 bool reason_printed = false;
2254 for (size_t i = 0; i != count(); ++i) {
2255 const internal::string& s = explanations[i];
2256 if (!s.empty()) {
2257 if (reason_printed) {
2258 *listener << ",\n";
2259 }
2260 *listener << "element " << i << " " << s;
2261 reason_printed = true;
2262 }
2263 }
2264
2265 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002266 }
2267
2268 private:
2269 static Message Elements(size_t count) {
2270 return Message() << count << (count == 1 ? " element" : " elements");
2271 }
2272
2273 size_t count() const { return matchers_.size(); }
2274 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002275
2276 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002277};
2278
2279// Implements ElementsAre() of 0 arguments.
2280class ElementsAreMatcher0 {
2281 public:
2282 ElementsAreMatcher0() {}
2283
2284 template <typename Container>
2285 operator Matcher<Container>() const {
2286 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2287 RawContainer;
2288 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2289 Element;
2290
2291 const Matcher<const Element&>* const matchers = NULL;
2292 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 0));
2293 }
2294};
2295
2296// Implements ElementsAreArray().
2297template <typename T>
2298class ElementsAreArrayMatcher {
2299 public:
2300 ElementsAreArrayMatcher(const T* first, size_t count) :
2301 first_(first), count_(count) {}
2302
2303 template <typename Container>
2304 operator Matcher<Container>() const {
2305 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2306 RawContainer;
2307 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2308 Element;
2309
2310 return MakeMatcher(new ElementsAreMatcherImpl<Container>(first_, count_));
2311 }
2312
2313 private:
2314 const T* const first_;
2315 const size_t count_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002316
2317 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002318};
2319
2320// Constants denoting interpolations in a matcher description string.
2321const int kTupleInterpolation = -1; // "%(*)s"
2322const int kPercentInterpolation = -2; // "%%"
2323const int kInvalidInterpolation = -3; // "%" followed by invalid text
2324
2325// Records the location and content of an interpolation.
2326struct Interpolation {
2327 Interpolation(const char* start, const char* end, int param)
2328 : start_pos(start), end_pos(end), param_index(param) {}
2329
2330 // Points to the start of the interpolation (the '%' character).
2331 const char* start_pos;
2332 // Points to the first character after the interpolation.
2333 const char* end_pos;
2334 // 0-based index of the interpolated matcher parameter;
2335 // kTupleInterpolation for "%(*)s"; kPercentInterpolation for "%%".
2336 int param_index;
2337};
2338
2339typedef ::std::vector<Interpolation> Interpolations;
2340
2341// Parses a matcher description string and returns a vector of
2342// interpolations that appear in the string; generates non-fatal
2343// failures iff 'description' is an invalid matcher description.
2344// 'param_names' is a NULL-terminated array of parameter names in the
2345// order they appear in the MATCHER_P*() parameter list.
2346Interpolations ValidateMatcherDescription(
2347 const char* param_names[], const char* description);
2348
2349// Returns the actual matcher description, given the matcher name,
2350// user-supplied description template string, interpolations in the
2351// string, and the printed values of the matcher parameters.
2352string FormatMatcherDescription(
2353 const char* matcher_name, const char* description,
2354 const Interpolations& interp, const Strings& param_values);
2355
shiqiane35fdd92008-12-10 05:08:54 +00002356} // namespace internal
2357
2358// Implements MatcherCast().
2359template <typename T, typename M>
2360inline Matcher<T> MatcherCast(M matcher) {
2361 return internal::MatcherCastImpl<T, M>::Cast(matcher);
2362}
2363
2364// _ is a matcher that matches anything of any type.
2365//
2366// This definition is fine as:
2367//
2368// 1. The C++ standard permits using the name _ in a namespace that
2369// is not the global namespace or ::std.
2370// 2. The AnythingMatcher class has no data member or constructor,
2371// so it's OK to create global variables of this type.
2372// 3. c-style has approved of using _ in this case.
2373const internal::AnythingMatcher _ = {};
2374// Creates a matcher that matches any value of the given type T.
2375template <typename T>
2376inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2377
2378// Creates a matcher that matches any value of the given type T.
2379template <typename T>
2380inline Matcher<T> An() { return A<T>(); }
2381
2382// Creates a polymorphic matcher that matches anything equal to x.
2383// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2384// wouldn't compile.
2385template <typename T>
2386inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2387
2388// Constructs a Matcher<T> from a 'value' of type T. The constructed
2389// matcher matches any value that's equal to 'value'.
2390template <typename T>
2391Matcher<T>::Matcher(T value) { *this = Eq(value); }
2392
2393// Creates a monomorphic matcher that matches anything with type Lhs
2394// and equal to rhs. A user may need to use this instead of Eq(...)
2395// in order to resolve an overloading ambiguity.
2396//
2397// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2398// or Matcher<T>(x), but more readable than the latter.
2399//
2400// We could define similar monomorphic matchers for other comparison
2401// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2402// it yet as those are used much less than Eq() in practice. A user
2403// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2404// for example.
2405template <typename Lhs, typename Rhs>
2406inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2407
2408// Creates a polymorphic matcher that matches anything >= x.
2409template <typename Rhs>
2410inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2411 return internal::GeMatcher<Rhs>(x);
2412}
2413
2414// Creates a polymorphic matcher that matches anything > x.
2415template <typename Rhs>
2416inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2417 return internal::GtMatcher<Rhs>(x);
2418}
2419
2420// Creates a polymorphic matcher that matches anything <= x.
2421template <typename Rhs>
2422inline internal::LeMatcher<Rhs> Le(Rhs x) {
2423 return internal::LeMatcher<Rhs>(x);
2424}
2425
2426// Creates a polymorphic matcher that matches anything < x.
2427template <typename Rhs>
2428inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2429 return internal::LtMatcher<Rhs>(x);
2430}
2431
2432// Creates a polymorphic matcher that matches anything != x.
2433template <typename Rhs>
2434inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2435 return internal::NeMatcher<Rhs>(x);
2436}
2437
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002438// Creates a polymorphic matcher that matches any NULL pointer.
2439inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2440 return MakePolymorphicMatcher(internal::IsNullMatcher());
2441}
2442
shiqiane35fdd92008-12-10 05:08:54 +00002443// Creates a polymorphic matcher that matches any non-NULL pointer.
2444// This is convenient as Not(NULL) doesn't compile (the compiler
2445// thinks that that expression is comparing a pointer with an integer).
2446inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2447 return MakePolymorphicMatcher(internal::NotNullMatcher());
2448}
2449
2450// Creates a polymorphic matcher that matches any argument that
2451// references variable x.
2452template <typename T>
2453inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2454 return internal::RefMatcher<T&>(x);
2455}
2456
2457// Creates a matcher that matches any double argument approximately
2458// equal to rhs, where two NANs are considered unequal.
2459inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2460 return internal::FloatingEqMatcher<double>(rhs, false);
2461}
2462
2463// Creates a matcher that matches any double argument approximately
2464// equal to rhs, including NaN values when rhs is NaN.
2465inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2466 return internal::FloatingEqMatcher<double>(rhs, true);
2467}
2468
2469// Creates a matcher that matches any float argument approximately
2470// equal to rhs, where two NANs are considered unequal.
2471inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2472 return internal::FloatingEqMatcher<float>(rhs, false);
2473}
2474
2475// Creates a matcher that matches any double argument approximately
2476// equal to rhs, including NaN values when rhs is NaN.
2477inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2478 return internal::FloatingEqMatcher<float>(rhs, true);
2479}
2480
2481// Creates a matcher that matches a pointer (raw or smart) that points
2482// to a value that matches inner_matcher.
2483template <typename InnerMatcher>
2484inline internal::PointeeMatcher<InnerMatcher> Pointee(
2485 const InnerMatcher& inner_matcher) {
2486 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2487}
2488
2489// Creates a matcher that matches an object whose given field matches
2490// 'matcher'. For example,
2491// Field(&Foo::number, Ge(5))
2492// matches a Foo object x iff x.number >= 5.
2493template <typename Class, typename FieldType, typename FieldMatcher>
2494inline PolymorphicMatcher<
2495 internal::FieldMatcher<Class, FieldType> > Field(
2496 FieldType Class::*field, const FieldMatcher& matcher) {
2497 return MakePolymorphicMatcher(
2498 internal::FieldMatcher<Class, FieldType>(
2499 field, MatcherCast<const FieldType&>(matcher)));
2500 // The call to MatcherCast() is required for supporting inner
2501 // matchers of compatible types. For example, it allows
2502 // Field(&Foo::bar, m)
2503 // to compile where bar is an int32 and m is a matcher for int64.
2504}
2505
2506// Creates a matcher that matches an object whose given property
2507// matches 'matcher'. For example,
2508// Property(&Foo::str, StartsWith("hi"))
2509// matches a Foo object x iff x.str() starts with "hi".
2510template <typename Class, typename PropertyType, typename PropertyMatcher>
2511inline PolymorphicMatcher<
2512 internal::PropertyMatcher<Class, PropertyType> > Property(
2513 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2514 return MakePolymorphicMatcher(
2515 internal::PropertyMatcher<Class, PropertyType>(
2516 property,
zhanyong.wane0d051e2009-02-19 00:33:37 +00002517 MatcherCast<GMOCK_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002518 // The call to MatcherCast() is required for supporting inner
2519 // matchers of compatible types. For example, it allows
2520 // Property(&Foo::bar, m)
2521 // to compile where bar() returns an int32 and m is a matcher for int64.
2522}
2523
2524// Creates a matcher that matches an object iff the result of applying
2525// a callable to x matches 'matcher'.
2526// For example,
2527// ResultOf(f, StartsWith("hi"))
2528// matches a Foo object x iff f(x) starts with "hi".
2529// callable parameter can be a function, function pointer, or a functor.
2530// Callable has to satisfy the following conditions:
2531// * It is required to keep no state affecting the results of
2532// the calls on it and make no assumptions about how many calls
2533// will be made. Any state it keeps must be protected from the
2534// concurrent access.
2535// * If it is a function object, it has to define type result_type.
2536// We recommend deriving your functor classes from std::unary_function.
2537template <typename Callable, typename ResultOfMatcher>
2538internal::ResultOfMatcher<Callable> ResultOf(
2539 Callable callable, const ResultOfMatcher& matcher) {
2540 return internal::ResultOfMatcher<Callable>(
2541 callable,
2542 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2543 matcher));
2544 // The call to MatcherCast() is required for supporting inner
2545 // matchers of compatible types. For example, it allows
2546 // ResultOf(Function, m)
2547 // to compile where Function() returns an int32 and m is a matcher for int64.
2548}
2549
2550// String matchers.
2551
2552// Matches a string equal to str.
2553inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2554 StrEq(const internal::string& str) {
2555 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2556 str, true, true));
2557}
2558
2559// Matches a string not equal to str.
2560inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2561 StrNe(const internal::string& str) {
2562 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2563 str, false, true));
2564}
2565
2566// Matches a string equal to str, ignoring case.
2567inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2568 StrCaseEq(const internal::string& str) {
2569 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2570 str, true, false));
2571}
2572
2573// Matches a string not equal to str, ignoring case.
2574inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2575 StrCaseNe(const internal::string& str) {
2576 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2577 str, false, false));
2578}
2579
2580// Creates a matcher that matches any string, std::string, or C string
2581// that contains the given substring.
2582inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2583 HasSubstr(const internal::string& substring) {
2584 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
2585 substring));
2586}
2587
2588// Matches a string that starts with 'prefix' (case-sensitive).
2589inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
2590 StartsWith(const internal::string& prefix) {
2591 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
2592 prefix));
2593}
2594
2595// Matches a string that ends with 'suffix' (case-sensitive).
2596inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
2597 EndsWith(const internal::string& suffix) {
2598 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
2599 suffix));
2600}
2601
shiqiane35fdd92008-12-10 05:08:54 +00002602// Matches a string that fully matches regular expression 'regex'.
2603// The matcher takes ownership of 'regex'.
2604inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2605 const internal::RE* regex) {
2606 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2607}
2608inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2609 const internal::string& regex) {
2610 return MatchesRegex(new internal::RE(regex));
2611}
2612
2613// Matches a string that contains regular expression 'regex'.
2614// The matcher takes ownership of 'regex'.
2615inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2616 const internal::RE* regex) {
2617 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2618}
2619inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2620 const internal::string& regex) {
2621 return ContainsRegex(new internal::RE(regex));
2622}
2623
shiqiane35fdd92008-12-10 05:08:54 +00002624#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2625// Wide string matchers.
2626
2627// Matches a string equal to str.
2628inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2629 StrEq(const internal::wstring& str) {
2630 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2631 str, true, true));
2632}
2633
2634// Matches a string not equal to str.
2635inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2636 StrNe(const internal::wstring& str) {
2637 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2638 str, false, true));
2639}
2640
2641// Matches a string equal to str, ignoring case.
2642inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2643 StrCaseEq(const internal::wstring& str) {
2644 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2645 str, true, false));
2646}
2647
2648// Matches a string not equal to str, ignoring case.
2649inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2650 StrCaseNe(const internal::wstring& str) {
2651 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2652 str, false, false));
2653}
2654
2655// Creates a matcher that matches any wstring, std::wstring, or C wide string
2656// that contains the given substring.
2657inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2658 HasSubstr(const internal::wstring& substring) {
2659 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2660 substring));
2661}
2662
2663// Matches a string that starts with 'prefix' (case-sensitive).
2664inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2665 StartsWith(const internal::wstring& prefix) {
2666 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2667 prefix));
2668}
2669
2670// Matches a string that ends with 'suffix' (case-sensitive).
2671inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2672 EndsWith(const internal::wstring& suffix) {
2673 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2674 suffix));
2675}
2676
2677#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2678
2679// Creates a polymorphic matcher that matches a 2-tuple where the
2680// first field == the second field.
2681inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2682
2683// Creates a polymorphic matcher that matches a 2-tuple where the
2684// first field >= the second field.
2685inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2686
2687// Creates a polymorphic matcher that matches a 2-tuple where the
2688// first field > the second field.
2689inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2690
2691// Creates a polymorphic matcher that matches a 2-tuple where the
2692// first field <= the second field.
2693inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2694
2695// Creates a polymorphic matcher that matches a 2-tuple where the
2696// first field < the second field.
2697inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2698
2699// Creates a polymorphic matcher that matches a 2-tuple where the
2700// first field != the second field.
2701inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2702
2703// Creates a matcher that matches any value of type T that m doesn't
2704// match.
2705template <typename InnerMatcher>
2706inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2707 return internal::NotMatcher<InnerMatcher>(m);
2708}
2709
2710// Creates a matcher that matches any value that matches all of the
2711// given matchers.
2712//
2713// For now we only support up to 5 matchers. Support for more
2714// matchers can be added as needed, or the user can use nested
2715// AllOf()s.
2716template <typename Matcher1, typename Matcher2>
2717inline internal::BothOfMatcher<Matcher1, Matcher2>
2718AllOf(Matcher1 m1, Matcher2 m2) {
2719 return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2);
2720}
2721
2722template <typename Matcher1, typename Matcher2, typename Matcher3>
2723inline internal::BothOfMatcher<Matcher1,
2724 internal::BothOfMatcher<Matcher2, Matcher3> >
2725AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2726 return AllOf(m1, AllOf(m2, m3));
2727}
2728
2729template <typename Matcher1, typename Matcher2, typename Matcher3,
2730 typename Matcher4>
2731inline internal::BothOfMatcher<Matcher1,
2732 internal::BothOfMatcher<Matcher2,
2733 internal::BothOfMatcher<Matcher3, Matcher4> > >
2734AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2735 return AllOf(m1, AllOf(m2, m3, m4));
2736}
2737
2738template <typename Matcher1, typename Matcher2, typename Matcher3,
2739 typename Matcher4, typename Matcher5>
2740inline internal::BothOfMatcher<Matcher1,
2741 internal::BothOfMatcher<Matcher2,
2742 internal::BothOfMatcher<Matcher3,
2743 internal::BothOfMatcher<Matcher4, Matcher5> > > >
2744AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2745 return AllOf(m1, AllOf(m2, m3, m4, m5));
2746}
2747
2748// Creates a matcher that matches any value that matches at least one
2749// of the given matchers.
2750//
2751// For now we only support up to 5 matchers. Support for more
2752// matchers can be added as needed, or the user can use nested
2753// AnyOf()s.
2754template <typename Matcher1, typename Matcher2>
2755inline internal::EitherOfMatcher<Matcher1, Matcher2>
2756AnyOf(Matcher1 m1, Matcher2 m2) {
2757 return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2);
2758}
2759
2760template <typename Matcher1, typename Matcher2, typename Matcher3>
2761inline internal::EitherOfMatcher<Matcher1,
2762 internal::EitherOfMatcher<Matcher2, Matcher3> >
2763AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2764 return AnyOf(m1, AnyOf(m2, m3));
2765}
2766
2767template <typename Matcher1, typename Matcher2, typename Matcher3,
2768 typename Matcher4>
2769inline internal::EitherOfMatcher<Matcher1,
2770 internal::EitherOfMatcher<Matcher2,
2771 internal::EitherOfMatcher<Matcher3, Matcher4> > >
2772AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2773 return AnyOf(m1, AnyOf(m2, m3, m4));
2774}
2775
2776template <typename Matcher1, typename Matcher2, typename Matcher3,
2777 typename Matcher4, typename Matcher5>
2778inline internal::EitherOfMatcher<Matcher1,
2779 internal::EitherOfMatcher<Matcher2,
2780 internal::EitherOfMatcher<Matcher3,
2781 internal::EitherOfMatcher<Matcher4, Matcher5> > > >
2782AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2783 return AnyOf(m1, AnyOf(m2, m3, m4, m5));
2784}
2785
2786// Returns a matcher that matches anything that satisfies the given
2787// predicate. The predicate can be any unary function or functor
2788// whose return type can be implicitly converted to bool.
2789template <typename Predicate>
2790inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
2791Truly(Predicate pred) {
2792 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
2793}
2794
zhanyong.wan6a896b52009-01-16 01:13:50 +00002795// Returns a matcher that matches an equal container.
2796// This matcher behaves like Eq(), but in the event of mismatch lists the
2797// values that are included in one container but not the other. (Duplicate
2798// values and order differences are not explained.)
2799template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00002800inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wanb8243162009-06-04 05:48:20 +00002801 GMOCK_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00002802 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002803 // This following line is for working around a bug in MSVC 8.0,
2804 // which causes Container to be a const type sometimes.
2805 typedef GMOCK_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00002806 return MakePolymorphicMatcher(
2807 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00002808}
2809
2810// Matches an STL-style container or a native array that contains at
2811// least one element matching the given value or matcher.
2812//
2813// Examples:
2814// ::std::set<int> page_ids;
2815// page_ids.insert(3);
2816// page_ids.insert(1);
2817// EXPECT_THAT(page_ids, Contains(1));
2818// EXPECT_THAT(page_ids, Contains(Gt(2)));
2819// EXPECT_THAT(page_ids, Not(Contains(4)));
2820//
2821// ::std::map<int, size_t> page_lengths;
2822// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00002823// EXPECT_THAT(page_lengths,
2824// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00002825//
2826// const char* user_ids[] = { "joe", "mike", "tom" };
2827// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
2828template <typename M>
2829inline internal::ContainsMatcher<M> Contains(M matcher) {
2830 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002831}
2832
zhanyong.wanb5937da2009-07-16 20:26:41 +00002833// Key(inner_matcher) matches an std::pair whose 'first' field matches
2834// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2835// std::map that contains at least one element whose key is >= 5.
2836template <typename M>
2837inline internal::KeyMatcher<M> Key(M inner_matcher) {
2838 return internal::KeyMatcher<M>(inner_matcher);
2839}
2840
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002841// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
2842// matches first_matcher and whose 'second' field matches second_matcher. For
2843// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
2844// to match a std::map<int, string> that contains exactly one element whose key
2845// is >= 5 and whose value equals "foo".
2846template <typename FirstMatcher, typename SecondMatcher>
2847inline internal::PairMatcher<FirstMatcher, SecondMatcher>
2848Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
2849 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
2850 first_matcher, second_matcher);
2851}
2852
shiqiane35fdd92008-12-10 05:08:54 +00002853// Returns a predicate that is satisfied by anything that matches the
2854// given matcher.
2855template <typename M>
2856inline internal::MatcherAsPredicate<M> Matches(M matcher) {
2857 return internal::MatcherAsPredicate<M>(matcher);
2858}
2859
zhanyong.wanb8243162009-06-04 05:48:20 +00002860// Returns true iff the value matches the matcher.
2861template <typename T, typename M>
2862inline bool Value(const T& value, M matcher) {
2863 return testing::Matches(matcher)(value);
2864}
2865
zhanyong.wan34b034c2010-03-05 21:23:23 +00002866// Matches the value against the given matcher and explains the match
2867// result to listener.
2868template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00002869inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00002870 M matcher, const T& value, MatchResultListener* listener) {
2871 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
2872}
2873
zhanyong.wanbf550852009-06-09 06:09:53 +00002874// AllArgs(m) is a synonym of m. This is useful in
2875//
2876// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
2877//
2878// which is easier to read than
2879//
2880// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
2881template <typename InnerMatcher>
2882inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
2883
shiqiane35fdd92008-12-10 05:08:54 +00002884// These macros allow using matchers to check values in Google Test
2885// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
2886// succeed iff the value matches the matcher. If the assertion fails,
2887// the value and the description of the matcher will be printed.
2888#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
2889 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2890#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
2891 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2892
2893} // namespace testing
2894
2895#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_