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