blob: c21fa515f2545144a1c24ad26c3c9c4836b59998 [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>
zhanyong.wanab5b77c2010-05-17 19:32:48 +000046#include <utility>
shiqiane35fdd92008-12-10 05:08:54 +000047#include <vector>
48
zhanyong.wan53e08c42010-09-14 05:38:21 +000049#include "gmock/internal/gmock-internal-utils.h"
50#include "gmock/internal/gmock-port.h"
51#include "gtest/gtest.h"
shiqiane35fdd92008-12-10 05:08:54 +000052
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:
vladlosev88032d82010-11-17 23:29:21 +0000253 // Constructs a null matcher. Needed for storing Matcher objects in STL
254 // containers. A default-constructed matcher is not yet initialized. You
255 // cannot use it until a valid value has been assigned to it.
shiqiane35fdd92008-12-10 05:08:54 +0000256 Matcher() {}
257
258 // Constructs a matcher from its implementation.
259 explicit Matcher(const MatcherInterface<T>* impl)
260 : internal::MatcherBase<T>(impl) {}
261
zhanyong.wan18490652009-05-11 18:54:08 +0000262 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000263 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
264 Matcher(T value); // NOLINT
265};
266
267// The following two specializations allow the user to write str
268// instead of Eq(str) and "foo" instead of Eq("foo") when a string
269// matcher is expected.
270template <>
271class Matcher<const internal::string&>
272 : public internal::MatcherBase<const internal::string&> {
273 public:
274 Matcher() {}
275
276 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
277 : internal::MatcherBase<const internal::string&>(impl) {}
278
279 // Allows the user to write str instead of Eq(str) sometimes, where
280 // str is a string object.
281 Matcher(const internal::string& s); // NOLINT
282
283 // Allows the user to write "foo" instead of Eq("foo") sometimes.
284 Matcher(const char* s); // NOLINT
285};
286
287template <>
288class Matcher<internal::string>
289 : public internal::MatcherBase<internal::string> {
290 public:
291 Matcher() {}
292
293 explicit Matcher(const MatcherInterface<internal::string>* impl)
294 : internal::MatcherBase<internal::string>(impl) {}
295
296 // Allows the user to write str instead of Eq(str) sometimes, where
297 // str is a string object.
298 Matcher(const internal::string& s); // NOLINT
299
300 // Allows the user to write "foo" instead of Eq("foo") sometimes.
301 Matcher(const char* s); // NOLINT
302};
303
304// The PolymorphicMatcher class template makes it easy to implement a
305// polymorphic matcher (i.e. a matcher that can match values of more
306// than one type, e.g. Eq(n) and NotNull()).
307//
zhanyong.wandb22c222010-01-28 21:52:29 +0000308// To define a polymorphic matcher, a user should provide an Impl
309// class that has a DescribeTo() method and a DescribeNegationTo()
310// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000311//
zhanyong.wandb22c222010-01-28 21:52:29 +0000312// bool MatchAndExplain(const Value& value,
313// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000314//
315// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000316template <class Impl>
317class PolymorphicMatcher {
318 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000319 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000320
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000321 // Returns a mutable reference to the underlying matcher
322 // implementation object.
323 Impl& mutable_impl() { return impl_; }
324
325 // Returns an immutable reference to the underlying matcher
326 // implementation object.
327 const Impl& impl() const { return impl_; }
328
shiqiane35fdd92008-12-10 05:08:54 +0000329 template <typename T>
330 operator Matcher<T>() const {
331 return Matcher<T>(new MonomorphicImpl<T>(impl_));
332 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000333
shiqiane35fdd92008-12-10 05:08:54 +0000334 private:
335 template <typename T>
336 class MonomorphicImpl : public MatcherInterface<T> {
337 public:
338 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
339
shiqiane35fdd92008-12-10 05:08:54 +0000340 virtual void DescribeTo(::std::ostream* os) const {
341 impl_.DescribeTo(os);
342 }
343
344 virtual void DescribeNegationTo(::std::ostream* os) const {
345 impl_.DescribeNegationTo(os);
346 }
347
zhanyong.wan82113312010-01-08 21:55:40 +0000348 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000349 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000350 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000351
shiqiane35fdd92008-12-10 05:08:54 +0000352 private:
353 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000354
355 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000356 };
357
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000358 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000359
360 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000361};
362
363// Creates a matcher from its implementation. This is easier to use
364// than the Matcher<T> constructor as it doesn't require you to
365// explicitly write the template argument, e.g.
366//
367// MakeMatcher(foo);
368// vs
369// Matcher<const string&>(foo);
370template <typename T>
371inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
372 return Matcher<T>(impl);
373};
374
375// Creates a polymorphic matcher from its implementation. This is
376// easier to use than the PolymorphicMatcher<Impl> constructor as it
377// doesn't require you to explicitly write the template argument, e.g.
378//
379// MakePolymorphicMatcher(foo);
380// vs
381// PolymorphicMatcher<TypeOfFoo>(foo);
382template <class Impl>
383inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
384 return PolymorphicMatcher<Impl>(impl);
385}
386
387// In order to be safe and clear, casting between different matcher
388// types is done explicitly via MatcherCast<T>(m), which takes a
389// matcher m and returns a Matcher<T>. It compiles only when T can be
390// statically converted to the argument type of m.
391template <typename T, typename M>
392Matcher<T> MatcherCast(M m);
393
zhanyong.wan18490652009-05-11 18:54:08 +0000394// Implements SafeMatcherCast().
395//
zhanyong.wan95b12332009-09-25 18:55:50 +0000396// We use an intermediate class to do the actual safe casting as Nokia's
397// Symbian compiler cannot decide between
398// template <T, M> ... (M) and
399// template <T, U> ... (const Matcher<U>&)
400// for function templates but can for member function templates.
401template <typename T>
402class SafeMatcherCastImpl {
403 public:
404 // This overload handles polymorphic matchers only since monomorphic
405 // matchers are handled by the next one.
406 template <typename M>
407 static inline Matcher<T> Cast(M polymorphic_matcher) {
408 return Matcher<T>(polymorphic_matcher);
409 }
zhanyong.wan18490652009-05-11 18:54:08 +0000410
zhanyong.wan95b12332009-09-25 18:55:50 +0000411 // This overload handles monomorphic matchers.
412 //
413 // In general, if type T can be implicitly converted to type U, we can
414 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
415 // contravariant): just keep a copy of the original Matcher<U>, convert the
416 // argument from type T to U, and then pass it to the underlying Matcher<U>.
417 // The only exception is when U is a reference and T is not, as the
418 // underlying Matcher<U> may be interested in the argument's address, which
419 // is not preserved in the conversion from T to U.
420 template <typename U>
421 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
422 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000423 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000424 T_must_be_implicitly_convertible_to_U);
425 // Enforce that we are not converting a non-reference type T to a reference
426 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000427 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000428 internal::is_reference<T>::value || !internal::is_reference<U>::value,
429 cannot_convert_non_referentce_arg_to_reference);
430 // In case both T and U are arithmetic types, enforce that the
431 // conversion is not lossy.
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000432 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
433 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000434 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
435 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000436 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000437 kTIsOther || kUIsOther ||
438 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
439 conversion_of_arithmetic_types_must_be_lossless);
440 return MatcherCast<T>(matcher);
441 }
442};
443
444template <typename T, typename M>
445inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
446 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000447}
448
shiqiane35fdd92008-12-10 05:08:54 +0000449// A<T>() returns a matcher that matches any value of type T.
450template <typename T>
451Matcher<T> A();
452
453// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
454// and MUST NOT BE USED IN USER CODE!!!
455namespace internal {
456
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000457// If the explanation is not empty, prints it to the ostream.
458inline void PrintIfNotEmpty(const internal::string& explanation,
459 std::ostream* os) {
460 if (explanation != "" && os != NULL) {
461 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000462 }
463}
464
zhanyong.wan736baa82010-09-27 17:44:16 +0000465// Returns true if the given type name is easy to read by a human.
466// This is used to decide whether printing the type of a value might
467// be helpful.
468inline bool IsReadableTypeName(const string& type_name) {
469 // We consider a type name readable if it's short or doesn't contain
470 // a template or function type.
471 return (type_name.length() <= 20 ||
472 type_name.find_first_of("<(") == string::npos);
473}
474
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000475// Matches the value against the given matcher, prints the value and explains
476// the match result to the listener. Returns the match result.
477// 'listener' must not be NULL.
478// Value cannot be passed by const reference, because some matchers take a
479// non-const argument.
480template <typename Value, typename T>
481bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
482 MatchResultListener* listener) {
483 if (!listener->IsInterested()) {
484 // If the listener is not interested, we do not need to construct the
485 // inner explanation.
486 return matcher.Matches(value);
487 }
488
489 StringMatchResultListener inner_listener;
490 const bool match = matcher.MatchAndExplain(value, &inner_listener);
491
492 UniversalPrint(value, listener->stream());
zhanyong.wan736baa82010-09-27 17:44:16 +0000493#if GTEST_HAS_RTTI
494 const string& type_name = GetTypeName<Value>();
495 if (IsReadableTypeName(type_name))
496 *listener->stream() << " (of type " << type_name << ")";
497#endif
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000498 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000499
500 return match;
501}
502
shiqiane35fdd92008-12-10 05:08:54 +0000503// An internal helper class for doing compile-time loop on a tuple's
504// fields.
505template <size_t N>
506class TuplePrefix {
507 public:
508 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
509 // iff the first N fields of matcher_tuple matches the first N
510 // fields of value_tuple, respectively.
511 template <typename MatcherTuple, typename ValueTuple>
512 static bool Matches(const MatcherTuple& matcher_tuple,
513 const ValueTuple& value_tuple) {
514 using ::std::tr1::get;
515 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
516 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
517 }
518
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000519 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000520 // describes failures in matching the first N fields of matchers
521 // against the first N fields of values. If there is no failure,
522 // nothing will be streamed to os.
523 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000524 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
525 const ValueTuple& values,
526 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000527 using ::std::tr1::tuple_element;
528 using ::std::tr1::get;
529
530 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000531 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000532
533 // Then describes the failure (if any) in the (N - 1)-th (0-based)
534 // field.
535 typename tuple_element<N - 1, MatcherTuple>::type matcher =
536 get<N - 1>(matchers);
537 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
538 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000539 StringMatchResultListener listener;
540 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000541 // TODO(wan): include in the message the name of the parameter
542 // as used in MOCK_METHOD*() when possible.
543 *os << " Expected arg #" << N - 1 << ": ";
544 get<N - 1>(matchers).DescribeTo(os);
545 *os << "\n Actual: ";
546 // We remove the reference in type Value to prevent the
547 // universal printer from printing the address of value, which
548 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000549 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000550 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000551 internal::UniversalPrint(value, os);
552 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000553 *os << "\n";
554 }
555 }
556};
557
558// The base case.
559template <>
560class TuplePrefix<0> {
561 public:
562 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000563 static bool Matches(const MatcherTuple& /* matcher_tuple */,
564 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000565 return true;
566 }
567
568 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000569 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
570 const ValueTuple& /* values */,
571 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000572};
573
574// TupleMatches(matcher_tuple, value_tuple) returns true iff all
575// matchers in matcher_tuple match the corresponding fields in
576// value_tuple. It is a compiler error if matcher_tuple and
577// value_tuple have different number of fields or incompatible field
578// types.
579template <typename MatcherTuple, typename ValueTuple>
580bool TupleMatches(const MatcherTuple& matcher_tuple,
581 const ValueTuple& value_tuple) {
582 using ::std::tr1::tuple_size;
583 // Makes sure that matcher_tuple and value_tuple have the same
584 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000585 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000586 tuple_size<ValueTuple>::value,
587 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000588 return TuplePrefix<tuple_size<ValueTuple>::value>::
589 Matches(matcher_tuple, value_tuple);
590}
591
592// Describes failures in matching matchers against values. If there
593// is no failure, nothing will be streamed to os.
594template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000595void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
596 const ValueTuple& values,
597 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000598 using ::std::tr1::tuple_size;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000599 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000600 matchers, values, os);
601}
602
603// The MatcherCastImpl class template is a helper for implementing
604// MatcherCast(). We need this helper in order to partially
605// specialize the implementation of MatcherCast() (C++ allows
606// class/struct templates to be partially specialized, but not
607// function templates.).
608
609// This general version is used when MatcherCast()'s argument is a
610// polymorphic matcher (i.e. something that can be converted to a
611// Matcher but is not one yet; for example, Eq(value)).
612template <typename T, typename M>
613class MatcherCastImpl {
614 public:
615 static Matcher<T> Cast(M polymorphic_matcher) {
616 return Matcher<T>(polymorphic_matcher);
617 }
618};
619
620// This more specialized version is used when MatcherCast()'s argument
621// is already a Matcher. This only compiles when type T can be
622// statically converted to type U.
623template <typename T, typename U>
624class MatcherCastImpl<T, Matcher<U> > {
625 public:
626 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
627 return Matcher<T>(new Impl(source_matcher));
628 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000629
shiqiane35fdd92008-12-10 05:08:54 +0000630 private:
631 class Impl : public MatcherInterface<T> {
632 public:
633 explicit Impl(const Matcher<U>& source_matcher)
634 : source_matcher_(source_matcher) {}
635
636 // We delegate the matching logic to the source matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000637 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
638 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000639 }
640
641 virtual void DescribeTo(::std::ostream* os) const {
642 source_matcher_.DescribeTo(os);
643 }
644
645 virtual void DescribeNegationTo(::std::ostream* os) const {
646 source_matcher_.DescribeNegationTo(os);
647 }
648
shiqiane35fdd92008-12-10 05:08:54 +0000649 private:
650 const Matcher<U> source_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000651
652 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000653 };
654};
655
656// This even more specialized version is used for efficiently casting
657// a matcher to its own type.
658template <typename T>
659class MatcherCastImpl<T, Matcher<T> > {
660 public:
661 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
662};
663
664// Implements A<T>().
665template <typename T>
666class AnyMatcherImpl : public MatcherInterface<T> {
667 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000668 virtual bool MatchAndExplain(
669 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000670 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
671 virtual void DescribeNegationTo(::std::ostream* os) const {
672 // This is mostly for completeness' safe, as it's not very useful
673 // to write Not(A<bool>()). However we cannot completely rule out
674 // such a possibility, and it doesn't hurt to be prepared.
675 *os << "never matches";
676 }
677};
678
679// Implements _, a matcher that matches any value of any
680// type. This is a polymorphic matcher, so we need a template type
681// conversion operator to make it appearing as a Matcher<T> for any
682// type T.
683class AnythingMatcher {
684 public:
685 template <typename T>
686 operator Matcher<T>() const { return A<T>(); }
687};
688
689// Implements a matcher that compares a given value with a
690// pre-supplied value using one of the ==, <=, <, etc, operators. The
691// two values being compared don't have to have the same type.
692//
693// The matcher defined here is polymorphic (for example, Eq(5) can be
694// used to match an int, a short, a double, etc). Therefore we use
695// a template type conversion operator in the implementation.
696//
697// We define this as a macro in order to eliminate duplicated source
698// code.
699//
700// The following template definition assumes that the Rhs parameter is
701// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000702#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_( \
703 name, op, relation, negated_relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000704 template <typename Rhs> class name##Matcher { \
705 public: \
706 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
707 template <typename Lhs> \
708 operator Matcher<Lhs>() const { \
709 return MakeMatcher(new Impl<Lhs>(rhs_)); \
710 } \
711 private: \
712 template <typename Lhs> \
713 class Impl : public MatcherInterface<Lhs> { \
714 public: \
715 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
zhanyong.wan82113312010-01-08 21:55:40 +0000716 virtual bool MatchAndExplain(\
717 Lhs lhs, MatchResultListener* /* listener */) const { \
718 return lhs op rhs_; \
719 } \
shiqiane35fdd92008-12-10 05:08:54 +0000720 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000721 *os << relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000722 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000723 } \
724 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000725 *os << negated_relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000726 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000727 } \
728 private: \
729 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000730 GTEST_DISALLOW_ASSIGN_(Impl); \
shiqiane35fdd92008-12-10 05:08:54 +0000731 }; \
732 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000733 GTEST_DISALLOW_ASSIGN_(name##Matcher); \
shiqiane35fdd92008-12-10 05:08:54 +0000734 }
735
736// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
737// respectively.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000738GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "is equal to", "isn't equal to");
739GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "is >=", "isn't >=");
740GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "is >", "isn't >");
741GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "is <=", "isn't <=");
742GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "is <", "isn't <");
743GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "isn't equal to", "is equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000744
zhanyong.wane0d051e2009-02-19 00:33:37 +0000745#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000746
vladlosev79b83502009-11-18 00:43:37 +0000747// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000748// pointer that is NULL.
749class IsNullMatcher {
750 public:
vladlosev79b83502009-11-18 00:43:37 +0000751 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000752 bool MatchAndExplain(const Pointer& p,
753 MatchResultListener* /* listener */) const {
754 return GetRawPointer(p) == NULL;
755 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000756
757 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
758 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000759 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000760 }
761};
762
vladlosev79b83502009-11-18 00:43:37 +0000763// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000764// pointer that is not NULL.
765class NotNullMatcher {
766 public:
vladlosev79b83502009-11-18 00:43:37 +0000767 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000768 bool MatchAndExplain(const Pointer& p,
769 MatchResultListener* /* listener */) const {
770 return GetRawPointer(p) != NULL;
771 }
shiqiane35fdd92008-12-10 05:08:54 +0000772
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000773 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +0000774 void DescribeNegationTo(::std::ostream* os) const {
775 *os << "is NULL";
776 }
777};
778
779// Ref(variable) matches any argument that is a reference to
780// 'variable'. This matcher is polymorphic as it can match any
781// super type of the type of 'variable'.
782//
783// The RefMatcher template class implements Ref(variable). It can
784// only be instantiated with a reference type. This prevents a user
785// from mistakenly using Ref(x) to match a non-reference function
786// argument. For example, the following will righteously cause a
787// compiler error:
788//
789// int n;
790// Matcher<int> m1 = Ref(n); // This won't compile.
791// Matcher<int&> m2 = Ref(n); // This will compile.
792template <typename T>
793class RefMatcher;
794
795template <typename T>
796class RefMatcher<T&> {
797 // Google Mock is a generic framework and thus needs to support
798 // mocking any function types, including those that take non-const
799 // reference arguments. Therefore the template parameter T (and
800 // Super below) can be instantiated to either a const type or a
801 // non-const type.
802 public:
803 // RefMatcher() takes a T& instead of const T&, as we want the
804 // compiler to catch using Ref(const_value) as a matcher for a
805 // non-const reference.
806 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
807
808 template <typename Super>
809 operator Matcher<Super&>() const {
810 // By passing object_ (type T&) to Impl(), which expects a Super&,
811 // we make sure that Super is a super type of T. In particular,
812 // this catches using Ref(const_value) as a matcher for a
813 // non-const reference, as you cannot implicitly convert a const
814 // reference to a non-const reference.
815 return MakeMatcher(new Impl<Super>(object_));
816 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000817
shiqiane35fdd92008-12-10 05:08:54 +0000818 private:
819 template <typename Super>
820 class Impl : public MatcherInterface<Super&> {
821 public:
822 explicit Impl(Super& x) : object_(x) {} // NOLINT
823
zhanyong.wandb22c222010-01-28 21:52:29 +0000824 // MatchAndExplain() takes a Super& (as opposed to const Super&)
825 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +0000826 virtual bool MatchAndExplain(
827 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000828 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +0000829 return &x == &object_;
830 }
shiqiane35fdd92008-12-10 05:08:54 +0000831
832 virtual void DescribeTo(::std::ostream* os) const {
833 *os << "references the variable ";
834 UniversalPrinter<Super&>::Print(object_, os);
835 }
836
837 virtual void DescribeNegationTo(::std::ostream* os) const {
838 *os << "does not reference the variable ";
839 UniversalPrinter<Super&>::Print(object_, os);
840 }
841
shiqiane35fdd92008-12-10 05:08:54 +0000842 private:
843 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000844
845 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000846 };
847
848 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000849
850 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000851};
852
853// Polymorphic helper functions for narrow and wide string matchers.
854inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
855 return String::CaseInsensitiveCStringEquals(lhs, rhs);
856}
857
858inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
859 const wchar_t* rhs) {
860 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
861}
862
863// String comparison for narrow or wide strings that can have embedded NUL
864// characters.
865template <typename StringType>
866bool CaseInsensitiveStringEquals(const StringType& s1,
867 const StringType& s2) {
868 // Are the heads equal?
869 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
870 return false;
871 }
872
873 // Skip the equal heads.
874 const typename StringType::value_type nul = 0;
875 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
876
877 // Are we at the end of either s1 or s2?
878 if (i1 == StringType::npos || i2 == StringType::npos) {
879 return i1 == i2;
880 }
881
882 // Are the tails equal?
883 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
884}
885
886// String matchers.
887
888// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
889template <typename StringType>
890class StrEqualityMatcher {
891 public:
892 typedef typename StringType::const_pointer ConstCharPointer;
893
894 StrEqualityMatcher(const StringType& str, bool expect_eq,
895 bool case_sensitive)
896 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
897
898 // When expect_eq_ is true, returns true iff s is equal to string_;
899 // otherwise returns true iff s is not equal to string_.
zhanyong.wandb22c222010-01-28 21:52:29 +0000900 bool MatchAndExplain(ConstCharPointer s,
901 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +0000902 if (s == NULL) {
903 return !expect_eq_;
904 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000905 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000906 }
907
zhanyong.wandb22c222010-01-28 21:52:29 +0000908 bool MatchAndExplain(const StringType& s,
909 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000910 const bool eq = case_sensitive_ ? s == string_ :
911 CaseInsensitiveStringEquals(s, string_);
912 return expect_eq_ == eq;
913 }
914
915 void DescribeTo(::std::ostream* os) const {
916 DescribeToHelper(expect_eq_, os);
917 }
918
919 void DescribeNegationTo(::std::ostream* os) const {
920 DescribeToHelper(!expect_eq_, os);
921 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000922
shiqiane35fdd92008-12-10 05:08:54 +0000923 private:
924 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000925 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +0000926 *os << "equal to ";
927 if (!case_sensitive_) {
928 *os << "(ignoring case) ";
929 }
vladloseve2e8ba42010-05-13 18:16:03 +0000930 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +0000931 }
932
933 const StringType string_;
934 const bool expect_eq_;
935 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000936
937 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000938};
939
940// Implements the polymorphic HasSubstr(substring) matcher, which
941// can be used as a Matcher<T> as long as T can be converted to a
942// string.
943template <typename StringType>
944class HasSubstrMatcher {
945 public:
946 typedef typename StringType::const_pointer ConstCharPointer;
947
948 explicit HasSubstrMatcher(const StringType& substring)
949 : substring_(substring) {}
950
951 // These overloaded methods allow HasSubstr(substring) to be used as a
952 // Matcher<T> as long as T can be converted to string. Returns true
953 // iff s contains substring_ as a substring.
zhanyong.wandb22c222010-01-28 21:52:29 +0000954 bool MatchAndExplain(ConstCharPointer s,
955 MatchResultListener* listener) const {
956 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000957 }
958
zhanyong.wandb22c222010-01-28 21:52:29 +0000959 bool MatchAndExplain(const StringType& s,
960 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000961 return s.find(substring_) != StringType::npos;
962 }
963
964 // Describes what this matcher matches.
965 void DescribeTo(::std::ostream* os) const {
966 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +0000967 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +0000968 }
969
970 void DescribeNegationTo(::std::ostream* os) const {
971 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +0000972 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +0000973 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000974
shiqiane35fdd92008-12-10 05:08:54 +0000975 private:
976 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000977
978 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000979};
980
981// Implements the polymorphic StartsWith(substring) matcher, which
982// can be used as a Matcher<T> as long as T can be converted to a
983// string.
984template <typename StringType>
985class StartsWithMatcher {
986 public:
987 typedef typename StringType::const_pointer ConstCharPointer;
988
989 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
990 }
991
992 // These overloaded methods allow StartsWith(prefix) to be used as a
993 // Matcher<T> as long as T can be converted to string. Returns true
994 // iff s starts with prefix_.
zhanyong.wandb22c222010-01-28 21:52:29 +0000995 bool MatchAndExplain(ConstCharPointer s,
996 MatchResultListener* listener) const {
997 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000998 }
999
zhanyong.wandb22c222010-01-28 21:52:29 +00001000 bool MatchAndExplain(const StringType& s,
1001 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001002 return s.length() >= prefix_.length() &&
1003 s.substr(0, prefix_.length()) == prefix_;
1004 }
1005
1006 void DescribeTo(::std::ostream* os) const {
1007 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001008 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001009 }
1010
1011 void DescribeNegationTo(::std::ostream* os) const {
1012 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001013 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001014 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001015
shiqiane35fdd92008-12-10 05:08:54 +00001016 private:
1017 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001018
1019 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001020};
1021
1022// Implements the polymorphic EndsWith(substring) matcher, which
1023// can be used as a Matcher<T> as long as T can be converted to a
1024// string.
1025template <typename StringType>
1026class EndsWithMatcher {
1027 public:
1028 typedef typename StringType::const_pointer ConstCharPointer;
1029
1030 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1031
1032 // These overloaded methods allow EndsWith(suffix) to be used as a
1033 // Matcher<T> as long as T can be converted to string. Returns true
1034 // iff s ends with suffix_.
zhanyong.wandb22c222010-01-28 21:52:29 +00001035 bool MatchAndExplain(ConstCharPointer s,
1036 MatchResultListener* listener) const {
1037 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001038 }
1039
zhanyong.wandb22c222010-01-28 21:52:29 +00001040 bool MatchAndExplain(const StringType& s,
1041 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001042 return s.length() >= suffix_.length() &&
1043 s.substr(s.length() - suffix_.length()) == suffix_;
1044 }
1045
1046 void DescribeTo(::std::ostream* os) const {
1047 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001048 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001049 }
1050
1051 void DescribeNegationTo(::std::ostream* os) const {
1052 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001053 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001054 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001055
shiqiane35fdd92008-12-10 05:08:54 +00001056 private:
1057 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001058
1059 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001060};
1061
shiqiane35fdd92008-12-10 05:08:54 +00001062// Implements polymorphic matchers MatchesRegex(regex) and
1063// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1064// T can be converted to a string.
1065class MatchesRegexMatcher {
1066 public:
1067 MatchesRegexMatcher(const RE* regex, bool full_match)
1068 : regex_(regex), full_match_(full_match) {}
1069
1070 // These overloaded methods allow MatchesRegex(regex) to be used as
1071 // a Matcher<T> as long as T can be converted to string. Returns
1072 // true iff s matches regular expression regex. When full_match_ is
1073 // true, a full match is done; otherwise a partial match is done.
zhanyong.wandb22c222010-01-28 21:52:29 +00001074 bool MatchAndExplain(const char* s,
1075 MatchResultListener* listener) const {
1076 return s != NULL && MatchAndExplain(internal::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001077 }
1078
zhanyong.wandb22c222010-01-28 21:52:29 +00001079 bool MatchAndExplain(const internal::string& s,
1080 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001081 return full_match_ ? RE::FullMatch(s, *regex_) :
1082 RE::PartialMatch(s, *regex_);
1083 }
1084
1085 void DescribeTo(::std::ostream* os) const {
1086 *os << (full_match_ ? "matches" : "contains")
1087 << " regular expression ";
1088 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1089 }
1090
1091 void DescribeNegationTo(::std::ostream* os) const {
1092 *os << "doesn't " << (full_match_ ? "match" : "contain")
1093 << " regular expression ";
1094 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1095 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001096
shiqiane35fdd92008-12-10 05:08:54 +00001097 private:
1098 const internal::linked_ptr<const RE> regex_;
1099 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001100
1101 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001102};
1103
shiqiane35fdd92008-12-10 05:08:54 +00001104// Implements a matcher that compares the two fields of a 2-tuple
1105// using one of the ==, <=, <, etc, operators. The two fields being
1106// compared don't have to have the same type.
1107//
1108// The matcher defined here is polymorphic (for example, Eq() can be
1109// used to match a tuple<int, short>, a tuple<const long&, double>,
1110// etc). Therefore we use a template type conversion operator in the
1111// implementation.
1112//
1113// We define this as a macro in order to eliminate duplicated source
1114// code.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001115#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +00001116 class name##2Matcher { \
1117 public: \
1118 template <typename T1, typename T2> \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001119 operator Matcher< ::std::tr1::tuple<T1, T2> >() const { \
1120 return MakeMatcher(new Impl< ::std::tr1::tuple<T1, T2> >); \
1121 } \
1122 template <typename T1, typename T2> \
shiqiane35fdd92008-12-10 05:08:54 +00001123 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001124 return MakeMatcher(new Impl<const ::std::tr1::tuple<T1, T2>&>); \
shiqiane35fdd92008-12-10 05:08:54 +00001125 } \
1126 private: \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001127 template <typename Tuple> \
1128 class Impl : public MatcherInterface<Tuple> { \
shiqiane35fdd92008-12-10 05:08:54 +00001129 public: \
zhanyong.wan82113312010-01-08 21:55:40 +00001130 virtual bool MatchAndExplain( \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001131 Tuple args, \
zhanyong.wan82113312010-01-08 21:55:40 +00001132 MatchResultListener* /* listener */) const { \
shiqiane35fdd92008-12-10 05:08:54 +00001133 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
1134 } \
1135 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001136 *os << "are " relation; \
shiqiane35fdd92008-12-10 05:08:54 +00001137 } \
1138 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001139 *os << "aren't " relation; \
shiqiane35fdd92008-12-10 05:08:54 +00001140 } \
1141 }; \
1142 }
1143
1144// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001145GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "an equal pair");
1146GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1147 Ge, >=, "a pair where the first >= the second");
1148GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1149 Gt, >, "a pair where the first > the second");
1150GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1151 Le, <=, "a pair where the first <= the second");
1152GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
1153 Lt, <, "a pair where the first < the second");
1154GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=, "an unequal pair");
shiqiane35fdd92008-12-10 05:08:54 +00001155
zhanyong.wane0d051e2009-02-19 00:33:37 +00001156#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +00001157
zhanyong.wanc6a41232009-05-13 23:38:40 +00001158// Implements the Not(...) matcher for a particular argument type T.
1159// We do not nest it inside the NotMatcher class template, as that
1160// will prevent different instantiations of NotMatcher from sharing
1161// the same NotMatcherImpl<T> class.
1162template <typename T>
1163class NotMatcherImpl : public MatcherInterface<T> {
1164 public:
1165 explicit NotMatcherImpl(const Matcher<T>& matcher)
1166 : matcher_(matcher) {}
1167
zhanyong.wan82113312010-01-08 21:55:40 +00001168 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1169 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001170 }
1171
1172 virtual void DescribeTo(::std::ostream* os) const {
1173 matcher_.DescribeNegationTo(os);
1174 }
1175
1176 virtual void DescribeNegationTo(::std::ostream* os) const {
1177 matcher_.DescribeTo(os);
1178 }
1179
zhanyong.wanc6a41232009-05-13 23:38:40 +00001180 private:
1181 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001182
1183 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001184};
1185
shiqiane35fdd92008-12-10 05:08:54 +00001186// Implements the Not(m) matcher, which matches a value that doesn't
1187// match matcher m.
1188template <typename InnerMatcher>
1189class NotMatcher {
1190 public:
1191 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1192
1193 // This template type conversion operator allows Not(m) to be used
1194 // to match any type m can match.
1195 template <typename T>
1196 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001197 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001198 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001199
shiqiane35fdd92008-12-10 05:08:54 +00001200 private:
shiqiane35fdd92008-12-10 05:08:54 +00001201 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001202
1203 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001204};
1205
zhanyong.wanc6a41232009-05-13 23:38:40 +00001206// Implements the AllOf(m1, m2) matcher for a particular argument type
1207// T. We do not nest it inside the BothOfMatcher class template, as
1208// that will prevent different instantiations of BothOfMatcher from
1209// sharing the same BothOfMatcherImpl<T> class.
1210template <typename T>
1211class BothOfMatcherImpl : public MatcherInterface<T> {
1212 public:
1213 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1214 : matcher1_(matcher1), matcher2_(matcher2) {}
1215
zhanyong.wanc6a41232009-05-13 23:38:40 +00001216 virtual void DescribeTo(::std::ostream* os) const {
1217 *os << "(";
1218 matcher1_.DescribeTo(os);
1219 *os << ") and (";
1220 matcher2_.DescribeTo(os);
1221 *os << ")";
1222 }
1223
1224 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001225 *os << "(";
1226 matcher1_.DescribeNegationTo(os);
1227 *os << ") or (";
1228 matcher2_.DescribeNegationTo(os);
1229 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001230 }
1231
zhanyong.wan82113312010-01-08 21:55:40 +00001232 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1233 // If either matcher1_ or matcher2_ doesn't match x, we only need
1234 // to explain why one of them fails.
1235 StringMatchResultListener listener1;
1236 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1237 *listener << listener1.str();
1238 return false;
1239 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001240
zhanyong.wan82113312010-01-08 21:55:40 +00001241 StringMatchResultListener listener2;
1242 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1243 *listener << listener2.str();
1244 return false;
1245 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001246
zhanyong.wan82113312010-01-08 21:55:40 +00001247 // Otherwise we need to explain why *both* of them match.
1248 const internal::string s1 = listener1.str();
1249 const internal::string s2 = listener2.str();
1250
1251 if (s1 == "") {
1252 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001253 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001254 *listener << s1;
1255 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001256 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001257 }
1258 }
zhanyong.wan82113312010-01-08 21:55:40 +00001259 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001260 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001261
zhanyong.wanc6a41232009-05-13 23:38:40 +00001262 private:
1263 const Matcher<T> matcher1_;
1264 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001265
1266 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001267};
1268
shiqiane35fdd92008-12-10 05:08:54 +00001269// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1270// matches a value that matches all of the matchers m_1, ..., and m_n.
1271template <typename Matcher1, typename Matcher2>
1272class BothOfMatcher {
1273 public:
1274 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1275 : matcher1_(matcher1), matcher2_(matcher2) {}
1276
1277 // This template type conversion operator allows a
1278 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1279 // both Matcher1 and Matcher2 can match.
1280 template <typename T>
1281 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001282 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1283 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001284 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001285
shiqiane35fdd92008-12-10 05:08:54 +00001286 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001287 Matcher1 matcher1_;
1288 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001289
1290 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001291};
shiqiane35fdd92008-12-10 05:08:54 +00001292
zhanyong.wanc6a41232009-05-13 23:38:40 +00001293// Implements the AnyOf(m1, m2) matcher for a particular argument type
1294// T. We do not nest it inside the AnyOfMatcher class template, as
1295// that will prevent different instantiations of AnyOfMatcher from
1296// sharing the same EitherOfMatcherImpl<T> class.
1297template <typename T>
1298class EitherOfMatcherImpl : public MatcherInterface<T> {
1299 public:
1300 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1301 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001302
zhanyong.wanc6a41232009-05-13 23:38:40 +00001303 virtual void DescribeTo(::std::ostream* os) const {
1304 *os << "(";
1305 matcher1_.DescribeTo(os);
1306 *os << ") or (";
1307 matcher2_.DescribeTo(os);
1308 *os << ")";
1309 }
shiqiane35fdd92008-12-10 05:08:54 +00001310
zhanyong.wanc6a41232009-05-13 23:38:40 +00001311 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001312 *os << "(";
1313 matcher1_.DescribeNegationTo(os);
1314 *os << ") and (";
1315 matcher2_.DescribeNegationTo(os);
1316 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001317 }
shiqiane35fdd92008-12-10 05:08:54 +00001318
zhanyong.wan82113312010-01-08 21:55:40 +00001319 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1320 // If either matcher1_ or matcher2_ matches x, we just need to
1321 // explain why *one* of them matches.
1322 StringMatchResultListener listener1;
1323 if (matcher1_.MatchAndExplain(x, &listener1)) {
1324 *listener << listener1.str();
1325 return true;
1326 }
1327
1328 StringMatchResultListener listener2;
1329 if (matcher2_.MatchAndExplain(x, &listener2)) {
1330 *listener << listener2.str();
1331 return true;
1332 }
1333
1334 // Otherwise we need to explain why *both* of them fail.
1335 const internal::string s1 = listener1.str();
1336 const internal::string s2 = listener2.str();
1337
1338 if (s1 == "") {
1339 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001340 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001341 *listener << s1;
1342 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001343 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001344 }
1345 }
zhanyong.wan82113312010-01-08 21:55:40 +00001346 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001347 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001348
zhanyong.wanc6a41232009-05-13 23:38:40 +00001349 private:
1350 const Matcher<T> matcher1_;
1351 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001352
1353 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001354};
1355
1356// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1357// matches a value that matches at least one of the matchers m_1, ...,
1358// and m_n.
1359template <typename Matcher1, typename Matcher2>
1360class EitherOfMatcher {
1361 public:
1362 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1363 : matcher1_(matcher1), matcher2_(matcher2) {}
1364
1365 // This template type conversion operator allows a
1366 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1367 // both Matcher1 and Matcher2 can match.
1368 template <typename T>
1369 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001370 return Matcher<T>(new EitherOfMatcherImpl<T>(
1371 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001372 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001373
shiqiane35fdd92008-12-10 05:08:54 +00001374 private:
shiqiane35fdd92008-12-10 05:08:54 +00001375 Matcher1 matcher1_;
1376 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001377
1378 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001379};
1380
1381// Used for implementing Truly(pred), which turns a predicate into a
1382// matcher.
1383template <typename Predicate>
1384class TrulyMatcher {
1385 public:
1386 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1387
1388 // This method template allows Truly(pred) to be used as a matcher
1389 // for type T where T is the argument type of predicate 'pred'. The
1390 // argument is passed by reference as the predicate may be
1391 // interested in the address of the argument.
1392 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001393 bool MatchAndExplain(T& x, // NOLINT
1394 MatchResultListener* /* listener */) const {
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00001395 // Without the if-statement, MSVC sometimes warns about converting
1396 // a value to bool (warning 4800).
1397 //
1398 // We cannot write 'return !!predicate_(x);' as that doesn't work
1399 // when predicate_(x) returns a class convertible to bool but
1400 // having no operator!().
1401 if (predicate_(x))
1402 return true;
1403 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001404 }
1405
1406 void DescribeTo(::std::ostream* os) const {
1407 *os << "satisfies the given predicate";
1408 }
1409
1410 void DescribeNegationTo(::std::ostream* os) const {
1411 *os << "doesn't satisfy the given predicate";
1412 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001413
shiqiane35fdd92008-12-10 05:08:54 +00001414 private:
1415 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001416
1417 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001418};
1419
1420// Used for implementing Matches(matcher), which turns a matcher into
1421// a predicate.
1422template <typename M>
1423class MatcherAsPredicate {
1424 public:
1425 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1426
1427 // This template operator() allows Matches(m) to be used as a
1428 // predicate on type T where m is a matcher on type T.
1429 //
1430 // The argument x is passed by reference instead of by value, as
1431 // some matcher may be interested in its address (e.g. as in
1432 // Matches(Ref(n))(x)).
1433 template <typename T>
1434 bool operator()(const T& x) const {
1435 // We let matcher_ commit to a particular type here instead of
1436 // when the MatcherAsPredicate object was constructed. This
1437 // allows us to write Matches(m) where m is a polymorphic matcher
1438 // (e.g. Eq(5)).
1439 //
1440 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1441 // compile when matcher_ has type Matcher<const T&>; if we write
1442 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1443 // when matcher_ has type Matcher<T>; if we just write
1444 // matcher_.Matches(x), it won't compile when matcher_ is
1445 // polymorphic, e.g. Eq(5).
1446 //
1447 // MatcherCast<const T&>() is necessary for making the code work
1448 // in all of the above situations.
1449 return MatcherCast<const T&>(matcher_).Matches(x);
1450 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001451
shiqiane35fdd92008-12-10 05:08:54 +00001452 private:
1453 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001454
1455 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001456};
1457
1458// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1459// argument M must be a type that can be converted to a matcher.
1460template <typename M>
1461class PredicateFormatterFromMatcher {
1462 public:
1463 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1464
1465 // This template () operator allows a PredicateFormatterFromMatcher
1466 // object to act as a predicate-formatter suitable for using with
1467 // Google Test's EXPECT_PRED_FORMAT1() macro.
1468 template <typename T>
1469 AssertionResult operator()(const char* value_text, const T& x) const {
1470 // We convert matcher_ to a Matcher<const T&> *now* instead of
1471 // when the PredicateFormatterFromMatcher object was constructed,
1472 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1473 // know which type to instantiate it to until we actually see the
1474 // type of x here.
1475 //
1476 // We write MatcherCast<const T&>(matcher_) instead of
1477 // Matcher<const T&>(matcher_), as the latter won't compile when
1478 // matcher_ has type Matcher<T> (e.g. An<int>()).
1479 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001480 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001481 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001482 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001483
1484 ::std::stringstream ss;
1485 ss << "Value of: " << value_text << "\n"
1486 << "Expected: ";
1487 matcher.DescribeTo(&ss);
1488 ss << "\n Actual: " << listener.str();
1489 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001490 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001491
shiqiane35fdd92008-12-10 05:08:54 +00001492 private:
1493 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001494
1495 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001496};
1497
1498// A helper function for converting a matcher to a predicate-formatter
1499// without the user needing to explicitly write the type. This is
1500// used for implementing ASSERT_THAT() and EXPECT_THAT().
1501template <typename M>
1502inline PredicateFormatterFromMatcher<M>
1503MakePredicateFormatterFromMatcher(const M& matcher) {
1504 return PredicateFormatterFromMatcher<M>(matcher);
1505}
1506
1507// Implements the polymorphic floating point equality matcher, which
1508// matches two float values using ULP-based approximation. The
1509// template is meant to be instantiated with FloatType being either
1510// float or double.
1511template <typename FloatType>
1512class FloatingEqMatcher {
1513 public:
1514 // Constructor for FloatingEqMatcher.
1515 // The matcher's input will be compared with rhs. The matcher treats two
1516 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1517 // equality comparisons between NANs will always return false.
1518 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1519 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1520
1521 // Implements floating point equality matcher as a Matcher<T>.
1522 template <typename T>
1523 class Impl : public MatcherInterface<T> {
1524 public:
1525 Impl(FloatType rhs, bool nan_eq_nan) :
1526 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1527
zhanyong.wan82113312010-01-08 21:55:40 +00001528 virtual bool MatchAndExplain(T value,
1529 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001530 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1531
1532 // Compares NaNs first, if nan_eq_nan_ is true.
1533 if (nan_eq_nan_ && lhs.is_nan()) {
1534 return rhs.is_nan();
1535 }
1536
1537 return lhs.AlmostEquals(rhs);
1538 }
1539
1540 virtual void DescribeTo(::std::ostream* os) const {
1541 // os->precision() returns the previously set precision, which we
1542 // store to restore the ostream to its original configuration
1543 // after outputting.
1544 const ::std::streamsize old_precision = os->precision(
1545 ::std::numeric_limits<FloatType>::digits10 + 2);
1546 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1547 if (nan_eq_nan_) {
1548 *os << "is NaN";
1549 } else {
1550 *os << "never matches";
1551 }
1552 } else {
1553 *os << "is approximately " << rhs_;
1554 }
1555 os->precision(old_precision);
1556 }
1557
1558 virtual void DescribeNegationTo(::std::ostream* os) const {
1559 // As before, get original precision.
1560 const ::std::streamsize old_precision = os->precision(
1561 ::std::numeric_limits<FloatType>::digits10 + 2);
1562 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1563 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001564 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00001565 } else {
1566 *os << "is anything";
1567 }
1568 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001569 *os << "isn't approximately " << rhs_;
shiqiane35fdd92008-12-10 05:08:54 +00001570 }
1571 // Restore original precision.
1572 os->precision(old_precision);
1573 }
1574
1575 private:
1576 const FloatType rhs_;
1577 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001578
1579 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001580 };
1581
1582 // The following 3 type conversion operators allow FloatEq(rhs) and
1583 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1584 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1585 // (While Google's C++ coding style doesn't allow arguments passed
1586 // by non-const reference, we may see them in code not conforming to
1587 // the style. Therefore Google Mock needs to support them.)
1588 operator Matcher<FloatType>() const {
1589 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1590 }
1591
1592 operator Matcher<const FloatType&>() const {
1593 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1594 }
1595
1596 operator Matcher<FloatType&>() const {
1597 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1598 }
1599 private:
1600 const FloatType rhs_;
1601 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001602
1603 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001604};
1605
1606// Implements the Pointee(m) matcher for matching a pointer whose
1607// pointee matches matcher m. The pointer can be either raw or smart.
1608template <typename InnerMatcher>
1609class PointeeMatcher {
1610 public:
1611 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1612
1613 // This type conversion operator template allows Pointee(m) to be
1614 // used as a matcher for any pointer type whose pointee type is
1615 // compatible with the inner matcher, where type Pointer can be
1616 // either a raw pointer or a smart pointer.
1617 //
1618 // The reason we do this instead of relying on
1619 // MakePolymorphicMatcher() is that the latter is not flexible
1620 // enough for implementing the DescribeTo() method of Pointee().
1621 template <typename Pointer>
1622 operator Matcher<Pointer>() const {
1623 return MakeMatcher(new Impl<Pointer>(matcher_));
1624 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001625
shiqiane35fdd92008-12-10 05:08:54 +00001626 private:
1627 // The monomorphic implementation that works for a particular pointer type.
1628 template <typename Pointer>
1629 class Impl : public MatcherInterface<Pointer> {
1630 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00001631 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
1632 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001633
1634 explicit Impl(const InnerMatcher& matcher)
1635 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1636
shiqiane35fdd92008-12-10 05:08:54 +00001637 virtual void DescribeTo(::std::ostream* os) const {
1638 *os << "points to a value that ";
1639 matcher_.DescribeTo(os);
1640 }
1641
1642 virtual void DescribeNegationTo(::std::ostream* os) const {
1643 *os << "does not point to a value that ";
1644 matcher_.DescribeTo(os);
1645 }
1646
zhanyong.wan82113312010-01-08 21:55:40 +00001647 virtual bool MatchAndExplain(Pointer pointer,
1648 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001649 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00001650 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001651
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001652 *listener << "which points to ";
1653 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001654 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001655
shiqiane35fdd92008-12-10 05:08:54 +00001656 private:
1657 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001658
1659 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001660 };
1661
1662 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001663
1664 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001665};
1666
1667// Implements the Field() matcher for matching a field (i.e. member
1668// variable) of an object.
1669template <typename Class, typename FieldType>
1670class FieldMatcher {
1671 public:
1672 FieldMatcher(FieldType Class::*field,
1673 const Matcher<const FieldType&>& matcher)
1674 : field_(field), matcher_(matcher) {}
1675
shiqiane35fdd92008-12-10 05:08:54 +00001676 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001677 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001678 matcher_.DescribeTo(os);
1679 }
1680
1681 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001682 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001683 matcher_.DescribeNegationTo(os);
1684 }
1685
zhanyong.wandb22c222010-01-28 21:52:29 +00001686 template <typename T>
1687 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
1688 return MatchAndExplainImpl(
1689 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00001690 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00001691 value, listener);
1692 }
1693
1694 private:
1695 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001696 // Symbian's C++ compiler choose which overload to use. Its type is
1697 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001698 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1699 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001700 *listener << "whose given field is ";
1701 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001702 }
1703
zhanyong.wandb22c222010-01-28 21:52:29 +00001704 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1705 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001706 if (p == NULL)
1707 return false;
1708
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001709 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001710 // Since *p has a field, it must be a class/struct/union type and
1711 // thus cannot be a pointer. Therefore we pass false_type() as
1712 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001713 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001714 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001715
shiqiane35fdd92008-12-10 05:08:54 +00001716 const FieldType Class::*field_;
1717 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001718
1719 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001720};
1721
shiqiane35fdd92008-12-10 05:08:54 +00001722// Implements the Property() matcher for matching a property
1723// (i.e. return value of a getter method) of an object.
1724template <typename Class, typename PropertyType>
1725class PropertyMatcher {
1726 public:
1727 // The property may have a reference type, so 'const PropertyType&'
1728 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00001729 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00001730 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00001731 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001732
1733 PropertyMatcher(PropertyType (Class::*property)() const,
1734 const Matcher<RefToConstProperty>& matcher)
1735 : property_(property), matcher_(matcher) {}
1736
shiqiane35fdd92008-12-10 05:08:54 +00001737 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001738 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001739 matcher_.DescribeTo(os);
1740 }
1741
1742 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001743 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001744 matcher_.DescribeNegationTo(os);
1745 }
1746
zhanyong.wandb22c222010-01-28 21:52:29 +00001747 template <typename T>
1748 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
1749 return MatchAndExplainImpl(
1750 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00001751 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00001752 value, listener);
1753 }
1754
1755 private:
1756 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001757 // Symbian's C++ compiler choose which overload to use. Its type is
1758 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001759 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1760 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001761 *listener << "whose given property is ";
1762 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
1763 // which takes a non-const reference as argument.
1764 RefToConstProperty result = (obj.*property_)();
1765 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001766 }
1767
zhanyong.wandb22c222010-01-28 21:52:29 +00001768 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1769 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001770 if (p == NULL)
1771 return false;
1772
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001773 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001774 // Since *p has a property method, it must be a class/struct/union
1775 // type and thus cannot be a pointer. Therefore we pass
1776 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001777 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001778 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001779
shiqiane35fdd92008-12-10 05:08:54 +00001780 PropertyType (Class::*property_)() const;
1781 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001782
1783 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001784};
1785
shiqiane35fdd92008-12-10 05:08:54 +00001786// Type traits specifying various features of different functors for ResultOf.
1787// The default template specifies features for functor objects.
1788// Functor classes have to typedef argument_type and result_type
1789// to be compatible with ResultOf.
1790template <typename Functor>
1791struct CallableTraits {
1792 typedef typename Functor::result_type ResultType;
1793 typedef Functor StorageType;
1794
zhanyong.wan32de5f52009-12-23 00:13:23 +00001795 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00001796 template <typename T>
1797 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1798};
1799
1800// Specialization for function pointers.
1801template <typename ArgType, typename ResType>
1802struct CallableTraits<ResType(*)(ArgType)> {
1803 typedef ResType ResultType;
1804 typedef ResType(*StorageType)(ArgType);
1805
1806 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001807 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00001808 << "NULL function pointer is passed into ResultOf().";
1809 }
1810 template <typename T>
1811 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1812 return (*f)(arg);
1813 }
1814};
1815
1816// Implements the ResultOf() matcher for matching a return value of a
1817// unary function of an object.
1818template <typename Callable>
1819class ResultOfMatcher {
1820 public:
1821 typedef typename CallableTraits<Callable>::ResultType ResultType;
1822
1823 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1824 : callable_(callable), matcher_(matcher) {
1825 CallableTraits<Callable>::CheckIsValid(callable_);
1826 }
1827
1828 template <typename T>
1829 operator Matcher<T>() const {
1830 return Matcher<T>(new Impl<T>(callable_, matcher_));
1831 }
1832
1833 private:
1834 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1835
1836 template <typename T>
1837 class Impl : public MatcherInterface<T> {
1838 public:
1839 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1840 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00001841
1842 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001843 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001844 matcher_.DescribeTo(os);
1845 }
1846
1847 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001848 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001849 matcher_.DescribeNegationTo(os);
1850 }
1851
zhanyong.wan82113312010-01-08 21:55:40 +00001852 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001853 *listener << "which is mapped by the given callable to ";
1854 // Cannot pass the return value (for example, int) to
1855 // MatchPrintAndExplain, which takes a non-const reference as argument.
1856 ResultType result =
1857 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
1858 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001859 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001860
shiqiane35fdd92008-12-10 05:08:54 +00001861 private:
1862 // Functors often define operator() as non-const method even though
1863 // they are actualy stateless. But we need to use them even when
1864 // 'this' is a const pointer. It's the user's responsibility not to
1865 // use stateful callables with ResultOf(), which does't guarantee
1866 // how many times the callable will be invoked.
1867 mutable CallableStorageType callable_;
1868 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001869
1870 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001871 }; // class Impl
1872
1873 const CallableStorageType callable_;
1874 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001875
1876 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001877};
1878
zhanyong.wan6a896b52009-01-16 01:13:50 +00001879// Implements an equality matcher for any STL-style container whose elements
1880// support ==. This matcher is like Eq(), but its failure explanations provide
1881// more detailed information that is useful when the container is used as a set.
1882// The failure message reports elements that are in one of the operands but not
1883// the other. The failure messages do not report duplicate or out-of-order
1884// elements in the containers (which don't properly matter to sets, but can
1885// occur if the containers are vectors or lists, for example).
1886//
1887// Uses the container's const_iterator, value_type, operator ==,
1888// begin(), and end().
1889template <typename Container>
1890class ContainerEqMatcher {
1891 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00001892 typedef internal::StlContainerView<Container> View;
1893 typedef typename View::type StlContainer;
1894 typedef typename View::const_reference StlContainerReference;
1895
1896 // We make a copy of rhs in case the elements in it are modified
1897 // after this matcher is created.
1898 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
1899 // Makes sure the user doesn't instantiate this class template
1900 // with a const or reference type.
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001901 (void)testing::StaticAssertTypeEq<Container,
1902 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
zhanyong.wanb8243162009-06-04 05:48:20 +00001903 }
1904
zhanyong.wan6a896b52009-01-16 01:13:50 +00001905 void DescribeTo(::std::ostream* os) const {
1906 *os << "equals ";
vladloseve2e8ba42010-05-13 18:16:03 +00001907 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001908 }
1909 void DescribeNegationTo(::std::ostream* os) const {
1910 *os << "does not equal ";
vladloseve2e8ba42010-05-13 18:16:03 +00001911 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001912 }
1913
zhanyong.wanb8243162009-06-04 05:48:20 +00001914 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00001915 bool MatchAndExplain(const LhsContainer& lhs,
1916 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00001917 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00001918 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00001919 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00001920 LhsView;
1921 typedef typename LhsView::type LhsStlContainer;
1922 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00001923 if (lhs_stl_container == rhs_)
1924 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00001925
zhanyong.wane122e452010-01-12 09:03:52 +00001926 ::std::ostream* const os = listener->stream();
1927 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001928 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00001929 bool printed_header = false;
1930 for (typename LhsStlContainer::const_iterator it =
1931 lhs_stl_container.begin();
1932 it != lhs_stl_container.end(); ++it) {
1933 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
1934 rhs_.end()) {
1935 if (printed_header) {
1936 *os << ", ";
1937 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001938 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00001939 printed_header = true;
1940 }
vladloseve2e8ba42010-05-13 18:16:03 +00001941 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001942 }
zhanyong.wane122e452010-01-12 09:03:52 +00001943 }
1944
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001945 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00001946 bool printed_header2 = false;
1947 for (typename StlContainer::const_iterator it = rhs_.begin();
1948 it != rhs_.end(); ++it) {
1949 if (internal::ArrayAwareFind(
1950 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
1951 lhs_stl_container.end()) {
1952 if (printed_header2) {
1953 *os << ", ";
1954 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001955 *os << (printed_header ? ",\nand" : "which")
1956 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00001957 printed_header2 = true;
1958 }
vladloseve2e8ba42010-05-13 18:16:03 +00001959 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00001960 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00001961 }
1962 }
1963
zhanyong.wane122e452010-01-12 09:03:52 +00001964 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00001965 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001966
zhanyong.wan6a896b52009-01-16 01:13:50 +00001967 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00001968 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001969
1970 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001971};
1972
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001973// Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
1974// must be able to be safely cast to Matcher<tuple<const T1&, const
1975// T2&> >, where T1 and T2 are the types of elements in the LHS
1976// container and the RHS container respectively.
1977template <typename TupleMatcher, typename RhsContainer>
1978class PointwiseMatcher {
1979 public:
1980 typedef internal::StlContainerView<RhsContainer> RhsView;
1981 typedef typename RhsView::type RhsStlContainer;
1982 typedef typename RhsStlContainer::value_type RhsValue;
1983
1984 // Like ContainerEq, we make a copy of rhs in case the elements in
1985 // it are modified after this matcher is created.
1986 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
1987 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
1988 // Makes sure the user doesn't instantiate this class template
1989 // with a const or reference type.
1990 (void)testing::StaticAssertTypeEq<RhsContainer,
1991 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
1992 }
1993
1994 template <typename LhsContainer>
1995 operator Matcher<LhsContainer>() const {
1996 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
1997 }
1998
1999 template <typename LhsContainer>
2000 class Impl : public MatcherInterface<LhsContainer> {
2001 public:
2002 typedef internal::StlContainerView<
2003 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2004 typedef typename LhsView::type LhsStlContainer;
2005 typedef typename LhsView::const_reference LhsStlContainerReference;
2006 typedef typename LhsStlContainer::value_type LhsValue;
2007 // We pass the LHS value and the RHS value to the inner matcher by
2008 // reference, as they may be expensive to copy. We must use tuple
2009 // instead of pair here, as a pair cannot hold references (C++ 98,
2010 // 20.2.2 [lib.pairs]).
2011 typedef std::tr1::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
2012
2013 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2014 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2015 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2016 rhs_(rhs) {}
2017
2018 virtual void DescribeTo(::std::ostream* os) const {
2019 *os << "contains " << rhs_.size()
2020 << " values, where each value and its corresponding value in ";
2021 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2022 *os << " ";
2023 mono_tuple_matcher_.DescribeTo(os);
2024 }
2025 virtual void DescribeNegationTo(::std::ostream* os) const {
2026 *os << "doesn't contain exactly " << rhs_.size()
2027 << " values, or contains a value x at some index i"
2028 << " where x and the i-th value of ";
2029 UniversalPrint(rhs_, os);
2030 *os << " ";
2031 mono_tuple_matcher_.DescribeNegationTo(os);
2032 }
2033
2034 virtual bool MatchAndExplain(LhsContainer lhs,
2035 MatchResultListener* listener) const {
2036 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2037 const size_t actual_size = lhs_stl_container.size();
2038 if (actual_size != rhs_.size()) {
2039 *listener << "which contains " << actual_size << " values";
2040 return false;
2041 }
2042
2043 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2044 typename RhsStlContainer::const_iterator right = rhs_.begin();
2045 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2046 const InnerMatcherArg value_pair(*left, *right);
2047
2048 if (listener->IsInterested()) {
2049 StringMatchResultListener inner_listener;
2050 if (!mono_tuple_matcher_.MatchAndExplain(
2051 value_pair, &inner_listener)) {
2052 *listener << "where the value pair (";
2053 UniversalPrint(*left, listener->stream());
2054 *listener << ", ";
2055 UniversalPrint(*right, listener->stream());
2056 *listener << ") at index #" << i << " don't match";
2057 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2058 return false;
2059 }
2060 } else {
2061 if (!mono_tuple_matcher_.Matches(value_pair))
2062 return false;
2063 }
2064 }
2065
2066 return true;
2067 }
2068
2069 private:
2070 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2071 const RhsStlContainer rhs_;
2072
2073 GTEST_DISALLOW_ASSIGN_(Impl);
2074 };
2075
2076 private:
2077 const TupleMatcher tuple_matcher_;
2078 const RhsStlContainer rhs_;
2079
2080 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2081};
2082
zhanyong.wan33605ba2010-04-22 23:37:47 +00002083// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00002084template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002085class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00002086 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002087 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00002088 typedef StlContainerView<RawContainer> View;
2089 typedef typename View::type StlContainer;
2090 typedef typename View::const_reference StlContainerReference;
2091 typedef typename StlContainer::value_type Element;
2092
2093 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00002094 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00002095 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00002096 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00002097
zhanyong.wan33605ba2010-04-22 23:37:47 +00002098 // Checks whether:
2099 // * All elements in the container match, if all_elements_should_match.
2100 // * Any element in the container matches, if !all_elements_should_match.
2101 bool MatchAndExplainImpl(bool all_elements_should_match,
2102 Container container,
2103 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00002104 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002105 size_t i = 0;
2106 for (typename StlContainer::const_iterator it = stl_container.begin();
2107 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002108 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00002109 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2110
2111 if (matches != all_elements_should_match) {
2112 *listener << "whose element #" << i
2113 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002114 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00002115 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00002116 }
2117 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00002118 return all_elements_should_match;
2119 }
2120
2121 protected:
2122 const Matcher<const Element&> inner_matcher_;
2123
2124 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2125};
2126
2127// Implements Contains(element_matcher) for the given argument type Container.
2128// Symmetric to EachMatcherImpl.
2129template <typename Container>
2130class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2131 public:
2132 template <typename InnerMatcher>
2133 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2134 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2135
2136 // Describes what this matcher does.
2137 virtual void DescribeTo(::std::ostream* os) const {
2138 *os << "contains at least one element that ";
2139 this->inner_matcher_.DescribeTo(os);
2140 }
2141
2142 virtual void DescribeNegationTo(::std::ostream* os) const {
2143 *os << "doesn't contain any element that ";
2144 this->inner_matcher_.DescribeTo(os);
2145 }
2146
2147 virtual bool MatchAndExplain(Container container,
2148 MatchResultListener* listener) const {
2149 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002150 }
2151
2152 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002153 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002154};
2155
zhanyong.wan33605ba2010-04-22 23:37:47 +00002156// Implements Each(element_matcher) for the given argument type Container.
2157// Symmetric to ContainsMatcherImpl.
2158template <typename Container>
2159class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2160 public:
2161 template <typename InnerMatcher>
2162 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2163 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2164
2165 // Describes what this matcher does.
2166 virtual void DescribeTo(::std::ostream* os) const {
2167 *os << "only contains elements that ";
2168 this->inner_matcher_.DescribeTo(os);
2169 }
2170
2171 virtual void DescribeNegationTo(::std::ostream* os) const {
2172 *os << "contains some element that ";
2173 this->inner_matcher_.DescribeNegationTo(os);
2174 }
2175
2176 virtual bool MatchAndExplain(Container container,
2177 MatchResultListener* listener) const {
2178 return this->MatchAndExplainImpl(true, container, listener);
2179 }
2180
2181 private:
2182 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2183};
2184
zhanyong.wanb8243162009-06-04 05:48:20 +00002185// Implements polymorphic Contains(element_matcher).
2186template <typename M>
2187class ContainsMatcher {
2188 public:
2189 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2190
2191 template <typename Container>
2192 operator Matcher<Container>() const {
2193 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2194 }
2195
2196 private:
2197 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002198
2199 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002200};
2201
zhanyong.wan33605ba2010-04-22 23:37:47 +00002202// Implements polymorphic Each(element_matcher).
2203template <typename M>
2204class EachMatcher {
2205 public:
2206 explicit EachMatcher(M m) : inner_matcher_(m) {}
2207
2208 template <typename Container>
2209 operator Matcher<Container>() const {
2210 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2211 }
2212
2213 private:
2214 const M inner_matcher_;
2215
2216 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2217};
2218
zhanyong.wanb5937da2009-07-16 20:26:41 +00002219// Implements Key(inner_matcher) for the given argument pair type.
2220// Key(inner_matcher) matches an std::pair whose 'first' field matches
2221// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2222// std::map that contains at least one element whose key is >= 5.
2223template <typename PairType>
2224class KeyMatcherImpl : public MatcherInterface<PairType> {
2225 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002226 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002227 typedef typename RawPairType::first_type KeyType;
2228
2229 template <typename InnerMatcher>
2230 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2231 : inner_matcher_(
2232 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2233 }
2234
2235 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002236 virtual bool MatchAndExplain(PairType key_value,
2237 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002238 StringMatchResultListener inner_listener;
2239 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2240 &inner_listener);
2241 const internal::string explanation = inner_listener.str();
2242 if (explanation != "") {
2243 *listener << "whose first field is a value " << explanation;
2244 }
2245 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002246 }
2247
2248 // Describes what this matcher does.
2249 virtual void DescribeTo(::std::ostream* os) const {
2250 *os << "has a key that ";
2251 inner_matcher_.DescribeTo(os);
2252 }
2253
2254 // Describes what the negation of this matcher does.
2255 virtual void DescribeNegationTo(::std::ostream* os) const {
2256 *os << "doesn't have a key that ";
2257 inner_matcher_.DescribeTo(os);
2258 }
2259
zhanyong.wanb5937da2009-07-16 20:26:41 +00002260 private:
2261 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002262
2263 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002264};
2265
2266// Implements polymorphic Key(matcher_for_key).
2267template <typename M>
2268class KeyMatcher {
2269 public:
2270 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2271
2272 template <typename PairType>
2273 operator Matcher<PairType>() const {
2274 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2275 }
2276
2277 private:
2278 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002279
2280 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002281};
2282
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002283// Implements Pair(first_matcher, second_matcher) for the given argument pair
2284// type with its two matchers. See Pair() function below.
2285template <typename PairType>
2286class PairMatcherImpl : public MatcherInterface<PairType> {
2287 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002288 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002289 typedef typename RawPairType::first_type FirstType;
2290 typedef typename RawPairType::second_type SecondType;
2291
2292 template <typename FirstMatcher, typename SecondMatcher>
2293 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2294 : first_matcher_(
2295 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2296 second_matcher_(
2297 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2298 }
2299
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002300 // Describes what this matcher does.
2301 virtual void DescribeTo(::std::ostream* os) const {
2302 *os << "has a first field that ";
2303 first_matcher_.DescribeTo(os);
2304 *os << ", and has a second field that ";
2305 second_matcher_.DescribeTo(os);
2306 }
2307
2308 // Describes what the negation of this matcher does.
2309 virtual void DescribeNegationTo(::std::ostream* os) const {
2310 *os << "has a first field that ";
2311 first_matcher_.DescribeNegationTo(os);
2312 *os << ", or has a second field that ";
2313 second_matcher_.DescribeNegationTo(os);
2314 }
2315
zhanyong.wan82113312010-01-08 21:55:40 +00002316 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2317 // matches second_matcher.
2318 virtual bool MatchAndExplain(PairType a_pair,
2319 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002320 if (!listener->IsInterested()) {
2321 // If the listener is not interested, we don't need to construct the
2322 // explanation.
2323 return first_matcher_.Matches(a_pair.first) &&
2324 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00002325 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002326 StringMatchResultListener first_inner_listener;
2327 if (!first_matcher_.MatchAndExplain(a_pair.first,
2328 &first_inner_listener)) {
2329 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002330 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002331 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002332 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002333 StringMatchResultListener second_inner_listener;
2334 if (!second_matcher_.MatchAndExplain(a_pair.second,
2335 &second_inner_listener)) {
2336 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002337 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002338 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002339 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002340 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
2341 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00002342 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002343 }
2344
2345 private:
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002346 void ExplainSuccess(const internal::string& first_explanation,
2347 const internal::string& second_explanation,
2348 MatchResultListener* listener) const {
2349 *listener << "whose both fields match";
2350 if (first_explanation != "") {
2351 *listener << ", where the first field is a value " << first_explanation;
2352 }
2353 if (second_explanation != "") {
2354 *listener << ", ";
2355 if (first_explanation != "") {
2356 *listener << "and ";
2357 } else {
2358 *listener << "where ";
2359 }
2360 *listener << "the second field is a value " << second_explanation;
2361 }
2362 }
2363
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002364 const Matcher<const FirstType&> first_matcher_;
2365 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002366
2367 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002368};
2369
2370// Implements polymorphic Pair(first_matcher, second_matcher).
2371template <typename FirstMatcher, typename SecondMatcher>
2372class PairMatcher {
2373 public:
2374 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2375 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2376
2377 template <typename PairType>
2378 operator Matcher<PairType> () const {
2379 return MakeMatcher(
2380 new PairMatcherImpl<PairType>(
2381 first_matcher_, second_matcher_));
2382 }
2383
2384 private:
2385 const FirstMatcher first_matcher_;
2386 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002387
2388 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002389};
2390
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002391// Implements ElementsAre() and ElementsAreArray().
2392template <typename Container>
2393class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2394 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002395 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002396 typedef internal::StlContainerView<RawContainer> View;
2397 typedef typename View::type StlContainer;
2398 typedef typename View::const_reference StlContainerReference;
2399 typedef typename StlContainer::value_type Element;
2400
2401 // Constructs the matcher from a sequence of element values or
2402 // element matchers.
2403 template <typename InputIter>
zhanyong.wan32de5f52009-12-23 00:13:23 +00002404 ElementsAreMatcherImpl(InputIter first, size_t a_count) {
2405 matchers_.reserve(a_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002406 InputIter it = first;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002407 for (size_t i = 0; i != a_count; ++i, ++it) {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002408 matchers_.push_back(MatcherCast<const Element&>(*it));
2409 }
2410 }
2411
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002412 // Describes what this matcher does.
2413 virtual void DescribeTo(::std::ostream* os) const {
2414 if (count() == 0) {
2415 *os << "is empty";
2416 } else if (count() == 1) {
2417 *os << "has 1 element that ";
2418 matchers_[0].DescribeTo(os);
2419 } else {
2420 *os << "has " << Elements(count()) << " where\n";
2421 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002422 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002423 matchers_[i].DescribeTo(os);
2424 if (i + 1 < count()) {
2425 *os << ",\n";
2426 }
2427 }
2428 }
2429 }
2430
2431 // Describes what the negation of this matcher does.
2432 virtual void DescribeNegationTo(::std::ostream* os) const {
2433 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002434 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002435 return;
2436 }
2437
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002438 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002439 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002440 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002441 matchers_[i].DescribeNegationTo(os);
2442 if (i + 1 < count()) {
2443 *os << ", or\n";
2444 }
2445 }
2446 }
2447
zhanyong.wan82113312010-01-08 21:55:40 +00002448 virtual bool MatchAndExplain(Container container,
2449 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002450 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002451 const size_t actual_count = stl_container.size();
2452 if (actual_count != count()) {
2453 // The element count doesn't match. If the container is empty,
2454 // there's no need to explain anything as Google Mock already
2455 // prints the empty container. Otherwise we just need to show
2456 // how many elements there actually are.
2457 if (actual_count != 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002458 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002459 }
zhanyong.wan82113312010-01-08 21:55:40 +00002460 return false;
2461 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002462
zhanyong.wan82113312010-01-08 21:55:40 +00002463 typename StlContainer::const_iterator it = stl_container.begin();
2464 // explanations[i] is the explanation of the element at index i.
2465 std::vector<internal::string> explanations(count());
2466 for (size_t i = 0; i != count(); ++it, ++i) {
2467 StringMatchResultListener s;
2468 if (matchers_[i].MatchAndExplain(*it, &s)) {
2469 explanations[i] = s.str();
2470 } else {
2471 // The container has the right size but the i-th element
2472 // doesn't match its expectation.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002473 *listener << "whose element #" << i << " doesn't match";
2474 PrintIfNotEmpty(s.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002475 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002476 }
2477 }
zhanyong.wan82113312010-01-08 21:55:40 +00002478
2479 // Every element matches its expectation. We need to explain why
2480 // (the obvious ones can be skipped).
zhanyong.wan82113312010-01-08 21:55:40 +00002481 bool reason_printed = false;
2482 for (size_t i = 0; i != count(); ++i) {
2483 const internal::string& s = explanations[i];
2484 if (!s.empty()) {
2485 if (reason_printed) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002486 *listener << ",\nand ";
zhanyong.wan82113312010-01-08 21:55:40 +00002487 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002488 *listener << "whose element #" << i << " matches, " << s;
zhanyong.wan82113312010-01-08 21:55:40 +00002489 reason_printed = true;
2490 }
2491 }
2492
2493 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002494 }
2495
2496 private:
2497 static Message Elements(size_t count) {
2498 return Message() << count << (count == 1 ? " element" : " elements");
2499 }
2500
2501 size_t count() const { return matchers_.size(); }
2502 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002503
2504 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002505};
2506
2507// Implements ElementsAre() of 0 arguments.
2508class ElementsAreMatcher0 {
2509 public:
2510 ElementsAreMatcher0() {}
2511
2512 template <typename Container>
2513 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002514 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002515 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2516 Element;
2517
2518 const Matcher<const Element&>* const matchers = NULL;
2519 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 0));
2520 }
2521};
2522
2523// Implements ElementsAreArray().
2524template <typename T>
2525class ElementsAreArrayMatcher {
2526 public:
2527 ElementsAreArrayMatcher(const T* first, size_t count) :
2528 first_(first), count_(count) {}
2529
2530 template <typename Container>
2531 operator Matcher<Container>() const {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002532 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002533 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2534 Element;
2535
2536 return MakeMatcher(new ElementsAreMatcherImpl<Container>(first_, count_));
2537 }
2538
2539 private:
2540 const T* const first_;
2541 const size_t count_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002542
2543 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002544};
2545
zhanyong.wanb4140802010-06-08 22:53:57 +00002546// Returns the description for a matcher defined using the MATCHER*()
2547// macro where the user-supplied description string is "", if
2548// 'negation' is false; otherwise returns the description of the
2549// negation of the matcher. 'param_values' contains a list of strings
2550// that are the print-out of the matcher's parameters.
2551string FormatMatcherDescription(bool negation, const char* matcher_name,
2552 const Strings& param_values);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002553
shiqiane35fdd92008-12-10 05:08:54 +00002554} // namespace internal
2555
2556// Implements MatcherCast().
2557template <typename T, typename M>
2558inline Matcher<T> MatcherCast(M matcher) {
2559 return internal::MatcherCastImpl<T, M>::Cast(matcher);
2560}
2561
2562// _ is a matcher that matches anything of any type.
2563//
2564// This definition is fine as:
2565//
2566// 1. The C++ standard permits using the name _ in a namespace that
2567// is not the global namespace or ::std.
2568// 2. The AnythingMatcher class has no data member or constructor,
2569// so it's OK to create global variables of this type.
2570// 3. c-style has approved of using _ in this case.
2571const internal::AnythingMatcher _ = {};
2572// Creates a matcher that matches any value of the given type T.
2573template <typename T>
2574inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2575
2576// Creates a matcher that matches any value of the given type T.
2577template <typename T>
2578inline Matcher<T> An() { return A<T>(); }
2579
2580// Creates a polymorphic matcher that matches anything equal to x.
2581// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2582// wouldn't compile.
2583template <typename T>
2584inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2585
2586// Constructs a Matcher<T> from a 'value' of type T. The constructed
2587// matcher matches any value that's equal to 'value'.
2588template <typename T>
2589Matcher<T>::Matcher(T value) { *this = Eq(value); }
2590
2591// Creates a monomorphic matcher that matches anything with type Lhs
2592// and equal to rhs. A user may need to use this instead of Eq(...)
2593// in order to resolve an overloading ambiguity.
2594//
2595// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2596// or Matcher<T>(x), but more readable than the latter.
2597//
2598// We could define similar monomorphic matchers for other comparison
2599// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2600// it yet as those are used much less than Eq() in practice. A user
2601// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2602// for example.
2603template <typename Lhs, typename Rhs>
2604inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2605
2606// Creates a polymorphic matcher that matches anything >= x.
2607template <typename Rhs>
2608inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2609 return internal::GeMatcher<Rhs>(x);
2610}
2611
2612// Creates a polymorphic matcher that matches anything > x.
2613template <typename Rhs>
2614inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2615 return internal::GtMatcher<Rhs>(x);
2616}
2617
2618// Creates a polymorphic matcher that matches anything <= x.
2619template <typename Rhs>
2620inline internal::LeMatcher<Rhs> Le(Rhs x) {
2621 return internal::LeMatcher<Rhs>(x);
2622}
2623
2624// Creates a polymorphic matcher that matches anything < x.
2625template <typename Rhs>
2626inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2627 return internal::LtMatcher<Rhs>(x);
2628}
2629
2630// Creates a polymorphic matcher that matches anything != x.
2631template <typename Rhs>
2632inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2633 return internal::NeMatcher<Rhs>(x);
2634}
2635
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002636// Creates a polymorphic matcher that matches any NULL pointer.
2637inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2638 return MakePolymorphicMatcher(internal::IsNullMatcher());
2639}
2640
shiqiane35fdd92008-12-10 05:08:54 +00002641// Creates a polymorphic matcher that matches any non-NULL pointer.
2642// This is convenient as Not(NULL) doesn't compile (the compiler
2643// thinks that that expression is comparing a pointer with an integer).
2644inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2645 return MakePolymorphicMatcher(internal::NotNullMatcher());
2646}
2647
2648// Creates a polymorphic matcher that matches any argument that
2649// references variable x.
2650template <typename T>
2651inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2652 return internal::RefMatcher<T&>(x);
2653}
2654
2655// Creates a matcher that matches any double argument approximately
2656// equal to rhs, where two NANs are considered unequal.
2657inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2658 return internal::FloatingEqMatcher<double>(rhs, false);
2659}
2660
2661// Creates a matcher that matches any double argument approximately
2662// equal to rhs, including NaN values when rhs is NaN.
2663inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2664 return internal::FloatingEqMatcher<double>(rhs, true);
2665}
2666
2667// Creates a matcher that matches any float argument approximately
2668// equal to rhs, where two NANs are considered unequal.
2669inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2670 return internal::FloatingEqMatcher<float>(rhs, false);
2671}
2672
2673// Creates a matcher that matches any double argument approximately
2674// equal to rhs, including NaN values when rhs is NaN.
2675inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2676 return internal::FloatingEqMatcher<float>(rhs, true);
2677}
2678
2679// Creates a matcher that matches a pointer (raw or smart) that points
2680// to a value that matches inner_matcher.
2681template <typename InnerMatcher>
2682inline internal::PointeeMatcher<InnerMatcher> Pointee(
2683 const InnerMatcher& inner_matcher) {
2684 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2685}
2686
2687// Creates a matcher that matches an object whose given field matches
2688// 'matcher'. For example,
2689// Field(&Foo::number, Ge(5))
2690// matches a Foo object x iff x.number >= 5.
2691template <typename Class, typename FieldType, typename FieldMatcher>
2692inline PolymorphicMatcher<
2693 internal::FieldMatcher<Class, FieldType> > Field(
2694 FieldType Class::*field, const FieldMatcher& matcher) {
2695 return MakePolymorphicMatcher(
2696 internal::FieldMatcher<Class, FieldType>(
2697 field, MatcherCast<const FieldType&>(matcher)));
2698 // The call to MatcherCast() is required for supporting inner
2699 // matchers of compatible types. For example, it allows
2700 // Field(&Foo::bar, m)
2701 // to compile where bar is an int32 and m is a matcher for int64.
2702}
2703
2704// Creates a matcher that matches an object whose given property
2705// matches 'matcher'. For example,
2706// Property(&Foo::str, StartsWith("hi"))
2707// matches a Foo object x iff x.str() starts with "hi".
2708template <typename Class, typename PropertyType, typename PropertyMatcher>
2709inline PolymorphicMatcher<
2710 internal::PropertyMatcher<Class, PropertyType> > Property(
2711 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2712 return MakePolymorphicMatcher(
2713 internal::PropertyMatcher<Class, PropertyType>(
2714 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00002715 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002716 // The call to MatcherCast() is required for supporting inner
2717 // matchers of compatible types. For example, it allows
2718 // Property(&Foo::bar, m)
2719 // to compile where bar() returns an int32 and m is a matcher for int64.
2720}
2721
2722// Creates a matcher that matches an object iff the result of applying
2723// a callable to x matches 'matcher'.
2724// For example,
2725// ResultOf(f, StartsWith("hi"))
2726// matches a Foo object x iff f(x) starts with "hi".
2727// callable parameter can be a function, function pointer, or a functor.
2728// Callable has to satisfy the following conditions:
2729// * It is required to keep no state affecting the results of
2730// the calls on it and make no assumptions about how many calls
2731// will be made. Any state it keeps must be protected from the
2732// concurrent access.
2733// * If it is a function object, it has to define type result_type.
2734// We recommend deriving your functor classes from std::unary_function.
2735template <typename Callable, typename ResultOfMatcher>
2736internal::ResultOfMatcher<Callable> ResultOf(
2737 Callable callable, const ResultOfMatcher& matcher) {
2738 return internal::ResultOfMatcher<Callable>(
2739 callable,
2740 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2741 matcher));
2742 // The call to MatcherCast() is required for supporting inner
2743 // matchers of compatible types. For example, it allows
2744 // ResultOf(Function, m)
2745 // to compile where Function() returns an int32 and m is a matcher for int64.
2746}
2747
2748// String matchers.
2749
2750// Matches a string equal to str.
2751inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2752 StrEq(const internal::string& str) {
2753 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2754 str, true, true));
2755}
2756
2757// Matches a string not equal to str.
2758inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2759 StrNe(const internal::string& str) {
2760 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2761 str, false, true));
2762}
2763
2764// Matches a string equal to str, ignoring case.
2765inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2766 StrCaseEq(const internal::string& str) {
2767 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2768 str, true, false));
2769}
2770
2771// Matches a string not equal to str, ignoring case.
2772inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2773 StrCaseNe(const internal::string& str) {
2774 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2775 str, false, false));
2776}
2777
2778// Creates a matcher that matches any string, std::string, or C string
2779// that contains the given substring.
2780inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2781 HasSubstr(const internal::string& substring) {
2782 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
2783 substring));
2784}
2785
2786// Matches a string that starts with 'prefix' (case-sensitive).
2787inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
2788 StartsWith(const internal::string& prefix) {
2789 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
2790 prefix));
2791}
2792
2793// Matches a string that ends with 'suffix' (case-sensitive).
2794inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
2795 EndsWith(const internal::string& suffix) {
2796 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
2797 suffix));
2798}
2799
shiqiane35fdd92008-12-10 05:08:54 +00002800// Matches a string that fully matches regular expression 'regex'.
2801// The matcher takes ownership of 'regex'.
2802inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2803 const internal::RE* regex) {
2804 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2805}
2806inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2807 const internal::string& regex) {
2808 return MatchesRegex(new internal::RE(regex));
2809}
2810
2811// Matches a string that contains regular expression 'regex'.
2812// The matcher takes ownership of 'regex'.
2813inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2814 const internal::RE* regex) {
2815 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2816}
2817inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2818 const internal::string& regex) {
2819 return ContainsRegex(new internal::RE(regex));
2820}
2821
shiqiane35fdd92008-12-10 05:08:54 +00002822#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2823// Wide string matchers.
2824
2825// Matches a string equal to str.
2826inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2827 StrEq(const internal::wstring& str) {
2828 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2829 str, true, true));
2830}
2831
2832// Matches a string not equal to str.
2833inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2834 StrNe(const internal::wstring& str) {
2835 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2836 str, false, true));
2837}
2838
2839// Matches a string equal to str, ignoring case.
2840inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2841 StrCaseEq(const internal::wstring& str) {
2842 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2843 str, true, false));
2844}
2845
2846// Matches a string not equal to str, ignoring case.
2847inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2848 StrCaseNe(const internal::wstring& str) {
2849 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2850 str, false, false));
2851}
2852
2853// Creates a matcher that matches any wstring, std::wstring, or C wide string
2854// that contains the given substring.
2855inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2856 HasSubstr(const internal::wstring& substring) {
2857 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2858 substring));
2859}
2860
2861// Matches a string that starts with 'prefix' (case-sensitive).
2862inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2863 StartsWith(const internal::wstring& prefix) {
2864 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2865 prefix));
2866}
2867
2868// Matches a string that ends with 'suffix' (case-sensitive).
2869inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2870 EndsWith(const internal::wstring& suffix) {
2871 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2872 suffix));
2873}
2874
2875#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2876
2877// Creates a polymorphic matcher that matches a 2-tuple where the
2878// first field == the second field.
2879inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2880
2881// Creates a polymorphic matcher that matches a 2-tuple where the
2882// first field >= the second field.
2883inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2884
2885// Creates a polymorphic matcher that matches a 2-tuple where the
2886// first field > the second field.
2887inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2888
2889// Creates a polymorphic matcher that matches a 2-tuple where the
2890// first field <= the second field.
2891inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2892
2893// Creates a polymorphic matcher that matches a 2-tuple where the
2894// first field < the second field.
2895inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2896
2897// Creates a polymorphic matcher that matches a 2-tuple where the
2898// first field != the second field.
2899inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2900
2901// Creates a matcher that matches any value of type T that m doesn't
2902// match.
2903template <typename InnerMatcher>
2904inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2905 return internal::NotMatcher<InnerMatcher>(m);
2906}
2907
shiqiane35fdd92008-12-10 05:08:54 +00002908// Returns a matcher that matches anything that satisfies the given
2909// predicate. The predicate can be any unary function or functor
2910// whose return type can be implicitly converted to bool.
2911template <typename Predicate>
2912inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
2913Truly(Predicate pred) {
2914 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
2915}
2916
zhanyong.wan6a896b52009-01-16 01:13:50 +00002917// Returns a matcher that matches an equal container.
2918// This matcher behaves like Eq(), but in the event of mismatch lists the
2919// values that are included in one container but not the other. (Duplicate
2920// values and order differences are not explained.)
2921template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00002922inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00002923 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00002924 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002925 // This following line is for working around a bug in MSVC 8.0,
2926 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002927 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00002928 return MakePolymorphicMatcher(
2929 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00002930}
2931
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002932// Matches an STL-style container or a native array that contains the
2933// same number of elements as in rhs, where its i-th element and rhs's
2934// i-th element (as a pair) satisfy the given pair matcher, for all i.
2935// TupleMatcher must be able to be safely cast to Matcher<tuple<const
2936// T1&, const T2&> >, where T1 and T2 are the types of elements in the
2937// LHS container and the RHS container respectively.
2938template <typename TupleMatcher, typename Container>
2939inline internal::PointwiseMatcher<TupleMatcher,
2940 GTEST_REMOVE_CONST_(Container)>
2941Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
2942 // This following line is for working around a bug in MSVC 8.0,
2943 // which causes Container to be a const type sometimes.
2944 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
2945 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
2946 tuple_matcher, rhs);
2947}
2948
zhanyong.wanb8243162009-06-04 05:48:20 +00002949// Matches an STL-style container or a native array that contains at
2950// least one element matching the given value or matcher.
2951//
2952// Examples:
2953// ::std::set<int> page_ids;
2954// page_ids.insert(3);
2955// page_ids.insert(1);
2956// EXPECT_THAT(page_ids, Contains(1));
2957// EXPECT_THAT(page_ids, Contains(Gt(2)));
2958// EXPECT_THAT(page_ids, Not(Contains(4)));
2959//
2960// ::std::map<int, size_t> page_lengths;
2961// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00002962// EXPECT_THAT(page_lengths,
2963// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00002964//
2965// const char* user_ids[] = { "joe", "mike", "tom" };
2966// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
2967template <typename M>
2968inline internal::ContainsMatcher<M> Contains(M matcher) {
2969 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002970}
2971
zhanyong.wan33605ba2010-04-22 23:37:47 +00002972// Matches an STL-style container or a native array that contains only
2973// elements matching the given value or matcher.
2974//
2975// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
2976// the messages are different.
2977//
2978// Examples:
2979// ::std::set<int> page_ids;
2980// // Each(m) matches an empty container, regardless of what m is.
2981// EXPECT_THAT(page_ids, Each(Eq(1)));
2982// EXPECT_THAT(page_ids, Each(Eq(77)));
2983//
2984// page_ids.insert(3);
2985// EXPECT_THAT(page_ids, Each(Gt(0)));
2986// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
2987// page_ids.insert(1);
2988// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
2989//
2990// ::std::map<int, size_t> page_lengths;
2991// page_lengths[1] = 100;
2992// page_lengths[2] = 200;
2993// page_lengths[3] = 300;
2994// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
2995// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
2996//
2997// const char* user_ids[] = { "joe", "mike", "tom" };
2998// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
2999template <typename M>
3000inline internal::EachMatcher<M> Each(M matcher) {
3001 return internal::EachMatcher<M>(matcher);
3002}
3003
zhanyong.wanb5937da2009-07-16 20:26:41 +00003004// Key(inner_matcher) matches an std::pair whose 'first' field matches
3005// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
3006// std::map that contains at least one element whose key is >= 5.
3007template <typename M>
3008inline internal::KeyMatcher<M> Key(M inner_matcher) {
3009 return internal::KeyMatcher<M>(inner_matcher);
3010}
3011
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00003012// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
3013// matches first_matcher and whose 'second' field matches second_matcher. For
3014// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
3015// to match a std::map<int, string> that contains exactly one element whose key
3016// is >= 5 and whose value equals "foo".
3017template <typename FirstMatcher, typename SecondMatcher>
3018inline internal::PairMatcher<FirstMatcher, SecondMatcher>
3019Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
3020 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
3021 first_matcher, second_matcher);
3022}
3023
shiqiane35fdd92008-12-10 05:08:54 +00003024// Returns a predicate that is satisfied by anything that matches the
3025// given matcher.
3026template <typename M>
3027inline internal::MatcherAsPredicate<M> Matches(M matcher) {
3028 return internal::MatcherAsPredicate<M>(matcher);
3029}
3030
zhanyong.wanb8243162009-06-04 05:48:20 +00003031// Returns true iff the value matches the matcher.
3032template <typename T, typename M>
3033inline bool Value(const T& value, M matcher) {
3034 return testing::Matches(matcher)(value);
3035}
3036
zhanyong.wan34b034c2010-03-05 21:23:23 +00003037// Matches the value against the given matcher and explains the match
3038// result to listener.
3039template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00003040inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00003041 M matcher, const T& value, MatchResultListener* listener) {
3042 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
3043}
3044
zhanyong.wanbf550852009-06-09 06:09:53 +00003045// AllArgs(m) is a synonym of m. This is useful in
3046//
3047// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
3048//
3049// which is easier to read than
3050//
3051// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
3052template <typename InnerMatcher>
3053inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
3054
shiqiane35fdd92008-12-10 05:08:54 +00003055// These macros allow using matchers to check values in Google Test
3056// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
3057// succeed iff the value matches the matcher. If the assertion fails,
3058// the value and the description of the matcher will be printed.
3059#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
3060 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3061#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
3062 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3063
3064} // namespace testing
3065
3066#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_