blob: 5f5a29fd93b7c6eb309daaabd5b66c092ac0191c [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
67// The implementation of a matcher.
68template <typename T>
69class MatcherInterface {
70 public:
71 virtual ~MatcherInterface() {}
72
73 // Returns true iff the matcher matches x.
74 virtual bool Matches(T x) const = 0;
75
76 // Describes this matcher to an ostream.
77 virtual void DescribeTo(::std::ostream* os) const = 0;
78
79 // Describes the negation of this matcher to an ostream. For
80 // example, if the description of this matcher is "is greater than
81 // 7", the negated description could be "is not greater than 7".
82 // You are not required to override this when implementing
83 // MatcherInterface, but it is highly advised so that your matcher
84 // can produce good error messages.
85 virtual void DescribeNegationTo(::std::ostream* os) const {
86 *os << "not (";
87 DescribeTo(os);
88 *os << ")";
89 }
90
91 // Explains why x matches, or doesn't match, the matcher. Override
92 // this to provide any additional information that helps a user
93 // understand the match result.
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +000094 virtual void ExplainMatchResultTo(T /* x */, ::std::ostream* /* os */) const {
shiqiane35fdd92008-12-10 05:08:54 +000095 // By default, nothing more needs to be explained, as Google Mock
96 // has already printed the value of x when this function is
97 // called.
98 }
99};
100
101namespace internal {
102
103// An internal class for implementing Matcher<T>, which will derive
104// from it. We put functionalities common to all Matcher<T>
105// specializations here to avoid code duplication.
106template <typename T>
107class MatcherBase {
108 public:
109 // Returns true iff this matcher matches x.
110 bool Matches(T x) const { return impl_->Matches(x); }
111
112 // Describes this matcher to an ostream.
113 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
114
115 // Describes the negation of this matcher to an ostream.
116 void DescribeNegationTo(::std::ostream* os) const {
117 impl_->DescribeNegationTo(os);
118 }
119
120 // Explains why x matches, or doesn't match, the matcher.
121 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
122 impl_->ExplainMatchResultTo(x, os);
123 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000124
shiqiane35fdd92008-12-10 05:08:54 +0000125 protected:
126 MatcherBase() {}
127
128 // Constructs a matcher from its implementation.
129 explicit MatcherBase(const MatcherInterface<T>* impl)
130 : impl_(impl) {}
131
132 virtual ~MatcherBase() {}
zhanyong.wan32de5f52009-12-23 00:13:23 +0000133
shiqiane35fdd92008-12-10 05:08:54 +0000134 private:
135 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
136 // interfaces. The former dynamically allocates a chunk of memory
137 // to hold the reference count, while the latter tracks all
138 // references using a circular linked list without allocating
139 // memory. It has been observed that linked_ptr performs better in
140 // typical scenarios. However, shared_ptr can out-perform
141 // linked_ptr when there are many more uses of the copy constructor
142 // than the default constructor.
143 //
144 // If performance becomes a problem, we should see if using
145 // shared_ptr helps.
146 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
147};
148
149// The default implementation of ExplainMatchResultTo() for
150// polymorphic matchers.
151template <typename PolymorphicMatcherImpl, typename T>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000152inline void ExplainMatchResultTo(const PolymorphicMatcherImpl& /* impl */,
153 const T& /* x */,
154 ::std::ostream* /* os */) {
shiqiane35fdd92008-12-10 05:08:54 +0000155 // By default, nothing more needs to be said, as Google Mock already
156 // prints the value of x elsewhere.
157}
158
159} // namespace internal
160
161// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
162// object that can check whether a value of type T matches. The
163// implementation of Matcher<T> is just a linked_ptr to const
164// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
165// from Matcher!
166template <typename T>
167class Matcher : public internal::MatcherBase<T> {
168 public:
169 // Constructs a null matcher. Needed for storing Matcher objects in
170 // STL containers.
171 Matcher() {}
172
173 // Constructs a matcher from its implementation.
174 explicit Matcher(const MatcherInterface<T>* impl)
175 : internal::MatcherBase<T>(impl) {}
176
zhanyong.wan18490652009-05-11 18:54:08 +0000177 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000178 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
179 Matcher(T value); // NOLINT
180};
181
182// The following two specializations allow the user to write str
183// instead of Eq(str) and "foo" instead of Eq("foo") when a string
184// matcher is expected.
185template <>
186class Matcher<const internal::string&>
187 : public internal::MatcherBase<const internal::string&> {
188 public:
189 Matcher() {}
190
191 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
192 : internal::MatcherBase<const internal::string&>(impl) {}
193
194 // Allows the user to write str instead of Eq(str) sometimes, where
195 // str is a string object.
196 Matcher(const internal::string& s); // NOLINT
197
198 // Allows the user to write "foo" instead of Eq("foo") sometimes.
199 Matcher(const char* s); // NOLINT
200};
201
202template <>
203class Matcher<internal::string>
204 : public internal::MatcherBase<internal::string> {
205 public:
206 Matcher() {}
207
208 explicit Matcher(const MatcherInterface<internal::string>* impl)
209 : internal::MatcherBase<internal::string>(impl) {}
210
211 // Allows the user to write str instead of Eq(str) sometimes, where
212 // str is a string object.
213 Matcher(const internal::string& s); // NOLINT
214
215 // Allows the user to write "foo" instead of Eq("foo") sometimes.
216 Matcher(const char* s); // NOLINT
217};
218
219// The PolymorphicMatcher class template makes it easy to implement a
220// polymorphic matcher (i.e. a matcher that can match values of more
221// than one type, e.g. Eq(n) and NotNull()).
222//
223// To define a polymorphic matcher, a user first provides a Impl class
224// that has a Matches() method, a DescribeTo() method, and a
225// DescribeNegationTo() method. The Matches() method is usually a
226// method template (such that it works with multiple types). Then the
227// user creates the polymorphic matcher using
228// MakePolymorphicMatcher(). To provide additional explanation to the
229// match result, define a FREE function (or function template)
230//
231// void ExplainMatchResultTo(const Impl& matcher, const Value& value,
232// ::std::ostream* os);
233//
234// in the SAME NAME SPACE where Impl is defined. See the definition
235// of NotNull() for a complete example.
236template <class Impl>
237class PolymorphicMatcher {
238 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000239 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
shiqiane35fdd92008-12-10 05:08:54 +0000240
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000241 // Returns a mutable reference to the underlying matcher
242 // implementation object.
243 Impl& mutable_impl() { return impl_; }
244
245 // Returns an immutable reference to the underlying matcher
246 // implementation object.
247 const Impl& impl() const { return impl_; }
248
shiqiane35fdd92008-12-10 05:08:54 +0000249 template <typename T>
250 operator Matcher<T>() const {
251 return Matcher<T>(new MonomorphicImpl<T>(impl_));
252 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000253
shiqiane35fdd92008-12-10 05:08:54 +0000254 private:
255 template <typename T>
256 class MonomorphicImpl : public MatcherInterface<T> {
257 public:
258 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
259
260 virtual bool Matches(T x) const { return impl_.Matches(x); }
261
262 virtual void DescribeTo(::std::ostream* os) const {
263 impl_.DescribeTo(os);
264 }
265
266 virtual void DescribeNegationTo(::std::ostream* os) const {
267 impl_.DescribeNegationTo(os);
268 }
269
270 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
271 using ::testing::internal::ExplainMatchResultTo;
272
273 // C++ uses Argument-Dependent Look-up (aka Koenig Look-up) to
274 // resolve the call to ExplainMatchResultTo() here. This
275 // means that if there's a ExplainMatchResultTo() function
276 // defined in the name space where class Impl is defined, it
277 // will be picked by the compiler as the better match.
278 // Otherwise the default implementation of it in
279 // ::testing::internal will be picked.
280 //
281 // This look-up rule lets a writer of a polymorphic matcher
282 // customize the behavior of ExplainMatchResultTo() when he
283 // cares to. Nothing needs to be done by the writer if he
284 // doesn't need to customize it.
285 ExplainMatchResultTo(impl_, x, os);
286 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000287
shiqiane35fdd92008-12-10 05:08:54 +0000288 private:
289 const Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000290
291 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
shiqiane35fdd92008-12-10 05:08:54 +0000292 };
293
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000294 Impl impl_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000295
296 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000297};
298
299// Creates a matcher from its implementation. This is easier to use
300// than the Matcher<T> constructor as it doesn't require you to
301// explicitly write the template argument, e.g.
302//
303// MakeMatcher(foo);
304// vs
305// Matcher<const string&>(foo);
306template <typename T>
307inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
308 return Matcher<T>(impl);
309};
310
311// Creates a polymorphic matcher from its implementation. This is
312// easier to use than the PolymorphicMatcher<Impl> constructor as it
313// doesn't require you to explicitly write the template argument, e.g.
314//
315// MakePolymorphicMatcher(foo);
316// vs
317// PolymorphicMatcher<TypeOfFoo>(foo);
318template <class Impl>
319inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
320 return PolymorphicMatcher<Impl>(impl);
321}
322
323// In order to be safe and clear, casting between different matcher
324// types is done explicitly via MatcherCast<T>(m), which takes a
325// matcher m and returns a Matcher<T>. It compiles only when T can be
326// statically converted to the argument type of m.
327template <typename T, typename M>
328Matcher<T> MatcherCast(M m);
329
zhanyong.wan18490652009-05-11 18:54:08 +0000330// Implements SafeMatcherCast().
331//
zhanyong.wan95b12332009-09-25 18:55:50 +0000332// We use an intermediate class to do the actual safe casting as Nokia's
333// Symbian compiler cannot decide between
334// template <T, M> ... (M) and
335// template <T, U> ... (const Matcher<U>&)
336// for function templates but can for member function templates.
337template <typename T>
338class SafeMatcherCastImpl {
339 public:
340 // This overload handles polymorphic matchers only since monomorphic
341 // matchers are handled by the next one.
342 template <typename M>
343 static inline Matcher<T> Cast(M polymorphic_matcher) {
344 return Matcher<T>(polymorphic_matcher);
345 }
zhanyong.wan18490652009-05-11 18:54:08 +0000346
zhanyong.wan95b12332009-09-25 18:55:50 +0000347 // This overload handles monomorphic matchers.
348 //
349 // In general, if type T can be implicitly converted to type U, we can
350 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
351 // contravariant): just keep a copy of the original Matcher<U>, convert the
352 // argument from type T to U, and then pass it to the underlying Matcher<U>.
353 // The only exception is when U is a reference and T is not, as the
354 // underlying Matcher<U> may be interested in the argument's address, which
355 // is not preserved in the conversion from T to U.
356 template <typename U>
357 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
358 // Enforce that T can be implicitly converted to U.
359 GMOCK_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
360 T_must_be_implicitly_convertible_to_U);
361 // Enforce that we are not converting a non-reference type T to a reference
362 // type U.
363 GMOCK_COMPILE_ASSERT_(
364 internal::is_reference<T>::value || !internal::is_reference<U>::value,
365 cannot_convert_non_referentce_arg_to_reference);
366 // In case both T and U are arithmetic types, enforce that the
367 // conversion is not lossy.
368 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(T)) RawT;
369 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(U)) RawU;
370 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
371 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
372 GMOCK_COMPILE_ASSERT_(
373 kTIsOther || kUIsOther ||
374 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
375 conversion_of_arithmetic_types_must_be_lossless);
376 return MatcherCast<T>(matcher);
377 }
378};
379
380template <typename T, typename M>
381inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
382 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
zhanyong.wan18490652009-05-11 18:54:08 +0000383}
384
shiqiane35fdd92008-12-10 05:08:54 +0000385// A<T>() returns a matcher that matches any value of type T.
386template <typename T>
387Matcher<T> A();
388
389// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
390// and MUST NOT BE USED IN USER CODE!!!
391namespace internal {
392
393// Appends the explanation on the result of matcher.Matches(value) to
394// os iff the explanation is not empty.
395template <typename T>
396void ExplainMatchResultAsNeededTo(const Matcher<T>& matcher, T value,
397 ::std::ostream* os) {
398 ::std::stringstream reason;
399 matcher.ExplainMatchResultTo(value, &reason);
400 const internal::string s = reason.str();
401 if (s != "") {
402 *os << " (" << s << ")";
403 }
404}
405
406// An internal helper class for doing compile-time loop on a tuple's
407// fields.
408template <size_t N>
409class TuplePrefix {
410 public:
411 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
412 // iff the first N fields of matcher_tuple matches the first N
413 // fields of value_tuple, respectively.
414 template <typename MatcherTuple, typename ValueTuple>
415 static bool Matches(const MatcherTuple& matcher_tuple,
416 const ValueTuple& value_tuple) {
417 using ::std::tr1::get;
418 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
419 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
420 }
421
422 // TuplePrefix<N>::DescribeMatchFailuresTo(matchers, values, os)
423 // describes failures in matching the first N fields of matchers
424 // against the first N fields of values. If there is no failure,
425 // nothing will be streamed to os.
426 template <typename MatcherTuple, typename ValueTuple>
427 static void DescribeMatchFailuresTo(const MatcherTuple& matchers,
428 const ValueTuple& values,
429 ::std::ostream* os) {
430 using ::std::tr1::tuple_element;
431 using ::std::tr1::get;
432
433 // First, describes failures in the first N - 1 fields.
434 TuplePrefix<N - 1>::DescribeMatchFailuresTo(matchers, values, os);
435
436 // Then describes the failure (if any) in the (N - 1)-th (0-based)
437 // field.
438 typename tuple_element<N - 1, MatcherTuple>::type matcher =
439 get<N - 1>(matchers);
440 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
441 Value value = get<N - 1>(values);
442 if (!matcher.Matches(value)) {
443 // TODO(wan): include in the message the name of the parameter
444 // as used in MOCK_METHOD*() when possible.
445 *os << " Expected arg #" << N - 1 << ": ";
446 get<N - 1>(matchers).DescribeTo(os);
447 *os << "\n Actual: ";
448 // We remove the reference in type Value to prevent the
449 // universal printer from printing the address of value, which
450 // isn't interesting to the user most of the time. The
451 // matcher's ExplainMatchResultTo() method handles the case when
452 // the address is interesting.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000453 internal::UniversalPrinter<GMOCK_REMOVE_REFERENCE_(Value)>::
shiqiane35fdd92008-12-10 05:08:54 +0000454 Print(value, os);
455 ExplainMatchResultAsNeededTo<Value>(matcher, value, os);
456 *os << "\n";
457 }
458 }
459};
460
461// The base case.
462template <>
463class TuplePrefix<0> {
464 public:
465 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000466 static bool Matches(const MatcherTuple& /* matcher_tuple */,
467 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000468 return true;
469 }
470
471 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000472 static void DescribeMatchFailuresTo(const MatcherTuple& /* matchers */,
473 const ValueTuple& /* values */,
474 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000475};
476
477// TupleMatches(matcher_tuple, value_tuple) returns true iff all
478// matchers in matcher_tuple match the corresponding fields in
479// value_tuple. It is a compiler error if matcher_tuple and
480// value_tuple have different number of fields or incompatible field
481// types.
482template <typename MatcherTuple, typename ValueTuple>
483bool TupleMatches(const MatcherTuple& matcher_tuple,
484 const ValueTuple& value_tuple) {
485 using ::std::tr1::tuple_size;
486 // Makes sure that matcher_tuple and value_tuple have the same
487 // number of fields.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000488 GMOCK_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
489 tuple_size<ValueTuple>::value,
490 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000491 return TuplePrefix<tuple_size<ValueTuple>::value>::
492 Matches(matcher_tuple, value_tuple);
493}
494
495// Describes failures in matching matchers against values. If there
496// is no failure, nothing will be streamed to os.
497template <typename MatcherTuple, typename ValueTuple>
498void DescribeMatchFailureTupleTo(const MatcherTuple& matchers,
499 const ValueTuple& values,
500 ::std::ostream* os) {
501 using ::std::tr1::tuple_size;
502 TuplePrefix<tuple_size<MatcherTuple>::value>::DescribeMatchFailuresTo(
503 matchers, values, os);
504}
505
506// The MatcherCastImpl class template is a helper for implementing
507// MatcherCast(). We need this helper in order to partially
508// specialize the implementation of MatcherCast() (C++ allows
509// class/struct templates to be partially specialized, but not
510// function templates.).
511
512// This general version is used when MatcherCast()'s argument is a
513// polymorphic matcher (i.e. something that can be converted to a
514// Matcher but is not one yet; for example, Eq(value)).
515template <typename T, typename M>
516class MatcherCastImpl {
517 public:
518 static Matcher<T> Cast(M polymorphic_matcher) {
519 return Matcher<T>(polymorphic_matcher);
520 }
521};
522
523// This more specialized version is used when MatcherCast()'s argument
524// is already a Matcher. This only compiles when type T can be
525// statically converted to type U.
526template <typename T, typename U>
527class MatcherCastImpl<T, Matcher<U> > {
528 public:
529 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
530 return Matcher<T>(new Impl(source_matcher));
531 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000532
shiqiane35fdd92008-12-10 05:08:54 +0000533 private:
534 class Impl : public MatcherInterface<T> {
535 public:
536 explicit Impl(const Matcher<U>& source_matcher)
537 : source_matcher_(source_matcher) {}
538
539 // We delegate the matching logic to the source matcher.
540 virtual bool Matches(T x) const {
541 return source_matcher_.Matches(static_cast<U>(x));
542 }
543
544 virtual void DescribeTo(::std::ostream* os) const {
545 source_matcher_.DescribeTo(os);
546 }
547
548 virtual void DescribeNegationTo(::std::ostream* os) const {
549 source_matcher_.DescribeNegationTo(os);
550 }
551
552 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
553 source_matcher_.ExplainMatchResultTo(static_cast<U>(x), os);
554 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000555
shiqiane35fdd92008-12-10 05:08:54 +0000556 private:
557 const Matcher<U> source_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000558
559 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000560 };
561};
562
563// This even more specialized version is used for efficiently casting
564// a matcher to its own type.
565template <typename T>
566class MatcherCastImpl<T, Matcher<T> > {
567 public:
568 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
569};
570
571// Implements A<T>().
572template <typename T>
573class AnyMatcherImpl : public MatcherInterface<T> {
574 public:
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000575 virtual bool Matches(T /* x */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000576 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
577 virtual void DescribeNegationTo(::std::ostream* os) const {
578 // This is mostly for completeness' safe, as it's not very useful
579 // to write Not(A<bool>()). However we cannot completely rule out
580 // such a possibility, and it doesn't hurt to be prepared.
581 *os << "never matches";
582 }
583};
584
585// Implements _, a matcher that matches any value of any
586// type. This is a polymorphic matcher, so we need a template type
587// conversion operator to make it appearing as a Matcher<T> for any
588// type T.
589class AnythingMatcher {
590 public:
591 template <typename T>
592 operator Matcher<T>() const { return A<T>(); }
593};
594
595// Implements a matcher that compares a given value with a
596// pre-supplied value using one of the ==, <=, <, etc, operators. The
597// two values being compared don't have to have the same type.
598//
599// The matcher defined here is polymorphic (for example, Eq(5) can be
600// used to match an int, a short, a double, etc). Therefore we use
601// a template type conversion operator in the implementation.
602//
603// We define this as a macro in order to eliminate duplicated source
604// code.
605//
606// The following template definition assumes that the Rhs parameter is
607// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wane0d051e2009-02-19 00:33:37 +0000608#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000609 template <typename Rhs> class name##Matcher { \
610 public: \
611 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
612 template <typename Lhs> \
613 operator Matcher<Lhs>() const { \
614 return MakeMatcher(new Impl<Lhs>(rhs_)); \
615 } \
616 private: \
617 template <typename Lhs> \
618 class Impl : public MatcherInterface<Lhs> { \
619 public: \
620 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
621 virtual bool Matches(Lhs lhs) const { return lhs op rhs_; } \
622 virtual void DescribeTo(::std::ostream* os) const { \
623 *os << "is " relation " "; \
624 UniversalPrinter<Rhs>::Print(rhs_, os); \
625 } \
626 virtual void DescribeNegationTo(::std::ostream* os) const { \
627 *os << "is not " relation " "; \
628 UniversalPrinter<Rhs>::Print(rhs_, os); \
629 } \
630 private: \
631 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000632 GTEST_DISALLOW_ASSIGN_(Impl); \
shiqiane35fdd92008-12-10 05:08:54 +0000633 }; \
634 Rhs rhs_; \
zhanyong.wan32de5f52009-12-23 00:13:23 +0000635 GTEST_DISALLOW_ASSIGN_(name##Matcher); \
shiqiane35fdd92008-12-10 05:08:54 +0000636 }
637
638// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
639// respectively.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000640GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "equal to");
641GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "greater than or equal to");
642GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "greater than");
643GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "less than or equal to");
644GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "less than");
645GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "not equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000646
zhanyong.wane0d051e2009-02-19 00:33:37 +0000647#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000648
vladlosev79b83502009-11-18 00:43:37 +0000649// Implements the polymorphic IsNull() matcher, which matches any raw or smart
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000650// pointer that is NULL.
651class IsNullMatcher {
652 public:
vladlosev79b83502009-11-18 00:43:37 +0000653 template <typename Pointer>
654 bool Matches(const Pointer& p) const { return GetRawPointer(p) == NULL; }
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000655
656 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
657 void DescribeNegationTo(::std::ostream* os) const {
658 *os << "is not NULL";
659 }
660};
661
vladlosev79b83502009-11-18 00:43:37 +0000662// Implements the polymorphic NotNull() matcher, which matches any raw or smart
shiqiane35fdd92008-12-10 05:08:54 +0000663// pointer that is not NULL.
664class NotNullMatcher {
665 public:
vladlosev79b83502009-11-18 00:43:37 +0000666 template <typename Pointer>
667 bool Matches(const Pointer& p) const { return GetRawPointer(p) != NULL; }
shiqiane35fdd92008-12-10 05:08:54 +0000668
669 void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; }
670 void DescribeNegationTo(::std::ostream* os) const {
671 *os << "is NULL";
672 }
673};
674
675// Ref(variable) matches any argument that is a reference to
676// 'variable'. This matcher is polymorphic as it can match any
677// super type of the type of 'variable'.
678//
679// The RefMatcher template class implements Ref(variable). It can
680// only be instantiated with a reference type. This prevents a user
681// from mistakenly using Ref(x) to match a non-reference function
682// argument. For example, the following will righteously cause a
683// compiler error:
684//
685// int n;
686// Matcher<int> m1 = Ref(n); // This won't compile.
687// Matcher<int&> m2 = Ref(n); // This will compile.
688template <typename T>
689class RefMatcher;
690
691template <typename T>
692class RefMatcher<T&> {
693 // Google Mock is a generic framework and thus needs to support
694 // mocking any function types, including those that take non-const
695 // reference arguments. Therefore the template parameter T (and
696 // Super below) can be instantiated to either a const type or a
697 // non-const type.
698 public:
699 // RefMatcher() takes a T& instead of const T&, as we want the
700 // compiler to catch using Ref(const_value) as a matcher for a
701 // non-const reference.
702 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
703
704 template <typename Super>
705 operator Matcher<Super&>() const {
706 // By passing object_ (type T&) to Impl(), which expects a Super&,
707 // we make sure that Super is a super type of T. In particular,
708 // this catches using Ref(const_value) as a matcher for a
709 // non-const reference, as you cannot implicitly convert a const
710 // reference to a non-const reference.
711 return MakeMatcher(new Impl<Super>(object_));
712 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000713
shiqiane35fdd92008-12-10 05:08:54 +0000714 private:
715 template <typename Super>
716 class Impl : public MatcherInterface<Super&> {
717 public:
718 explicit Impl(Super& x) : object_(x) {} // NOLINT
719
720 // Matches() takes a Super& (as opposed to const Super&) in
721 // order to match the interface MatcherInterface<Super&>.
722 virtual bool Matches(Super& x) const { return &x == &object_; } // NOLINT
723
724 virtual void DescribeTo(::std::ostream* os) const {
725 *os << "references the variable ";
726 UniversalPrinter<Super&>::Print(object_, os);
727 }
728
729 virtual void DescribeNegationTo(::std::ostream* os) const {
730 *os << "does not reference the variable ";
731 UniversalPrinter<Super&>::Print(object_, os);
732 }
733
734 virtual void ExplainMatchResultTo(Super& x, // NOLINT
735 ::std::ostream* os) const {
736 *os << "is located @" << static_cast<const void*>(&x);
737 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000738
shiqiane35fdd92008-12-10 05:08:54 +0000739 private:
740 const Super& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000741
742 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +0000743 };
744
745 T& object_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000746
747 GTEST_DISALLOW_ASSIGN_(RefMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000748};
749
750// Polymorphic helper functions for narrow and wide string matchers.
751inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
752 return String::CaseInsensitiveCStringEquals(lhs, rhs);
753}
754
755inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
756 const wchar_t* rhs) {
757 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
758}
759
760// String comparison for narrow or wide strings that can have embedded NUL
761// characters.
762template <typename StringType>
763bool CaseInsensitiveStringEquals(const StringType& s1,
764 const StringType& s2) {
765 // Are the heads equal?
766 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
767 return false;
768 }
769
770 // Skip the equal heads.
771 const typename StringType::value_type nul = 0;
772 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
773
774 // Are we at the end of either s1 or s2?
775 if (i1 == StringType::npos || i2 == StringType::npos) {
776 return i1 == i2;
777 }
778
779 // Are the tails equal?
780 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
781}
782
783// String matchers.
784
785// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
786template <typename StringType>
787class StrEqualityMatcher {
788 public:
789 typedef typename StringType::const_pointer ConstCharPointer;
790
791 StrEqualityMatcher(const StringType& str, bool expect_eq,
792 bool case_sensitive)
793 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
794
795 // When expect_eq_ is true, returns true iff s is equal to string_;
796 // otherwise returns true iff s is not equal to string_.
797 bool Matches(ConstCharPointer s) const {
798 if (s == NULL) {
799 return !expect_eq_;
800 }
801 return Matches(StringType(s));
802 }
803
804 bool Matches(const StringType& s) const {
805 const bool eq = case_sensitive_ ? s == string_ :
806 CaseInsensitiveStringEquals(s, string_);
807 return expect_eq_ == eq;
808 }
809
810 void DescribeTo(::std::ostream* os) const {
811 DescribeToHelper(expect_eq_, os);
812 }
813
814 void DescribeNegationTo(::std::ostream* os) const {
815 DescribeToHelper(!expect_eq_, os);
816 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000817
shiqiane35fdd92008-12-10 05:08:54 +0000818 private:
819 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
820 *os << "is ";
821 if (!expect_eq) {
822 *os << "not ";
823 }
824 *os << "equal to ";
825 if (!case_sensitive_) {
826 *os << "(ignoring case) ";
827 }
828 UniversalPrinter<StringType>::Print(string_, os);
829 }
830
831 const StringType string_;
832 const bool expect_eq_;
833 const bool case_sensitive_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000834
835 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000836};
837
838// Implements the polymorphic HasSubstr(substring) matcher, which
839// can be used as a Matcher<T> as long as T can be converted to a
840// string.
841template <typename StringType>
842class HasSubstrMatcher {
843 public:
844 typedef typename StringType::const_pointer ConstCharPointer;
845
846 explicit HasSubstrMatcher(const StringType& substring)
847 : substring_(substring) {}
848
849 // These overloaded methods allow HasSubstr(substring) to be used as a
850 // Matcher<T> as long as T can be converted to string. Returns true
851 // iff s contains substring_ as a substring.
852 bool Matches(ConstCharPointer s) const {
853 return s != NULL && Matches(StringType(s));
854 }
855
856 bool Matches(const StringType& s) const {
857 return s.find(substring_) != StringType::npos;
858 }
859
860 // Describes what this matcher matches.
861 void DescribeTo(::std::ostream* os) const {
862 *os << "has substring ";
863 UniversalPrinter<StringType>::Print(substring_, os);
864 }
865
866 void DescribeNegationTo(::std::ostream* os) const {
867 *os << "has no substring ";
868 UniversalPrinter<StringType>::Print(substring_, os);
869 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000870
shiqiane35fdd92008-12-10 05:08:54 +0000871 private:
872 const StringType substring_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000873
874 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000875};
876
877// Implements the polymorphic StartsWith(substring) matcher, which
878// can be used as a Matcher<T> as long as T can be converted to a
879// string.
880template <typename StringType>
881class StartsWithMatcher {
882 public:
883 typedef typename StringType::const_pointer ConstCharPointer;
884
885 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
886 }
887
888 // These overloaded methods allow StartsWith(prefix) to be used as a
889 // Matcher<T> as long as T can be converted to string. Returns true
890 // iff s starts with prefix_.
891 bool Matches(ConstCharPointer s) const {
892 return s != NULL && Matches(StringType(s));
893 }
894
895 bool Matches(const StringType& s) const {
896 return s.length() >= prefix_.length() &&
897 s.substr(0, prefix_.length()) == prefix_;
898 }
899
900 void DescribeTo(::std::ostream* os) const {
901 *os << "starts with ";
902 UniversalPrinter<StringType>::Print(prefix_, os);
903 }
904
905 void DescribeNegationTo(::std::ostream* os) const {
906 *os << "doesn't start with ";
907 UniversalPrinter<StringType>::Print(prefix_, os);
908 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000909
shiqiane35fdd92008-12-10 05:08:54 +0000910 private:
911 const StringType prefix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000912
913 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000914};
915
916// Implements the polymorphic EndsWith(substring) matcher, which
917// can be used as a Matcher<T> as long as T can be converted to a
918// string.
919template <typename StringType>
920class EndsWithMatcher {
921 public:
922 typedef typename StringType::const_pointer ConstCharPointer;
923
924 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
925
926 // These overloaded methods allow EndsWith(suffix) to be used as a
927 // Matcher<T> as long as T can be converted to string. Returns true
928 // iff s ends with suffix_.
929 bool Matches(ConstCharPointer s) const {
930 return s != NULL && Matches(StringType(s));
931 }
932
933 bool Matches(const StringType& s) const {
934 return s.length() >= suffix_.length() &&
935 s.substr(s.length() - suffix_.length()) == suffix_;
936 }
937
938 void DescribeTo(::std::ostream* os) const {
939 *os << "ends with ";
940 UniversalPrinter<StringType>::Print(suffix_, os);
941 }
942
943 void DescribeNegationTo(::std::ostream* os) const {
944 *os << "doesn't end with ";
945 UniversalPrinter<StringType>::Print(suffix_, os);
946 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000947
shiqiane35fdd92008-12-10 05:08:54 +0000948 private:
949 const StringType suffix_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000950
951 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000952};
953
954#if GMOCK_HAS_REGEX
955
956// Implements polymorphic matchers MatchesRegex(regex) and
957// ContainsRegex(regex), which can be used as a Matcher<T> as long as
958// T can be converted to a string.
959class MatchesRegexMatcher {
960 public:
961 MatchesRegexMatcher(const RE* regex, bool full_match)
962 : regex_(regex), full_match_(full_match) {}
963
964 // These overloaded methods allow MatchesRegex(regex) to be used as
965 // a Matcher<T> as long as T can be converted to string. Returns
966 // true iff s matches regular expression regex. When full_match_ is
967 // true, a full match is done; otherwise a partial match is done.
968 bool Matches(const char* s) const {
969 return s != NULL && Matches(internal::string(s));
970 }
971
972 bool Matches(const internal::string& s) const {
973 return full_match_ ? RE::FullMatch(s, *regex_) :
974 RE::PartialMatch(s, *regex_);
975 }
976
977 void DescribeTo(::std::ostream* os) const {
978 *os << (full_match_ ? "matches" : "contains")
979 << " regular expression ";
980 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
981 }
982
983 void DescribeNegationTo(::std::ostream* os) const {
984 *os << "doesn't " << (full_match_ ? "match" : "contain")
985 << " regular expression ";
986 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
987 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000988
shiqiane35fdd92008-12-10 05:08:54 +0000989 private:
990 const internal::linked_ptr<const RE> regex_;
991 const bool full_match_;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000992
993 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
shiqiane35fdd92008-12-10 05:08:54 +0000994};
995
996#endif // GMOCK_HAS_REGEX
997
998// Implements a matcher that compares the two fields of a 2-tuple
999// using one of the ==, <=, <, etc, operators. The two fields being
1000// compared don't have to have the same type.
1001//
1002// The matcher defined here is polymorphic (for example, Eq() can be
1003// used to match a tuple<int, short>, a tuple<const long&, double>,
1004// etc). Therefore we use a template type conversion operator in the
1005// implementation.
1006//
1007// We define this as a macro in order to eliminate duplicated source
1008// code.
zhanyong.wan2661c682009-06-09 05:42:12 +00001009#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op) \
shiqiane35fdd92008-12-10 05:08:54 +00001010 class name##2Matcher { \
1011 public: \
1012 template <typename T1, typename T2> \
1013 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
1014 return MakeMatcher(new Impl<T1, T2>); \
1015 } \
1016 private: \
1017 template <typename T1, typename T2> \
1018 class Impl : public MatcherInterface<const ::std::tr1::tuple<T1, T2>&> { \
1019 public: \
1020 virtual bool Matches(const ::std::tr1::tuple<T1, T2>& args) const { \
1021 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
1022 } \
1023 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +00001024 *os << "are a pair (x, y) where x " #op " y"; \
shiqiane35fdd92008-12-10 05:08:54 +00001025 } \
1026 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +00001027 *os << "are a pair (x, y) where x " #op " y is false"; \
shiqiane35fdd92008-12-10 05:08:54 +00001028 } \
1029 }; \
1030 }
1031
1032// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wan2661c682009-06-09 05:42:12 +00001033GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==);
1034GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ge, >=);
1035GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Gt, >);
1036GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Le, <=);
1037GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Lt, <);
1038GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=);
shiqiane35fdd92008-12-10 05:08:54 +00001039
zhanyong.wane0d051e2009-02-19 00:33:37 +00001040#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +00001041
zhanyong.wanc6a41232009-05-13 23:38:40 +00001042// Implements the Not(...) matcher for a particular argument type T.
1043// We do not nest it inside the NotMatcher class template, as that
1044// will prevent different instantiations of NotMatcher from sharing
1045// the same NotMatcherImpl<T> class.
1046template <typename T>
1047class NotMatcherImpl : public MatcherInterface<T> {
1048 public:
1049 explicit NotMatcherImpl(const Matcher<T>& matcher)
1050 : matcher_(matcher) {}
1051
1052 virtual bool Matches(T x) const {
1053 return !matcher_.Matches(x);
1054 }
1055
1056 virtual void DescribeTo(::std::ostream* os) const {
1057 matcher_.DescribeNegationTo(os);
1058 }
1059
1060 virtual void DescribeNegationTo(::std::ostream* os) const {
1061 matcher_.DescribeTo(os);
1062 }
1063
1064 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1065 matcher_.ExplainMatchResultTo(x, os);
1066 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001067
zhanyong.wanc6a41232009-05-13 23:38:40 +00001068 private:
1069 const Matcher<T> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001070
1071 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001072};
1073
shiqiane35fdd92008-12-10 05:08:54 +00001074// Implements the Not(m) matcher, which matches a value that doesn't
1075// match matcher m.
1076template <typename InnerMatcher>
1077class NotMatcher {
1078 public:
1079 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1080
1081 // This template type conversion operator allows Not(m) to be used
1082 // to match any type m can match.
1083 template <typename T>
1084 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001085 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001086 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001087
shiqiane35fdd92008-12-10 05:08:54 +00001088 private:
shiqiane35fdd92008-12-10 05:08:54 +00001089 InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001090
1091 GTEST_DISALLOW_ASSIGN_(NotMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001092};
1093
zhanyong.wanc6a41232009-05-13 23:38:40 +00001094// Implements the AllOf(m1, m2) matcher for a particular argument type
1095// T. We do not nest it inside the BothOfMatcher class template, as
1096// that will prevent different instantiations of BothOfMatcher from
1097// sharing the same BothOfMatcherImpl<T> class.
1098template <typename T>
1099class BothOfMatcherImpl : public MatcherInterface<T> {
1100 public:
1101 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1102 : matcher1_(matcher1), matcher2_(matcher2) {}
1103
1104 virtual bool Matches(T x) const {
1105 return matcher1_.Matches(x) && matcher2_.Matches(x);
1106 }
1107
1108 virtual void DescribeTo(::std::ostream* os) const {
1109 *os << "(";
1110 matcher1_.DescribeTo(os);
1111 *os << ") and (";
1112 matcher2_.DescribeTo(os);
1113 *os << ")";
1114 }
1115
1116 virtual void DescribeNegationTo(::std::ostream* os) const {
1117 *os << "not ";
1118 DescribeTo(os);
1119 }
1120
1121 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1122 if (Matches(x)) {
1123 // When both matcher1_ and matcher2_ match x, we need to
1124 // explain why *both* of them match.
1125 ::std::stringstream ss1;
1126 matcher1_.ExplainMatchResultTo(x, &ss1);
1127 const internal::string s1 = ss1.str();
1128
1129 ::std::stringstream ss2;
1130 matcher2_.ExplainMatchResultTo(x, &ss2);
1131 const internal::string s2 = ss2.str();
1132
1133 if (s1 == "") {
1134 *os << s2;
1135 } else {
1136 *os << s1;
1137 if (s2 != "") {
1138 *os << "; " << s2;
1139 }
1140 }
1141 } else {
1142 // Otherwise we only need to explain why *one* of them fails
1143 // to match.
1144 if (!matcher1_.Matches(x)) {
1145 matcher1_.ExplainMatchResultTo(x, os);
1146 } else {
1147 matcher2_.ExplainMatchResultTo(x, os);
1148 }
1149 }
1150 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001151
zhanyong.wanc6a41232009-05-13 23:38:40 +00001152 private:
1153 const Matcher<T> matcher1_;
1154 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001155
1156 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001157};
1158
shiqiane35fdd92008-12-10 05:08:54 +00001159// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1160// matches a value that matches all of the matchers m_1, ..., and m_n.
1161template <typename Matcher1, typename Matcher2>
1162class BothOfMatcher {
1163 public:
1164 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1165 : matcher1_(matcher1), matcher2_(matcher2) {}
1166
1167 // This template type conversion operator allows a
1168 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1169 // both Matcher1 and Matcher2 can match.
1170 template <typename T>
1171 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001172 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1173 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001174 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001175
shiqiane35fdd92008-12-10 05:08:54 +00001176 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001177 Matcher1 matcher1_;
1178 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001179
1180 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
zhanyong.wanc6a41232009-05-13 23:38:40 +00001181};
shiqiane35fdd92008-12-10 05:08:54 +00001182
zhanyong.wanc6a41232009-05-13 23:38:40 +00001183// Implements the AnyOf(m1, m2) matcher for a particular argument type
1184// T. We do not nest it inside the AnyOfMatcher class template, as
1185// that will prevent different instantiations of AnyOfMatcher from
1186// sharing the same EitherOfMatcherImpl<T> class.
1187template <typename T>
1188class EitherOfMatcherImpl : public MatcherInterface<T> {
1189 public:
1190 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1191 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001192
zhanyong.wanc6a41232009-05-13 23:38:40 +00001193 virtual bool Matches(T x) const {
1194 return matcher1_.Matches(x) || matcher2_.Matches(x);
1195 }
shiqiane35fdd92008-12-10 05:08:54 +00001196
zhanyong.wanc6a41232009-05-13 23:38:40 +00001197 virtual void DescribeTo(::std::ostream* os) const {
1198 *os << "(";
1199 matcher1_.DescribeTo(os);
1200 *os << ") or (";
1201 matcher2_.DescribeTo(os);
1202 *os << ")";
1203 }
shiqiane35fdd92008-12-10 05:08:54 +00001204
zhanyong.wanc6a41232009-05-13 23:38:40 +00001205 virtual void DescribeNegationTo(::std::ostream* os) const {
1206 *os << "not ";
1207 DescribeTo(os);
1208 }
shiqiane35fdd92008-12-10 05:08:54 +00001209
zhanyong.wanc6a41232009-05-13 23:38:40 +00001210 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1211 if (Matches(x)) {
1212 // If either matcher1_ or matcher2_ matches x, we just need
1213 // to explain why *one* of them matches.
1214 if (matcher1_.Matches(x)) {
1215 matcher1_.ExplainMatchResultTo(x, os);
shiqiane35fdd92008-12-10 05:08:54 +00001216 } else {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001217 matcher2_.ExplainMatchResultTo(x, os);
1218 }
1219 } else {
1220 // Otherwise we need to explain why *neither* matches.
1221 ::std::stringstream ss1;
1222 matcher1_.ExplainMatchResultTo(x, &ss1);
1223 const internal::string s1 = ss1.str();
1224
1225 ::std::stringstream ss2;
1226 matcher2_.ExplainMatchResultTo(x, &ss2);
1227 const internal::string s2 = ss2.str();
1228
1229 if (s1 == "") {
1230 *os << s2;
1231 } else {
1232 *os << s1;
1233 if (s2 != "") {
1234 *os << "; " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001235 }
1236 }
1237 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001238 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001239
zhanyong.wanc6a41232009-05-13 23:38:40 +00001240 private:
1241 const Matcher<T> matcher1_;
1242 const Matcher<T> matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001243
1244 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
shiqiane35fdd92008-12-10 05:08:54 +00001245};
1246
1247// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1248// matches a value that matches at least one of the matchers m_1, ...,
1249// and m_n.
1250template <typename Matcher1, typename Matcher2>
1251class EitherOfMatcher {
1252 public:
1253 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1254 : matcher1_(matcher1), matcher2_(matcher2) {}
1255
1256 // This template type conversion operator allows a
1257 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1258 // both Matcher1 and Matcher2 can match.
1259 template <typename T>
1260 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001261 return Matcher<T>(new EitherOfMatcherImpl<T>(
1262 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001263 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001264
shiqiane35fdd92008-12-10 05:08:54 +00001265 private:
shiqiane35fdd92008-12-10 05:08:54 +00001266 Matcher1 matcher1_;
1267 Matcher2 matcher2_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001268
1269 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001270};
1271
1272// Used for implementing Truly(pred), which turns a predicate into a
1273// matcher.
1274template <typename Predicate>
1275class TrulyMatcher {
1276 public:
1277 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1278
1279 // This method template allows Truly(pred) to be used as a matcher
1280 // for type T where T is the argument type of predicate 'pred'. The
1281 // argument is passed by reference as the predicate may be
1282 // interested in the address of the argument.
1283 template <typename T>
zhanyong.wan16cf4732009-05-14 20:55:30 +00001284 bool Matches(T& x) const { // NOLINT
zhanyong.wan652540a2009-02-23 23:37:29 +00001285#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001286 // MSVC warns about converting a value into bool (warning 4800).
1287#pragma warning(push) // Saves the current warning state.
1288#pragma warning(disable:4800) // Temporarily disables warning 4800.
1289#endif // GTEST_OS_WINDOWS
1290 return predicate_(x);
zhanyong.wan652540a2009-02-23 23:37:29 +00001291#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001292#pragma warning(pop) // Restores the warning state.
1293#endif // GTEST_OS_WINDOWS
1294 }
1295
1296 void DescribeTo(::std::ostream* os) const {
1297 *os << "satisfies the given predicate";
1298 }
1299
1300 void DescribeNegationTo(::std::ostream* os) const {
1301 *os << "doesn't satisfy the given predicate";
1302 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001303
shiqiane35fdd92008-12-10 05:08:54 +00001304 private:
1305 Predicate predicate_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001306
1307 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001308};
1309
1310// Used for implementing Matches(matcher), which turns a matcher into
1311// a predicate.
1312template <typename M>
1313class MatcherAsPredicate {
1314 public:
1315 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1316
1317 // This template operator() allows Matches(m) to be used as a
1318 // predicate on type T where m is a matcher on type T.
1319 //
1320 // The argument x is passed by reference instead of by value, as
1321 // some matcher may be interested in its address (e.g. as in
1322 // Matches(Ref(n))(x)).
1323 template <typename T>
1324 bool operator()(const T& x) const {
1325 // We let matcher_ commit to a particular type here instead of
1326 // when the MatcherAsPredicate object was constructed. This
1327 // allows us to write Matches(m) where m is a polymorphic matcher
1328 // (e.g. Eq(5)).
1329 //
1330 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1331 // compile when matcher_ has type Matcher<const T&>; if we write
1332 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1333 // when matcher_ has type Matcher<T>; if we just write
1334 // matcher_.Matches(x), it won't compile when matcher_ is
1335 // polymorphic, e.g. Eq(5).
1336 //
1337 // MatcherCast<const T&>() is necessary for making the code work
1338 // in all of the above situations.
1339 return MatcherCast<const T&>(matcher_).Matches(x);
1340 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001341
shiqiane35fdd92008-12-10 05:08:54 +00001342 private:
1343 M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001344
1345 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
shiqiane35fdd92008-12-10 05:08:54 +00001346};
1347
1348// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1349// argument M must be a type that can be converted to a matcher.
1350template <typename M>
1351class PredicateFormatterFromMatcher {
1352 public:
1353 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1354
1355 // This template () operator allows a PredicateFormatterFromMatcher
1356 // object to act as a predicate-formatter suitable for using with
1357 // Google Test's EXPECT_PRED_FORMAT1() macro.
1358 template <typename T>
1359 AssertionResult operator()(const char* value_text, const T& x) const {
1360 // We convert matcher_ to a Matcher<const T&> *now* instead of
1361 // when the PredicateFormatterFromMatcher object was constructed,
1362 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1363 // know which type to instantiate it to until we actually see the
1364 // type of x here.
1365 //
1366 // We write MatcherCast<const T&>(matcher_) instead of
1367 // Matcher<const T&>(matcher_), as the latter won't compile when
1368 // matcher_ has type Matcher<T> (e.g. An<int>()).
1369 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
1370 if (matcher.Matches(x)) {
1371 return AssertionSuccess();
1372 } else {
1373 ::std::stringstream ss;
1374 ss << "Value of: " << value_text << "\n"
1375 << "Expected: ";
1376 matcher.DescribeTo(&ss);
1377 ss << "\n Actual: ";
1378 UniversalPrinter<T>::Print(x, &ss);
1379 ExplainMatchResultAsNeededTo<const T&>(matcher, x, &ss);
1380 return AssertionFailure(Message() << ss.str());
1381 }
1382 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001383
shiqiane35fdd92008-12-10 05:08:54 +00001384 private:
1385 const M matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001386
1387 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001388};
1389
1390// A helper function for converting a matcher to a predicate-formatter
1391// without the user needing to explicitly write the type. This is
1392// used for implementing ASSERT_THAT() and EXPECT_THAT().
1393template <typename M>
1394inline PredicateFormatterFromMatcher<M>
1395MakePredicateFormatterFromMatcher(const M& matcher) {
1396 return PredicateFormatterFromMatcher<M>(matcher);
1397}
1398
1399// Implements the polymorphic floating point equality matcher, which
1400// matches two float values using ULP-based approximation. The
1401// template is meant to be instantiated with FloatType being either
1402// float or double.
1403template <typename FloatType>
1404class FloatingEqMatcher {
1405 public:
1406 // Constructor for FloatingEqMatcher.
1407 // The matcher's input will be compared with rhs. The matcher treats two
1408 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1409 // equality comparisons between NANs will always return false.
1410 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1411 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1412
1413 // Implements floating point equality matcher as a Matcher<T>.
1414 template <typename T>
1415 class Impl : public MatcherInterface<T> {
1416 public:
1417 Impl(FloatType rhs, bool nan_eq_nan) :
1418 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1419
1420 virtual bool Matches(T value) const {
1421 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1422
1423 // Compares NaNs first, if nan_eq_nan_ is true.
1424 if (nan_eq_nan_ && lhs.is_nan()) {
1425 return rhs.is_nan();
1426 }
1427
1428 return lhs.AlmostEquals(rhs);
1429 }
1430
1431 virtual void DescribeTo(::std::ostream* os) const {
1432 // os->precision() returns the previously set precision, which we
1433 // store to restore the ostream to its original configuration
1434 // after outputting.
1435 const ::std::streamsize old_precision = os->precision(
1436 ::std::numeric_limits<FloatType>::digits10 + 2);
1437 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1438 if (nan_eq_nan_) {
1439 *os << "is NaN";
1440 } else {
1441 *os << "never matches";
1442 }
1443 } else {
1444 *os << "is approximately " << rhs_;
1445 }
1446 os->precision(old_precision);
1447 }
1448
1449 virtual void DescribeNegationTo(::std::ostream* os) const {
1450 // As before, get original precision.
1451 const ::std::streamsize old_precision = os->precision(
1452 ::std::numeric_limits<FloatType>::digits10 + 2);
1453 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1454 if (nan_eq_nan_) {
1455 *os << "is not NaN";
1456 } else {
1457 *os << "is anything";
1458 }
1459 } else {
1460 *os << "is not approximately " << rhs_;
1461 }
1462 // Restore original precision.
1463 os->precision(old_precision);
1464 }
1465
1466 private:
1467 const FloatType rhs_;
1468 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001469
1470 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001471 };
1472
1473 // The following 3 type conversion operators allow FloatEq(rhs) and
1474 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1475 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1476 // (While Google's C++ coding style doesn't allow arguments passed
1477 // by non-const reference, we may see them in code not conforming to
1478 // the style. Therefore Google Mock needs to support them.)
1479 operator Matcher<FloatType>() const {
1480 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1481 }
1482
1483 operator Matcher<const FloatType&>() const {
1484 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1485 }
1486
1487 operator Matcher<FloatType&>() const {
1488 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1489 }
1490 private:
1491 const FloatType rhs_;
1492 const bool nan_eq_nan_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001493
1494 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001495};
1496
1497// Implements the Pointee(m) matcher for matching a pointer whose
1498// pointee matches matcher m. The pointer can be either raw or smart.
1499template <typename InnerMatcher>
1500class PointeeMatcher {
1501 public:
1502 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1503
1504 // This type conversion operator template allows Pointee(m) to be
1505 // used as a matcher for any pointer type whose pointee type is
1506 // compatible with the inner matcher, where type Pointer can be
1507 // either a raw pointer or a smart pointer.
1508 //
1509 // The reason we do this instead of relying on
1510 // MakePolymorphicMatcher() is that the latter is not flexible
1511 // enough for implementing the DescribeTo() method of Pointee().
1512 template <typename Pointer>
1513 operator Matcher<Pointer>() const {
1514 return MakeMatcher(new Impl<Pointer>(matcher_));
1515 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001516
shiqiane35fdd92008-12-10 05:08:54 +00001517 private:
1518 // The monomorphic implementation that works for a particular pointer type.
1519 template <typename Pointer>
1520 class Impl : public MatcherInterface<Pointer> {
1521 public:
zhanyong.wane0d051e2009-02-19 00:33:37 +00001522 typedef typename PointeeOf<GMOCK_REMOVE_CONST_( // NOLINT
1523 GMOCK_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001524
1525 explicit Impl(const InnerMatcher& matcher)
1526 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1527
1528 virtual bool Matches(Pointer p) const {
1529 return GetRawPointer(p) != NULL && matcher_.Matches(*p);
1530 }
1531
1532 virtual void DescribeTo(::std::ostream* os) const {
1533 *os << "points to a value that ";
1534 matcher_.DescribeTo(os);
1535 }
1536
1537 virtual void DescribeNegationTo(::std::ostream* os) const {
1538 *os << "does not point to a value that ";
1539 matcher_.DescribeTo(os);
1540 }
1541
1542 virtual void ExplainMatchResultTo(Pointer pointer,
1543 ::std::ostream* os) const {
1544 if (GetRawPointer(pointer) == NULL)
1545 return;
1546
1547 ::std::stringstream ss;
1548 matcher_.ExplainMatchResultTo(*pointer, &ss);
1549 const internal::string s = ss.str();
1550 if (s != "") {
1551 *os << "points to a value that " << s;
1552 }
1553 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001554
shiqiane35fdd92008-12-10 05:08:54 +00001555 private:
1556 const Matcher<const Pointee&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001557
1558 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001559 };
1560
1561 const InnerMatcher matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001562
1563 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001564};
1565
1566// Implements the Field() matcher for matching a field (i.e. member
1567// variable) of an object.
1568template <typename Class, typename FieldType>
1569class FieldMatcher {
1570 public:
1571 FieldMatcher(FieldType Class::*field,
1572 const Matcher<const FieldType&>& matcher)
1573 : field_(field), matcher_(matcher) {}
1574
1575 // Returns true iff the inner matcher matches obj.field.
1576 bool Matches(const Class& obj) const {
1577 return matcher_.Matches(obj.*field_);
1578 }
1579
1580 // Returns true iff the inner matcher matches obj->field.
1581 bool Matches(const Class* p) const {
1582 return (p != NULL) && matcher_.Matches(p->*field_);
1583 }
1584
1585 void DescribeTo(::std::ostream* os) const {
1586 *os << "the given field ";
1587 matcher_.DescribeTo(os);
1588 }
1589
1590 void DescribeNegationTo(::std::ostream* os) const {
1591 *os << "the given field ";
1592 matcher_.DescribeNegationTo(os);
1593 }
1594
zhanyong.wan18490652009-05-11 18:54:08 +00001595 // The first argument of ExplainMatchResultTo() is needed to help
1596 // Symbian's C++ compiler choose which overload to use. Its type is
1597 // true_type iff the Field() matcher is used to match a pointer.
1598 void ExplainMatchResultTo(false_type /* is_not_pointer */, const Class& obj,
1599 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001600 ::std::stringstream ss;
1601 matcher_.ExplainMatchResultTo(obj.*field_, &ss);
1602 const internal::string s = ss.str();
1603 if (s != "") {
1604 *os << "the given field " << s;
1605 }
1606 }
1607
zhanyong.wan18490652009-05-11 18:54:08 +00001608 void ExplainMatchResultTo(true_type /* is_pointer */, const Class* p,
1609 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001610 if (p != NULL) {
zhanyong.wan18490652009-05-11 18:54:08 +00001611 // Since *p has a field, it must be a class/struct/union type
1612 // and thus cannot be a pointer. Therefore we pass false_type()
1613 // as the first argument.
1614 ExplainMatchResultTo(false_type(), *p, os);
shiqiane35fdd92008-12-10 05:08:54 +00001615 }
1616 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001617
shiqiane35fdd92008-12-10 05:08:54 +00001618 private:
1619 const FieldType Class::*field_;
1620 const Matcher<const FieldType&> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001621
1622 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001623};
1624
zhanyong.wan18490652009-05-11 18:54:08 +00001625// Explains the result of matching an object or pointer against a field matcher.
1626template <typename Class, typename FieldType, typename T>
shiqiane35fdd92008-12-10 05:08:54 +00001627void ExplainMatchResultTo(const FieldMatcher<Class, FieldType>& matcher,
zhanyong.wan18490652009-05-11 18:54:08 +00001628 const T& value, ::std::ostream* os) {
1629 matcher.ExplainMatchResultTo(
1630 typename ::testing::internal::is_pointer<T>::type(), value, os);
shiqiane35fdd92008-12-10 05:08:54 +00001631}
1632
1633// Implements the Property() matcher for matching a property
1634// (i.e. return value of a getter method) of an object.
1635template <typename Class, typename PropertyType>
1636class PropertyMatcher {
1637 public:
1638 // The property may have a reference type, so 'const PropertyType&'
1639 // may cause double references and fail to compile. That's why we
1640 // need GMOCK_REFERENCE_TO_CONST, which works regardless of
1641 // PropertyType being a reference or not.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001642 typedef GMOCK_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001643
1644 PropertyMatcher(PropertyType (Class::*property)() const,
1645 const Matcher<RefToConstProperty>& matcher)
1646 : property_(property), matcher_(matcher) {}
1647
1648 // Returns true iff obj.property() matches the inner matcher.
1649 bool Matches(const Class& obj) const {
1650 return matcher_.Matches((obj.*property_)());
1651 }
1652
1653 // Returns true iff p->property() matches the inner matcher.
1654 bool Matches(const Class* p) const {
1655 return (p != NULL) && matcher_.Matches((p->*property_)());
1656 }
1657
1658 void DescribeTo(::std::ostream* os) const {
1659 *os << "the given property ";
1660 matcher_.DescribeTo(os);
1661 }
1662
1663 void DescribeNegationTo(::std::ostream* os) const {
1664 *os << "the given property ";
1665 matcher_.DescribeNegationTo(os);
1666 }
1667
zhanyong.wan18490652009-05-11 18:54:08 +00001668 // The first argument of ExplainMatchResultTo() is needed to help
1669 // Symbian's C++ compiler choose which overload to use. Its type is
1670 // true_type iff the Property() matcher is used to match a pointer.
1671 void ExplainMatchResultTo(false_type /* is_not_pointer */, const Class& obj,
1672 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001673 ::std::stringstream ss;
1674 matcher_.ExplainMatchResultTo((obj.*property_)(), &ss);
1675 const internal::string s = ss.str();
1676 if (s != "") {
1677 *os << "the given property " << s;
1678 }
1679 }
1680
zhanyong.wan18490652009-05-11 18:54:08 +00001681 void ExplainMatchResultTo(true_type /* is_pointer */, const Class* p,
1682 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001683 if (p != NULL) {
zhanyong.wan18490652009-05-11 18:54:08 +00001684 // Since *p has a property method, it must be a
1685 // class/struct/union type and thus cannot be a pointer.
1686 // Therefore we pass false_type() as the first argument.
1687 ExplainMatchResultTo(false_type(), *p, os);
shiqiane35fdd92008-12-10 05:08:54 +00001688 }
1689 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001690
shiqiane35fdd92008-12-10 05:08:54 +00001691 private:
1692 PropertyType (Class::*property_)() const;
1693 const Matcher<RefToConstProperty> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001694
1695 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001696};
1697
zhanyong.wan18490652009-05-11 18:54:08 +00001698// Explains the result of matching an object or pointer against a
1699// property matcher.
1700template <typename Class, typename PropertyType, typename T>
shiqiane35fdd92008-12-10 05:08:54 +00001701void ExplainMatchResultTo(const PropertyMatcher<Class, PropertyType>& matcher,
zhanyong.wan18490652009-05-11 18:54:08 +00001702 const T& value, ::std::ostream* os) {
1703 matcher.ExplainMatchResultTo(
1704 typename ::testing::internal::is_pointer<T>::type(), value, os);
shiqiane35fdd92008-12-10 05:08:54 +00001705}
1706
1707// Type traits specifying various features of different functors for ResultOf.
1708// The default template specifies features for functor objects.
1709// Functor classes have to typedef argument_type and result_type
1710// to be compatible with ResultOf.
1711template <typename Functor>
1712struct CallableTraits {
1713 typedef typename Functor::result_type ResultType;
1714 typedef Functor StorageType;
1715
zhanyong.wan32de5f52009-12-23 00:13:23 +00001716 static void CheckIsValid(Functor /* functor */) {}
shiqiane35fdd92008-12-10 05:08:54 +00001717 template <typename T>
1718 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1719};
1720
1721// Specialization for function pointers.
1722template <typename ArgType, typename ResType>
1723struct CallableTraits<ResType(*)(ArgType)> {
1724 typedef ResType ResultType;
1725 typedef ResType(*StorageType)(ArgType);
1726
1727 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001728 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00001729 << "NULL function pointer is passed into ResultOf().";
1730 }
1731 template <typename T>
1732 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1733 return (*f)(arg);
1734 }
1735};
1736
1737// Implements the ResultOf() matcher for matching a return value of a
1738// unary function of an object.
1739template <typename Callable>
1740class ResultOfMatcher {
1741 public:
1742 typedef typename CallableTraits<Callable>::ResultType ResultType;
1743
1744 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1745 : callable_(callable), matcher_(matcher) {
1746 CallableTraits<Callable>::CheckIsValid(callable_);
1747 }
1748
1749 template <typename T>
1750 operator Matcher<T>() const {
1751 return Matcher<T>(new Impl<T>(callable_, matcher_));
1752 }
1753
1754 private:
1755 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1756
1757 template <typename T>
1758 class Impl : public MatcherInterface<T> {
1759 public:
1760 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1761 : callable_(callable), matcher_(matcher) {}
1762 // Returns true iff callable_(obj) matches the inner matcher.
1763 // The calling syntax is different for different types of callables
1764 // so we abstract it in CallableTraits<Callable>::Invoke().
1765 virtual bool Matches(T obj) const {
1766 return matcher_.Matches(
1767 CallableTraits<Callable>::template Invoke<T>(callable_, obj));
1768 }
1769
1770 virtual void DescribeTo(::std::ostream* os) const {
1771 *os << "result of the given callable ";
1772 matcher_.DescribeTo(os);
1773 }
1774
1775 virtual void DescribeNegationTo(::std::ostream* os) const {
1776 *os << "result of the given callable ";
1777 matcher_.DescribeNegationTo(os);
1778 }
1779
1780 virtual void ExplainMatchResultTo(T obj, ::std::ostream* os) const {
1781 ::std::stringstream ss;
1782 matcher_.ExplainMatchResultTo(
1783 CallableTraits<Callable>::template Invoke<T>(callable_, obj),
1784 &ss);
1785 const internal::string s = ss.str();
1786 if (s != "")
1787 *os << "result of the given callable " << s;
1788 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001789
shiqiane35fdd92008-12-10 05:08:54 +00001790 private:
1791 // Functors often define operator() as non-const method even though
1792 // they are actualy stateless. But we need to use them even when
1793 // 'this' is a const pointer. It's the user's responsibility not to
1794 // use stateful callables with ResultOf(), which does't guarantee
1795 // how many times the callable will be invoked.
1796 mutable CallableStorageType callable_;
1797 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001798
1799 GTEST_DISALLOW_ASSIGN_(Impl);
shiqiane35fdd92008-12-10 05:08:54 +00001800 }; // class Impl
1801
1802 const CallableStorageType callable_;
1803 const Matcher<ResultType> matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001804
1805 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
shiqiane35fdd92008-12-10 05:08:54 +00001806};
1807
1808// Explains the result of matching a value against a functor matcher.
1809template <typename T, typename Callable>
1810void ExplainMatchResultTo(const ResultOfMatcher<Callable>& matcher,
1811 T obj, ::std::ostream* os) {
1812 matcher.ExplainMatchResultTo(obj, os);
1813}
1814
zhanyong.wan6a896b52009-01-16 01:13:50 +00001815// Implements an equality matcher for any STL-style container whose elements
1816// support ==. This matcher is like Eq(), but its failure explanations provide
1817// more detailed information that is useful when the container is used as a set.
1818// The failure message reports elements that are in one of the operands but not
1819// the other. The failure messages do not report duplicate or out-of-order
1820// elements in the containers (which don't properly matter to sets, but can
1821// occur if the containers are vectors or lists, for example).
1822//
1823// Uses the container's const_iterator, value_type, operator ==,
1824// begin(), and end().
1825template <typename Container>
1826class ContainerEqMatcher {
1827 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00001828 typedef internal::StlContainerView<Container> View;
1829 typedef typename View::type StlContainer;
1830 typedef typename View::const_reference StlContainerReference;
1831
1832 // We make a copy of rhs in case the elements in it are modified
1833 // after this matcher is created.
1834 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
1835 // Makes sure the user doesn't instantiate this class template
1836 // with a const or reference type.
1837 testing::StaticAssertTypeEq<Container,
1838 GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))>();
1839 }
1840
1841 template <typename LhsContainer>
1842 bool Matches(const LhsContainer& lhs) const {
1843 // GMOCK_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
1844 // that causes LhsContainer to be a const type sometimes.
1845 typedef internal::StlContainerView<GMOCK_REMOVE_CONST_(LhsContainer)>
1846 LhsView;
1847 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
1848 return lhs_stl_container == rhs_;
1849 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00001850 void DescribeTo(::std::ostream* os) const {
1851 *os << "equals ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001852 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001853 }
1854 void DescribeNegationTo(::std::ostream* os) const {
1855 *os << "does not equal ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001856 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001857 }
1858
zhanyong.wanb8243162009-06-04 05:48:20 +00001859 template <typename LhsContainer>
1860 void ExplainMatchResultTo(const LhsContainer& lhs,
zhanyong.wan6a896b52009-01-16 01:13:50 +00001861 ::std::ostream* os) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00001862 // GMOCK_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
1863 // that causes LhsContainer to be a const type sometimes.
1864 typedef internal::StlContainerView<GMOCK_REMOVE_CONST_(LhsContainer)>
1865 LhsView;
1866 typedef typename LhsView::type LhsStlContainer;
1867 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
1868
zhanyong.wan6a896b52009-01-16 01:13:50 +00001869 // Something is different. Check for missing values first.
1870 bool printed_header = false;
zhanyong.wanb8243162009-06-04 05:48:20 +00001871 for (typename LhsStlContainer::const_iterator it =
1872 lhs_stl_container.begin();
1873 it != lhs_stl_container.end(); ++it) {
1874 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
1875 rhs_.end()) {
zhanyong.wan6a896b52009-01-16 01:13:50 +00001876 if (printed_header) {
1877 *os << ", ";
1878 } else {
1879 *os << "Only in actual: ";
1880 printed_header = true;
1881 }
zhanyong.wanb8243162009-06-04 05:48:20 +00001882 UniversalPrinter<typename LhsStlContainer::value_type>::Print(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001883 }
1884 }
1885
1886 // Now check for extra values.
1887 bool printed_header2 = false;
zhanyong.wanb8243162009-06-04 05:48:20 +00001888 for (typename StlContainer::const_iterator it = rhs_.begin();
zhanyong.wan6a896b52009-01-16 01:13:50 +00001889 it != rhs_.end(); ++it) {
zhanyong.wanb8243162009-06-04 05:48:20 +00001890 if (internal::ArrayAwareFind(
1891 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
1892 lhs_stl_container.end()) {
zhanyong.wan6a896b52009-01-16 01:13:50 +00001893 if (printed_header2) {
1894 *os << ", ";
1895 } else {
1896 *os << (printed_header ? "; not" : "Not") << " in actual: ";
1897 printed_header2 = true;
1898 }
zhanyong.wanb8243162009-06-04 05:48:20 +00001899 UniversalPrinter<typename StlContainer::value_type>::Print(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001900 }
1901 }
1902 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001903
zhanyong.wan6a896b52009-01-16 01:13:50 +00001904 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00001905 const StlContainer rhs_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001906
1907 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001908};
1909
zhanyong.wanb8243162009-06-04 05:48:20 +00001910template <typename LhsContainer, typename Container>
zhanyong.wan6a896b52009-01-16 01:13:50 +00001911void ExplainMatchResultTo(const ContainerEqMatcher<Container>& matcher,
zhanyong.wanb8243162009-06-04 05:48:20 +00001912 const LhsContainer& lhs,
zhanyong.wan6a896b52009-01-16 01:13:50 +00001913 ::std::ostream* os) {
1914 matcher.ExplainMatchResultTo(lhs, os);
1915}
1916
zhanyong.wanb8243162009-06-04 05:48:20 +00001917// Implements Contains(element_matcher) for the given argument type Container.
1918template <typename Container>
1919class ContainsMatcherImpl : public MatcherInterface<Container> {
1920 public:
1921 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
1922 typedef StlContainerView<RawContainer> View;
1923 typedef typename View::type StlContainer;
1924 typedef typename View::const_reference StlContainerReference;
1925 typedef typename StlContainer::value_type Element;
1926
1927 template <typename InnerMatcher>
1928 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
1929 : inner_matcher_(
1930 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
1931
1932 // Returns true iff 'container' matches.
1933 virtual bool Matches(Container container) const {
1934 StlContainerReference stl_container = View::ConstReference(container);
1935 for (typename StlContainer::const_iterator it = stl_container.begin();
1936 it != stl_container.end(); ++it) {
1937 if (inner_matcher_.Matches(*it))
1938 return true;
1939 }
1940 return false;
1941 }
1942
1943 // Describes what this matcher does.
1944 virtual void DescribeTo(::std::ostream* os) const {
1945 *os << "contains at least one element that ";
1946 inner_matcher_.DescribeTo(os);
1947 }
1948
1949 // Describes what the negation of this matcher does.
1950 virtual void DescribeNegationTo(::std::ostream* os) const {
1951 *os << "doesn't contain any element that ";
1952 inner_matcher_.DescribeTo(os);
1953 }
1954
1955 // Explains why 'container' matches, or doesn't match, this matcher.
1956 virtual void ExplainMatchResultTo(Container container,
1957 ::std::ostream* os) const {
1958 StlContainerReference stl_container = View::ConstReference(container);
1959
1960 // We need to explain which (if any) element matches inner_matcher_.
1961 typename StlContainer::const_iterator it = stl_container.begin();
1962 for (size_t i = 0; it != stl_container.end(); ++it, ++i) {
1963 if (inner_matcher_.Matches(*it)) {
1964 *os << "element " << i << " matches";
1965 return;
1966 }
1967 }
1968 }
1969
1970 private:
1971 const Matcher<const Element&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001972
1973 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
zhanyong.wanb8243162009-06-04 05:48:20 +00001974};
1975
1976// Implements polymorphic Contains(element_matcher).
1977template <typename M>
1978class ContainsMatcher {
1979 public:
1980 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
1981
1982 template <typename Container>
1983 operator Matcher<Container>() const {
1984 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
1985 }
1986
1987 private:
1988 const M inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001989
1990 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
zhanyong.wanb8243162009-06-04 05:48:20 +00001991};
1992
zhanyong.wanb5937da2009-07-16 20:26:41 +00001993// Implements Key(inner_matcher) for the given argument pair type.
1994// Key(inner_matcher) matches an std::pair whose 'first' field matches
1995// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
1996// std::map that contains at least one element whose key is >= 5.
1997template <typename PairType>
1998class KeyMatcherImpl : public MatcherInterface<PairType> {
1999 public:
2000 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
2001 typedef typename RawPairType::first_type KeyType;
2002
2003 template <typename InnerMatcher>
2004 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2005 : inner_matcher_(
2006 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2007 }
2008
2009 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
2010 virtual bool Matches(PairType key_value) const {
2011 return inner_matcher_.Matches(key_value.first);
2012 }
2013
2014 // Describes what this matcher does.
2015 virtual void DescribeTo(::std::ostream* os) const {
2016 *os << "has a key that ";
2017 inner_matcher_.DescribeTo(os);
2018 }
2019
2020 // Describes what the negation of this matcher does.
2021 virtual void DescribeNegationTo(::std::ostream* os) const {
2022 *os << "doesn't have a key that ";
2023 inner_matcher_.DescribeTo(os);
2024 }
2025
2026 // Explains why 'key_value' matches, or doesn't match, this matcher.
2027 virtual void ExplainMatchResultTo(PairType key_value,
2028 ::std::ostream* os) const {
2029 inner_matcher_.ExplainMatchResultTo(key_value.first, os);
2030 }
2031
2032 private:
2033 const Matcher<const KeyType&> inner_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002034
2035 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002036};
2037
2038// Implements polymorphic Key(matcher_for_key).
2039template <typename M>
2040class KeyMatcher {
2041 public:
2042 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2043
2044 template <typename PairType>
2045 operator Matcher<PairType>() const {
2046 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2047 }
2048
2049 private:
2050 const M matcher_for_key_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002051
2052 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
zhanyong.wanb5937da2009-07-16 20:26:41 +00002053};
2054
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002055// Implements Pair(first_matcher, second_matcher) for the given argument pair
2056// type with its two matchers. See Pair() function below.
2057template <typename PairType>
2058class PairMatcherImpl : public MatcherInterface<PairType> {
2059 public:
2060 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
2061 typedef typename RawPairType::first_type FirstType;
2062 typedef typename RawPairType::second_type SecondType;
2063
2064 template <typename FirstMatcher, typename SecondMatcher>
2065 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
2066 : first_matcher_(
2067 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
2068 second_matcher_(
2069 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
2070 }
2071
2072 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
2073 // matches second_matcher.
2074 virtual bool Matches(PairType a_pair) const {
2075 return first_matcher_.Matches(a_pair.first) &&
2076 second_matcher_.Matches(a_pair.second);
2077 }
2078
2079 // Describes what this matcher does.
2080 virtual void DescribeTo(::std::ostream* os) const {
2081 *os << "has a first field that ";
2082 first_matcher_.DescribeTo(os);
2083 *os << ", and has a second field that ";
2084 second_matcher_.DescribeTo(os);
2085 }
2086
2087 // Describes what the negation of this matcher does.
2088 virtual void DescribeNegationTo(::std::ostream* os) const {
2089 *os << "has a first field that ";
2090 first_matcher_.DescribeNegationTo(os);
2091 *os << ", or has a second field that ";
2092 second_matcher_.DescribeNegationTo(os);
2093 }
2094
2095 // Explains why 'a_pair' matches, or doesn't match, this matcher.
2096 virtual void ExplainMatchResultTo(PairType a_pair,
2097 ::std::ostream* os) const {
2098 ::std::stringstream ss1;
2099 first_matcher_.ExplainMatchResultTo(a_pair.first, &ss1);
2100 internal::string s1 = ss1.str();
2101 if (s1 != "") {
2102 s1 = "the first field " + s1;
2103 }
2104
2105 ::std::stringstream ss2;
2106 second_matcher_.ExplainMatchResultTo(a_pair.second, &ss2);
2107 internal::string s2 = ss2.str();
2108 if (s2 != "") {
2109 s2 = "the second field " + s2;
2110 }
2111
2112 *os << s1;
2113 if (s1 != "" && s2 != "") {
2114 *os << ", and ";
2115 }
2116 *os << s2;
2117 }
2118
2119 private:
2120 const Matcher<const FirstType&> first_matcher_;
2121 const Matcher<const SecondType&> second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002122
2123 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002124};
2125
2126// Implements polymorphic Pair(first_matcher, second_matcher).
2127template <typename FirstMatcher, typename SecondMatcher>
2128class PairMatcher {
2129 public:
2130 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2131 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2132
2133 template <typename PairType>
2134 operator Matcher<PairType> () const {
2135 return MakeMatcher(
2136 new PairMatcherImpl<PairType>(
2137 first_matcher_, second_matcher_));
2138 }
2139
2140 private:
2141 const FirstMatcher first_matcher_;
2142 const SecondMatcher second_matcher_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002143
2144 GTEST_DISALLOW_ASSIGN_(PairMatcher);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002145};
2146
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002147// Implements ElementsAre() and ElementsAreArray().
2148template <typename Container>
2149class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2150 public:
2151 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
2152 typedef internal::StlContainerView<RawContainer> View;
2153 typedef typename View::type StlContainer;
2154 typedef typename View::const_reference StlContainerReference;
2155 typedef typename StlContainer::value_type Element;
2156
2157 // Constructs the matcher from a sequence of element values or
2158 // element matchers.
2159 template <typename InputIter>
zhanyong.wan32de5f52009-12-23 00:13:23 +00002160 ElementsAreMatcherImpl(InputIter first, size_t a_count) {
2161 matchers_.reserve(a_count);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002162 InputIter it = first;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002163 for (size_t i = 0; i != a_count; ++i, ++it) {
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002164 matchers_.push_back(MatcherCast<const Element&>(*it));
2165 }
2166 }
2167
2168 // Returns true iff 'container' matches.
2169 virtual bool Matches(Container container) const {
2170 StlContainerReference stl_container = View::ConstReference(container);
2171 if (stl_container.size() != count())
2172 return false;
2173
2174 typename StlContainer::const_iterator it = stl_container.begin();
2175 for (size_t i = 0; i != count(); ++it, ++i) {
2176 if (!matchers_[i].Matches(*it))
2177 return false;
2178 }
2179
2180 return true;
2181 }
2182
2183 // Describes what this matcher does.
2184 virtual void DescribeTo(::std::ostream* os) const {
2185 if (count() == 0) {
2186 *os << "is empty";
2187 } else if (count() == 1) {
2188 *os << "has 1 element that ";
2189 matchers_[0].DescribeTo(os);
2190 } else {
2191 *os << "has " << Elements(count()) << " where\n";
2192 for (size_t i = 0; i != count(); ++i) {
2193 *os << "element " << i << " ";
2194 matchers_[i].DescribeTo(os);
2195 if (i + 1 < count()) {
2196 *os << ",\n";
2197 }
2198 }
2199 }
2200 }
2201
2202 // Describes what the negation of this matcher does.
2203 virtual void DescribeNegationTo(::std::ostream* os) const {
2204 if (count() == 0) {
2205 *os << "is not empty";
2206 return;
2207 }
2208
2209 *os << "does not have " << Elements(count()) << ", or\n";
2210 for (size_t i = 0; i != count(); ++i) {
2211 *os << "element " << i << " ";
2212 matchers_[i].DescribeNegationTo(os);
2213 if (i + 1 < count()) {
2214 *os << ", or\n";
2215 }
2216 }
2217 }
2218
2219 // Explains why 'container' matches, or doesn't match, this matcher.
2220 virtual void ExplainMatchResultTo(Container container,
2221 ::std::ostream* os) const {
2222 StlContainerReference stl_container = View::ConstReference(container);
2223 if (Matches(container)) {
2224 // We need to explain why *each* element matches (the obvious
2225 // ones can be skipped).
2226
2227 bool reason_printed = false;
2228 typename StlContainer::const_iterator it = stl_container.begin();
2229 for (size_t i = 0; i != count(); ++it, ++i) {
2230 ::std::stringstream ss;
2231 matchers_[i].ExplainMatchResultTo(*it, &ss);
2232
2233 const string s = ss.str();
2234 if (!s.empty()) {
2235 if (reason_printed) {
2236 *os << ",\n";
2237 }
2238 *os << "element " << i << " " << s;
2239 reason_printed = true;
2240 }
2241 }
2242 } else {
2243 // We need to explain why the container doesn't match.
2244 const size_t actual_count = stl_container.size();
2245 if (actual_count != count()) {
2246 // The element count doesn't match. If the container is
2247 // empty, there's no need to explain anything as Google Mock
2248 // already prints the empty container. Otherwise we just need
2249 // to show how many elements there actually are.
2250 if (actual_count != 0) {
2251 *os << "has " << Elements(actual_count);
2252 }
2253 return;
2254 }
2255
2256 // The container has the right size but at least one element
2257 // doesn't match expectation. We need to find this element and
2258 // explain why it doesn't match.
2259 typename StlContainer::const_iterator it = stl_container.begin();
2260 for (size_t i = 0; i != count(); ++it, ++i) {
2261 if (matchers_[i].Matches(*it)) {
2262 continue;
2263 }
2264
2265 *os << "element " << i << " doesn't match";
2266
2267 ::std::stringstream ss;
2268 matchers_[i].ExplainMatchResultTo(*it, &ss);
2269 const string s = ss.str();
2270 if (!s.empty()) {
2271 *os << " (" << s << ")";
2272 }
2273 return;
2274 }
2275 }
2276 }
2277
2278 private:
2279 static Message Elements(size_t count) {
2280 return Message() << count << (count == 1 ? " element" : " elements");
2281 }
2282
2283 size_t count() const { return matchers_.size(); }
2284 std::vector<Matcher<const Element&> > matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002285
2286 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002287};
2288
2289// Implements ElementsAre() of 0 arguments.
2290class ElementsAreMatcher0 {
2291 public:
2292 ElementsAreMatcher0() {}
2293
2294 template <typename Container>
2295 operator Matcher<Container>() const {
2296 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2297 RawContainer;
2298 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2299 Element;
2300
2301 const Matcher<const Element&>* const matchers = NULL;
2302 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 0));
2303 }
2304};
2305
2306// Implements ElementsAreArray().
2307template <typename T>
2308class ElementsAreArrayMatcher {
2309 public:
2310 ElementsAreArrayMatcher(const T* first, size_t count) :
2311 first_(first), count_(count) {}
2312
2313 template <typename Container>
2314 operator Matcher<Container>() const {
2315 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2316 RawContainer;
2317 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2318 Element;
2319
2320 return MakeMatcher(new ElementsAreMatcherImpl<Container>(first_, count_));
2321 }
2322
2323 private:
2324 const T* const first_;
2325 const size_t count_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00002326
2327 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002328};
2329
2330// Constants denoting interpolations in a matcher description string.
2331const int kTupleInterpolation = -1; // "%(*)s"
2332const int kPercentInterpolation = -2; // "%%"
2333const int kInvalidInterpolation = -3; // "%" followed by invalid text
2334
2335// Records the location and content of an interpolation.
2336struct Interpolation {
2337 Interpolation(const char* start, const char* end, int param)
2338 : start_pos(start), end_pos(end), param_index(param) {}
2339
2340 // Points to the start of the interpolation (the '%' character).
2341 const char* start_pos;
2342 // Points to the first character after the interpolation.
2343 const char* end_pos;
2344 // 0-based index of the interpolated matcher parameter;
2345 // kTupleInterpolation for "%(*)s"; kPercentInterpolation for "%%".
2346 int param_index;
2347};
2348
2349typedef ::std::vector<Interpolation> Interpolations;
2350
2351// Parses a matcher description string and returns a vector of
2352// interpolations that appear in the string; generates non-fatal
2353// failures iff 'description' is an invalid matcher description.
2354// 'param_names' is a NULL-terminated array of parameter names in the
2355// order they appear in the MATCHER_P*() parameter list.
2356Interpolations ValidateMatcherDescription(
2357 const char* param_names[], const char* description);
2358
2359// Returns the actual matcher description, given the matcher name,
2360// user-supplied description template string, interpolations in the
2361// string, and the printed values of the matcher parameters.
2362string FormatMatcherDescription(
2363 const char* matcher_name, const char* description,
2364 const Interpolations& interp, const Strings& param_values);
2365
shiqiane35fdd92008-12-10 05:08:54 +00002366} // namespace internal
2367
2368// Implements MatcherCast().
2369template <typename T, typename M>
2370inline Matcher<T> MatcherCast(M matcher) {
2371 return internal::MatcherCastImpl<T, M>::Cast(matcher);
2372}
2373
2374// _ is a matcher that matches anything of any type.
2375//
2376// This definition is fine as:
2377//
2378// 1. The C++ standard permits using the name _ in a namespace that
2379// is not the global namespace or ::std.
2380// 2. The AnythingMatcher class has no data member or constructor,
2381// so it's OK to create global variables of this type.
2382// 3. c-style has approved of using _ in this case.
2383const internal::AnythingMatcher _ = {};
2384// Creates a matcher that matches any value of the given type T.
2385template <typename T>
2386inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2387
2388// Creates a matcher that matches any value of the given type T.
2389template <typename T>
2390inline Matcher<T> An() { return A<T>(); }
2391
2392// Creates a polymorphic matcher that matches anything equal to x.
2393// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2394// wouldn't compile.
2395template <typename T>
2396inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2397
2398// Constructs a Matcher<T> from a 'value' of type T. The constructed
2399// matcher matches any value that's equal to 'value'.
2400template <typename T>
2401Matcher<T>::Matcher(T value) { *this = Eq(value); }
2402
2403// Creates a monomorphic matcher that matches anything with type Lhs
2404// and equal to rhs. A user may need to use this instead of Eq(...)
2405// in order to resolve an overloading ambiguity.
2406//
2407// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2408// or Matcher<T>(x), but more readable than the latter.
2409//
2410// We could define similar monomorphic matchers for other comparison
2411// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2412// it yet as those are used much less than Eq() in practice. A user
2413// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2414// for example.
2415template <typename Lhs, typename Rhs>
2416inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2417
2418// Creates a polymorphic matcher that matches anything >= x.
2419template <typename Rhs>
2420inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2421 return internal::GeMatcher<Rhs>(x);
2422}
2423
2424// Creates a polymorphic matcher that matches anything > x.
2425template <typename Rhs>
2426inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2427 return internal::GtMatcher<Rhs>(x);
2428}
2429
2430// Creates a polymorphic matcher that matches anything <= x.
2431template <typename Rhs>
2432inline internal::LeMatcher<Rhs> Le(Rhs x) {
2433 return internal::LeMatcher<Rhs>(x);
2434}
2435
2436// Creates a polymorphic matcher that matches anything < x.
2437template <typename Rhs>
2438inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2439 return internal::LtMatcher<Rhs>(x);
2440}
2441
2442// Creates a polymorphic matcher that matches anything != x.
2443template <typename Rhs>
2444inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2445 return internal::NeMatcher<Rhs>(x);
2446}
2447
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002448// Creates a polymorphic matcher that matches any NULL pointer.
2449inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2450 return MakePolymorphicMatcher(internal::IsNullMatcher());
2451}
2452
shiqiane35fdd92008-12-10 05:08:54 +00002453// Creates a polymorphic matcher that matches any non-NULL pointer.
2454// This is convenient as Not(NULL) doesn't compile (the compiler
2455// thinks that that expression is comparing a pointer with an integer).
2456inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2457 return MakePolymorphicMatcher(internal::NotNullMatcher());
2458}
2459
2460// Creates a polymorphic matcher that matches any argument that
2461// references variable x.
2462template <typename T>
2463inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2464 return internal::RefMatcher<T&>(x);
2465}
2466
2467// Creates a matcher that matches any double argument approximately
2468// equal to rhs, where two NANs are considered unequal.
2469inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2470 return internal::FloatingEqMatcher<double>(rhs, false);
2471}
2472
2473// Creates a matcher that matches any double argument approximately
2474// equal to rhs, including NaN values when rhs is NaN.
2475inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2476 return internal::FloatingEqMatcher<double>(rhs, true);
2477}
2478
2479// Creates a matcher that matches any float argument approximately
2480// equal to rhs, where two NANs are considered unequal.
2481inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2482 return internal::FloatingEqMatcher<float>(rhs, false);
2483}
2484
2485// Creates a matcher that matches any double argument approximately
2486// equal to rhs, including NaN values when rhs is NaN.
2487inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2488 return internal::FloatingEqMatcher<float>(rhs, true);
2489}
2490
2491// Creates a matcher that matches a pointer (raw or smart) that points
2492// to a value that matches inner_matcher.
2493template <typename InnerMatcher>
2494inline internal::PointeeMatcher<InnerMatcher> Pointee(
2495 const InnerMatcher& inner_matcher) {
2496 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2497}
2498
2499// Creates a matcher that matches an object whose given field matches
2500// 'matcher'. For example,
2501// Field(&Foo::number, Ge(5))
2502// matches a Foo object x iff x.number >= 5.
2503template <typename Class, typename FieldType, typename FieldMatcher>
2504inline PolymorphicMatcher<
2505 internal::FieldMatcher<Class, FieldType> > Field(
2506 FieldType Class::*field, const FieldMatcher& matcher) {
2507 return MakePolymorphicMatcher(
2508 internal::FieldMatcher<Class, FieldType>(
2509 field, MatcherCast<const FieldType&>(matcher)));
2510 // The call to MatcherCast() is required for supporting inner
2511 // matchers of compatible types. For example, it allows
2512 // Field(&Foo::bar, m)
2513 // to compile where bar is an int32 and m is a matcher for int64.
2514}
2515
2516// Creates a matcher that matches an object whose given property
2517// matches 'matcher'. For example,
2518// Property(&Foo::str, StartsWith("hi"))
2519// matches a Foo object x iff x.str() starts with "hi".
2520template <typename Class, typename PropertyType, typename PropertyMatcher>
2521inline PolymorphicMatcher<
2522 internal::PropertyMatcher<Class, PropertyType> > Property(
2523 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2524 return MakePolymorphicMatcher(
2525 internal::PropertyMatcher<Class, PropertyType>(
2526 property,
zhanyong.wane0d051e2009-02-19 00:33:37 +00002527 MatcherCast<GMOCK_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002528 // The call to MatcherCast() is required for supporting inner
2529 // matchers of compatible types. For example, it allows
2530 // Property(&Foo::bar, m)
2531 // to compile where bar() returns an int32 and m is a matcher for int64.
2532}
2533
2534// Creates a matcher that matches an object iff the result of applying
2535// a callable to x matches 'matcher'.
2536// For example,
2537// ResultOf(f, StartsWith("hi"))
2538// matches a Foo object x iff f(x) starts with "hi".
2539// callable parameter can be a function, function pointer, or a functor.
2540// Callable has to satisfy the following conditions:
2541// * It is required to keep no state affecting the results of
2542// the calls on it and make no assumptions about how many calls
2543// will be made. Any state it keeps must be protected from the
2544// concurrent access.
2545// * If it is a function object, it has to define type result_type.
2546// We recommend deriving your functor classes from std::unary_function.
2547template <typename Callable, typename ResultOfMatcher>
2548internal::ResultOfMatcher<Callable> ResultOf(
2549 Callable callable, const ResultOfMatcher& matcher) {
2550 return internal::ResultOfMatcher<Callable>(
2551 callable,
2552 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2553 matcher));
2554 // The call to MatcherCast() is required for supporting inner
2555 // matchers of compatible types. For example, it allows
2556 // ResultOf(Function, m)
2557 // to compile where Function() returns an int32 and m is a matcher for int64.
2558}
2559
2560// String matchers.
2561
2562// Matches a string equal to str.
2563inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2564 StrEq(const internal::string& str) {
2565 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2566 str, true, true));
2567}
2568
2569// Matches a string not equal to str.
2570inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2571 StrNe(const internal::string& str) {
2572 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2573 str, false, true));
2574}
2575
2576// Matches a string equal to str, ignoring case.
2577inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2578 StrCaseEq(const internal::string& str) {
2579 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2580 str, true, false));
2581}
2582
2583// Matches a string not equal to str, ignoring case.
2584inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2585 StrCaseNe(const internal::string& str) {
2586 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2587 str, false, false));
2588}
2589
2590// Creates a matcher that matches any string, std::string, or C string
2591// that contains the given substring.
2592inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2593 HasSubstr(const internal::string& substring) {
2594 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
2595 substring));
2596}
2597
2598// Matches a string that starts with 'prefix' (case-sensitive).
2599inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
2600 StartsWith(const internal::string& prefix) {
2601 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
2602 prefix));
2603}
2604
2605// Matches a string that ends with 'suffix' (case-sensitive).
2606inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
2607 EndsWith(const internal::string& suffix) {
2608 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
2609 suffix));
2610}
2611
2612#ifdef GMOCK_HAS_REGEX
2613
2614// Matches a string that fully matches regular expression 'regex'.
2615// The matcher takes ownership of 'regex'.
2616inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2617 const internal::RE* regex) {
2618 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2619}
2620inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2621 const internal::string& regex) {
2622 return MatchesRegex(new internal::RE(regex));
2623}
2624
2625// Matches a string that contains regular expression 'regex'.
2626// The matcher takes ownership of 'regex'.
2627inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2628 const internal::RE* regex) {
2629 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2630}
2631inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2632 const internal::string& regex) {
2633 return ContainsRegex(new internal::RE(regex));
2634}
2635
2636#endif // GMOCK_HAS_REGEX
2637
2638#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2639// Wide string matchers.
2640
2641// Matches a string equal to str.
2642inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2643 StrEq(const internal::wstring& str) {
2644 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2645 str, true, true));
2646}
2647
2648// Matches a string not equal to str.
2649inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2650 StrNe(const internal::wstring& str) {
2651 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2652 str, false, true));
2653}
2654
2655// Matches a string equal to str, ignoring case.
2656inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2657 StrCaseEq(const internal::wstring& str) {
2658 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2659 str, true, false));
2660}
2661
2662// Matches a string not equal to str, ignoring case.
2663inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2664 StrCaseNe(const internal::wstring& str) {
2665 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2666 str, false, false));
2667}
2668
2669// Creates a matcher that matches any wstring, std::wstring, or C wide string
2670// that contains the given substring.
2671inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2672 HasSubstr(const internal::wstring& substring) {
2673 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2674 substring));
2675}
2676
2677// Matches a string that starts with 'prefix' (case-sensitive).
2678inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2679 StartsWith(const internal::wstring& prefix) {
2680 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2681 prefix));
2682}
2683
2684// Matches a string that ends with 'suffix' (case-sensitive).
2685inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2686 EndsWith(const internal::wstring& suffix) {
2687 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2688 suffix));
2689}
2690
2691#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2692
2693// Creates a polymorphic matcher that matches a 2-tuple where the
2694// first field == the second field.
2695inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2696
2697// Creates a polymorphic matcher that matches a 2-tuple where the
2698// first field >= the second field.
2699inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2700
2701// Creates a polymorphic matcher that matches a 2-tuple where the
2702// first field > the second field.
2703inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2704
2705// Creates a polymorphic matcher that matches a 2-tuple where the
2706// first field <= the second field.
2707inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2708
2709// Creates a polymorphic matcher that matches a 2-tuple where the
2710// first field < the second field.
2711inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2712
2713// Creates a polymorphic matcher that matches a 2-tuple where the
2714// first field != the second field.
2715inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2716
2717// Creates a matcher that matches any value of type T that m doesn't
2718// match.
2719template <typename InnerMatcher>
2720inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2721 return internal::NotMatcher<InnerMatcher>(m);
2722}
2723
2724// Creates a matcher that matches any value that matches all of the
2725// given matchers.
2726//
2727// For now we only support up to 5 matchers. Support for more
2728// matchers can be added as needed, or the user can use nested
2729// AllOf()s.
2730template <typename Matcher1, typename Matcher2>
2731inline internal::BothOfMatcher<Matcher1, Matcher2>
2732AllOf(Matcher1 m1, Matcher2 m2) {
2733 return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2);
2734}
2735
2736template <typename Matcher1, typename Matcher2, typename Matcher3>
2737inline internal::BothOfMatcher<Matcher1,
2738 internal::BothOfMatcher<Matcher2, Matcher3> >
2739AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2740 return AllOf(m1, AllOf(m2, m3));
2741}
2742
2743template <typename Matcher1, typename Matcher2, typename Matcher3,
2744 typename Matcher4>
2745inline internal::BothOfMatcher<Matcher1,
2746 internal::BothOfMatcher<Matcher2,
2747 internal::BothOfMatcher<Matcher3, Matcher4> > >
2748AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2749 return AllOf(m1, AllOf(m2, m3, m4));
2750}
2751
2752template <typename Matcher1, typename Matcher2, typename Matcher3,
2753 typename Matcher4, typename Matcher5>
2754inline internal::BothOfMatcher<Matcher1,
2755 internal::BothOfMatcher<Matcher2,
2756 internal::BothOfMatcher<Matcher3,
2757 internal::BothOfMatcher<Matcher4, Matcher5> > > >
2758AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2759 return AllOf(m1, AllOf(m2, m3, m4, m5));
2760}
2761
2762// Creates a matcher that matches any value that matches at least one
2763// of the given matchers.
2764//
2765// For now we only support up to 5 matchers. Support for more
2766// matchers can be added as needed, or the user can use nested
2767// AnyOf()s.
2768template <typename Matcher1, typename Matcher2>
2769inline internal::EitherOfMatcher<Matcher1, Matcher2>
2770AnyOf(Matcher1 m1, Matcher2 m2) {
2771 return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2);
2772}
2773
2774template <typename Matcher1, typename Matcher2, typename Matcher3>
2775inline internal::EitherOfMatcher<Matcher1,
2776 internal::EitherOfMatcher<Matcher2, Matcher3> >
2777AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2778 return AnyOf(m1, AnyOf(m2, m3));
2779}
2780
2781template <typename Matcher1, typename Matcher2, typename Matcher3,
2782 typename Matcher4>
2783inline internal::EitherOfMatcher<Matcher1,
2784 internal::EitherOfMatcher<Matcher2,
2785 internal::EitherOfMatcher<Matcher3, Matcher4> > >
2786AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2787 return AnyOf(m1, AnyOf(m2, m3, m4));
2788}
2789
2790template <typename Matcher1, typename Matcher2, typename Matcher3,
2791 typename Matcher4, typename Matcher5>
2792inline internal::EitherOfMatcher<Matcher1,
2793 internal::EitherOfMatcher<Matcher2,
2794 internal::EitherOfMatcher<Matcher3,
2795 internal::EitherOfMatcher<Matcher4, Matcher5> > > >
2796AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2797 return AnyOf(m1, AnyOf(m2, m3, m4, m5));
2798}
2799
2800// Returns a matcher that matches anything that satisfies the given
2801// predicate. The predicate can be any unary function or functor
2802// whose return type can be implicitly converted to bool.
2803template <typename Predicate>
2804inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
2805Truly(Predicate pred) {
2806 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
2807}
2808
zhanyong.wan6a896b52009-01-16 01:13:50 +00002809// Returns a matcher that matches an equal container.
2810// This matcher behaves like Eq(), but in the event of mismatch lists the
2811// values that are included in one container but not the other. (Duplicate
2812// values and order differences are not explained.)
2813template <typename Container>
zhanyong.wanb8243162009-06-04 05:48:20 +00002814inline PolymorphicMatcher<internal::ContainerEqMatcher<
2815 GMOCK_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00002816 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002817 // This following line is for working around a bug in MSVC 8.0,
2818 // which causes Container to be a const type sometimes.
2819 typedef GMOCK_REMOVE_CONST_(Container) RawContainer;
2820 return MakePolymorphicMatcher(internal::ContainerEqMatcher<RawContainer>(rhs));
2821}
2822
2823// Matches an STL-style container or a native array that contains at
2824// least one element matching the given value or matcher.
2825//
2826// Examples:
2827// ::std::set<int> page_ids;
2828// page_ids.insert(3);
2829// page_ids.insert(1);
2830// EXPECT_THAT(page_ids, Contains(1));
2831// EXPECT_THAT(page_ids, Contains(Gt(2)));
2832// EXPECT_THAT(page_ids, Not(Contains(4)));
2833//
2834// ::std::map<int, size_t> page_lengths;
2835// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00002836// EXPECT_THAT(page_lengths,
2837// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00002838//
2839// const char* user_ids[] = { "joe", "mike", "tom" };
2840// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
2841template <typename M>
2842inline internal::ContainsMatcher<M> Contains(M matcher) {
2843 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002844}
2845
zhanyong.wanb5937da2009-07-16 20:26:41 +00002846// Key(inner_matcher) matches an std::pair whose 'first' field matches
2847// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2848// std::map that contains at least one element whose key is >= 5.
2849template <typename M>
2850inline internal::KeyMatcher<M> Key(M inner_matcher) {
2851 return internal::KeyMatcher<M>(inner_matcher);
2852}
2853
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002854// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
2855// matches first_matcher and whose 'second' field matches second_matcher. For
2856// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
2857// to match a std::map<int, string> that contains exactly one element whose key
2858// is >= 5 and whose value equals "foo".
2859template <typename FirstMatcher, typename SecondMatcher>
2860inline internal::PairMatcher<FirstMatcher, SecondMatcher>
2861Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
2862 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
2863 first_matcher, second_matcher);
2864}
2865
shiqiane35fdd92008-12-10 05:08:54 +00002866// Returns a predicate that is satisfied by anything that matches the
2867// given matcher.
2868template <typename M>
2869inline internal::MatcherAsPredicate<M> Matches(M matcher) {
2870 return internal::MatcherAsPredicate<M>(matcher);
2871}
2872
zhanyong.wanb8243162009-06-04 05:48:20 +00002873// Returns true iff the value matches the matcher.
2874template <typename T, typename M>
2875inline bool Value(const T& value, M matcher) {
2876 return testing::Matches(matcher)(value);
2877}
2878
zhanyong.wanbf550852009-06-09 06:09:53 +00002879// AllArgs(m) is a synonym of m. This is useful in
2880//
2881// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
2882//
2883// which is easier to read than
2884//
2885// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
2886template <typename InnerMatcher>
2887inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
2888
shiqiane35fdd92008-12-10 05:08:54 +00002889// These macros allow using matchers to check values in Google Test
2890// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
2891// succeed iff the value matches the matcher. If the assertion fails,
2892// the value and the description of the matcher will be printed.
2893#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
2894 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2895#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
2896 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2897
2898} // namespace testing
2899
2900#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_