blob: 9a1bab242a03b60f8d2c7d5ecd67fd0926d02e01 [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.wan676e8cc2010-03-16 20:01:51 +0000456// If the explanation is not empty, prints it to the listener.
457// 'listener' must not be NULL.
458inline void PrintIfNotEmpty(
459 const internal::string& explanation, MatchResultListener* listener) {
460 if (explanation != "") {
461 *listener << ", " << explanation;
462 }
463}
464
465// Matches the value against the given matcher, prints the value and explains
466// the match result to the listener. Returns the match result.
467// 'listener' must not be NULL.
468// Value cannot be passed by const reference, because some matchers take a
469// non-const argument.
470template <typename Value, typename T>
471bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
472 MatchResultListener* listener) {
473 if (!listener->IsInterested()) {
474 // If the listener is not interested, we do not need to construct the
475 // inner explanation.
476 return matcher.Matches(value);
477 }
478
479 StringMatchResultListener inner_listener;
480 const bool match = matcher.MatchAndExplain(value, &inner_listener);
481
482 UniversalPrint(value, listener->stream());
483 PrintIfNotEmpty(inner_listener.str(), listener);
484
485 return match;
486}
487
zhanyong.wan82113312010-01-08 21:55:40 +0000488// If the given string is not empty and os is not NULL, wraps the
489// string inside a pair of parentheses and streams the result to os.
490inline void StreamInParensAsNeeded(const internal::string& str,
491 ::std::ostream* os) {
492 if (!str.empty() && os != NULL) {
493 *os << " (" << str << ")";
shiqiane35fdd92008-12-10 05:08:54 +0000494 }
495}
496
497// An internal helper class for doing compile-time loop on a tuple's
498// fields.
499template <size_t N>
500class TuplePrefix {
501 public:
502 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
503 // iff the first N fields of matcher_tuple matches the first N
504 // fields of value_tuple, respectively.
505 template <typename MatcherTuple, typename ValueTuple>
506 static bool Matches(const MatcherTuple& matcher_tuple,
507 const ValueTuple& value_tuple) {
508 using ::std::tr1::get;
509 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
510 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
511 }
512
513 // TuplePrefix<N>::DescribeMatchFailuresTo(matchers, values, os)
514 // describes failures in matching the first N fields of matchers
515 // against the first N fields of values. If there is no failure,
516 // nothing will be streamed to os.
517 template <typename MatcherTuple, typename ValueTuple>
518 static void DescribeMatchFailuresTo(const MatcherTuple& matchers,
519 const ValueTuple& values,
520 ::std::ostream* os) {
521 using ::std::tr1::tuple_element;
522 using ::std::tr1::get;
523
524 // First, describes failures in the first N - 1 fields.
525 TuplePrefix<N - 1>::DescribeMatchFailuresTo(matchers, values, os);
526
527 // Then describes the failure (if any) in the (N - 1)-th (0-based)
528 // field.
529 typename tuple_element<N - 1, MatcherTuple>::type matcher =
530 get<N - 1>(matchers);
531 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
532 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000533 StringMatchResultListener listener;
534 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000535 // TODO(wan): include in the message the name of the parameter
536 // as used in MOCK_METHOD*() when possible.
537 *os << " Expected arg #" << N - 1 << ": ";
538 get<N - 1>(matchers).DescribeTo(os);
539 *os << "\n Actual: ";
540 // We remove the reference in type Value to prevent the
541 // universal printer from printing the address of value, which
542 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000543 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000544 // the address is interesting.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000545 internal::UniversalPrinter<GMOCK_REMOVE_REFERENCE_(Value)>::
shiqiane35fdd92008-12-10 05:08:54 +0000546 Print(value, os);
zhanyong.wan82113312010-01-08 21:55:40 +0000547
548 StreamInParensAsNeeded(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000549 *os << "\n";
550 }
551 }
552};
553
554// The base case.
555template <>
556class TuplePrefix<0> {
557 public:
558 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000559 static bool Matches(const MatcherTuple& /* matcher_tuple */,
560 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000561 return true;
562 }
563
564 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000565 static void DescribeMatchFailuresTo(const MatcherTuple& /* matchers */,
566 const ValueTuple& /* values */,
567 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000568};
569
570// TupleMatches(matcher_tuple, value_tuple) returns true iff all
571// matchers in matcher_tuple match the corresponding fields in
572// value_tuple. It is a compiler error if matcher_tuple and
573// value_tuple have different number of fields or incompatible field
574// types.
575template <typename MatcherTuple, typename ValueTuple>
576bool TupleMatches(const MatcherTuple& matcher_tuple,
577 const ValueTuple& value_tuple) {
578 using ::std::tr1::tuple_size;
579 // Makes sure that matcher_tuple and value_tuple have the same
580 // number of fields.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000581 GMOCK_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
582 tuple_size<ValueTuple>::value,
583 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000584 return TuplePrefix<tuple_size<ValueTuple>::value>::
585 Matches(matcher_tuple, value_tuple);
586}
587
588// Describes failures in matching matchers against values. If there
589// is no failure, nothing will be streamed to os.
590template <typename MatcherTuple, typename ValueTuple>
591void DescribeMatchFailureTupleTo(const MatcherTuple& matchers,
592 const ValueTuple& values,
593 ::std::ostream* os) {
594 using ::std::tr1::tuple_size;
595 TuplePrefix<tuple_size<MatcherTuple>::value>::DescribeMatchFailuresTo(
596 matchers, values, os);
597}
598
599// The MatcherCastImpl class template is a helper for implementing
600// MatcherCast(). We need this helper in order to partially
601// specialize the implementation of MatcherCast() (C++ allows
602// class/struct templates to be partially specialized, but not
603// function templates.).
604
605// This general version is used when MatcherCast()'s argument is a
606// polymorphic matcher (i.e. something that can be converted to a
607// Matcher but is not one yet; for example, Eq(value)).
608template <typename T, typename M>
609class MatcherCastImpl {
610 public:
611 static Matcher<T> Cast(M polymorphic_matcher) {
612 return Matcher<T>(polymorphic_matcher);
613 }
614};
615
616// This more specialized version is used when MatcherCast()'s argument
617// is already a Matcher. This only compiles when type T can be
618// statically converted to type U.
619template <typename T, typename U>
620class MatcherCastImpl<T, Matcher<U> > {
621 public:
622 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
623 return Matcher<T>(new Impl(source_matcher));
624 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000625
shiqiane35fdd92008-12-10 05:08:54 +0000626 private:
627 class Impl : public MatcherInterface<T> {
628 public:
629 explicit Impl(const Matcher<U>& source_matcher)
630 : source_matcher_(source_matcher) {}
631
632 // We delegate the matching logic to the source matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000633 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
634 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000635 }
636
637 virtual void DescribeTo(::std::ostream* os) const {
638 source_matcher_.DescribeTo(os);
639 }
640
641 virtual void DescribeNegationTo(::std::ostream* os) const {
642 source_matcher_.DescribeNegationTo(os);
643 }
644
shiqiane35fdd92008-12-10 05:08:54 +0000645 private:
646 const Matcher<U> source_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000647
648 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000649 };
650};
651
652// This even more specialized version is used for efficiently casting
653// a matcher to its own type.
654template <typename T>
655class MatcherCastImpl<T, Matcher<T> > {
656 public:
657 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
658};
659
660// Implements A<T>().
661template <typename T>
662class AnyMatcherImpl : public MatcherInterface<T> {
663 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000664 virtual bool MatchAndExplain(
665 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000666 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
667 virtual void DescribeNegationTo(::std::ostream* os) const {
668 // This is mostly for completeness' safe, as it's not very useful
669 // to write Not(A<bool>()). However we cannot completely rule out
670 // such a possibility, and it doesn't hurt to be prepared.
671 *os << "never matches";
672 }
673};
674
675// Implements _, a matcher that matches any value of any
676// type. This is a polymorphic matcher, so we need a template type
677// conversion operator to make it appearing as a Matcher<T> for any
678// type T.
679class AnythingMatcher {
680 public:
681 template <typename T>
682 operator Matcher<T>() const { return A<T>(); }
683};
684
685// Implements a matcher that compares a given value with a
686// pre-supplied value using one of the ==, <=, <, etc, operators. The
687// two values being compared don't have to have the same type.
688//
689// The matcher defined here is polymorphic (for example, Eq(5) can be
690// used to match an int, a short, a double, etc). Therefore we use
691// a template type conversion operator in the implementation.
692//
693// We define this as a macro in order to eliminate duplicated source
694// code.
695//
696// The following template definition assumes that the Rhs parameter is
697// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wane0d051e2009-02-19 00:33:37 +0000698#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000699 template <typename Rhs> class name##Matcher { \
700 public: \
701 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
702 template <typename Lhs> \
703 operator Matcher<Lhs>() const { \
704 return MakeMatcher(new Impl<Lhs>(rhs_)); \
705 } \
706 private: \
707 template <typename Lhs> \
708 class Impl : public MatcherInterface<Lhs> { \
709 public: \
710 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
zhanyong.wan82113312010-01-08 21:55:40 +0000711 virtual bool MatchAndExplain(\
712 Lhs lhs, MatchResultListener* /* listener */) const { \
713 return lhs op rhs_; \
714 } \
shiqiane35fdd92008-12-10 05:08:54 +0000715 virtual void DescribeTo(::std::ostream* os) const { \
716 *os << "is " relation " "; \
717 UniversalPrinter<Rhs>::Print(rhs_, os); \
718 } \
719 virtual void DescribeNegationTo(::std::ostream* os) const { \
720 *os << "is not " relation " "; \
721 UniversalPrinter<Rhs>::Print(rhs_, os); \
722 } \
723 private: \
724 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000725 GTEST_DISALLOW_ASSIGN_(Impl); \
shiqiane35fdd92008-12-10 05:08:54 +0000726 }; \
727 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000728 GTEST_DISALLOW_ASSIGN_(name##Matcher); \
shiqiane35fdd92008-12-10 05:08:54 +0000729 }
730
731// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
732// respectively.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000733GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "equal to");
734GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "greater than or equal to");
735GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "greater than");
736GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "less than or equal to");
737GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "less than");
738GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "not equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000739
zhanyong.wane0d051e2009-02-19 00:33:37 +0000740#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000741
vladlosev79b83502009-11-18 00:43:37 +0000742// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000743// pointer that is NULL.
744class IsNullMatcher {
745 public:
vladlosev79b83502009-11-18 00:43:37 +0000746 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000747 bool MatchAndExplain(const Pointer& p,
748 MatchResultListener* /* listener */) const {
749 return GetRawPointer(p) == NULL;
750 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000751
752 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
753 void DescribeNegationTo(::std::ostream* os) const {
754 *os << "is not NULL";
755 }
756};
757
vladlosev79b83502009-11-18 00:43:37 +0000758// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000759// pointer that is not NULL.
760class NotNullMatcher {
761 public:
vladlosev79b83502009-11-18 00:43:37 +0000762 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000763 bool MatchAndExplain(const Pointer& p,
764 MatchResultListener* /* listener */) const {
765 return GetRawPointer(p) != NULL;
766 }
shiqiane35fdd92008-12-10 05:08:54 +0000767
768 void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; }
769 void DescribeNegationTo(::std::ostream* os) const {
770 *os << "is NULL";
771 }
772};
773
774// Ref(variable) matches any argument that is a reference to
775// 'variable'. This matcher is polymorphic as it can match any
776// super type of the type of 'variable'.
777//
778// The RefMatcher template class implements Ref(variable). It can
779// only be instantiated with a reference type. This prevents a user
780// from mistakenly using Ref(x) to match a non-reference function
781// argument. For example, the following will righteously cause a
782// compiler error:
783//
784// int n;
785// Matcher<int> m1 = Ref(n); // This won't compile.
786// Matcher<int&> m2 = Ref(n); // This will compile.
787template <typename T>
788class RefMatcher;
789
790template <typename T>
791class RefMatcher<T&> {
792 // Google Mock is a generic framework and thus needs to support
793 // mocking any function types, including those that take non-const
794 // reference arguments. Therefore the template parameter T (and
795 // Super below) can be instantiated to either a const type or a
796 // non-const type.
797 public:
798 // RefMatcher() takes a T& instead of const T&, as we want the
799 // compiler to catch using Ref(const_value) as a matcher for a
800 // non-const reference.
801 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
802
803 template <typename Super>
804 operator Matcher<Super&>() const {
805 // By passing object_ (type T&) to Impl(), which expects a Super&,
806 // we make sure that Super is a super type of T. In particular,
807 // this catches using Ref(const_value) as a matcher for a
808 // non-const reference, as you cannot implicitly convert a const
809 // reference to a non-const reference.
810 return MakeMatcher(new Impl<Super>(object_));
811 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000812
shiqiane35fdd92008-12-10 05:08:54 +0000813 private:
814 template <typename Super>
815 class Impl : public MatcherInterface<Super&> {
816 public:
817 explicit Impl(Super& x) : object_(x) {} // NOLINT
818
zhanyong.wandb22c222010-01-28 21:52:29 +0000819 // MatchAndExplain() takes a Super& (as opposed to const Super&)
820 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +0000821 virtual bool MatchAndExplain(
822 Super& x, MatchResultListener* listener) const {
823 *listener << "is located @" << static_cast<const void*>(&x);
824 return &x == &object_;
825 }
shiqiane35fdd92008-12-10 05:08:54 +0000826
827 virtual void DescribeTo(::std::ostream* os) const {
828 *os << "references the variable ";
829 UniversalPrinter<Super&>::Print(object_, os);
830 }
831
832 virtual void DescribeNegationTo(::std::ostream* os) const {
833 *os << "does not reference the variable ";
834 UniversalPrinter<Super&>::Print(object_, os);
835 }
836
shiqiane35fdd92008-12-10 05:08:54 +0000837 private:
838 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000839
840 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000841 };
842
843 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000844
845 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000846};
847
848// Polymorphic helper functions for narrow and wide string matchers.
849inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
850 return String::CaseInsensitiveCStringEquals(lhs, rhs);
851}
852
853inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
854 const wchar_t* rhs) {
855 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
856}
857
858// String comparison for narrow or wide strings that can have embedded NUL
859// characters.
860template <typename StringType>
861bool CaseInsensitiveStringEquals(const StringType& s1,
862 const StringType& s2) {
863 // Are the heads equal?
864 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
865 return false;
866 }
867
868 // Skip the equal heads.
869 const typename StringType::value_type nul = 0;
870 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
871
872 // Are we at the end of either s1 or s2?
873 if (i1 == StringType::npos || i2 == StringType::npos) {
874 return i1 == i2;
875 }
876
877 // Are the tails equal?
878 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
879}
880
881// String matchers.
882
883// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
884template <typename StringType>
885class StrEqualityMatcher {
886 public:
887 typedef typename StringType::const_pointer ConstCharPointer;
888
889 StrEqualityMatcher(const StringType& str, bool expect_eq,
890 bool case_sensitive)
891 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
892
893 // When expect_eq_ is true, returns true iff s is equal to string_;
894 // otherwise returns true iff s is not equal to string_.
zhanyong.wandb22c222010-01-28 21:52:29 +0000895 bool MatchAndExplain(ConstCharPointer s,
896 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +0000897 if (s == NULL) {
898 return !expect_eq_;
899 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000900 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000901 }
902
zhanyong.wandb22c222010-01-28 21:52:29 +0000903 bool MatchAndExplain(const StringType& s,
904 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000905 const bool eq = case_sensitive_ ? s == string_ :
906 CaseInsensitiveStringEquals(s, string_);
907 return expect_eq_ == eq;
908 }
909
910 void DescribeTo(::std::ostream* os) const {
911 DescribeToHelper(expect_eq_, os);
912 }
913
914 void DescribeNegationTo(::std::ostream* os) const {
915 DescribeToHelper(!expect_eq_, os);
916 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000917
shiqiane35fdd92008-12-10 05:08:54 +0000918 private:
919 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
920 *os << "is ";
921 if (!expect_eq) {
922 *os << "not ";
923 }
924 *os << "equal to ";
925 if (!case_sensitive_) {
926 *os << "(ignoring case) ";
927 }
928 UniversalPrinter<StringType>::Print(string_, os);
929 }
930
931 const StringType string_;
932 const bool expect_eq_;
933 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000934
935 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000936};
937
938// Implements the polymorphic HasSubstr(substring) matcher, which
939// can be used as a Matcher<T> as long as T can be converted to a
940// string.
941template <typename StringType>
942class HasSubstrMatcher {
943 public:
944 typedef typename StringType::const_pointer ConstCharPointer;
945
946 explicit HasSubstrMatcher(const StringType& substring)
947 : substring_(substring) {}
948
949 // These overloaded methods allow HasSubstr(substring) to be used as a
950 // Matcher<T> as long as T can be converted to string. Returns true
951 // iff s contains substring_ as a substring.
zhanyong.wandb22c222010-01-28 21:52:29 +0000952 bool MatchAndExplain(ConstCharPointer s,
953 MatchResultListener* listener) const {
954 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000955 }
956
zhanyong.wandb22c222010-01-28 21:52:29 +0000957 bool MatchAndExplain(const StringType& s,
958 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000959 return s.find(substring_) != StringType::npos;
960 }
961
962 // Describes what this matcher matches.
963 void DescribeTo(::std::ostream* os) const {
964 *os << "has substring ";
965 UniversalPrinter<StringType>::Print(substring_, os);
966 }
967
968 void DescribeNegationTo(::std::ostream* os) const {
969 *os << "has no substring ";
970 UniversalPrinter<StringType>::Print(substring_, os);
971 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000972
shiqiane35fdd92008-12-10 05:08:54 +0000973 private:
974 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000975
976 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000977};
978
979// Implements the polymorphic StartsWith(substring) matcher, which
980// can be used as a Matcher<T> as long as T can be converted to a
981// string.
982template <typename StringType>
983class StartsWithMatcher {
984 public:
985 typedef typename StringType::const_pointer ConstCharPointer;
986
987 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
988 }
989
990 // These overloaded methods allow StartsWith(prefix) to be used as a
991 // Matcher<T> as long as T can be converted to string. Returns true
992 // iff s starts with prefix_.
zhanyong.wandb22c222010-01-28 21:52:29 +0000993 bool MatchAndExplain(ConstCharPointer s,
994 MatchResultListener* listener) const {
995 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000996 }
997
zhanyong.wandb22c222010-01-28 21:52:29 +0000998 bool MatchAndExplain(const StringType& s,
999 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001000 return s.length() >= prefix_.length() &&
1001 s.substr(0, prefix_.length()) == prefix_;
1002 }
1003
1004 void DescribeTo(::std::ostream* os) const {
1005 *os << "starts with ";
1006 UniversalPrinter<StringType>::Print(prefix_, os);
1007 }
1008
1009 void DescribeNegationTo(::std::ostream* os) const {
1010 *os << "doesn't start with ";
1011 UniversalPrinter<StringType>::Print(prefix_, os);
1012 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001013
shiqiane35fdd92008-12-10 05:08:54 +00001014 private:
1015 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001016
1017 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001018};
1019
1020// Implements the polymorphic EndsWith(substring) matcher, which
1021// can be used as a Matcher<T> as long as T can be converted to a
1022// string.
1023template <typename StringType>
1024class EndsWithMatcher {
1025 public:
1026 typedef typename StringType::const_pointer ConstCharPointer;
1027
1028 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1029
1030 // These overloaded methods allow EndsWith(suffix) to be used as a
1031 // Matcher<T> as long as T can be converted to string. Returns true
1032 // iff s ends with suffix_.
zhanyong.wandb22c222010-01-28 21:52:29 +00001033 bool MatchAndExplain(ConstCharPointer s,
1034 MatchResultListener* listener) const {
1035 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001036 }
1037
zhanyong.wandb22c222010-01-28 21:52:29 +00001038 bool MatchAndExplain(const StringType& s,
1039 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001040 return s.length() >= suffix_.length() &&
1041 s.substr(s.length() - suffix_.length()) == suffix_;
1042 }
1043
1044 void DescribeTo(::std::ostream* os) const {
1045 *os << "ends with ";
1046 UniversalPrinter<StringType>::Print(suffix_, os);
1047 }
1048
1049 void DescribeNegationTo(::std::ostream* os) const {
1050 *os << "doesn't end with ";
1051 UniversalPrinter<StringType>::Print(suffix_, os);
1052 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001053
shiqiane35fdd92008-12-10 05:08:54 +00001054 private:
1055 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001056
1057 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001058};
1059
shiqiane35fdd92008-12-10 05:08:54 +00001060// Implements polymorphic matchers MatchesRegex(regex) and
1061// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1062// T can be converted to a string.
1063class MatchesRegexMatcher {
1064 public:
1065 MatchesRegexMatcher(const RE* regex, bool full_match)
1066 : regex_(regex), full_match_(full_match) {}
1067
1068 // These overloaded methods allow MatchesRegex(regex) to be used as
1069 // a Matcher<T> as long as T can be converted to string. Returns
1070 // true iff s matches regular expression regex. When full_match_ is
1071 // true, a full match is done; otherwise a partial match is done.
zhanyong.wandb22c222010-01-28 21:52:29 +00001072 bool MatchAndExplain(const char* s,
1073 MatchResultListener* listener) const {
1074 return s != NULL && MatchAndExplain(internal::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001075 }
1076
zhanyong.wandb22c222010-01-28 21:52:29 +00001077 bool MatchAndExplain(const internal::string& s,
1078 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001079 return full_match_ ? RE::FullMatch(s, *regex_) :
1080 RE::PartialMatch(s, *regex_);
1081 }
1082
1083 void DescribeTo(::std::ostream* os) const {
1084 *os << (full_match_ ? "matches" : "contains")
1085 << " regular expression ";
1086 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1087 }
1088
1089 void DescribeNegationTo(::std::ostream* os) const {
1090 *os << "doesn't " << (full_match_ ? "match" : "contain")
1091 << " regular expression ";
1092 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1093 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001094
shiqiane35fdd92008-12-10 05:08:54 +00001095 private:
1096 const internal::linked_ptr<const RE> regex_;
1097 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001098
1099 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001100};
1101
shiqiane35fdd92008-12-10 05:08:54 +00001102// Implements a matcher that compares the two fields of a 2-tuple
1103// using one of the ==, <=, <, etc, operators. The two fields being
1104// compared don't have to have the same type.
1105//
1106// The matcher defined here is polymorphic (for example, Eq() can be
1107// used to match a tuple<int, short>, a tuple<const long&, double>,
1108// etc). Therefore we use a template type conversion operator in the
1109// implementation.
1110//
1111// We define this as a macro in order to eliminate duplicated source
1112// code.
zhanyong.wan2661c682009-06-09 05:42:12 +00001113#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op) \
shiqiane35fdd92008-12-10 05:08:54 +00001114 class name##2Matcher { \
1115 public: \
1116 template <typename T1, typename T2> \
1117 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
1118 return MakeMatcher(new Impl<T1, T2>); \
1119 } \
1120 private: \
1121 template <typename T1, typename T2> \
1122 class Impl : public MatcherInterface<const ::std::tr1::tuple<T1, T2>&> { \
1123 public: \
zhanyong.wan82113312010-01-08 21:55:40 +00001124 virtual bool MatchAndExplain( \
1125 const ::std::tr1::tuple<T1, T2>& args, \
1126 MatchResultListener* /* listener */) const { \
shiqiane35fdd92008-12-10 05:08:54 +00001127 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
1128 } \
1129 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +00001130 *os << "are a pair (x, y) where x " #op " y"; \
shiqiane35fdd92008-12-10 05:08:54 +00001131 } \
1132 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +00001133 *os << "are a pair (x, y) where x " #op " y is false"; \
shiqiane35fdd92008-12-10 05:08:54 +00001134 } \
1135 }; \
1136 }
1137
1138// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wan2661c682009-06-09 05:42:12 +00001139GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==);
1140GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ge, >=);
1141GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Gt, >);
1142GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Le, <=);
1143GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Lt, <);
1144GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=);
shiqiane35fdd92008-12-10 05:08:54 +00001145
zhanyong.wane0d051e2009-02-19 00:33:37 +00001146#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +00001147
zhanyong.wanc6a41232009-05-13 23:38:40 +00001148// Implements the Not(...) matcher for a particular argument type T.
1149// We do not nest it inside the NotMatcher class template, as that
1150// will prevent different instantiations of NotMatcher from sharing
1151// the same NotMatcherImpl<T> class.
1152template <typename T>
1153class NotMatcherImpl : public MatcherInterface<T> {
1154 public:
1155 explicit NotMatcherImpl(const Matcher<T>& matcher)
1156 : matcher_(matcher) {}
1157
zhanyong.wan82113312010-01-08 21:55:40 +00001158 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1159 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001160 }
1161
1162 virtual void DescribeTo(::std::ostream* os) const {
1163 matcher_.DescribeNegationTo(os);
1164 }
1165
1166 virtual void DescribeNegationTo(::std::ostream* os) const {
1167 matcher_.DescribeTo(os);
1168 }
1169
zhanyong.wanc6a41232009-05-13 23:38:40 +00001170 private:
1171 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001172
1173 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001174};
1175
shiqiane35fdd92008-12-10 05:08:54 +00001176// Implements the Not(m) matcher, which matches a value that doesn't
1177// match matcher m.
1178template <typename InnerMatcher>
1179class NotMatcher {
1180 public:
1181 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1182
1183 // This template type conversion operator allows Not(m) to be used
1184 // to match any type m can match.
1185 template <typename T>
1186 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001187 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001188 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001189
shiqiane35fdd92008-12-10 05:08:54 +00001190 private:
shiqiane35fdd92008-12-10 05:08:54 +00001191 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001192
1193 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001194};
1195
zhanyong.wanc6a41232009-05-13 23:38:40 +00001196// Implements the AllOf(m1, m2) matcher for a particular argument type
1197// T. We do not nest it inside the BothOfMatcher class template, as
1198// that will prevent different instantiations of BothOfMatcher from
1199// sharing the same BothOfMatcherImpl<T> class.
1200template <typename T>
1201class BothOfMatcherImpl : public MatcherInterface<T> {
1202 public:
1203 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1204 : matcher1_(matcher1), matcher2_(matcher2) {}
1205
zhanyong.wanc6a41232009-05-13 23:38:40 +00001206 virtual void DescribeTo(::std::ostream* os) const {
1207 *os << "(";
1208 matcher1_.DescribeTo(os);
1209 *os << ") and (";
1210 matcher2_.DescribeTo(os);
1211 *os << ")";
1212 }
1213
1214 virtual void DescribeNegationTo(::std::ostream* os) const {
1215 *os << "not ";
1216 DescribeTo(os);
1217 }
1218
zhanyong.wan82113312010-01-08 21:55:40 +00001219 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1220 // If either matcher1_ or matcher2_ doesn't match x, we only need
1221 // to explain why one of them fails.
1222 StringMatchResultListener listener1;
1223 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1224 *listener << listener1.str();
1225 return false;
1226 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001227
zhanyong.wan82113312010-01-08 21:55:40 +00001228 StringMatchResultListener listener2;
1229 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1230 *listener << listener2.str();
1231 return false;
1232 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001233
zhanyong.wan82113312010-01-08 21:55:40 +00001234 // Otherwise we need to explain why *both* of them match.
1235 const internal::string s1 = listener1.str();
1236 const internal::string s2 = listener2.str();
1237
1238 if (s1 == "") {
1239 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001240 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001241 *listener << s1;
1242 if (s2 != "") {
1243 *listener << "; " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001244 }
1245 }
zhanyong.wan82113312010-01-08 21:55:40 +00001246 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001247 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001248
zhanyong.wanc6a41232009-05-13 23:38:40 +00001249 private:
1250 const Matcher<T> matcher1_;
1251 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001252
1253 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001254};
1255
shiqiane35fdd92008-12-10 05:08:54 +00001256// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1257// matches a value that matches all of the matchers m_1, ..., and m_n.
1258template <typename Matcher1, typename Matcher2>
1259class BothOfMatcher {
1260 public:
1261 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1262 : matcher1_(matcher1), matcher2_(matcher2) {}
1263
1264 // This template type conversion operator allows a
1265 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1266 // both Matcher1 and Matcher2 can match.
1267 template <typename T>
1268 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001269 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1270 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001271 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001272
shiqiane35fdd92008-12-10 05:08:54 +00001273 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001274 Matcher1 matcher1_;
1275 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001276
1277 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001278};
shiqiane35fdd92008-12-10 05:08:54 +00001279
zhanyong.wanc6a41232009-05-13 23:38:40 +00001280// Implements the AnyOf(m1, m2) matcher for a particular argument type
1281// T. We do not nest it inside the AnyOfMatcher class template, as
1282// that will prevent different instantiations of AnyOfMatcher from
1283// sharing the same EitherOfMatcherImpl<T> class.
1284template <typename T>
1285class EitherOfMatcherImpl : public MatcherInterface<T> {
1286 public:
1287 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1288 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001289
zhanyong.wanc6a41232009-05-13 23:38:40 +00001290 virtual void DescribeTo(::std::ostream* os) const {
1291 *os << "(";
1292 matcher1_.DescribeTo(os);
1293 *os << ") or (";
1294 matcher2_.DescribeTo(os);
1295 *os << ")";
1296 }
shiqiane35fdd92008-12-10 05:08:54 +00001297
zhanyong.wanc6a41232009-05-13 23:38:40 +00001298 virtual void DescribeNegationTo(::std::ostream* os) const {
1299 *os << "not ";
1300 DescribeTo(os);
1301 }
shiqiane35fdd92008-12-10 05:08:54 +00001302
zhanyong.wan82113312010-01-08 21:55:40 +00001303 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1304 // If either matcher1_ or matcher2_ matches x, we just need to
1305 // explain why *one* of them matches.
1306 StringMatchResultListener listener1;
1307 if (matcher1_.MatchAndExplain(x, &listener1)) {
1308 *listener << listener1.str();
1309 return true;
1310 }
1311
1312 StringMatchResultListener listener2;
1313 if (matcher2_.MatchAndExplain(x, &listener2)) {
1314 *listener << listener2.str();
1315 return true;
1316 }
1317
1318 // Otherwise we need to explain why *both* of them fail.
1319 const internal::string s1 = listener1.str();
1320 const internal::string s2 = listener2.str();
1321
1322 if (s1 == "") {
1323 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001324 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001325 *listener << s1;
1326 if (s2 != "") {
1327 *listener << "; " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001328 }
1329 }
zhanyong.wan82113312010-01-08 21:55:40 +00001330 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001331 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001332
zhanyong.wanc6a41232009-05-13 23:38:40 +00001333 private:
1334 const Matcher<T> matcher1_;
1335 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001336
1337 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001338};
1339
1340// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1341// matches a value that matches at least one of the matchers m_1, ...,
1342// and m_n.
1343template <typename Matcher1, typename Matcher2>
1344class EitherOfMatcher {
1345 public:
1346 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1347 : matcher1_(matcher1), matcher2_(matcher2) {}
1348
1349 // This template type conversion operator allows a
1350 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1351 // both Matcher1 and Matcher2 can match.
1352 template <typename T>
1353 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001354 return Matcher<T>(new EitherOfMatcherImpl<T>(
1355 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001356 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001357
shiqiane35fdd92008-12-10 05:08:54 +00001358 private:
shiqiane35fdd92008-12-10 05:08:54 +00001359 Matcher1 matcher1_;
1360 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001361
1362 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001363};
1364
1365// Used for implementing Truly(pred), which turns a predicate into a
1366// matcher.
1367template <typename Predicate>
1368class TrulyMatcher {
1369 public:
1370 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1371
1372 // This method template allows Truly(pred) to be used as a matcher
1373 // for type T where T is the argument type of predicate 'pred'. The
1374 // argument is passed by reference as the predicate may be
1375 // interested in the address of the argument.
1376 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001377 bool MatchAndExplain(T& x, // NOLINT
1378 MatchResultListener* /* listener */) const {
zhanyong.wan652540a2009-02-23 23:37:29 +00001379#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001380 // MSVC warns about converting a value into bool (warning 4800).
1381#pragma warning(push) // Saves the current warning state.
1382#pragma warning(disable:4800) // Temporarily disables warning 4800.
1383#endif // GTEST_OS_WINDOWS
1384 return predicate_(x);
zhanyong.wan652540a2009-02-23 23:37:29 +00001385#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001386#pragma warning(pop) // Restores the warning state.
1387#endif // GTEST_OS_WINDOWS
1388 }
1389
1390 void DescribeTo(::std::ostream* os) const {
1391 *os << "satisfies the given predicate";
1392 }
1393
1394 void DescribeNegationTo(::std::ostream* os) const {
1395 *os << "doesn't satisfy the given predicate";
1396 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001397
shiqiane35fdd92008-12-10 05:08:54 +00001398 private:
1399 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001400
1401 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001402};
1403
1404// Used for implementing Matches(matcher), which turns a matcher into
1405// a predicate.
1406template <typename M>
1407class MatcherAsPredicate {
1408 public:
1409 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1410
1411 // This template operator() allows Matches(m) to be used as a
1412 // predicate on type T where m is a matcher on type T.
1413 //
1414 // The argument x is passed by reference instead of by value, as
1415 // some matcher may be interested in its address (e.g. as in
1416 // Matches(Ref(n))(x)).
1417 template <typename T>
1418 bool operator()(const T& x) const {
1419 // We let matcher_ commit to a particular type here instead of
1420 // when the MatcherAsPredicate object was constructed. This
1421 // allows us to write Matches(m) where m is a polymorphic matcher
1422 // (e.g. Eq(5)).
1423 //
1424 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1425 // compile when matcher_ has type Matcher<const T&>; if we write
1426 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1427 // when matcher_ has type Matcher<T>; if we just write
1428 // matcher_.Matches(x), it won't compile when matcher_ is
1429 // polymorphic, e.g. Eq(5).
1430 //
1431 // MatcherCast<const T&>() is necessary for making the code work
1432 // in all of the above situations.
1433 return MatcherCast<const T&>(matcher_).Matches(x);
1434 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001435
shiqiane35fdd92008-12-10 05:08:54 +00001436 private:
1437 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001438
1439 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001440};
1441
1442// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1443// argument M must be a type that can be converted to a matcher.
1444template <typename M>
1445class PredicateFormatterFromMatcher {
1446 public:
1447 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1448
1449 // This template () operator allows a PredicateFormatterFromMatcher
1450 // object to act as a predicate-formatter suitable for using with
1451 // Google Test's EXPECT_PRED_FORMAT1() macro.
1452 template <typename T>
1453 AssertionResult operator()(const char* value_text, const T& x) const {
1454 // We convert matcher_ to a Matcher<const T&> *now* instead of
1455 // when the PredicateFormatterFromMatcher object was constructed,
1456 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1457 // know which type to instantiate it to until we actually see the
1458 // type of x here.
1459 //
1460 // We write MatcherCast<const T&>(matcher_) instead of
1461 // Matcher<const T&>(matcher_), as the latter won't compile when
1462 // matcher_ has type Matcher<T> (e.g. An<int>()).
1463 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001464 StringMatchResultListener listener;
1465 if (matcher.MatchAndExplain(x, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +00001466 return AssertionSuccess();
1467 } else {
1468 ::std::stringstream ss;
1469 ss << "Value of: " << value_text << "\n"
1470 << "Expected: ";
1471 matcher.DescribeTo(&ss);
1472 ss << "\n Actual: ";
1473 UniversalPrinter<T>::Print(x, &ss);
zhanyong.wan82113312010-01-08 21:55:40 +00001474 StreamInParensAsNeeded(listener.str(), &ss);
shiqiane35fdd92008-12-10 05:08:54 +00001475 return AssertionFailure(Message() << ss.str());
1476 }
1477 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001478
shiqiane35fdd92008-12-10 05:08:54 +00001479 private:
1480 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001481
1482 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001483};
1484
1485// A helper function for converting a matcher to a predicate-formatter
1486// without the user needing to explicitly write the type. This is
1487// used for implementing ASSERT_THAT() and EXPECT_THAT().
1488template <typename M>
1489inline PredicateFormatterFromMatcher<M>
1490MakePredicateFormatterFromMatcher(const M& matcher) {
1491 return PredicateFormatterFromMatcher<M>(matcher);
1492}
1493
1494// Implements the polymorphic floating point equality matcher, which
1495// matches two float values using ULP-based approximation. The
1496// template is meant to be instantiated with FloatType being either
1497// float or double.
1498template <typename FloatType>
1499class FloatingEqMatcher {
1500 public:
1501 // Constructor for FloatingEqMatcher.
1502 // The matcher's input will be compared with rhs. The matcher treats two
1503 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1504 // equality comparisons between NANs will always return false.
1505 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1506 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1507
1508 // Implements floating point equality matcher as a Matcher<T>.
1509 template <typename T>
1510 class Impl : public MatcherInterface<T> {
1511 public:
1512 Impl(FloatType rhs, bool nan_eq_nan) :
1513 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1514
zhanyong.wan82113312010-01-08 21:55:40 +00001515 virtual bool MatchAndExplain(T value,
1516 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001517 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1518
1519 // Compares NaNs first, if nan_eq_nan_ is true.
1520 if (nan_eq_nan_ && lhs.is_nan()) {
1521 return rhs.is_nan();
1522 }
1523
1524 return lhs.AlmostEquals(rhs);
1525 }
1526
1527 virtual void DescribeTo(::std::ostream* os) const {
1528 // os->precision() returns the previously set precision, which we
1529 // store to restore the ostream to its original configuration
1530 // after outputting.
1531 const ::std::streamsize old_precision = os->precision(
1532 ::std::numeric_limits<FloatType>::digits10 + 2);
1533 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1534 if (nan_eq_nan_) {
1535 *os << "is NaN";
1536 } else {
1537 *os << "never matches";
1538 }
1539 } else {
1540 *os << "is approximately " << rhs_;
1541 }
1542 os->precision(old_precision);
1543 }
1544
1545 virtual void DescribeNegationTo(::std::ostream* os) const {
1546 // As before, get original precision.
1547 const ::std::streamsize old_precision = os->precision(
1548 ::std::numeric_limits<FloatType>::digits10 + 2);
1549 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1550 if (nan_eq_nan_) {
1551 *os << "is not NaN";
1552 } else {
1553 *os << "is anything";
1554 }
1555 } else {
1556 *os << "is not approximately " << rhs_;
1557 }
1558 // Restore original precision.
1559 os->precision(old_precision);
1560 }
1561
1562 private:
1563 const FloatType rhs_;
1564 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001565
1566 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001567 };
1568
1569 // The following 3 type conversion operators allow FloatEq(rhs) and
1570 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1571 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1572 // (While Google's C++ coding style doesn't allow arguments passed
1573 // by non-const reference, we may see them in code not conforming to
1574 // the style. Therefore Google Mock needs to support them.)
1575 operator Matcher<FloatType>() const {
1576 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1577 }
1578
1579 operator Matcher<const FloatType&>() const {
1580 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1581 }
1582
1583 operator Matcher<FloatType&>() const {
1584 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1585 }
1586 private:
1587 const FloatType rhs_;
1588 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001589
1590 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001591};
1592
1593// Implements the Pointee(m) matcher for matching a pointer whose
1594// pointee matches matcher m. The pointer can be either raw or smart.
1595template <typename InnerMatcher>
1596class PointeeMatcher {
1597 public:
1598 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1599
1600 // This type conversion operator template allows Pointee(m) to be
1601 // used as a matcher for any pointer type whose pointee type is
1602 // compatible with the inner matcher, where type Pointer can be
1603 // either a raw pointer or a smart pointer.
1604 //
1605 // The reason we do this instead of relying on
1606 // MakePolymorphicMatcher() is that the latter is not flexible
1607 // enough for implementing the DescribeTo() method of Pointee().
1608 template <typename Pointer>
1609 operator Matcher<Pointer>() const {
1610 return MakeMatcher(new Impl<Pointer>(matcher_));
1611 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001612
shiqiane35fdd92008-12-10 05:08:54 +00001613 private:
1614 // The monomorphic implementation that works for a particular pointer type.
1615 template <typename Pointer>
1616 class Impl : public MatcherInterface<Pointer> {
1617 public:
zhanyong.wane0d051e2009-02-19 00:33:37 +00001618 typedef typename PointeeOf<GMOCK_REMOVE_CONST_( // NOLINT
1619 GMOCK_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001620
1621 explicit Impl(const InnerMatcher& matcher)
1622 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1623
shiqiane35fdd92008-12-10 05:08:54 +00001624 virtual void DescribeTo(::std::ostream* os) const {
1625 *os << "points to a value that ";
1626 matcher_.DescribeTo(os);
1627 }
1628
1629 virtual void DescribeNegationTo(::std::ostream* os) const {
1630 *os << "does not point to a value that ";
1631 matcher_.DescribeTo(os);
1632 }
1633
zhanyong.wan82113312010-01-08 21:55:40 +00001634 virtual bool MatchAndExplain(Pointer pointer,
1635 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001636 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00001637 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001638
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001639 *listener << "which points to ";
1640 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001641 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001642
shiqiane35fdd92008-12-10 05:08:54 +00001643 private:
1644 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001645
1646 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001647 };
1648
1649 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001650
1651 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001652};
1653
1654// Implements the Field() matcher for matching a field (i.e. member
1655// variable) of an object.
1656template <typename Class, typename FieldType>
1657class FieldMatcher {
1658 public:
1659 FieldMatcher(FieldType Class::*field,
1660 const Matcher<const FieldType&>& matcher)
1661 : field_(field), matcher_(matcher) {}
1662
shiqiane35fdd92008-12-10 05:08:54 +00001663 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001664 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001665 matcher_.DescribeTo(os);
1666 }
1667
1668 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001669 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001670 matcher_.DescribeNegationTo(os);
1671 }
1672
zhanyong.wandb22c222010-01-28 21:52:29 +00001673 template <typename T>
1674 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
1675 return MatchAndExplainImpl(
1676 typename ::testing::internal::
1677 is_pointer<GMOCK_REMOVE_CONST_(T)>::type(),
1678 value, listener);
1679 }
1680
1681 private:
1682 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001683 // Symbian's C++ compiler choose which overload to use. Its type is
1684 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001685 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1686 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001687 *listener << "whose given field is ";
1688 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001689 }
1690
zhanyong.wandb22c222010-01-28 21:52:29 +00001691 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1692 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001693 if (p == NULL)
1694 return false;
1695
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001696 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001697 // Since *p has a field, it must be a class/struct/union type and
1698 // thus cannot be a pointer. Therefore we pass false_type() as
1699 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001700 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001701 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001702
shiqiane35fdd92008-12-10 05:08:54 +00001703 const FieldType Class::*field_;
1704 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001705
1706 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001707};
1708
shiqiane35fdd92008-12-10 05:08:54 +00001709// Implements the Property() matcher for matching a property
1710// (i.e. return value of a getter method) of an object.
1711template <typename Class, typename PropertyType>
1712class PropertyMatcher {
1713 public:
1714 // The property may have a reference type, so 'const PropertyType&'
1715 // may cause double references and fail to compile. That's why we
1716 // need GMOCK_REFERENCE_TO_CONST, which works regardless of
1717 // PropertyType being a reference or not.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001718 typedef GMOCK_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001719
1720 PropertyMatcher(PropertyType (Class::*property)() const,
1721 const Matcher<RefToConstProperty>& matcher)
1722 : property_(property), matcher_(matcher) {}
1723
shiqiane35fdd92008-12-10 05:08:54 +00001724 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001725 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001726 matcher_.DescribeTo(os);
1727 }
1728
1729 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001730 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001731 matcher_.DescribeNegationTo(os);
1732 }
1733
zhanyong.wandb22c222010-01-28 21:52:29 +00001734 template <typename T>
1735 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
1736 return MatchAndExplainImpl(
1737 typename ::testing::internal::
1738 is_pointer<GMOCK_REMOVE_CONST_(T)>::type(),
1739 value, listener);
1740 }
1741
1742 private:
1743 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001744 // Symbian's C++ compiler choose which overload to use. Its type is
1745 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001746 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1747 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001748 *listener << "whose given property is ";
1749 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
1750 // which takes a non-const reference as argument.
1751 RefToConstProperty result = (obj.*property_)();
1752 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001753 }
1754
zhanyong.wandb22c222010-01-28 21:52:29 +00001755 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1756 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001757 if (p == NULL)
1758 return false;
1759
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001760 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001761 // Since *p has a property method, it must be a class/struct/union
1762 // type and thus cannot be a pointer. Therefore we pass
1763 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001764 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001765 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001766
shiqiane35fdd92008-12-10 05:08:54 +00001767 PropertyType (Class::*property_)() const;
1768 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001769
1770 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001771};
1772
shiqiane35fdd92008-12-10 05:08:54 +00001773// Type traits specifying various features of different functors for ResultOf.
1774// The default template specifies features for functor objects.
1775// Functor classes have to typedef argument_type and result_type
1776// to be compatible with ResultOf.
1777template <typename Functor>
1778struct CallableTraits {
1779 typedef typename Functor::result_type ResultType;
1780 typedef Functor StorageType;
1781
zhanyong.wan32de5f52009-12-23 00:13:23 +00001782 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00001783 template <typename T>
1784 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1785};
1786
1787// Specialization for function pointers.
1788template <typename ArgType, typename ResType>
1789struct CallableTraits<ResType(*)(ArgType)> {
1790 typedef ResType ResultType;
1791 typedef ResType(*StorageType)(ArgType);
1792
1793 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001794 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00001795 << "NULL function pointer is passed into ResultOf().";
1796 }
1797 template <typename T>
1798 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1799 return (*f)(arg);
1800 }
1801};
1802
1803// Implements the ResultOf() matcher for matching a return value of a
1804// unary function of an object.
1805template <typename Callable>
1806class ResultOfMatcher {
1807 public:
1808 typedef typename CallableTraits<Callable>::ResultType ResultType;
1809
1810 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1811 : callable_(callable), matcher_(matcher) {
1812 CallableTraits<Callable>::CheckIsValid(callable_);
1813 }
1814
1815 template <typename T>
1816 operator Matcher<T>() const {
1817 return Matcher<T>(new Impl<T>(callable_, matcher_));
1818 }
1819
1820 private:
1821 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1822
1823 template <typename T>
1824 class Impl : public MatcherInterface<T> {
1825 public:
1826 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1827 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00001828
1829 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001830 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001831 matcher_.DescribeTo(os);
1832 }
1833
1834 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001835 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001836 matcher_.DescribeNegationTo(os);
1837 }
1838
zhanyong.wan82113312010-01-08 21:55:40 +00001839 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001840 *listener << "which is mapped by the given callable to ";
1841 // Cannot pass the return value (for example, int) to
1842 // MatchPrintAndExplain, which takes a non-const reference as argument.
1843 ResultType result =
1844 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
1845 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001846 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001847
shiqiane35fdd92008-12-10 05:08:54 +00001848 private:
1849 // Functors often define operator() as non-const method even though
1850 // they are actualy stateless. But we need to use them even when
1851 // 'this' is a const pointer. It's the user's responsibility not to
1852 // use stateful callables with ResultOf(), which does't guarantee
1853 // how many times the callable will be invoked.
1854 mutable CallableStorageType callable_;
1855 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001856
1857 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001858 }; // class Impl
1859
1860 const CallableStorageType callable_;
1861 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001862
1863 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001864};
1865
zhanyong.wan6a896b52009-01-16 01:13:50 +00001866// Implements an equality matcher for any STL-style container whose elements
1867// support ==. This matcher is like Eq(), but its failure explanations provide
1868// more detailed information that is useful when the container is used as a set.
1869// The failure message reports elements that are in one of the operands but not
1870// the other. The failure messages do not report duplicate or out-of-order
1871// elements in the containers (which don't properly matter to sets, but can
1872// occur if the containers are vectors or lists, for example).
1873//
1874// Uses the container's const_iterator, value_type, operator ==,
1875// begin(), and end().
1876template <typename Container>
1877class ContainerEqMatcher {
1878 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00001879 typedef internal::StlContainerView<Container> View;
1880 typedef typename View::type StlContainer;
1881 typedef typename View::const_reference StlContainerReference;
1882
1883 // We make a copy of rhs in case the elements in it are modified
1884 // after this matcher is created.
1885 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
1886 // Makes sure the user doesn't instantiate this class template
1887 // with a const or reference type.
1888 testing::StaticAssertTypeEq<Container,
1889 GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))>();
1890 }
1891
zhanyong.wan6a896b52009-01-16 01:13:50 +00001892 void DescribeTo(::std::ostream* os) const {
1893 *os << "equals ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001894 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001895 }
1896 void DescribeNegationTo(::std::ostream* os) const {
1897 *os << "does not equal ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001898 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001899 }
1900
zhanyong.wanb8243162009-06-04 05:48:20 +00001901 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00001902 bool MatchAndExplain(const LhsContainer& lhs,
1903 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00001904 // GMOCK_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
1905 // that causes LhsContainer to be a const type sometimes.
1906 typedef internal::StlContainerView<GMOCK_REMOVE_CONST_(LhsContainer)>
1907 LhsView;
1908 typedef typename LhsView::type LhsStlContainer;
1909 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00001910 if (lhs_stl_container == rhs_)
1911 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00001912
zhanyong.wane122e452010-01-12 09:03:52 +00001913 ::std::ostream* const os = listener->stream();
1914 if (os != NULL) {
1915 // Something is different. Check for missing values first.
1916 bool printed_header = false;
1917 for (typename LhsStlContainer::const_iterator it =
1918 lhs_stl_container.begin();
1919 it != lhs_stl_container.end(); ++it) {
1920 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
1921 rhs_.end()) {
1922 if (printed_header) {
1923 *os << ", ";
1924 } else {
1925 *os << "Only in actual: ";
1926 printed_header = true;
1927 }
zhanyong.wan6953a722010-01-13 05:15:07 +00001928 UniversalPrinter<typename LhsStlContainer::value_type>::
1929 Print(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001930 }
zhanyong.wane122e452010-01-12 09:03:52 +00001931 }
1932
1933 // Now check for extra values.
1934 bool printed_header2 = false;
1935 for (typename StlContainer::const_iterator it = rhs_.begin();
1936 it != rhs_.end(); ++it) {
1937 if (internal::ArrayAwareFind(
1938 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
1939 lhs_stl_container.end()) {
1940 if (printed_header2) {
1941 *os << ", ";
1942 } else {
1943 *os << (printed_header ? "; not" : "Not") << " in actual: ";
1944 printed_header2 = true;
1945 }
1946 UniversalPrinter<typename StlContainer::value_type>::Print(*it, os);
1947 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00001948 }
1949 }
1950
zhanyong.wane122e452010-01-12 09:03:52 +00001951 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00001952 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001953
zhanyong.wan6a896b52009-01-16 01:13:50 +00001954 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00001955 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001956
1957 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001958};
1959
zhanyong.wanb8243162009-06-04 05:48:20 +00001960// Implements Contains(element_matcher) for the given argument type Container.
1961template <typename Container>
1962class ContainsMatcherImpl : public MatcherInterface<Container> {
1963 public:
1964 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
1965 typedef StlContainerView<RawContainer> View;
1966 typedef typename View::type StlContainer;
1967 typedef typename View::const_reference StlContainerReference;
1968 typedef typename StlContainer::value_type Element;
1969
1970 template <typename InnerMatcher>
1971 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
1972 : inner_matcher_(
1973 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
1974
zhanyong.wanb8243162009-06-04 05:48:20 +00001975 // Describes what this matcher does.
1976 virtual void DescribeTo(::std::ostream* os) const {
1977 *os << "contains at least one element that ";
1978 inner_matcher_.DescribeTo(os);
1979 }
1980
1981 // Describes what the negation of this matcher does.
1982 virtual void DescribeNegationTo(::std::ostream* os) const {
1983 *os << "doesn't contain any element that ";
1984 inner_matcher_.DescribeTo(os);
1985 }
1986
zhanyong.wan82113312010-01-08 21:55:40 +00001987 virtual bool MatchAndExplain(Container container,
1988 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00001989 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00001990 size_t i = 0;
1991 for (typename StlContainer::const_iterator it = stl_container.begin();
1992 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb8243162009-06-04 05:48:20 +00001993 if (inner_matcher_.Matches(*it)) {
zhanyong.wan82113312010-01-08 21:55:40 +00001994 *listener << "element " << i << " matches";
1995 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00001996 }
1997 }
zhanyong.wan82113312010-01-08 21:55:40 +00001998 return false;
zhanyong.wanb8243162009-06-04 05:48:20 +00001999 }
2000
2001 private:
2002 const Matcher<const Element&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002003
2004 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002005};
2006
2007// Implements polymorphic Contains(element_matcher).
2008template <typename M>
2009class ContainsMatcher {
2010 public:
2011 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2012
2013 template <typename Container>
2014 operator Matcher<Container>() const {
2015 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2016 }
2017
2018 private:
2019 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002020
2021 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002022};
2023
zhanyong.wanb5937da2009-07-16 20:26:41 +00002024// Implements Key(inner_matcher) for the given argument pair type.
2025// Key(inner_matcher) matches an std::pair whose 'first' field matches
2026// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2027// std::map that contains at least one element whose key is >= 5.
2028template <typename PairType>
2029class KeyMatcherImpl : public MatcherInterface<PairType> {
2030 public:
2031 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
2032 typedef typename RawPairType::first_type KeyType;
2033
2034 template <typename InnerMatcher>
2035 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2036 : inner_matcher_(
2037 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2038 }
2039
2040 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002041 virtual bool MatchAndExplain(PairType key_value,
2042 MatchResultListener* listener) const {
2043 return inner_matcher_.MatchAndExplain(key_value.first, listener);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002044 }
2045
2046 // Describes what this matcher does.
2047 virtual void DescribeTo(::std::ostream* os) const {
2048 *os << "has a key that ";
2049 inner_matcher_.DescribeTo(os);
2050 }
2051
2052 // Describes what the negation of this matcher does.
2053 virtual void DescribeNegationTo(::std::ostream* os) const {
2054 *os << "doesn't have a key that ";
2055 inner_matcher_.DescribeTo(os);
2056 }
2057
zhanyong.wanb5937da2009-07-16 20:26:41 +00002058 private:
2059 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002060
2061 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002062};
2063
2064// Implements polymorphic Key(matcher_for_key).
2065template <typename M>
2066class KeyMatcher {
2067 public:
2068 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2069
2070 template <typename PairType>
2071 operator Matcher<PairType>() const {
2072 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2073 }
2074
2075 private:
2076 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002077
2078 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002079};
2080
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002081// Implements Pair(first_matcher, second_matcher) for the given argument pair
2082// type with its two matchers. See Pair() function below.
2083template <typename PairType>
2084class PairMatcherImpl : public MatcherInterface<PairType> {
2085 public:
2086 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
2087 typedef typename RawPairType::first_type FirstType;
2088 typedef typename RawPairType::second_type SecondType;
2089
2090 template <typename FirstMatcher, typename SecondMatcher>
2091 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2092 : first_matcher_(
2093 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2094 second_matcher_(
2095 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2096 }
2097
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002098 // Describes what this matcher does.
2099 virtual void DescribeTo(::std::ostream* os) const {
2100 *os << "has a first field that ";
2101 first_matcher_.DescribeTo(os);
2102 *os << ", and has a second field that ";
2103 second_matcher_.DescribeTo(os);
2104 }
2105
2106 // Describes what the negation of this matcher does.
2107 virtual void DescribeNegationTo(::std::ostream* os) const {
2108 *os << "has a first field that ";
2109 first_matcher_.DescribeNegationTo(os);
2110 *os << ", or has a second field that ";
2111 second_matcher_.DescribeNegationTo(os);
2112 }
2113
zhanyong.wan82113312010-01-08 21:55:40 +00002114 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2115 // matches second_matcher.
2116 virtual bool MatchAndExplain(PairType a_pair,
2117 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002118 if (!listener->IsInterested()) {
2119 // If the listener is not interested, we don't need to construct the
2120 // explanation.
2121 return first_matcher_.Matches(a_pair.first) &&
2122 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00002123 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002124 StringMatchResultListener first_inner_listener;
2125 if (!first_matcher_.MatchAndExplain(a_pair.first,
2126 &first_inner_listener)) {
2127 *listener << "whose first field does not match";
2128 PrintIfNotEmpty(first_inner_listener.str(), listener);
zhanyong.wan82113312010-01-08 21:55:40 +00002129 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002130 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002131 StringMatchResultListener second_inner_listener;
2132 if (!second_matcher_.MatchAndExplain(a_pair.second,
2133 &second_inner_listener)) {
2134 *listener << "whose second field does not match";
2135 PrintIfNotEmpty(second_inner_listener.str(), listener);
zhanyong.wan82113312010-01-08 21:55:40 +00002136 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002137 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002138 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
2139 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00002140 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002141 }
2142
2143 private:
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002144 void ExplainSuccess(const internal::string& first_explanation,
2145 const internal::string& second_explanation,
2146 MatchResultListener* listener) const {
2147 *listener << "whose both fields match";
2148 if (first_explanation != "") {
2149 *listener << ", where the first field is a value " << first_explanation;
2150 }
2151 if (second_explanation != "") {
2152 *listener << ", ";
2153 if (first_explanation != "") {
2154 *listener << "and ";
2155 } else {
2156 *listener << "where ";
2157 }
2158 *listener << "the second field is a value " << second_explanation;
2159 }
2160 }
2161
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002162 const Matcher<const FirstType&> first_matcher_;
2163 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002164
2165 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002166};
2167
2168// Implements polymorphic Pair(first_matcher, second_matcher).
2169template <typename FirstMatcher, typename SecondMatcher>
2170class PairMatcher {
2171 public:
2172 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2173 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2174
2175 template <typename PairType>
2176 operator Matcher<PairType> () const {
2177 return MakeMatcher(
2178 new PairMatcherImpl<PairType>(
2179 first_matcher_, second_matcher_));
2180 }
2181
2182 private:
2183 const FirstMatcher first_matcher_;
2184 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002185
2186 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002187};
2188
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002189// Implements ElementsAre() and ElementsAreArray().
2190template <typename Container>
2191class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2192 public:
2193 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
2194 typedef internal::StlContainerView<RawContainer> View;
2195 typedef typename View::type StlContainer;
2196 typedef typename View::const_reference StlContainerReference;
2197 typedef typename StlContainer::value_type Element;
2198
2199 // Constructs the matcher from a sequence of element values or
2200 // element matchers.
2201 template <typename InputIter>
zhanyong.wan32de5f52009-12-23 00:13:23 +00002202 ElementsAreMatcherImpl(InputIter first, size_t a_count) {
2203 matchers_.reserve(a_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002204 InputIter it = first;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002205 for (size_t i = 0; i != a_count; ++i, ++it) {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002206 matchers_.push_back(MatcherCast<const Element&>(*it));
2207 }
2208 }
2209
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002210 // Describes what this matcher does.
2211 virtual void DescribeTo(::std::ostream* os) const {
2212 if (count() == 0) {
2213 *os << "is empty";
2214 } else if (count() == 1) {
2215 *os << "has 1 element that ";
2216 matchers_[0].DescribeTo(os);
2217 } else {
2218 *os << "has " << Elements(count()) << " where\n";
2219 for (size_t i = 0; i != count(); ++i) {
2220 *os << "element " << i << " ";
2221 matchers_[i].DescribeTo(os);
2222 if (i + 1 < count()) {
2223 *os << ",\n";
2224 }
2225 }
2226 }
2227 }
2228
2229 // Describes what the negation of this matcher does.
2230 virtual void DescribeNegationTo(::std::ostream* os) const {
2231 if (count() == 0) {
2232 *os << "is not empty";
2233 return;
2234 }
2235
2236 *os << "does not have " << Elements(count()) << ", or\n";
2237 for (size_t i = 0; i != count(); ++i) {
2238 *os << "element " << i << " ";
2239 matchers_[i].DescribeNegationTo(os);
2240 if (i + 1 < count()) {
2241 *os << ", or\n";
2242 }
2243 }
2244 }
2245
zhanyong.wan82113312010-01-08 21:55:40 +00002246 virtual bool MatchAndExplain(Container container,
2247 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002248 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002249 const size_t actual_count = stl_container.size();
2250 if (actual_count != count()) {
2251 // The element count doesn't match. If the container is empty,
2252 // there's no need to explain anything as Google Mock already
2253 // prints the empty container. Otherwise we just need to show
2254 // how many elements there actually are.
2255 if (actual_count != 0) {
2256 *listener << "has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002257 }
zhanyong.wan82113312010-01-08 21:55:40 +00002258 return false;
2259 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002260
zhanyong.wan82113312010-01-08 21:55:40 +00002261 typename StlContainer::const_iterator it = stl_container.begin();
2262 // explanations[i] is the explanation of the element at index i.
2263 std::vector<internal::string> explanations(count());
2264 for (size_t i = 0; i != count(); ++it, ++i) {
2265 StringMatchResultListener s;
2266 if (matchers_[i].MatchAndExplain(*it, &s)) {
2267 explanations[i] = s.str();
2268 } else {
2269 // The container has the right size but the i-th element
2270 // doesn't match its expectation.
2271 *listener << "element " << i << " doesn't match";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002272
zhanyong.wan82113312010-01-08 21:55:40 +00002273 StreamInParensAsNeeded(s.str(), listener->stream());
2274 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002275 }
2276 }
zhanyong.wan82113312010-01-08 21:55:40 +00002277
2278 // Every element matches its expectation. We need to explain why
2279 // (the obvious ones can be skipped).
2280
2281 bool reason_printed = false;
2282 for (size_t i = 0; i != count(); ++i) {
2283 const internal::string& s = explanations[i];
2284 if (!s.empty()) {
2285 if (reason_printed) {
2286 *listener << ",\n";
2287 }
2288 *listener << "element " << i << " " << s;
2289 reason_printed = true;
2290 }
2291 }
2292
2293 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002294 }
2295
2296 private:
2297 static Message Elements(size_t count) {
2298 return Message() << count << (count == 1 ? " element" : " elements");
2299 }
2300
2301 size_t count() const { return matchers_.size(); }
2302 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002303
2304 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002305};
2306
2307// Implements ElementsAre() of 0 arguments.
2308class ElementsAreMatcher0 {
2309 public:
2310 ElementsAreMatcher0() {}
2311
2312 template <typename Container>
2313 operator Matcher<Container>() const {
2314 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2315 RawContainer;
2316 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2317 Element;
2318
2319 const Matcher<const Element&>* const matchers = NULL;
2320 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 0));
2321 }
2322};
2323
2324// Implements ElementsAreArray().
2325template <typename T>
2326class ElementsAreArrayMatcher {
2327 public:
2328 ElementsAreArrayMatcher(const T* first, size_t count) :
2329 first_(first), count_(count) {}
2330
2331 template <typename Container>
2332 operator Matcher<Container>() const {
2333 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2334 RawContainer;
2335 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2336 Element;
2337
2338 return MakeMatcher(new ElementsAreMatcherImpl<Container>(first_, count_));
2339 }
2340
2341 private:
2342 const T* const first_;
2343 const size_t count_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002344
2345 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002346};
2347
2348// Constants denoting interpolations in a matcher description string.
2349const int kTupleInterpolation = -1; // "%(*)s"
2350const int kPercentInterpolation = -2; // "%%"
2351const int kInvalidInterpolation = -3; // "%" followed by invalid text
2352
2353// Records the location and content of an interpolation.
2354struct Interpolation {
2355 Interpolation(const char* start, const char* end, int param)
2356 : start_pos(start), end_pos(end), param_index(param) {}
2357
2358 // Points to the start of the interpolation (the '%' character).
2359 const char* start_pos;
2360 // Points to the first character after the interpolation.
2361 const char* end_pos;
2362 // 0-based index of the interpolated matcher parameter;
2363 // kTupleInterpolation for "%(*)s"; kPercentInterpolation for "%%".
2364 int param_index;
2365};
2366
2367typedef ::std::vector<Interpolation> Interpolations;
2368
2369// Parses a matcher description string and returns a vector of
2370// interpolations that appear in the string; generates non-fatal
2371// failures iff 'description' is an invalid matcher description.
2372// 'param_names' is a NULL-terminated array of parameter names in the
2373// order they appear in the MATCHER_P*() parameter list.
2374Interpolations ValidateMatcherDescription(
2375 const char* param_names[], const char* description);
2376
2377// Returns the actual matcher description, given the matcher name,
2378// user-supplied description template string, interpolations in the
2379// string, and the printed values of the matcher parameters.
2380string FormatMatcherDescription(
2381 const char* matcher_name, const char* description,
2382 const Interpolations& interp, const Strings& param_values);
2383
shiqiane35fdd92008-12-10 05:08:54 +00002384} // namespace internal
2385
2386// Implements MatcherCast().
2387template <typename T, typename M>
2388inline Matcher<T> MatcherCast(M matcher) {
2389 return internal::MatcherCastImpl<T, M>::Cast(matcher);
2390}
2391
2392// _ is a matcher that matches anything of any type.
2393//
2394// This definition is fine as:
2395//
2396// 1. The C++ standard permits using the name _ in a namespace that
2397// is not the global namespace or ::std.
2398// 2. The AnythingMatcher class has no data member or constructor,
2399// so it's OK to create global variables of this type.
2400// 3. c-style has approved of using _ in this case.
2401const internal::AnythingMatcher _ = {};
2402// Creates a matcher that matches any value of the given type T.
2403template <typename T>
2404inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2405
2406// Creates a matcher that matches any value of the given type T.
2407template <typename T>
2408inline Matcher<T> An() { return A<T>(); }
2409
2410// Creates a polymorphic matcher that matches anything equal to x.
2411// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2412// wouldn't compile.
2413template <typename T>
2414inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2415
2416// Constructs a Matcher<T> from a 'value' of type T. The constructed
2417// matcher matches any value that's equal to 'value'.
2418template <typename T>
2419Matcher<T>::Matcher(T value) { *this = Eq(value); }
2420
2421// Creates a monomorphic matcher that matches anything with type Lhs
2422// and equal to rhs. A user may need to use this instead of Eq(...)
2423// in order to resolve an overloading ambiguity.
2424//
2425// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2426// or Matcher<T>(x), but more readable than the latter.
2427//
2428// We could define similar monomorphic matchers for other comparison
2429// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2430// it yet as those are used much less than Eq() in practice. A user
2431// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2432// for example.
2433template <typename Lhs, typename Rhs>
2434inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2435
2436// Creates a polymorphic matcher that matches anything >= x.
2437template <typename Rhs>
2438inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2439 return internal::GeMatcher<Rhs>(x);
2440}
2441
2442// Creates a polymorphic matcher that matches anything > x.
2443template <typename Rhs>
2444inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2445 return internal::GtMatcher<Rhs>(x);
2446}
2447
2448// Creates a polymorphic matcher that matches anything <= x.
2449template <typename Rhs>
2450inline internal::LeMatcher<Rhs> Le(Rhs x) {
2451 return internal::LeMatcher<Rhs>(x);
2452}
2453
2454// Creates a polymorphic matcher that matches anything < x.
2455template <typename Rhs>
2456inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2457 return internal::LtMatcher<Rhs>(x);
2458}
2459
2460// Creates a polymorphic matcher that matches anything != x.
2461template <typename Rhs>
2462inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2463 return internal::NeMatcher<Rhs>(x);
2464}
2465
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002466// Creates a polymorphic matcher that matches any NULL pointer.
2467inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2468 return MakePolymorphicMatcher(internal::IsNullMatcher());
2469}
2470
shiqiane35fdd92008-12-10 05:08:54 +00002471// Creates a polymorphic matcher that matches any non-NULL pointer.
2472// This is convenient as Not(NULL) doesn't compile (the compiler
2473// thinks that that expression is comparing a pointer with an integer).
2474inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2475 return MakePolymorphicMatcher(internal::NotNullMatcher());
2476}
2477
2478// Creates a polymorphic matcher that matches any argument that
2479// references variable x.
2480template <typename T>
2481inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2482 return internal::RefMatcher<T&>(x);
2483}
2484
2485// Creates a matcher that matches any double argument approximately
2486// equal to rhs, where two NANs are considered unequal.
2487inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2488 return internal::FloatingEqMatcher<double>(rhs, false);
2489}
2490
2491// Creates a matcher that matches any double argument approximately
2492// equal to rhs, including NaN values when rhs is NaN.
2493inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2494 return internal::FloatingEqMatcher<double>(rhs, true);
2495}
2496
2497// Creates a matcher that matches any float argument approximately
2498// equal to rhs, where two NANs are considered unequal.
2499inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2500 return internal::FloatingEqMatcher<float>(rhs, false);
2501}
2502
2503// Creates a matcher that matches any double argument approximately
2504// equal to rhs, including NaN values when rhs is NaN.
2505inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2506 return internal::FloatingEqMatcher<float>(rhs, true);
2507}
2508
2509// Creates a matcher that matches a pointer (raw or smart) that points
2510// to a value that matches inner_matcher.
2511template <typename InnerMatcher>
2512inline internal::PointeeMatcher<InnerMatcher> Pointee(
2513 const InnerMatcher& inner_matcher) {
2514 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2515}
2516
2517// Creates a matcher that matches an object whose given field matches
2518// 'matcher'. For example,
2519// Field(&Foo::number, Ge(5))
2520// matches a Foo object x iff x.number >= 5.
2521template <typename Class, typename FieldType, typename FieldMatcher>
2522inline PolymorphicMatcher<
2523 internal::FieldMatcher<Class, FieldType> > Field(
2524 FieldType Class::*field, const FieldMatcher& matcher) {
2525 return MakePolymorphicMatcher(
2526 internal::FieldMatcher<Class, FieldType>(
2527 field, MatcherCast<const FieldType&>(matcher)));
2528 // The call to MatcherCast() is required for supporting inner
2529 // matchers of compatible types. For example, it allows
2530 // Field(&Foo::bar, m)
2531 // to compile where bar is an int32 and m is a matcher for int64.
2532}
2533
2534// Creates a matcher that matches an object whose given property
2535// matches 'matcher'. For example,
2536// Property(&Foo::str, StartsWith("hi"))
2537// matches a Foo object x iff x.str() starts with "hi".
2538template <typename Class, typename PropertyType, typename PropertyMatcher>
2539inline PolymorphicMatcher<
2540 internal::PropertyMatcher<Class, PropertyType> > Property(
2541 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2542 return MakePolymorphicMatcher(
2543 internal::PropertyMatcher<Class, PropertyType>(
2544 property,
zhanyong.wane0d051e2009-02-19 00:33:37 +00002545 MatcherCast<GMOCK_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002546 // The call to MatcherCast() is required for supporting inner
2547 // matchers of compatible types. For example, it allows
2548 // Property(&Foo::bar, m)
2549 // to compile where bar() returns an int32 and m is a matcher for int64.
2550}
2551
2552// Creates a matcher that matches an object iff the result of applying
2553// a callable to x matches 'matcher'.
2554// For example,
2555// ResultOf(f, StartsWith("hi"))
2556// matches a Foo object x iff f(x) starts with "hi".
2557// callable parameter can be a function, function pointer, or a functor.
2558// Callable has to satisfy the following conditions:
2559// * It is required to keep no state affecting the results of
2560// the calls on it and make no assumptions about how many calls
2561// will be made. Any state it keeps must be protected from the
2562// concurrent access.
2563// * If it is a function object, it has to define type result_type.
2564// We recommend deriving your functor classes from std::unary_function.
2565template <typename Callable, typename ResultOfMatcher>
2566internal::ResultOfMatcher<Callable> ResultOf(
2567 Callable callable, const ResultOfMatcher& matcher) {
2568 return internal::ResultOfMatcher<Callable>(
2569 callable,
2570 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2571 matcher));
2572 // The call to MatcherCast() is required for supporting inner
2573 // matchers of compatible types. For example, it allows
2574 // ResultOf(Function, m)
2575 // to compile where Function() returns an int32 and m is a matcher for int64.
2576}
2577
2578// String matchers.
2579
2580// Matches a string equal to str.
2581inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2582 StrEq(const internal::string& str) {
2583 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2584 str, true, true));
2585}
2586
2587// Matches a string not equal to str.
2588inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2589 StrNe(const internal::string& str) {
2590 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2591 str, false, true));
2592}
2593
2594// Matches a string equal to str, ignoring case.
2595inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2596 StrCaseEq(const internal::string& str) {
2597 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2598 str, true, false));
2599}
2600
2601// Matches a string not equal to str, ignoring case.
2602inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2603 StrCaseNe(const internal::string& str) {
2604 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2605 str, false, false));
2606}
2607
2608// Creates a matcher that matches any string, std::string, or C string
2609// that contains the given substring.
2610inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2611 HasSubstr(const internal::string& substring) {
2612 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
2613 substring));
2614}
2615
2616// Matches a string that starts with 'prefix' (case-sensitive).
2617inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
2618 StartsWith(const internal::string& prefix) {
2619 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
2620 prefix));
2621}
2622
2623// Matches a string that ends with 'suffix' (case-sensitive).
2624inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
2625 EndsWith(const internal::string& suffix) {
2626 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
2627 suffix));
2628}
2629
shiqiane35fdd92008-12-10 05:08:54 +00002630// Matches a string that fully matches regular expression 'regex'.
2631// The matcher takes ownership of 'regex'.
2632inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2633 const internal::RE* regex) {
2634 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2635}
2636inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2637 const internal::string& regex) {
2638 return MatchesRegex(new internal::RE(regex));
2639}
2640
2641// Matches a string that contains regular expression 'regex'.
2642// The matcher takes ownership of 'regex'.
2643inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2644 const internal::RE* regex) {
2645 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2646}
2647inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2648 const internal::string& regex) {
2649 return ContainsRegex(new internal::RE(regex));
2650}
2651
shiqiane35fdd92008-12-10 05:08:54 +00002652#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2653// Wide string matchers.
2654
2655// Matches a string equal to str.
2656inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2657 StrEq(const internal::wstring& str) {
2658 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2659 str, true, true));
2660}
2661
2662// Matches a string not equal to str.
2663inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2664 StrNe(const internal::wstring& str) {
2665 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2666 str, false, true));
2667}
2668
2669// Matches a string equal to str, ignoring case.
2670inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2671 StrCaseEq(const internal::wstring& str) {
2672 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2673 str, true, false));
2674}
2675
2676// Matches a string not equal to str, ignoring case.
2677inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2678 StrCaseNe(const internal::wstring& str) {
2679 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2680 str, false, false));
2681}
2682
2683// Creates a matcher that matches any wstring, std::wstring, or C wide string
2684// that contains the given substring.
2685inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2686 HasSubstr(const internal::wstring& substring) {
2687 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2688 substring));
2689}
2690
2691// Matches a string that starts with 'prefix' (case-sensitive).
2692inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2693 StartsWith(const internal::wstring& prefix) {
2694 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2695 prefix));
2696}
2697
2698// Matches a string that ends with 'suffix' (case-sensitive).
2699inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2700 EndsWith(const internal::wstring& suffix) {
2701 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2702 suffix));
2703}
2704
2705#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2706
2707// Creates a polymorphic matcher that matches a 2-tuple where the
2708// first field == the second field.
2709inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2710
2711// Creates a polymorphic matcher that matches a 2-tuple where the
2712// first field >= the second field.
2713inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2714
2715// Creates a polymorphic matcher that matches a 2-tuple where the
2716// first field > the second field.
2717inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2718
2719// Creates a polymorphic matcher that matches a 2-tuple where the
2720// first field <= the second field.
2721inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2722
2723// Creates a polymorphic matcher that matches a 2-tuple where the
2724// first field < the second field.
2725inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2726
2727// Creates a polymorphic matcher that matches a 2-tuple where the
2728// first field != the second field.
2729inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2730
2731// Creates a matcher that matches any value of type T that m doesn't
2732// match.
2733template <typename InnerMatcher>
2734inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2735 return internal::NotMatcher<InnerMatcher>(m);
2736}
2737
2738// Creates a matcher that matches any value that matches all of the
2739// given matchers.
2740//
2741// For now we only support up to 5 matchers. Support for more
2742// matchers can be added as needed, or the user can use nested
2743// AllOf()s.
2744template <typename Matcher1, typename Matcher2>
2745inline internal::BothOfMatcher<Matcher1, Matcher2>
2746AllOf(Matcher1 m1, Matcher2 m2) {
2747 return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2);
2748}
2749
2750template <typename Matcher1, typename Matcher2, typename Matcher3>
2751inline internal::BothOfMatcher<Matcher1,
2752 internal::BothOfMatcher<Matcher2, Matcher3> >
2753AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2754 return AllOf(m1, AllOf(m2, m3));
2755}
2756
2757template <typename Matcher1, typename Matcher2, typename Matcher3,
2758 typename Matcher4>
2759inline internal::BothOfMatcher<Matcher1,
2760 internal::BothOfMatcher<Matcher2,
2761 internal::BothOfMatcher<Matcher3, Matcher4> > >
2762AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2763 return AllOf(m1, AllOf(m2, m3, m4));
2764}
2765
2766template <typename Matcher1, typename Matcher2, typename Matcher3,
2767 typename Matcher4, typename Matcher5>
2768inline internal::BothOfMatcher<Matcher1,
2769 internal::BothOfMatcher<Matcher2,
2770 internal::BothOfMatcher<Matcher3,
2771 internal::BothOfMatcher<Matcher4, Matcher5> > > >
2772AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2773 return AllOf(m1, AllOf(m2, m3, m4, m5));
2774}
2775
2776// Creates a matcher that matches any value that matches at least one
2777// of the given matchers.
2778//
2779// For now we only support up to 5 matchers. Support for more
2780// matchers can be added as needed, or the user can use nested
2781// AnyOf()s.
2782template <typename Matcher1, typename Matcher2>
2783inline internal::EitherOfMatcher<Matcher1, Matcher2>
2784AnyOf(Matcher1 m1, Matcher2 m2) {
2785 return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2);
2786}
2787
2788template <typename Matcher1, typename Matcher2, typename Matcher3>
2789inline internal::EitherOfMatcher<Matcher1,
2790 internal::EitherOfMatcher<Matcher2, Matcher3> >
2791AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2792 return AnyOf(m1, AnyOf(m2, m3));
2793}
2794
2795template <typename Matcher1, typename Matcher2, typename Matcher3,
2796 typename Matcher4>
2797inline internal::EitherOfMatcher<Matcher1,
2798 internal::EitherOfMatcher<Matcher2,
2799 internal::EitherOfMatcher<Matcher3, Matcher4> > >
2800AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2801 return AnyOf(m1, AnyOf(m2, m3, m4));
2802}
2803
2804template <typename Matcher1, typename Matcher2, typename Matcher3,
2805 typename Matcher4, typename Matcher5>
2806inline internal::EitherOfMatcher<Matcher1,
2807 internal::EitherOfMatcher<Matcher2,
2808 internal::EitherOfMatcher<Matcher3,
2809 internal::EitherOfMatcher<Matcher4, Matcher5> > > >
2810AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2811 return AnyOf(m1, AnyOf(m2, m3, m4, m5));
2812}
2813
2814// Returns a matcher that matches anything that satisfies the given
2815// predicate. The predicate can be any unary function or functor
2816// whose return type can be implicitly converted to bool.
2817template <typename Predicate>
2818inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
2819Truly(Predicate pred) {
2820 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
2821}
2822
zhanyong.wan6a896b52009-01-16 01:13:50 +00002823// Returns a matcher that matches an equal container.
2824// This matcher behaves like Eq(), but in the event of mismatch lists the
2825// values that are included in one container but not the other. (Duplicate
2826// values and order differences are not explained.)
2827template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00002828inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wanb8243162009-06-04 05:48:20 +00002829 GMOCK_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00002830 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002831 // This following line is for working around a bug in MSVC 8.0,
2832 // which causes Container to be a const type sometimes.
2833 typedef GMOCK_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00002834 return MakePolymorphicMatcher(
2835 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00002836}
2837
2838// Matches an STL-style container or a native array that contains at
2839// least one element matching the given value or matcher.
2840//
2841// Examples:
2842// ::std::set<int> page_ids;
2843// page_ids.insert(3);
2844// page_ids.insert(1);
2845// EXPECT_THAT(page_ids, Contains(1));
2846// EXPECT_THAT(page_ids, Contains(Gt(2)));
2847// EXPECT_THAT(page_ids, Not(Contains(4)));
2848//
2849// ::std::map<int, size_t> page_lengths;
2850// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00002851// EXPECT_THAT(page_lengths,
2852// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00002853//
2854// const char* user_ids[] = { "joe", "mike", "tom" };
2855// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
2856template <typename M>
2857inline internal::ContainsMatcher<M> Contains(M matcher) {
2858 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002859}
2860
zhanyong.wanb5937da2009-07-16 20:26:41 +00002861// Key(inner_matcher) matches an std::pair whose 'first' field matches
2862// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2863// std::map that contains at least one element whose key is >= 5.
2864template <typename M>
2865inline internal::KeyMatcher<M> Key(M inner_matcher) {
2866 return internal::KeyMatcher<M>(inner_matcher);
2867}
2868
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002869// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
2870// matches first_matcher and whose 'second' field matches second_matcher. For
2871// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
2872// to match a std::map<int, string> that contains exactly one element whose key
2873// is >= 5 and whose value equals "foo".
2874template <typename FirstMatcher, typename SecondMatcher>
2875inline internal::PairMatcher<FirstMatcher, SecondMatcher>
2876Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
2877 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
2878 first_matcher, second_matcher);
2879}
2880
shiqiane35fdd92008-12-10 05:08:54 +00002881// Returns a predicate that is satisfied by anything that matches the
2882// given matcher.
2883template <typename M>
2884inline internal::MatcherAsPredicate<M> Matches(M matcher) {
2885 return internal::MatcherAsPredicate<M>(matcher);
2886}
2887
zhanyong.wanb8243162009-06-04 05:48:20 +00002888// Returns true iff the value matches the matcher.
2889template <typename T, typename M>
2890inline bool Value(const T& value, M matcher) {
2891 return testing::Matches(matcher)(value);
2892}
2893
zhanyong.wan34b034c2010-03-05 21:23:23 +00002894// Matches the value against the given matcher and explains the match
2895// result to listener.
2896template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00002897inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00002898 M matcher, const T& value, MatchResultListener* listener) {
2899 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
2900}
2901
zhanyong.wanbf550852009-06-09 06:09:53 +00002902// AllArgs(m) is a synonym of m. This is useful in
2903//
2904// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
2905//
2906// which is easier to read than
2907//
2908// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
2909template <typename InnerMatcher>
2910inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
2911
shiqiane35fdd92008-12-10 05:08:54 +00002912// These macros allow using matchers to check values in Google Test
2913// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
2914// succeed iff the value matches the matcher. If the assertion fails,
2915// the value and the description of the matcher will be printed.
2916#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
2917 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2918#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
2919 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2920
2921} // namespace testing
2922
2923#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_