blob: f764344d4c9429cfc34ecf7eb8247342186b59c4 [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
174 // Implicit constructor here allows ipeople to write
175 // 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
313// A<T>() returns a matcher that matches any value of type T.
314template <typename T>
315Matcher<T> A();
316
317// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
318// and MUST NOT BE USED IN USER CODE!!!
319namespace internal {
320
321// Appends the explanation on the result of matcher.Matches(value) to
322// os iff the explanation is not empty.
323template <typename T>
324void ExplainMatchResultAsNeededTo(const Matcher<T>& matcher, T value,
325 ::std::ostream* os) {
326 ::std::stringstream reason;
327 matcher.ExplainMatchResultTo(value, &reason);
328 const internal::string s = reason.str();
329 if (s != "") {
330 *os << " (" << s << ")";
331 }
332}
333
334// An internal helper class for doing compile-time loop on a tuple's
335// fields.
336template <size_t N>
337class TuplePrefix {
338 public:
339 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
340 // iff the first N fields of matcher_tuple matches the first N
341 // fields of value_tuple, respectively.
342 template <typename MatcherTuple, typename ValueTuple>
343 static bool Matches(const MatcherTuple& matcher_tuple,
344 const ValueTuple& value_tuple) {
345 using ::std::tr1::get;
346 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
347 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
348 }
349
350 // TuplePrefix<N>::DescribeMatchFailuresTo(matchers, values, os)
351 // describes failures in matching the first N fields of matchers
352 // against the first N fields of values. If there is no failure,
353 // nothing will be streamed to os.
354 template <typename MatcherTuple, typename ValueTuple>
355 static void DescribeMatchFailuresTo(const MatcherTuple& matchers,
356 const ValueTuple& values,
357 ::std::ostream* os) {
358 using ::std::tr1::tuple_element;
359 using ::std::tr1::get;
360
361 // First, describes failures in the first N - 1 fields.
362 TuplePrefix<N - 1>::DescribeMatchFailuresTo(matchers, values, os);
363
364 // Then describes the failure (if any) in the (N - 1)-th (0-based)
365 // field.
366 typename tuple_element<N - 1, MatcherTuple>::type matcher =
367 get<N - 1>(matchers);
368 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
369 Value value = get<N - 1>(values);
370 if (!matcher.Matches(value)) {
371 // TODO(wan): include in the message the name of the parameter
372 // as used in MOCK_METHOD*() when possible.
373 *os << " Expected arg #" << N - 1 << ": ";
374 get<N - 1>(matchers).DescribeTo(os);
375 *os << "\n Actual: ";
376 // We remove the reference in type Value to prevent the
377 // universal printer from printing the address of value, which
378 // isn't interesting to the user most of the time. The
379 // matcher's ExplainMatchResultTo() method handles the case when
380 // the address is interesting.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000381 internal::UniversalPrinter<GMOCK_REMOVE_REFERENCE_(Value)>::
shiqiane35fdd92008-12-10 05:08:54 +0000382 Print(value, os);
383 ExplainMatchResultAsNeededTo<Value>(matcher, value, os);
384 *os << "\n";
385 }
386 }
387};
388
389// The base case.
390template <>
391class TuplePrefix<0> {
392 public:
393 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000394 static bool Matches(const MatcherTuple& /* matcher_tuple */,
395 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000396 return true;
397 }
398
399 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000400 static void DescribeMatchFailuresTo(const MatcherTuple& /* matchers */,
401 const ValueTuple& /* values */,
402 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000403};
404
405// TupleMatches(matcher_tuple, value_tuple) returns true iff all
406// matchers in matcher_tuple match the corresponding fields in
407// value_tuple. It is a compiler error if matcher_tuple and
408// value_tuple have different number of fields or incompatible field
409// types.
410template <typename MatcherTuple, typename ValueTuple>
411bool TupleMatches(const MatcherTuple& matcher_tuple,
412 const ValueTuple& value_tuple) {
413 using ::std::tr1::tuple_size;
414 // Makes sure that matcher_tuple and value_tuple have the same
415 // number of fields.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000416 GMOCK_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
417 tuple_size<ValueTuple>::value,
418 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000419 return TuplePrefix<tuple_size<ValueTuple>::value>::
420 Matches(matcher_tuple, value_tuple);
421}
422
423// Describes failures in matching matchers against values. If there
424// is no failure, nothing will be streamed to os.
425template <typename MatcherTuple, typename ValueTuple>
426void DescribeMatchFailureTupleTo(const MatcherTuple& matchers,
427 const ValueTuple& values,
428 ::std::ostream* os) {
429 using ::std::tr1::tuple_size;
430 TuplePrefix<tuple_size<MatcherTuple>::value>::DescribeMatchFailuresTo(
431 matchers, values, os);
432}
433
434// The MatcherCastImpl class template is a helper for implementing
435// MatcherCast(). We need this helper in order to partially
436// specialize the implementation of MatcherCast() (C++ allows
437// class/struct templates to be partially specialized, but not
438// function templates.).
439
440// This general version is used when MatcherCast()'s argument is a
441// polymorphic matcher (i.e. something that can be converted to a
442// Matcher but is not one yet; for example, Eq(value)).
443template <typename T, typename M>
444class MatcherCastImpl {
445 public:
446 static Matcher<T> Cast(M polymorphic_matcher) {
447 return Matcher<T>(polymorphic_matcher);
448 }
449};
450
451// This more specialized version is used when MatcherCast()'s argument
452// is already a Matcher. This only compiles when type T can be
453// statically converted to type U.
454template <typename T, typename U>
455class MatcherCastImpl<T, Matcher<U> > {
456 public:
457 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
458 return Matcher<T>(new Impl(source_matcher));
459 }
460 private:
461 class Impl : public MatcherInterface<T> {
462 public:
463 explicit Impl(const Matcher<U>& source_matcher)
464 : source_matcher_(source_matcher) {}
465
466 // We delegate the matching logic to the source matcher.
467 virtual bool Matches(T x) const {
468 return source_matcher_.Matches(static_cast<U>(x));
469 }
470
471 virtual void DescribeTo(::std::ostream* os) const {
472 source_matcher_.DescribeTo(os);
473 }
474
475 virtual void DescribeNegationTo(::std::ostream* os) const {
476 source_matcher_.DescribeNegationTo(os);
477 }
478
479 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
480 source_matcher_.ExplainMatchResultTo(static_cast<U>(x), os);
481 }
482 private:
483 const Matcher<U> source_matcher_;
484 };
485};
486
487// This even more specialized version is used for efficiently casting
488// a matcher to its own type.
489template <typename T>
490class MatcherCastImpl<T, Matcher<T> > {
491 public:
492 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
493};
494
495// Implements A<T>().
496template <typename T>
497class AnyMatcherImpl : public MatcherInterface<T> {
498 public:
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000499 virtual bool Matches(T /* x */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000500 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
501 virtual void DescribeNegationTo(::std::ostream* os) const {
502 // This is mostly for completeness' safe, as it's not very useful
503 // to write Not(A<bool>()). However we cannot completely rule out
504 // such a possibility, and it doesn't hurt to be prepared.
505 *os << "never matches";
506 }
507};
508
509// Implements _, a matcher that matches any value of any
510// type. This is a polymorphic matcher, so we need a template type
511// conversion operator to make it appearing as a Matcher<T> for any
512// type T.
513class AnythingMatcher {
514 public:
515 template <typename T>
516 operator Matcher<T>() const { return A<T>(); }
517};
518
519// Implements a matcher that compares a given value with a
520// pre-supplied value using one of the ==, <=, <, etc, operators. The
521// two values being compared don't have to have the same type.
522//
523// The matcher defined here is polymorphic (for example, Eq(5) can be
524// used to match an int, a short, a double, etc). Therefore we use
525// a template type conversion operator in the implementation.
526//
527// We define this as a macro in order to eliminate duplicated source
528// code.
529//
530// The following template definition assumes that the Rhs parameter is
531// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wane0d051e2009-02-19 00:33:37 +0000532#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000533 template <typename Rhs> class name##Matcher { \
534 public: \
535 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
536 template <typename Lhs> \
537 operator Matcher<Lhs>() const { \
538 return MakeMatcher(new Impl<Lhs>(rhs_)); \
539 } \
540 private: \
541 template <typename Lhs> \
542 class Impl : public MatcherInterface<Lhs> { \
543 public: \
544 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
545 virtual bool Matches(Lhs lhs) const { return lhs op rhs_; } \
546 virtual void DescribeTo(::std::ostream* os) const { \
547 *os << "is " relation " "; \
548 UniversalPrinter<Rhs>::Print(rhs_, os); \
549 } \
550 virtual void DescribeNegationTo(::std::ostream* os) const { \
551 *os << "is not " relation " "; \
552 UniversalPrinter<Rhs>::Print(rhs_, os); \
553 } \
554 private: \
555 Rhs rhs_; \
556 }; \
557 Rhs rhs_; \
558 }
559
560// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
561// respectively.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000562GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "equal to");
563GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "greater than or equal to");
564GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "greater than");
565GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "less than or equal to");
566GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "less than");
567GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "not equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000568
zhanyong.wane0d051e2009-02-19 00:33:37 +0000569#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000570
571// Implements the polymorphic NotNull() matcher, which matches any
572// pointer that is not NULL.
573class NotNullMatcher {
574 public:
575 template <typename T>
576 bool Matches(T* p) const { return p != NULL; }
577
578 void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; }
579 void DescribeNegationTo(::std::ostream* os) const {
580 *os << "is NULL";
581 }
582};
583
584// Ref(variable) matches any argument that is a reference to
585// 'variable'. This matcher is polymorphic as it can match any
586// super type of the type of 'variable'.
587//
588// The RefMatcher template class implements Ref(variable). It can
589// only be instantiated with a reference type. This prevents a user
590// from mistakenly using Ref(x) to match a non-reference function
591// argument. For example, the following will righteously cause a
592// compiler error:
593//
594// int n;
595// Matcher<int> m1 = Ref(n); // This won't compile.
596// Matcher<int&> m2 = Ref(n); // This will compile.
597template <typename T>
598class RefMatcher;
599
600template <typename T>
601class RefMatcher<T&> {
602 // Google Mock is a generic framework and thus needs to support
603 // mocking any function types, including those that take non-const
604 // reference arguments. Therefore the template parameter T (and
605 // Super below) can be instantiated to either a const type or a
606 // non-const type.
607 public:
608 // RefMatcher() takes a T& instead of const T&, as we want the
609 // compiler to catch using Ref(const_value) as a matcher for a
610 // non-const reference.
611 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
612
613 template <typename Super>
614 operator Matcher<Super&>() const {
615 // By passing object_ (type T&) to Impl(), which expects a Super&,
616 // we make sure that Super is a super type of T. In particular,
617 // this catches using Ref(const_value) as a matcher for a
618 // non-const reference, as you cannot implicitly convert a const
619 // reference to a non-const reference.
620 return MakeMatcher(new Impl<Super>(object_));
621 }
622 private:
623 template <typename Super>
624 class Impl : public MatcherInterface<Super&> {
625 public:
626 explicit Impl(Super& x) : object_(x) {} // NOLINT
627
628 // Matches() takes a Super& (as opposed to const Super&) in
629 // order to match the interface MatcherInterface<Super&>.
630 virtual bool Matches(Super& x) const { return &x == &object_; } // NOLINT
631
632 virtual void DescribeTo(::std::ostream* os) const {
633 *os << "references the variable ";
634 UniversalPrinter<Super&>::Print(object_, os);
635 }
636
637 virtual void DescribeNegationTo(::std::ostream* os) const {
638 *os << "does not reference the variable ";
639 UniversalPrinter<Super&>::Print(object_, os);
640 }
641
642 virtual void ExplainMatchResultTo(Super& x, // NOLINT
643 ::std::ostream* os) const {
644 *os << "is located @" << static_cast<const void*>(&x);
645 }
646 private:
647 const Super& object_;
648 };
649
650 T& object_;
651};
652
653// Polymorphic helper functions for narrow and wide string matchers.
654inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
655 return String::CaseInsensitiveCStringEquals(lhs, rhs);
656}
657
658inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
659 const wchar_t* rhs) {
660 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
661}
662
663// String comparison for narrow or wide strings that can have embedded NUL
664// characters.
665template <typename StringType>
666bool CaseInsensitiveStringEquals(const StringType& s1,
667 const StringType& s2) {
668 // Are the heads equal?
669 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
670 return false;
671 }
672
673 // Skip the equal heads.
674 const typename StringType::value_type nul = 0;
675 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
676
677 // Are we at the end of either s1 or s2?
678 if (i1 == StringType::npos || i2 == StringType::npos) {
679 return i1 == i2;
680 }
681
682 // Are the tails equal?
683 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
684}
685
686// String matchers.
687
688// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
689template <typename StringType>
690class StrEqualityMatcher {
691 public:
692 typedef typename StringType::const_pointer ConstCharPointer;
693
694 StrEqualityMatcher(const StringType& str, bool expect_eq,
695 bool case_sensitive)
696 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
697
698 // When expect_eq_ is true, returns true iff s is equal to string_;
699 // otherwise returns true iff s is not equal to string_.
700 bool Matches(ConstCharPointer s) const {
701 if (s == NULL) {
702 return !expect_eq_;
703 }
704 return Matches(StringType(s));
705 }
706
707 bool Matches(const StringType& s) const {
708 const bool eq = case_sensitive_ ? s == string_ :
709 CaseInsensitiveStringEquals(s, string_);
710 return expect_eq_ == eq;
711 }
712
713 void DescribeTo(::std::ostream* os) const {
714 DescribeToHelper(expect_eq_, os);
715 }
716
717 void DescribeNegationTo(::std::ostream* os) const {
718 DescribeToHelper(!expect_eq_, os);
719 }
720 private:
721 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
722 *os << "is ";
723 if (!expect_eq) {
724 *os << "not ";
725 }
726 *os << "equal to ";
727 if (!case_sensitive_) {
728 *os << "(ignoring case) ";
729 }
730 UniversalPrinter<StringType>::Print(string_, os);
731 }
732
733 const StringType string_;
734 const bool expect_eq_;
735 const bool case_sensitive_;
736};
737
738// Implements the polymorphic HasSubstr(substring) matcher, which
739// can be used as a Matcher<T> as long as T can be converted to a
740// string.
741template <typename StringType>
742class HasSubstrMatcher {
743 public:
744 typedef typename StringType::const_pointer ConstCharPointer;
745
746 explicit HasSubstrMatcher(const StringType& substring)
747 : substring_(substring) {}
748
749 // These overloaded methods allow HasSubstr(substring) to be used as a
750 // Matcher<T> as long as T can be converted to string. Returns true
751 // iff s contains substring_ as a substring.
752 bool Matches(ConstCharPointer s) const {
753 return s != NULL && Matches(StringType(s));
754 }
755
756 bool Matches(const StringType& s) const {
757 return s.find(substring_) != StringType::npos;
758 }
759
760 // Describes what this matcher matches.
761 void DescribeTo(::std::ostream* os) const {
762 *os << "has substring ";
763 UniversalPrinter<StringType>::Print(substring_, os);
764 }
765
766 void DescribeNegationTo(::std::ostream* os) const {
767 *os << "has no substring ";
768 UniversalPrinter<StringType>::Print(substring_, os);
769 }
770 private:
771 const StringType substring_;
772};
773
774// Implements the polymorphic StartsWith(substring) matcher, which
775// can be used as a Matcher<T> as long as T can be converted to a
776// string.
777template <typename StringType>
778class StartsWithMatcher {
779 public:
780 typedef typename StringType::const_pointer ConstCharPointer;
781
782 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
783 }
784
785 // These overloaded methods allow StartsWith(prefix) to be used as a
786 // Matcher<T> as long as T can be converted to string. Returns true
787 // iff s starts with prefix_.
788 bool Matches(ConstCharPointer s) const {
789 return s != NULL && Matches(StringType(s));
790 }
791
792 bool Matches(const StringType& s) const {
793 return s.length() >= prefix_.length() &&
794 s.substr(0, prefix_.length()) == prefix_;
795 }
796
797 void DescribeTo(::std::ostream* os) const {
798 *os << "starts with ";
799 UniversalPrinter<StringType>::Print(prefix_, os);
800 }
801
802 void DescribeNegationTo(::std::ostream* os) const {
803 *os << "doesn't start with ";
804 UniversalPrinter<StringType>::Print(prefix_, os);
805 }
806 private:
807 const StringType prefix_;
808};
809
810// Implements the polymorphic EndsWith(substring) matcher, which
811// can be used as a Matcher<T> as long as T can be converted to a
812// string.
813template <typename StringType>
814class EndsWithMatcher {
815 public:
816 typedef typename StringType::const_pointer ConstCharPointer;
817
818 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
819
820 // These overloaded methods allow EndsWith(suffix) to be used as a
821 // Matcher<T> as long as T can be converted to string. Returns true
822 // iff s ends with suffix_.
823 bool Matches(ConstCharPointer s) const {
824 return s != NULL && Matches(StringType(s));
825 }
826
827 bool Matches(const StringType& s) const {
828 return s.length() >= suffix_.length() &&
829 s.substr(s.length() - suffix_.length()) == suffix_;
830 }
831
832 void DescribeTo(::std::ostream* os) const {
833 *os << "ends with ";
834 UniversalPrinter<StringType>::Print(suffix_, os);
835 }
836
837 void DescribeNegationTo(::std::ostream* os) const {
838 *os << "doesn't end with ";
839 UniversalPrinter<StringType>::Print(suffix_, os);
840 }
841 private:
842 const StringType suffix_;
843};
844
845#if GMOCK_HAS_REGEX
846
847// Implements polymorphic matchers MatchesRegex(regex) and
848// ContainsRegex(regex), which can be used as a Matcher<T> as long as
849// T can be converted to a string.
850class MatchesRegexMatcher {
851 public:
852 MatchesRegexMatcher(const RE* regex, bool full_match)
853 : regex_(regex), full_match_(full_match) {}
854
855 // These overloaded methods allow MatchesRegex(regex) to be used as
856 // a Matcher<T> as long as T can be converted to string. Returns
857 // true iff s matches regular expression regex. When full_match_ is
858 // true, a full match is done; otherwise a partial match is done.
859 bool Matches(const char* s) const {
860 return s != NULL && Matches(internal::string(s));
861 }
862
863 bool Matches(const internal::string& s) const {
864 return full_match_ ? RE::FullMatch(s, *regex_) :
865 RE::PartialMatch(s, *regex_);
866 }
867
868 void DescribeTo(::std::ostream* os) const {
869 *os << (full_match_ ? "matches" : "contains")
870 << " regular expression ";
871 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
872 }
873
874 void DescribeNegationTo(::std::ostream* os) const {
875 *os << "doesn't " << (full_match_ ? "match" : "contain")
876 << " regular expression ";
877 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
878 }
879 private:
880 const internal::linked_ptr<const RE> regex_;
881 const bool full_match_;
882};
883
884#endif // GMOCK_HAS_REGEX
885
886// Implements a matcher that compares the two fields of a 2-tuple
887// using one of the ==, <=, <, etc, operators. The two fields being
888// compared don't have to have the same type.
889//
890// The matcher defined here is polymorphic (for example, Eq() can be
891// used to match a tuple<int, short>, a tuple<const long&, double>,
892// etc). Therefore we use a template type conversion operator in the
893// implementation.
894//
895// We define this as a macro in order to eliminate duplicated source
896// code.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000897#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000898 class name##2Matcher { \
899 public: \
900 template <typename T1, typename T2> \
901 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
902 return MakeMatcher(new Impl<T1, T2>); \
903 } \
904 private: \
905 template <typename T1, typename T2> \
906 class Impl : public MatcherInterface<const ::std::tr1::tuple<T1, T2>&> { \
907 public: \
908 virtual bool Matches(const ::std::tr1::tuple<T1, T2>& args) const { \
909 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
910 } \
911 virtual void DescribeTo(::std::ostream* os) const { \
912 *os << "argument #0 is " relation " argument #1"; \
913 } \
914 virtual void DescribeNegationTo(::std::ostream* os) const { \
915 *os << "argument #0 is not " relation " argument #1"; \
916 } \
917 }; \
918 }
919
920// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000921GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "equal to");
922GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ge, >=, "greater than or equal to");
923GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Gt, >, "greater than");
924GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Le, <=, "less than or equal to");
925GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Lt, <, "less than");
926GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=, "not equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000927
zhanyong.wane0d051e2009-02-19 00:33:37 +0000928#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000929
930// Implements the Not(m) matcher, which matches a value that doesn't
931// match matcher m.
932template <typename InnerMatcher>
933class NotMatcher {
934 public:
935 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
936
937 // This template type conversion operator allows Not(m) to be used
938 // to match any type m can match.
939 template <typename T>
940 operator Matcher<T>() const {
941 return Matcher<T>(new Impl<T>(matcher_));
942 }
943 private:
944 // Implements the Not(...) matcher for a particular argument type T.
945 template <typename T>
946 class Impl : public MatcherInterface<T> {
947 public:
948 explicit Impl(const Matcher<T>& matcher) : matcher_(matcher) {}
949
950 virtual bool Matches(T x) const {
951 return !matcher_.Matches(x);
952 }
953
954 virtual void DescribeTo(::std::ostream* os) const {
955 matcher_.DescribeNegationTo(os);
956 }
957
958 virtual void DescribeNegationTo(::std::ostream* os) const {
959 matcher_.DescribeTo(os);
960 }
961
962 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
963 matcher_.ExplainMatchResultTo(x, os);
964 }
965 private:
966 const Matcher<T> matcher_;
967 };
968
969 InnerMatcher matcher_;
970};
971
972// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
973// matches a value that matches all of the matchers m_1, ..., and m_n.
974template <typename Matcher1, typename Matcher2>
975class BothOfMatcher {
976 public:
977 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
978 : matcher1_(matcher1), matcher2_(matcher2) {}
979
980 // This template type conversion operator allows a
981 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
982 // both Matcher1 and Matcher2 can match.
983 template <typename T>
984 operator Matcher<T>() const {
985 return Matcher<T>(new Impl<T>(matcher1_, matcher2_));
986 }
987 private:
988 // Implements the AllOf(m1, m2) matcher for a particular argument
989 // type T.
990 template <typename T>
991 class Impl : public MatcherInterface<T> {
992 public:
993 Impl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
994 : matcher1_(matcher1), matcher2_(matcher2) {}
995
996 virtual bool Matches(T x) const {
997 return matcher1_.Matches(x) && matcher2_.Matches(x);
998 }
999
1000 virtual void DescribeTo(::std::ostream* os) const {
1001 *os << "(";
1002 matcher1_.DescribeTo(os);
1003 *os << ") and (";
1004 matcher2_.DescribeTo(os);
1005 *os << ")";
1006 }
1007
1008 virtual void DescribeNegationTo(::std::ostream* os) const {
1009 *os << "not ";
1010 DescribeTo(os);
1011 }
1012
1013 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1014 if (Matches(x)) {
1015 // When both matcher1_ and matcher2_ match x, we need to
1016 // explain why *both* of them match.
1017 ::std::stringstream ss1;
1018 matcher1_.ExplainMatchResultTo(x, &ss1);
1019 const internal::string s1 = ss1.str();
1020
1021 ::std::stringstream ss2;
1022 matcher2_.ExplainMatchResultTo(x, &ss2);
1023 const internal::string s2 = ss2.str();
1024
1025 if (s1 == "") {
1026 *os << s2;
1027 } else {
1028 *os << s1;
1029 if (s2 != "") {
1030 *os << "; " << s2;
1031 }
1032 }
1033 } else {
1034 // Otherwise we only need to explain why *one* of them fails
1035 // to match.
1036 if (!matcher1_.Matches(x)) {
1037 matcher1_.ExplainMatchResultTo(x, os);
1038 } else {
1039 matcher2_.ExplainMatchResultTo(x, os);
1040 }
1041 }
1042 }
1043 private:
1044 const Matcher<T> matcher1_;
1045 const Matcher<T> matcher2_;
1046 };
1047
1048 Matcher1 matcher1_;
1049 Matcher2 matcher2_;
1050};
1051
1052// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1053// matches a value that matches at least one of the matchers m_1, ...,
1054// and m_n.
1055template <typename Matcher1, typename Matcher2>
1056class EitherOfMatcher {
1057 public:
1058 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1059 : matcher1_(matcher1), matcher2_(matcher2) {}
1060
1061 // This template type conversion operator allows a
1062 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1063 // both Matcher1 and Matcher2 can match.
1064 template <typename T>
1065 operator Matcher<T>() const {
1066 return Matcher<T>(new Impl<T>(matcher1_, matcher2_));
1067 }
1068 private:
1069 // Implements the AnyOf(m1, m2) matcher for a particular argument
1070 // type T.
1071 template <typename T>
1072 class Impl : public MatcherInterface<T> {
1073 public:
1074 Impl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1075 : matcher1_(matcher1), matcher2_(matcher2) {}
1076
1077 virtual bool Matches(T x) const {
1078 return matcher1_.Matches(x) || matcher2_.Matches(x);
1079 }
1080
1081 virtual void DescribeTo(::std::ostream* os) const {
1082 *os << "(";
1083 matcher1_.DescribeTo(os);
1084 *os << ") or (";
1085 matcher2_.DescribeTo(os);
1086 *os << ")";
1087 }
1088
1089 virtual void DescribeNegationTo(::std::ostream* os) const {
1090 *os << "not ";
1091 DescribeTo(os);
1092 }
1093
1094 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1095 if (Matches(x)) {
1096 // If either matcher1_ or matcher2_ matches x, we just need
1097 // to explain why *one* of them matches.
1098 if (matcher1_.Matches(x)) {
1099 matcher1_.ExplainMatchResultTo(x, os);
1100 } else {
1101 matcher2_.ExplainMatchResultTo(x, os);
1102 }
1103 } else {
1104 // Otherwise we need to explain why *neither* matches.
1105 ::std::stringstream ss1;
1106 matcher1_.ExplainMatchResultTo(x, &ss1);
1107 const internal::string s1 = ss1.str();
1108
1109 ::std::stringstream ss2;
1110 matcher2_.ExplainMatchResultTo(x, &ss2);
1111 const internal::string s2 = ss2.str();
1112
1113 if (s1 == "") {
1114 *os << s2;
1115 } else {
1116 *os << s1;
1117 if (s2 != "") {
1118 *os << "; " << s2;
1119 }
1120 }
1121 }
1122 }
1123 private:
1124 const Matcher<T> matcher1_;
1125 const Matcher<T> matcher2_;
1126 };
1127
1128 Matcher1 matcher1_;
1129 Matcher2 matcher2_;
1130};
1131
1132// Used for implementing Truly(pred), which turns a predicate into a
1133// matcher.
1134template <typename Predicate>
1135class TrulyMatcher {
1136 public:
1137 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1138
1139 // This method template allows Truly(pred) to be used as a matcher
1140 // for type T where T is the argument type of predicate 'pred'. The
1141 // argument is passed by reference as the predicate may be
1142 // interested in the address of the argument.
1143 template <typename T>
1144 bool Matches(T& x) const {
zhanyong.wan652540a2009-02-23 23:37:29 +00001145#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001146 // MSVC warns about converting a value into bool (warning 4800).
1147#pragma warning(push) // Saves the current warning state.
1148#pragma warning(disable:4800) // Temporarily disables warning 4800.
1149#endif // GTEST_OS_WINDOWS
1150 return predicate_(x);
zhanyong.wan652540a2009-02-23 23:37:29 +00001151#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001152#pragma warning(pop) // Restores the warning state.
1153#endif // GTEST_OS_WINDOWS
1154 }
1155
1156 void DescribeTo(::std::ostream* os) const {
1157 *os << "satisfies the given predicate";
1158 }
1159
1160 void DescribeNegationTo(::std::ostream* os) const {
1161 *os << "doesn't satisfy the given predicate";
1162 }
1163 private:
1164 Predicate predicate_;
1165};
1166
1167// Used for implementing Matches(matcher), which turns a matcher into
1168// a predicate.
1169template <typename M>
1170class MatcherAsPredicate {
1171 public:
1172 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1173
1174 // This template operator() allows Matches(m) to be used as a
1175 // predicate on type T where m is a matcher on type T.
1176 //
1177 // The argument x is passed by reference instead of by value, as
1178 // some matcher may be interested in its address (e.g. as in
1179 // Matches(Ref(n))(x)).
1180 template <typename T>
1181 bool operator()(const T& x) const {
1182 // We let matcher_ commit to a particular type here instead of
1183 // when the MatcherAsPredicate object was constructed. This
1184 // allows us to write Matches(m) where m is a polymorphic matcher
1185 // (e.g. Eq(5)).
1186 //
1187 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1188 // compile when matcher_ has type Matcher<const T&>; if we write
1189 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1190 // when matcher_ has type Matcher<T>; if we just write
1191 // matcher_.Matches(x), it won't compile when matcher_ is
1192 // polymorphic, e.g. Eq(5).
1193 //
1194 // MatcherCast<const T&>() is necessary for making the code work
1195 // in all of the above situations.
1196 return MatcherCast<const T&>(matcher_).Matches(x);
1197 }
1198 private:
1199 M matcher_;
1200};
1201
1202// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1203// argument M must be a type that can be converted to a matcher.
1204template <typename M>
1205class PredicateFormatterFromMatcher {
1206 public:
1207 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1208
1209 // This template () operator allows a PredicateFormatterFromMatcher
1210 // object to act as a predicate-formatter suitable for using with
1211 // Google Test's EXPECT_PRED_FORMAT1() macro.
1212 template <typename T>
1213 AssertionResult operator()(const char* value_text, const T& x) const {
1214 // We convert matcher_ to a Matcher<const T&> *now* instead of
1215 // when the PredicateFormatterFromMatcher object was constructed,
1216 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1217 // know which type to instantiate it to until we actually see the
1218 // type of x here.
1219 //
1220 // We write MatcherCast<const T&>(matcher_) instead of
1221 // Matcher<const T&>(matcher_), as the latter won't compile when
1222 // matcher_ has type Matcher<T> (e.g. An<int>()).
1223 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
1224 if (matcher.Matches(x)) {
1225 return AssertionSuccess();
1226 } else {
1227 ::std::stringstream ss;
1228 ss << "Value of: " << value_text << "\n"
1229 << "Expected: ";
1230 matcher.DescribeTo(&ss);
1231 ss << "\n Actual: ";
1232 UniversalPrinter<T>::Print(x, &ss);
1233 ExplainMatchResultAsNeededTo<const T&>(matcher, x, &ss);
1234 return AssertionFailure(Message() << ss.str());
1235 }
1236 }
1237 private:
1238 const M matcher_;
1239};
1240
1241// A helper function for converting a matcher to a predicate-formatter
1242// without the user needing to explicitly write the type. This is
1243// used for implementing ASSERT_THAT() and EXPECT_THAT().
1244template <typename M>
1245inline PredicateFormatterFromMatcher<M>
1246MakePredicateFormatterFromMatcher(const M& matcher) {
1247 return PredicateFormatterFromMatcher<M>(matcher);
1248}
1249
1250// Implements the polymorphic floating point equality matcher, which
1251// matches two float values using ULP-based approximation. The
1252// template is meant to be instantiated with FloatType being either
1253// float or double.
1254template <typename FloatType>
1255class FloatingEqMatcher {
1256 public:
1257 // Constructor for FloatingEqMatcher.
1258 // The matcher's input will be compared with rhs. The matcher treats two
1259 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1260 // equality comparisons between NANs will always return false.
1261 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1262 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1263
1264 // Implements floating point equality matcher as a Matcher<T>.
1265 template <typename T>
1266 class Impl : public MatcherInterface<T> {
1267 public:
1268 Impl(FloatType rhs, bool nan_eq_nan) :
1269 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1270
1271 virtual bool Matches(T value) const {
1272 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1273
1274 // Compares NaNs first, if nan_eq_nan_ is true.
1275 if (nan_eq_nan_ && lhs.is_nan()) {
1276 return rhs.is_nan();
1277 }
1278
1279 return lhs.AlmostEquals(rhs);
1280 }
1281
1282 virtual void DescribeTo(::std::ostream* os) const {
1283 // os->precision() returns the previously set precision, which we
1284 // store to restore the ostream to its original configuration
1285 // after outputting.
1286 const ::std::streamsize old_precision = os->precision(
1287 ::std::numeric_limits<FloatType>::digits10 + 2);
1288 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1289 if (nan_eq_nan_) {
1290 *os << "is NaN";
1291 } else {
1292 *os << "never matches";
1293 }
1294 } else {
1295 *os << "is approximately " << rhs_;
1296 }
1297 os->precision(old_precision);
1298 }
1299
1300 virtual void DescribeNegationTo(::std::ostream* os) const {
1301 // As before, get original precision.
1302 const ::std::streamsize old_precision = os->precision(
1303 ::std::numeric_limits<FloatType>::digits10 + 2);
1304 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1305 if (nan_eq_nan_) {
1306 *os << "is not NaN";
1307 } else {
1308 *os << "is anything";
1309 }
1310 } else {
1311 *os << "is not approximately " << rhs_;
1312 }
1313 // Restore original precision.
1314 os->precision(old_precision);
1315 }
1316
1317 private:
1318 const FloatType rhs_;
1319 const bool nan_eq_nan_;
1320 };
1321
1322 // The following 3 type conversion operators allow FloatEq(rhs) and
1323 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1324 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1325 // (While Google's C++ coding style doesn't allow arguments passed
1326 // by non-const reference, we may see them in code not conforming to
1327 // the style. Therefore Google Mock needs to support them.)
1328 operator Matcher<FloatType>() const {
1329 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1330 }
1331
1332 operator Matcher<const FloatType&>() const {
1333 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1334 }
1335
1336 operator Matcher<FloatType&>() const {
1337 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1338 }
1339 private:
1340 const FloatType rhs_;
1341 const bool nan_eq_nan_;
1342};
1343
1344// Implements the Pointee(m) matcher for matching a pointer whose
1345// pointee matches matcher m. The pointer can be either raw or smart.
1346template <typename InnerMatcher>
1347class PointeeMatcher {
1348 public:
1349 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1350
1351 // This type conversion operator template allows Pointee(m) to be
1352 // used as a matcher for any pointer type whose pointee type is
1353 // compatible with the inner matcher, where type Pointer can be
1354 // either a raw pointer or a smart pointer.
1355 //
1356 // The reason we do this instead of relying on
1357 // MakePolymorphicMatcher() is that the latter is not flexible
1358 // enough for implementing the DescribeTo() method of Pointee().
1359 template <typename Pointer>
1360 operator Matcher<Pointer>() const {
1361 return MakeMatcher(new Impl<Pointer>(matcher_));
1362 }
1363 private:
1364 // The monomorphic implementation that works for a particular pointer type.
1365 template <typename Pointer>
1366 class Impl : public MatcherInterface<Pointer> {
1367 public:
zhanyong.wane0d051e2009-02-19 00:33:37 +00001368 typedef typename PointeeOf<GMOCK_REMOVE_CONST_( // NOLINT
1369 GMOCK_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001370
1371 explicit Impl(const InnerMatcher& matcher)
1372 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1373
1374 virtual bool Matches(Pointer p) const {
1375 return GetRawPointer(p) != NULL && matcher_.Matches(*p);
1376 }
1377
1378 virtual void DescribeTo(::std::ostream* os) const {
1379 *os << "points to a value that ";
1380 matcher_.DescribeTo(os);
1381 }
1382
1383 virtual void DescribeNegationTo(::std::ostream* os) const {
1384 *os << "does not point to a value that ";
1385 matcher_.DescribeTo(os);
1386 }
1387
1388 virtual void ExplainMatchResultTo(Pointer pointer,
1389 ::std::ostream* os) const {
1390 if (GetRawPointer(pointer) == NULL)
1391 return;
1392
1393 ::std::stringstream ss;
1394 matcher_.ExplainMatchResultTo(*pointer, &ss);
1395 const internal::string s = ss.str();
1396 if (s != "") {
1397 *os << "points to a value that " << s;
1398 }
1399 }
1400 private:
1401 const Matcher<const Pointee&> matcher_;
1402 };
1403
1404 const InnerMatcher matcher_;
1405};
1406
1407// Implements the Field() matcher for matching a field (i.e. member
1408// variable) of an object.
1409template <typename Class, typename FieldType>
1410class FieldMatcher {
1411 public:
1412 FieldMatcher(FieldType Class::*field,
1413 const Matcher<const FieldType&>& matcher)
1414 : field_(field), matcher_(matcher) {}
1415
1416 // Returns true iff the inner matcher matches obj.field.
1417 bool Matches(const Class& obj) const {
1418 return matcher_.Matches(obj.*field_);
1419 }
1420
1421 // Returns true iff the inner matcher matches obj->field.
1422 bool Matches(const Class* p) const {
1423 return (p != NULL) && matcher_.Matches(p->*field_);
1424 }
1425
1426 void DescribeTo(::std::ostream* os) const {
1427 *os << "the given field ";
1428 matcher_.DescribeTo(os);
1429 }
1430
1431 void DescribeNegationTo(::std::ostream* os) const {
1432 *os << "the given field ";
1433 matcher_.DescribeNegationTo(os);
1434 }
1435
1436 void ExplainMatchResultTo(const Class& obj, ::std::ostream* os) const {
1437 ::std::stringstream ss;
1438 matcher_.ExplainMatchResultTo(obj.*field_, &ss);
1439 const internal::string s = ss.str();
1440 if (s != "") {
1441 *os << "the given field " << s;
1442 }
1443 }
1444
1445 void ExplainMatchResultTo(const Class* p, ::std::ostream* os) const {
1446 if (p != NULL) {
1447 ExplainMatchResultTo(*p, os);
1448 }
1449 }
1450 private:
1451 const FieldType Class::*field_;
1452 const Matcher<const FieldType&> matcher_;
1453};
1454
1455// Explains the result of matching an object against a field matcher.
1456template <typename Class, typename FieldType>
1457void ExplainMatchResultTo(const FieldMatcher<Class, FieldType>& matcher,
1458 const Class& obj, ::std::ostream* os) {
1459 matcher.ExplainMatchResultTo(obj, os);
1460}
1461
1462// Explains the result of matching a pointer against a field matcher.
1463template <typename Class, typename FieldType>
1464void ExplainMatchResultTo(const FieldMatcher<Class, FieldType>& matcher,
1465 const Class* p, ::std::ostream* os) {
1466 matcher.ExplainMatchResultTo(p, os);
1467}
1468
1469// Implements the Property() matcher for matching a property
1470// (i.e. return value of a getter method) of an object.
1471template <typename Class, typename PropertyType>
1472class PropertyMatcher {
1473 public:
1474 // The property may have a reference type, so 'const PropertyType&'
1475 // may cause double references and fail to compile. That's why we
1476 // need GMOCK_REFERENCE_TO_CONST, which works regardless of
1477 // PropertyType being a reference or not.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001478 typedef GMOCK_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001479
1480 PropertyMatcher(PropertyType (Class::*property)() const,
1481 const Matcher<RefToConstProperty>& matcher)
1482 : property_(property), matcher_(matcher) {}
1483
1484 // Returns true iff obj.property() matches the inner matcher.
1485 bool Matches(const Class& obj) const {
1486 return matcher_.Matches((obj.*property_)());
1487 }
1488
1489 // Returns true iff p->property() matches the inner matcher.
1490 bool Matches(const Class* p) const {
1491 return (p != NULL) && matcher_.Matches((p->*property_)());
1492 }
1493
1494 void DescribeTo(::std::ostream* os) const {
1495 *os << "the given property ";
1496 matcher_.DescribeTo(os);
1497 }
1498
1499 void DescribeNegationTo(::std::ostream* os) const {
1500 *os << "the given property ";
1501 matcher_.DescribeNegationTo(os);
1502 }
1503
1504 void ExplainMatchResultTo(const Class& obj, ::std::ostream* os) const {
1505 ::std::stringstream ss;
1506 matcher_.ExplainMatchResultTo((obj.*property_)(), &ss);
1507 const internal::string s = ss.str();
1508 if (s != "") {
1509 *os << "the given property " << s;
1510 }
1511 }
1512
1513 void ExplainMatchResultTo(const Class* p, ::std::ostream* os) const {
1514 if (p != NULL) {
1515 ExplainMatchResultTo(*p, os);
1516 }
1517 }
1518 private:
1519 PropertyType (Class::*property_)() const;
1520 const Matcher<RefToConstProperty> matcher_;
1521};
1522
1523// Explains the result of matching an object against a property matcher.
1524template <typename Class, typename PropertyType>
1525void ExplainMatchResultTo(const PropertyMatcher<Class, PropertyType>& matcher,
1526 const Class& obj, ::std::ostream* os) {
1527 matcher.ExplainMatchResultTo(obj, os);
1528}
1529
1530// Explains the result of matching a pointer against a property matcher.
1531template <typename Class, typename PropertyType>
1532void ExplainMatchResultTo(const PropertyMatcher<Class, PropertyType>& matcher,
1533 const Class* p, ::std::ostream* os) {
1534 matcher.ExplainMatchResultTo(p, os);
1535}
1536
1537// Type traits specifying various features of different functors for ResultOf.
1538// The default template specifies features for functor objects.
1539// Functor classes have to typedef argument_type and result_type
1540// to be compatible with ResultOf.
1541template <typename Functor>
1542struct CallableTraits {
1543 typedef typename Functor::result_type ResultType;
1544 typedef Functor StorageType;
1545
1546 static void CheckIsValid(Functor functor) {}
1547 template <typename T>
1548 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1549};
1550
1551// Specialization for function pointers.
1552template <typename ArgType, typename ResType>
1553struct CallableTraits<ResType(*)(ArgType)> {
1554 typedef ResType ResultType;
1555 typedef ResType(*StorageType)(ArgType);
1556
1557 static void CheckIsValid(ResType(*f)(ArgType)) {
1558 GMOCK_CHECK_(f != NULL)
1559 << "NULL function pointer is passed into ResultOf().";
1560 }
1561 template <typename T>
1562 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1563 return (*f)(arg);
1564 }
1565};
1566
1567// Implements the ResultOf() matcher for matching a return value of a
1568// unary function of an object.
1569template <typename Callable>
1570class ResultOfMatcher {
1571 public:
1572 typedef typename CallableTraits<Callable>::ResultType ResultType;
1573
1574 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1575 : callable_(callable), matcher_(matcher) {
1576 CallableTraits<Callable>::CheckIsValid(callable_);
1577 }
1578
1579 template <typename T>
1580 operator Matcher<T>() const {
1581 return Matcher<T>(new Impl<T>(callable_, matcher_));
1582 }
1583
1584 private:
1585 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1586
1587 template <typename T>
1588 class Impl : public MatcherInterface<T> {
1589 public:
1590 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1591 : callable_(callable), matcher_(matcher) {}
1592 // Returns true iff callable_(obj) matches the inner matcher.
1593 // The calling syntax is different for different types of callables
1594 // so we abstract it in CallableTraits<Callable>::Invoke().
1595 virtual bool Matches(T obj) const {
1596 return matcher_.Matches(
1597 CallableTraits<Callable>::template Invoke<T>(callable_, obj));
1598 }
1599
1600 virtual void DescribeTo(::std::ostream* os) const {
1601 *os << "result of the given callable ";
1602 matcher_.DescribeTo(os);
1603 }
1604
1605 virtual void DescribeNegationTo(::std::ostream* os) const {
1606 *os << "result of the given callable ";
1607 matcher_.DescribeNegationTo(os);
1608 }
1609
1610 virtual void ExplainMatchResultTo(T obj, ::std::ostream* os) const {
1611 ::std::stringstream ss;
1612 matcher_.ExplainMatchResultTo(
1613 CallableTraits<Callable>::template Invoke<T>(callable_, obj),
1614 &ss);
1615 const internal::string s = ss.str();
1616 if (s != "")
1617 *os << "result of the given callable " << s;
1618 }
1619 private:
1620 // Functors often define operator() as non-const method even though
1621 // they are actualy stateless. But we need to use them even when
1622 // 'this' is a const pointer. It's the user's responsibility not to
1623 // use stateful callables with ResultOf(), which does't guarantee
1624 // how many times the callable will be invoked.
1625 mutable CallableStorageType callable_;
1626 const Matcher<ResultType> matcher_;
1627 }; // class Impl
1628
1629 const CallableStorageType callable_;
1630 const Matcher<ResultType> matcher_;
1631};
1632
1633// Explains the result of matching a value against a functor matcher.
1634template <typename T, typename Callable>
1635void ExplainMatchResultTo(const ResultOfMatcher<Callable>& matcher,
1636 T obj, ::std::ostream* os) {
1637 matcher.ExplainMatchResultTo(obj, os);
1638}
1639
zhanyong.wan6a896b52009-01-16 01:13:50 +00001640// Implements an equality matcher for any STL-style container whose elements
1641// support ==. This matcher is like Eq(), but its failure explanations provide
1642// more detailed information that is useful when the container is used as a set.
1643// The failure message reports elements that are in one of the operands but not
1644// the other. The failure messages do not report duplicate or out-of-order
1645// elements in the containers (which don't properly matter to sets, but can
1646// occur if the containers are vectors or lists, for example).
1647//
1648// Uses the container's const_iterator, value_type, operator ==,
1649// begin(), and end().
1650template <typename Container>
1651class ContainerEqMatcher {
1652 public:
1653 explicit ContainerEqMatcher(const Container& rhs) : rhs_(rhs) {}
1654 bool Matches(const Container& lhs) const { return lhs == rhs_; }
1655 void DescribeTo(::std::ostream* os) const {
1656 *os << "equals ";
1657 UniversalPrinter<Container>::Print(rhs_, os);
1658 }
1659 void DescribeNegationTo(::std::ostream* os) const {
1660 *os << "does not equal ";
1661 UniversalPrinter<Container>::Print(rhs_, os);
1662 }
1663
1664 void ExplainMatchResultTo(const Container& lhs,
1665 ::std::ostream* os) const {
1666 // Something is different. Check for missing values first.
1667 bool printed_header = false;
1668 for (typename Container::const_iterator it = lhs.begin();
1669 it != lhs.end(); ++it) {
1670 if (std::find(rhs_.begin(), rhs_.end(), *it) == rhs_.end()) {
1671 if (printed_header) {
1672 *os << ", ";
1673 } else {
1674 *os << "Only in actual: ";
1675 printed_header = true;
1676 }
1677 UniversalPrinter<typename Container::value_type>::Print(*it, os);
1678 }
1679 }
1680
1681 // Now check for extra values.
1682 bool printed_header2 = false;
1683 for (typename Container::const_iterator it = rhs_.begin();
1684 it != rhs_.end(); ++it) {
1685 if (std::find(lhs.begin(), lhs.end(), *it) == lhs.end()) {
1686 if (printed_header2) {
1687 *os << ", ";
1688 } else {
1689 *os << (printed_header ? "; not" : "Not") << " in actual: ";
1690 printed_header2 = true;
1691 }
1692 UniversalPrinter<typename Container::value_type>::Print(*it, os);
1693 }
1694 }
1695 }
1696 private:
1697 const Container rhs_;
1698};
1699
1700template <typename Container>
1701void ExplainMatchResultTo(const ContainerEqMatcher<Container>& matcher,
1702 const Container& lhs,
1703 ::std::ostream* os) {
1704 matcher.ExplainMatchResultTo(lhs, os);
1705}
1706
shiqiane35fdd92008-12-10 05:08:54 +00001707} // namespace internal
1708
1709// Implements MatcherCast().
1710template <typename T, typename M>
1711inline Matcher<T> MatcherCast(M matcher) {
1712 return internal::MatcherCastImpl<T, M>::Cast(matcher);
1713}
1714
1715// _ is a matcher that matches anything of any type.
1716//
1717// This definition is fine as:
1718//
1719// 1. The C++ standard permits using the name _ in a namespace that
1720// is not the global namespace or ::std.
1721// 2. The AnythingMatcher class has no data member or constructor,
1722// so it's OK to create global variables of this type.
1723// 3. c-style has approved of using _ in this case.
1724const internal::AnythingMatcher _ = {};
1725// Creates a matcher that matches any value of the given type T.
1726template <typename T>
1727inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
1728
1729// Creates a matcher that matches any value of the given type T.
1730template <typename T>
1731inline Matcher<T> An() { return A<T>(); }
1732
1733// Creates a polymorphic matcher that matches anything equal to x.
1734// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
1735// wouldn't compile.
1736template <typename T>
1737inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
1738
1739// Constructs a Matcher<T> from a 'value' of type T. The constructed
1740// matcher matches any value that's equal to 'value'.
1741template <typename T>
1742Matcher<T>::Matcher(T value) { *this = Eq(value); }
1743
1744// Creates a monomorphic matcher that matches anything with type Lhs
1745// and equal to rhs. A user may need to use this instead of Eq(...)
1746// in order to resolve an overloading ambiguity.
1747//
1748// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
1749// or Matcher<T>(x), but more readable than the latter.
1750//
1751// We could define similar monomorphic matchers for other comparison
1752// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
1753// it yet as those are used much less than Eq() in practice. A user
1754// can always write Matcher<T>(Lt(5)) to be explicit about the type,
1755// for example.
1756template <typename Lhs, typename Rhs>
1757inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
1758
1759// Creates a polymorphic matcher that matches anything >= x.
1760template <typename Rhs>
1761inline internal::GeMatcher<Rhs> Ge(Rhs x) {
1762 return internal::GeMatcher<Rhs>(x);
1763}
1764
1765// Creates a polymorphic matcher that matches anything > x.
1766template <typename Rhs>
1767inline internal::GtMatcher<Rhs> Gt(Rhs x) {
1768 return internal::GtMatcher<Rhs>(x);
1769}
1770
1771// Creates a polymorphic matcher that matches anything <= x.
1772template <typename Rhs>
1773inline internal::LeMatcher<Rhs> Le(Rhs x) {
1774 return internal::LeMatcher<Rhs>(x);
1775}
1776
1777// Creates a polymorphic matcher that matches anything < x.
1778template <typename Rhs>
1779inline internal::LtMatcher<Rhs> Lt(Rhs x) {
1780 return internal::LtMatcher<Rhs>(x);
1781}
1782
1783// Creates a polymorphic matcher that matches anything != x.
1784template <typename Rhs>
1785inline internal::NeMatcher<Rhs> Ne(Rhs x) {
1786 return internal::NeMatcher<Rhs>(x);
1787}
1788
1789// Creates a polymorphic matcher that matches any non-NULL pointer.
1790// This is convenient as Not(NULL) doesn't compile (the compiler
1791// thinks that that expression is comparing a pointer with an integer).
1792inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
1793 return MakePolymorphicMatcher(internal::NotNullMatcher());
1794}
1795
1796// Creates a polymorphic matcher that matches any argument that
1797// references variable x.
1798template <typename T>
1799inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
1800 return internal::RefMatcher<T&>(x);
1801}
1802
1803// Creates a matcher that matches any double argument approximately
1804// equal to rhs, where two NANs are considered unequal.
1805inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
1806 return internal::FloatingEqMatcher<double>(rhs, false);
1807}
1808
1809// Creates a matcher that matches any double argument approximately
1810// equal to rhs, including NaN values when rhs is NaN.
1811inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
1812 return internal::FloatingEqMatcher<double>(rhs, true);
1813}
1814
1815// Creates a matcher that matches any float argument approximately
1816// equal to rhs, where two NANs are considered unequal.
1817inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
1818 return internal::FloatingEqMatcher<float>(rhs, false);
1819}
1820
1821// Creates a matcher that matches any double argument approximately
1822// equal to rhs, including NaN values when rhs is NaN.
1823inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
1824 return internal::FloatingEqMatcher<float>(rhs, true);
1825}
1826
1827// Creates a matcher that matches a pointer (raw or smart) that points
1828// to a value that matches inner_matcher.
1829template <typename InnerMatcher>
1830inline internal::PointeeMatcher<InnerMatcher> Pointee(
1831 const InnerMatcher& inner_matcher) {
1832 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
1833}
1834
1835// Creates a matcher that matches an object whose given field matches
1836// 'matcher'. For example,
1837// Field(&Foo::number, Ge(5))
1838// matches a Foo object x iff x.number >= 5.
1839template <typename Class, typename FieldType, typename FieldMatcher>
1840inline PolymorphicMatcher<
1841 internal::FieldMatcher<Class, FieldType> > Field(
1842 FieldType Class::*field, const FieldMatcher& matcher) {
1843 return MakePolymorphicMatcher(
1844 internal::FieldMatcher<Class, FieldType>(
1845 field, MatcherCast<const FieldType&>(matcher)));
1846 // The call to MatcherCast() is required for supporting inner
1847 // matchers of compatible types. For example, it allows
1848 // Field(&Foo::bar, m)
1849 // to compile where bar is an int32 and m is a matcher for int64.
1850}
1851
1852// Creates a matcher that matches an object whose given property
1853// matches 'matcher'. For example,
1854// Property(&Foo::str, StartsWith("hi"))
1855// matches a Foo object x iff x.str() starts with "hi".
1856template <typename Class, typename PropertyType, typename PropertyMatcher>
1857inline PolymorphicMatcher<
1858 internal::PropertyMatcher<Class, PropertyType> > Property(
1859 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
1860 return MakePolymorphicMatcher(
1861 internal::PropertyMatcher<Class, PropertyType>(
1862 property,
zhanyong.wane0d051e2009-02-19 00:33:37 +00001863 MatcherCast<GMOCK_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00001864 // The call to MatcherCast() is required for supporting inner
1865 // matchers of compatible types. For example, it allows
1866 // Property(&Foo::bar, m)
1867 // to compile where bar() returns an int32 and m is a matcher for int64.
1868}
1869
1870// Creates a matcher that matches an object iff the result of applying
1871// a callable to x matches 'matcher'.
1872// For example,
1873// ResultOf(f, StartsWith("hi"))
1874// matches a Foo object x iff f(x) starts with "hi".
1875// callable parameter can be a function, function pointer, or a functor.
1876// Callable has to satisfy the following conditions:
1877// * It is required to keep no state affecting the results of
1878// the calls on it and make no assumptions about how many calls
1879// will be made. Any state it keeps must be protected from the
1880// concurrent access.
1881// * If it is a function object, it has to define type result_type.
1882// We recommend deriving your functor classes from std::unary_function.
1883template <typename Callable, typename ResultOfMatcher>
1884internal::ResultOfMatcher<Callable> ResultOf(
1885 Callable callable, const ResultOfMatcher& matcher) {
1886 return internal::ResultOfMatcher<Callable>(
1887 callable,
1888 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
1889 matcher));
1890 // The call to MatcherCast() is required for supporting inner
1891 // matchers of compatible types. For example, it allows
1892 // ResultOf(Function, m)
1893 // to compile where Function() returns an int32 and m is a matcher for int64.
1894}
1895
1896// String matchers.
1897
1898// Matches a string equal to str.
1899inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
1900 StrEq(const internal::string& str) {
1901 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
1902 str, true, true));
1903}
1904
1905// Matches a string not equal to str.
1906inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
1907 StrNe(const internal::string& str) {
1908 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
1909 str, false, true));
1910}
1911
1912// Matches a string equal to str, ignoring case.
1913inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
1914 StrCaseEq(const internal::string& str) {
1915 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
1916 str, true, false));
1917}
1918
1919// Matches a string not equal to str, ignoring case.
1920inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
1921 StrCaseNe(const internal::string& str) {
1922 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
1923 str, false, false));
1924}
1925
1926// Creates a matcher that matches any string, std::string, or C string
1927// that contains the given substring.
1928inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
1929 HasSubstr(const internal::string& substring) {
1930 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
1931 substring));
1932}
1933
1934// Matches a string that starts with 'prefix' (case-sensitive).
1935inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
1936 StartsWith(const internal::string& prefix) {
1937 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
1938 prefix));
1939}
1940
1941// Matches a string that ends with 'suffix' (case-sensitive).
1942inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
1943 EndsWith(const internal::string& suffix) {
1944 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
1945 suffix));
1946}
1947
1948#ifdef GMOCK_HAS_REGEX
1949
1950// Matches a string that fully matches regular expression 'regex'.
1951// The matcher takes ownership of 'regex'.
1952inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
1953 const internal::RE* regex) {
1954 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
1955}
1956inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
1957 const internal::string& regex) {
1958 return MatchesRegex(new internal::RE(regex));
1959}
1960
1961// Matches a string that contains regular expression 'regex'.
1962// The matcher takes ownership of 'regex'.
1963inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
1964 const internal::RE* regex) {
1965 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
1966}
1967inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
1968 const internal::string& regex) {
1969 return ContainsRegex(new internal::RE(regex));
1970}
1971
1972#endif // GMOCK_HAS_REGEX
1973
1974#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
1975// Wide string matchers.
1976
1977// Matches a string equal to str.
1978inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
1979 StrEq(const internal::wstring& str) {
1980 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
1981 str, true, true));
1982}
1983
1984// Matches a string not equal to str.
1985inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
1986 StrNe(const internal::wstring& str) {
1987 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
1988 str, false, true));
1989}
1990
1991// Matches a string equal to str, ignoring case.
1992inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
1993 StrCaseEq(const internal::wstring& str) {
1994 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
1995 str, true, false));
1996}
1997
1998// Matches a string not equal to str, ignoring case.
1999inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2000 StrCaseNe(const internal::wstring& str) {
2001 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2002 str, false, false));
2003}
2004
2005// Creates a matcher that matches any wstring, std::wstring, or C wide string
2006// that contains the given substring.
2007inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2008 HasSubstr(const internal::wstring& substring) {
2009 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2010 substring));
2011}
2012
2013// Matches a string that starts with 'prefix' (case-sensitive).
2014inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2015 StartsWith(const internal::wstring& prefix) {
2016 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2017 prefix));
2018}
2019
2020// Matches a string that ends with 'suffix' (case-sensitive).
2021inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2022 EndsWith(const internal::wstring& suffix) {
2023 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2024 suffix));
2025}
2026
2027#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2028
2029// Creates a polymorphic matcher that matches a 2-tuple where the
2030// first field == the second field.
2031inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2032
2033// Creates a polymorphic matcher that matches a 2-tuple where the
2034// first field >= the second field.
2035inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2036
2037// Creates a polymorphic matcher that matches a 2-tuple where the
2038// first field > the second field.
2039inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2040
2041// Creates a polymorphic matcher that matches a 2-tuple where the
2042// first field <= the second field.
2043inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2044
2045// Creates a polymorphic matcher that matches a 2-tuple where the
2046// first field < the second field.
2047inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2048
2049// Creates a polymorphic matcher that matches a 2-tuple where the
2050// first field != the second field.
2051inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2052
2053// Creates a matcher that matches any value of type T that m doesn't
2054// match.
2055template <typename InnerMatcher>
2056inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2057 return internal::NotMatcher<InnerMatcher>(m);
2058}
2059
2060// Creates a matcher that matches any value that matches all of the
2061// given matchers.
2062//
2063// For now we only support up to 5 matchers. Support for more
2064// matchers can be added as needed, or the user can use nested
2065// AllOf()s.
2066template <typename Matcher1, typename Matcher2>
2067inline internal::BothOfMatcher<Matcher1, Matcher2>
2068AllOf(Matcher1 m1, Matcher2 m2) {
2069 return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2);
2070}
2071
2072template <typename Matcher1, typename Matcher2, typename Matcher3>
2073inline internal::BothOfMatcher<Matcher1,
2074 internal::BothOfMatcher<Matcher2, Matcher3> >
2075AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2076 return AllOf(m1, AllOf(m2, m3));
2077}
2078
2079template <typename Matcher1, typename Matcher2, typename Matcher3,
2080 typename Matcher4>
2081inline internal::BothOfMatcher<Matcher1,
2082 internal::BothOfMatcher<Matcher2,
2083 internal::BothOfMatcher<Matcher3, Matcher4> > >
2084AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2085 return AllOf(m1, AllOf(m2, m3, m4));
2086}
2087
2088template <typename Matcher1, typename Matcher2, typename Matcher3,
2089 typename Matcher4, typename Matcher5>
2090inline internal::BothOfMatcher<Matcher1,
2091 internal::BothOfMatcher<Matcher2,
2092 internal::BothOfMatcher<Matcher3,
2093 internal::BothOfMatcher<Matcher4, Matcher5> > > >
2094AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2095 return AllOf(m1, AllOf(m2, m3, m4, m5));
2096}
2097
2098// Creates a matcher that matches any value that matches at least one
2099// of the given matchers.
2100//
2101// For now we only support up to 5 matchers. Support for more
2102// matchers can be added as needed, or the user can use nested
2103// AnyOf()s.
2104template <typename Matcher1, typename Matcher2>
2105inline internal::EitherOfMatcher<Matcher1, Matcher2>
2106AnyOf(Matcher1 m1, Matcher2 m2) {
2107 return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2);
2108}
2109
2110template <typename Matcher1, typename Matcher2, typename Matcher3>
2111inline internal::EitherOfMatcher<Matcher1,
2112 internal::EitherOfMatcher<Matcher2, Matcher3> >
2113AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2114 return AnyOf(m1, AnyOf(m2, m3));
2115}
2116
2117template <typename Matcher1, typename Matcher2, typename Matcher3,
2118 typename Matcher4>
2119inline internal::EitherOfMatcher<Matcher1,
2120 internal::EitherOfMatcher<Matcher2,
2121 internal::EitherOfMatcher<Matcher3, Matcher4> > >
2122AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2123 return AnyOf(m1, AnyOf(m2, m3, m4));
2124}
2125
2126template <typename Matcher1, typename Matcher2, typename Matcher3,
2127 typename Matcher4, typename Matcher5>
2128inline internal::EitherOfMatcher<Matcher1,
2129 internal::EitherOfMatcher<Matcher2,
2130 internal::EitherOfMatcher<Matcher3,
2131 internal::EitherOfMatcher<Matcher4, Matcher5> > > >
2132AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2133 return AnyOf(m1, AnyOf(m2, m3, m4, m5));
2134}
2135
2136// Returns a matcher that matches anything that satisfies the given
2137// predicate. The predicate can be any unary function or functor
2138// whose return type can be implicitly converted to bool.
2139template <typename Predicate>
2140inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
2141Truly(Predicate pred) {
2142 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
2143}
2144
zhanyong.wan6a896b52009-01-16 01:13:50 +00002145// Returns a matcher that matches an equal container.
2146// This matcher behaves like Eq(), but in the event of mismatch lists the
2147// values that are included in one container but not the other. (Duplicate
2148// values and order differences are not explained.)
2149template <typename Container>
2150inline PolymorphicMatcher<internal::ContainerEqMatcher<Container> >
2151 ContainerEq(const Container& rhs) {
2152 return MakePolymorphicMatcher(internal::ContainerEqMatcher<Container>(rhs));
2153}
2154
shiqiane35fdd92008-12-10 05:08:54 +00002155// Returns a predicate that is satisfied by anything that matches the
2156// given matcher.
2157template <typename M>
2158inline internal::MatcherAsPredicate<M> Matches(M matcher) {
2159 return internal::MatcherAsPredicate<M>(matcher);
2160}
2161
2162// These macros allow using matchers to check values in Google Test
2163// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
2164// succeed iff the value matches the matcher. If the assertion fails,
2165// the value and the description of the matcher will be printed.
2166#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
2167 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2168#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
2169 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2170
2171} // namespace testing
2172
2173#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_