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