blob: 7f84761e81bce6ce53b0664c9671bfd8a25c4ad4 [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements some commonly used argument matchers. More
35// matchers can be defined by the user implementing the
36// MatcherInterface<T> interface if necessary.
37
38#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
39#define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
40
zhanyong.wan6a896b52009-01-16 01:13:50 +000041#include <algorithm>
zhanyong.wan16cf4732009-05-14 20:55:30 +000042#include <limits>
shiqiane35fdd92008-12-10 05:08:54 +000043#include <ostream> // NOLINT
44#include <sstream>
45#include <string>
46#include <vector>
47
shiqiane35fdd92008-12-10 05:08:54 +000048#include <gmock/internal/gmock-internal-utils.h>
49#include <gmock/internal/gmock-port.h>
50#include <gtest/gtest.h>
51
52namespace testing {
53
54// To implement a matcher Foo for type T, define:
55// 1. a class FooMatcherImpl that implements the
56// MatcherInterface<T> interface, and
57// 2. a factory function that creates a Matcher<T> object from a
58// FooMatcherImpl*.
59//
60// The two-level delegation design makes it possible to allow a user
61// to write "v" instead of "Eq(v)" where a Matcher is expected, which
62// is impossible if we pass matchers by pointers. It also eases
63// ownership management as Matcher objects can now be copied like
64// plain values.
65
zhanyong.wan82113312010-01-08 21:55:40 +000066// MatchResultListener is an abstract class. Its << operator can be
67// used by a matcher to explain why a value matches or doesn't match.
68//
69// TODO(wan@google.com): add method
70// bool InterestedInWhy(bool result) const;
71// to indicate whether the listener is interested in why the match
72// result is 'result'.
73class MatchResultListener {
74 public:
75 // Creates a listener object with the given underlying ostream. The
76 // listener does not own the ostream.
77 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
78 virtual ~MatchResultListener() = 0; // Makes this class abstract.
79
80 // Streams x to the underlying ostream; does nothing if the ostream
81 // is NULL.
82 template <typename T>
83 MatchResultListener& operator<<(const T& x) {
84 if (stream_ != NULL)
85 *stream_ << x;
86 return *this;
87 }
88
89 // Returns the underlying ostream.
90 ::std::ostream* stream() { return stream_; }
91
zhanyong.wana862f1d2010-03-15 21:23:04 +000092 // Returns true iff the listener is interested in an explanation of
93 // the match result. A matcher's MatchAndExplain() method can use
94 // this information to avoid generating the explanation when no one
95 // intends to hear it.
96 bool IsInterested() const { return stream_ != NULL; }
97
zhanyong.wan82113312010-01-08 21:55:40 +000098 private:
99 ::std::ostream* const stream_;
100
101 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
102};
103
104inline MatchResultListener::~MatchResultListener() {
105}
106
shiqiane35fdd92008-12-10 05:08:54 +0000107// The implementation of a matcher.
108template <typename T>
109class MatcherInterface {
110 public:
111 virtual ~MatcherInterface() {}
112
zhanyong.wan82113312010-01-08 21:55:40 +0000113 // Returns true iff the matcher matches x; also explains the match
zhanyong.wana862f1d2010-03-15 21:23:04 +0000114 // result to 'listener', in the form of a non-restrictive relative
115 // clause ("which ...", "whose ...", etc) that describes x. For
116 // example, the MatchAndExplain() method of the Pointee(...) matcher
117 // should generate an explanation like "which points to ...".
zhanyong.wan82113312010-01-08 21:55:40 +0000118 //
zhanyong.wandb22c222010-01-28 21:52:29 +0000119 // You should override this method when defining a new matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000120 //
121 // It's the responsibility of the caller (Google Mock) to guarantee
122 // that 'listener' is not NULL. This helps to simplify a matcher's
123 // implementation when it doesn't care about the performance, as it
124 // can talk to 'listener' without checking its validity first.
125 // However, in order to implement dummy listeners efficiently,
126 // listener->stream() may be NULL.
zhanyong.wandb22c222010-01-28 21:52:29 +0000127 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
shiqiane35fdd92008-12-10 05:08:54 +0000128
zhanyong.wana862f1d2010-03-15 21:23:04 +0000129 // Describes this matcher to an ostream. The function should print
130 // a verb phrase that describes the property a value matching this
131 // matcher should have. The subject of the verb phrase is the value
132 // being matched. For example, the DescribeTo() method of the Gt(7)
133 // matcher prints "is greater than 7".
shiqiane35fdd92008-12-10 05:08:54 +0000134 virtual void DescribeTo(::std::ostream* os) const = 0;
135
136 // Describes the negation of this matcher to an ostream. For
137 // example, if the description of this matcher is "is greater than
138 // 7", the negated description could be "is not greater than 7".
139 // You are not required to override this when implementing
140 // MatcherInterface, but it is highly advised so that your matcher
141 // can produce good error messages.
142 virtual void DescribeNegationTo(::std::ostream* os) const {
143 *os << "not (";
144 DescribeTo(os);
145 *os << ")";
146 }
shiqiane35fdd92008-12-10 05:08:54 +0000147};
148
149namespace internal {
150
zhanyong.wan82113312010-01-08 21:55:40 +0000151// A match result listener that ignores the explanation.
152class DummyMatchResultListener : public MatchResultListener {
153 public:
154 DummyMatchResultListener() : MatchResultListener(NULL) {}
155
156 private:
157 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
158};
159
160// A match result listener that forwards the explanation to a given
161// ostream. The difference between this and MatchResultListener is
162// that the former is concrete.
163class StreamMatchResultListener : public MatchResultListener {
164 public:
165 explicit StreamMatchResultListener(::std::ostream* os)
166 : MatchResultListener(os) {}
167
168 private:
169 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
170};
171
172// A match result listener that stores the explanation in a string.
173class StringMatchResultListener : public MatchResultListener {
174 public:
175 StringMatchResultListener() : MatchResultListener(&ss_) {}
176
177 // Returns the explanation heard so far.
178 internal::string str() const { return ss_.str(); }
179
180 private:
181 ::std::stringstream ss_;
182
183 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
184};
185
shiqiane35fdd92008-12-10 05:08:54 +0000186// An internal class for implementing Matcher<T>, which will derive
187// from it. We put functionalities common to all Matcher<T>
188// specializations here to avoid code duplication.
189template <typename T>
190class MatcherBase {
191 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000192 // Returns true iff the matcher matches x; also explains the match
193 // result to 'listener'.
194 bool MatchAndExplain(T x, MatchResultListener* listener) const {
195 return impl_->MatchAndExplain(x, listener);
196 }
197
shiqiane35fdd92008-12-10 05:08:54 +0000198 // Returns true iff this matcher matches x.
zhanyong.wan82113312010-01-08 21:55:40 +0000199 bool Matches(T x) const {
200 DummyMatchResultListener dummy;
201 return MatchAndExplain(x, &dummy);
202 }
shiqiane35fdd92008-12-10 05:08:54 +0000203
204 // Describes this matcher to an ostream.
205 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
206
207 // Describes the negation of this matcher to an ostream.
208 void DescribeNegationTo(::std::ostream* os) const {
209 impl_->DescribeNegationTo(os);
210 }
211
212 // Explains why x matches, or doesn't match, the matcher.
213 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000214 StreamMatchResultListener listener(os);
215 MatchAndExplain(x, &listener);
shiqiane35fdd92008-12-10 05:08:54 +0000216 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000217
shiqiane35fdd92008-12-10 05:08:54 +0000218 protected:
219 MatcherBase() {}
220
221 // Constructs a matcher from its implementation.
222 explicit MatcherBase(const MatcherInterface<T>* impl)
223 : impl_(impl) {}
224
225 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000226
shiqiane35fdd92008-12-10 05:08:54 +0000227 private:
228 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
229 // interfaces. The former dynamically allocates a chunk of memory
230 // to hold the reference count, while the latter tracks all
231 // references using a circular linked list without allocating
232 // memory. It has been observed that linked_ptr performs better in
233 // typical scenarios. However, shared_ptr can out-perform
234 // linked_ptr when there are many more uses of the copy constructor
235 // than the default constructor.
236 //
237 // If performance becomes a problem, we should see if using
238 // shared_ptr helps.
239 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
240};
241
shiqiane35fdd92008-12-10 05:08:54 +0000242} // namespace internal
243
244// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
245// object that can check whether a value of type T matches. The
246// implementation of Matcher<T> is just a linked_ptr to const
247// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
248// from Matcher!
249template <typename T>
250class Matcher : public internal::MatcherBase<T> {
251 public:
252 // Constructs a null matcher. Needed for storing Matcher objects in
253 // STL containers.
254 Matcher() {}
255
256 // Constructs a matcher from its implementation.
257 explicit Matcher(const MatcherInterface<T>* impl)
258 : internal::MatcherBase<T>(impl) {}
259
zhanyong.wan18490652009-05-11 18:54:08 +0000260 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000261 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
262 Matcher(T value); // NOLINT
263};
264
265// The following two specializations allow the user to write str
266// instead of Eq(str) and "foo" instead of Eq("foo") when a string
267// matcher is expected.
268template <>
269class Matcher<const internal::string&>
270 : public internal::MatcherBase<const internal::string&> {
271 public:
272 Matcher() {}
273
274 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
275 : internal::MatcherBase<const internal::string&>(impl) {}
276
277 // Allows the user to write str instead of Eq(str) sometimes, where
278 // str is a string object.
279 Matcher(const internal::string& s); // NOLINT
280
281 // Allows the user to write "foo" instead of Eq("foo") sometimes.
282 Matcher(const char* s); // NOLINT
283};
284
285template <>
286class Matcher<internal::string>
287 : public internal::MatcherBase<internal::string> {
288 public:
289 Matcher() {}
290
291 explicit Matcher(const MatcherInterface<internal::string>* impl)
292 : internal::MatcherBase<internal::string>(impl) {}
293
294 // Allows the user to write str instead of Eq(str) sometimes, where
295 // str is a string object.
296 Matcher(const internal::string& s); // NOLINT
297
298 // Allows the user to write "foo" instead of Eq("foo") sometimes.
299 Matcher(const char* s); // NOLINT
300};
301
302// The PolymorphicMatcher class template makes it easy to implement a
303// polymorphic matcher (i.e. a matcher that can match values of more
304// than one type, e.g. Eq(n) and NotNull()).
305//
zhanyong.wandb22c222010-01-28 21:52:29 +0000306// To define a polymorphic matcher, a user should provide an Impl
307// class that has a DescribeTo() method and a DescribeNegationTo()
308// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000309//
zhanyong.wandb22c222010-01-28 21:52:29 +0000310// bool MatchAndExplain(const Value& value,
311// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000312//
313// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000314template <class Impl>
315class PolymorphicMatcher {
316 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000317 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000318
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000319 // Returns a mutable reference to the underlying matcher
320 // implementation object.
321 Impl& mutable_impl() { return impl_; }
322
323 // Returns an immutable reference to the underlying matcher
324 // implementation object.
325 const Impl& impl() const { return impl_; }
326
shiqiane35fdd92008-12-10 05:08:54 +0000327 template <typename T>
328 operator Matcher<T>() const {
329 return Matcher<T>(new MonomorphicImpl<T>(impl_));
330 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000331
shiqiane35fdd92008-12-10 05:08:54 +0000332 private:
333 template <typename T>
334 class MonomorphicImpl : public MatcherInterface<T> {
335 public:
336 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
337
shiqiane35fdd92008-12-10 05:08:54 +0000338 virtual void DescribeTo(::std::ostream* os) const {
339 impl_.DescribeTo(os);
340 }
341
342 virtual void DescribeNegationTo(::std::ostream* os) const {
343 impl_.DescribeNegationTo(os);
344 }
345
zhanyong.wan82113312010-01-08 21:55:40 +0000346 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000347 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000348 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000349
shiqiane35fdd92008-12-10 05:08:54 +0000350 private:
351 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000352
353 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000354 };
355
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000356 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000357
358 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000359};
360
361// Creates a matcher from its implementation. This is easier to use
362// than the Matcher<T> constructor as it doesn't require you to
363// explicitly write the template argument, e.g.
364//
365// MakeMatcher(foo);
366// vs
367// Matcher<const string&>(foo);
368template <typename T>
369inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
370 return Matcher<T>(impl);
371};
372
373// Creates a polymorphic matcher from its implementation. This is
374// easier to use than the PolymorphicMatcher<Impl> constructor as it
375// doesn't require you to explicitly write the template argument, e.g.
376//
377// MakePolymorphicMatcher(foo);
378// vs
379// PolymorphicMatcher<TypeOfFoo>(foo);
380template <class Impl>
381inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
382 return PolymorphicMatcher<Impl>(impl);
383}
384
385// In order to be safe and clear, casting between different matcher
386// types is done explicitly via MatcherCast<T>(m), which takes a
387// matcher m and returns a Matcher<T>. It compiles only when T can be
388// statically converted to the argument type of m.
389template <typename T, typename M>
390Matcher<T> MatcherCast(M m);
391
zhanyong.wan18490652009-05-11 18:54:08 +0000392// Implements SafeMatcherCast().
393//
zhanyong.wan95b12332009-09-25 18:55:50 +0000394// We use an intermediate class to do the actual safe casting as Nokia's
395// Symbian compiler cannot decide between
396// template <T, M> ... (M) and
397// template <T, U> ... (const Matcher<U>&)
398// for function templates but can for member function templates.
399template <typename T>
400class SafeMatcherCastImpl {
401 public:
402 // This overload handles polymorphic matchers only since monomorphic
403 // matchers are handled by the next one.
404 template <typename M>
405 static inline Matcher<T> Cast(M polymorphic_matcher) {
406 return Matcher<T>(polymorphic_matcher);
407 }
zhanyong.wan18490652009-05-11 18:54:08 +0000408
zhanyong.wan95b12332009-09-25 18:55:50 +0000409 // This overload handles monomorphic matchers.
410 //
411 // In general, if type T can be implicitly converted to type U, we can
412 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
413 // contravariant): just keep a copy of the original Matcher<U>, convert the
414 // argument from type T to U, and then pass it to the underlying Matcher<U>.
415 // The only exception is when U is a reference and T is not, as the
416 // underlying Matcher<U> may be interested in the argument's address, which
417 // is not preserved in the conversion from T to U.
418 template <typename U>
419 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
420 // Enforce that T can be implicitly converted to U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000421 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
zhanyong.wan95b12332009-09-25 18:55:50 +0000422 T_must_be_implicitly_convertible_to_U);
423 // Enforce that we are not converting a non-reference type T to a reference
424 // type U.
zhanyong.wan02f71062010-05-10 17:14:29 +0000425 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000426 internal::is_reference<T>::value || !internal::is_reference<U>::value,
427 cannot_convert_non_referentce_arg_to_reference);
428 // In case both T and U are arithmetic types, enforce that the
429 // conversion is not lossy.
zhanyong.wan02f71062010-05-10 17:14:29 +0000430 typedef GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(T)) RawT;
431 typedef GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(U)) RawU;
zhanyong.wan95b12332009-09-25 18:55:50 +0000432 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
433 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
zhanyong.wan02f71062010-05-10 17:14:29 +0000434 GTEST_COMPILE_ASSERT_(
zhanyong.wan95b12332009-09-25 18:55:50 +0000435 kTIsOther || kUIsOther ||
436 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
437 conversion_of_arithmetic_types_must_be_lossless);
438 return MatcherCast<T>(matcher);
439 }
440};
441
442template <typename T, typename M>
443inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
444 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000445}
446
shiqiane35fdd92008-12-10 05:08:54 +0000447// A<T>() returns a matcher that matches any value of type T.
448template <typename T>
449Matcher<T> A();
450
451// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
452// and MUST NOT BE USED IN USER CODE!!!
453namespace internal {
454
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000455// If the explanation is not empty, prints it to the ostream.
456inline void PrintIfNotEmpty(const internal::string& explanation,
457 std::ostream* os) {
458 if (explanation != "" && os != NULL) {
459 *os << ", " << explanation;
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000460 }
461}
462
463// Matches the value against the given matcher, prints the value and explains
464// the match result to the listener. Returns the match result.
465// 'listener' must not be NULL.
466// Value cannot be passed by const reference, because some matchers take a
467// non-const argument.
468template <typename Value, typename T>
469bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
470 MatchResultListener* listener) {
471 if (!listener->IsInterested()) {
472 // If the listener is not interested, we do not need to construct the
473 // inner explanation.
474 return matcher.Matches(value);
475 }
476
477 StringMatchResultListener inner_listener;
478 const bool match = matcher.MatchAndExplain(value, &inner_listener);
479
480 UniversalPrint(value, listener->stream());
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000481 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000482
483 return match;
484}
485
shiqiane35fdd92008-12-10 05:08:54 +0000486// An internal helper class for doing compile-time loop on a tuple's
487// fields.
488template <size_t N>
489class TuplePrefix {
490 public:
491 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
492 // iff the first N fields of matcher_tuple matches the first N
493 // fields of value_tuple, respectively.
494 template <typename MatcherTuple, typename ValueTuple>
495 static bool Matches(const MatcherTuple& matcher_tuple,
496 const ValueTuple& value_tuple) {
497 using ::std::tr1::get;
498 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
499 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
500 }
501
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000502 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
shiqiane35fdd92008-12-10 05:08:54 +0000503 // describes failures in matching the first N fields of matchers
504 // against the first N fields of values. If there is no failure,
505 // nothing will be streamed to os.
506 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000507 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
508 const ValueTuple& values,
509 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000510 using ::std::tr1::tuple_element;
511 using ::std::tr1::get;
512
513 // First, describes failures in the first N - 1 fields.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000514 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
shiqiane35fdd92008-12-10 05:08:54 +0000515
516 // Then describes the failure (if any) in the (N - 1)-th (0-based)
517 // field.
518 typename tuple_element<N - 1, MatcherTuple>::type matcher =
519 get<N - 1>(matchers);
520 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
521 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000522 StringMatchResultListener listener;
523 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000524 // TODO(wan): include in the message the name of the parameter
525 // as used in MOCK_METHOD*() when possible.
526 *os << " Expected arg #" << N - 1 << ": ";
527 get<N - 1>(matchers).DescribeTo(os);
528 *os << "\n Actual: ";
529 // We remove the reference in type Value to prevent the
530 // universal printer from printing the address of value, which
531 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000532 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000533 // the address is interesting.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000534 internal::UniversalPrint(value, os);
535 PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000536 *os << "\n";
537 }
538 }
539};
540
541// The base case.
542template <>
543class TuplePrefix<0> {
544 public:
545 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000546 static bool Matches(const MatcherTuple& /* matcher_tuple */,
547 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000548 return true;
549 }
550
551 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000552 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
553 const ValueTuple& /* values */,
554 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000555};
556
557// TupleMatches(matcher_tuple, value_tuple) returns true iff all
558// matchers in matcher_tuple match the corresponding fields in
559// value_tuple. It is a compiler error if matcher_tuple and
560// value_tuple have different number of fields or incompatible field
561// types.
562template <typename MatcherTuple, typename ValueTuple>
563bool TupleMatches(const MatcherTuple& matcher_tuple,
564 const ValueTuple& value_tuple) {
565 using ::std::tr1::tuple_size;
566 // Makes sure that matcher_tuple and value_tuple have the same
567 // number of fields.
zhanyong.wan02f71062010-05-10 17:14:29 +0000568 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
zhanyong.wane0d051e2009-02-19 00:33:37 +0000569 tuple_size<ValueTuple>::value,
570 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000571 return TuplePrefix<tuple_size<ValueTuple>::value>::
572 Matches(matcher_tuple, value_tuple);
573}
574
575// Describes failures in matching matchers against values. If there
576// is no failure, nothing will be streamed to os.
577template <typename MatcherTuple, typename ValueTuple>
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000578void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
579 const ValueTuple& values,
580 ::std::ostream* os) {
shiqiane35fdd92008-12-10 05:08:54 +0000581 using ::std::tr1::tuple_size;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000582 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
shiqiane35fdd92008-12-10 05:08:54 +0000583 matchers, values, os);
584}
585
586// The MatcherCastImpl class template is a helper for implementing
587// MatcherCast(). We need this helper in order to partially
588// specialize the implementation of MatcherCast() (C++ allows
589// class/struct templates to be partially specialized, but not
590// function templates.).
591
592// This general version is used when MatcherCast()'s argument is a
593// polymorphic matcher (i.e. something that can be converted to a
594// Matcher but is not one yet; for example, Eq(value)).
595template <typename T, typename M>
596class MatcherCastImpl {
597 public:
598 static Matcher<T> Cast(M polymorphic_matcher) {
599 return Matcher<T>(polymorphic_matcher);
600 }
601};
602
603// This more specialized version is used when MatcherCast()'s argument
604// is already a Matcher. This only compiles when type T can be
605// statically converted to type U.
606template <typename T, typename U>
607class MatcherCastImpl<T, Matcher<U> > {
608 public:
609 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
610 return Matcher<T>(new Impl(source_matcher));
611 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000612
shiqiane35fdd92008-12-10 05:08:54 +0000613 private:
614 class Impl : public MatcherInterface<T> {
615 public:
616 explicit Impl(const Matcher<U>& source_matcher)
617 : source_matcher_(source_matcher) {}
618
619 // We delegate the matching logic to the source matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000620 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
621 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000622 }
623
624 virtual void DescribeTo(::std::ostream* os) const {
625 source_matcher_.DescribeTo(os);
626 }
627
628 virtual void DescribeNegationTo(::std::ostream* os) const {
629 source_matcher_.DescribeNegationTo(os);
630 }
631
shiqiane35fdd92008-12-10 05:08:54 +0000632 private:
633 const Matcher<U> source_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000634
635 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000636 };
637};
638
639// This even more specialized version is used for efficiently casting
640// a matcher to its own type.
641template <typename T>
642class MatcherCastImpl<T, Matcher<T> > {
643 public:
644 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
645};
646
647// Implements A<T>().
648template <typename T>
649class AnyMatcherImpl : public MatcherInterface<T> {
650 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000651 virtual bool MatchAndExplain(
652 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000653 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
654 virtual void DescribeNegationTo(::std::ostream* os) const {
655 // This is mostly for completeness' safe, as it's not very useful
656 // to write Not(A<bool>()). However we cannot completely rule out
657 // such a possibility, and it doesn't hurt to be prepared.
658 *os << "never matches";
659 }
660};
661
662// Implements _, a matcher that matches any value of any
663// type. This is a polymorphic matcher, so we need a template type
664// conversion operator to make it appearing as a Matcher<T> for any
665// type T.
666class AnythingMatcher {
667 public:
668 template <typename T>
669 operator Matcher<T>() const { return A<T>(); }
670};
671
672// Implements a matcher that compares a given value with a
673// pre-supplied value using one of the ==, <=, <, etc, operators. The
674// two values being compared don't have to have the same type.
675//
676// The matcher defined here is polymorphic (for example, Eq(5) can be
677// used to match an int, a short, a double, etc). Therefore we use
678// a template type conversion operator in the implementation.
679//
680// We define this as a macro in order to eliminate duplicated source
681// code.
682//
683// The following template definition assumes that the Rhs parameter is
684// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000685#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_( \
686 name, op, relation, negated_relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000687 template <typename Rhs> class name##Matcher { \
688 public: \
689 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
690 template <typename Lhs> \
691 operator Matcher<Lhs>() const { \
692 return MakeMatcher(new Impl<Lhs>(rhs_)); \
693 } \
694 private: \
695 template <typename Lhs> \
696 class Impl : public MatcherInterface<Lhs> { \
697 public: \
698 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
zhanyong.wan82113312010-01-08 21:55:40 +0000699 virtual bool MatchAndExplain(\
700 Lhs lhs, MatchResultListener* /* listener */) const { \
701 return lhs op rhs_; \
702 } \
shiqiane35fdd92008-12-10 05:08:54 +0000703 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000704 *os << relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000705 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000706 } \
707 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000708 *os << negated_relation " "; \
vladloseve2e8ba42010-05-13 18:16:03 +0000709 UniversalPrint(rhs_, os); \
shiqiane35fdd92008-12-10 05:08:54 +0000710 } \
711 private: \
712 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000713 GTEST_DISALLOW_ASSIGN_(Impl); \
shiqiane35fdd92008-12-10 05:08:54 +0000714 }; \
715 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000716 GTEST_DISALLOW_ASSIGN_(name##Matcher); \
shiqiane35fdd92008-12-10 05:08:54 +0000717 }
718
719// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
720// respectively.
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000721GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "is equal to", "isn't equal to");
722GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "is >=", "isn't >=");
723GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "is >", "isn't >");
724GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "is <=", "isn't <=");
725GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "is <", "isn't <");
726GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "isn't equal to", "is equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000727
zhanyong.wane0d051e2009-02-19 00:33:37 +0000728#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000729
vladlosev79b83502009-11-18 00:43:37 +0000730// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000731// pointer that is NULL.
732class IsNullMatcher {
733 public:
vladlosev79b83502009-11-18 00:43:37 +0000734 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000735 bool MatchAndExplain(const Pointer& p,
736 MatchResultListener* /* listener */) const {
737 return GetRawPointer(p) == NULL;
738 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000739
740 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
741 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000742 *os << "isn't NULL";
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000743 }
744};
745
vladlosev79b83502009-11-18 00:43:37 +0000746// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000747// pointer that is not NULL.
748class NotNullMatcher {
749 public:
vladlosev79b83502009-11-18 00:43:37 +0000750 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000751 bool MatchAndExplain(const Pointer& p,
752 MatchResultListener* /* listener */) const {
753 return GetRawPointer(p) != NULL;
754 }
shiqiane35fdd92008-12-10 05:08:54 +0000755
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000756 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
shiqiane35fdd92008-12-10 05:08:54 +0000757 void DescribeNegationTo(::std::ostream* os) const {
758 *os << "is NULL";
759 }
760};
761
762// Ref(variable) matches any argument that is a reference to
763// 'variable'. This matcher is polymorphic as it can match any
764// super type of the type of 'variable'.
765//
766// The RefMatcher template class implements Ref(variable). It can
767// only be instantiated with a reference type. This prevents a user
768// from mistakenly using Ref(x) to match a non-reference function
769// argument. For example, the following will righteously cause a
770// compiler error:
771//
772// int n;
773// Matcher<int> m1 = Ref(n); // This won't compile.
774// Matcher<int&> m2 = Ref(n); // This will compile.
775template <typename T>
776class RefMatcher;
777
778template <typename T>
779class RefMatcher<T&> {
780 // Google Mock is a generic framework and thus needs to support
781 // mocking any function types, including those that take non-const
782 // reference arguments. Therefore the template parameter T (and
783 // Super below) can be instantiated to either a const type or a
784 // non-const type.
785 public:
786 // RefMatcher() takes a T& instead of const T&, as we want the
787 // compiler to catch using Ref(const_value) as a matcher for a
788 // non-const reference.
789 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
790
791 template <typename Super>
792 operator Matcher<Super&>() const {
793 // By passing object_ (type T&) to Impl(), which expects a Super&,
794 // we make sure that Super is a super type of T. In particular,
795 // this catches using Ref(const_value) as a matcher for a
796 // non-const reference, as you cannot implicitly convert a const
797 // reference to a non-const reference.
798 return MakeMatcher(new Impl<Super>(object_));
799 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000800
shiqiane35fdd92008-12-10 05:08:54 +0000801 private:
802 template <typename Super>
803 class Impl : public MatcherInterface<Super&> {
804 public:
805 explicit Impl(Super& x) : object_(x) {} // NOLINT
806
zhanyong.wandb22c222010-01-28 21:52:29 +0000807 // MatchAndExplain() takes a Super& (as opposed to const Super&)
808 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +0000809 virtual bool MatchAndExplain(
810 Super& x, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000811 *listener << "which is located @" << static_cast<const void*>(&x);
zhanyong.wan82113312010-01-08 21:55:40 +0000812 return &x == &object_;
813 }
shiqiane35fdd92008-12-10 05:08:54 +0000814
815 virtual void DescribeTo(::std::ostream* os) const {
816 *os << "references the variable ";
817 UniversalPrinter<Super&>::Print(object_, os);
818 }
819
820 virtual void DescribeNegationTo(::std::ostream* os) const {
821 *os << "does not reference the variable ";
822 UniversalPrinter<Super&>::Print(object_, os);
823 }
824
shiqiane35fdd92008-12-10 05:08:54 +0000825 private:
826 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000827
828 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000829 };
830
831 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000832
833 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000834};
835
836// Polymorphic helper functions for narrow and wide string matchers.
837inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
838 return String::CaseInsensitiveCStringEquals(lhs, rhs);
839}
840
841inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
842 const wchar_t* rhs) {
843 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
844}
845
846// String comparison for narrow or wide strings that can have embedded NUL
847// characters.
848template <typename StringType>
849bool CaseInsensitiveStringEquals(const StringType& s1,
850 const StringType& s2) {
851 // Are the heads equal?
852 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
853 return false;
854 }
855
856 // Skip the equal heads.
857 const typename StringType::value_type nul = 0;
858 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
859
860 // Are we at the end of either s1 or s2?
861 if (i1 == StringType::npos || i2 == StringType::npos) {
862 return i1 == i2;
863 }
864
865 // Are the tails equal?
866 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
867}
868
869// String matchers.
870
871// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
872template <typename StringType>
873class StrEqualityMatcher {
874 public:
875 typedef typename StringType::const_pointer ConstCharPointer;
876
877 StrEqualityMatcher(const StringType& str, bool expect_eq,
878 bool case_sensitive)
879 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
880
881 // When expect_eq_ is true, returns true iff s is equal to string_;
882 // otherwise returns true iff s is not equal to string_.
zhanyong.wandb22c222010-01-28 21:52:29 +0000883 bool MatchAndExplain(ConstCharPointer s,
884 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +0000885 if (s == NULL) {
886 return !expect_eq_;
887 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000888 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000889 }
890
zhanyong.wandb22c222010-01-28 21:52:29 +0000891 bool MatchAndExplain(const StringType& s,
892 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000893 const bool eq = case_sensitive_ ? s == string_ :
894 CaseInsensitiveStringEquals(s, string_);
895 return expect_eq_ == eq;
896 }
897
898 void DescribeTo(::std::ostream* os) const {
899 DescribeToHelper(expect_eq_, os);
900 }
901
902 void DescribeNegationTo(::std::ostream* os) const {
903 DescribeToHelper(!expect_eq_, os);
904 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000905
shiqiane35fdd92008-12-10 05:08:54 +0000906 private:
907 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000908 *os << (expect_eq ? "is " : "isn't ");
shiqiane35fdd92008-12-10 05:08:54 +0000909 *os << "equal to ";
910 if (!case_sensitive_) {
911 *os << "(ignoring case) ";
912 }
vladloseve2e8ba42010-05-13 18:16:03 +0000913 UniversalPrint(string_, os);
shiqiane35fdd92008-12-10 05:08:54 +0000914 }
915
916 const StringType string_;
917 const bool expect_eq_;
918 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000919
920 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000921};
922
923// Implements the polymorphic HasSubstr(substring) matcher, which
924// can be used as a Matcher<T> as long as T can be converted to a
925// string.
926template <typename StringType>
927class HasSubstrMatcher {
928 public:
929 typedef typename StringType::const_pointer ConstCharPointer;
930
931 explicit HasSubstrMatcher(const StringType& substring)
932 : substring_(substring) {}
933
934 // These overloaded methods allow HasSubstr(substring) to be used as a
935 // Matcher<T> as long as T can be converted to string. Returns true
936 // iff s contains substring_ as a substring.
zhanyong.wandb22c222010-01-28 21:52:29 +0000937 bool MatchAndExplain(ConstCharPointer s,
938 MatchResultListener* listener) const {
939 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000940 }
941
zhanyong.wandb22c222010-01-28 21:52:29 +0000942 bool MatchAndExplain(const StringType& s,
943 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000944 return s.find(substring_) != StringType::npos;
945 }
946
947 // Describes what this matcher matches.
948 void DescribeTo(::std::ostream* os) const {
949 *os << "has substring ";
vladloseve2e8ba42010-05-13 18:16:03 +0000950 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +0000951 }
952
953 void DescribeNegationTo(::std::ostream* os) const {
954 *os << "has no substring ";
vladloseve2e8ba42010-05-13 18:16:03 +0000955 UniversalPrint(substring_, os);
shiqiane35fdd92008-12-10 05:08:54 +0000956 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000957
shiqiane35fdd92008-12-10 05:08:54 +0000958 private:
959 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000960
961 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000962};
963
964// Implements the polymorphic StartsWith(substring) matcher, which
965// can be used as a Matcher<T> as long as T can be converted to a
966// string.
967template <typename StringType>
968class StartsWithMatcher {
969 public:
970 typedef typename StringType::const_pointer ConstCharPointer;
971
972 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
973 }
974
975 // These overloaded methods allow StartsWith(prefix) to be used as a
976 // Matcher<T> as long as T can be converted to string. Returns true
977 // iff s starts with prefix_.
zhanyong.wandb22c222010-01-28 21:52:29 +0000978 bool MatchAndExplain(ConstCharPointer s,
979 MatchResultListener* listener) const {
980 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000981 }
982
zhanyong.wandb22c222010-01-28 21:52:29 +0000983 bool MatchAndExplain(const StringType& s,
984 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000985 return s.length() >= prefix_.length() &&
986 s.substr(0, prefix_.length()) == prefix_;
987 }
988
989 void DescribeTo(::std::ostream* os) const {
990 *os << "starts with ";
vladloseve2e8ba42010-05-13 18:16:03 +0000991 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +0000992 }
993
994 void DescribeNegationTo(::std::ostream* os) const {
995 *os << "doesn't start with ";
vladloseve2e8ba42010-05-13 18:16:03 +0000996 UniversalPrint(prefix_, os);
shiqiane35fdd92008-12-10 05:08:54 +0000997 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000998
shiqiane35fdd92008-12-10 05:08:54 +0000999 private:
1000 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001001
1002 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001003};
1004
1005// Implements the polymorphic EndsWith(substring) matcher, which
1006// can be used as a Matcher<T> as long as T can be converted to a
1007// string.
1008template <typename StringType>
1009class EndsWithMatcher {
1010 public:
1011 typedef typename StringType::const_pointer ConstCharPointer;
1012
1013 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1014
1015 // These overloaded methods allow EndsWith(suffix) to be used as a
1016 // Matcher<T> as long as T can be converted to string. Returns true
1017 // iff s ends with suffix_.
zhanyong.wandb22c222010-01-28 21:52:29 +00001018 bool MatchAndExplain(ConstCharPointer s,
1019 MatchResultListener* listener) const {
1020 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001021 }
1022
zhanyong.wandb22c222010-01-28 21:52:29 +00001023 bool MatchAndExplain(const StringType& s,
1024 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001025 return s.length() >= suffix_.length() &&
1026 s.substr(s.length() - suffix_.length()) == suffix_;
1027 }
1028
1029 void DescribeTo(::std::ostream* os) const {
1030 *os << "ends with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001031 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001032 }
1033
1034 void DescribeNegationTo(::std::ostream* os) const {
1035 *os << "doesn't end with ";
vladloseve2e8ba42010-05-13 18:16:03 +00001036 UniversalPrint(suffix_, os);
shiqiane35fdd92008-12-10 05:08:54 +00001037 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001038
shiqiane35fdd92008-12-10 05:08:54 +00001039 private:
1040 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001041
1042 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001043};
1044
shiqiane35fdd92008-12-10 05:08:54 +00001045// Implements polymorphic matchers MatchesRegex(regex) and
1046// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1047// T can be converted to a string.
1048class MatchesRegexMatcher {
1049 public:
1050 MatchesRegexMatcher(const RE* regex, bool full_match)
1051 : regex_(regex), full_match_(full_match) {}
1052
1053 // These overloaded methods allow MatchesRegex(regex) to be used as
1054 // a Matcher<T> as long as T can be converted to string. Returns
1055 // true iff s matches regular expression regex. When full_match_ is
1056 // true, a full match is done; otherwise a partial match is done.
zhanyong.wandb22c222010-01-28 21:52:29 +00001057 bool MatchAndExplain(const char* s,
1058 MatchResultListener* listener) const {
1059 return s != NULL && MatchAndExplain(internal::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001060 }
1061
zhanyong.wandb22c222010-01-28 21:52:29 +00001062 bool MatchAndExplain(const internal::string& s,
1063 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001064 return full_match_ ? RE::FullMatch(s, *regex_) :
1065 RE::PartialMatch(s, *regex_);
1066 }
1067
1068 void DescribeTo(::std::ostream* os) const {
1069 *os << (full_match_ ? "matches" : "contains")
1070 << " regular expression ";
1071 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1072 }
1073
1074 void DescribeNegationTo(::std::ostream* os) const {
1075 *os << "doesn't " << (full_match_ ? "match" : "contain")
1076 << " regular expression ";
1077 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1078 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001079
shiqiane35fdd92008-12-10 05:08:54 +00001080 private:
1081 const internal::linked_ptr<const RE> regex_;
1082 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001083
1084 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001085};
1086
shiqiane35fdd92008-12-10 05:08:54 +00001087// Implements a matcher that compares the two fields of a 2-tuple
1088// using one of the ==, <=, <, etc, operators. The two fields being
1089// compared don't have to have the same type.
1090//
1091// The matcher defined here is polymorphic (for example, Eq() can be
1092// used to match a tuple<int, short>, a tuple<const long&, double>,
1093// etc). Therefore we use a template type conversion operator in the
1094// implementation.
1095//
1096// We define this as a macro in order to eliminate duplicated source
1097// code.
zhanyong.wan2661c682009-06-09 05:42:12 +00001098#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op) \
shiqiane35fdd92008-12-10 05:08:54 +00001099 class name##2Matcher { \
1100 public: \
1101 template <typename T1, typename T2> \
1102 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
1103 return MakeMatcher(new Impl<T1, T2>); \
1104 } \
1105 private: \
1106 template <typename T1, typename T2> \
1107 class Impl : public MatcherInterface<const ::std::tr1::tuple<T1, T2>&> { \
1108 public: \
zhanyong.wan82113312010-01-08 21:55:40 +00001109 virtual bool MatchAndExplain( \
1110 const ::std::tr1::tuple<T1, T2>& args, \
1111 MatchResultListener* /* listener */) const { \
shiqiane35fdd92008-12-10 05:08:54 +00001112 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
1113 } \
1114 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +00001115 *os << "are a pair (x, y) where x " #op " y"; \
shiqiane35fdd92008-12-10 05:08:54 +00001116 } \
1117 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +00001118 *os << "are a pair (x, y) where x " #op " y is false"; \
shiqiane35fdd92008-12-10 05:08:54 +00001119 } \
1120 }; \
1121 }
1122
1123// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wan2661c682009-06-09 05:42:12 +00001124GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==);
1125GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ge, >=);
1126GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Gt, >);
1127GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Le, <=);
1128GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Lt, <);
1129GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=);
shiqiane35fdd92008-12-10 05:08:54 +00001130
zhanyong.wane0d051e2009-02-19 00:33:37 +00001131#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +00001132
zhanyong.wanc6a41232009-05-13 23:38:40 +00001133// Implements the Not(...) matcher for a particular argument type T.
1134// We do not nest it inside the NotMatcher class template, as that
1135// will prevent different instantiations of NotMatcher from sharing
1136// the same NotMatcherImpl<T> class.
1137template <typename T>
1138class NotMatcherImpl : public MatcherInterface<T> {
1139 public:
1140 explicit NotMatcherImpl(const Matcher<T>& matcher)
1141 : matcher_(matcher) {}
1142
zhanyong.wan82113312010-01-08 21:55:40 +00001143 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1144 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001145 }
1146
1147 virtual void DescribeTo(::std::ostream* os) const {
1148 matcher_.DescribeNegationTo(os);
1149 }
1150
1151 virtual void DescribeNegationTo(::std::ostream* os) const {
1152 matcher_.DescribeTo(os);
1153 }
1154
zhanyong.wanc6a41232009-05-13 23:38:40 +00001155 private:
1156 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001157
1158 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001159};
1160
shiqiane35fdd92008-12-10 05:08:54 +00001161// Implements the Not(m) matcher, which matches a value that doesn't
1162// match matcher m.
1163template <typename InnerMatcher>
1164class NotMatcher {
1165 public:
1166 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1167
1168 // This template type conversion operator allows Not(m) to be used
1169 // to match any type m can match.
1170 template <typename T>
1171 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001172 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001173 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001174
shiqiane35fdd92008-12-10 05:08:54 +00001175 private:
shiqiane35fdd92008-12-10 05:08:54 +00001176 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001177
1178 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001179};
1180
zhanyong.wanc6a41232009-05-13 23:38:40 +00001181// Implements the AllOf(m1, m2) matcher for a particular argument type
1182// T. We do not nest it inside the BothOfMatcher class template, as
1183// that will prevent different instantiations of BothOfMatcher from
1184// sharing the same BothOfMatcherImpl<T> class.
1185template <typename T>
1186class BothOfMatcherImpl : public MatcherInterface<T> {
1187 public:
1188 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1189 : matcher1_(matcher1), matcher2_(matcher2) {}
1190
zhanyong.wanc6a41232009-05-13 23:38:40 +00001191 virtual void DescribeTo(::std::ostream* os) const {
1192 *os << "(";
1193 matcher1_.DescribeTo(os);
1194 *os << ") and (";
1195 matcher2_.DescribeTo(os);
1196 *os << ")";
1197 }
1198
1199 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001200 *os << "(";
1201 matcher1_.DescribeNegationTo(os);
1202 *os << ") or (";
1203 matcher2_.DescribeNegationTo(os);
1204 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001205 }
1206
zhanyong.wan82113312010-01-08 21:55:40 +00001207 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1208 // If either matcher1_ or matcher2_ doesn't match x, we only need
1209 // to explain why one of them fails.
1210 StringMatchResultListener listener1;
1211 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1212 *listener << listener1.str();
1213 return false;
1214 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001215
zhanyong.wan82113312010-01-08 21:55:40 +00001216 StringMatchResultListener listener2;
1217 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1218 *listener << listener2.str();
1219 return false;
1220 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001221
zhanyong.wan82113312010-01-08 21:55:40 +00001222 // Otherwise we need to explain why *both* of them match.
1223 const internal::string s1 = listener1.str();
1224 const internal::string s2 = listener2.str();
1225
1226 if (s1 == "") {
1227 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001228 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001229 *listener << s1;
1230 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001231 *listener << ", and " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001232 }
1233 }
zhanyong.wan82113312010-01-08 21:55:40 +00001234 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001235 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001236
zhanyong.wanc6a41232009-05-13 23:38:40 +00001237 private:
1238 const Matcher<T> matcher1_;
1239 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001240
1241 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001242};
1243
shiqiane35fdd92008-12-10 05:08:54 +00001244// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1245// matches a value that matches all of the matchers m_1, ..., and m_n.
1246template <typename Matcher1, typename Matcher2>
1247class BothOfMatcher {
1248 public:
1249 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1250 : matcher1_(matcher1), matcher2_(matcher2) {}
1251
1252 // This template type conversion operator allows a
1253 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1254 // both Matcher1 and Matcher2 can match.
1255 template <typename T>
1256 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001257 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1258 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001259 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001260
shiqiane35fdd92008-12-10 05:08:54 +00001261 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001262 Matcher1 matcher1_;
1263 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001264
1265 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001266};
shiqiane35fdd92008-12-10 05:08:54 +00001267
zhanyong.wanc6a41232009-05-13 23:38:40 +00001268// Implements the AnyOf(m1, m2) matcher for a particular argument type
1269// T. We do not nest it inside the AnyOfMatcher class template, as
1270// that will prevent different instantiations of AnyOfMatcher from
1271// sharing the same EitherOfMatcherImpl<T> class.
1272template <typename T>
1273class EitherOfMatcherImpl : public MatcherInterface<T> {
1274 public:
1275 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1276 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001277
zhanyong.wanc6a41232009-05-13 23:38:40 +00001278 virtual void DescribeTo(::std::ostream* os) const {
1279 *os << "(";
1280 matcher1_.DescribeTo(os);
1281 *os << ") or (";
1282 matcher2_.DescribeTo(os);
1283 *os << ")";
1284 }
shiqiane35fdd92008-12-10 05:08:54 +00001285
zhanyong.wanc6a41232009-05-13 23:38:40 +00001286 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001287 *os << "(";
1288 matcher1_.DescribeNegationTo(os);
1289 *os << ") and (";
1290 matcher2_.DescribeNegationTo(os);
1291 *os << ")";
zhanyong.wanc6a41232009-05-13 23:38:40 +00001292 }
shiqiane35fdd92008-12-10 05:08:54 +00001293
zhanyong.wan82113312010-01-08 21:55:40 +00001294 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1295 // If either matcher1_ or matcher2_ matches x, we just need to
1296 // explain why *one* of them matches.
1297 StringMatchResultListener listener1;
1298 if (matcher1_.MatchAndExplain(x, &listener1)) {
1299 *listener << listener1.str();
1300 return true;
1301 }
1302
1303 StringMatchResultListener listener2;
1304 if (matcher2_.MatchAndExplain(x, &listener2)) {
1305 *listener << listener2.str();
1306 return true;
1307 }
1308
1309 // Otherwise we need to explain why *both* of them fail.
1310 const internal::string s1 = listener1.str();
1311 const internal::string s2 = listener2.str();
1312
1313 if (s1 == "") {
1314 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001315 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001316 *listener << s1;
1317 if (s2 != "") {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001318 *listener << ", and " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001319 }
1320 }
zhanyong.wan82113312010-01-08 21:55:40 +00001321 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001322 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001323
zhanyong.wanc6a41232009-05-13 23:38:40 +00001324 private:
1325 const Matcher<T> matcher1_;
1326 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001327
1328 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001329};
1330
1331// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1332// matches a value that matches at least one of the matchers m_1, ...,
1333// and m_n.
1334template <typename Matcher1, typename Matcher2>
1335class EitherOfMatcher {
1336 public:
1337 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1338 : matcher1_(matcher1), matcher2_(matcher2) {}
1339
1340 // This template type conversion operator allows a
1341 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1342 // both Matcher1 and Matcher2 can match.
1343 template <typename T>
1344 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001345 return Matcher<T>(new EitherOfMatcherImpl<T>(
1346 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001347 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001348
shiqiane35fdd92008-12-10 05:08:54 +00001349 private:
shiqiane35fdd92008-12-10 05:08:54 +00001350 Matcher1 matcher1_;
1351 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001352
1353 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001354};
1355
1356// Used for implementing Truly(pred), which turns a predicate into a
1357// matcher.
1358template <typename Predicate>
1359class TrulyMatcher {
1360 public:
1361 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1362
1363 // This method template allows Truly(pred) to be used as a matcher
1364 // for type T where T is the argument type of predicate 'pred'. The
1365 // argument is passed by reference as the predicate may be
1366 // interested in the address of the argument.
1367 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001368 bool MatchAndExplain(T& x, // NOLINT
1369 MatchResultListener* /* listener */) const {
zhanyong.wan652540a2009-02-23 23:37:29 +00001370#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001371 // MSVC warns about converting a value into bool (warning 4800).
1372#pragma warning(push) // Saves the current warning state.
1373#pragma warning(disable:4800) // Temporarily disables warning 4800.
1374#endif // GTEST_OS_WINDOWS
1375 return predicate_(x);
zhanyong.wan652540a2009-02-23 23:37:29 +00001376#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001377#pragma warning(pop) // Restores the warning state.
1378#endif // GTEST_OS_WINDOWS
1379 }
1380
1381 void DescribeTo(::std::ostream* os) const {
1382 *os << "satisfies the given predicate";
1383 }
1384
1385 void DescribeNegationTo(::std::ostream* os) const {
1386 *os << "doesn't satisfy the given predicate";
1387 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001388
shiqiane35fdd92008-12-10 05:08:54 +00001389 private:
1390 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001391
1392 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001393};
1394
1395// Used for implementing Matches(matcher), which turns a matcher into
1396// a predicate.
1397template <typename M>
1398class MatcherAsPredicate {
1399 public:
1400 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1401
1402 // This template operator() allows Matches(m) to be used as a
1403 // predicate on type T where m is a matcher on type T.
1404 //
1405 // The argument x is passed by reference instead of by value, as
1406 // some matcher may be interested in its address (e.g. as in
1407 // Matches(Ref(n))(x)).
1408 template <typename T>
1409 bool operator()(const T& x) const {
1410 // We let matcher_ commit to a particular type here instead of
1411 // when the MatcherAsPredicate object was constructed. This
1412 // allows us to write Matches(m) where m is a polymorphic matcher
1413 // (e.g. Eq(5)).
1414 //
1415 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1416 // compile when matcher_ has type Matcher<const T&>; if we write
1417 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1418 // when matcher_ has type Matcher<T>; if we just write
1419 // matcher_.Matches(x), it won't compile when matcher_ is
1420 // polymorphic, e.g. Eq(5).
1421 //
1422 // MatcherCast<const T&>() is necessary for making the code work
1423 // in all of the above situations.
1424 return MatcherCast<const T&>(matcher_).Matches(x);
1425 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001426
shiqiane35fdd92008-12-10 05:08:54 +00001427 private:
1428 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001429
1430 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001431};
1432
1433// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1434// argument M must be a type that can be converted to a matcher.
1435template <typename M>
1436class PredicateFormatterFromMatcher {
1437 public:
1438 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1439
1440 // This template () operator allows a PredicateFormatterFromMatcher
1441 // object to act as a predicate-formatter suitable for using with
1442 // Google Test's EXPECT_PRED_FORMAT1() macro.
1443 template <typename T>
1444 AssertionResult operator()(const char* value_text, const T& x) const {
1445 // We convert matcher_ to a Matcher<const T&> *now* instead of
1446 // when the PredicateFormatterFromMatcher object was constructed,
1447 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1448 // know which type to instantiate it to until we actually see the
1449 // type of x here.
1450 //
1451 // We write MatcherCast<const T&>(matcher_) instead of
1452 // Matcher<const T&>(matcher_), as the latter won't compile when
1453 // matcher_ has type Matcher<T> (e.g. An<int>()).
1454 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001455 StringMatchResultListener listener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001456 if (MatchPrintAndExplain(x, matcher, &listener))
shiqiane35fdd92008-12-10 05:08:54 +00001457 return AssertionSuccess();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001458
1459 ::std::stringstream ss;
1460 ss << "Value of: " << value_text << "\n"
1461 << "Expected: ";
1462 matcher.DescribeTo(&ss);
1463 ss << "\n Actual: " << listener.str();
1464 return AssertionFailure() << ss.str();
shiqiane35fdd92008-12-10 05:08:54 +00001465 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001466
shiqiane35fdd92008-12-10 05:08:54 +00001467 private:
1468 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001469
1470 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001471};
1472
1473// A helper function for converting a matcher to a predicate-formatter
1474// without the user needing to explicitly write the type. This is
1475// used for implementing ASSERT_THAT() and EXPECT_THAT().
1476template <typename M>
1477inline PredicateFormatterFromMatcher<M>
1478MakePredicateFormatterFromMatcher(const M& matcher) {
1479 return PredicateFormatterFromMatcher<M>(matcher);
1480}
1481
1482// Implements the polymorphic floating point equality matcher, which
1483// matches two float values using ULP-based approximation. The
1484// template is meant to be instantiated with FloatType being either
1485// float or double.
1486template <typename FloatType>
1487class FloatingEqMatcher {
1488 public:
1489 // Constructor for FloatingEqMatcher.
1490 // The matcher's input will be compared with rhs. The matcher treats two
1491 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1492 // equality comparisons between NANs will always return false.
1493 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1494 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1495
1496 // Implements floating point equality matcher as a Matcher<T>.
1497 template <typename T>
1498 class Impl : public MatcherInterface<T> {
1499 public:
1500 Impl(FloatType rhs, bool nan_eq_nan) :
1501 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1502
zhanyong.wan82113312010-01-08 21:55:40 +00001503 virtual bool MatchAndExplain(T value,
1504 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001505 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1506
1507 // Compares NaNs first, if nan_eq_nan_ is true.
1508 if (nan_eq_nan_ && lhs.is_nan()) {
1509 return rhs.is_nan();
1510 }
1511
1512 return lhs.AlmostEquals(rhs);
1513 }
1514
1515 virtual void DescribeTo(::std::ostream* os) const {
1516 // os->precision() returns the previously set precision, which we
1517 // store to restore the ostream to its original configuration
1518 // after outputting.
1519 const ::std::streamsize old_precision = os->precision(
1520 ::std::numeric_limits<FloatType>::digits10 + 2);
1521 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1522 if (nan_eq_nan_) {
1523 *os << "is NaN";
1524 } else {
1525 *os << "never matches";
1526 }
1527 } else {
1528 *os << "is approximately " << rhs_;
1529 }
1530 os->precision(old_precision);
1531 }
1532
1533 virtual void DescribeNegationTo(::std::ostream* os) const {
1534 // As before, get original precision.
1535 const ::std::streamsize old_precision = os->precision(
1536 ::std::numeric_limits<FloatType>::digits10 + 2);
1537 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1538 if (nan_eq_nan_) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001539 *os << "isn't NaN";
shiqiane35fdd92008-12-10 05:08:54 +00001540 } else {
1541 *os << "is anything";
1542 }
1543 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001544 *os << "isn't approximately " << rhs_;
shiqiane35fdd92008-12-10 05:08:54 +00001545 }
1546 // Restore original precision.
1547 os->precision(old_precision);
1548 }
1549
1550 private:
1551 const FloatType rhs_;
1552 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001553
1554 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001555 };
1556
1557 // The following 3 type conversion operators allow FloatEq(rhs) and
1558 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1559 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1560 // (While Google's C++ coding style doesn't allow arguments passed
1561 // by non-const reference, we may see them in code not conforming to
1562 // the style. Therefore Google Mock needs to support them.)
1563 operator Matcher<FloatType>() const {
1564 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1565 }
1566
1567 operator Matcher<const FloatType&>() const {
1568 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1569 }
1570
1571 operator Matcher<FloatType&>() const {
1572 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1573 }
1574 private:
1575 const FloatType rhs_;
1576 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001577
1578 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001579};
1580
1581// Implements the Pointee(m) matcher for matching a pointer whose
1582// pointee matches matcher m. The pointer can be either raw or smart.
1583template <typename InnerMatcher>
1584class PointeeMatcher {
1585 public:
1586 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1587
1588 // This type conversion operator template allows Pointee(m) to be
1589 // used as a matcher for any pointer type whose pointee type is
1590 // compatible with the inner matcher, where type Pointer can be
1591 // either a raw pointer or a smart pointer.
1592 //
1593 // The reason we do this instead of relying on
1594 // MakePolymorphicMatcher() is that the latter is not flexible
1595 // enough for implementing the DescribeTo() method of Pointee().
1596 template <typename Pointer>
1597 operator Matcher<Pointer>() const {
1598 return MakeMatcher(new Impl<Pointer>(matcher_));
1599 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001600
shiqiane35fdd92008-12-10 05:08:54 +00001601 private:
1602 // The monomorphic implementation that works for a particular pointer type.
1603 template <typename Pointer>
1604 class Impl : public MatcherInterface<Pointer> {
1605 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00001606 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
1607 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001608
1609 explicit Impl(const InnerMatcher& matcher)
1610 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1611
shiqiane35fdd92008-12-10 05:08:54 +00001612 virtual void DescribeTo(::std::ostream* os) const {
1613 *os << "points to a value that ";
1614 matcher_.DescribeTo(os);
1615 }
1616
1617 virtual void DescribeNegationTo(::std::ostream* os) const {
1618 *os << "does not point to a value that ";
1619 matcher_.DescribeTo(os);
1620 }
1621
zhanyong.wan82113312010-01-08 21:55:40 +00001622 virtual bool MatchAndExplain(Pointer pointer,
1623 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001624 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00001625 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001626
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001627 *listener << "which points to ";
1628 return MatchPrintAndExplain(*pointer, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001629 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001630
shiqiane35fdd92008-12-10 05:08:54 +00001631 private:
1632 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001633
1634 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001635 };
1636
1637 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001638
1639 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001640};
1641
1642// Implements the Field() matcher for matching a field (i.e. member
1643// variable) of an object.
1644template <typename Class, typename FieldType>
1645class FieldMatcher {
1646 public:
1647 FieldMatcher(FieldType Class::*field,
1648 const Matcher<const FieldType&>& matcher)
1649 : field_(field), matcher_(matcher) {}
1650
shiqiane35fdd92008-12-10 05:08:54 +00001651 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001652 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001653 matcher_.DescribeTo(os);
1654 }
1655
1656 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001657 *os << "is an object whose given field ";
shiqiane35fdd92008-12-10 05:08:54 +00001658 matcher_.DescribeNegationTo(os);
1659 }
1660
zhanyong.wandb22c222010-01-28 21:52:29 +00001661 template <typename T>
1662 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
1663 return MatchAndExplainImpl(
1664 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00001665 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00001666 value, listener);
1667 }
1668
1669 private:
1670 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001671 // Symbian's C++ compiler choose which overload to use. Its type is
1672 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001673 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1674 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001675 *listener << "whose given field is ";
1676 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001677 }
1678
zhanyong.wandb22c222010-01-28 21:52:29 +00001679 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1680 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001681 if (p == NULL)
1682 return false;
1683
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001684 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001685 // Since *p has a field, it must be a class/struct/union type and
1686 // thus cannot be a pointer. Therefore we pass false_type() as
1687 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001688 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001689 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001690
shiqiane35fdd92008-12-10 05:08:54 +00001691 const FieldType Class::*field_;
1692 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001693
1694 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001695};
1696
shiqiane35fdd92008-12-10 05:08:54 +00001697// Implements the Property() matcher for matching a property
1698// (i.e. return value of a getter method) of an object.
1699template <typename Class, typename PropertyType>
1700class PropertyMatcher {
1701 public:
1702 // The property may have a reference type, so 'const PropertyType&'
1703 // may cause double references and fail to compile. That's why we
zhanyong.wan02f71062010-05-10 17:14:29 +00001704 // need GTEST_REFERENCE_TO_CONST, which works regardless of
shiqiane35fdd92008-12-10 05:08:54 +00001705 // PropertyType being a reference or not.
zhanyong.wan02f71062010-05-10 17:14:29 +00001706 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001707
1708 PropertyMatcher(PropertyType (Class::*property)() const,
1709 const Matcher<RefToConstProperty>& matcher)
1710 : property_(property), matcher_(matcher) {}
1711
shiqiane35fdd92008-12-10 05:08:54 +00001712 void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001713 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001714 matcher_.DescribeTo(os);
1715 }
1716
1717 void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001718 *os << "is an object whose given property ";
shiqiane35fdd92008-12-10 05:08:54 +00001719 matcher_.DescribeNegationTo(os);
1720 }
1721
zhanyong.wandb22c222010-01-28 21:52:29 +00001722 template <typename T>
1723 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
1724 return MatchAndExplainImpl(
1725 typename ::testing::internal::
zhanyong.wan02f71062010-05-10 17:14:29 +00001726 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
zhanyong.wandb22c222010-01-28 21:52:29 +00001727 value, listener);
1728 }
1729
1730 private:
1731 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001732 // Symbian's C++ compiler choose which overload to use. Its type is
1733 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001734 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1735 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001736 *listener << "whose given property is ";
1737 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
1738 // which takes a non-const reference as argument.
1739 RefToConstProperty result = (obj.*property_)();
1740 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001741 }
1742
zhanyong.wandb22c222010-01-28 21:52:29 +00001743 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1744 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001745 if (p == NULL)
1746 return false;
1747
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001748 *listener << "which points to an object ";
zhanyong.wan82113312010-01-08 21:55:40 +00001749 // Since *p has a property method, it must be a class/struct/union
1750 // type and thus cannot be a pointer. Therefore we pass
1751 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001752 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001753 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001754
shiqiane35fdd92008-12-10 05:08:54 +00001755 PropertyType (Class::*property_)() const;
1756 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001757
1758 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001759};
1760
shiqiane35fdd92008-12-10 05:08:54 +00001761// Type traits specifying various features of different functors for ResultOf.
1762// The default template specifies features for functor objects.
1763// Functor classes have to typedef argument_type and result_type
1764// to be compatible with ResultOf.
1765template <typename Functor>
1766struct CallableTraits {
1767 typedef typename Functor::result_type ResultType;
1768 typedef Functor StorageType;
1769
zhanyong.wan32de5f52009-12-23 00:13:23 +00001770 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00001771 template <typename T>
1772 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1773};
1774
1775// Specialization for function pointers.
1776template <typename ArgType, typename ResType>
1777struct CallableTraits<ResType(*)(ArgType)> {
1778 typedef ResType ResultType;
1779 typedef ResType(*StorageType)(ArgType);
1780
1781 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001782 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00001783 << "NULL function pointer is passed into ResultOf().";
1784 }
1785 template <typename T>
1786 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1787 return (*f)(arg);
1788 }
1789};
1790
1791// Implements the ResultOf() matcher for matching a return value of a
1792// unary function of an object.
1793template <typename Callable>
1794class ResultOfMatcher {
1795 public:
1796 typedef typename CallableTraits<Callable>::ResultType ResultType;
1797
1798 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1799 : callable_(callable), matcher_(matcher) {
1800 CallableTraits<Callable>::CheckIsValid(callable_);
1801 }
1802
1803 template <typename T>
1804 operator Matcher<T>() const {
1805 return Matcher<T>(new Impl<T>(callable_, matcher_));
1806 }
1807
1808 private:
1809 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1810
1811 template <typename T>
1812 class Impl : public MatcherInterface<T> {
1813 public:
1814 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1815 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00001816
1817 virtual void DescribeTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001818 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001819 matcher_.DescribeTo(os);
1820 }
1821
1822 virtual void DescribeNegationTo(::std::ostream* os) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001823 *os << "is mapped by the given callable to a value that ";
shiqiane35fdd92008-12-10 05:08:54 +00001824 matcher_.DescribeNegationTo(os);
1825 }
1826
zhanyong.wan82113312010-01-08 21:55:40 +00001827 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001828 *listener << "which is mapped by the given callable to ";
1829 // Cannot pass the return value (for example, int) to
1830 // MatchPrintAndExplain, which takes a non-const reference as argument.
1831 ResultType result =
1832 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
1833 return MatchPrintAndExplain(result, matcher_, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001834 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001835
shiqiane35fdd92008-12-10 05:08:54 +00001836 private:
1837 // Functors often define operator() as non-const method even though
1838 // they are actualy stateless. But we need to use them even when
1839 // 'this' is a const pointer. It's the user's responsibility not to
1840 // use stateful callables with ResultOf(), which does't guarantee
1841 // how many times the callable will be invoked.
1842 mutable CallableStorageType callable_;
1843 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001844
1845 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001846 }; // class Impl
1847
1848 const CallableStorageType callable_;
1849 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001850
1851 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001852};
1853
zhanyong.wan6a896b52009-01-16 01:13:50 +00001854// Implements an equality matcher for any STL-style container whose elements
1855// support ==. This matcher is like Eq(), but its failure explanations provide
1856// more detailed information that is useful when the container is used as a set.
1857// The failure message reports elements that are in one of the operands but not
1858// the other. The failure messages do not report duplicate or out-of-order
1859// elements in the containers (which don't properly matter to sets, but can
1860// occur if the containers are vectors or lists, for example).
1861//
1862// Uses the container's const_iterator, value_type, operator ==,
1863// begin(), and end().
1864template <typename Container>
1865class ContainerEqMatcher {
1866 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00001867 typedef internal::StlContainerView<Container> View;
1868 typedef typename View::type StlContainer;
1869 typedef typename View::const_reference StlContainerReference;
1870
1871 // We make a copy of rhs in case the elements in it are modified
1872 // after this matcher is created.
1873 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
1874 // Makes sure the user doesn't instantiate this class template
1875 // with a const or reference type.
1876 testing::StaticAssertTypeEq<Container,
zhanyong.wan02f71062010-05-10 17:14:29 +00001877 GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(Container))>();
zhanyong.wanb8243162009-06-04 05:48:20 +00001878 }
1879
zhanyong.wan6a896b52009-01-16 01:13:50 +00001880 void DescribeTo(::std::ostream* os) const {
1881 *os << "equals ";
vladloseve2e8ba42010-05-13 18:16:03 +00001882 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001883 }
1884 void DescribeNegationTo(::std::ostream* os) const {
1885 *os << "does not equal ";
vladloseve2e8ba42010-05-13 18:16:03 +00001886 UniversalPrint(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001887 }
1888
zhanyong.wanb8243162009-06-04 05:48:20 +00001889 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00001890 bool MatchAndExplain(const LhsContainer& lhs,
1891 MatchResultListener* listener) const {
zhanyong.wan02f71062010-05-10 17:14:29 +00001892 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
zhanyong.wanb8243162009-06-04 05:48:20 +00001893 // that causes LhsContainer to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00001894 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
zhanyong.wanb8243162009-06-04 05:48:20 +00001895 LhsView;
1896 typedef typename LhsView::type LhsStlContainer;
1897 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00001898 if (lhs_stl_container == rhs_)
1899 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00001900
zhanyong.wane122e452010-01-12 09:03:52 +00001901 ::std::ostream* const os = listener->stream();
1902 if (os != NULL) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001903 // Something is different. Check for extra values first.
zhanyong.wane122e452010-01-12 09:03:52 +00001904 bool printed_header = false;
1905 for (typename LhsStlContainer::const_iterator it =
1906 lhs_stl_container.begin();
1907 it != lhs_stl_container.end(); ++it) {
1908 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
1909 rhs_.end()) {
1910 if (printed_header) {
1911 *os << ", ";
1912 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001913 *os << "which has these unexpected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00001914 printed_header = true;
1915 }
vladloseve2e8ba42010-05-13 18:16:03 +00001916 UniversalPrint(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001917 }
zhanyong.wane122e452010-01-12 09:03:52 +00001918 }
1919
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001920 // Now check for missing values.
zhanyong.wane122e452010-01-12 09:03:52 +00001921 bool printed_header2 = false;
1922 for (typename StlContainer::const_iterator it = rhs_.begin();
1923 it != rhs_.end(); ++it) {
1924 if (internal::ArrayAwareFind(
1925 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
1926 lhs_stl_container.end()) {
1927 if (printed_header2) {
1928 *os << ", ";
1929 } else {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001930 *os << (printed_header ? ",\nand" : "which")
1931 << " doesn't have these expected elements: ";
zhanyong.wane122e452010-01-12 09:03:52 +00001932 printed_header2 = true;
1933 }
vladloseve2e8ba42010-05-13 18:16:03 +00001934 UniversalPrint(*it, os);
zhanyong.wane122e452010-01-12 09:03:52 +00001935 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00001936 }
1937 }
1938
zhanyong.wane122e452010-01-12 09:03:52 +00001939 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00001940 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001941
zhanyong.wan6a896b52009-01-16 01:13:50 +00001942 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00001943 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001944
1945 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001946};
1947
zhanyong.wan33605ba2010-04-22 23:37:47 +00001948// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
zhanyong.wanb8243162009-06-04 05:48:20 +00001949template <typename Container>
zhanyong.wan33605ba2010-04-22 23:37:47 +00001950class QuantifierMatcherImpl : public MatcherInterface<Container> {
zhanyong.wanb8243162009-06-04 05:48:20 +00001951 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00001952 typedef GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(Container)) RawContainer;
zhanyong.wanb8243162009-06-04 05:48:20 +00001953 typedef StlContainerView<RawContainer> View;
1954 typedef typename View::type StlContainer;
1955 typedef typename View::const_reference StlContainerReference;
1956 typedef typename StlContainer::value_type Element;
1957
1958 template <typename InnerMatcher>
zhanyong.wan33605ba2010-04-22 23:37:47 +00001959 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
zhanyong.wanb8243162009-06-04 05:48:20 +00001960 : inner_matcher_(
zhanyong.wan33605ba2010-04-22 23:37:47 +00001961 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
zhanyong.wanb8243162009-06-04 05:48:20 +00001962
zhanyong.wan33605ba2010-04-22 23:37:47 +00001963 // Checks whether:
1964 // * All elements in the container match, if all_elements_should_match.
1965 // * Any element in the container matches, if !all_elements_should_match.
1966 bool MatchAndExplainImpl(bool all_elements_should_match,
1967 Container container,
1968 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00001969 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00001970 size_t i = 0;
1971 for (typename StlContainer::const_iterator it = stl_container.begin();
1972 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001973 StringMatchResultListener inner_listener;
zhanyong.wan33605ba2010-04-22 23:37:47 +00001974 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
1975
1976 if (matches != all_elements_should_match) {
1977 *listener << "whose element #" << i
1978 << (matches ? " matches" : " doesn't match");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001979 PrintIfNotEmpty(inner_listener.str(), listener->stream());
zhanyong.wan33605ba2010-04-22 23:37:47 +00001980 return !all_elements_should_match;
zhanyong.wanb8243162009-06-04 05:48:20 +00001981 }
1982 }
zhanyong.wan33605ba2010-04-22 23:37:47 +00001983 return all_elements_should_match;
1984 }
1985
1986 protected:
1987 const Matcher<const Element&> inner_matcher_;
1988
1989 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
1990};
1991
1992// Implements Contains(element_matcher) for the given argument type Container.
1993// Symmetric to EachMatcherImpl.
1994template <typename Container>
1995class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
1996 public:
1997 template <typename InnerMatcher>
1998 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
1999 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2000
2001 // Describes what this matcher does.
2002 virtual void DescribeTo(::std::ostream* os) const {
2003 *os << "contains at least one element that ";
2004 this->inner_matcher_.DescribeTo(os);
2005 }
2006
2007 virtual void DescribeNegationTo(::std::ostream* os) const {
2008 *os << "doesn't contain any element that ";
2009 this->inner_matcher_.DescribeTo(os);
2010 }
2011
2012 virtual bool MatchAndExplain(Container container,
2013 MatchResultListener* listener) const {
2014 return this->MatchAndExplainImpl(false, container, listener);
zhanyong.wanb8243162009-06-04 05:48:20 +00002015 }
2016
2017 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002018 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00002019};
2020
zhanyong.wan33605ba2010-04-22 23:37:47 +00002021// Implements Each(element_matcher) for the given argument type Container.
2022// Symmetric to ContainsMatcherImpl.
2023template <typename Container>
2024class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2025 public:
2026 template <typename InnerMatcher>
2027 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2028 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2029
2030 // Describes what this matcher does.
2031 virtual void DescribeTo(::std::ostream* os) const {
2032 *os << "only contains elements that ";
2033 this->inner_matcher_.DescribeTo(os);
2034 }
2035
2036 virtual void DescribeNegationTo(::std::ostream* os) const {
2037 *os << "contains some element that ";
2038 this->inner_matcher_.DescribeNegationTo(os);
2039 }
2040
2041 virtual bool MatchAndExplain(Container container,
2042 MatchResultListener* listener) const {
2043 return this->MatchAndExplainImpl(true, container, listener);
2044 }
2045
2046 private:
2047 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2048};
2049
zhanyong.wanb8243162009-06-04 05:48:20 +00002050// Implements polymorphic Contains(element_matcher).
2051template <typename M>
2052class ContainsMatcher {
2053 public:
2054 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2055
2056 template <typename Container>
2057 operator Matcher<Container>() const {
2058 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2059 }
2060
2061 private:
2062 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002063
2064 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00002065};
2066
zhanyong.wan33605ba2010-04-22 23:37:47 +00002067// Implements polymorphic Each(element_matcher).
2068template <typename M>
2069class EachMatcher {
2070 public:
2071 explicit EachMatcher(M m) : inner_matcher_(m) {}
2072
2073 template <typename Container>
2074 operator Matcher<Container>() const {
2075 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2076 }
2077
2078 private:
2079 const M inner_matcher_;
2080
2081 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2082};
2083
zhanyong.wanb5937da2009-07-16 20:26:41 +00002084// Implements Key(inner_matcher) for the given argument pair type.
2085// Key(inner_matcher) matches an std::pair whose 'first' field matches
2086// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2087// std::map that contains at least one element whose key is >= 5.
2088template <typename PairType>
2089class KeyMatcherImpl : public MatcherInterface<PairType> {
2090 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00002091 typedef GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(PairType)) RawPairType;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002092 typedef typename RawPairType::first_type KeyType;
2093
2094 template <typename InnerMatcher>
2095 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2096 : inner_matcher_(
2097 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2098 }
2099
2100 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002101 virtual bool MatchAndExplain(PairType key_value,
2102 MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002103 StringMatchResultListener inner_listener;
2104 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2105 &inner_listener);
2106 const internal::string explanation = inner_listener.str();
2107 if (explanation != "") {
2108 *listener << "whose first field is a value " << explanation;
2109 }
2110 return match;
zhanyong.wanb5937da2009-07-16 20:26:41 +00002111 }
2112
2113 // Describes what this matcher does.
2114 virtual void DescribeTo(::std::ostream* os) const {
2115 *os << "has a key that ";
2116 inner_matcher_.DescribeTo(os);
2117 }
2118
2119 // Describes what the negation of this matcher does.
2120 virtual void DescribeNegationTo(::std::ostream* os) const {
2121 *os << "doesn't have a key that ";
2122 inner_matcher_.DescribeTo(os);
2123 }
2124
zhanyong.wanb5937da2009-07-16 20:26:41 +00002125 private:
2126 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002127
2128 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002129};
2130
2131// Implements polymorphic Key(matcher_for_key).
2132template <typename M>
2133class KeyMatcher {
2134 public:
2135 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2136
2137 template <typename PairType>
2138 operator Matcher<PairType>() const {
2139 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2140 }
2141
2142 private:
2143 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002144
2145 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002146};
2147
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002148// Implements Pair(first_matcher, second_matcher) for the given argument pair
2149// type with its two matchers. See Pair() function below.
2150template <typename PairType>
2151class PairMatcherImpl : public MatcherInterface<PairType> {
2152 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00002153 typedef GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(PairType)) RawPairType;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002154 typedef typename RawPairType::first_type FirstType;
2155 typedef typename RawPairType::second_type SecondType;
2156
2157 template <typename FirstMatcher, typename SecondMatcher>
2158 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2159 : first_matcher_(
2160 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2161 second_matcher_(
2162 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2163 }
2164
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002165 // Describes what this matcher does.
2166 virtual void DescribeTo(::std::ostream* os) const {
2167 *os << "has a first field that ";
2168 first_matcher_.DescribeTo(os);
2169 *os << ", and has a second field that ";
2170 second_matcher_.DescribeTo(os);
2171 }
2172
2173 // Describes what the negation of this matcher does.
2174 virtual void DescribeNegationTo(::std::ostream* os) const {
2175 *os << "has a first field that ";
2176 first_matcher_.DescribeNegationTo(os);
2177 *os << ", or has a second field that ";
2178 second_matcher_.DescribeNegationTo(os);
2179 }
2180
zhanyong.wan82113312010-01-08 21:55:40 +00002181 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2182 // matches second_matcher.
2183 virtual bool MatchAndExplain(PairType a_pair,
2184 MatchResultListener* listener) const {
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002185 if (!listener->IsInterested()) {
2186 // If the listener is not interested, we don't need to construct the
2187 // explanation.
2188 return first_matcher_.Matches(a_pair.first) &&
2189 second_matcher_.Matches(a_pair.second);
zhanyong.wan82113312010-01-08 21:55:40 +00002190 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002191 StringMatchResultListener first_inner_listener;
2192 if (!first_matcher_.MatchAndExplain(a_pair.first,
2193 &first_inner_listener)) {
2194 *listener << "whose first field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002195 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002196 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002197 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002198 StringMatchResultListener second_inner_listener;
2199 if (!second_matcher_.MatchAndExplain(a_pair.second,
2200 &second_inner_listener)) {
2201 *listener << "whose second field does not match";
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002202 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002203 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002204 }
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002205 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
2206 listener);
zhanyong.wan82113312010-01-08 21:55:40 +00002207 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002208 }
2209
2210 private:
zhanyong.wan676e8cc2010-03-16 20:01:51 +00002211 void ExplainSuccess(const internal::string& first_explanation,
2212 const internal::string& second_explanation,
2213 MatchResultListener* listener) const {
2214 *listener << "whose both fields match";
2215 if (first_explanation != "") {
2216 *listener << ", where the first field is a value " << first_explanation;
2217 }
2218 if (second_explanation != "") {
2219 *listener << ", ";
2220 if (first_explanation != "") {
2221 *listener << "and ";
2222 } else {
2223 *listener << "where ";
2224 }
2225 *listener << "the second field is a value " << second_explanation;
2226 }
2227 }
2228
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002229 const Matcher<const FirstType&> first_matcher_;
2230 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002231
2232 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002233};
2234
2235// Implements polymorphic Pair(first_matcher, second_matcher).
2236template <typename FirstMatcher, typename SecondMatcher>
2237class PairMatcher {
2238 public:
2239 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2240 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2241
2242 template <typename PairType>
2243 operator Matcher<PairType> () const {
2244 return MakeMatcher(
2245 new PairMatcherImpl<PairType>(
2246 first_matcher_, second_matcher_));
2247 }
2248
2249 private:
2250 const FirstMatcher first_matcher_;
2251 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002252
2253 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002254};
2255
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002256// Implements ElementsAre() and ElementsAreArray().
2257template <typename Container>
2258class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2259 public:
zhanyong.wan02f71062010-05-10 17:14:29 +00002260 typedef GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(Container)) RawContainer;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002261 typedef internal::StlContainerView<RawContainer> View;
2262 typedef typename View::type StlContainer;
2263 typedef typename View::const_reference StlContainerReference;
2264 typedef typename StlContainer::value_type Element;
2265
2266 // Constructs the matcher from a sequence of element values or
2267 // element matchers.
2268 template <typename InputIter>
zhanyong.wan32de5f52009-12-23 00:13:23 +00002269 ElementsAreMatcherImpl(InputIter first, size_t a_count) {
2270 matchers_.reserve(a_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002271 InputIter it = first;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002272 for (size_t i = 0; i != a_count; ++i, ++it) {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002273 matchers_.push_back(MatcherCast<const Element&>(*it));
2274 }
2275 }
2276
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002277 // Describes what this matcher does.
2278 virtual void DescribeTo(::std::ostream* os) const {
2279 if (count() == 0) {
2280 *os << "is empty";
2281 } else if (count() == 1) {
2282 *os << "has 1 element that ";
2283 matchers_[0].DescribeTo(os);
2284 } else {
2285 *os << "has " << Elements(count()) << " where\n";
2286 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002287 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002288 matchers_[i].DescribeTo(os);
2289 if (i + 1 < count()) {
2290 *os << ",\n";
2291 }
2292 }
2293 }
2294 }
2295
2296 // Describes what the negation of this matcher does.
2297 virtual void DescribeNegationTo(::std::ostream* os) const {
2298 if (count() == 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002299 *os << "isn't empty";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002300 return;
2301 }
2302
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002303 *os << "doesn't have " << Elements(count()) << ", or\n";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002304 for (size_t i = 0; i != count(); ++i) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002305 *os << "element #" << i << " ";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002306 matchers_[i].DescribeNegationTo(os);
2307 if (i + 1 < count()) {
2308 *os << ", or\n";
2309 }
2310 }
2311 }
2312
zhanyong.wan82113312010-01-08 21:55:40 +00002313 virtual bool MatchAndExplain(Container container,
2314 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002315 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002316 const size_t actual_count = stl_container.size();
2317 if (actual_count != count()) {
2318 // The element count doesn't match. If the container is empty,
2319 // there's no need to explain anything as Google Mock already
2320 // prints the empty container. Otherwise we just need to show
2321 // how many elements there actually are.
2322 if (actual_count != 0) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002323 *listener << "which has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002324 }
zhanyong.wan82113312010-01-08 21:55:40 +00002325 return false;
2326 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002327
zhanyong.wan82113312010-01-08 21:55:40 +00002328 typename StlContainer::const_iterator it = stl_container.begin();
2329 // explanations[i] is the explanation of the element at index i.
2330 std::vector<internal::string> explanations(count());
2331 for (size_t i = 0; i != count(); ++it, ++i) {
2332 StringMatchResultListener s;
2333 if (matchers_[i].MatchAndExplain(*it, &s)) {
2334 explanations[i] = s.str();
2335 } else {
2336 // The container has the right size but the i-th element
2337 // doesn't match its expectation.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002338 *listener << "whose element #" << i << " doesn't match";
2339 PrintIfNotEmpty(s.str(), listener->stream());
zhanyong.wan82113312010-01-08 21:55:40 +00002340 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002341 }
2342 }
zhanyong.wan82113312010-01-08 21:55:40 +00002343
2344 // Every element matches its expectation. We need to explain why
2345 // (the obvious ones can be skipped).
zhanyong.wan82113312010-01-08 21:55:40 +00002346 bool reason_printed = false;
2347 for (size_t i = 0; i != count(); ++i) {
2348 const internal::string& s = explanations[i];
2349 if (!s.empty()) {
2350 if (reason_printed) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002351 *listener << ",\nand ";
zhanyong.wan82113312010-01-08 21:55:40 +00002352 }
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002353 *listener << "whose element #" << i << " matches, " << s;
zhanyong.wan82113312010-01-08 21:55:40 +00002354 reason_printed = true;
2355 }
2356 }
2357
2358 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002359 }
2360
2361 private:
2362 static Message Elements(size_t count) {
2363 return Message() << count << (count == 1 ? " element" : " elements");
2364 }
2365
2366 size_t count() const { return matchers_.size(); }
2367 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002368
2369 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002370};
2371
2372// Implements ElementsAre() of 0 arguments.
2373class ElementsAreMatcher0 {
2374 public:
2375 ElementsAreMatcher0() {}
2376
2377 template <typename Container>
2378 operator Matcher<Container>() const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002379 typedef GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(Container))
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002380 RawContainer;
2381 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2382 Element;
2383
2384 const Matcher<const Element&>* const matchers = NULL;
2385 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 0));
2386 }
2387};
2388
2389// Implements ElementsAreArray().
2390template <typename T>
2391class ElementsAreArrayMatcher {
2392 public:
2393 ElementsAreArrayMatcher(const T* first, size_t count) :
2394 first_(first), count_(count) {}
2395
2396 template <typename Container>
2397 operator Matcher<Container>() const {
zhanyong.wan02f71062010-05-10 17:14:29 +00002398 typedef GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(Container))
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002399 RawContainer;
2400 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2401 Element;
2402
2403 return MakeMatcher(new ElementsAreMatcherImpl<Container>(first_, count_));
2404 }
2405
2406 private:
2407 const T* const first_;
2408 const size_t count_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002409
2410 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002411};
2412
2413// Constants denoting interpolations in a matcher description string.
2414const int kTupleInterpolation = -1; // "%(*)s"
2415const int kPercentInterpolation = -2; // "%%"
2416const int kInvalidInterpolation = -3; // "%" followed by invalid text
2417
2418// Records the location and content of an interpolation.
2419struct Interpolation {
2420 Interpolation(const char* start, const char* end, int param)
2421 : start_pos(start), end_pos(end), param_index(param) {}
2422
2423 // Points to the start of the interpolation (the '%' character).
2424 const char* start_pos;
2425 // Points to the first character after the interpolation.
2426 const char* end_pos;
2427 // 0-based index of the interpolated matcher parameter;
2428 // kTupleInterpolation for "%(*)s"; kPercentInterpolation for "%%".
2429 int param_index;
2430};
2431
2432typedef ::std::vector<Interpolation> Interpolations;
2433
2434// Parses a matcher description string and returns a vector of
2435// interpolations that appear in the string; generates non-fatal
2436// failures iff 'description' is an invalid matcher description.
2437// 'param_names' is a NULL-terminated array of parameter names in the
2438// order they appear in the MATCHER_P*() parameter list.
2439Interpolations ValidateMatcherDescription(
2440 const char* param_names[], const char* description);
2441
2442// Returns the actual matcher description, given the matcher name,
2443// user-supplied description template string, interpolations in the
2444// string, and the printed values of the matcher parameters.
2445string FormatMatcherDescription(
2446 const char* matcher_name, const char* description,
2447 const Interpolations& interp, const Strings& param_values);
2448
shiqiane35fdd92008-12-10 05:08:54 +00002449} // namespace internal
2450
2451// Implements MatcherCast().
2452template <typename T, typename M>
2453inline Matcher<T> MatcherCast(M matcher) {
2454 return internal::MatcherCastImpl<T, M>::Cast(matcher);
2455}
2456
2457// _ is a matcher that matches anything of any type.
2458//
2459// This definition is fine as:
2460//
2461// 1. The C++ standard permits using the name _ in a namespace that
2462// is not the global namespace or ::std.
2463// 2. The AnythingMatcher class has no data member or constructor,
2464// so it's OK to create global variables of this type.
2465// 3. c-style has approved of using _ in this case.
2466const internal::AnythingMatcher _ = {};
2467// Creates a matcher that matches any value of the given type T.
2468template <typename T>
2469inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2470
2471// Creates a matcher that matches any value of the given type T.
2472template <typename T>
2473inline Matcher<T> An() { return A<T>(); }
2474
2475// Creates a polymorphic matcher that matches anything equal to x.
2476// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2477// wouldn't compile.
2478template <typename T>
2479inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2480
2481// Constructs a Matcher<T> from a 'value' of type T. The constructed
2482// matcher matches any value that's equal to 'value'.
2483template <typename T>
2484Matcher<T>::Matcher(T value) { *this = Eq(value); }
2485
2486// Creates a monomorphic matcher that matches anything with type Lhs
2487// and equal to rhs. A user may need to use this instead of Eq(...)
2488// in order to resolve an overloading ambiguity.
2489//
2490// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2491// or Matcher<T>(x), but more readable than the latter.
2492//
2493// We could define similar monomorphic matchers for other comparison
2494// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2495// it yet as those are used much less than Eq() in practice. A user
2496// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2497// for example.
2498template <typename Lhs, typename Rhs>
2499inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2500
2501// Creates a polymorphic matcher that matches anything >= x.
2502template <typename Rhs>
2503inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2504 return internal::GeMatcher<Rhs>(x);
2505}
2506
2507// Creates a polymorphic matcher that matches anything > x.
2508template <typename Rhs>
2509inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2510 return internal::GtMatcher<Rhs>(x);
2511}
2512
2513// Creates a polymorphic matcher that matches anything <= x.
2514template <typename Rhs>
2515inline internal::LeMatcher<Rhs> Le(Rhs x) {
2516 return internal::LeMatcher<Rhs>(x);
2517}
2518
2519// Creates a polymorphic matcher that matches anything < x.
2520template <typename Rhs>
2521inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2522 return internal::LtMatcher<Rhs>(x);
2523}
2524
2525// Creates a polymorphic matcher that matches anything != x.
2526template <typename Rhs>
2527inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2528 return internal::NeMatcher<Rhs>(x);
2529}
2530
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002531// Creates a polymorphic matcher that matches any NULL pointer.
2532inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2533 return MakePolymorphicMatcher(internal::IsNullMatcher());
2534}
2535
shiqiane35fdd92008-12-10 05:08:54 +00002536// Creates a polymorphic matcher that matches any non-NULL pointer.
2537// This is convenient as Not(NULL) doesn't compile (the compiler
2538// thinks that that expression is comparing a pointer with an integer).
2539inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2540 return MakePolymorphicMatcher(internal::NotNullMatcher());
2541}
2542
2543// Creates a polymorphic matcher that matches any argument that
2544// references variable x.
2545template <typename T>
2546inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2547 return internal::RefMatcher<T&>(x);
2548}
2549
2550// Creates a matcher that matches any double argument approximately
2551// equal to rhs, where two NANs are considered unequal.
2552inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2553 return internal::FloatingEqMatcher<double>(rhs, false);
2554}
2555
2556// Creates a matcher that matches any double argument approximately
2557// equal to rhs, including NaN values when rhs is NaN.
2558inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2559 return internal::FloatingEqMatcher<double>(rhs, true);
2560}
2561
2562// Creates a matcher that matches any float argument approximately
2563// equal to rhs, where two NANs are considered unequal.
2564inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2565 return internal::FloatingEqMatcher<float>(rhs, false);
2566}
2567
2568// Creates a matcher that matches any double argument approximately
2569// equal to rhs, including NaN values when rhs is NaN.
2570inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2571 return internal::FloatingEqMatcher<float>(rhs, true);
2572}
2573
2574// Creates a matcher that matches a pointer (raw or smart) that points
2575// to a value that matches inner_matcher.
2576template <typename InnerMatcher>
2577inline internal::PointeeMatcher<InnerMatcher> Pointee(
2578 const InnerMatcher& inner_matcher) {
2579 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2580}
2581
2582// Creates a matcher that matches an object whose given field matches
2583// 'matcher'. For example,
2584// Field(&Foo::number, Ge(5))
2585// matches a Foo object x iff x.number >= 5.
2586template <typename Class, typename FieldType, typename FieldMatcher>
2587inline PolymorphicMatcher<
2588 internal::FieldMatcher<Class, FieldType> > Field(
2589 FieldType Class::*field, const FieldMatcher& matcher) {
2590 return MakePolymorphicMatcher(
2591 internal::FieldMatcher<Class, FieldType>(
2592 field, MatcherCast<const FieldType&>(matcher)));
2593 // The call to MatcherCast() is required for supporting inner
2594 // matchers of compatible types. For example, it allows
2595 // Field(&Foo::bar, m)
2596 // to compile where bar is an int32 and m is a matcher for int64.
2597}
2598
2599// Creates a matcher that matches an object whose given property
2600// matches 'matcher'. For example,
2601// Property(&Foo::str, StartsWith("hi"))
2602// matches a Foo object x iff x.str() starts with "hi".
2603template <typename Class, typename PropertyType, typename PropertyMatcher>
2604inline PolymorphicMatcher<
2605 internal::PropertyMatcher<Class, PropertyType> > Property(
2606 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2607 return MakePolymorphicMatcher(
2608 internal::PropertyMatcher<Class, PropertyType>(
2609 property,
zhanyong.wan02f71062010-05-10 17:14:29 +00002610 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002611 // The call to MatcherCast() is required for supporting inner
2612 // matchers of compatible types. For example, it allows
2613 // Property(&Foo::bar, m)
2614 // to compile where bar() returns an int32 and m is a matcher for int64.
2615}
2616
2617// Creates a matcher that matches an object iff the result of applying
2618// a callable to x matches 'matcher'.
2619// For example,
2620// ResultOf(f, StartsWith("hi"))
2621// matches a Foo object x iff f(x) starts with "hi".
2622// callable parameter can be a function, function pointer, or a functor.
2623// Callable has to satisfy the following conditions:
2624// * It is required to keep no state affecting the results of
2625// the calls on it and make no assumptions about how many calls
2626// will be made. Any state it keeps must be protected from the
2627// concurrent access.
2628// * If it is a function object, it has to define type result_type.
2629// We recommend deriving your functor classes from std::unary_function.
2630template <typename Callable, typename ResultOfMatcher>
2631internal::ResultOfMatcher<Callable> ResultOf(
2632 Callable callable, const ResultOfMatcher& matcher) {
2633 return internal::ResultOfMatcher<Callable>(
2634 callable,
2635 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2636 matcher));
2637 // The call to MatcherCast() is required for supporting inner
2638 // matchers of compatible types. For example, it allows
2639 // ResultOf(Function, m)
2640 // to compile where Function() returns an int32 and m is a matcher for int64.
2641}
2642
2643// String matchers.
2644
2645// Matches a string equal to str.
2646inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2647 StrEq(const internal::string& str) {
2648 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2649 str, true, true));
2650}
2651
2652// Matches a string not equal to str.
2653inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2654 StrNe(const internal::string& str) {
2655 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2656 str, false, true));
2657}
2658
2659// Matches a string equal to str, ignoring case.
2660inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2661 StrCaseEq(const internal::string& str) {
2662 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2663 str, true, false));
2664}
2665
2666// Matches a string not equal to str, ignoring case.
2667inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2668 StrCaseNe(const internal::string& str) {
2669 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2670 str, false, false));
2671}
2672
2673// Creates a matcher that matches any string, std::string, or C string
2674// that contains the given substring.
2675inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2676 HasSubstr(const internal::string& substring) {
2677 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
2678 substring));
2679}
2680
2681// Matches a string that starts with 'prefix' (case-sensitive).
2682inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
2683 StartsWith(const internal::string& prefix) {
2684 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
2685 prefix));
2686}
2687
2688// Matches a string that ends with 'suffix' (case-sensitive).
2689inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
2690 EndsWith(const internal::string& suffix) {
2691 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
2692 suffix));
2693}
2694
shiqiane35fdd92008-12-10 05:08:54 +00002695// Matches a string that fully matches regular expression 'regex'.
2696// The matcher takes ownership of 'regex'.
2697inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2698 const internal::RE* regex) {
2699 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2700}
2701inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2702 const internal::string& regex) {
2703 return MatchesRegex(new internal::RE(regex));
2704}
2705
2706// Matches a string that contains regular expression 'regex'.
2707// The matcher takes ownership of 'regex'.
2708inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2709 const internal::RE* regex) {
2710 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2711}
2712inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2713 const internal::string& regex) {
2714 return ContainsRegex(new internal::RE(regex));
2715}
2716
shiqiane35fdd92008-12-10 05:08:54 +00002717#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2718// Wide string matchers.
2719
2720// Matches a string equal to str.
2721inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2722 StrEq(const internal::wstring& str) {
2723 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2724 str, true, true));
2725}
2726
2727// Matches a string not equal to str.
2728inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2729 StrNe(const internal::wstring& str) {
2730 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2731 str, false, true));
2732}
2733
2734// Matches a string equal to str, ignoring case.
2735inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2736 StrCaseEq(const internal::wstring& str) {
2737 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2738 str, true, false));
2739}
2740
2741// Matches a string not equal to str, ignoring case.
2742inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2743 StrCaseNe(const internal::wstring& str) {
2744 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2745 str, false, false));
2746}
2747
2748// Creates a matcher that matches any wstring, std::wstring, or C wide string
2749// that contains the given substring.
2750inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2751 HasSubstr(const internal::wstring& substring) {
2752 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2753 substring));
2754}
2755
2756// Matches a string that starts with 'prefix' (case-sensitive).
2757inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2758 StartsWith(const internal::wstring& prefix) {
2759 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2760 prefix));
2761}
2762
2763// Matches a string that ends with 'suffix' (case-sensitive).
2764inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2765 EndsWith(const internal::wstring& suffix) {
2766 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2767 suffix));
2768}
2769
2770#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2771
2772// Creates a polymorphic matcher that matches a 2-tuple where the
2773// first field == the second field.
2774inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2775
2776// Creates a polymorphic matcher that matches a 2-tuple where the
2777// first field >= the second field.
2778inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2779
2780// Creates a polymorphic matcher that matches a 2-tuple where the
2781// first field > the second field.
2782inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2783
2784// Creates a polymorphic matcher that matches a 2-tuple where the
2785// first field <= the second field.
2786inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2787
2788// Creates a polymorphic matcher that matches a 2-tuple where the
2789// first field < the second field.
2790inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2791
2792// Creates a polymorphic matcher that matches a 2-tuple where the
2793// first field != the second field.
2794inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2795
2796// Creates a matcher that matches any value of type T that m doesn't
2797// match.
2798template <typename InnerMatcher>
2799inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2800 return internal::NotMatcher<InnerMatcher>(m);
2801}
2802
2803// Creates a matcher that matches any value that matches all of the
2804// given matchers.
2805//
2806// For now we only support up to 5 matchers. Support for more
2807// matchers can be added as needed, or the user can use nested
2808// AllOf()s.
2809template <typename Matcher1, typename Matcher2>
2810inline internal::BothOfMatcher<Matcher1, Matcher2>
2811AllOf(Matcher1 m1, Matcher2 m2) {
2812 return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2);
2813}
2814
2815template <typename Matcher1, typename Matcher2, typename Matcher3>
2816inline internal::BothOfMatcher<Matcher1,
2817 internal::BothOfMatcher<Matcher2, Matcher3> >
2818AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2819 return AllOf(m1, AllOf(m2, m3));
2820}
2821
2822template <typename Matcher1, typename Matcher2, typename Matcher3,
2823 typename Matcher4>
2824inline internal::BothOfMatcher<Matcher1,
2825 internal::BothOfMatcher<Matcher2,
2826 internal::BothOfMatcher<Matcher3, Matcher4> > >
2827AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2828 return AllOf(m1, AllOf(m2, m3, m4));
2829}
2830
2831template <typename Matcher1, typename Matcher2, typename Matcher3,
2832 typename Matcher4, typename Matcher5>
2833inline internal::BothOfMatcher<Matcher1,
2834 internal::BothOfMatcher<Matcher2,
2835 internal::BothOfMatcher<Matcher3,
2836 internal::BothOfMatcher<Matcher4, Matcher5> > > >
2837AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2838 return AllOf(m1, AllOf(m2, m3, m4, m5));
2839}
2840
2841// Creates a matcher that matches any value that matches at least one
2842// of the given matchers.
2843//
2844// For now we only support up to 5 matchers. Support for more
2845// matchers can be added as needed, or the user can use nested
2846// AnyOf()s.
2847template <typename Matcher1, typename Matcher2>
2848inline internal::EitherOfMatcher<Matcher1, Matcher2>
2849AnyOf(Matcher1 m1, Matcher2 m2) {
2850 return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2);
2851}
2852
2853template <typename Matcher1, typename Matcher2, typename Matcher3>
2854inline internal::EitherOfMatcher<Matcher1,
2855 internal::EitherOfMatcher<Matcher2, Matcher3> >
2856AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2857 return AnyOf(m1, AnyOf(m2, m3));
2858}
2859
2860template <typename Matcher1, typename Matcher2, typename Matcher3,
2861 typename Matcher4>
2862inline internal::EitherOfMatcher<Matcher1,
2863 internal::EitherOfMatcher<Matcher2,
2864 internal::EitherOfMatcher<Matcher3, Matcher4> > >
2865AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2866 return AnyOf(m1, AnyOf(m2, m3, m4));
2867}
2868
2869template <typename Matcher1, typename Matcher2, typename Matcher3,
2870 typename Matcher4, typename Matcher5>
2871inline internal::EitherOfMatcher<Matcher1,
2872 internal::EitherOfMatcher<Matcher2,
2873 internal::EitherOfMatcher<Matcher3,
2874 internal::EitherOfMatcher<Matcher4, Matcher5> > > >
2875AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2876 return AnyOf(m1, AnyOf(m2, m3, m4, m5));
2877}
2878
2879// Returns a matcher that matches anything that satisfies the given
2880// predicate. The predicate can be any unary function or functor
2881// whose return type can be implicitly converted to bool.
2882template <typename Predicate>
2883inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
2884Truly(Predicate pred) {
2885 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
2886}
2887
zhanyong.wan6a896b52009-01-16 01:13:50 +00002888// Returns a matcher that matches an equal container.
2889// This matcher behaves like Eq(), but in the event of mismatch lists the
2890// values that are included in one container but not the other. (Duplicate
2891// values and order differences are not explained.)
2892template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00002893inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wan02f71062010-05-10 17:14:29 +00002894 GTEST_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00002895 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002896 // This following line is for working around a bug in MSVC 8.0,
2897 // which causes Container to be a const type sometimes.
zhanyong.wan02f71062010-05-10 17:14:29 +00002898 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00002899 return MakePolymorphicMatcher(
2900 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00002901}
2902
2903// Matches an STL-style container or a native array that contains at
2904// least one element matching the given value or matcher.
2905//
2906// Examples:
2907// ::std::set<int> page_ids;
2908// page_ids.insert(3);
2909// page_ids.insert(1);
2910// EXPECT_THAT(page_ids, Contains(1));
2911// EXPECT_THAT(page_ids, Contains(Gt(2)));
2912// EXPECT_THAT(page_ids, Not(Contains(4)));
2913//
2914// ::std::map<int, size_t> page_lengths;
2915// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00002916// EXPECT_THAT(page_lengths,
2917// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00002918//
2919// const char* user_ids[] = { "joe", "mike", "tom" };
2920// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
2921template <typename M>
2922inline internal::ContainsMatcher<M> Contains(M matcher) {
2923 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002924}
2925
zhanyong.wan33605ba2010-04-22 23:37:47 +00002926// Matches an STL-style container or a native array that contains only
2927// elements matching the given value or matcher.
2928//
2929// Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
2930// the messages are different.
2931//
2932// Examples:
2933// ::std::set<int> page_ids;
2934// // Each(m) matches an empty container, regardless of what m is.
2935// EXPECT_THAT(page_ids, Each(Eq(1)));
2936// EXPECT_THAT(page_ids, Each(Eq(77)));
2937//
2938// page_ids.insert(3);
2939// EXPECT_THAT(page_ids, Each(Gt(0)));
2940// EXPECT_THAT(page_ids, Not(Each(Gt(4))));
2941// page_ids.insert(1);
2942// EXPECT_THAT(page_ids, Not(Each(Lt(2))));
2943//
2944// ::std::map<int, size_t> page_lengths;
2945// page_lengths[1] = 100;
2946// page_lengths[2] = 200;
2947// page_lengths[3] = 300;
2948// EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
2949// EXPECT_THAT(page_lengths, Each(Key(Le(3))));
2950//
2951// const char* user_ids[] = { "joe", "mike", "tom" };
2952// EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
2953template <typename M>
2954inline internal::EachMatcher<M> Each(M matcher) {
2955 return internal::EachMatcher<M>(matcher);
2956}
2957
zhanyong.wanb5937da2009-07-16 20:26:41 +00002958// Key(inner_matcher) matches an std::pair whose 'first' field matches
2959// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2960// std::map that contains at least one element whose key is >= 5.
2961template <typename M>
2962inline internal::KeyMatcher<M> Key(M inner_matcher) {
2963 return internal::KeyMatcher<M>(inner_matcher);
2964}
2965
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002966// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
2967// matches first_matcher and whose 'second' field matches second_matcher. For
2968// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
2969// to match a std::map<int, string> that contains exactly one element whose key
2970// is >= 5 and whose value equals "foo".
2971template <typename FirstMatcher, typename SecondMatcher>
2972inline internal::PairMatcher<FirstMatcher, SecondMatcher>
2973Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
2974 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
2975 first_matcher, second_matcher);
2976}
2977
shiqiane35fdd92008-12-10 05:08:54 +00002978// Returns a predicate that is satisfied by anything that matches the
2979// given matcher.
2980template <typename M>
2981inline internal::MatcherAsPredicate<M> Matches(M matcher) {
2982 return internal::MatcherAsPredicate<M>(matcher);
2983}
2984
zhanyong.wanb8243162009-06-04 05:48:20 +00002985// Returns true iff the value matches the matcher.
2986template <typename T, typename M>
2987inline bool Value(const T& value, M matcher) {
2988 return testing::Matches(matcher)(value);
2989}
2990
zhanyong.wan34b034c2010-03-05 21:23:23 +00002991// Matches the value against the given matcher and explains the match
2992// result to listener.
2993template <typename T, typename M>
zhanyong.wana862f1d2010-03-15 21:23:04 +00002994inline bool ExplainMatchResult(
zhanyong.wan34b034c2010-03-05 21:23:23 +00002995 M matcher, const T& value, MatchResultListener* listener) {
2996 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
2997}
2998
zhanyong.wanbf550852009-06-09 06:09:53 +00002999// AllArgs(m) is a synonym of m. This is useful in
3000//
3001// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
3002//
3003// which is easier to read than
3004//
3005// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
3006template <typename InnerMatcher>
3007inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
3008
shiqiane35fdd92008-12-10 05:08:54 +00003009// These macros allow using matchers to check values in Google Test
3010// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
3011// succeed iff the value matches the matcher. If the assertion fails,
3012// the value and the description of the matcher will be printed.
3013#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
3014 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3015#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
3016 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
3017
3018} // namespace testing
3019
3020#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_