blob: ae7e131d49b9a0b3975487590ad8390face204cd [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements some commonly used argument matchers. More
35// matchers can be defined by the user implementing the
36// MatcherInterface<T> interface if necessary.
37
38#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
39#define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
40
zhanyong.wan6a896b52009-01-16 01:13:50 +000041#include <algorithm>
zhanyong.wan16cf4732009-05-14 20:55:30 +000042#include <limits>
shiqiane35fdd92008-12-10 05:08:54 +000043#include <ostream> // NOLINT
44#include <sstream>
45#include <string>
46#include <vector>
47
48#include <gmock/gmock-printers.h>
49#include <gmock/internal/gmock-internal-utils.h>
50#include <gmock/internal/gmock-port.h>
51#include <gtest/gtest.h>
52
53namespace testing {
54
55// To implement a matcher Foo for type T, define:
56// 1. a class FooMatcherImpl that implements the
57// MatcherInterface<T> interface, and
58// 2. a factory function that creates a Matcher<T> object from a
59// FooMatcherImpl*.
60//
61// The two-level delegation design makes it possible to allow a user
62// to write "v" instead of "Eq(v)" where a Matcher is expected, which
63// is impossible if we pass matchers by pointers. It also eases
64// ownership management as Matcher objects can now be copied like
65// plain values.
66
zhanyong.wan82113312010-01-08 21:55:40 +000067// MatchResultListener is an abstract class. Its << operator can be
68// used by a matcher to explain why a value matches or doesn't match.
69//
70// TODO(wan@google.com): add method
71// bool InterestedInWhy(bool result) const;
72// to indicate whether the listener is interested in why the match
73// result is 'result'.
74class MatchResultListener {
75 public:
76 // Creates a listener object with the given underlying ostream. The
77 // listener does not own the ostream.
78 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
79 virtual ~MatchResultListener() = 0; // Makes this class abstract.
80
81 // Streams x to the underlying ostream; does nothing if the ostream
82 // is NULL.
83 template <typename T>
84 MatchResultListener& operator<<(const T& x) {
85 if (stream_ != NULL)
86 *stream_ << x;
87 return *this;
88 }
89
90 // Returns the underlying ostream.
91 ::std::ostream* stream() { return stream_; }
92
93 private:
94 ::std::ostream* const stream_;
95
96 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
97};
98
99inline MatchResultListener::~MatchResultListener() {
100}
101
shiqiane35fdd92008-12-10 05:08:54 +0000102// The implementation of a matcher.
103template <typename T>
104class MatcherInterface {
105 public:
106 virtual ~MatcherInterface() {}
107
zhanyong.wan82113312010-01-08 21:55:40 +0000108 // Returns true iff the matcher matches x; also explains the match
109 // result to 'listener'.
110 //
zhanyong.wandb22c222010-01-28 21:52:29 +0000111 // You should override this method when defining a new matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000112 //
113 // It's the responsibility of the caller (Google Mock) to guarantee
114 // that 'listener' is not NULL. This helps to simplify a matcher's
115 // implementation when it doesn't care about the performance, as it
116 // can talk to 'listener' without checking its validity first.
117 // However, in order to implement dummy listeners efficiently,
118 // listener->stream() may be NULL.
zhanyong.wandb22c222010-01-28 21:52:29 +0000119 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
shiqiane35fdd92008-12-10 05:08:54 +0000120
121 // Describes this matcher to an ostream.
122 virtual void DescribeTo(::std::ostream* os) const = 0;
123
124 // Describes the negation of this matcher to an ostream. For
125 // example, if the description of this matcher is "is greater than
126 // 7", the negated description could be "is not greater than 7".
127 // You are not required to override this when implementing
128 // MatcherInterface, but it is highly advised so that your matcher
129 // can produce good error messages.
130 virtual void DescribeNegationTo(::std::ostream* os) const {
131 *os << "not (";
132 DescribeTo(os);
133 *os << ")";
134 }
shiqiane35fdd92008-12-10 05:08:54 +0000135};
136
137namespace internal {
138
zhanyong.wan82113312010-01-08 21:55:40 +0000139// A match result listener that ignores the explanation.
140class DummyMatchResultListener : public MatchResultListener {
141 public:
142 DummyMatchResultListener() : MatchResultListener(NULL) {}
143
144 private:
145 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
146};
147
148// A match result listener that forwards the explanation to a given
149// ostream. The difference between this and MatchResultListener is
150// that the former is concrete.
151class StreamMatchResultListener : public MatchResultListener {
152 public:
153 explicit StreamMatchResultListener(::std::ostream* os)
154 : MatchResultListener(os) {}
155
156 private:
157 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
158};
159
160// A match result listener that stores the explanation in a string.
161class StringMatchResultListener : public MatchResultListener {
162 public:
163 StringMatchResultListener() : MatchResultListener(&ss_) {}
164
165 // Returns the explanation heard so far.
166 internal::string str() const { return ss_.str(); }
167
168 private:
169 ::std::stringstream ss_;
170
171 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
172};
173
shiqiane35fdd92008-12-10 05:08:54 +0000174// An internal class for implementing Matcher<T>, which will derive
175// from it. We put functionalities common to all Matcher<T>
176// specializations here to avoid code duplication.
177template <typename T>
178class MatcherBase {
179 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000180 // Returns true iff the matcher matches x; also explains the match
181 // result to 'listener'.
182 bool MatchAndExplain(T x, MatchResultListener* listener) const {
183 return impl_->MatchAndExplain(x, listener);
184 }
185
shiqiane35fdd92008-12-10 05:08:54 +0000186 // Returns true iff this matcher matches x.
zhanyong.wan82113312010-01-08 21:55:40 +0000187 bool Matches(T x) const {
188 DummyMatchResultListener dummy;
189 return MatchAndExplain(x, &dummy);
190 }
shiqiane35fdd92008-12-10 05:08:54 +0000191
192 // Describes this matcher to an ostream.
193 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
194
195 // Describes the negation of this matcher to an ostream.
196 void DescribeNegationTo(::std::ostream* os) const {
197 impl_->DescribeNegationTo(os);
198 }
199
200 // Explains why x matches, or doesn't match, the matcher.
201 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000202 StreamMatchResultListener listener(os);
203 MatchAndExplain(x, &listener);
shiqiane35fdd92008-12-10 05:08:54 +0000204 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000205
shiqiane35fdd92008-12-10 05:08:54 +0000206 protected:
207 MatcherBase() {}
208
209 // Constructs a matcher from its implementation.
210 explicit MatcherBase(const MatcherInterface<T>* impl)
211 : impl_(impl) {}
212
213 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000214
shiqiane35fdd92008-12-10 05:08:54 +0000215 private:
216 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
217 // interfaces. The former dynamically allocates a chunk of memory
218 // to hold the reference count, while the latter tracks all
219 // references using a circular linked list without allocating
220 // memory. It has been observed that linked_ptr performs better in
221 // typical scenarios. However, shared_ptr can out-perform
222 // linked_ptr when there are many more uses of the copy constructor
223 // than the default constructor.
224 //
225 // If performance becomes a problem, we should see if using
226 // shared_ptr helps.
227 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
228};
229
shiqiane35fdd92008-12-10 05:08:54 +0000230} // namespace internal
231
232// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
233// object that can check whether a value of type T matches. The
234// implementation of Matcher<T> is just a linked_ptr to const
235// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
236// from Matcher!
237template <typename T>
238class Matcher : public internal::MatcherBase<T> {
239 public:
240 // Constructs a null matcher. Needed for storing Matcher objects in
241 // STL containers.
242 Matcher() {}
243
244 // Constructs a matcher from its implementation.
245 explicit Matcher(const MatcherInterface<T>* impl)
246 : internal::MatcherBase<T>(impl) {}
247
zhanyong.wan18490652009-05-11 18:54:08 +0000248 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000249 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
250 Matcher(T value); // NOLINT
251};
252
253// The following two specializations allow the user to write str
254// instead of Eq(str) and "foo" instead of Eq("foo") when a string
255// matcher is expected.
256template <>
257class Matcher<const internal::string&>
258 : public internal::MatcherBase<const internal::string&> {
259 public:
260 Matcher() {}
261
262 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
263 : internal::MatcherBase<const internal::string&>(impl) {}
264
265 // Allows the user to write str instead of Eq(str) sometimes, where
266 // str is a string object.
267 Matcher(const internal::string& s); // NOLINT
268
269 // Allows the user to write "foo" instead of Eq("foo") sometimes.
270 Matcher(const char* s); // NOLINT
271};
272
273template <>
274class Matcher<internal::string>
275 : public internal::MatcherBase<internal::string> {
276 public:
277 Matcher() {}
278
279 explicit Matcher(const MatcherInterface<internal::string>* impl)
280 : internal::MatcherBase<internal::string>(impl) {}
281
282 // Allows the user to write str instead of Eq(str) sometimes, where
283 // str is a string object.
284 Matcher(const internal::string& s); // NOLINT
285
286 // Allows the user to write "foo" instead of Eq("foo") sometimes.
287 Matcher(const char* s); // NOLINT
288};
289
290// The PolymorphicMatcher class template makes it easy to implement a
291// polymorphic matcher (i.e. a matcher that can match values of more
292// than one type, e.g. Eq(n) and NotNull()).
293//
zhanyong.wandb22c222010-01-28 21:52:29 +0000294// To define a polymorphic matcher, a user should provide an Impl
295// class that has a DescribeTo() method and a DescribeNegationTo()
296// method, and define a member function (or member function template)
shiqiane35fdd92008-12-10 05:08:54 +0000297//
zhanyong.wandb22c222010-01-28 21:52:29 +0000298// bool MatchAndExplain(const Value& value,
299// MatchResultListener* listener) const;
zhanyong.wan82113312010-01-08 21:55:40 +0000300//
301// See the definition of NotNull() for a complete example.
shiqiane35fdd92008-12-10 05:08:54 +0000302template <class Impl>
303class PolymorphicMatcher {
304 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000305 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000306
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000307 // Returns a mutable reference to the underlying matcher
308 // implementation object.
309 Impl& mutable_impl() { return impl_; }
310
311 // Returns an immutable reference to the underlying matcher
312 // implementation object.
313 const Impl& impl() const { return impl_; }
314
shiqiane35fdd92008-12-10 05:08:54 +0000315 template <typename T>
316 operator Matcher<T>() const {
317 return Matcher<T>(new MonomorphicImpl<T>(impl_));
318 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000319
shiqiane35fdd92008-12-10 05:08:54 +0000320 private:
321 template <typename T>
322 class MonomorphicImpl : public MatcherInterface<T> {
323 public:
324 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
325
shiqiane35fdd92008-12-10 05:08:54 +0000326 virtual void DescribeTo(::std::ostream* os) const {
327 impl_.DescribeTo(os);
328 }
329
330 virtual void DescribeNegationTo(::std::ostream* os) const {
331 impl_.DescribeNegationTo(os);
332 }
333
zhanyong.wan82113312010-01-08 21:55:40 +0000334 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
zhanyong.wandb22c222010-01-28 21:52:29 +0000335 return impl_.MatchAndExplain(x, listener);
shiqiane35fdd92008-12-10 05:08:54 +0000336 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000337
shiqiane35fdd92008-12-10 05:08:54 +0000338 private:
339 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000340
341 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000342 };
343
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000344 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000345
346 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000347};
348
349// Creates a matcher from its implementation. This is easier to use
350// than the Matcher<T> constructor as it doesn't require you to
351// explicitly write the template argument, e.g.
352//
353// MakeMatcher(foo);
354// vs
355// Matcher<const string&>(foo);
356template <typename T>
357inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
358 return Matcher<T>(impl);
359};
360
361// Creates a polymorphic matcher from its implementation. This is
362// easier to use than the PolymorphicMatcher<Impl> constructor as it
363// doesn't require you to explicitly write the template argument, e.g.
364//
365// MakePolymorphicMatcher(foo);
366// vs
367// PolymorphicMatcher<TypeOfFoo>(foo);
368template <class Impl>
369inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
370 return PolymorphicMatcher<Impl>(impl);
371}
372
373// In order to be safe and clear, casting between different matcher
374// types is done explicitly via MatcherCast<T>(m), which takes a
375// matcher m and returns a Matcher<T>. It compiles only when T can be
376// statically converted to the argument type of m.
377template <typename T, typename M>
378Matcher<T> MatcherCast(M m);
379
zhanyong.wan18490652009-05-11 18:54:08 +0000380// Implements SafeMatcherCast().
381//
zhanyong.wan95b12332009-09-25 18:55:50 +0000382// We use an intermediate class to do the actual safe casting as Nokia's
383// Symbian compiler cannot decide between
384// template <T, M> ... (M) and
385// template <T, U> ... (const Matcher<U>&)
386// for function templates but can for member function templates.
387template <typename T>
388class SafeMatcherCastImpl {
389 public:
390 // This overload handles polymorphic matchers only since monomorphic
391 // matchers are handled by the next one.
392 template <typename M>
393 static inline Matcher<T> Cast(M polymorphic_matcher) {
394 return Matcher<T>(polymorphic_matcher);
395 }
zhanyong.wan18490652009-05-11 18:54:08 +0000396
zhanyong.wan95b12332009-09-25 18:55:50 +0000397 // This overload handles monomorphic matchers.
398 //
399 // In general, if type T can be implicitly converted to type U, we can
400 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
401 // contravariant): just keep a copy of the original Matcher<U>, convert the
402 // argument from type T to U, and then pass it to the underlying Matcher<U>.
403 // The only exception is when U is a reference and T is not, as the
404 // underlying Matcher<U> may be interested in the argument's address, which
405 // is not preserved in the conversion from T to U.
406 template <typename U>
407 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
408 // Enforce that T can be implicitly converted to U.
409 GMOCK_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
410 T_must_be_implicitly_convertible_to_U);
411 // Enforce that we are not converting a non-reference type T to a reference
412 // type U.
413 GMOCK_COMPILE_ASSERT_(
414 internal::is_reference<T>::value || !internal::is_reference<U>::value,
415 cannot_convert_non_referentce_arg_to_reference);
416 // In case both T and U are arithmetic types, enforce that the
417 // conversion is not lossy.
418 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(T)) RawT;
419 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(U)) RawU;
420 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
421 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
422 GMOCK_COMPILE_ASSERT_(
423 kTIsOther || kUIsOther ||
424 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
425 conversion_of_arithmetic_types_must_be_lossless);
426 return MatcherCast<T>(matcher);
427 }
428};
429
430template <typename T, typename M>
431inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
432 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000433}
434
shiqiane35fdd92008-12-10 05:08:54 +0000435// A<T>() returns a matcher that matches any value of type T.
436template <typename T>
437Matcher<T> A();
438
439// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
440// and MUST NOT BE USED IN USER CODE!!!
441namespace internal {
442
zhanyong.wan82113312010-01-08 21:55:40 +0000443// If the given string is not empty and os is not NULL, wraps the
444// string inside a pair of parentheses and streams the result to os.
445inline void StreamInParensAsNeeded(const internal::string& str,
446 ::std::ostream* os) {
447 if (!str.empty() && os != NULL) {
448 *os << " (" << str << ")";
shiqiane35fdd92008-12-10 05:08:54 +0000449 }
450}
451
452// An internal helper class for doing compile-time loop on a tuple's
453// fields.
454template <size_t N>
455class TuplePrefix {
456 public:
457 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
458 // iff the first N fields of matcher_tuple matches the first N
459 // fields of value_tuple, respectively.
460 template <typename MatcherTuple, typename ValueTuple>
461 static bool Matches(const MatcherTuple& matcher_tuple,
462 const ValueTuple& value_tuple) {
463 using ::std::tr1::get;
464 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
465 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
466 }
467
468 // TuplePrefix<N>::DescribeMatchFailuresTo(matchers, values, os)
469 // describes failures in matching the first N fields of matchers
470 // against the first N fields of values. If there is no failure,
471 // nothing will be streamed to os.
472 template <typename MatcherTuple, typename ValueTuple>
473 static void DescribeMatchFailuresTo(const MatcherTuple& matchers,
474 const ValueTuple& values,
475 ::std::ostream* os) {
476 using ::std::tr1::tuple_element;
477 using ::std::tr1::get;
478
479 // First, describes failures in the first N - 1 fields.
480 TuplePrefix<N - 1>::DescribeMatchFailuresTo(matchers, values, os);
481
482 // Then describes the failure (if any) in the (N - 1)-th (0-based)
483 // field.
484 typename tuple_element<N - 1, MatcherTuple>::type matcher =
485 get<N - 1>(matchers);
486 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
487 Value value = get<N - 1>(values);
zhanyong.wan82113312010-01-08 21:55:40 +0000488 StringMatchResultListener listener;
489 if (!matcher.MatchAndExplain(value, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +0000490 // TODO(wan): include in the message the name of the parameter
491 // as used in MOCK_METHOD*() when possible.
492 *os << " Expected arg #" << N - 1 << ": ";
493 get<N - 1>(matchers).DescribeTo(os);
494 *os << "\n Actual: ";
495 // We remove the reference in type Value to prevent the
496 // universal printer from printing the address of value, which
497 // isn't interesting to the user most of the time. The
zhanyong.wandb22c222010-01-28 21:52:29 +0000498 // matcher's MatchAndExplain() method handles the case when
shiqiane35fdd92008-12-10 05:08:54 +0000499 // the address is interesting.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000500 internal::UniversalPrinter<GMOCK_REMOVE_REFERENCE_(Value)>::
shiqiane35fdd92008-12-10 05:08:54 +0000501 Print(value, os);
zhanyong.wan82113312010-01-08 21:55:40 +0000502
503 StreamInParensAsNeeded(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +0000504 *os << "\n";
505 }
506 }
507};
508
509// The base case.
510template <>
511class TuplePrefix<0> {
512 public:
513 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000514 static bool Matches(const MatcherTuple& /* matcher_tuple */,
515 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000516 return true;
517 }
518
519 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000520 static void DescribeMatchFailuresTo(const MatcherTuple& /* matchers */,
521 const ValueTuple& /* values */,
522 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000523};
524
525// TupleMatches(matcher_tuple, value_tuple) returns true iff all
526// matchers in matcher_tuple match the corresponding fields in
527// value_tuple. It is a compiler error if matcher_tuple and
528// value_tuple have different number of fields or incompatible field
529// types.
530template <typename MatcherTuple, typename ValueTuple>
531bool TupleMatches(const MatcherTuple& matcher_tuple,
532 const ValueTuple& value_tuple) {
533 using ::std::tr1::tuple_size;
534 // Makes sure that matcher_tuple and value_tuple have the same
535 // number of fields.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000536 GMOCK_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
537 tuple_size<ValueTuple>::value,
538 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000539 return TuplePrefix<tuple_size<ValueTuple>::value>::
540 Matches(matcher_tuple, value_tuple);
541}
542
543// Describes failures in matching matchers against values. If there
544// is no failure, nothing will be streamed to os.
545template <typename MatcherTuple, typename ValueTuple>
546void DescribeMatchFailureTupleTo(const MatcherTuple& matchers,
547 const ValueTuple& values,
548 ::std::ostream* os) {
549 using ::std::tr1::tuple_size;
550 TuplePrefix<tuple_size<MatcherTuple>::value>::DescribeMatchFailuresTo(
551 matchers, values, os);
552}
553
554// The MatcherCastImpl class template is a helper for implementing
555// MatcherCast(). We need this helper in order to partially
556// specialize the implementation of MatcherCast() (C++ allows
557// class/struct templates to be partially specialized, but not
558// function templates.).
559
560// This general version is used when MatcherCast()'s argument is a
561// polymorphic matcher (i.e. something that can be converted to a
562// Matcher but is not one yet; for example, Eq(value)).
563template <typename T, typename M>
564class MatcherCastImpl {
565 public:
566 static Matcher<T> Cast(M polymorphic_matcher) {
567 return Matcher<T>(polymorphic_matcher);
568 }
569};
570
571// This more specialized version is used when MatcherCast()'s argument
572// is already a Matcher. This only compiles when type T can be
573// statically converted to type U.
574template <typename T, typename U>
575class MatcherCastImpl<T, Matcher<U> > {
576 public:
577 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
578 return Matcher<T>(new Impl(source_matcher));
579 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000580
shiqiane35fdd92008-12-10 05:08:54 +0000581 private:
582 class Impl : public MatcherInterface<T> {
583 public:
584 explicit Impl(const Matcher<U>& source_matcher)
585 : source_matcher_(source_matcher) {}
586
587 // We delegate the matching logic to the source matcher.
zhanyong.wan82113312010-01-08 21:55:40 +0000588 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
589 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000590 }
591
592 virtual void DescribeTo(::std::ostream* os) const {
593 source_matcher_.DescribeTo(os);
594 }
595
596 virtual void DescribeNegationTo(::std::ostream* os) const {
597 source_matcher_.DescribeNegationTo(os);
598 }
599
shiqiane35fdd92008-12-10 05:08:54 +0000600 private:
601 const Matcher<U> source_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000602
603 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000604 };
605};
606
607// This even more specialized version is used for efficiently casting
608// a matcher to its own type.
609template <typename T>
610class MatcherCastImpl<T, Matcher<T> > {
611 public:
612 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
613};
614
615// Implements A<T>().
616template <typename T>
617class AnyMatcherImpl : public MatcherInterface<T> {
618 public:
zhanyong.wan82113312010-01-08 21:55:40 +0000619 virtual bool MatchAndExplain(
620 T /* x */, MatchResultListener* /* listener */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000621 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
622 virtual void DescribeNegationTo(::std::ostream* os) const {
623 // This is mostly for completeness' safe, as it's not very useful
624 // to write Not(A<bool>()). However we cannot completely rule out
625 // such a possibility, and it doesn't hurt to be prepared.
626 *os << "never matches";
627 }
628};
629
630// Implements _, a matcher that matches any value of any
631// type. This is a polymorphic matcher, so we need a template type
632// conversion operator to make it appearing as a Matcher<T> for any
633// type T.
634class AnythingMatcher {
635 public:
636 template <typename T>
637 operator Matcher<T>() const { return A<T>(); }
638};
639
640// Implements a matcher that compares a given value with a
641// pre-supplied value using one of the ==, <=, <, etc, operators. The
642// two values being compared don't have to have the same type.
643//
644// The matcher defined here is polymorphic (for example, Eq(5) can be
645// used to match an int, a short, a double, etc). Therefore we use
646// a template type conversion operator in the implementation.
647//
648// We define this as a macro in order to eliminate duplicated source
649// code.
650//
651// The following template definition assumes that the Rhs parameter is
652// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wane0d051e2009-02-19 00:33:37 +0000653#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000654 template <typename Rhs> class name##Matcher { \
655 public: \
656 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
657 template <typename Lhs> \
658 operator Matcher<Lhs>() const { \
659 return MakeMatcher(new Impl<Lhs>(rhs_)); \
660 } \
661 private: \
662 template <typename Lhs> \
663 class Impl : public MatcherInterface<Lhs> { \
664 public: \
665 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
zhanyong.wan82113312010-01-08 21:55:40 +0000666 virtual bool MatchAndExplain(\
667 Lhs lhs, MatchResultListener* /* listener */) const { \
668 return lhs op rhs_; \
669 } \
shiqiane35fdd92008-12-10 05:08:54 +0000670 virtual void DescribeTo(::std::ostream* os) const { \
671 *os << "is " relation " "; \
672 UniversalPrinter<Rhs>::Print(rhs_, os); \
673 } \
674 virtual void DescribeNegationTo(::std::ostream* os) const { \
675 *os << "is not " relation " "; \
676 UniversalPrinter<Rhs>::Print(rhs_, os); \
677 } \
678 private: \
679 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000680 GTEST_DISALLOW_ASSIGN_(Impl); \
shiqiane35fdd92008-12-10 05:08:54 +0000681 }; \
682 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000683 GTEST_DISALLOW_ASSIGN_(name##Matcher); \
shiqiane35fdd92008-12-10 05:08:54 +0000684 }
685
686// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
687// respectively.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000688GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "equal to");
689GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "greater than or equal to");
690GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "greater than");
691GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "less than or equal to");
692GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "less than");
693GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "not equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000694
zhanyong.wane0d051e2009-02-19 00:33:37 +0000695#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000696
vladlosev79b83502009-11-18 00:43:37 +0000697// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000698// pointer that is NULL.
699class IsNullMatcher {
700 public:
vladlosev79b83502009-11-18 00:43:37 +0000701 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000702 bool MatchAndExplain(const Pointer& p,
703 MatchResultListener* /* listener */) const {
704 return GetRawPointer(p) == NULL;
705 }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000706
707 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
708 void DescribeNegationTo(::std::ostream* os) const {
709 *os << "is not NULL";
710 }
711};
712
vladlosev79b83502009-11-18 00:43:37 +0000713// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000714// pointer that is not NULL.
715class NotNullMatcher {
716 public:
vladlosev79b83502009-11-18 00:43:37 +0000717 template <typename Pointer>
zhanyong.wandb22c222010-01-28 21:52:29 +0000718 bool MatchAndExplain(const Pointer& p,
719 MatchResultListener* /* listener */) const {
720 return GetRawPointer(p) != NULL;
721 }
shiqiane35fdd92008-12-10 05:08:54 +0000722
723 void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; }
724 void DescribeNegationTo(::std::ostream* os) const {
725 *os << "is NULL";
726 }
727};
728
729// Ref(variable) matches any argument that is a reference to
730// 'variable'. This matcher is polymorphic as it can match any
731// super type of the type of 'variable'.
732//
733// The RefMatcher template class implements Ref(variable). It can
734// only be instantiated with a reference type. This prevents a user
735// from mistakenly using Ref(x) to match a non-reference function
736// argument. For example, the following will righteously cause a
737// compiler error:
738//
739// int n;
740// Matcher<int> m1 = Ref(n); // This won't compile.
741// Matcher<int&> m2 = Ref(n); // This will compile.
742template <typename T>
743class RefMatcher;
744
745template <typename T>
746class RefMatcher<T&> {
747 // Google Mock is a generic framework and thus needs to support
748 // mocking any function types, including those that take non-const
749 // reference arguments. Therefore the template parameter T (and
750 // Super below) can be instantiated to either a const type or a
751 // non-const type.
752 public:
753 // RefMatcher() takes a T& instead of const T&, as we want the
754 // compiler to catch using Ref(const_value) as a matcher for a
755 // non-const reference.
756 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
757
758 template <typename Super>
759 operator Matcher<Super&>() const {
760 // By passing object_ (type T&) to Impl(), which expects a Super&,
761 // we make sure that Super is a super type of T. In particular,
762 // this catches using Ref(const_value) as a matcher for a
763 // non-const reference, as you cannot implicitly convert a const
764 // reference to a non-const reference.
765 return MakeMatcher(new Impl<Super>(object_));
766 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000767
shiqiane35fdd92008-12-10 05:08:54 +0000768 private:
769 template <typename Super>
770 class Impl : public MatcherInterface<Super&> {
771 public:
772 explicit Impl(Super& x) : object_(x) {} // NOLINT
773
zhanyong.wandb22c222010-01-28 21:52:29 +0000774 // MatchAndExplain() takes a Super& (as opposed to const Super&)
775 // in order to match the interface MatcherInterface<Super&>.
zhanyong.wan82113312010-01-08 21:55:40 +0000776 virtual bool MatchAndExplain(
777 Super& x, MatchResultListener* listener) const {
778 *listener << "is located @" << static_cast<const void*>(&x);
779 return &x == &object_;
780 }
shiqiane35fdd92008-12-10 05:08:54 +0000781
782 virtual void DescribeTo(::std::ostream* os) const {
783 *os << "references the variable ";
784 UniversalPrinter<Super&>::Print(object_, os);
785 }
786
787 virtual void DescribeNegationTo(::std::ostream* os) const {
788 *os << "does not reference the variable ";
789 UniversalPrinter<Super&>::Print(object_, os);
790 }
791
shiqiane35fdd92008-12-10 05:08:54 +0000792 private:
793 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000794
795 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000796 };
797
798 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000799
800 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000801};
802
803// Polymorphic helper functions for narrow and wide string matchers.
804inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
805 return String::CaseInsensitiveCStringEquals(lhs, rhs);
806}
807
808inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
809 const wchar_t* rhs) {
810 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
811}
812
813// String comparison for narrow or wide strings that can have embedded NUL
814// characters.
815template <typename StringType>
816bool CaseInsensitiveStringEquals(const StringType& s1,
817 const StringType& s2) {
818 // Are the heads equal?
819 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
820 return false;
821 }
822
823 // Skip the equal heads.
824 const typename StringType::value_type nul = 0;
825 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
826
827 // Are we at the end of either s1 or s2?
828 if (i1 == StringType::npos || i2 == StringType::npos) {
829 return i1 == i2;
830 }
831
832 // Are the tails equal?
833 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
834}
835
836// String matchers.
837
838// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
839template <typename StringType>
840class StrEqualityMatcher {
841 public:
842 typedef typename StringType::const_pointer ConstCharPointer;
843
844 StrEqualityMatcher(const StringType& str, bool expect_eq,
845 bool case_sensitive)
846 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
847
848 // When expect_eq_ is true, returns true iff s is equal to string_;
849 // otherwise returns true iff s is not equal to string_.
zhanyong.wandb22c222010-01-28 21:52:29 +0000850 bool MatchAndExplain(ConstCharPointer s,
851 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +0000852 if (s == NULL) {
853 return !expect_eq_;
854 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000855 return MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000856 }
857
zhanyong.wandb22c222010-01-28 21:52:29 +0000858 bool MatchAndExplain(const StringType& s,
859 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000860 const bool eq = case_sensitive_ ? s == string_ :
861 CaseInsensitiveStringEquals(s, string_);
862 return expect_eq_ == eq;
863 }
864
865 void DescribeTo(::std::ostream* os) const {
866 DescribeToHelper(expect_eq_, os);
867 }
868
869 void DescribeNegationTo(::std::ostream* os) const {
870 DescribeToHelper(!expect_eq_, os);
871 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000872
shiqiane35fdd92008-12-10 05:08:54 +0000873 private:
874 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
875 *os << "is ";
876 if (!expect_eq) {
877 *os << "not ";
878 }
879 *os << "equal to ";
880 if (!case_sensitive_) {
881 *os << "(ignoring case) ";
882 }
883 UniversalPrinter<StringType>::Print(string_, os);
884 }
885
886 const StringType string_;
887 const bool expect_eq_;
888 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000889
890 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000891};
892
893// Implements the polymorphic HasSubstr(substring) matcher, which
894// can be used as a Matcher<T> as long as T can be converted to a
895// string.
896template <typename StringType>
897class HasSubstrMatcher {
898 public:
899 typedef typename StringType::const_pointer ConstCharPointer;
900
901 explicit HasSubstrMatcher(const StringType& substring)
902 : substring_(substring) {}
903
904 // These overloaded methods allow HasSubstr(substring) to be used as a
905 // Matcher<T> as long as T can be converted to string. Returns true
906 // iff s contains substring_ as a substring.
zhanyong.wandb22c222010-01-28 21:52:29 +0000907 bool MatchAndExplain(ConstCharPointer s,
908 MatchResultListener* listener) const {
909 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000910 }
911
zhanyong.wandb22c222010-01-28 21:52:29 +0000912 bool MatchAndExplain(const StringType& s,
913 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000914 return s.find(substring_) != StringType::npos;
915 }
916
917 // Describes what this matcher matches.
918 void DescribeTo(::std::ostream* os) const {
919 *os << "has substring ";
920 UniversalPrinter<StringType>::Print(substring_, os);
921 }
922
923 void DescribeNegationTo(::std::ostream* os) const {
924 *os << "has no substring ";
925 UniversalPrinter<StringType>::Print(substring_, os);
926 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000927
shiqiane35fdd92008-12-10 05:08:54 +0000928 private:
929 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000930
931 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000932};
933
934// Implements the polymorphic StartsWith(substring) matcher, which
935// can be used as a Matcher<T> as long as T can be converted to a
936// string.
937template <typename StringType>
938class StartsWithMatcher {
939 public:
940 typedef typename StringType::const_pointer ConstCharPointer;
941
942 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
943 }
944
945 // These overloaded methods allow StartsWith(prefix) to be used as a
946 // Matcher<T> as long as T can be converted to string. Returns true
947 // iff s starts with prefix_.
zhanyong.wandb22c222010-01-28 21:52:29 +0000948 bool MatchAndExplain(ConstCharPointer s,
949 MatchResultListener* listener) const {
950 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000951 }
952
zhanyong.wandb22c222010-01-28 21:52:29 +0000953 bool MatchAndExplain(const StringType& s,
954 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000955 return s.length() >= prefix_.length() &&
956 s.substr(0, prefix_.length()) == prefix_;
957 }
958
959 void DescribeTo(::std::ostream* os) const {
960 *os << "starts with ";
961 UniversalPrinter<StringType>::Print(prefix_, os);
962 }
963
964 void DescribeNegationTo(::std::ostream* os) const {
965 *os << "doesn't start with ";
966 UniversalPrinter<StringType>::Print(prefix_, os);
967 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000968
shiqiane35fdd92008-12-10 05:08:54 +0000969 private:
970 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000971
972 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000973};
974
975// Implements the polymorphic EndsWith(substring) matcher, which
976// can be used as a Matcher<T> as long as T can be converted to a
977// string.
978template <typename StringType>
979class EndsWithMatcher {
980 public:
981 typedef typename StringType::const_pointer ConstCharPointer;
982
983 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
984
985 // These overloaded methods allow EndsWith(suffix) to be used as a
986 // Matcher<T> as long as T can be converted to string. Returns true
987 // iff s ends with suffix_.
zhanyong.wandb22c222010-01-28 21:52:29 +0000988 bool MatchAndExplain(ConstCharPointer s,
989 MatchResultListener* listener) const {
990 return s != NULL && MatchAndExplain(StringType(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +0000991 }
992
zhanyong.wandb22c222010-01-28 21:52:29 +0000993 bool MatchAndExplain(const StringType& s,
994 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000995 return s.length() >= suffix_.length() &&
996 s.substr(s.length() - suffix_.length()) == suffix_;
997 }
998
999 void DescribeTo(::std::ostream* os) const {
1000 *os << "ends with ";
1001 UniversalPrinter<StringType>::Print(suffix_, os);
1002 }
1003
1004 void DescribeNegationTo(::std::ostream* os) const {
1005 *os << "doesn't end with ";
1006 UniversalPrinter<StringType>::Print(suffix_, os);
1007 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001008
shiqiane35fdd92008-12-10 05:08:54 +00001009 private:
1010 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001011
1012 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001013};
1014
shiqiane35fdd92008-12-10 05:08:54 +00001015// Implements polymorphic matchers MatchesRegex(regex) and
1016// ContainsRegex(regex), which can be used as a Matcher<T> as long as
1017// T can be converted to a string.
1018class MatchesRegexMatcher {
1019 public:
1020 MatchesRegexMatcher(const RE* regex, bool full_match)
1021 : regex_(regex), full_match_(full_match) {}
1022
1023 // These overloaded methods allow MatchesRegex(regex) to be used as
1024 // a Matcher<T> as long as T can be converted to string. Returns
1025 // true iff s matches regular expression regex. When full_match_ is
1026 // true, a full match is done; otherwise a partial match is done.
zhanyong.wandb22c222010-01-28 21:52:29 +00001027 bool MatchAndExplain(const char* s,
1028 MatchResultListener* listener) const {
1029 return s != NULL && MatchAndExplain(internal::string(s), listener);
shiqiane35fdd92008-12-10 05:08:54 +00001030 }
1031
zhanyong.wandb22c222010-01-28 21:52:29 +00001032 bool MatchAndExplain(const internal::string& s,
1033 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001034 return full_match_ ? RE::FullMatch(s, *regex_) :
1035 RE::PartialMatch(s, *regex_);
1036 }
1037
1038 void DescribeTo(::std::ostream* os) const {
1039 *os << (full_match_ ? "matches" : "contains")
1040 << " regular expression ";
1041 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1042 }
1043
1044 void DescribeNegationTo(::std::ostream* os) const {
1045 *os << "doesn't " << (full_match_ ? "match" : "contain")
1046 << " regular expression ";
1047 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1048 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001049
shiqiane35fdd92008-12-10 05:08:54 +00001050 private:
1051 const internal::linked_ptr<const RE> regex_;
1052 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001053
1054 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001055};
1056
shiqiane35fdd92008-12-10 05:08:54 +00001057// Implements a matcher that compares the two fields of a 2-tuple
1058// using one of the ==, <=, <, etc, operators. The two fields being
1059// compared don't have to have the same type.
1060//
1061// The matcher defined here is polymorphic (for example, Eq() can be
1062// used to match a tuple<int, short>, a tuple<const long&, double>,
1063// etc). Therefore we use a template type conversion operator in the
1064// implementation.
1065//
1066// We define this as a macro in order to eliminate duplicated source
1067// code.
zhanyong.wan2661c682009-06-09 05:42:12 +00001068#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op) \
shiqiane35fdd92008-12-10 05:08:54 +00001069 class name##2Matcher { \
1070 public: \
1071 template <typename T1, typename T2> \
1072 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
1073 return MakeMatcher(new Impl<T1, T2>); \
1074 } \
1075 private: \
1076 template <typename T1, typename T2> \
1077 class Impl : public MatcherInterface<const ::std::tr1::tuple<T1, T2>&> { \
1078 public: \
zhanyong.wan82113312010-01-08 21:55:40 +00001079 virtual bool MatchAndExplain( \
1080 const ::std::tr1::tuple<T1, T2>& args, \
1081 MatchResultListener* /* listener */) const { \
shiqiane35fdd92008-12-10 05:08:54 +00001082 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
1083 } \
1084 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +00001085 *os << "are a pair (x, y) where x " #op " y"; \
shiqiane35fdd92008-12-10 05:08:54 +00001086 } \
1087 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +00001088 *os << "are a pair (x, y) where x " #op " y is false"; \
shiqiane35fdd92008-12-10 05:08:54 +00001089 } \
1090 }; \
1091 }
1092
1093// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wan2661c682009-06-09 05:42:12 +00001094GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==);
1095GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ge, >=);
1096GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Gt, >);
1097GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Le, <=);
1098GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Lt, <);
1099GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=);
shiqiane35fdd92008-12-10 05:08:54 +00001100
zhanyong.wane0d051e2009-02-19 00:33:37 +00001101#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +00001102
zhanyong.wanc6a41232009-05-13 23:38:40 +00001103// Implements the Not(...) matcher for a particular argument type T.
1104// We do not nest it inside the NotMatcher class template, as that
1105// will prevent different instantiations of NotMatcher from sharing
1106// the same NotMatcherImpl<T> class.
1107template <typename T>
1108class NotMatcherImpl : public MatcherInterface<T> {
1109 public:
1110 explicit NotMatcherImpl(const Matcher<T>& matcher)
1111 : matcher_(matcher) {}
1112
zhanyong.wan82113312010-01-08 21:55:40 +00001113 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1114 return !matcher_.MatchAndExplain(x, listener);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001115 }
1116
1117 virtual void DescribeTo(::std::ostream* os) const {
1118 matcher_.DescribeNegationTo(os);
1119 }
1120
1121 virtual void DescribeNegationTo(::std::ostream* os) const {
1122 matcher_.DescribeTo(os);
1123 }
1124
zhanyong.wanc6a41232009-05-13 23:38:40 +00001125 private:
1126 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001127
1128 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001129};
1130
shiqiane35fdd92008-12-10 05:08:54 +00001131// Implements the Not(m) matcher, which matches a value that doesn't
1132// match matcher m.
1133template <typename InnerMatcher>
1134class NotMatcher {
1135 public:
1136 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1137
1138 // This template type conversion operator allows Not(m) to be used
1139 // to match any type m can match.
1140 template <typename T>
1141 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001142 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001143 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001144
shiqiane35fdd92008-12-10 05:08:54 +00001145 private:
shiqiane35fdd92008-12-10 05:08:54 +00001146 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001147
1148 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001149};
1150
zhanyong.wanc6a41232009-05-13 23:38:40 +00001151// Implements the AllOf(m1, m2) matcher for a particular argument type
1152// T. We do not nest it inside the BothOfMatcher class template, as
1153// that will prevent different instantiations of BothOfMatcher from
1154// sharing the same BothOfMatcherImpl<T> class.
1155template <typename T>
1156class BothOfMatcherImpl : public MatcherInterface<T> {
1157 public:
1158 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1159 : matcher1_(matcher1), matcher2_(matcher2) {}
1160
zhanyong.wanc6a41232009-05-13 23:38:40 +00001161 virtual void DescribeTo(::std::ostream* os) const {
1162 *os << "(";
1163 matcher1_.DescribeTo(os);
1164 *os << ") and (";
1165 matcher2_.DescribeTo(os);
1166 *os << ")";
1167 }
1168
1169 virtual void DescribeNegationTo(::std::ostream* os) const {
1170 *os << "not ";
1171 DescribeTo(os);
1172 }
1173
zhanyong.wan82113312010-01-08 21:55:40 +00001174 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1175 // If either matcher1_ or matcher2_ doesn't match x, we only need
1176 // to explain why one of them fails.
1177 StringMatchResultListener listener1;
1178 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1179 *listener << listener1.str();
1180 return false;
1181 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001182
zhanyong.wan82113312010-01-08 21:55:40 +00001183 StringMatchResultListener listener2;
1184 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1185 *listener << listener2.str();
1186 return false;
1187 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001188
zhanyong.wan82113312010-01-08 21:55:40 +00001189 // Otherwise we need to explain why *both* of them match.
1190 const internal::string s1 = listener1.str();
1191 const internal::string s2 = listener2.str();
1192
1193 if (s1 == "") {
1194 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001195 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001196 *listener << s1;
1197 if (s2 != "") {
1198 *listener << "; " << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001199 }
1200 }
zhanyong.wan82113312010-01-08 21:55:40 +00001201 return true;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001202 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001203
zhanyong.wanc6a41232009-05-13 23:38:40 +00001204 private:
1205 const Matcher<T> matcher1_;
1206 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001207
1208 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001209};
1210
shiqiane35fdd92008-12-10 05:08:54 +00001211// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1212// matches a value that matches all of the matchers m_1, ..., and m_n.
1213template <typename Matcher1, typename Matcher2>
1214class BothOfMatcher {
1215 public:
1216 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1217 : matcher1_(matcher1), matcher2_(matcher2) {}
1218
1219 // This template type conversion operator allows a
1220 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1221 // both Matcher1 and Matcher2 can match.
1222 template <typename T>
1223 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001224 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1225 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001226 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001227
shiqiane35fdd92008-12-10 05:08:54 +00001228 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001229 Matcher1 matcher1_;
1230 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001231
1232 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001233};
shiqiane35fdd92008-12-10 05:08:54 +00001234
zhanyong.wanc6a41232009-05-13 23:38:40 +00001235// Implements the AnyOf(m1, m2) matcher for a particular argument type
1236// T. We do not nest it inside the AnyOfMatcher class template, as
1237// that will prevent different instantiations of AnyOfMatcher from
1238// sharing the same EitherOfMatcherImpl<T> class.
1239template <typename T>
1240class EitherOfMatcherImpl : public MatcherInterface<T> {
1241 public:
1242 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1243 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001244
zhanyong.wanc6a41232009-05-13 23:38:40 +00001245 virtual void DescribeTo(::std::ostream* os) const {
1246 *os << "(";
1247 matcher1_.DescribeTo(os);
1248 *os << ") or (";
1249 matcher2_.DescribeTo(os);
1250 *os << ")";
1251 }
shiqiane35fdd92008-12-10 05:08:54 +00001252
zhanyong.wanc6a41232009-05-13 23:38:40 +00001253 virtual void DescribeNegationTo(::std::ostream* os) const {
1254 *os << "not ";
1255 DescribeTo(os);
1256 }
shiqiane35fdd92008-12-10 05:08:54 +00001257
zhanyong.wan82113312010-01-08 21:55:40 +00001258 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1259 // If either matcher1_ or matcher2_ matches x, we just need to
1260 // explain why *one* of them matches.
1261 StringMatchResultListener listener1;
1262 if (matcher1_.MatchAndExplain(x, &listener1)) {
1263 *listener << listener1.str();
1264 return true;
1265 }
1266
1267 StringMatchResultListener listener2;
1268 if (matcher2_.MatchAndExplain(x, &listener2)) {
1269 *listener << listener2.str();
1270 return true;
1271 }
1272
1273 // Otherwise we need to explain why *both* of them fail.
1274 const internal::string s1 = listener1.str();
1275 const internal::string s2 = listener2.str();
1276
1277 if (s1 == "") {
1278 *listener << s2;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001279 } else {
zhanyong.wan82113312010-01-08 21:55:40 +00001280 *listener << s1;
1281 if (s2 != "") {
1282 *listener << "; " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001283 }
1284 }
zhanyong.wan82113312010-01-08 21:55:40 +00001285 return false;
zhanyong.wanc6a41232009-05-13 23:38:40 +00001286 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001287
zhanyong.wanc6a41232009-05-13 23:38:40 +00001288 private:
1289 const Matcher<T> matcher1_;
1290 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001291
1292 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001293};
1294
1295// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1296// matches a value that matches at least one of the matchers m_1, ...,
1297// and m_n.
1298template <typename Matcher1, typename Matcher2>
1299class EitherOfMatcher {
1300 public:
1301 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1302 : matcher1_(matcher1), matcher2_(matcher2) {}
1303
1304 // This template type conversion operator allows a
1305 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1306 // both Matcher1 and Matcher2 can match.
1307 template <typename T>
1308 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001309 return Matcher<T>(new EitherOfMatcherImpl<T>(
1310 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001311 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001312
shiqiane35fdd92008-12-10 05:08:54 +00001313 private:
shiqiane35fdd92008-12-10 05:08:54 +00001314 Matcher1 matcher1_;
1315 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001316
1317 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001318};
1319
1320// Used for implementing Truly(pred), which turns a predicate into a
1321// matcher.
1322template <typename Predicate>
1323class TrulyMatcher {
1324 public:
1325 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1326
1327 // This method template allows Truly(pred) to be used as a matcher
1328 // for type T where T is the argument type of predicate 'pred'. The
1329 // argument is passed by reference as the predicate may be
1330 // interested in the address of the argument.
1331 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00001332 bool MatchAndExplain(T& x, // NOLINT
1333 MatchResultListener* /* listener */) const {
zhanyong.wan652540a2009-02-23 23:37:29 +00001334#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001335 // MSVC warns about converting a value into bool (warning 4800).
1336#pragma warning(push) // Saves the current warning state.
1337#pragma warning(disable:4800) // Temporarily disables warning 4800.
1338#endif // GTEST_OS_WINDOWS
1339 return predicate_(x);
zhanyong.wan652540a2009-02-23 23:37:29 +00001340#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001341#pragma warning(pop) // Restores the warning state.
1342#endif // GTEST_OS_WINDOWS
1343 }
1344
1345 void DescribeTo(::std::ostream* os) const {
1346 *os << "satisfies the given predicate";
1347 }
1348
1349 void DescribeNegationTo(::std::ostream* os) const {
1350 *os << "doesn't satisfy the given predicate";
1351 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001352
shiqiane35fdd92008-12-10 05:08:54 +00001353 private:
1354 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001355
1356 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001357};
1358
1359// Used for implementing Matches(matcher), which turns a matcher into
1360// a predicate.
1361template <typename M>
1362class MatcherAsPredicate {
1363 public:
1364 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1365
1366 // This template operator() allows Matches(m) to be used as a
1367 // predicate on type T where m is a matcher on type T.
1368 //
1369 // The argument x is passed by reference instead of by value, as
1370 // some matcher may be interested in its address (e.g. as in
1371 // Matches(Ref(n))(x)).
1372 template <typename T>
1373 bool operator()(const T& x) const {
1374 // We let matcher_ commit to a particular type here instead of
1375 // when the MatcherAsPredicate object was constructed. This
1376 // allows us to write Matches(m) where m is a polymorphic matcher
1377 // (e.g. Eq(5)).
1378 //
1379 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1380 // compile when matcher_ has type Matcher<const T&>; if we write
1381 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1382 // when matcher_ has type Matcher<T>; if we just write
1383 // matcher_.Matches(x), it won't compile when matcher_ is
1384 // polymorphic, e.g. Eq(5).
1385 //
1386 // MatcherCast<const T&>() is necessary for making the code work
1387 // in all of the above situations.
1388 return MatcherCast<const T&>(matcher_).Matches(x);
1389 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001390
shiqiane35fdd92008-12-10 05:08:54 +00001391 private:
1392 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001393
1394 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001395};
1396
1397// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1398// argument M must be a type that can be converted to a matcher.
1399template <typename M>
1400class PredicateFormatterFromMatcher {
1401 public:
1402 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1403
1404 // This template () operator allows a PredicateFormatterFromMatcher
1405 // object to act as a predicate-formatter suitable for using with
1406 // Google Test's EXPECT_PRED_FORMAT1() macro.
1407 template <typename T>
1408 AssertionResult operator()(const char* value_text, const T& x) const {
1409 // We convert matcher_ to a Matcher<const T&> *now* instead of
1410 // when the PredicateFormatterFromMatcher object was constructed,
1411 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1412 // know which type to instantiate it to until we actually see the
1413 // type of x here.
1414 //
1415 // We write MatcherCast<const T&>(matcher_) instead of
1416 // Matcher<const T&>(matcher_), as the latter won't compile when
1417 // matcher_ has type Matcher<T> (e.g. An<int>()).
1418 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
zhanyong.wan82113312010-01-08 21:55:40 +00001419 StringMatchResultListener listener;
1420 if (matcher.MatchAndExplain(x, &listener)) {
shiqiane35fdd92008-12-10 05:08:54 +00001421 return AssertionSuccess();
1422 } else {
1423 ::std::stringstream ss;
1424 ss << "Value of: " << value_text << "\n"
1425 << "Expected: ";
1426 matcher.DescribeTo(&ss);
1427 ss << "\n Actual: ";
1428 UniversalPrinter<T>::Print(x, &ss);
zhanyong.wan82113312010-01-08 21:55:40 +00001429 StreamInParensAsNeeded(listener.str(), &ss);
shiqiane35fdd92008-12-10 05:08:54 +00001430 return AssertionFailure(Message() << ss.str());
1431 }
1432 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001433
shiqiane35fdd92008-12-10 05:08:54 +00001434 private:
1435 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001436
1437 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001438};
1439
1440// A helper function for converting a matcher to a predicate-formatter
1441// without the user needing to explicitly write the type. This is
1442// used for implementing ASSERT_THAT() and EXPECT_THAT().
1443template <typename M>
1444inline PredicateFormatterFromMatcher<M>
1445MakePredicateFormatterFromMatcher(const M& matcher) {
1446 return PredicateFormatterFromMatcher<M>(matcher);
1447}
1448
1449// Implements the polymorphic floating point equality matcher, which
1450// matches two float values using ULP-based approximation. The
1451// template is meant to be instantiated with FloatType being either
1452// float or double.
1453template <typename FloatType>
1454class FloatingEqMatcher {
1455 public:
1456 // Constructor for FloatingEqMatcher.
1457 // The matcher's input will be compared with rhs. The matcher treats two
1458 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1459 // equality comparisons between NANs will always return false.
1460 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1461 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1462
1463 // Implements floating point equality matcher as a Matcher<T>.
1464 template <typename T>
1465 class Impl : public MatcherInterface<T> {
1466 public:
1467 Impl(FloatType rhs, bool nan_eq_nan) :
1468 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1469
zhanyong.wan82113312010-01-08 21:55:40 +00001470 virtual bool MatchAndExplain(T value,
1471 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +00001472 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1473
1474 // Compares NaNs first, if nan_eq_nan_ is true.
1475 if (nan_eq_nan_ && lhs.is_nan()) {
1476 return rhs.is_nan();
1477 }
1478
1479 return lhs.AlmostEquals(rhs);
1480 }
1481
1482 virtual void DescribeTo(::std::ostream* os) const {
1483 // os->precision() returns the previously set precision, which we
1484 // store to restore the ostream to its original configuration
1485 // after outputting.
1486 const ::std::streamsize old_precision = os->precision(
1487 ::std::numeric_limits<FloatType>::digits10 + 2);
1488 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1489 if (nan_eq_nan_) {
1490 *os << "is NaN";
1491 } else {
1492 *os << "never matches";
1493 }
1494 } else {
1495 *os << "is approximately " << rhs_;
1496 }
1497 os->precision(old_precision);
1498 }
1499
1500 virtual void DescribeNegationTo(::std::ostream* os) const {
1501 // As before, get original precision.
1502 const ::std::streamsize old_precision = os->precision(
1503 ::std::numeric_limits<FloatType>::digits10 + 2);
1504 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1505 if (nan_eq_nan_) {
1506 *os << "is not NaN";
1507 } else {
1508 *os << "is anything";
1509 }
1510 } else {
1511 *os << "is not approximately " << rhs_;
1512 }
1513 // Restore original precision.
1514 os->precision(old_precision);
1515 }
1516
1517 private:
1518 const FloatType rhs_;
1519 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001520
1521 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001522 };
1523
1524 // The following 3 type conversion operators allow FloatEq(rhs) and
1525 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1526 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1527 // (While Google's C++ coding style doesn't allow arguments passed
1528 // by non-const reference, we may see them in code not conforming to
1529 // the style. Therefore Google Mock needs to support them.)
1530 operator Matcher<FloatType>() const {
1531 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1532 }
1533
1534 operator Matcher<const FloatType&>() const {
1535 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1536 }
1537
1538 operator Matcher<FloatType&>() const {
1539 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1540 }
1541 private:
1542 const FloatType rhs_;
1543 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001544
1545 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001546};
1547
1548// Implements the Pointee(m) matcher for matching a pointer whose
1549// pointee matches matcher m. The pointer can be either raw or smart.
1550template <typename InnerMatcher>
1551class PointeeMatcher {
1552 public:
1553 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1554
1555 // This type conversion operator template allows Pointee(m) to be
1556 // used as a matcher for any pointer type whose pointee type is
1557 // compatible with the inner matcher, where type Pointer can be
1558 // either a raw pointer or a smart pointer.
1559 //
1560 // The reason we do this instead of relying on
1561 // MakePolymorphicMatcher() is that the latter is not flexible
1562 // enough for implementing the DescribeTo() method of Pointee().
1563 template <typename Pointer>
1564 operator Matcher<Pointer>() const {
1565 return MakeMatcher(new Impl<Pointer>(matcher_));
1566 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001567
shiqiane35fdd92008-12-10 05:08:54 +00001568 private:
1569 // The monomorphic implementation that works for a particular pointer type.
1570 template <typename Pointer>
1571 class Impl : public MatcherInterface<Pointer> {
1572 public:
zhanyong.wane0d051e2009-02-19 00:33:37 +00001573 typedef typename PointeeOf<GMOCK_REMOVE_CONST_( // NOLINT
1574 GMOCK_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001575
1576 explicit Impl(const InnerMatcher& matcher)
1577 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1578
shiqiane35fdd92008-12-10 05:08:54 +00001579 virtual void DescribeTo(::std::ostream* os) const {
1580 *os << "points to a value that ";
1581 matcher_.DescribeTo(os);
1582 }
1583
1584 virtual void DescribeNegationTo(::std::ostream* os) const {
1585 *os << "does not point to a value that ";
1586 matcher_.DescribeTo(os);
1587 }
1588
zhanyong.wan82113312010-01-08 21:55:40 +00001589 virtual bool MatchAndExplain(Pointer pointer,
1590 MatchResultListener* listener) const {
shiqiane35fdd92008-12-10 05:08:54 +00001591 if (GetRawPointer(pointer) == NULL)
zhanyong.wan82113312010-01-08 21:55:40 +00001592 return false;
shiqiane35fdd92008-12-10 05:08:54 +00001593
zhanyong.wan82113312010-01-08 21:55:40 +00001594 StringMatchResultListener inner_listener;
1595 const bool match = matcher_.MatchAndExplain(*pointer, &inner_listener);
1596 const internal::string s = inner_listener.str();
shiqiane35fdd92008-12-10 05:08:54 +00001597 if (s != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00001598 *listener << "points to a value that " << s;
shiqiane35fdd92008-12-10 05:08:54 +00001599 }
zhanyong.wan82113312010-01-08 21:55:40 +00001600 return match;
shiqiane35fdd92008-12-10 05:08:54 +00001601 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001602
shiqiane35fdd92008-12-10 05:08:54 +00001603 private:
1604 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001605
1606 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001607 };
1608
1609 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001610
1611 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001612};
1613
1614// Implements the Field() matcher for matching a field (i.e. member
1615// variable) of an object.
1616template <typename Class, typename FieldType>
1617class FieldMatcher {
1618 public:
1619 FieldMatcher(FieldType Class::*field,
1620 const Matcher<const FieldType&>& matcher)
1621 : field_(field), matcher_(matcher) {}
1622
shiqiane35fdd92008-12-10 05:08:54 +00001623 void DescribeTo(::std::ostream* os) const {
1624 *os << "the given field ";
1625 matcher_.DescribeTo(os);
1626 }
1627
1628 void DescribeNegationTo(::std::ostream* os) const {
1629 *os << "the given field ";
1630 matcher_.DescribeNegationTo(os);
1631 }
1632
zhanyong.wandb22c222010-01-28 21:52:29 +00001633 template <typename T>
1634 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
1635 return MatchAndExplainImpl(
1636 typename ::testing::internal::
1637 is_pointer<GMOCK_REMOVE_CONST_(T)>::type(),
1638 value, listener);
1639 }
1640
1641 private:
1642 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001643 // Symbian's C++ compiler choose which overload to use. Its type is
1644 // true_type iff the Field() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001645 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1646 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001647 StringMatchResultListener inner_listener;
1648 const bool match = matcher_.MatchAndExplain(obj.*field_, &inner_listener);
1649 const internal::string s = inner_listener.str();
shiqiane35fdd92008-12-10 05:08:54 +00001650 if (s != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00001651 *listener << "the given field " << s;
shiqiane35fdd92008-12-10 05:08:54 +00001652 }
zhanyong.wan82113312010-01-08 21:55:40 +00001653 return match;
shiqiane35fdd92008-12-10 05:08:54 +00001654 }
1655
zhanyong.wandb22c222010-01-28 21:52:29 +00001656 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1657 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001658 if (p == NULL)
1659 return false;
1660
1661 // Since *p has a field, it must be a class/struct/union type and
1662 // thus cannot be a pointer. Therefore we pass false_type() as
1663 // the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001664 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001665 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001666
shiqiane35fdd92008-12-10 05:08:54 +00001667 const FieldType Class::*field_;
1668 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001669
1670 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001671};
1672
shiqiane35fdd92008-12-10 05:08:54 +00001673// Implements the Property() matcher for matching a property
1674// (i.e. return value of a getter method) of an object.
1675template <typename Class, typename PropertyType>
1676class PropertyMatcher {
1677 public:
1678 // The property may have a reference type, so 'const PropertyType&'
1679 // may cause double references and fail to compile. That's why we
1680 // need GMOCK_REFERENCE_TO_CONST, which works regardless of
1681 // PropertyType being a reference or not.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001682 typedef GMOCK_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001683
1684 PropertyMatcher(PropertyType (Class::*property)() const,
1685 const Matcher<RefToConstProperty>& matcher)
1686 : property_(property), matcher_(matcher) {}
1687
shiqiane35fdd92008-12-10 05:08:54 +00001688 void DescribeTo(::std::ostream* os) const {
1689 *os << "the given property ";
1690 matcher_.DescribeTo(os);
1691 }
1692
1693 void DescribeNegationTo(::std::ostream* os) const {
1694 *os << "the given property ";
1695 matcher_.DescribeNegationTo(os);
1696 }
1697
zhanyong.wandb22c222010-01-28 21:52:29 +00001698 template <typename T>
1699 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
1700 return MatchAndExplainImpl(
1701 typename ::testing::internal::
1702 is_pointer<GMOCK_REMOVE_CONST_(T)>::type(),
1703 value, listener);
1704 }
1705
1706 private:
1707 // The first argument of MatchAndExplainImpl() is needed to help
zhanyong.wan18490652009-05-11 18:54:08 +00001708 // Symbian's C++ compiler choose which overload to use. Its type is
1709 // true_type iff the Property() matcher is used to match a pointer.
zhanyong.wandb22c222010-01-28 21:52:29 +00001710 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
1711 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001712 StringMatchResultListener inner_listener;
1713 const bool match = matcher_.MatchAndExplain((obj.*property_)(),
1714 &inner_listener);
1715 const internal::string s = inner_listener.str();
shiqiane35fdd92008-12-10 05:08:54 +00001716 if (s != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00001717 *listener << "the given property " << s;
shiqiane35fdd92008-12-10 05:08:54 +00001718 }
zhanyong.wan82113312010-01-08 21:55:40 +00001719 return match;
shiqiane35fdd92008-12-10 05:08:54 +00001720 }
1721
zhanyong.wandb22c222010-01-28 21:52:29 +00001722 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
1723 MatchResultListener* listener) const {
zhanyong.wan82113312010-01-08 21:55:40 +00001724 if (p == NULL)
1725 return false;
1726
1727 // Since *p has a property method, it must be a class/struct/union
1728 // type and thus cannot be a pointer. Therefore we pass
1729 // false_type() as the first argument.
zhanyong.wandb22c222010-01-28 21:52:29 +00001730 return MatchAndExplainImpl(false_type(), *p, listener);
shiqiane35fdd92008-12-10 05:08:54 +00001731 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001732
shiqiane35fdd92008-12-10 05:08:54 +00001733 PropertyType (Class::*property_)() const;
1734 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001735
1736 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001737};
1738
shiqiane35fdd92008-12-10 05:08:54 +00001739// Type traits specifying various features of different functors for ResultOf.
1740// The default template specifies features for functor objects.
1741// Functor classes have to typedef argument_type and result_type
1742// to be compatible with ResultOf.
1743template <typename Functor>
1744struct CallableTraits {
1745 typedef typename Functor::result_type ResultType;
1746 typedef Functor StorageType;
1747
zhanyong.wan32de5f52009-12-23 00:13:23 +00001748 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00001749 template <typename T>
1750 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1751};
1752
1753// Specialization for function pointers.
1754template <typename ArgType, typename ResType>
1755struct CallableTraits<ResType(*)(ArgType)> {
1756 typedef ResType ResultType;
1757 typedef ResType(*StorageType)(ArgType);
1758
1759 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001760 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00001761 << "NULL function pointer is passed into ResultOf().";
1762 }
1763 template <typename T>
1764 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1765 return (*f)(arg);
1766 }
1767};
1768
1769// Implements the ResultOf() matcher for matching a return value of a
1770// unary function of an object.
1771template <typename Callable>
1772class ResultOfMatcher {
1773 public:
1774 typedef typename CallableTraits<Callable>::ResultType ResultType;
1775
1776 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1777 : callable_(callable), matcher_(matcher) {
1778 CallableTraits<Callable>::CheckIsValid(callable_);
1779 }
1780
1781 template <typename T>
1782 operator Matcher<T>() const {
1783 return Matcher<T>(new Impl<T>(callable_, matcher_));
1784 }
1785
1786 private:
1787 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1788
1789 template <typename T>
1790 class Impl : public MatcherInterface<T> {
1791 public:
1792 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1793 : callable_(callable), matcher_(matcher) {}
shiqiane35fdd92008-12-10 05:08:54 +00001794
1795 virtual void DescribeTo(::std::ostream* os) const {
1796 *os << "result of the given callable ";
1797 matcher_.DescribeTo(os);
1798 }
1799
1800 virtual void DescribeNegationTo(::std::ostream* os) const {
1801 *os << "result of the given callable ";
1802 matcher_.DescribeNegationTo(os);
1803 }
1804
zhanyong.wan82113312010-01-08 21:55:40 +00001805 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
1806 StringMatchResultListener inner_listener;
1807 const bool match = matcher_.MatchAndExplain(
shiqiane35fdd92008-12-10 05:08:54 +00001808 CallableTraits<Callable>::template Invoke<T>(callable_, obj),
zhanyong.wan82113312010-01-08 21:55:40 +00001809 &inner_listener);
1810
1811 const internal::string s = inner_listener.str();
shiqiane35fdd92008-12-10 05:08:54 +00001812 if (s != "")
zhanyong.wan82113312010-01-08 21:55:40 +00001813 *listener << "result of the given callable " << s;
1814
1815 return match;
shiqiane35fdd92008-12-10 05:08:54 +00001816 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001817
shiqiane35fdd92008-12-10 05:08:54 +00001818 private:
1819 // Functors often define operator() as non-const method even though
1820 // they are actualy stateless. But we need to use them even when
1821 // 'this' is a const pointer. It's the user's responsibility not to
1822 // use stateful callables with ResultOf(), which does't guarantee
1823 // how many times the callable will be invoked.
1824 mutable CallableStorageType callable_;
1825 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001826
1827 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001828 }; // class Impl
1829
1830 const CallableStorageType callable_;
1831 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001832
1833 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001834};
1835
zhanyong.wan6a896b52009-01-16 01:13:50 +00001836// Implements an equality matcher for any STL-style container whose elements
1837// support ==. This matcher is like Eq(), but its failure explanations provide
1838// more detailed information that is useful when the container is used as a set.
1839// The failure message reports elements that are in one of the operands but not
1840// the other. The failure messages do not report duplicate or out-of-order
1841// elements in the containers (which don't properly matter to sets, but can
1842// occur if the containers are vectors or lists, for example).
1843//
1844// Uses the container's const_iterator, value_type, operator ==,
1845// begin(), and end().
1846template <typename Container>
1847class ContainerEqMatcher {
1848 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00001849 typedef internal::StlContainerView<Container> View;
1850 typedef typename View::type StlContainer;
1851 typedef typename View::const_reference StlContainerReference;
1852
1853 // We make a copy of rhs in case the elements in it are modified
1854 // after this matcher is created.
1855 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
1856 // Makes sure the user doesn't instantiate this class template
1857 // with a const or reference type.
1858 testing::StaticAssertTypeEq<Container,
1859 GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))>();
1860 }
1861
zhanyong.wan6a896b52009-01-16 01:13:50 +00001862 void DescribeTo(::std::ostream* os) const {
1863 *os << "equals ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001864 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001865 }
1866 void DescribeNegationTo(::std::ostream* os) const {
1867 *os << "does not equal ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001868 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001869 }
1870
zhanyong.wanb8243162009-06-04 05:48:20 +00001871 template <typename LhsContainer>
zhanyong.wane122e452010-01-12 09:03:52 +00001872 bool MatchAndExplain(const LhsContainer& lhs,
1873 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00001874 // GMOCK_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
1875 // that causes LhsContainer to be a const type sometimes.
1876 typedef internal::StlContainerView<GMOCK_REMOVE_CONST_(LhsContainer)>
1877 LhsView;
1878 typedef typename LhsView::type LhsStlContainer;
1879 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
zhanyong.wane122e452010-01-12 09:03:52 +00001880 if (lhs_stl_container == rhs_)
1881 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00001882
zhanyong.wane122e452010-01-12 09:03:52 +00001883 ::std::ostream* const os = listener->stream();
1884 if (os != NULL) {
1885 // Something is different. Check for missing values first.
1886 bool printed_header = false;
1887 for (typename LhsStlContainer::const_iterator it =
1888 lhs_stl_container.begin();
1889 it != lhs_stl_container.end(); ++it) {
1890 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
1891 rhs_.end()) {
1892 if (printed_header) {
1893 *os << ", ";
1894 } else {
1895 *os << "Only in actual: ";
1896 printed_header = true;
1897 }
zhanyong.wan6953a722010-01-13 05:15:07 +00001898 UniversalPrinter<typename LhsStlContainer::value_type>::
1899 Print(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001900 }
zhanyong.wane122e452010-01-12 09:03:52 +00001901 }
1902
1903 // Now check for extra values.
1904 bool printed_header2 = false;
1905 for (typename StlContainer::const_iterator it = rhs_.begin();
1906 it != rhs_.end(); ++it) {
1907 if (internal::ArrayAwareFind(
1908 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
1909 lhs_stl_container.end()) {
1910 if (printed_header2) {
1911 *os << ", ";
1912 } else {
1913 *os << (printed_header ? "; not" : "Not") << " in actual: ";
1914 printed_header2 = true;
1915 }
1916 UniversalPrinter<typename StlContainer::value_type>::Print(*it, os);
1917 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00001918 }
1919 }
1920
zhanyong.wane122e452010-01-12 09:03:52 +00001921 return false;
zhanyong.wan6a896b52009-01-16 01:13:50 +00001922 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001923
zhanyong.wan6a896b52009-01-16 01:13:50 +00001924 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00001925 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001926
1927 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001928};
1929
zhanyong.wanb8243162009-06-04 05:48:20 +00001930// Implements Contains(element_matcher) for the given argument type Container.
1931template <typename Container>
1932class ContainsMatcherImpl : public MatcherInterface<Container> {
1933 public:
1934 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
1935 typedef StlContainerView<RawContainer> View;
1936 typedef typename View::type StlContainer;
1937 typedef typename View::const_reference StlContainerReference;
1938 typedef typename StlContainer::value_type Element;
1939
1940 template <typename InnerMatcher>
1941 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
1942 : inner_matcher_(
1943 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
1944
zhanyong.wanb8243162009-06-04 05:48:20 +00001945 // Describes what this matcher does.
1946 virtual void DescribeTo(::std::ostream* os) const {
1947 *os << "contains at least one element that ";
1948 inner_matcher_.DescribeTo(os);
1949 }
1950
1951 // Describes what the negation of this matcher does.
1952 virtual void DescribeNegationTo(::std::ostream* os) const {
1953 *os << "doesn't contain any element that ";
1954 inner_matcher_.DescribeTo(os);
1955 }
1956
zhanyong.wan82113312010-01-08 21:55:40 +00001957 virtual bool MatchAndExplain(Container container,
1958 MatchResultListener* listener) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00001959 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00001960 size_t i = 0;
1961 for (typename StlContainer::const_iterator it = stl_container.begin();
1962 it != stl_container.end(); ++it, ++i) {
zhanyong.wanb8243162009-06-04 05:48:20 +00001963 if (inner_matcher_.Matches(*it)) {
zhanyong.wan82113312010-01-08 21:55:40 +00001964 *listener << "element " << i << " matches";
1965 return true;
zhanyong.wanb8243162009-06-04 05:48:20 +00001966 }
1967 }
zhanyong.wan82113312010-01-08 21:55:40 +00001968 return false;
zhanyong.wanb8243162009-06-04 05:48:20 +00001969 }
1970
1971 private:
1972 const Matcher<const Element&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001973
1974 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00001975};
1976
1977// Implements polymorphic Contains(element_matcher).
1978template <typename M>
1979class ContainsMatcher {
1980 public:
1981 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
1982
1983 template <typename Container>
1984 operator Matcher<Container>() const {
1985 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
1986 }
1987
1988 private:
1989 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001990
1991 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00001992};
1993
zhanyong.wanb5937da2009-07-16 20:26:41 +00001994// Implements Key(inner_matcher) for the given argument pair type.
1995// Key(inner_matcher) matches an std::pair whose 'first' field matches
1996// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
1997// std::map that contains at least one element whose key is >= 5.
1998template <typename PairType>
1999class KeyMatcherImpl : public MatcherInterface<PairType> {
2000 public:
2001 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
2002 typedef typename RawPairType::first_type KeyType;
2003
2004 template <typename InnerMatcher>
2005 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2006 : inner_matcher_(
2007 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2008 }
2009
2010 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
zhanyong.wan82113312010-01-08 21:55:40 +00002011 virtual bool MatchAndExplain(PairType key_value,
2012 MatchResultListener* listener) const {
2013 return inner_matcher_.MatchAndExplain(key_value.first, listener);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002014 }
2015
2016 // Describes what this matcher does.
2017 virtual void DescribeTo(::std::ostream* os) const {
2018 *os << "has a key that ";
2019 inner_matcher_.DescribeTo(os);
2020 }
2021
2022 // Describes what the negation of this matcher does.
2023 virtual void DescribeNegationTo(::std::ostream* os) const {
2024 *os << "doesn't have a key that ";
2025 inner_matcher_.DescribeTo(os);
2026 }
2027
zhanyong.wanb5937da2009-07-16 20:26:41 +00002028 private:
2029 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002030
2031 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002032};
2033
2034// Implements polymorphic Key(matcher_for_key).
2035template <typename M>
2036class KeyMatcher {
2037 public:
2038 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2039
2040 template <typename PairType>
2041 operator Matcher<PairType>() const {
2042 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2043 }
2044
2045 private:
2046 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002047
2048 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002049};
2050
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002051// Implements Pair(first_matcher, second_matcher) for the given argument pair
2052// type with its two matchers. See Pair() function below.
2053template <typename PairType>
2054class PairMatcherImpl : public MatcherInterface<PairType> {
2055 public:
2056 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
2057 typedef typename RawPairType::first_type FirstType;
2058 typedef typename RawPairType::second_type SecondType;
2059
2060 template <typename FirstMatcher, typename SecondMatcher>
2061 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2062 : first_matcher_(
2063 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2064 second_matcher_(
2065 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2066 }
2067
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002068 // Describes what this matcher does.
2069 virtual void DescribeTo(::std::ostream* os) const {
2070 *os << "has a first field that ";
2071 first_matcher_.DescribeTo(os);
2072 *os << ", and has a second field that ";
2073 second_matcher_.DescribeTo(os);
2074 }
2075
2076 // Describes what the negation of this matcher does.
2077 virtual void DescribeNegationTo(::std::ostream* os) const {
2078 *os << "has a first field that ";
2079 first_matcher_.DescribeNegationTo(os);
2080 *os << ", or has a second field that ";
2081 second_matcher_.DescribeNegationTo(os);
2082 }
2083
zhanyong.wan82113312010-01-08 21:55:40 +00002084 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2085 // matches second_matcher.
2086 virtual bool MatchAndExplain(PairType a_pair,
2087 MatchResultListener* listener) const {
2088 StringMatchResultListener listener1;
2089 const bool match1 = first_matcher_.MatchAndExplain(a_pair.first,
2090 &listener1);
2091 internal::string s1 = listener1.str();
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002092 if (s1 != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00002093 s1 = "the first field " + s1;
2094 }
2095 if (!match1) {
2096 *listener << s1;
2097 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002098 }
2099
zhanyong.wan82113312010-01-08 21:55:40 +00002100 StringMatchResultListener listener2;
2101 const bool match2 = second_matcher_.MatchAndExplain(a_pair.second,
2102 &listener2);
2103 internal::string s2 = listener2.str();
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002104 if (s2 != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00002105 s2 = "the second field " + s2;
2106 }
2107 if (!match2) {
2108 *listener << s2;
2109 return false;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002110 }
2111
zhanyong.wan82113312010-01-08 21:55:40 +00002112 *listener << s1;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002113 if (s1 != "" && s2 != "") {
zhanyong.wan82113312010-01-08 21:55:40 +00002114 *listener << ", and ";
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002115 }
zhanyong.wan82113312010-01-08 21:55:40 +00002116 *listener << s2;
2117 return true;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002118 }
2119
2120 private:
2121 const Matcher<const FirstType&> first_matcher_;
2122 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002123
2124 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002125};
2126
2127// Implements polymorphic Pair(first_matcher, second_matcher).
2128template <typename FirstMatcher, typename SecondMatcher>
2129class PairMatcher {
2130 public:
2131 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2132 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2133
2134 template <typename PairType>
2135 operator Matcher<PairType> () const {
2136 return MakeMatcher(
2137 new PairMatcherImpl<PairType>(
2138 first_matcher_, second_matcher_));
2139 }
2140
2141 private:
2142 const FirstMatcher first_matcher_;
2143 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002144
2145 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002146};
2147
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002148// Implements ElementsAre() and ElementsAreArray().
2149template <typename Container>
2150class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2151 public:
2152 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
2153 typedef internal::StlContainerView<RawContainer> View;
2154 typedef typename View::type StlContainer;
2155 typedef typename View::const_reference StlContainerReference;
2156 typedef typename StlContainer::value_type Element;
2157
2158 // Constructs the matcher from a sequence of element values or
2159 // element matchers.
2160 template <typename InputIter>
zhanyong.wan32de5f52009-12-23 00:13:23 +00002161 ElementsAreMatcherImpl(InputIter first, size_t a_count) {
2162 matchers_.reserve(a_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002163 InputIter it = first;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002164 for (size_t i = 0; i != a_count; ++i, ++it) {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002165 matchers_.push_back(MatcherCast<const Element&>(*it));
2166 }
2167 }
2168
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002169 // Describes what this matcher does.
2170 virtual void DescribeTo(::std::ostream* os) const {
2171 if (count() == 0) {
2172 *os << "is empty";
2173 } else if (count() == 1) {
2174 *os << "has 1 element that ";
2175 matchers_[0].DescribeTo(os);
2176 } else {
2177 *os << "has " << Elements(count()) << " where\n";
2178 for (size_t i = 0; i != count(); ++i) {
2179 *os << "element " << i << " ";
2180 matchers_[i].DescribeTo(os);
2181 if (i + 1 < count()) {
2182 *os << ",\n";
2183 }
2184 }
2185 }
2186 }
2187
2188 // Describes what the negation of this matcher does.
2189 virtual void DescribeNegationTo(::std::ostream* os) const {
2190 if (count() == 0) {
2191 *os << "is not empty";
2192 return;
2193 }
2194
2195 *os << "does not have " << Elements(count()) << ", or\n";
2196 for (size_t i = 0; i != count(); ++i) {
2197 *os << "element " << i << " ";
2198 matchers_[i].DescribeNegationTo(os);
2199 if (i + 1 < count()) {
2200 *os << ", or\n";
2201 }
2202 }
2203 }
2204
zhanyong.wan82113312010-01-08 21:55:40 +00002205 virtual bool MatchAndExplain(Container container,
2206 MatchResultListener* listener) const {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002207 StlContainerReference stl_container = View::ConstReference(container);
zhanyong.wan82113312010-01-08 21:55:40 +00002208 const size_t actual_count = stl_container.size();
2209 if (actual_count != count()) {
2210 // The element count doesn't match. If the container is empty,
2211 // there's no need to explain anything as Google Mock already
2212 // prints the empty container. Otherwise we just need to show
2213 // how many elements there actually are.
2214 if (actual_count != 0) {
2215 *listener << "has " << Elements(actual_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002216 }
zhanyong.wan82113312010-01-08 21:55:40 +00002217 return false;
2218 }
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002219
zhanyong.wan82113312010-01-08 21:55:40 +00002220 typename StlContainer::const_iterator it = stl_container.begin();
2221 // explanations[i] is the explanation of the element at index i.
2222 std::vector<internal::string> explanations(count());
2223 for (size_t i = 0; i != count(); ++it, ++i) {
2224 StringMatchResultListener s;
2225 if (matchers_[i].MatchAndExplain(*it, &s)) {
2226 explanations[i] = s.str();
2227 } else {
2228 // The container has the right size but the i-th element
2229 // doesn't match its expectation.
2230 *listener << "element " << i << " doesn't match";
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002231
zhanyong.wan82113312010-01-08 21:55:40 +00002232 StreamInParensAsNeeded(s.str(), listener->stream());
2233 return false;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002234 }
2235 }
zhanyong.wan82113312010-01-08 21:55:40 +00002236
2237 // Every element matches its expectation. We need to explain why
2238 // (the obvious ones can be skipped).
2239
2240 bool reason_printed = false;
2241 for (size_t i = 0; i != count(); ++i) {
2242 const internal::string& s = explanations[i];
2243 if (!s.empty()) {
2244 if (reason_printed) {
2245 *listener << ",\n";
2246 }
2247 *listener << "element " << i << " " << s;
2248 reason_printed = true;
2249 }
2250 }
2251
2252 return true;
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002253 }
2254
2255 private:
2256 static Message Elements(size_t count) {
2257 return Message() << count << (count == 1 ? " element" : " elements");
2258 }
2259
2260 size_t count() const { return matchers_.size(); }
2261 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002262
2263 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002264};
2265
2266// Implements ElementsAre() of 0 arguments.
2267class ElementsAreMatcher0 {
2268 public:
2269 ElementsAreMatcher0() {}
2270
2271 template <typename Container>
2272 operator Matcher<Container>() const {
2273 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2274 RawContainer;
2275 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2276 Element;
2277
2278 const Matcher<const Element&>* const matchers = NULL;
2279 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 0));
2280 }
2281};
2282
2283// Implements ElementsAreArray().
2284template <typename T>
2285class ElementsAreArrayMatcher {
2286 public:
2287 ElementsAreArrayMatcher(const T* first, size_t count) :
2288 first_(first), count_(count) {}
2289
2290 template <typename Container>
2291 operator Matcher<Container>() const {
2292 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2293 RawContainer;
2294 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2295 Element;
2296
2297 return MakeMatcher(new ElementsAreMatcherImpl<Container>(first_, count_));
2298 }
2299
2300 private:
2301 const T* const first_;
2302 const size_t count_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002303
2304 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002305};
2306
2307// Constants denoting interpolations in a matcher description string.
2308const int kTupleInterpolation = -1; // "%(*)s"
2309const int kPercentInterpolation = -2; // "%%"
2310const int kInvalidInterpolation = -3; // "%" followed by invalid text
2311
2312// Records the location and content of an interpolation.
2313struct Interpolation {
2314 Interpolation(const char* start, const char* end, int param)
2315 : start_pos(start), end_pos(end), param_index(param) {}
2316
2317 // Points to the start of the interpolation (the '%' character).
2318 const char* start_pos;
2319 // Points to the first character after the interpolation.
2320 const char* end_pos;
2321 // 0-based index of the interpolated matcher parameter;
2322 // kTupleInterpolation for "%(*)s"; kPercentInterpolation for "%%".
2323 int param_index;
2324};
2325
2326typedef ::std::vector<Interpolation> Interpolations;
2327
2328// Parses a matcher description string and returns a vector of
2329// interpolations that appear in the string; generates non-fatal
2330// failures iff 'description' is an invalid matcher description.
2331// 'param_names' is a NULL-terminated array of parameter names in the
2332// order they appear in the MATCHER_P*() parameter list.
2333Interpolations ValidateMatcherDescription(
2334 const char* param_names[], const char* description);
2335
2336// Returns the actual matcher description, given the matcher name,
2337// user-supplied description template string, interpolations in the
2338// string, and the printed values of the matcher parameters.
2339string FormatMatcherDescription(
2340 const char* matcher_name, const char* description,
2341 const Interpolations& interp, const Strings& param_values);
2342
shiqiane35fdd92008-12-10 05:08:54 +00002343} // namespace internal
2344
2345// Implements MatcherCast().
2346template <typename T, typename M>
2347inline Matcher<T> MatcherCast(M matcher) {
2348 return internal::MatcherCastImpl<T, M>::Cast(matcher);
2349}
2350
2351// _ is a matcher that matches anything of any type.
2352//
2353// This definition is fine as:
2354//
2355// 1. The C++ standard permits using the name _ in a namespace that
2356// is not the global namespace or ::std.
2357// 2. The AnythingMatcher class has no data member or constructor,
2358// so it's OK to create global variables of this type.
2359// 3. c-style has approved of using _ in this case.
2360const internal::AnythingMatcher _ = {};
2361// Creates a matcher that matches any value of the given type T.
2362template <typename T>
2363inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2364
2365// Creates a matcher that matches any value of the given type T.
2366template <typename T>
2367inline Matcher<T> An() { return A<T>(); }
2368
2369// Creates a polymorphic matcher that matches anything equal to x.
2370// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2371// wouldn't compile.
2372template <typename T>
2373inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2374
2375// Constructs a Matcher<T> from a 'value' of type T. The constructed
2376// matcher matches any value that's equal to 'value'.
2377template <typename T>
2378Matcher<T>::Matcher(T value) { *this = Eq(value); }
2379
2380// Creates a monomorphic matcher that matches anything with type Lhs
2381// and equal to rhs. A user may need to use this instead of Eq(...)
2382// in order to resolve an overloading ambiguity.
2383//
2384// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2385// or Matcher<T>(x), but more readable than the latter.
2386//
2387// We could define similar monomorphic matchers for other comparison
2388// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2389// it yet as those are used much less than Eq() in practice. A user
2390// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2391// for example.
2392template <typename Lhs, typename Rhs>
2393inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2394
2395// Creates a polymorphic matcher that matches anything >= x.
2396template <typename Rhs>
2397inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2398 return internal::GeMatcher<Rhs>(x);
2399}
2400
2401// Creates a polymorphic matcher that matches anything > x.
2402template <typename Rhs>
2403inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2404 return internal::GtMatcher<Rhs>(x);
2405}
2406
2407// Creates a polymorphic matcher that matches anything <= x.
2408template <typename Rhs>
2409inline internal::LeMatcher<Rhs> Le(Rhs x) {
2410 return internal::LeMatcher<Rhs>(x);
2411}
2412
2413// Creates a polymorphic matcher that matches anything < x.
2414template <typename Rhs>
2415inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2416 return internal::LtMatcher<Rhs>(x);
2417}
2418
2419// Creates a polymorphic matcher that matches anything != x.
2420template <typename Rhs>
2421inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2422 return internal::NeMatcher<Rhs>(x);
2423}
2424
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002425// Creates a polymorphic matcher that matches any NULL pointer.
2426inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2427 return MakePolymorphicMatcher(internal::IsNullMatcher());
2428}
2429
shiqiane35fdd92008-12-10 05:08:54 +00002430// Creates a polymorphic matcher that matches any non-NULL pointer.
2431// This is convenient as Not(NULL) doesn't compile (the compiler
2432// thinks that that expression is comparing a pointer with an integer).
2433inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2434 return MakePolymorphicMatcher(internal::NotNullMatcher());
2435}
2436
2437// Creates a polymorphic matcher that matches any argument that
2438// references variable x.
2439template <typename T>
2440inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2441 return internal::RefMatcher<T&>(x);
2442}
2443
2444// Creates a matcher that matches any double argument approximately
2445// equal to rhs, where two NANs are considered unequal.
2446inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2447 return internal::FloatingEqMatcher<double>(rhs, false);
2448}
2449
2450// Creates a matcher that matches any double argument approximately
2451// equal to rhs, including NaN values when rhs is NaN.
2452inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2453 return internal::FloatingEqMatcher<double>(rhs, true);
2454}
2455
2456// Creates a matcher that matches any float argument approximately
2457// equal to rhs, where two NANs are considered unequal.
2458inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2459 return internal::FloatingEqMatcher<float>(rhs, false);
2460}
2461
2462// Creates a matcher that matches any double argument approximately
2463// equal to rhs, including NaN values when rhs is NaN.
2464inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2465 return internal::FloatingEqMatcher<float>(rhs, true);
2466}
2467
2468// Creates a matcher that matches a pointer (raw or smart) that points
2469// to a value that matches inner_matcher.
2470template <typename InnerMatcher>
2471inline internal::PointeeMatcher<InnerMatcher> Pointee(
2472 const InnerMatcher& inner_matcher) {
2473 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2474}
2475
2476// Creates a matcher that matches an object whose given field matches
2477// 'matcher'. For example,
2478// Field(&Foo::number, Ge(5))
2479// matches a Foo object x iff x.number >= 5.
2480template <typename Class, typename FieldType, typename FieldMatcher>
2481inline PolymorphicMatcher<
2482 internal::FieldMatcher<Class, FieldType> > Field(
2483 FieldType Class::*field, const FieldMatcher& matcher) {
2484 return MakePolymorphicMatcher(
2485 internal::FieldMatcher<Class, FieldType>(
2486 field, MatcherCast<const FieldType&>(matcher)));
2487 // The call to MatcherCast() is required for supporting inner
2488 // matchers of compatible types. For example, it allows
2489 // Field(&Foo::bar, m)
2490 // to compile where bar is an int32 and m is a matcher for int64.
2491}
2492
2493// Creates a matcher that matches an object whose given property
2494// matches 'matcher'. For example,
2495// Property(&Foo::str, StartsWith("hi"))
2496// matches a Foo object x iff x.str() starts with "hi".
2497template <typename Class, typename PropertyType, typename PropertyMatcher>
2498inline PolymorphicMatcher<
2499 internal::PropertyMatcher<Class, PropertyType> > Property(
2500 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2501 return MakePolymorphicMatcher(
2502 internal::PropertyMatcher<Class, PropertyType>(
2503 property,
zhanyong.wane0d051e2009-02-19 00:33:37 +00002504 MatcherCast<GMOCK_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002505 // The call to MatcherCast() is required for supporting inner
2506 // matchers of compatible types. For example, it allows
2507 // Property(&Foo::bar, m)
2508 // to compile where bar() returns an int32 and m is a matcher for int64.
2509}
2510
2511// Creates a matcher that matches an object iff the result of applying
2512// a callable to x matches 'matcher'.
2513// For example,
2514// ResultOf(f, StartsWith("hi"))
2515// matches a Foo object x iff f(x) starts with "hi".
2516// callable parameter can be a function, function pointer, or a functor.
2517// Callable has to satisfy the following conditions:
2518// * It is required to keep no state affecting the results of
2519// the calls on it and make no assumptions about how many calls
2520// will be made. Any state it keeps must be protected from the
2521// concurrent access.
2522// * If it is a function object, it has to define type result_type.
2523// We recommend deriving your functor classes from std::unary_function.
2524template <typename Callable, typename ResultOfMatcher>
2525internal::ResultOfMatcher<Callable> ResultOf(
2526 Callable callable, const ResultOfMatcher& matcher) {
2527 return internal::ResultOfMatcher<Callable>(
2528 callable,
2529 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2530 matcher));
2531 // The call to MatcherCast() is required for supporting inner
2532 // matchers of compatible types. For example, it allows
2533 // ResultOf(Function, m)
2534 // to compile where Function() returns an int32 and m is a matcher for int64.
2535}
2536
2537// String matchers.
2538
2539// Matches a string equal to str.
2540inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2541 StrEq(const internal::string& str) {
2542 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2543 str, true, true));
2544}
2545
2546// Matches a string not equal to str.
2547inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2548 StrNe(const internal::string& str) {
2549 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2550 str, false, true));
2551}
2552
2553// Matches a string equal to str, ignoring case.
2554inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2555 StrCaseEq(const internal::string& str) {
2556 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2557 str, true, false));
2558}
2559
2560// Matches a string not equal to str, ignoring case.
2561inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2562 StrCaseNe(const internal::string& str) {
2563 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2564 str, false, false));
2565}
2566
2567// Creates a matcher that matches any string, std::string, or C string
2568// that contains the given substring.
2569inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2570 HasSubstr(const internal::string& substring) {
2571 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
2572 substring));
2573}
2574
2575// Matches a string that starts with 'prefix' (case-sensitive).
2576inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
2577 StartsWith(const internal::string& prefix) {
2578 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
2579 prefix));
2580}
2581
2582// Matches a string that ends with 'suffix' (case-sensitive).
2583inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
2584 EndsWith(const internal::string& suffix) {
2585 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
2586 suffix));
2587}
2588
shiqiane35fdd92008-12-10 05:08:54 +00002589// Matches a string that fully matches regular expression 'regex'.
2590// The matcher takes ownership of 'regex'.
2591inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2592 const internal::RE* regex) {
2593 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2594}
2595inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2596 const internal::string& regex) {
2597 return MatchesRegex(new internal::RE(regex));
2598}
2599
2600// Matches a string that contains regular expression 'regex'.
2601// The matcher takes ownership of 'regex'.
2602inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2603 const internal::RE* regex) {
2604 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2605}
2606inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2607 const internal::string& regex) {
2608 return ContainsRegex(new internal::RE(regex));
2609}
2610
shiqiane35fdd92008-12-10 05:08:54 +00002611#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2612// Wide string matchers.
2613
2614// Matches a string equal to str.
2615inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2616 StrEq(const internal::wstring& str) {
2617 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2618 str, true, true));
2619}
2620
2621// Matches a string not equal to str.
2622inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2623 StrNe(const internal::wstring& str) {
2624 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2625 str, false, true));
2626}
2627
2628// Matches a string equal to str, ignoring case.
2629inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2630 StrCaseEq(const internal::wstring& str) {
2631 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2632 str, true, false));
2633}
2634
2635// Matches a string not equal to str, ignoring case.
2636inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2637 StrCaseNe(const internal::wstring& str) {
2638 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2639 str, false, false));
2640}
2641
2642// Creates a matcher that matches any wstring, std::wstring, or C wide string
2643// that contains the given substring.
2644inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2645 HasSubstr(const internal::wstring& substring) {
2646 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2647 substring));
2648}
2649
2650// Matches a string that starts with 'prefix' (case-sensitive).
2651inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2652 StartsWith(const internal::wstring& prefix) {
2653 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2654 prefix));
2655}
2656
2657// Matches a string that ends with 'suffix' (case-sensitive).
2658inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2659 EndsWith(const internal::wstring& suffix) {
2660 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2661 suffix));
2662}
2663
2664#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2665
2666// Creates a polymorphic matcher that matches a 2-tuple where the
2667// first field == the second field.
2668inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2669
2670// Creates a polymorphic matcher that matches a 2-tuple where the
2671// first field >= the second field.
2672inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2673
2674// Creates a polymorphic matcher that matches a 2-tuple where the
2675// first field > the second field.
2676inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2677
2678// Creates a polymorphic matcher that matches a 2-tuple where the
2679// first field <= the second field.
2680inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2681
2682// Creates a polymorphic matcher that matches a 2-tuple where the
2683// first field < the second field.
2684inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2685
2686// Creates a polymorphic matcher that matches a 2-tuple where the
2687// first field != the second field.
2688inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2689
2690// Creates a matcher that matches any value of type T that m doesn't
2691// match.
2692template <typename InnerMatcher>
2693inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2694 return internal::NotMatcher<InnerMatcher>(m);
2695}
2696
2697// Creates a matcher that matches any value that matches all of the
2698// given matchers.
2699//
2700// For now we only support up to 5 matchers. Support for more
2701// matchers can be added as needed, or the user can use nested
2702// AllOf()s.
2703template <typename Matcher1, typename Matcher2>
2704inline internal::BothOfMatcher<Matcher1, Matcher2>
2705AllOf(Matcher1 m1, Matcher2 m2) {
2706 return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2);
2707}
2708
2709template <typename Matcher1, typename Matcher2, typename Matcher3>
2710inline internal::BothOfMatcher<Matcher1,
2711 internal::BothOfMatcher<Matcher2, Matcher3> >
2712AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2713 return AllOf(m1, AllOf(m2, m3));
2714}
2715
2716template <typename Matcher1, typename Matcher2, typename Matcher3,
2717 typename Matcher4>
2718inline internal::BothOfMatcher<Matcher1,
2719 internal::BothOfMatcher<Matcher2,
2720 internal::BothOfMatcher<Matcher3, Matcher4> > >
2721AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2722 return AllOf(m1, AllOf(m2, m3, m4));
2723}
2724
2725template <typename Matcher1, typename Matcher2, typename Matcher3,
2726 typename Matcher4, typename Matcher5>
2727inline internal::BothOfMatcher<Matcher1,
2728 internal::BothOfMatcher<Matcher2,
2729 internal::BothOfMatcher<Matcher3,
2730 internal::BothOfMatcher<Matcher4, Matcher5> > > >
2731AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2732 return AllOf(m1, AllOf(m2, m3, m4, m5));
2733}
2734
2735// Creates a matcher that matches any value that matches at least one
2736// of the given matchers.
2737//
2738// For now we only support up to 5 matchers. Support for more
2739// matchers can be added as needed, or the user can use nested
2740// AnyOf()s.
2741template <typename Matcher1, typename Matcher2>
2742inline internal::EitherOfMatcher<Matcher1, Matcher2>
2743AnyOf(Matcher1 m1, Matcher2 m2) {
2744 return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2);
2745}
2746
2747template <typename Matcher1, typename Matcher2, typename Matcher3>
2748inline internal::EitherOfMatcher<Matcher1,
2749 internal::EitherOfMatcher<Matcher2, Matcher3> >
2750AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2751 return AnyOf(m1, AnyOf(m2, m3));
2752}
2753
2754template <typename Matcher1, typename Matcher2, typename Matcher3,
2755 typename Matcher4>
2756inline internal::EitherOfMatcher<Matcher1,
2757 internal::EitherOfMatcher<Matcher2,
2758 internal::EitherOfMatcher<Matcher3, Matcher4> > >
2759AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2760 return AnyOf(m1, AnyOf(m2, m3, m4));
2761}
2762
2763template <typename Matcher1, typename Matcher2, typename Matcher3,
2764 typename Matcher4, typename Matcher5>
2765inline internal::EitherOfMatcher<Matcher1,
2766 internal::EitherOfMatcher<Matcher2,
2767 internal::EitherOfMatcher<Matcher3,
2768 internal::EitherOfMatcher<Matcher4, Matcher5> > > >
2769AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2770 return AnyOf(m1, AnyOf(m2, m3, m4, m5));
2771}
2772
2773// Returns a matcher that matches anything that satisfies the given
2774// predicate. The predicate can be any unary function or functor
2775// whose return type can be implicitly converted to bool.
2776template <typename Predicate>
2777inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
2778Truly(Predicate pred) {
2779 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
2780}
2781
zhanyong.wan6a896b52009-01-16 01:13:50 +00002782// Returns a matcher that matches an equal container.
2783// This matcher behaves like Eq(), but in the event of mismatch lists the
2784// values that are included in one container but not the other. (Duplicate
2785// values and order differences are not explained.)
2786template <typename Container>
zhanyong.wan82113312010-01-08 21:55:40 +00002787inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
zhanyong.wanb8243162009-06-04 05:48:20 +00002788 GMOCK_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00002789 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002790 // This following line is for working around a bug in MSVC 8.0,
2791 // which causes Container to be a const type sometimes.
2792 typedef GMOCK_REMOVE_CONST_(Container) RawContainer;
zhanyong.wan82113312010-01-08 21:55:40 +00002793 return MakePolymorphicMatcher(
2794 internal::ContainerEqMatcher<RawContainer>(rhs));
zhanyong.wanb8243162009-06-04 05:48:20 +00002795}
2796
2797// Matches an STL-style container or a native array that contains at
2798// least one element matching the given value or matcher.
2799//
2800// Examples:
2801// ::std::set<int> page_ids;
2802// page_ids.insert(3);
2803// page_ids.insert(1);
2804// EXPECT_THAT(page_ids, Contains(1));
2805// EXPECT_THAT(page_ids, Contains(Gt(2)));
2806// EXPECT_THAT(page_ids, Not(Contains(4)));
2807//
2808// ::std::map<int, size_t> page_lengths;
2809// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00002810// EXPECT_THAT(page_lengths,
2811// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00002812//
2813// const char* user_ids[] = { "joe", "mike", "tom" };
2814// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
2815template <typename M>
2816inline internal::ContainsMatcher<M> Contains(M matcher) {
2817 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002818}
2819
zhanyong.wanb5937da2009-07-16 20:26:41 +00002820// Key(inner_matcher) matches an std::pair whose 'first' field matches
2821// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2822// std::map that contains at least one element whose key is >= 5.
2823template <typename M>
2824inline internal::KeyMatcher<M> Key(M inner_matcher) {
2825 return internal::KeyMatcher<M>(inner_matcher);
2826}
2827
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002828// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
2829// matches first_matcher and whose 'second' field matches second_matcher. For
2830// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
2831// to match a std::map<int, string> that contains exactly one element whose key
2832// is >= 5 and whose value equals "foo".
2833template <typename FirstMatcher, typename SecondMatcher>
2834inline internal::PairMatcher<FirstMatcher, SecondMatcher>
2835Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
2836 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
2837 first_matcher, second_matcher);
2838}
2839
shiqiane35fdd92008-12-10 05:08:54 +00002840// Returns a predicate that is satisfied by anything that matches the
2841// given matcher.
2842template <typename M>
2843inline internal::MatcherAsPredicate<M> Matches(M matcher) {
2844 return internal::MatcherAsPredicate<M>(matcher);
2845}
2846
zhanyong.wanb8243162009-06-04 05:48:20 +00002847// Returns true iff the value matches the matcher.
2848template <typename T, typename M>
2849inline bool Value(const T& value, M matcher) {
2850 return testing::Matches(matcher)(value);
2851}
2852
zhanyong.wanbf550852009-06-09 06:09:53 +00002853// AllArgs(m) is a synonym of m. This is useful in
2854//
2855// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
2856//
2857// which is easier to read than
2858//
2859// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
2860template <typename InnerMatcher>
2861inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
2862
shiqiane35fdd92008-12-10 05:08:54 +00002863// These macros allow using matchers to check values in Google Test
2864// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
2865// succeed iff the value matches the matcher. If the assertion fails,
2866// the value and the description of the matcher will be printed.
2867#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
2868 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2869#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
2870 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2871
2872} // namespace testing
2873
2874#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_