blob: 5700fb251347439c25d895164b54a2aa466970da [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>
shiqiane35fdd92008-12-10 05:08:54 +000042#include <ostream> // NOLINT
43#include <sstream>
44#include <string>
45#include <vector>
46
47#include <gmock/gmock-printers.h>
48#include <gmock/internal/gmock-internal-utils.h>
49#include <gmock/internal/gmock-port.h>
50#include <gtest/gtest.h>
51
52namespace testing {
53
54// To implement a matcher Foo for type T, define:
55// 1. a class FooMatcherImpl that implements the
56// MatcherInterface<T> interface, and
57// 2. a factory function that creates a Matcher<T> object from a
58// FooMatcherImpl*.
59//
60// The two-level delegation design makes it possible to allow a user
61// to write "v" instead of "Eq(v)" where a Matcher is expected, which
62// is impossible if we pass matchers by pointers. It also eases
63// ownership management as Matcher objects can now be copied like
64// plain values.
65
66// The implementation of a matcher.
67template <typename T>
68class MatcherInterface {
69 public:
70 virtual ~MatcherInterface() {}
71
72 // Returns true iff the matcher matches x.
73 virtual bool Matches(T x) const = 0;
74
75 // Describes this matcher to an ostream.
76 virtual void DescribeTo(::std::ostream* os) const = 0;
77
78 // Describes the negation of this matcher to an ostream. For
79 // example, if the description of this matcher is "is greater than
80 // 7", the negated description could be "is not greater than 7".
81 // You are not required to override this when implementing
82 // MatcherInterface, but it is highly advised so that your matcher
83 // can produce good error messages.
84 virtual void DescribeNegationTo(::std::ostream* os) const {
85 *os << "not (";
86 DescribeTo(os);
87 *os << ")";
88 }
89
90 // Explains why x matches, or doesn't match, the matcher. Override
91 // this to provide any additional information that helps a user
92 // understand the match result.
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +000093 virtual void ExplainMatchResultTo(T /* x */, ::std::ostream* /* os */) const {
shiqiane35fdd92008-12-10 05:08:54 +000094 // By default, nothing more needs to be explained, as Google Mock
95 // has already printed the value of x when this function is
96 // called.
97 }
98};
99
100namespace internal {
101
102// An internal class for implementing Matcher<T>, which will derive
103// from it. We put functionalities common to all Matcher<T>
104// specializations here to avoid code duplication.
105template <typename T>
106class MatcherBase {
107 public:
108 // Returns true iff this matcher matches x.
109 bool Matches(T x) const { return impl_->Matches(x); }
110
111 // Describes this matcher to an ostream.
112 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
113
114 // Describes the negation of this matcher to an ostream.
115 void DescribeNegationTo(::std::ostream* os) const {
116 impl_->DescribeNegationTo(os);
117 }
118
119 // Explains why x matches, or doesn't match, the matcher.
120 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
121 impl_->ExplainMatchResultTo(x, os);
122 }
123 protected:
124 MatcherBase() {}
125
126 // Constructs a matcher from its implementation.
127 explicit MatcherBase(const MatcherInterface<T>* impl)
128 : impl_(impl) {}
129
130 virtual ~MatcherBase() {}
131 private:
132 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
133 // interfaces. The former dynamically allocates a chunk of memory
134 // to hold the reference count, while the latter tracks all
135 // references using a circular linked list without allocating
136 // memory. It has been observed that linked_ptr performs better in
137 // typical scenarios. However, shared_ptr can out-perform
138 // linked_ptr when there are many more uses of the copy constructor
139 // than the default constructor.
140 //
141 // If performance becomes a problem, we should see if using
142 // shared_ptr helps.
143 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
144};
145
146// The default implementation of ExplainMatchResultTo() for
147// polymorphic matchers.
148template <typename PolymorphicMatcherImpl, typename T>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000149inline void ExplainMatchResultTo(const PolymorphicMatcherImpl& /* impl */,
150 const T& /* x */,
151 ::std::ostream* /* os */) {
shiqiane35fdd92008-12-10 05:08:54 +0000152 // By default, nothing more needs to be said, as Google Mock already
153 // prints the value of x elsewhere.
154}
155
156} // namespace internal
157
158// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
159// object that can check whether a value of type T matches. The
160// implementation of Matcher<T> is just a linked_ptr to const
161// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
162// from Matcher!
163template <typename T>
164class Matcher : public internal::MatcherBase<T> {
165 public:
166 // Constructs a null matcher. Needed for storing Matcher objects in
167 // STL containers.
168 Matcher() {}
169
170 // Constructs a matcher from its implementation.
171 explicit Matcher(const MatcherInterface<T>* impl)
172 : internal::MatcherBase<T>(impl) {}
173
zhanyong.wan18490652009-05-11 18:54:08 +0000174 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000175 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
176 Matcher(T value); // NOLINT
177};
178
179// The following two specializations allow the user to write str
180// instead of Eq(str) and "foo" instead of Eq("foo") when a string
181// matcher is expected.
182template <>
183class Matcher<const internal::string&>
184 : public internal::MatcherBase<const internal::string&> {
185 public:
186 Matcher() {}
187
188 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
189 : internal::MatcherBase<const internal::string&>(impl) {}
190
191 // Allows the user to write str instead of Eq(str) sometimes, where
192 // str is a string object.
193 Matcher(const internal::string& s); // NOLINT
194
195 // Allows the user to write "foo" instead of Eq("foo") sometimes.
196 Matcher(const char* s); // NOLINT
197};
198
199template <>
200class Matcher<internal::string>
201 : public internal::MatcherBase<internal::string> {
202 public:
203 Matcher() {}
204
205 explicit Matcher(const MatcherInterface<internal::string>* impl)
206 : internal::MatcherBase<internal::string>(impl) {}
207
208 // Allows the user to write str instead of Eq(str) sometimes, where
209 // str is a string object.
210 Matcher(const internal::string& s); // NOLINT
211
212 // Allows the user to write "foo" instead of Eq("foo") sometimes.
213 Matcher(const char* s); // NOLINT
214};
215
216// The PolymorphicMatcher class template makes it easy to implement a
217// polymorphic matcher (i.e. a matcher that can match values of more
218// than one type, e.g. Eq(n) and NotNull()).
219//
220// To define a polymorphic matcher, a user first provides a Impl class
221// that has a Matches() method, a DescribeTo() method, and a
222// DescribeNegationTo() method. The Matches() method is usually a
223// method template (such that it works with multiple types). Then the
224// user creates the polymorphic matcher using
225// MakePolymorphicMatcher(). To provide additional explanation to the
226// match result, define a FREE function (or function template)
227//
228// void ExplainMatchResultTo(const Impl& matcher, const Value& value,
229// ::std::ostream* os);
230//
231// in the SAME NAME SPACE where Impl is defined. See the definition
232// of NotNull() for a complete example.
233template <class Impl>
234class PolymorphicMatcher {
235 public:
236 explicit PolymorphicMatcher(const Impl& impl) : impl_(impl) {}
237
238 template <typename T>
239 operator Matcher<T>() const {
240 return Matcher<T>(new MonomorphicImpl<T>(impl_));
241 }
242 private:
243 template <typename T>
244 class MonomorphicImpl : public MatcherInterface<T> {
245 public:
246 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
247
248 virtual bool Matches(T x) const { return impl_.Matches(x); }
249
250 virtual void DescribeTo(::std::ostream* os) const {
251 impl_.DescribeTo(os);
252 }
253
254 virtual void DescribeNegationTo(::std::ostream* os) const {
255 impl_.DescribeNegationTo(os);
256 }
257
258 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
259 using ::testing::internal::ExplainMatchResultTo;
260
261 // C++ uses Argument-Dependent Look-up (aka Koenig Look-up) to
262 // resolve the call to ExplainMatchResultTo() here. This
263 // means that if there's a ExplainMatchResultTo() function
264 // defined in the name space where class Impl is defined, it
265 // will be picked by the compiler as the better match.
266 // Otherwise the default implementation of it in
267 // ::testing::internal will be picked.
268 //
269 // This look-up rule lets a writer of a polymorphic matcher
270 // customize the behavior of ExplainMatchResultTo() when he
271 // cares to. Nothing needs to be done by the writer if he
272 // doesn't need to customize it.
273 ExplainMatchResultTo(impl_, x, os);
274 }
275 private:
276 const Impl impl_;
277 };
278
279 const Impl impl_;
280};
281
282// Creates a matcher from its implementation. This is easier to use
283// than the Matcher<T> constructor as it doesn't require you to
284// explicitly write the template argument, e.g.
285//
286// MakeMatcher(foo);
287// vs
288// Matcher<const string&>(foo);
289template <typename T>
290inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
291 return Matcher<T>(impl);
292};
293
294// Creates a polymorphic matcher from its implementation. This is
295// easier to use than the PolymorphicMatcher<Impl> constructor as it
296// doesn't require you to explicitly write the template argument, e.g.
297//
298// MakePolymorphicMatcher(foo);
299// vs
300// PolymorphicMatcher<TypeOfFoo>(foo);
301template <class Impl>
302inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
303 return PolymorphicMatcher<Impl>(impl);
304}
305
306// In order to be safe and clear, casting between different matcher
307// types is done explicitly via MatcherCast<T>(m), which takes a
308// matcher m and returns a Matcher<T>. It compiles only when T can be
309// statically converted to the argument type of m.
310template <typename T, typename M>
311Matcher<T> MatcherCast(M m);
312
zhanyong.wan18490652009-05-11 18:54:08 +0000313// TODO(vladl@google.com): Modify the implementation to reject casting
314// Matcher<int> to Matcher<double>.
315// Implements SafeMatcherCast().
316//
317// This overload handles polymorphic matchers only since monomorphic
318// matchers are handled by the next one.
319template <typename T, typename M>
320inline Matcher<T> SafeMatcherCast(M polymorphic_matcher) {
321 return Matcher<T>(polymorphic_matcher);
322}
323
324// This overload handles monomorphic matchers.
325//
326// In general, if type T can be implicitly converted to type U, we can
327// safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
328// contravariant): just keep a copy of the original Matcher<U>, convert the
329// argument from type T to U, and then pass it to the underlying Matcher<U>.
330// The only exception is when U is a reference and T is not, as the
331// underlying Matcher<U> may be interested in the argument's address, which
332// is not preserved in the conversion from T to U.
333template <typename T, typename U>
334Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) {
335 // Enforce that T can be implicitly converted to U.
336 GMOCK_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
337 T_must_be_implicitly_convertible_to_U);
338 // Enforce that we are not converting a non-reference type T to a reference
339 // type U.
340 GMOCK_COMPILE_ASSERT_(
341 internal::is_reference<T>::value || !internal::is_reference<U>::value,
342 cannot_convert_non_referentce_arg_to_reference);
343 return MatcherCast<T>(matcher);
344}
345
shiqiane35fdd92008-12-10 05:08:54 +0000346// A<T>() returns a matcher that matches any value of type T.
347template <typename T>
348Matcher<T> A();
349
350// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
351// and MUST NOT BE USED IN USER CODE!!!
352namespace internal {
353
354// Appends the explanation on the result of matcher.Matches(value) to
355// os iff the explanation is not empty.
356template <typename T>
357void ExplainMatchResultAsNeededTo(const Matcher<T>& matcher, T value,
358 ::std::ostream* os) {
359 ::std::stringstream reason;
360 matcher.ExplainMatchResultTo(value, &reason);
361 const internal::string s = reason.str();
362 if (s != "") {
363 *os << " (" << s << ")";
364 }
365}
366
367// An internal helper class for doing compile-time loop on a tuple's
368// fields.
369template <size_t N>
370class TuplePrefix {
371 public:
372 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
373 // iff the first N fields of matcher_tuple matches the first N
374 // fields of value_tuple, respectively.
375 template <typename MatcherTuple, typename ValueTuple>
376 static bool Matches(const MatcherTuple& matcher_tuple,
377 const ValueTuple& value_tuple) {
378 using ::std::tr1::get;
379 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
380 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
381 }
382
383 // TuplePrefix<N>::DescribeMatchFailuresTo(matchers, values, os)
384 // describes failures in matching the first N fields of matchers
385 // against the first N fields of values. If there is no failure,
386 // nothing will be streamed to os.
387 template <typename MatcherTuple, typename ValueTuple>
388 static void DescribeMatchFailuresTo(const MatcherTuple& matchers,
389 const ValueTuple& values,
390 ::std::ostream* os) {
391 using ::std::tr1::tuple_element;
392 using ::std::tr1::get;
393
394 // First, describes failures in the first N - 1 fields.
395 TuplePrefix<N - 1>::DescribeMatchFailuresTo(matchers, values, os);
396
397 // Then describes the failure (if any) in the (N - 1)-th (0-based)
398 // field.
399 typename tuple_element<N - 1, MatcherTuple>::type matcher =
400 get<N - 1>(matchers);
401 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
402 Value value = get<N - 1>(values);
403 if (!matcher.Matches(value)) {
404 // TODO(wan): include in the message the name of the parameter
405 // as used in MOCK_METHOD*() when possible.
406 *os << " Expected arg #" << N - 1 << ": ";
407 get<N - 1>(matchers).DescribeTo(os);
408 *os << "\n Actual: ";
409 // We remove the reference in type Value to prevent the
410 // universal printer from printing the address of value, which
411 // isn't interesting to the user most of the time. The
412 // matcher's ExplainMatchResultTo() method handles the case when
413 // the address is interesting.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000414 internal::UniversalPrinter<GMOCK_REMOVE_REFERENCE_(Value)>::
shiqiane35fdd92008-12-10 05:08:54 +0000415 Print(value, os);
416 ExplainMatchResultAsNeededTo<Value>(matcher, value, os);
417 *os << "\n";
418 }
419 }
420};
421
422// The base case.
423template <>
424class TuplePrefix<0> {
425 public:
426 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000427 static bool Matches(const MatcherTuple& /* matcher_tuple */,
428 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000429 return true;
430 }
431
432 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000433 static void DescribeMatchFailuresTo(const MatcherTuple& /* matchers */,
434 const ValueTuple& /* values */,
435 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000436};
437
438// TupleMatches(matcher_tuple, value_tuple) returns true iff all
439// matchers in matcher_tuple match the corresponding fields in
440// value_tuple. It is a compiler error if matcher_tuple and
441// value_tuple have different number of fields or incompatible field
442// types.
443template <typename MatcherTuple, typename ValueTuple>
444bool TupleMatches(const MatcherTuple& matcher_tuple,
445 const ValueTuple& value_tuple) {
446 using ::std::tr1::tuple_size;
447 // Makes sure that matcher_tuple and value_tuple have the same
448 // number of fields.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000449 GMOCK_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
450 tuple_size<ValueTuple>::value,
451 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000452 return TuplePrefix<tuple_size<ValueTuple>::value>::
453 Matches(matcher_tuple, value_tuple);
454}
455
456// Describes failures in matching matchers against values. If there
457// is no failure, nothing will be streamed to os.
458template <typename MatcherTuple, typename ValueTuple>
459void DescribeMatchFailureTupleTo(const MatcherTuple& matchers,
460 const ValueTuple& values,
461 ::std::ostream* os) {
462 using ::std::tr1::tuple_size;
463 TuplePrefix<tuple_size<MatcherTuple>::value>::DescribeMatchFailuresTo(
464 matchers, values, os);
465}
466
467// The MatcherCastImpl class template is a helper for implementing
468// MatcherCast(). We need this helper in order to partially
469// specialize the implementation of MatcherCast() (C++ allows
470// class/struct templates to be partially specialized, but not
471// function templates.).
472
473// This general version is used when MatcherCast()'s argument is a
474// polymorphic matcher (i.e. something that can be converted to a
475// Matcher but is not one yet; for example, Eq(value)).
476template <typename T, typename M>
477class MatcherCastImpl {
478 public:
479 static Matcher<T> Cast(M polymorphic_matcher) {
480 return Matcher<T>(polymorphic_matcher);
481 }
482};
483
484// This more specialized version is used when MatcherCast()'s argument
485// is already a Matcher. This only compiles when type T can be
486// statically converted to type U.
487template <typename T, typename U>
488class MatcherCastImpl<T, Matcher<U> > {
489 public:
490 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
491 return Matcher<T>(new Impl(source_matcher));
492 }
493 private:
494 class Impl : public MatcherInterface<T> {
495 public:
496 explicit Impl(const Matcher<U>& source_matcher)
497 : source_matcher_(source_matcher) {}
498
499 // We delegate the matching logic to the source matcher.
500 virtual bool Matches(T x) const {
501 return source_matcher_.Matches(static_cast<U>(x));
502 }
503
504 virtual void DescribeTo(::std::ostream* os) const {
505 source_matcher_.DescribeTo(os);
506 }
507
508 virtual void DescribeNegationTo(::std::ostream* os) const {
509 source_matcher_.DescribeNegationTo(os);
510 }
511
512 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
513 source_matcher_.ExplainMatchResultTo(static_cast<U>(x), os);
514 }
515 private:
516 const Matcher<U> source_matcher_;
517 };
518};
519
520// This even more specialized version is used for efficiently casting
521// a matcher to its own type.
522template <typename T>
523class MatcherCastImpl<T, Matcher<T> > {
524 public:
525 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
526};
527
528// Implements A<T>().
529template <typename T>
530class AnyMatcherImpl : public MatcherInterface<T> {
531 public:
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000532 virtual bool Matches(T /* x */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000533 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
534 virtual void DescribeNegationTo(::std::ostream* os) const {
535 // This is mostly for completeness' safe, as it's not very useful
536 // to write Not(A<bool>()). However we cannot completely rule out
537 // such a possibility, and it doesn't hurt to be prepared.
538 *os << "never matches";
539 }
540};
541
542// Implements _, a matcher that matches any value of any
543// type. This is a polymorphic matcher, so we need a template type
544// conversion operator to make it appearing as a Matcher<T> for any
545// type T.
546class AnythingMatcher {
547 public:
548 template <typename T>
549 operator Matcher<T>() const { return A<T>(); }
550};
551
552// Implements a matcher that compares a given value with a
553// pre-supplied value using one of the ==, <=, <, etc, operators. The
554// two values being compared don't have to have the same type.
555//
556// The matcher defined here is polymorphic (for example, Eq(5) can be
557// used to match an int, a short, a double, etc). Therefore we use
558// a template type conversion operator in the implementation.
559//
560// We define this as a macro in order to eliminate duplicated source
561// code.
562//
563// The following template definition assumes that the Rhs parameter is
564// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wane0d051e2009-02-19 00:33:37 +0000565#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000566 template <typename Rhs> class name##Matcher { \
567 public: \
568 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
569 template <typename Lhs> \
570 operator Matcher<Lhs>() const { \
571 return MakeMatcher(new Impl<Lhs>(rhs_)); \
572 } \
573 private: \
574 template <typename Lhs> \
575 class Impl : public MatcherInterface<Lhs> { \
576 public: \
577 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
578 virtual bool Matches(Lhs lhs) const { return lhs op rhs_; } \
579 virtual void DescribeTo(::std::ostream* os) const { \
580 *os << "is " relation " "; \
581 UniversalPrinter<Rhs>::Print(rhs_, os); \
582 } \
583 virtual void DescribeNegationTo(::std::ostream* os) const { \
584 *os << "is not " relation " "; \
585 UniversalPrinter<Rhs>::Print(rhs_, os); \
586 } \
587 private: \
588 Rhs rhs_; \
589 }; \
590 Rhs rhs_; \
591 }
592
593// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
594// respectively.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000595GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "equal to");
596GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "greater than or equal to");
597GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "greater than");
598GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "less than or equal to");
599GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "less than");
600GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "not equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000601
zhanyong.wane0d051e2009-02-19 00:33:37 +0000602#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000603
604// Implements the polymorphic NotNull() matcher, which matches any
605// pointer that is not NULL.
606class NotNullMatcher {
607 public:
608 template <typename T>
609 bool Matches(T* p) const { return p != NULL; }
610
611 void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; }
612 void DescribeNegationTo(::std::ostream* os) const {
613 *os << "is NULL";
614 }
615};
616
617// Ref(variable) matches any argument that is a reference to
618// 'variable'. This matcher is polymorphic as it can match any
619// super type of the type of 'variable'.
620//
621// The RefMatcher template class implements Ref(variable). It can
622// only be instantiated with a reference type. This prevents a user
623// from mistakenly using Ref(x) to match a non-reference function
624// argument. For example, the following will righteously cause a
625// compiler error:
626//
627// int n;
628// Matcher<int> m1 = Ref(n); // This won't compile.
629// Matcher<int&> m2 = Ref(n); // This will compile.
630template <typename T>
631class RefMatcher;
632
633template <typename T>
634class RefMatcher<T&> {
635 // Google Mock is a generic framework and thus needs to support
636 // mocking any function types, including those that take non-const
637 // reference arguments. Therefore the template parameter T (and
638 // Super below) can be instantiated to either a const type or a
639 // non-const type.
640 public:
641 // RefMatcher() takes a T& instead of const T&, as we want the
642 // compiler to catch using Ref(const_value) as a matcher for a
643 // non-const reference.
644 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
645
646 template <typename Super>
647 operator Matcher<Super&>() const {
648 // By passing object_ (type T&) to Impl(), which expects a Super&,
649 // we make sure that Super is a super type of T. In particular,
650 // this catches using Ref(const_value) as a matcher for a
651 // non-const reference, as you cannot implicitly convert a const
652 // reference to a non-const reference.
653 return MakeMatcher(new Impl<Super>(object_));
654 }
655 private:
656 template <typename Super>
657 class Impl : public MatcherInterface<Super&> {
658 public:
659 explicit Impl(Super& x) : object_(x) {} // NOLINT
660
661 // Matches() takes a Super& (as opposed to const Super&) in
662 // order to match the interface MatcherInterface<Super&>.
663 virtual bool Matches(Super& x) const { return &x == &object_; } // NOLINT
664
665 virtual void DescribeTo(::std::ostream* os) const {
666 *os << "references the variable ";
667 UniversalPrinter<Super&>::Print(object_, os);
668 }
669
670 virtual void DescribeNegationTo(::std::ostream* os) const {
671 *os << "does not reference the variable ";
672 UniversalPrinter<Super&>::Print(object_, os);
673 }
674
675 virtual void ExplainMatchResultTo(Super& x, // NOLINT
676 ::std::ostream* os) const {
677 *os << "is located @" << static_cast<const void*>(&x);
678 }
679 private:
680 const Super& object_;
681 };
682
683 T& object_;
684};
685
686// Polymorphic helper functions for narrow and wide string matchers.
687inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
688 return String::CaseInsensitiveCStringEquals(lhs, rhs);
689}
690
691inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
692 const wchar_t* rhs) {
693 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
694}
695
696// String comparison for narrow or wide strings that can have embedded NUL
697// characters.
698template <typename StringType>
699bool CaseInsensitiveStringEquals(const StringType& s1,
700 const StringType& s2) {
701 // Are the heads equal?
702 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
703 return false;
704 }
705
706 // Skip the equal heads.
707 const typename StringType::value_type nul = 0;
708 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
709
710 // Are we at the end of either s1 or s2?
711 if (i1 == StringType::npos || i2 == StringType::npos) {
712 return i1 == i2;
713 }
714
715 // Are the tails equal?
716 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
717}
718
719// String matchers.
720
721// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
722template <typename StringType>
723class StrEqualityMatcher {
724 public:
725 typedef typename StringType::const_pointer ConstCharPointer;
726
727 StrEqualityMatcher(const StringType& str, bool expect_eq,
728 bool case_sensitive)
729 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
730
731 // When expect_eq_ is true, returns true iff s is equal to string_;
732 // otherwise returns true iff s is not equal to string_.
733 bool Matches(ConstCharPointer s) const {
734 if (s == NULL) {
735 return !expect_eq_;
736 }
737 return Matches(StringType(s));
738 }
739
740 bool Matches(const StringType& s) const {
741 const bool eq = case_sensitive_ ? s == string_ :
742 CaseInsensitiveStringEquals(s, string_);
743 return expect_eq_ == eq;
744 }
745
746 void DescribeTo(::std::ostream* os) const {
747 DescribeToHelper(expect_eq_, os);
748 }
749
750 void DescribeNegationTo(::std::ostream* os) const {
751 DescribeToHelper(!expect_eq_, os);
752 }
753 private:
754 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
755 *os << "is ";
756 if (!expect_eq) {
757 *os << "not ";
758 }
759 *os << "equal to ";
760 if (!case_sensitive_) {
761 *os << "(ignoring case) ";
762 }
763 UniversalPrinter<StringType>::Print(string_, os);
764 }
765
766 const StringType string_;
767 const bool expect_eq_;
768 const bool case_sensitive_;
769};
770
771// Implements the polymorphic HasSubstr(substring) matcher, which
772// can be used as a Matcher<T> as long as T can be converted to a
773// string.
774template <typename StringType>
775class HasSubstrMatcher {
776 public:
777 typedef typename StringType::const_pointer ConstCharPointer;
778
779 explicit HasSubstrMatcher(const StringType& substring)
780 : substring_(substring) {}
781
782 // These overloaded methods allow HasSubstr(substring) to be used as a
783 // Matcher<T> as long as T can be converted to string. Returns true
784 // iff s contains substring_ as a substring.
785 bool Matches(ConstCharPointer s) const {
786 return s != NULL && Matches(StringType(s));
787 }
788
789 bool Matches(const StringType& s) const {
790 return s.find(substring_) != StringType::npos;
791 }
792
793 // Describes what this matcher matches.
794 void DescribeTo(::std::ostream* os) const {
795 *os << "has substring ";
796 UniversalPrinter<StringType>::Print(substring_, os);
797 }
798
799 void DescribeNegationTo(::std::ostream* os) const {
800 *os << "has no substring ";
801 UniversalPrinter<StringType>::Print(substring_, os);
802 }
803 private:
804 const StringType substring_;
805};
806
807// Implements the polymorphic StartsWith(substring) matcher, which
808// can be used as a Matcher<T> as long as T can be converted to a
809// string.
810template <typename StringType>
811class StartsWithMatcher {
812 public:
813 typedef typename StringType::const_pointer ConstCharPointer;
814
815 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
816 }
817
818 // These overloaded methods allow StartsWith(prefix) to be used as a
819 // Matcher<T> as long as T can be converted to string. Returns true
820 // iff s starts with prefix_.
821 bool Matches(ConstCharPointer s) const {
822 return s != NULL && Matches(StringType(s));
823 }
824
825 bool Matches(const StringType& s) const {
826 return s.length() >= prefix_.length() &&
827 s.substr(0, prefix_.length()) == prefix_;
828 }
829
830 void DescribeTo(::std::ostream* os) const {
831 *os << "starts with ";
832 UniversalPrinter<StringType>::Print(prefix_, os);
833 }
834
835 void DescribeNegationTo(::std::ostream* os) const {
836 *os << "doesn't start with ";
837 UniversalPrinter<StringType>::Print(prefix_, os);
838 }
839 private:
840 const StringType prefix_;
841};
842
843// Implements the polymorphic EndsWith(substring) matcher, which
844// can be used as a Matcher<T> as long as T can be converted to a
845// string.
846template <typename StringType>
847class EndsWithMatcher {
848 public:
849 typedef typename StringType::const_pointer ConstCharPointer;
850
851 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
852
853 // These overloaded methods allow EndsWith(suffix) to be used as a
854 // Matcher<T> as long as T can be converted to string. Returns true
855 // iff s ends with suffix_.
856 bool Matches(ConstCharPointer s) const {
857 return s != NULL && Matches(StringType(s));
858 }
859
860 bool Matches(const StringType& s) const {
861 return s.length() >= suffix_.length() &&
862 s.substr(s.length() - suffix_.length()) == suffix_;
863 }
864
865 void DescribeTo(::std::ostream* os) const {
866 *os << "ends with ";
867 UniversalPrinter<StringType>::Print(suffix_, os);
868 }
869
870 void DescribeNegationTo(::std::ostream* os) const {
871 *os << "doesn't end with ";
872 UniversalPrinter<StringType>::Print(suffix_, os);
873 }
874 private:
875 const StringType suffix_;
876};
877
878#if GMOCK_HAS_REGEX
879
880// Implements polymorphic matchers MatchesRegex(regex) and
881// ContainsRegex(regex), which can be used as a Matcher<T> as long as
882// T can be converted to a string.
883class MatchesRegexMatcher {
884 public:
885 MatchesRegexMatcher(const RE* regex, bool full_match)
886 : regex_(regex), full_match_(full_match) {}
887
888 // These overloaded methods allow MatchesRegex(regex) to be used as
889 // a Matcher<T> as long as T can be converted to string. Returns
890 // true iff s matches regular expression regex. When full_match_ is
891 // true, a full match is done; otherwise a partial match is done.
892 bool Matches(const char* s) const {
893 return s != NULL && Matches(internal::string(s));
894 }
895
896 bool Matches(const internal::string& s) const {
897 return full_match_ ? RE::FullMatch(s, *regex_) :
898 RE::PartialMatch(s, *regex_);
899 }
900
901 void DescribeTo(::std::ostream* os) const {
902 *os << (full_match_ ? "matches" : "contains")
903 << " regular expression ";
904 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
905 }
906
907 void DescribeNegationTo(::std::ostream* os) const {
908 *os << "doesn't " << (full_match_ ? "match" : "contain")
909 << " regular expression ";
910 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
911 }
912 private:
913 const internal::linked_ptr<const RE> regex_;
914 const bool full_match_;
915};
916
917#endif // GMOCK_HAS_REGEX
918
919// Implements a matcher that compares the two fields of a 2-tuple
920// using one of the ==, <=, <, etc, operators. The two fields being
921// compared don't have to have the same type.
922//
923// The matcher defined here is polymorphic (for example, Eq() can be
924// used to match a tuple<int, short>, a tuple<const long&, double>,
925// etc). Therefore we use a template type conversion operator in the
926// implementation.
927//
928// We define this as a macro in order to eliminate duplicated source
929// code.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000930#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000931 class name##2Matcher { \
932 public: \
933 template <typename T1, typename T2> \
934 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
935 return MakeMatcher(new Impl<T1, T2>); \
936 } \
937 private: \
938 template <typename T1, typename T2> \
939 class Impl : public MatcherInterface<const ::std::tr1::tuple<T1, T2>&> { \
940 public: \
941 virtual bool Matches(const ::std::tr1::tuple<T1, T2>& args) const { \
942 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
943 } \
944 virtual void DescribeTo(::std::ostream* os) const { \
945 *os << "argument #0 is " relation " argument #1"; \
946 } \
947 virtual void DescribeNegationTo(::std::ostream* os) const { \
948 *os << "argument #0 is not " relation " argument #1"; \
949 } \
950 }; \
951 }
952
953// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000954GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "equal to");
955GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ge, >=, "greater than or equal to");
956GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Gt, >, "greater than");
957GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Le, <=, "less than or equal to");
958GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Lt, <, "less than");
959GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=, "not equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000960
zhanyong.wane0d051e2009-02-19 00:33:37 +0000961#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000962
zhanyong.wan18490652009-05-11 18:54:08 +0000963// TODO(vladl@google.com): Move Impl outside of NotMatcher and rename it
964// NotMatcherImpl to reduce compilation overhead and the size of the binary.
965// This also applies to BothOfMatcher::Impl and EitherOfMatcher::Impl.
966//
shiqiane35fdd92008-12-10 05:08:54 +0000967// Implements the Not(m) matcher, which matches a value that doesn't
968// match matcher m.
969template <typename InnerMatcher>
970class NotMatcher {
971 public:
972 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
973
974 // This template type conversion operator allows Not(m) to be used
975 // to match any type m can match.
976 template <typename T>
977 operator Matcher<T>() const {
978 return Matcher<T>(new Impl<T>(matcher_));
979 }
980 private:
981 // Implements the Not(...) matcher for a particular argument type T.
982 template <typename T>
983 class Impl : public MatcherInterface<T> {
984 public:
zhanyong.wan18490652009-05-11 18:54:08 +0000985 explicit Impl(InnerMatcher matcher)
986 : matcher_(SafeMatcherCast<T>(matcher)) {}
shiqiane35fdd92008-12-10 05:08:54 +0000987
988 virtual bool Matches(T x) const {
989 return !matcher_.Matches(x);
990 }
991
992 virtual void DescribeTo(::std::ostream* os) const {
993 matcher_.DescribeNegationTo(os);
994 }
995
996 virtual void DescribeNegationTo(::std::ostream* os) const {
997 matcher_.DescribeTo(os);
998 }
999
1000 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1001 matcher_.ExplainMatchResultTo(x, os);
1002 }
1003 private:
1004 const Matcher<T> matcher_;
1005 };
1006
1007 InnerMatcher matcher_;
1008};
1009
1010// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1011// matches a value that matches all of the matchers m_1, ..., and m_n.
1012template <typename Matcher1, typename Matcher2>
1013class BothOfMatcher {
1014 public:
1015 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1016 : matcher1_(matcher1), matcher2_(matcher2) {}
1017
1018 // This template type conversion operator allows a
1019 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1020 // both Matcher1 and Matcher2 can match.
1021 template <typename T>
1022 operator Matcher<T>() const {
1023 return Matcher<T>(new Impl<T>(matcher1_, matcher2_));
1024 }
1025 private:
1026 // Implements the AllOf(m1, m2) matcher for a particular argument
1027 // type T.
1028 template <typename T>
1029 class Impl : public MatcherInterface<T> {
1030 public:
zhanyong.wan18490652009-05-11 18:54:08 +00001031 Impl(Matcher1 matcher1, Matcher2 matcher2)
1032 : matcher1_(SafeMatcherCast<T>(matcher1)),
1033 matcher2_(SafeMatcherCast<T>(matcher2)) {}
shiqiane35fdd92008-12-10 05:08:54 +00001034
1035 virtual bool Matches(T x) const {
1036 return matcher1_.Matches(x) && matcher2_.Matches(x);
1037 }
1038
1039 virtual void DescribeTo(::std::ostream* os) const {
1040 *os << "(";
1041 matcher1_.DescribeTo(os);
1042 *os << ") and (";
1043 matcher2_.DescribeTo(os);
1044 *os << ")";
1045 }
1046
1047 virtual void DescribeNegationTo(::std::ostream* os) const {
1048 *os << "not ";
1049 DescribeTo(os);
1050 }
1051
1052 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1053 if (Matches(x)) {
1054 // When both matcher1_ and matcher2_ match x, we need to
1055 // explain why *both* of them match.
1056 ::std::stringstream ss1;
1057 matcher1_.ExplainMatchResultTo(x, &ss1);
1058 const internal::string s1 = ss1.str();
1059
1060 ::std::stringstream ss2;
1061 matcher2_.ExplainMatchResultTo(x, &ss2);
1062 const internal::string s2 = ss2.str();
1063
1064 if (s1 == "") {
1065 *os << s2;
1066 } else {
1067 *os << s1;
1068 if (s2 != "") {
1069 *os << "; " << s2;
1070 }
1071 }
1072 } else {
1073 // Otherwise we only need to explain why *one* of them fails
1074 // to match.
1075 if (!matcher1_.Matches(x)) {
1076 matcher1_.ExplainMatchResultTo(x, os);
1077 } else {
1078 matcher2_.ExplainMatchResultTo(x, os);
1079 }
1080 }
1081 }
1082 private:
1083 const Matcher<T> matcher1_;
1084 const Matcher<T> matcher2_;
1085 };
1086
1087 Matcher1 matcher1_;
1088 Matcher2 matcher2_;
1089};
1090
1091// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1092// matches a value that matches at least one of the matchers m_1, ...,
1093// and m_n.
1094template <typename Matcher1, typename Matcher2>
1095class EitherOfMatcher {
1096 public:
1097 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1098 : matcher1_(matcher1), matcher2_(matcher2) {}
1099
1100 // This template type conversion operator allows a
1101 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1102 // both Matcher1 and Matcher2 can match.
1103 template <typename T>
1104 operator Matcher<T>() const {
1105 return Matcher<T>(new Impl<T>(matcher1_, matcher2_));
1106 }
1107 private:
1108 // Implements the AnyOf(m1, m2) matcher for a particular argument
1109 // type T.
1110 template <typename T>
1111 class Impl : public MatcherInterface<T> {
1112 public:
zhanyong.wan18490652009-05-11 18:54:08 +00001113 Impl(Matcher1 matcher1, Matcher2 matcher2)
1114 : matcher1_(SafeMatcherCast<T>(matcher1)),
1115 matcher2_(SafeMatcherCast<T>(matcher2)) {}
shiqiane35fdd92008-12-10 05:08:54 +00001116
1117 virtual bool Matches(T x) const {
1118 return matcher1_.Matches(x) || matcher2_.Matches(x);
1119 }
1120
1121 virtual void DescribeTo(::std::ostream* os) const {
1122 *os << "(";
1123 matcher1_.DescribeTo(os);
1124 *os << ") or (";
1125 matcher2_.DescribeTo(os);
1126 *os << ")";
1127 }
1128
1129 virtual void DescribeNegationTo(::std::ostream* os) const {
1130 *os << "not ";
1131 DescribeTo(os);
1132 }
1133
1134 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1135 if (Matches(x)) {
1136 // If either matcher1_ or matcher2_ matches x, we just need
1137 // to explain why *one* of them matches.
1138 if (matcher1_.Matches(x)) {
1139 matcher1_.ExplainMatchResultTo(x, os);
1140 } else {
1141 matcher2_.ExplainMatchResultTo(x, os);
1142 }
1143 } else {
1144 // Otherwise we need to explain why *neither* matches.
1145 ::std::stringstream ss1;
1146 matcher1_.ExplainMatchResultTo(x, &ss1);
1147 const internal::string s1 = ss1.str();
1148
1149 ::std::stringstream ss2;
1150 matcher2_.ExplainMatchResultTo(x, &ss2);
1151 const internal::string s2 = ss2.str();
1152
1153 if (s1 == "") {
1154 *os << s2;
1155 } else {
1156 *os << s1;
1157 if (s2 != "") {
1158 *os << "; " << s2;
1159 }
1160 }
1161 }
1162 }
1163 private:
1164 const Matcher<T> matcher1_;
1165 const Matcher<T> matcher2_;
1166 };
1167
1168 Matcher1 matcher1_;
1169 Matcher2 matcher2_;
1170};
1171
1172// Used for implementing Truly(pred), which turns a predicate into a
1173// matcher.
1174template <typename Predicate>
1175class TrulyMatcher {
1176 public:
1177 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1178
1179 // This method template allows Truly(pred) to be used as a matcher
1180 // for type T where T is the argument type of predicate 'pred'. The
1181 // argument is passed by reference as the predicate may be
1182 // interested in the address of the argument.
1183 template <typename T>
1184 bool Matches(T& x) const {
zhanyong.wan652540a2009-02-23 23:37:29 +00001185#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001186 // MSVC warns about converting a value into bool (warning 4800).
1187#pragma warning(push) // Saves the current warning state.
1188#pragma warning(disable:4800) // Temporarily disables warning 4800.
1189#endif // GTEST_OS_WINDOWS
1190 return predicate_(x);
zhanyong.wan652540a2009-02-23 23:37:29 +00001191#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001192#pragma warning(pop) // Restores the warning state.
1193#endif // GTEST_OS_WINDOWS
1194 }
1195
1196 void DescribeTo(::std::ostream* os) const {
1197 *os << "satisfies the given predicate";
1198 }
1199
1200 void DescribeNegationTo(::std::ostream* os) const {
1201 *os << "doesn't satisfy the given predicate";
1202 }
1203 private:
1204 Predicate predicate_;
1205};
1206
1207// Used for implementing Matches(matcher), which turns a matcher into
1208// a predicate.
1209template <typename M>
1210class MatcherAsPredicate {
1211 public:
1212 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1213
1214 // This template operator() allows Matches(m) to be used as a
1215 // predicate on type T where m is a matcher on type T.
1216 //
1217 // The argument x is passed by reference instead of by value, as
1218 // some matcher may be interested in its address (e.g. as in
1219 // Matches(Ref(n))(x)).
1220 template <typename T>
1221 bool operator()(const T& x) const {
1222 // We let matcher_ commit to a particular type here instead of
1223 // when the MatcherAsPredicate object was constructed. This
1224 // allows us to write Matches(m) where m is a polymorphic matcher
1225 // (e.g. Eq(5)).
1226 //
1227 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1228 // compile when matcher_ has type Matcher<const T&>; if we write
1229 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1230 // when matcher_ has type Matcher<T>; if we just write
1231 // matcher_.Matches(x), it won't compile when matcher_ is
1232 // polymorphic, e.g. Eq(5).
1233 //
1234 // MatcherCast<const T&>() is necessary for making the code work
1235 // in all of the above situations.
1236 return MatcherCast<const T&>(matcher_).Matches(x);
1237 }
1238 private:
1239 M matcher_;
1240};
1241
1242// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1243// argument M must be a type that can be converted to a matcher.
1244template <typename M>
1245class PredicateFormatterFromMatcher {
1246 public:
1247 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1248
1249 // This template () operator allows a PredicateFormatterFromMatcher
1250 // object to act as a predicate-formatter suitable for using with
1251 // Google Test's EXPECT_PRED_FORMAT1() macro.
1252 template <typename T>
1253 AssertionResult operator()(const char* value_text, const T& x) const {
1254 // We convert matcher_ to a Matcher<const T&> *now* instead of
1255 // when the PredicateFormatterFromMatcher object was constructed,
1256 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1257 // know which type to instantiate it to until we actually see the
1258 // type of x here.
1259 //
1260 // We write MatcherCast<const T&>(matcher_) instead of
1261 // Matcher<const T&>(matcher_), as the latter won't compile when
1262 // matcher_ has type Matcher<T> (e.g. An<int>()).
1263 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
1264 if (matcher.Matches(x)) {
1265 return AssertionSuccess();
1266 } else {
1267 ::std::stringstream ss;
1268 ss << "Value of: " << value_text << "\n"
1269 << "Expected: ";
1270 matcher.DescribeTo(&ss);
1271 ss << "\n Actual: ";
1272 UniversalPrinter<T>::Print(x, &ss);
1273 ExplainMatchResultAsNeededTo<const T&>(matcher, x, &ss);
1274 return AssertionFailure(Message() << ss.str());
1275 }
1276 }
1277 private:
1278 const M matcher_;
1279};
1280
1281// A helper function for converting a matcher to a predicate-formatter
1282// without the user needing to explicitly write the type. This is
1283// used for implementing ASSERT_THAT() and EXPECT_THAT().
1284template <typename M>
1285inline PredicateFormatterFromMatcher<M>
1286MakePredicateFormatterFromMatcher(const M& matcher) {
1287 return PredicateFormatterFromMatcher<M>(matcher);
1288}
1289
1290// Implements the polymorphic floating point equality matcher, which
1291// matches two float values using ULP-based approximation. The
1292// template is meant to be instantiated with FloatType being either
1293// float or double.
1294template <typename FloatType>
1295class FloatingEqMatcher {
1296 public:
1297 // Constructor for FloatingEqMatcher.
1298 // The matcher's input will be compared with rhs. The matcher treats two
1299 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1300 // equality comparisons between NANs will always return false.
1301 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1302 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1303
1304 // Implements floating point equality matcher as a Matcher<T>.
1305 template <typename T>
1306 class Impl : public MatcherInterface<T> {
1307 public:
1308 Impl(FloatType rhs, bool nan_eq_nan) :
1309 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1310
1311 virtual bool Matches(T value) const {
1312 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1313
1314 // Compares NaNs first, if nan_eq_nan_ is true.
1315 if (nan_eq_nan_ && lhs.is_nan()) {
1316 return rhs.is_nan();
1317 }
1318
1319 return lhs.AlmostEquals(rhs);
1320 }
1321
1322 virtual void DescribeTo(::std::ostream* os) const {
1323 // os->precision() returns the previously set precision, which we
1324 // store to restore the ostream to its original configuration
1325 // after outputting.
1326 const ::std::streamsize old_precision = os->precision(
1327 ::std::numeric_limits<FloatType>::digits10 + 2);
1328 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1329 if (nan_eq_nan_) {
1330 *os << "is NaN";
1331 } else {
1332 *os << "never matches";
1333 }
1334 } else {
1335 *os << "is approximately " << rhs_;
1336 }
1337 os->precision(old_precision);
1338 }
1339
1340 virtual void DescribeNegationTo(::std::ostream* os) const {
1341 // As before, get original precision.
1342 const ::std::streamsize old_precision = os->precision(
1343 ::std::numeric_limits<FloatType>::digits10 + 2);
1344 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1345 if (nan_eq_nan_) {
1346 *os << "is not NaN";
1347 } else {
1348 *os << "is anything";
1349 }
1350 } else {
1351 *os << "is not approximately " << rhs_;
1352 }
1353 // Restore original precision.
1354 os->precision(old_precision);
1355 }
1356
1357 private:
1358 const FloatType rhs_;
1359 const bool nan_eq_nan_;
1360 };
1361
1362 // The following 3 type conversion operators allow FloatEq(rhs) and
1363 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1364 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1365 // (While Google's C++ coding style doesn't allow arguments passed
1366 // by non-const reference, we may see them in code not conforming to
1367 // the style. Therefore Google Mock needs to support them.)
1368 operator Matcher<FloatType>() const {
1369 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1370 }
1371
1372 operator Matcher<const FloatType&>() const {
1373 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1374 }
1375
1376 operator Matcher<FloatType&>() const {
1377 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1378 }
1379 private:
1380 const FloatType rhs_;
1381 const bool nan_eq_nan_;
1382};
1383
1384// Implements the Pointee(m) matcher for matching a pointer whose
1385// pointee matches matcher m. The pointer can be either raw or smart.
1386template <typename InnerMatcher>
1387class PointeeMatcher {
1388 public:
1389 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1390
1391 // This type conversion operator template allows Pointee(m) to be
1392 // used as a matcher for any pointer type whose pointee type is
1393 // compatible with the inner matcher, where type Pointer can be
1394 // either a raw pointer or a smart pointer.
1395 //
1396 // The reason we do this instead of relying on
1397 // MakePolymorphicMatcher() is that the latter is not flexible
1398 // enough for implementing the DescribeTo() method of Pointee().
1399 template <typename Pointer>
1400 operator Matcher<Pointer>() const {
1401 return MakeMatcher(new Impl<Pointer>(matcher_));
1402 }
1403 private:
1404 // The monomorphic implementation that works for a particular pointer type.
1405 template <typename Pointer>
1406 class Impl : public MatcherInterface<Pointer> {
1407 public:
zhanyong.wane0d051e2009-02-19 00:33:37 +00001408 typedef typename PointeeOf<GMOCK_REMOVE_CONST_( // NOLINT
1409 GMOCK_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001410
1411 explicit Impl(const InnerMatcher& matcher)
1412 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1413
1414 virtual bool Matches(Pointer p) const {
1415 return GetRawPointer(p) != NULL && matcher_.Matches(*p);
1416 }
1417
1418 virtual void DescribeTo(::std::ostream* os) const {
1419 *os << "points to a value that ";
1420 matcher_.DescribeTo(os);
1421 }
1422
1423 virtual void DescribeNegationTo(::std::ostream* os) const {
1424 *os << "does not point to a value that ";
1425 matcher_.DescribeTo(os);
1426 }
1427
1428 virtual void ExplainMatchResultTo(Pointer pointer,
1429 ::std::ostream* os) const {
1430 if (GetRawPointer(pointer) == NULL)
1431 return;
1432
1433 ::std::stringstream ss;
1434 matcher_.ExplainMatchResultTo(*pointer, &ss);
1435 const internal::string s = ss.str();
1436 if (s != "") {
1437 *os << "points to a value that " << s;
1438 }
1439 }
1440 private:
1441 const Matcher<const Pointee&> matcher_;
1442 };
1443
1444 const InnerMatcher matcher_;
1445};
1446
1447// Implements the Field() matcher for matching a field (i.e. member
1448// variable) of an object.
1449template <typename Class, typename FieldType>
1450class FieldMatcher {
1451 public:
1452 FieldMatcher(FieldType Class::*field,
1453 const Matcher<const FieldType&>& matcher)
1454 : field_(field), matcher_(matcher) {}
1455
1456 // Returns true iff the inner matcher matches obj.field.
1457 bool Matches(const Class& obj) const {
1458 return matcher_.Matches(obj.*field_);
1459 }
1460
1461 // Returns true iff the inner matcher matches obj->field.
1462 bool Matches(const Class* p) const {
1463 return (p != NULL) && matcher_.Matches(p->*field_);
1464 }
1465
1466 void DescribeTo(::std::ostream* os) const {
1467 *os << "the given field ";
1468 matcher_.DescribeTo(os);
1469 }
1470
1471 void DescribeNegationTo(::std::ostream* os) const {
1472 *os << "the given field ";
1473 matcher_.DescribeNegationTo(os);
1474 }
1475
zhanyong.wan18490652009-05-11 18:54:08 +00001476 // The first argument of ExplainMatchResultTo() is needed to help
1477 // Symbian's C++ compiler choose which overload to use. Its type is
1478 // true_type iff the Field() matcher is used to match a pointer.
1479 void ExplainMatchResultTo(false_type /* is_not_pointer */, const Class& obj,
1480 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001481 ::std::stringstream ss;
1482 matcher_.ExplainMatchResultTo(obj.*field_, &ss);
1483 const internal::string s = ss.str();
1484 if (s != "") {
1485 *os << "the given field " << s;
1486 }
1487 }
1488
zhanyong.wan18490652009-05-11 18:54:08 +00001489 void ExplainMatchResultTo(true_type /* is_pointer */, const Class* p,
1490 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001491 if (p != NULL) {
zhanyong.wan18490652009-05-11 18:54:08 +00001492 // Since *p has a field, it must be a class/struct/union type
1493 // and thus cannot be a pointer. Therefore we pass false_type()
1494 // as the first argument.
1495 ExplainMatchResultTo(false_type(), *p, os);
shiqiane35fdd92008-12-10 05:08:54 +00001496 }
1497 }
1498 private:
1499 const FieldType Class::*field_;
1500 const Matcher<const FieldType&> matcher_;
1501};
1502
zhanyong.wan18490652009-05-11 18:54:08 +00001503// Explains the result of matching an object or pointer against a field matcher.
1504template <typename Class, typename FieldType, typename T>
shiqiane35fdd92008-12-10 05:08:54 +00001505void ExplainMatchResultTo(const FieldMatcher<Class, FieldType>& matcher,
zhanyong.wan18490652009-05-11 18:54:08 +00001506 const T& value, ::std::ostream* os) {
1507 matcher.ExplainMatchResultTo(
1508 typename ::testing::internal::is_pointer<T>::type(), value, os);
shiqiane35fdd92008-12-10 05:08:54 +00001509}
1510
1511// Implements the Property() matcher for matching a property
1512// (i.e. return value of a getter method) of an object.
1513template <typename Class, typename PropertyType>
1514class PropertyMatcher {
1515 public:
1516 // The property may have a reference type, so 'const PropertyType&'
1517 // may cause double references and fail to compile. That's why we
1518 // need GMOCK_REFERENCE_TO_CONST, which works regardless of
1519 // PropertyType being a reference or not.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001520 typedef GMOCK_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001521
1522 PropertyMatcher(PropertyType (Class::*property)() const,
1523 const Matcher<RefToConstProperty>& matcher)
1524 : property_(property), matcher_(matcher) {}
1525
1526 // Returns true iff obj.property() matches the inner matcher.
1527 bool Matches(const Class& obj) const {
1528 return matcher_.Matches((obj.*property_)());
1529 }
1530
1531 // Returns true iff p->property() matches the inner matcher.
1532 bool Matches(const Class* p) const {
1533 return (p != NULL) && matcher_.Matches((p->*property_)());
1534 }
1535
1536 void DescribeTo(::std::ostream* os) const {
1537 *os << "the given property ";
1538 matcher_.DescribeTo(os);
1539 }
1540
1541 void DescribeNegationTo(::std::ostream* os) const {
1542 *os << "the given property ";
1543 matcher_.DescribeNegationTo(os);
1544 }
1545
zhanyong.wan18490652009-05-11 18:54:08 +00001546 // The first argument of ExplainMatchResultTo() is needed to help
1547 // Symbian's C++ compiler choose which overload to use. Its type is
1548 // true_type iff the Property() matcher is used to match a pointer.
1549 void ExplainMatchResultTo(false_type /* is_not_pointer */, const Class& obj,
1550 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001551 ::std::stringstream ss;
1552 matcher_.ExplainMatchResultTo((obj.*property_)(), &ss);
1553 const internal::string s = ss.str();
1554 if (s != "") {
1555 *os << "the given property " << s;
1556 }
1557 }
1558
zhanyong.wan18490652009-05-11 18:54:08 +00001559 void ExplainMatchResultTo(true_type /* is_pointer */, const Class* p,
1560 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001561 if (p != NULL) {
zhanyong.wan18490652009-05-11 18:54:08 +00001562 // Since *p has a property method, it must be a
1563 // class/struct/union type and thus cannot be a pointer.
1564 // Therefore we pass false_type() as the first argument.
1565 ExplainMatchResultTo(false_type(), *p, os);
shiqiane35fdd92008-12-10 05:08:54 +00001566 }
1567 }
1568 private:
1569 PropertyType (Class::*property_)() const;
1570 const Matcher<RefToConstProperty> matcher_;
1571};
1572
zhanyong.wan18490652009-05-11 18:54:08 +00001573// Explains the result of matching an object or pointer against a
1574// property matcher.
1575template <typename Class, typename PropertyType, typename T>
shiqiane35fdd92008-12-10 05:08:54 +00001576void ExplainMatchResultTo(const PropertyMatcher<Class, PropertyType>& matcher,
zhanyong.wan18490652009-05-11 18:54:08 +00001577 const T& value, ::std::ostream* os) {
1578 matcher.ExplainMatchResultTo(
1579 typename ::testing::internal::is_pointer<T>::type(), value, os);
shiqiane35fdd92008-12-10 05:08:54 +00001580}
1581
1582// Type traits specifying various features of different functors for ResultOf.
1583// The default template specifies features for functor objects.
1584// Functor classes have to typedef argument_type and result_type
1585// to be compatible with ResultOf.
1586template <typename Functor>
1587struct CallableTraits {
1588 typedef typename Functor::result_type ResultType;
1589 typedef Functor StorageType;
1590
1591 static void CheckIsValid(Functor functor) {}
1592 template <typename T>
1593 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1594};
1595
1596// Specialization for function pointers.
1597template <typename ArgType, typename ResType>
1598struct CallableTraits<ResType(*)(ArgType)> {
1599 typedef ResType ResultType;
1600 typedef ResType(*StorageType)(ArgType);
1601
1602 static void CheckIsValid(ResType(*f)(ArgType)) {
1603 GMOCK_CHECK_(f != NULL)
1604 << "NULL function pointer is passed into ResultOf().";
1605 }
1606 template <typename T>
1607 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1608 return (*f)(arg);
1609 }
1610};
1611
1612// Implements the ResultOf() matcher for matching a return value of a
1613// unary function of an object.
1614template <typename Callable>
1615class ResultOfMatcher {
1616 public:
1617 typedef typename CallableTraits<Callable>::ResultType ResultType;
1618
1619 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1620 : callable_(callable), matcher_(matcher) {
1621 CallableTraits<Callable>::CheckIsValid(callable_);
1622 }
1623
1624 template <typename T>
1625 operator Matcher<T>() const {
1626 return Matcher<T>(new Impl<T>(callable_, matcher_));
1627 }
1628
1629 private:
1630 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1631
1632 template <typename T>
1633 class Impl : public MatcherInterface<T> {
1634 public:
1635 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1636 : callable_(callable), matcher_(matcher) {}
1637 // Returns true iff callable_(obj) matches the inner matcher.
1638 // The calling syntax is different for different types of callables
1639 // so we abstract it in CallableTraits<Callable>::Invoke().
1640 virtual bool Matches(T obj) const {
1641 return matcher_.Matches(
1642 CallableTraits<Callable>::template Invoke<T>(callable_, obj));
1643 }
1644
1645 virtual void DescribeTo(::std::ostream* os) const {
1646 *os << "result of the given callable ";
1647 matcher_.DescribeTo(os);
1648 }
1649
1650 virtual void DescribeNegationTo(::std::ostream* os) const {
1651 *os << "result of the given callable ";
1652 matcher_.DescribeNegationTo(os);
1653 }
1654
1655 virtual void ExplainMatchResultTo(T obj, ::std::ostream* os) const {
1656 ::std::stringstream ss;
1657 matcher_.ExplainMatchResultTo(
1658 CallableTraits<Callable>::template Invoke<T>(callable_, obj),
1659 &ss);
1660 const internal::string s = ss.str();
1661 if (s != "")
1662 *os << "result of the given callable " << s;
1663 }
1664 private:
1665 // Functors often define operator() as non-const method even though
1666 // they are actualy stateless. But we need to use them even when
1667 // 'this' is a const pointer. It's the user's responsibility not to
1668 // use stateful callables with ResultOf(), which does't guarantee
1669 // how many times the callable will be invoked.
1670 mutable CallableStorageType callable_;
1671 const Matcher<ResultType> matcher_;
1672 }; // class Impl
1673
1674 const CallableStorageType callable_;
1675 const Matcher<ResultType> matcher_;
1676};
1677
1678// Explains the result of matching a value against a functor matcher.
1679template <typename T, typename Callable>
1680void ExplainMatchResultTo(const ResultOfMatcher<Callable>& matcher,
1681 T obj, ::std::ostream* os) {
1682 matcher.ExplainMatchResultTo(obj, os);
1683}
1684
zhanyong.wan6a896b52009-01-16 01:13:50 +00001685// Implements an equality matcher for any STL-style container whose elements
1686// support ==. This matcher is like Eq(), but its failure explanations provide
1687// more detailed information that is useful when the container is used as a set.
1688// The failure message reports elements that are in one of the operands but not
1689// the other. The failure messages do not report duplicate or out-of-order
1690// elements in the containers (which don't properly matter to sets, but can
1691// occur if the containers are vectors or lists, for example).
1692//
1693// Uses the container's const_iterator, value_type, operator ==,
1694// begin(), and end().
1695template <typename Container>
1696class ContainerEqMatcher {
1697 public:
1698 explicit ContainerEqMatcher(const Container& rhs) : rhs_(rhs) {}
1699 bool Matches(const Container& lhs) const { return lhs == rhs_; }
1700 void DescribeTo(::std::ostream* os) const {
1701 *os << "equals ";
1702 UniversalPrinter<Container>::Print(rhs_, os);
1703 }
1704 void DescribeNegationTo(::std::ostream* os) const {
1705 *os << "does not equal ";
1706 UniversalPrinter<Container>::Print(rhs_, os);
1707 }
1708
1709 void ExplainMatchResultTo(const Container& lhs,
1710 ::std::ostream* os) const {
1711 // Something is different. Check for missing values first.
1712 bool printed_header = false;
1713 for (typename Container::const_iterator it = lhs.begin();
1714 it != lhs.end(); ++it) {
1715 if (std::find(rhs_.begin(), rhs_.end(), *it) == rhs_.end()) {
1716 if (printed_header) {
1717 *os << ", ";
1718 } else {
1719 *os << "Only in actual: ";
1720 printed_header = true;
1721 }
1722 UniversalPrinter<typename Container::value_type>::Print(*it, os);
1723 }
1724 }
1725
1726 // Now check for extra values.
1727 bool printed_header2 = false;
1728 for (typename Container::const_iterator it = rhs_.begin();
1729 it != rhs_.end(); ++it) {
1730 if (std::find(lhs.begin(), lhs.end(), *it) == lhs.end()) {
1731 if (printed_header2) {
1732 *os << ", ";
1733 } else {
1734 *os << (printed_header ? "; not" : "Not") << " in actual: ";
1735 printed_header2 = true;
1736 }
1737 UniversalPrinter<typename Container::value_type>::Print(*it, os);
1738 }
1739 }
1740 }
1741 private:
1742 const Container rhs_;
1743};
1744
1745template <typename Container>
1746void ExplainMatchResultTo(const ContainerEqMatcher<Container>& matcher,
1747 const Container& lhs,
1748 ::std::ostream* os) {
1749 matcher.ExplainMatchResultTo(lhs, os);
1750}
1751
shiqiane35fdd92008-12-10 05:08:54 +00001752} // namespace internal
1753
1754// Implements MatcherCast().
1755template <typename T, typename M>
1756inline Matcher<T> MatcherCast(M matcher) {
1757 return internal::MatcherCastImpl<T, M>::Cast(matcher);
1758}
1759
1760// _ is a matcher that matches anything of any type.
1761//
1762// This definition is fine as:
1763//
1764// 1. The C++ standard permits using the name _ in a namespace that
1765// is not the global namespace or ::std.
1766// 2. The AnythingMatcher class has no data member or constructor,
1767// so it's OK to create global variables of this type.
1768// 3. c-style has approved of using _ in this case.
1769const internal::AnythingMatcher _ = {};
1770// Creates a matcher that matches any value of the given type T.
1771template <typename T>
1772inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
1773
1774// Creates a matcher that matches any value of the given type T.
1775template <typename T>
1776inline Matcher<T> An() { return A<T>(); }
1777
1778// Creates a polymorphic matcher that matches anything equal to x.
1779// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
1780// wouldn't compile.
1781template <typename T>
1782inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
1783
1784// Constructs a Matcher<T> from a 'value' of type T. The constructed
1785// matcher matches any value that's equal to 'value'.
1786template <typename T>
1787Matcher<T>::Matcher(T value) { *this = Eq(value); }
1788
1789// Creates a monomorphic matcher that matches anything with type Lhs
1790// and equal to rhs. A user may need to use this instead of Eq(...)
1791// in order to resolve an overloading ambiguity.
1792//
1793// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
1794// or Matcher<T>(x), but more readable than the latter.
1795//
1796// We could define similar monomorphic matchers for other comparison
1797// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
1798// it yet as those are used much less than Eq() in practice. A user
1799// can always write Matcher<T>(Lt(5)) to be explicit about the type,
1800// for example.
1801template <typename Lhs, typename Rhs>
1802inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
1803
1804// Creates a polymorphic matcher that matches anything >= x.
1805template <typename Rhs>
1806inline internal::GeMatcher<Rhs> Ge(Rhs x) {
1807 return internal::GeMatcher<Rhs>(x);
1808}
1809
1810// Creates a polymorphic matcher that matches anything > x.
1811template <typename Rhs>
1812inline internal::GtMatcher<Rhs> Gt(Rhs x) {
1813 return internal::GtMatcher<Rhs>(x);
1814}
1815
1816// Creates a polymorphic matcher that matches anything <= x.
1817template <typename Rhs>
1818inline internal::LeMatcher<Rhs> Le(Rhs x) {
1819 return internal::LeMatcher<Rhs>(x);
1820}
1821
1822// Creates a polymorphic matcher that matches anything < x.
1823template <typename Rhs>
1824inline internal::LtMatcher<Rhs> Lt(Rhs x) {
1825 return internal::LtMatcher<Rhs>(x);
1826}
1827
1828// Creates a polymorphic matcher that matches anything != x.
1829template <typename Rhs>
1830inline internal::NeMatcher<Rhs> Ne(Rhs x) {
1831 return internal::NeMatcher<Rhs>(x);
1832}
1833
1834// Creates a polymorphic matcher that matches any non-NULL pointer.
1835// This is convenient as Not(NULL) doesn't compile (the compiler
1836// thinks that that expression is comparing a pointer with an integer).
1837inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
1838 return MakePolymorphicMatcher(internal::NotNullMatcher());
1839}
1840
1841// Creates a polymorphic matcher that matches any argument that
1842// references variable x.
1843template <typename T>
1844inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
1845 return internal::RefMatcher<T&>(x);
1846}
1847
1848// Creates a matcher that matches any double argument approximately
1849// equal to rhs, where two NANs are considered unequal.
1850inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
1851 return internal::FloatingEqMatcher<double>(rhs, false);
1852}
1853
1854// Creates a matcher that matches any double argument approximately
1855// equal to rhs, including NaN values when rhs is NaN.
1856inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
1857 return internal::FloatingEqMatcher<double>(rhs, true);
1858}
1859
1860// Creates a matcher that matches any float argument approximately
1861// equal to rhs, where two NANs are considered unequal.
1862inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
1863 return internal::FloatingEqMatcher<float>(rhs, false);
1864}
1865
1866// Creates a matcher that matches any double argument approximately
1867// equal to rhs, including NaN values when rhs is NaN.
1868inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
1869 return internal::FloatingEqMatcher<float>(rhs, true);
1870}
1871
1872// Creates a matcher that matches a pointer (raw or smart) that points
1873// to a value that matches inner_matcher.
1874template <typename InnerMatcher>
1875inline internal::PointeeMatcher<InnerMatcher> Pointee(
1876 const InnerMatcher& inner_matcher) {
1877 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
1878}
1879
1880// Creates a matcher that matches an object whose given field matches
1881// 'matcher'. For example,
1882// Field(&Foo::number, Ge(5))
1883// matches a Foo object x iff x.number >= 5.
1884template <typename Class, typename FieldType, typename FieldMatcher>
1885inline PolymorphicMatcher<
1886 internal::FieldMatcher<Class, FieldType> > Field(
1887 FieldType Class::*field, const FieldMatcher& matcher) {
1888 return MakePolymorphicMatcher(
1889 internal::FieldMatcher<Class, FieldType>(
1890 field, MatcherCast<const FieldType&>(matcher)));
1891 // The call to MatcherCast() is required for supporting inner
1892 // matchers of compatible types. For example, it allows
1893 // Field(&Foo::bar, m)
1894 // to compile where bar is an int32 and m is a matcher for int64.
1895}
1896
1897// Creates a matcher that matches an object whose given property
1898// matches 'matcher'. For example,
1899// Property(&Foo::str, StartsWith("hi"))
1900// matches a Foo object x iff x.str() starts with "hi".
1901template <typename Class, typename PropertyType, typename PropertyMatcher>
1902inline PolymorphicMatcher<
1903 internal::PropertyMatcher<Class, PropertyType> > Property(
1904 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
1905 return MakePolymorphicMatcher(
1906 internal::PropertyMatcher<Class, PropertyType>(
1907 property,
zhanyong.wane0d051e2009-02-19 00:33:37 +00001908 MatcherCast<GMOCK_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00001909 // The call to MatcherCast() is required for supporting inner
1910 // matchers of compatible types. For example, it allows
1911 // Property(&Foo::bar, m)
1912 // to compile where bar() returns an int32 and m is a matcher for int64.
1913}
1914
1915// Creates a matcher that matches an object iff the result of applying
1916// a callable to x matches 'matcher'.
1917// For example,
1918// ResultOf(f, StartsWith("hi"))
1919// matches a Foo object x iff f(x) starts with "hi".
1920// callable parameter can be a function, function pointer, or a functor.
1921// Callable has to satisfy the following conditions:
1922// * It is required to keep no state affecting the results of
1923// the calls on it and make no assumptions about how many calls
1924// will be made. Any state it keeps must be protected from the
1925// concurrent access.
1926// * If it is a function object, it has to define type result_type.
1927// We recommend deriving your functor classes from std::unary_function.
1928template <typename Callable, typename ResultOfMatcher>
1929internal::ResultOfMatcher<Callable> ResultOf(
1930 Callable callable, const ResultOfMatcher& matcher) {
1931 return internal::ResultOfMatcher<Callable>(
1932 callable,
1933 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
1934 matcher));
1935 // The call to MatcherCast() is required for supporting inner
1936 // matchers of compatible types. For example, it allows
1937 // ResultOf(Function, m)
1938 // to compile where Function() returns an int32 and m is a matcher for int64.
1939}
1940
1941// String matchers.
1942
1943// Matches a string equal to str.
1944inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
1945 StrEq(const internal::string& str) {
1946 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
1947 str, true, true));
1948}
1949
1950// Matches a string not equal to str.
1951inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
1952 StrNe(const internal::string& str) {
1953 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
1954 str, false, true));
1955}
1956
1957// Matches a string equal to str, ignoring case.
1958inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
1959 StrCaseEq(const internal::string& str) {
1960 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
1961 str, true, false));
1962}
1963
1964// Matches a string not equal to str, ignoring case.
1965inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
1966 StrCaseNe(const internal::string& str) {
1967 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
1968 str, false, false));
1969}
1970
1971// Creates a matcher that matches any string, std::string, or C string
1972// that contains the given substring.
1973inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
1974 HasSubstr(const internal::string& substring) {
1975 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
1976 substring));
1977}
1978
1979// Matches a string that starts with 'prefix' (case-sensitive).
1980inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
1981 StartsWith(const internal::string& prefix) {
1982 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
1983 prefix));
1984}
1985
1986// Matches a string that ends with 'suffix' (case-sensitive).
1987inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
1988 EndsWith(const internal::string& suffix) {
1989 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
1990 suffix));
1991}
1992
1993#ifdef GMOCK_HAS_REGEX
1994
1995// Matches a string that fully matches regular expression 'regex'.
1996// The matcher takes ownership of 'regex'.
1997inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
1998 const internal::RE* regex) {
1999 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2000}
2001inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2002 const internal::string& regex) {
2003 return MatchesRegex(new internal::RE(regex));
2004}
2005
2006// Matches a string that contains regular expression 'regex'.
2007// The matcher takes ownership of 'regex'.
2008inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2009 const internal::RE* regex) {
2010 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2011}
2012inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2013 const internal::string& regex) {
2014 return ContainsRegex(new internal::RE(regex));
2015}
2016
2017#endif // GMOCK_HAS_REGEX
2018
2019#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2020// Wide string matchers.
2021
2022// Matches a string equal to str.
2023inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2024 StrEq(const internal::wstring& str) {
2025 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2026 str, true, true));
2027}
2028
2029// Matches a string not equal to str.
2030inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2031 StrNe(const internal::wstring& str) {
2032 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2033 str, false, true));
2034}
2035
2036// Matches a string equal to str, ignoring case.
2037inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2038 StrCaseEq(const internal::wstring& str) {
2039 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2040 str, true, false));
2041}
2042
2043// Matches a string not equal to str, ignoring case.
2044inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2045 StrCaseNe(const internal::wstring& str) {
2046 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2047 str, false, false));
2048}
2049
2050// Creates a matcher that matches any wstring, std::wstring, or C wide string
2051// that contains the given substring.
2052inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2053 HasSubstr(const internal::wstring& substring) {
2054 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2055 substring));
2056}
2057
2058// Matches a string that starts with 'prefix' (case-sensitive).
2059inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2060 StartsWith(const internal::wstring& prefix) {
2061 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2062 prefix));
2063}
2064
2065// Matches a string that ends with 'suffix' (case-sensitive).
2066inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2067 EndsWith(const internal::wstring& suffix) {
2068 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2069 suffix));
2070}
2071
2072#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2073
2074// Creates a polymorphic matcher that matches a 2-tuple where the
2075// first field == the second field.
2076inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2077
2078// Creates a polymorphic matcher that matches a 2-tuple where the
2079// first field >= the second field.
2080inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2081
2082// Creates a polymorphic matcher that matches a 2-tuple where the
2083// first field > the second field.
2084inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2085
2086// Creates a polymorphic matcher that matches a 2-tuple where the
2087// first field <= the second field.
2088inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2089
2090// Creates a polymorphic matcher that matches a 2-tuple where the
2091// first field < the second field.
2092inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2093
2094// Creates a polymorphic matcher that matches a 2-tuple where the
2095// first field != the second field.
2096inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2097
2098// Creates a matcher that matches any value of type T that m doesn't
2099// match.
2100template <typename InnerMatcher>
2101inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2102 return internal::NotMatcher<InnerMatcher>(m);
2103}
2104
2105// Creates a matcher that matches any value that matches all of the
2106// given matchers.
2107//
2108// For now we only support up to 5 matchers. Support for more
2109// matchers can be added as needed, or the user can use nested
2110// AllOf()s.
2111template <typename Matcher1, typename Matcher2>
2112inline internal::BothOfMatcher<Matcher1, Matcher2>
2113AllOf(Matcher1 m1, Matcher2 m2) {
2114 return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2);
2115}
2116
2117template <typename Matcher1, typename Matcher2, typename Matcher3>
2118inline internal::BothOfMatcher<Matcher1,
2119 internal::BothOfMatcher<Matcher2, Matcher3> >
2120AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2121 return AllOf(m1, AllOf(m2, m3));
2122}
2123
2124template <typename Matcher1, typename Matcher2, typename Matcher3,
2125 typename Matcher4>
2126inline internal::BothOfMatcher<Matcher1,
2127 internal::BothOfMatcher<Matcher2,
2128 internal::BothOfMatcher<Matcher3, Matcher4> > >
2129AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2130 return AllOf(m1, AllOf(m2, m3, m4));
2131}
2132
2133template <typename Matcher1, typename Matcher2, typename Matcher3,
2134 typename Matcher4, typename Matcher5>
2135inline internal::BothOfMatcher<Matcher1,
2136 internal::BothOfMatcher<Matcher2,
2137 internal::BothOfMatcher<Matcher3,
2138 internal::BothOfMatcher<Matcher4, Matcher5> > > >
2139AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2140 return AllOf(m1, AllOf(m2, m3, m4, m5));
2141}
2142
2143// Creates a matcher that matches any value that matches at least one
2144// of the given matchers.
2145//
2146// For now we only support up to 5 matchers. Support for more
2147// matchers can be added as needed, or the user can use nested
2148// AnyOf()s.
2149template <typename Matcher1, typename Matcher2>
2150inline internal::EitherOfMatcher<Matcher1, Matcher2>
2151AnyOf(Matcher1 m1, Matcher2 m2) {
2152 return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2);
2153}
2154
2155template <typename Matcher1, typename Matcher2, typename Matcher3>
2156inline internal::EitherOfMatcher<Matcher1,
2157 internal::EitherOfMatcher<Matcher2, Matcher3> >
2158AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2159 return AnyOf(m1, AnyOf(m2, m3));
2160}
2161
2162template <typename Matcher1, typename Matcher2, typename Matcher3,
2163 typename Matcher4>
2164inline internal::EitherOfMatcher<Matcher1,
2165 internal::EitherOfMatcher<Matcher2,
2166 internal::EitherOfMatcher<Matcher3, Matcher4> > >
2167AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2168 return AnyOf(m1, AnyOf(m2, m3, m4));
2169}
2170
2171template <typename Matcher1, typename Matcher2, typename Matcher3,
2172 typename Matcher4, typename Matcher5>
2173inline internal::EitherOfMatcher<Matcher1,
2174 internal::EitherOfMatcher<Matcher2,
2175 internal::EitherOfMatcher<Matcher3,
2176 internal::EitherOfMatcher<Matcher4, Matcher5> > > >
2177AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2178 return AnyOf(m1, AnyOf(m2, m3, m4, m5));
2179}
2180
2181// Returns a matcher that matches anything that satisfies the given
2182// predicate. The predicate can be any unary function or functor
2183// whose return type can be implicitly converted to bool.
2184template <typename Predicate>
2185inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
2186Truly(Predicate pred) {
2187 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
2188}
2189
zhanyong.wan6a896b52009-01-16 01:13:50 +00002190// Returns a matcher that matches an equal container.
2191// This matcher behaves like Eq(), but in the event of mismatch lists the
2192// values that are included in one container but not the other. (Duplicate
2193// values and order differences are not explained.)
2194template <typename Container>
2195inline PolymorphicMatcher<internal::ContainerEqMatcher<Container> >
2196 ContainerEq(const Container& rhs) {
2197 return MakePolymorphicMatcher(internal::ContainerEqMatcher<Container>(rhs));
2198}
2199
shiqiane35fdd92008-12-10 05:08:54 +00002200// Returns a predicate that is satisfied by anything that matches the
2201// given matcher.
2202template <typename M>
2203inline internal::MatcherAsPredicate<M> Matches(M matcher) {
2204 return internal::MatcherAsPredicate<M>(matcher);
2205}
2206
2207// These macros allow using matchers to check values in Google Test
2208// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
2209// succeed iff the value matches the matcher. If the assertion fails,
2210// the value and the description of the matcher will be printed.
2211#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
2212 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2213#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
2214 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2215
2216} // namespace testing
2217
2218#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_