blob: e2beff4effbd3adca2b1b32af65cc54977b6e7ed [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements some commonly used argument matchers. More
35// matchers can be defined by the user implementing the
36// MatcherInterface<T> interface if necessary.
37
38#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
39#define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
40
zhanyong.wan6a896b52009-01-16 01:13:50 +000041#include <algorithm>
zhanyong.wan16cf4732009-05-14 20:55:30 +000042#include <limits>
shiqiane35fdd92008-12-10 05:08:54 +000043#include <ostream> // NOLINT
44#include <sstream>
45#include <string>
46#include <vector>
47
48#include <gmock/gmock-printers.h>
49#include <gmock/internal/gmock-internal-utils.h>
50#include <gmock/internal/gmock-port.h>
51#include <gtest/gtest.h>
52
53namespace testing {
54
55// To implement a matcher Foo for type T, define:
56// 1. a class FooMatcherImpl that implements the
57// MatcherInterface<T> interface, and
58// 2. a factory function that creates a Matcher<T> object from a
59// FooMatcherImpl*.
60//
61// The two-level delegation design makes it possible to allow a user
62// to write "v" instead of "Eq(v)" where a Matcher is expected, which
63// is impossible if we pass matchers by pointers. It also eases
64// ownership management as Matcher objects can now be copied like
65// plain values.
66
67// The implementation of a matcher.
68template <typename T>
69class MatcherInterface {
70 public:
71 virtual ~MatcherInterface() {}
72
73 // Returns true iff the matcher matches x.
74 virtual bool Matches(T x) const = 0;
75
76 // Describes this matcher to an ostream.
77 virtual void DescribeTo(::std::ostream* os) const = 0;
78
79 // Describes the negation of this matcher to an ostream. For
80 // example, if the description of this matcher is "is greater than
81 // 7", the negated description could be "is not greater than 7".
82 // You are not required to override this when implementing
83 // MatcherInterface, but it is highly advised so that your matcher
84 // can produce good error messages.
85 virtual void DescribeNegationTo(::std::ostream* os) const {
86 *os << "not (";
87 DescribeTo(os);
88 *os << ")";
89 }
90
91 // Explains why x matches, or doesn't match, the matcher. Override
92 // this to provide any additional information that helps a user
93 // understand the match result.
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +000094 virtual void ExplainMatchResultTo(T /* x */, ::std::ostream* /* os */) const {
shiqiane35fdd92008-12-10 05:08:54 +000095 // By default, nothing more needs to be explained, as Google Mock
96 // has already printed the value of x when this function is
97 // called.
98 }
99};
100
101namespace internal {
102
103// An internal class for implementing Matcher<T>, which will derive
104// from it. We put functionalities common to all Matcher<T>
105// specializations here to avoid code duplication.
106template <typename T>
107class MatcherBase {
108 public:
109 // Returns true iff this matcher matches x.
110 bool Matches(T x) const { return impl_->Matches(x); }
111
112 // Describes this matcher to an ostream.
113 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
114
115 // Describes the negation of this matcher to an ostream.
116 void DescribeNegationTo(::std::ostream* os) const {
117 impl_->DescribeNegationTo(os);
118 }
119
120 // Explains why x matches, or doesn't match, the matcher.
121 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
122 impl_->ExplainMatchResultTo(x, os);
123 }
124 protected:
125 MatcherBase() {}
126
127 // Constructs a matcher from its implementation.
128 explicit MatcherBase(const MatcherInterface<T>* impl)
129 : impl_(impl) {}
130
131 virtual ~MatcherBase() {}
132 private:
133 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
134 // interfaces. The former dynamically allocates a chunk of memory
135 // to hold the reference count, while the latter tracks all
136 // references using a circular linked list without allocating
137 // memory. It has been observed that linked_ptr performs better in
138 // typical scenarios. However, shared_ptr can out-perform
139 // linked_ptr when there are many more uses of the copy constructor
140 // than the default constructor.
141 //
142 // If performance becomes a problem, we should see if using
143 // shared_ptr helps.
144 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
145};
146
147// The default implementation of ExplainMatchResultTo() for
148// polymorphic matchers.
149template <typename PolymorphicMatcherImpl, typename T>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000150inline void ExplainMatchResultTo(const PolymorphicMatcherImpl& /* impl */,
151 const T& /* x */,
152 ::std::ostream* /* os */) {
shiqiane35fdd92008-12-10 05:08:54 +0000153 // By default, nothing more needs to be said, as Google Mock already
154 // prints the value of x elsewhere.
155}
156
157} // namespace internal
158
159// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
160// object that can check whether a value of type T matches. The
161// implementation of Matcher<T> is just a linked_ptr to const
162// MatcherInterface<T>, so copying is fairly cheap. Don't inherit
163// from Matcher!
164template <typename T>
165class Matcher : public internal::MatcherBase<T> {
166 public:
167 // Constructs a null matcher. Needed for storing Matcher objects in
168 // STL containers.
169 Matcher() {}
170
171 // Constructs a matcher from its implementation.
172 explicit Matcher(const MatcherInterface<T>* impl)
173 : internal::MatcherBase<T>(impl) {}
174
zhanyong.wan18490652009-05-11 18:54:08 +0000175 // Implicit constructor here allows people to write
shiqiane35fdd92008-12-10 05:08:54 +0000176 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
177 Matcher(T value); // NOLINT
178};
179
180// The following two specializations allow the user to write str
181// instead of Eq(str) and "foo" instead of Eq("foo") when a string
182// matcher is expected.
183template <>
184class Matcher<const internal::string&>
185 : public internal::MatcherBase<const internal::string&> {
186 public:
187 Matcher() {}
188
189 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
190 : internal::MatcherBase<const internal::string&>(impl) {}
191
192 // Allows the user to write str instead of Eq(str) sometimes, where
193 // str is a string object.
194 Matcher(const internal::string& s); // NOLINT
195
196 // Allows the user to write "foo" instead of Eq("foo") sometimes.
197 Matcher(const char* s); // NOLINT
198};
199
200template <>
201class Matcher<internal::string>
202 : public internal::MatcherBase<internal::string> {
203 public:
204 Matcher() {}
205
206 explicit Matcher(const MatcherInterface<internal::string>* impl)
207 : internal::MatcherBase<internal::string>(impl) {}
208
209 // Allows the user to write str instead of Eq(str) sometimes, where
210 // str is a string object.
211 Matcher(const internal::string& s); // NOLINT
212
213 // Allows the user to write "foo" instead of Eq("foo") sometimes.
214 Matcher(const char* s); // NOLINT
215};
216
217// The PolymorphicMatcher class template makes it easy to implement a
218// polymorphic matcher (i.e. a matcher that can match values of more
219// than one type, e.g. Eq(n) and NotNull()).
220//
221// To define a polymorphic matcher, a user first provides a Impl class
222// that has a Matches() method, a DescribeTo() method, and a
223// DescribeNegationTo() method. The Matches() method is usually a
224// method template (such that it works with multiple types). Then the
225// user creates the polymorphic matcher using
226// MakePolymorphicMatcher(). To provide additional explanation to the
227// match result, define a FREE function (or function template)
228//
229// void ExplainMatchResultTo(const Impl& matcher, const Value& value,
230// ::std::ostream* os);
231//
232// in the SAME NAME SPACE where Impl is defined. See the definition
233// of NotNull() for a complete example.
234template <class Impl>
235class PolymorphicMatcher {
236 public:
237 explicit PolymorphicMatcher(const Impl& impl) : impl_(impl) {}
238
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000239 // Returns a mutable reference to the underlying matcher
240 // implementation object.
241 Impl& mutable_impl() { return impl_; }
242
243 // Returns an immutable reference to the underlying matcher
244 // implementation object.
245 const Impl& impl() const { return impl_; }
246
shiqiane35fdd92008-12-10 05:08:54 +0000247 template <typename T>
248 operator Matcher<T>() const {
249 return Matcher<T>(new MonomorphicImpl<T>(impl_));
250 }
251 private:
252 template <typename T>
253 class MonomorphicImpl : public MatcherInterface<T> {
254 public:
255 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
256
257 virtual bool Matches(T x) const { return impl_.Matches(x); }
258
259 virtual void DescribeTo(::std::ostream* os) const {
260 impl_.DescribeTo(os);
261 }
262
263 virtual void DescribeNegationTo(::std::ostream* os) const {
264 impl_.DescribeNegationTo(os);
265 }
266
267 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
268 using ::testing::internal::ExplainMatchResultTo;
269
270 // C++ uses Argument-Dependent Look-up (aka Koenig Look-up) to
271 // resolve the call to ExplainMatchResultTo() here. This
272 // means that if there's a ExplainMatchResultTo() function
273 // defined in the name space where class Impl is defined, it
274 // will be picked by the compiler as the better match.
275 // Otherwise the default implementation of it in
276 // ::testing::internal will be picked.
277 //
278 // This look-up rule lets a writer of a polymorphic matcher
279 // customize the behavior of ExplainMatchResultTo() when he
280 // cares to. Nothing needs to be done by the writer if he
281 // doesn't need to customize it.
282 ExplainMatchResultTo(impl_, x, os);
283 }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000284
shiqiane35fdd92008-12-10 05:08:54 +0000285 private:
286 const Impl impl_;
287 };
288
zhanyong.wan2b43a9e2009-08-31 23:51:23 +0000289 Impl impl_;
shiqiane35fdd92008-12-10 05:08:54 +0000290};
291
292// Creates a matcher from its implementation. This is easier to use
293// than the Matcher<T> constructor as it doesn't require you to
294// explicitly write the template argument, e.g.
295//
296// MakeMatcher(foo);
297// vs
298// Matcher<const string&>(foo);
299template <typename T>
300inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
301 return Matcher<T>(impl);
302};
303
304// Creates a polymorphic matcher from its implementation. This is
305// easier to use than the PolymorphicMatcher<Impl> constructor as it
306// doesn't require you to explicitly write the template argument, e.g.
307//
308// MakePolymorphicMatcher(foo);
309// vs
310// PolymorphicMatcher<TypeOfFoo>(foo);
311template <class Impl>
312inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
313 return PolymorphicMatcher<Impl>(impl);
314}
315
316// In order to be safe and clear, casting between different matcher
317// types is done explicitly via MatcherCast<T>(m), which takes a
318// matcher m and returns a Matcher<T>. It compiles only when T can be
319// statically converted to the argument type of m.
320template <typename T, typename M>
321Matcher<T> MatcherCast(M m);
322
zhanyong.wan18490652009-05-11 18:54:08 +0000323// TODO(vladl@google.com): Modify the implementation to reject casting
324// Matcher<int> to Matcher<double>.
325// Implements SafeMatcherCast().
326//
327// This overload handles polymorphic matchers only since monomorphic
328// matchers are handled by the next one.
329template <typename T, typename M>
330inline Matcher<T> SafeMatcherCast(M polymorphic_matcher) {
331 return Matcher<T>(polymorphic_matcher);
332}
333
334// This overload handles monomorphic matchers.
335//
336// In general, if type T can be implicitly converted to type U, we can
337// safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
338// contravariant): just keep a copy of the original Matcher<U>, convert the
339// argument from type T to U, and then pass it to the underlying Matcher<U>.
340// The only exception is when U is a reference and T is not, as the
341// underlying Matcher<U> may be interested in the argument's address, which
342// is not preserved in the conversion from T to U.
343template <typename T, typename U>
344Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) {
345 // Enforce that T can be implicitly converted to U.
346 GMOCK_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
347 T_must_be_implicitly_convertible_to_U);
348 // Enforce that we are not converting a non-reference type T to a reference
349 // type U.
350 GMOCK_COMPILE_ASSERT_(
351 internal::is_reference<T>::value || !internal::is_reference<U>::value,
352 cannot_convert_non_referentce_arg_to_reference);
zhanyong.wan16cf4732009-05-14 20:55:30 +0000353 // In case both T and U are arithmetic types, enforce that the
354 // conversion is not lossy.
355 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(T)) RawT;
356 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(U)) RawU;
357 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
358 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
359 GMOCK_COMPILE_ASSERT_(
360 kTIsOther || kUIsOther ||
361 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
362 conversion_of_arithmetic_types_must_be_lossless);
zhanyong.wan18490652009-05-11 18:54:08 +0000363 return MatcherCast<T>(matcher);
364}
365
shiqiane35fdd92008-12-10 05:08:54 +0000366// A<T>() returns a matcher that matches any value of type T.
367template <typename T>
368Matcher<T> A();
369
370// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
371// and MUST NOT BE USED IN USER CODE!!!
372namespace internal {
373
374// Appends the explanation on the result of matcher.Matches(value) to
375// os iff the explanation is not empty.
376template <typename T>
377void ExplainMatchResultAsNeededTo(const Matcher<T>& matcher, T value,
378 ::std::ostream* os) {
379 ::std::stringstream reason;
380 matcher.ExplainMatchResultTo(value, &reason);
381 const internal::string s = reason.str();
382 if (s != "") {
383 *os << " (" << s << ")";
384 }
385}
386
387// An internal helper class for doing compile-time loop on a tuple's
388// fields.
389template <size_t N>
390class TuplePrefix {
391 public:
392 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
393 // iff the first N fields of matcher_tuple matches the first N
394 // fields of value_tuple, respectively.
395 template <typename MatcherTuple, typename ValueTuple>
396 static bool Matches(const MatcherTuple& matcher_tuple,
397 const ValueTuple& value_tuple) {
398 using ::std::tr1::get;
399 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
400 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
401 }
402
403 // TuplePrefix<N>::DescribeMatchFailuresTo(matchers, values, os)
404 // describes failures in matching the first N fields of matchers
405 // against the first N fields of values. If there is no failure,
406 // nothing will be streamed to os.
407 template <typename MatcherTuple, typename ValueTuple>
408 static void DescribeMatchFailuresTo(const MatcherTuple& matchers,
409 const ValueTuple& values,
410 ::std::ostream* os) {
411 using ::std::tr1::tuple_element;
412 using ::std::tr1::get;
413
414 // First, describes failures in the first N - 1 fields.
415 TuplePrefix<N - 1>::DescribeMatchFailuresTo(matchers, values, os);
416
417 // Then describes the failure (if any) in the (N - 1)-th (0-based)
418 // field.
419 typename tuple_element<N - 1, MatcherTuple>::type matcher =
420 get<N - 1>(matchers);
421 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
422 Value value = get<N - 1>(values);
423 if (!matcher.Matches(value)) {
424 // TODO(wan): include in the message the name of the parameter
425 // as used in MOCK_METHOD*() when possible.
426 *os << " Expected arg #" << N - 1 << ": ";
427 get<N - 1>(matchers).DescribeTo(os);
428 *os << "\n Actual: ";
429 // We remove the reference in type Value to prevent the
430 // universal printer from printing the address of value, which
431 // isn't interesting to the user most of the time. The
432 // matcher's ExplainMatchResultTo() method handles the case when
433 // the address is interesting.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000434 internal::UniversalPrinter<GMOCK_REMOVE_REFERENCE_(Value)>::
shiqiane35fdd92008-12-10 05:08:54 +0000435 Print(value, os);
436 ExplainMatchResultAsNeededTo<Value>(matcher, value, os);
437 *os << "\n";
438 }
439 }
440};
441
442// The base case.
443template <>
444class TuplePrefix<0> {
445 public:
446 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000447 static bool Matches(const MatcherTuple& /* matcher_tuple */,
448 const ValueTuple& /* value_tuple */) {
shiqiane35fdd92008-12-10 05:08:54 +0000449 return true;
450 }
451
452 template <typename MatcherTuple, typename ValueTuple>
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000453 static void DescribeMatchFailuresTo(const MatcherTuple& /* matchers */,
454 const ValueTuple& /* values */,
455 ::std::ostream* /* os */) {}
shiqiane35fdd92008-12-10 05:08:54 +0000456};
457
458// TupleMatches(matcher_tuple, value_tuple) returns true iff all
459// matchers in matcher_tuple match the corresponding fields in
460// value_tuple. It is a compiler error if matcher_tuple and
461// value_tuple have different number of fields or incompatible field
462// types.
463template <typename MatcherTuple, typename ValueTuple>
464bool TupleMatches(const MatcherTuple& matcher_tuple,
465 const ValueTuple& value_tuple) {
466 using ::std::tr1::tuple_size;
467 // Makes sure that matcher_tuple and value_tuple have the same
468 // number of fields.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000469 GMOCK_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
470 tuple_size<ValueTuple>::value,
471 matcher_and_value_have_different_numbers_of_fields);
shiqiane35fdd92008-12-10 05:08:54 +0000472 return TuplePrefix<tuple_size<ValueTuple>::value>::
473 Matches(matcher_tuple, value_tuple);
474}
475
476// Describes failures in matching matchers against values. If there
477// is no failure, nothing will be streamed to os.
478template <typename MatcherTuple, typename ValueTuple>
479void DescribeMatchFailureTupleTo(const MatcherTuple& matchers,
480 const ValueTuple& values,
481 ::std::ostream* os) {
482 using ::std::tr1::tuple_size;
483 TuplePrefix<tuple_size<MatcherTuple>::value>::DescribeMatchFailuresTo(
484 matchers, values, os);
485}
486
487// The MatcherCastImpl class template is a helper for implementing
488// MatcherCast(). We need this helper in order to partially
489// specialize the implementation of MatcherCast() (C++ allows
490// class/struct templates to be partially specialized, but not
491// function templates.).
492
493// This general version is used when MatcherCast()'s argument is a
494// polymorphic matcher (i.e. something that can be converted to a
495// Matcher but is not one yet; for example, Eq(value)).
496template <typename T, typename M>
497class MatcherCastImpl {
498 public:
499 static Matcher<T> Cast(M polymorphic_matcher) {
500 return Matcher<T>(polymorphic_matcher);
501 }
502};
503
504// This more specialized version is used when MatcherCast()'s argument
505// is already a Matcher. This only compiles when type T can be
506// statically converted to type U.
507template <typename T, typename U>
508class MatcherCastImpl<T, Matcher<U> > {
509 public:
510 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
511 return Matcher<T>(new Impl(source_matcher));
512 }
513 private:
514 class Impl : public MatcherInterface<T> {
515 public:
516 explicit Impl(const Matcher<U>& source_matcher)
517 : source_matcher_(source_matcher) {}
518
519 // We delegate the matching logic to the source matcher.
520 virtual bool Matches(T x) const {
521 return source_matcher_.Matches(static_cast<U>(x));
522 }
523
524 virtual void DescribeTo(::std::ostream* os) const {
525 source_matcher_.DescribeTo(os);
526 }
527
528 virtual void DescribeNegationTo(::std::ostream* os) const {
529 source_matcher_.DescribeNegationTo(os);
530 }
531
532 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
533 source_matcher_.ExplainMatchResultTo(static_cast<U>(x), os);
534 }
535 private:
536 const Matcher<U> source_matcher_;
537 };
538};
539
540// This even more specialized version is used for efficiently casting
541// a matcher to its own type.
542template <typename T>
543class MatcherCastImpl<T, Matcher<T> > {
544 public:
545 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
546};
547
548// Implements A<T>().
549template <typename T>
550class AnyMatcherImpl : public MatcherInterface<T> {
551 public:
zhanyong.wan3fbd2dd2009-03-26 19:06:45 +0000552 virtual bool Matches(T /* x */) const { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000553 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
554 virtual void DescribeNegationTo(::std::ostream* os) const {
555 // This is mostly for completeness' safe, as it's not very useful
556 // to write Not(A<bool>()). However we cannot completely rule out
557 // such a possibility, and it doesn't hurt to be prepared.
558 *os << "never matches";
559 }
560};
561
562// Implements _, a matcher that matches any value of any
563// type. This is a polymorphic matcher, so we need a template type
564// conversion operator to make it appearing as a Matcher<T> for any
565// type T.
566class AnythingMatcher {
567 public:
568 template <typename T>
569 operator Matcher<T>() const { return A<T>(); }
570};
571
572// Implements a matcher that compares a given value with a
573// pre-supplied value using one of the ==, <=, <, etc, operators. The
574// two values being compared don't have to have the same type.
575//
576// The matcher defined here is polymorphic (for example, Eq(5) can be
577// used to match an int, a short, a double, etc). Therefore we use
578// a template type conversion operator in the implementation.
579//
580// We define this as a macro in order to eliminate duplicated source
581// code.
582//
583// The following template definition assumes that the Rhs parameter is
584// a "bare" type (i.e. neither 'const T' nor 'T&').
zhanyong.wane0d051e2009-02-19 00:33:37 +0000585#define GMOCK_IMPLEMENT_COMPARISON_MATCHER_(name, op, relation) \
shiqiane35fdd92008-12-10 05:08:54 +0000586 template <typename Rhs> class name##Matcher { \
587 public: \
588 explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
589 template <typename Lhs> \
590 operator Matcher<Lhs>() const { \
591 return MakeMatcher(new Impl<Lhs>(rhs_)); \
592 } \
593 private: \
594 template <typename Lhs> \
595 class Impl : public MatcherInterface<Lhs> { \
596 public: \
597 explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
598 virtual bool Matches(Lhs lhs) const { return lhs op rhs_; } \
599 virtual void DescribeTo(::std::ostream* os) const { \
600 *os << "is " relation " "; \
601 UniversalPrinter<Rhs>::Print(rhs_, os); \
602 } \
603 virtual void DescribeNegationTo(::std::ostream* os) const { \
604 *os << "is not " relation " "; \
605 UniversalPrinter<Rhs>::Print(rhs_, os); \
606 } \
607 private: \
608 Rhs rhs_; \
609 }; \
610 Rhs rhs_; \
611 }
612
613// Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
614// respectively.
zhanyong.wane0d051e2009-02-19 00:33:37 +0000615GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "equal to");
616GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "greater than or equal to");
617GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "greater than");
618GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "less than or equal to");
619GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "less than");
620GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "not equal to");
shiqiane35fdd92008-12-10 05:08:54 +0000621
zhanyong.wane0d051e2009-02-19 00:33:37 +0000622#undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000623
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000624// Implements the polymorphic IsNull() matcher, which matches any
625// pointer that is NULL.
626class IsNullMatcher {
627 public:
628 template <typename T>
629 bool Matches(T* p) const { return p == NULL; }
630
631 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
632 void DescribeNegationTo(::std::ostream* os) const {
633 *os << "is not NULL";
634 }
635};
636
shiqiane35fdd92008-12-10 05:08:54 +0000637// Implements the polymorphic NotNull() matcher, which matches any
638// pointer that is not NULL.
639class NotNullMatcher {
640 public:
641 template <typename T>
642 bool Matches(T* p) const { return p != NULL; }
643
644 void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; }
645 void DescribeNegationTo(::std::ostream* os) const {
646 *os << "is NULL";
647 }
648};
649
650// Ref(variable) matches any argument that is a reference to
651// 'variable'. This matcher is polymorphic as it can match any
652// super type of the type of 'variable'.
653//
654// The RefMatcher template class implements Ref(variable). It can
655// only be instantiated with a reference type. This prevents a user
656// from mistakenly using Ref(x) to match a non-reference function
657// argument. For example, the following will righteously cause a
658// compiler error:
659//
660// int n;
661// Matcher<int> m1 = Ref(n); // This won't compile.
662// Matcher<int&> m2 = Ref(n); // This will compile.
663template <typename T>
664class RefMatcher;
665
666template <typename T>
667class RefMatcher<T&> {
668 // Google Mock is a generic framework and thus needs to support
669 // mocking any function types, including those that take non-const
670 // reference arguments. Therefore the template parameter T (and
671 // Super below) can be instantiated to either a const type or a
672 // non-const type.
673 public:
674 // RefMatcher() takes a T& instead of const T&, as we want the
675 // compiler to catch using Ref(const_value) as a matcher for a
676 // non-const reference.
677 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
678
679 template <typename Super>
680 operator Matcher<Super&>() const {
681 // By passing object_ (type T&) to Impl(), which expects a Super&,
682 // we make sure that Super is a super type of T. In particular,
683 // this catches using Ref(const_value) as a matcher for a
684 // non-const reference, as you cannot implicitly convert a const
685 // reference to a non-const reference.
686 return MakeMatcher(new Impl<Super>(object_));
687 }
688 private:
689 template <typename Super>
690 class Impl : public MatcherInterface<Super&> {
691 public:
692 explicit Impl(Super& x) : object_(x) {} // NOLINT
693
694 // Matches() takes a Super& (as opposed to const Super&) in
695 // order to match the interface MatcherInterface<Super&>.
696 virtual bool Matches(Super& x) const { return &x == &object_; } // NOLINT
697
698 virtual void DescribeTo(::std::ostream* os) const {
699 *os << "references the variable ";
700 UniversalPrinter<Super&>::Print(object_, os);
701 }
702
703 virtual void DescribeNegationTo(::std::ostream* os) const {
704 *os << "does not reference the variable ";
705 UniversalPrinter<Super&>::Print(object_, os);
706 }
707
708 virtual void ExplainMatchResultTo(Super& x, // NOLINT
709 ::std::ostream* os) const {
710 *os << "is located @" << static_cast<const void*>(&x);
711 }
712 private:
713 const Super& object_;
714 };
715
716 T& object_;
717};
718
719// Polymorphic helper functions for narrow and wide string matchers.
720inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
721 return String::CaseInsensitiveCStringEquals(lhs, rhs);
722}
723
724inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
725 const wchar_t* rhs) {
726 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
727}
728
729// String comparison for narrow or wide strings that can have embedded NUL
730// characters.
731template <typename StringType>
732bool CaseInsensitiveStringEquals(const StringType& s1,
733 const StringType& s2) {
734 // Are the heads equal?
735 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
736 return false;
737 }
738
739 // Skip the equal heads.
740 const typename StringType::value_type nul = 0;
741 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
742
743 // Are we at the end of either s1 or s2?
744 if (i1 == StringType::npos || i2 == StringType::npos) {
745 return i1 == i2;
746 }
747
748 // Are the tails equal?
749 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
750}
751
752// String matchers.
753
754// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
755template <typename StringType>
756class StrEqualityMatcher {
757 public:
758 typedef typename StringType::const_pointer ConstCharPointer;
759
760 StrEqualityMatcher(const StringType& str, bool expect_eq,
761 bool case_sensitive)
762 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
763
764 // When expect_eq_ is true, returns true iff s is equal to string_;
765 // otherwise returns true iff s is not equal to string_.
766 bool Matches(ConstCharPointer s) const {
767 if (s == NULL) {
768 return !expect_eq_;
769 }
770 return Matches(StringType(s));
771 }
772
773 bool Matches(const StringType& s) const {
774 const bool eq = case_sensitive_ ? s == string_ :
775 CaseInsensitiveStringEquals(s, string_);
776 return expect_eq_ == eq;
777 }
778
779 void DescribeTo(::std::ostream* os) const {
780 DescribeToHelper(expect_eq_, os);
781 }
782
783 void DescribeNegationTo(::std::ostream* os) const {
784 DescribeToHelper(!expect_eq_, os);
785 }
786 private:
787 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
788 *os << "is ";
789 if (!expect_eq) {
790 *os << "not ";
791 }
792 *os << "equal to ";
793 if (!case_sensitive_) {
794 *os << "(ignoring case) ";
795 }
796 UniversalPrinter<StringType>::Print(string_, os);
797 }
798
799 const StringType string_;
800 const bool expect_eq_;
801 const bool case_sensitive_;
802};
803
804// Implements the polymorphic HasSubstr(substring) matcher, which
805// can be used as a Matcher<T> as long as T can be converted to a
806// string.
807template <typename StringType>
808class HasSubstrMatcher {
809 public:
810 typedef typename StringType::const_pointer ConstCharPointer;
811
812 explicit HasSubstrMatcher(const StringType& substring)
813 : substring_(substring) {}
814
815 // These overloaded methods allow HasSubstr(substring) to be used as a
816 // Matcher<T> as long as T can be converted to string. Returns true
817 // iff s contains substring_ as a substring.
818 bool Matches(ConstCharPointer s) const {
819 return s != NULL && Matches(StringType(s));
820 }
821
822 bool Matches(const StringType& s) const {
823 return s.find(substring_) != StringType::npos;
824 }
825
826 // Describes what this matcher matches.
827 void DescribeTo(::std::ostream* os) const {
828 *os << "has substring ";
829 UniversalPrinter<StringType>::Print(substring_, os);
830 }
831
832 void DescribeNegationTo(::std::ostream* os) const {
833 *os << "has no substring ";
834 UniversalPrinter<StringType>::Print(substring_, os);
835 }
836 private:
837 const StringType substring_;
838};
839
840// Implements the polymorphic StartsWith(substring) matcher, which
841// can be used as a Matcher<T> as long as T can be converted to a
842// string.
843template <typename StringType>
844class StartsWithMatcher {
845 public:
846 typedef typename StringType::const_pointer ConstCharPointer;
847
848 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
849 }
850
851 // These overloaded methods allow StartsWith(prefix) to be used as a
852 // Matcher<T> as long as T can be converted to string. Returns true
853 // iff s starts with prefix_.
854 bool Matches(ConstCharPointer s) const {
855 return s != NULL && Matches(StringType(s));
856 }
857
858 bool Matches(const StringType& s) const {
859 return s.length() >= prefix_.length() &&
860 s.substr(0, prefix_.length()) == prefix_;
861 }
862
863 void DescribeTo(::std::ostream* os) const {
864 *os << "starts with ";
865 UniversalPrinter<StringType>::Print(prefix_, os);
866 }
867
868 void DescribeNegationTo(::std::ostream* os) const {
869 *os << "doesn't start with ";
870 UniversalPrinter<StringType>::Print(prefix_, os);
871 }
872 private:
873 const StringType prefix_;
874};
875
876// Implements the polymorphic EndsWith(substring) matcher, which
877// can be used as a Matcher<T> as long as T can be converted to a
878// string.
879template <typename StringType>
880class EndsWithMatcher {
881 public:
882 typedef typename StringType::const_pointer ConstCharPointer;
883
884 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
885
886 // These overloaded methods allow EndsWith(suffix) to be used as a
887 // Matcher<T> as long as T can be converted to string. Returns true
888 // iff s ends with suffix_.
889 bool Matches(ConstCharPointer s) const {
890 return s != NULL && Matches(StringType(s));
891 }
892
893 bool Matches(const StringType& s) const {
894 return s.length() >= suffix_.length() &&
895 s.substr(s.length() - suffix_.length()) == suffix_;
896 }
897
898 void DescribeTo(::std::ostream* os) const {
899 *os << "ends with ";
900 UniversalPrinter<StringType>::Print(suffix_, os);
901 }
902
903 void DescribeNegationTo(::std::ostream* os) const {
904 *os << "doesn't end with ";
905 UniversalPrinter<StringType>::Print(suffix_, os);
906 }
907 private:
908 const StringType suffix_;
909};
910
911#if GMOCK_HAS_REGEX
912
913// Implements polymorphic matchers MatchesRegex(regex) and
914// ContainsRegex(regex), which can be used as a Matcher<T> as long as
915// T can be converted to a string.
916class MatchesRegexMatcher {
917 public:
918 MatchesRegexMatcher(const RE* regex, bool full_match)
919 : regex_(regex), full_match_(full_match) {}
920
921 // These overloaded methods allow MatchesRegex(regex) to be used as
922 // a Matcher<T> as long as T can be converted to string. Returns
923 // true iff s matches regular expression regex. When full_match_ is
924 // true, a full match is done; otherwise a partial match is done.
925 bool Matches(const char* s) const {
926 return s != NULL && Matches(internal::string(s));
927 }
928
929 bool Matches(const internal::string& s) const {
930 return full_match_ ? RE::FullMatch(s, *regex_) :
931 RE::PartialMatch(s, *regex_);
932 }
933
934 void DescribeTo(::std::ostream* os) const {
935 *os << (full_match_ ? "matches" : "contains")
936 << " regular expression ";
937 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
938 }
939
940 void DescribeNegationTo(::std::ostream* os) const {
941 *os << "doesn't " << (full_match_ ? "match" : "contain")
942 << " regular expression ";
943 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
944 }
945 private:
946 const internal::linked_ptr<const RE> regex_;
947 const bool full_match_;
948};
949
950#endif // GMOCK_HAS_REGEX
951
952// Implements a matcher that compares the two fields of a 2-tuple
953// using one of the ==, <=, <, etc, operators. The two fields being
954// compared don't have to have the same type.
955//
956// The matcher defined here is polymorphic (for example, Eq() can be
957// used to match a tuple<int, short>, a tuple<const long&, double>,
958// etc). Therefore we use a template type conversion operator in the
959// implementation.
960//
961// We define this as a macro in order to eliminate duplicated source
962// code.
zhanyong.wan2661c682009-06-09 05:42:12 +0000963#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op) \
shiqiane35fdd92008-12-10 05:08:54 +0000964 class name##2Matcher { \
965 public: \
966 template <typename T1, typename T2> \
967 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
968 return MakeMatcher(new Impl<T1, T2>); \
969 } \
970 private: \
971 template <typename T1, typename T2> \
972 class Impl : public MatcherInterface<const ::std::tr1::tuple<T1, T2>&> { \
973 public: \
974 virtual bool Matches(const ::std::tr1::tuple<T1, T2>& args) const { \
975 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
976 } \
977 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +0000978 *os << "are a pair (x, y) where x " #op " y"; \
shiqiane35fdd92008-12-10 05:08:54 +0000979 } \
980 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +0000981 *os << "are a pair (x, y) where x " #op " y is false"; \
shiqiane35fdd92008-12-10 05:08:54 +0000982 } \
983 }; \
984 }
985
986// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wan2661c682009-06-09 05:42:12 +0000987GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==);
988GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ge, >=);
989GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Gt, >);
990GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Le, <=);
991GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Lt, <);
992GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=);
shiqiane35fdd92008-12-10 05:08:54 +0000993
zhanyong.wane0d051e2009-02-19 00:33:37 +0000994#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000995
zhanyong.wanc6a41232009-05-13 23:38:40 +0000996// Implements the Not(...) matcher for a particular argument type T.
997// We do not nest it inside the NotMatcher class template, as that
998// will prevent different instantiations of NotMatcher from sharing
999// the same NotMatcherImpl<T> class.
1000template <typename T>
1001class NotMatcherImpl : public MatcherInterface<T> {
1002 public:
1003 explicit NotMatcherImpl(const Matcher<T>& matcher)
1004 : matcher_(matcher) {}
1005
1006 virtual bool Matches(T x) const {
1007 return !matcher_.Matches(x);
1008 }
1009
1010 virtual void DescribeTo(::std::ostream* os) const {
1011 matcher_.DescribeNegationTo(os);
1012 }
1013
1014 virtual void DescribeNegationTo(::std::ostream* os) const {
1015 matcher_.DescribeTo(os);
1016 }
1017
1018 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1019 matcher_.ExplainMatchResultTo(x, os);
1020 }
1021 private:
1022 const Matcher<T> matcher_;
1023};
1024
shiqiane35fdd92008-12-10 05:08:54 +00001025// Implements the Not(m) matcher, which matches a value that doesn't
1026// match matcher m.
1027template <typename InnerMatcher>
1028class NotMatcher {
1029 public:
1030 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1031
1032 // This template type conversion operator allows Not(m) to be used
1033 // to match any type m can match.
1034 template <typename T>
1035 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001036 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001037 }
1038 private:
shiqiane35fdd92008-12-10 05:08:54 +00001039 InnerMatcher matcher_;
1040};
1041
zhanyong.wanc6a41232009-05-13 23:38:40 +00001042// Implements the AllOf(m1, m2) matcher for a particular argument type
1043// T. We do not nest it inside the BothOfMatcher class template, as
1044// that will prevent different instantiations of BothOfMatcher from
1045// sharing the same BothOfMatcherImpl<T> class.
1046template <typename T>
1047class BothOfMatcherImpl : public MatcherInterface<T> {
1048 public:
1049 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1050 : matcher1_(matcher1), matcher2_(matcher2) {}
1051
1052 virtual bool Matches(T x) const {
1053 return matcher1_.Matches(x) && matcher2_.Matches(x);
1054 }
1055
1056 virtual void DescribeTo(::std::ostream* os) const {
1057 *os << "(";
1058 matcher1_.DescribeTo(os);
1059 *os << ") and (";
1060 matcher2_.DescribeTo(os);
1061 *os << ")";
1062 }
1063
1064 virtual void DescribeNegationTo(::std::ostream* os) const {
1065 *os << "not ";
1066 DescribeTo(os);
1067 }
1068
1069 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1070 if (Matches(x)) {
1071 // When both matcher1_ and matcher2_ match x, we need to
1072 // explain why *both* of them match.
1073 ::std::stringstream ss1;
1074 matcher1_.ExplainMatchResultTo(x, &ss1);
1075 const internal::string s1 = ss1.str();
1076
1077 ::std::stringstream ss2;
1078 matcher2_.ExplainMatchResultTo(x, &ss2);
1079 const internal::string s2 = ss2.str();
1080
1081 if (s1 == "") {
1082 *os << s2;
1083 } else {
1084 *os << s1;
1085 if (s2 != "") {
1086 *os << "; " << s2;
1087 }
1088 }
1089 } else {
1090 // Otherwise we only need to explain why *one* of them fails
1091 // to match.
1092 if (!matcher1_.Matches(x)) {
1093 matcher1_.ExplainMatchResultTo(x, os);
1094 } else {
1095 matcher2_.ExplainMatchResultTo(x, os);
1096 }
1097 }
1098 }
1099 private:
1100 const Matcher<T> matcher1_;
1101 const Matcher<T> matcher2_;
1102};
1103
shiqiane35fdd92008-12-10 05:08:54 +00001104// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1105// matches a value that matches all of the matchers m_1, ..., and m_n.
1106template <typename Matcher1, typename Matcher2>
1107class BothOfMatcher {
1108 public:
1109 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1110 : matcher1_(matcher1), matcher2_(matcher2) {}
1111
1112 // This template type conversion operator allows a
1113 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1114 // both Matcher1 and Matcher2 can match.
1115 template <typename T>
1116 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001117 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1118 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001119 }
1120 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001121 Matcher1 matcher1_;
1122 Matcher2 matcher2_;
1123};
shiqiane35fdd92008-12-10 05:08:54 +00001124
zhanyong.wanc6a41232009-05-13 23:38:40 +00001125// Implements the AnyOf(m1, m2) matcher for a particular argument type
1126// T. We do not nest it inside the AnyOfMatcher class template, as
1127// that will prevent different instantiations of AnyOfMatcher from
1128// sharing the same EitherOfMatcherImpl<T> class.
1129template <typename T>
1130class EitherOfMatcherImpl : public MatcherInterface<T> {
1131 public:
1132 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1133 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001134
zhanyong.wanc6a41232009-05-13 23:38:40 +00001135 virtual bool Matches(T x) const {
1136 return matcher1_.Matches(x) || matcher2_.Matches(x);
1137 }
shiqiane35fdd92008-12-10 05:08:54 +00001138
zhanyong.wanc6a41232009-05-13 23:38:40 +00001139 virtual void DescribeTo(::std::ostream* os) const {
1140 *os << "(";
1141 matcher1_.DescribeTo(os);
1142 *os << ") or (";
1143 matcher2_.DescribeTo(os);
1144 *os << ")";
1145 }
shiqiane35fdd92008-12-10 05:08:54 +00001146
zhanyong.wanc6a41232009-05-13 23:38:40 +00001147 virtual void DescribeNegationTo(::std::ostream* os) const {
1148 *os << "not ";
1149 DescribeTo(os);
1150 }
shiqiane35fdd92008-12-10 05:08:54 +00001151
zhanyong.wanc6a41232009-05-13 23:38:40 +00001152 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1153 if (Matches(x)) {
1154 // If either matcher1_ or matcher2_ matches x, we just need
1155 // to explain why *one* of them matches.
1156 if (matcher1_.Matches(x)) {
1157 matcher1_.ExplainMatchResultTo(x, os);
shiqiane35fdd92008-12-10 05:08:54 +00001158 } else {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001159 matcher2_.ExplainMatchResultTo(x, os);
1160 }
1161 } else {
1162 // Otherwise we need to explain why *neither* matches.
1163 ::std::stringstream ss1;
1164 matcher1_.ExplainMatchResultTo(x, &ss1);
1165 const internal::string s1 = ss1.str();
1166
1167 ::std::stringstream ss2;
1168 matcher2_.ExplainMatchResultTo(x, &ss2);
1169 const internal::string s2 = ss2.str();
1170
1171 if (s1 == "") {
1172 *os << s2;
1173 } else {
1174 *os << s1;
1175 if (s2 != "") {
1176 *os << "; " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001177 }
1178 }
1179 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001180 }
1181 private:
1182 const Matcher<T> matcher1_;
1183 const Matcher<T> matcher2_;
shiqiane35fdd92008-12-10 05:08:54 +00001184};
1185
1186// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1187// matches a value that matches at least one of the matchers m_1, ...,
1188// and m_n.
1189template <typename Matcher1, typename Matcher2>
1190class EitherOfMatcher {
1191 public:
1192 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1193 : matcher1_(matcher1), matcher2_(matcher2) {}
1194
1195 // This template type conversion operator allows a
1196 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1197 // both Matcher1 and Matcher2 can match.
1198 template <typename T>
1199 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001200 return Matcher<T>(new EitherOfMatcherImpl<T>(
1201 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001202 }
1203 private:
shiqiane35fdd92008-12-10 05:08:54 +00001204 Matcher1 matcher1_;
1205 Matcher2 matcher2_;
1206};
1207
1208// Used for implementing Truly(pred), which turns a predicate into a
1209// matcher.
1210template <typename Predicate>
1211class TrulyMatcher {
1212 public:
1213 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1214
1215 // This method template allows Truly(pred) to be used as a matcher
1216 // for type T where T is the argument type of predicate 'pred'. The
1217 // argument is passed by reference as the predicate may be
1218 // interested in the address of the argument.
1219 template <typename T>
zhanyong.wan16cf4732009-05-14 20:55:30 +00001220 bool Matches(T& x) const { // NOLINT
zhanyong.wan652540a2009-02-23 23:37:29 +00001221#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001222 // MSVC warns about converting a value into bool (warning 4800).
1223#pragma warning(push) // Saves the current warning state.
1224#pragma warning(disable:4800) // Temporarily disables warning 4800.
1225#endif // GTEST_OS_WINDOWS
1226 return predicate_(x);
zhanyong.wan652540a2009-02-23 23:37:29 +00001227#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001228#pragma warning(pop) // Restores the warning state.
1229#endif // GTEST_OS_WINDOWS
1230 }
1231
1232 void DescribeTo(::std::ostream* os) const {
1233 *os << "satisfies the given predicate";
1234 }
1235
1236 void DescribeNegationTo(::std::ostream* os) const {
1237 *os << "doesn't satisfy the given predicate";
1238 }
1239 private:
1240 Predicate predicate_;
1241};
1242
1243// Used for implementing Matches(matcher), which turns a matcher into
1244// a predicate.
1245template <typename M>
1246class MatcherAsPredicate {
1247 public:
1248 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1249
1250 // This template operator() allows Matches(m) to be used as a
1251 // predicate on type T where m is a matcher on type T.
1252 //
1253 // The argument x is passed by reference instead of by value, as
1254 // some matcher may be interested in its address (e.g. as in
1255 // Matches(Ref(n))(x)).
1256 template <typename T>
1257 bool operator()(const T& x) const {
1258 // We let matcher_ commit to a particular type here instead of
1259 // when the MatcherAsPredicate object was constructed. This
1260 // allows us to write Matches(m) where m is a polymorphic matcher
1261 // (e.g. Eq(5)).
1262 //
1263 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1264 // compile when matcher_ has type Matcher<const T&>; if we write
1265 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1266 // when matcher_ has type Matcher<T>; if we just write
1267 // matcher_.Matches(x), it won't compile when matcher_ is
1268 // polymorphic, e.g. Eq(5).
1269 //
1270 // MatcherCast<const T&>() is necessary for making the code work
1271 // in all of the above situations.
1272 return MatcherCast<const T&>(matcher_).Matches(x);
1273 }
1274 private:
1275 M matcher_;
1276};
1277
1278// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1279// argument M must be a type that can be converted to a matcher.
1280template <typename M>
1281class PredicateFormatterFromMatcher {
1282 public:
1283 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1284
1285 // This template () operator allows a PredicateFormatterFromMatcher
1286 // object to act as a predicate-formatter suitable for using with
1287 // Google Test's EXPECT_PRED_FORMAT1() macro.
1288 template <typename T>
1289 AssertionResult operator()(const char* value_text, const T& x) const {
1290 // We convert matcher_ to a Matcher<const T&> *now* instead of
1291 // when the PredicateFormatterFromMatcher object was constructed,
1292 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1293 // know which type to instantiate it to until we actually see the
1294 // type of x here.
1295 //
1296 // We write MatcherCast<const T&>(matcher_) instead of
1297 // Matcher<const T&>(matcher_), as the latter won't compile when
1298 // matcher_ has type Matcher<T> (e.g. An<int>()).
1299 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
1300 if (matcher.Matches(x)) {
1301 return AssertionSuccess();
1302 } else {
1303 ::std::stringstream ss;
1304 ss << "Value of: " << value_text << "\n"
1305 << "Expected: ";
1306 matcher.DescribeTo(&ss);
1307 ss << "\n Actual: ";
1308 UniversalPrinter<T>::Print(x, &ss);
1309 ExplainMatchResultAsNeededTo<const T&>(matcher, x, &ss);
1310 return AssertionFailure(Message() << ss.str());
1311 }
1312 }
1313 private:
1314 const M matcher_;
1315};
1316
1317// A helper function for converting a matcher to a predicate-formatter
1318// without the user needing to explicitly write the type. This is
1319// used for implementing ASSERT_THAT() and EXPECT_THAT().
1320template <typename M>
1321inline PredicateFormatterFromMatcher<M>
1322MakePredicateFormatterFromMatcher(const M& matcher) {
1323 return PredicateFormatterFromMatcher<M>(matcher);
1324}
1325
1326// Implements the polymorphic floating point equality matcher, which
1327// matches two float values using ULP-based approximation. The
1328// template is meant to be instantiated with FloatType being either
1329// float or double.
1330template <typename FloatType>
1331class FloatingEqMatcher {
1332 public:
1333 // Constructor for FloatingEqMatcher.
1334 // The matcher's input will be compared with rhs. The matcher treats two
1335 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1336 // equality comparisons between NANs will always return false.
1337 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1338 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1339
1340 // Implements floating point equality matcher as a Matcher<T>.
1341 template <typename T>
1342 class Impl : public MatcherInterface<T> {
1343 public:
1344 Impl(FloatType rhs, bool nan_eq_nan) :
1345 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1346
1347 virtual bool Matches(T value) const {
1348 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1349
1350 // Compares NaNs first, if nan_eq_nan_ is true.
1351 if (nan_eq_nan_ && lhs.is_nan()) {
1352 return rhs.is_nan();
1353 }
1354
1355 return lhs.AlmostEquals(rhs);
1356 }
1357
1358 virtual void DescribeTo(::std::ostream* os) const {
1359 // os->precision() returns the previously set precision, which we
1360 // store to restore the ostream to its original configuration
1361 // after outputting.
1362 const ::std::streamsize old_precision = os->precision(
1363 ::std::numeric_limits<FloatType>::digits10 + 2);
1364 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1365 if (nan_eq_nan_) {
1366 *os << "is NaN";
1367 } else {
1368 *os << "never matches";
1369 }
1370 } else {
1371 *os << "is approximately " << rhs_;
1372 }
1373 os->precision(old_precision);
1374 }
1375
1376 virtual void DescribeNegationTo(::std::ostream* os) const {
1377 // As before, get original precision.
1378 const ::std::streamsize old_precision = os->precision(
1379 ::std::numeric_limits<FloatType>::digits10 + 2);
1380 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1381 if (nan_eq_nan_) {
1382 *os << "is not NaN";
1383 } else {
1384 *os << "is anything";
1385 }
1386 } else {
1387 *os << "is not approximately " << rhs_;
1388 }
1389 // Restore original precision.
1390 os->precision(old_precision);
1391 }
1392
1393 private:
1394 const FloatType rhs_;
1395 const bool nan_eq_nan_;
1396 };
1397
1398 // The following 3 type conversion operators allow FloatEq(rhs) and
1399 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1400 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1401 // (While Google's C++ coding style doesn't allow arguments passed
1402 // by non-const reference, we may see them in code not conforming to
1403 // the style. Therefore Google Mock needs to support them.)
1404 operator Matcher<FloatType>() const {
1405 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1406 }
1407
1408 operator Matcher<const FloatType&>() const {
1409 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1410 }
1411
1412 operator Matcher<FloatType&>() const {
1413 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1414 }
1415 private:
1416 const FloatType rhs_;
1417 const bool nan_eq_nan_;
1418};
1419
1420// Implements the Pointee(m) matcher for matching a pointer whose
1421// pointee matches matcher m. The pointer can be either raw or smart.
1422template <typename InnerMatcher>
1423class PointeeMatcher {
1424 public:
1425 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1426
1427 // This type conversion operator template allows Pointee(m) to be
1428 // used as a matcher for any pointer type whose pointee type is
1429 // compatible with the inner matcher, where type Pointer can be
1430 // either a raw pointer or a smart pointer.
1431 //
1432 // The reason we do this instead of relying on
1433 // MakePolymorphicMatcher() is that the latter is not flexible
1434 // enough for implementing the DescribeTo() method of Pointee().
1435 template <typename Pointer>
1436 operator Matcher<Pointer>() const {
1437 return MakeMatcher(new Impl<Pointer>(matcher_));
1438 }
1439 private:
1440 // The monomorphic implementation that works for a particular pointer type.
1441 template <typename Pointer>
1442 class Impl : public MatcherInterface<Pointer> {
1443 public:
zhanyong.wane0d051e2009-02-19 00:33:37 +00001444 typedef typename PointeeOf<GMOCK_REMOVE_CONST_( // NOLINT
1445 GMOCK_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001446
1447 explicit Impl(const InnerMatcher& matcher)
1448 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1449
1450 virtual bool Matches(Pointer p) const {
1451 return GetRawPointer(p) != NULL && matcher_.Matches(*p);
1452 }
1453
1454 virtual void DescribeTo(::std::ostream* os) const {
1455 *os << "points to a value that ";
1456 matcher_.DescribeTo(os);
1457 }
1458
1459 virtual void DescribeNegationTo(::std::ostream* os) const {
1460 *os << "does not point to a value that ";
1461 matcher_.DescribeTo(os);
1462 }
1463
1464 virtual void ExplainMatchResultTo(Pointer pointer,
1465 ::std::ostream* os) const {
1466 if (GetRawPointer(pointer) == NULL)
1467 return;
1468
1469 ::std::stringstream ss;
1470 matcher_.ExplainMatchResultTo(*pointer, &ss);
1471 const internal::string s = ss.str();
1472 if (s != "") {
1473 *os << "points to a value that " << s;
1474 }
1475 }
1476 private:
1477 const Matcher<const Pointee&> matcher_;
1478 };
1479
1480 const InnerMatcher matcher_;
1481};
1482
1483// Implements the Field() matcher for matching a field (i.e. member
1484// variable) of an object.
1485template <typename Class, typename FieldType>
1486class FieldMatcher {
1487 public:
1488 FieldMatcher(FieldType Class::*field,
1489 const Matcher<const FieldType&>& matcher)
1490 : field_(field), matcher_(matcher) {}
1491
1492 // Returns true iff the inner matcher matches obj.field.
1493 bool Matches(const Class& obj) const {
1494 return matcher_.Matches(obj.*field_);
1495 }
1496
1497 // Returns true iff the inner matcher matches obj->field.
1498 bool Matches(const Class* p) const {
1499 return (p != NULL) && matcher_.Matches(p->*field_);
1500 }
1501
1502 void DescribeTo(::std::ostream* os) const {
1503 *os << "the given field ";
1504 matcher_.DescribeTo(os);
1505 }
1506
1507 void DescribeNegationTo(::std::ostream* os) const {
1508 *os << "the given field ";
1509 matcher_.DescribeNegationTo(os);
1510 }
1511
zhanyong.wan18490652009-05-11 18:54:08 +00001512 // The first argument of ExplainMatchResultTo() is needed to help
1513 // Symbian's C++ compiler choose which overload to use. Its type is
1514 // true_type iff the Field() matcher is used to match a pointer.
1515 void ExplainMatchResultTo(false_type /* is_not_pointer */, const Class& obj,
1516 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001517 ::std::stringstream ss;
1518 matcher_.ExplainMatchResultTo(obj.*field_, &ss);
1519 const internal::string s = ss.str();
1520 if (s != "") {
1521 *os << "the given field " << s;
1522 }
1523 }
1524
zhanyong.wan18490652009-05-11 18:54:08 +00001525 void ExplainMatchResultTo(true_type /* is_pointer */, const Class* p,
1526 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001527 if (p != NULL) {
zhanyong.wan18490652009-05-11 18:54:08 +00001528 // Since *p has a field, it must be a class/struct/union type
1529 // and thus cannot be a pointer. Therefore we pass false_type()
1530 // as the first argument.
1531 ExplainMatchResultTo(false_type(), *p, os);
shiqiane35fdd92008-12-10 05:08:54 +00001532 }
1533 }
1534 private:
1535 const FieldType Class::*field_;
1536 const Matcher<const FieldType&> matcher_;
1537};
1538
zhanyong.wan18490652009-05-11 18:54:08 +00001539// Explains the result of matching an object or pointer against a field matcher.
1540template <typename Class, typename FieldType, typename T>
shiqiane35fdd92008-12-10 05:08:54 +00001541void ExplainMatchResultTo(const FieldMatcher<Class, FieldType>& matcher,
zhanyong.wan18490652009-05-11 18:54:08 +00001542 const T& value, ::std::ostream* os) {
1543 matcher.ExplainMatchResultTo(
1544 typename ::testing::internal::is_pointer<T>::type(), value, os);
shiqiane35fdd92008-12-10 05:08:54 +00001545}
1546
1547// Implements the Property() matcher for matching a property
1548// (i.e. return value of a getter method) of an object.
1549template <typename Class, typename PropertyType>
1550class PropertyMatcher {
1551 public:
1552 // The property may have a reference type, so 'const PropertyType&'
1553 // may cause double references and fail to compile. That's why we
1554 // need GMOCK_REFERENCE_TO_CONST, which works regardless of
1555 // PropertyType being a reference or not.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001556 typedef GMOCK_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001557
1558 PropertyMatcher(PropertyType (Class::*property)() const,
1559 const Matcher<RefToConstProperty>& matcher)
1560 : property_(property), matcher_(matcher) {}
1561
1562 // Returns true iff obj.property() matches the inner matcher.
1563 bool Matches(const Class& obj) const {
1564 return matcher_.Matches((obj.*property_)());
1565 }
1566
1567 // Returns true iff p->property() matches the inner matcher.
1568 bool Matches(const Class* p) const {
1569 return (p != NULL) && matcher_.Matches((p->*property_)());
1570 }
1571
1572 void DescribeTo(::std::ostream* os) const {
1573 *os << "the given property ";
1574 matcher_.DescribeTo(os);
1575 }
1576
1577 void DescribeNegationTo(::std::ostream* os) const {
1578 *os << "the given property ";
1579 matcher_.DescribeNegationTo(os);
1580 }
1581
zhanyong.wan18490652009-05-11 18:54:08 +00001582 // The first argument of ExplainMatchResultTo() is needed to help
1583 // Symbian's C++ compiler choose which overload to use. Its type is
1584 // true_type iff the Property() matcher is used to match a pointer.
1585 void ExplainMatchResultTo(false_type /* is_not_pointer */, const Class& obj,
1586 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001587 ::std::stringstream ss;
1588 matcher_.ExplainMatchResultTo((obj.*property_)(), &ss);
1589 const internal::string s = ss.str();
1590 if (s != "") {
1591 *os << "the given property " << s;
1592 }
1593 }
1594
zhanyong.wan18490652009-05-11 18:54:08 +00001595 void ExplainMatchResultTo(true_type /* is_pointer */, const Class* p,
1596 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001597 if (p != NULL) {
zhanyong.wan18490652009-05-11 18:54:08 +00001598 // Since *p has a property method, it must be a
1599 // class/struct/union type and thus cannot be a pointer.
1600 // Therefore we pass false_type() as the first argument.
1601 ExplainMatchResultTo(false_type(), *p, os);
shiqiane35fdd92008-12-10 05:08:54 +00001602 }
1603 }
1604 private:
1605 PropertyType (Class::*property_)() const;
1606 const Matcher<RefToConstProperty> matcher_;
1607};
1608
zhanyong.wan18490652009-05-11 18:54:08 +00001609// Explains the result of matching an object or pointer against a
1610// property matcher.
1611template <typename Class, typename PropertyType, typename T>
shiqiane35fdd92008-12-10 05:08:54 +00001612void ExplainMatchResultTo(const PropertyMatcher<Class, PropertyType>& matcher,
zhanyong.wan18490652009-05-11 18:54:08 +00001613 const T& value, ::std::ostream* os) {
1614 matcher.ExplainMatchResultTo(
1615 typename ::testing::internal::is_pointer<T>::type(), value, os);
shiqiane35fdd92008-12-10 05:08:54 +00001616}
1617
1618// Type traits specifying various features of different functors for ResultOf.
1619// The default template specifies features for functor objects.
1620// Functor classes have to typedef argument_type and result_type
1621// to be compatible with ResultOf.
1622template <typename Functor>
1623struct CallableTraits {
1624 typedef typename Functor::result_type ResultType;
1625 typedef Functor StorageType;
1626
1627 static void CheckIsValid(Functor functor) {}
1628 template <typename T>
1629 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1630};
1631
1632// Specialization for function pointers.
1633template <typename ArgType, typename ResType>
1634struct CallableTraits<ResType(*)(ArgType)> {
1635 typedef ResType ResultType;
1636 typedef ResType(*StorageType)(ArgType);
1637
1638 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001639 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00001640 << "NULL function pointer is passed into ResultOf().";
1641 }
1642 template <typename T>
1643 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1644 return (*f)(arg);
1645 }
1646};
1647
1648// Implements the ResultOf() matcher for matching a return value of a
1649// unary function of an object.
1650template <typename Callable>
1651class ResultOfMatcher {
1652 public:
1653 typedef typename CallableTraits<Callable>::ResultType ResultType;
1654
1655 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1656 : callable_(callable), matcher_(matcher) {
1657 CallableTraits<Callable>::CheckIsValid(callable_);
1658 }
1659
1660 template <typename T>
1661 operator Matcher<T>() const {
1662 return Matcher<T>(new Impl<T>(callable_, matcher_));
1663 }
1664
1665 private:
1666 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1667
1668 template <typename T>
1669 class Impl : public MatcherInterface<T> {
1670 public:
1671 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1672 : callable_(callable), matcher_(matcher) {}
1673 // Returns true iff callable_(obj) matches the inner matcher.
1674 // The calling syntax is different for different types of callables
1675 // so we abstract it in CallableTraits<Callable>::Invoke().
1676 virtual bool Matches(T obj) const {
1677 return matcher_.Matches(
1678 CallableTraits<Callable>::template Invoke<T>(callable_, obj));
1679 }
1680
1681 virtual void DescribeTo(::std::ostream* os) const {
1682 *os << "result of the given callable ";
1683 matcher_.DescribeTo(os);
1684 }
1685
1686 virtual void DescribeNegationTo(::std::ostream* os) const {
1687 *os << "result of the given callable ";
1688 matcher_.DescribeNegationTo(os);
1689 }
1690
1691 virtual void ExplainMatchResultTo(T obj, ::std::ostream* os) const {
1692 ::std::stringstream ss;
1693 matcher_.ExplainMatchResultTo(
1694 CallableTraits<Callable>::template Invoke<T>(callable_, obj),
1695 &ss);
1696 const internal::string s = ss.str();
1697 if (s != "")
1698 *os << "result of the given callable " << s;
1699 }
1700 private:
1701 // Functors often define operator() as non-const method even though
1702 // they are actualy stateless. But we need to use them even when
1703 // 'this' is a const pointer. It's the user's responsibility not to
1704 // use stateful callables with ResultOf(), which does't guarantee
1705 // how many times the callable will be invoked.
1706 mutable CallableStorageType callable_;
1707 const Matcher<ResultType> matcher_;
1708 }; // class Impl
1709
1710 const CallableStorageType callable_;
1711 const Matcher<ResultType> matcher_;
1712};
1713
1714// Explains the result of matching a value against a functor matcher.
1715template <typename T, typename Callable>
1716void ExplainMatchResultTo(const ResultOfMatcher<Callable>& matcher,
1717 T obj, ::std::ostream* os) {
1718 matcher.ExplainMatchResultTo(obj, os);
1719}
1720
zhanyong.wan6a896b52009-01-16 01:13:50 +00001721// Implements an equality matcher for any STL-style container whose elements
1722// support ==. This matcher is like Eq(), but its failure explanations provide
1723// more detailed information that is useful when the container is used as a set.
1724// The failure message reports elements that are in one of the operands but not
1725// the other. The failure messages do not report duplicate or out-of-order
1726// elements in the containers (which don't properly matter to sets, but can
1727// occur if the containers are vectors or lists, for example).
1728//
1729// Uses the container's const_iterator, value_type, operator ==,
1730// begin(), and end().
1731template <typename Container>
1732class ContainerEqMatcher {
1733 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00001734 typedef internal::StlContainerView<Container> View;
1735 typedef typename View::type StlContainer;
1736 typedef typename View::const_reference StlContainerReference;
1737
1738 // We make a copy of rhs in case the elements in it are modified
1739 // after this matcher is created.
1740 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
1741 // Makes sure the user doesn't instantiate this class template
1742 // with a const or reference type.
1743 testing::StaticAssertTypeEq<Container,
1744 GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))>();
1745 }
1746
1747 template <typename LhsContainer>
1748 bool Matches(const LhsContainer& lhs) const {
1749 // GMOCK_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
1750 // that causes LhsContainer to be a const type sometimes.
1751 typedef internal::StlContainerView<GMOCK_REMOVE_CONST_(LhsContainer)>
1752 LhsView;
1753 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
1754 return lhs_stl_container == rhs_;
1755 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00001756 void DescribeTo(::std::ostream* os) const {
1757 *os << "equals ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001758 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001759 }
1760 void DescribeNegationTo(::std::ostream* os) const {
1761 *os << "does not equal ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001762 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001763 }
1764
zhanyong.wanb8243162009-06-04 05:48:20 +00001765 template <typename LhsContainer>
1766 void ExplainMatchResultTo(const LhsContainer& lhs,
zhanyong.wan6a896b52009-01-16 01:13:50 +00001767 ::std::ostream* os) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00001768 // GMOCK_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
1769 // that causes LhsContainer to be a const type sometimes.
1770 typedef internal::StlContainerView<GMOCK_REMOVE_CONST_(LhsContainer)>
1771 LhsView;
1772 typedef typename LhsView::type LhsStlContainer;
1773 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
1774
zhanyong.wan6a896b52009-01-16 01:13:50 +00001775 // Something is different. Check for missing values first.
1776 bool printed_header = false;
zhanyong.wanb8243162009-06-04 05:48:20 +00001777 for (typename LhsStlContainer::const_iterator it =
1778 lhs_stl_container.begin();
1779 it != lhs_stl_container.end(); ++it) {
1780 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
1781 rhs_.end()) {
zhanyong.wan6a896b52009-01-16 01:13:50 +00001782 if (printed_header) {
1783 *os << ", ";
1784 } else {
1785 *os << "Only in actual: ";
1786 printed_header = true;
1787 }
zhanyong.wanb8243162009-06-04 05:48:20 +00001788 UniversalPrinter<typename LhsStlContainer::value_type>::Print(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001789 }
1790 }
1791
1792 // Now check for extra values.
1793 bool printed_header2 = false;
zhanyong.wanb8243162009-06-04 05:48:20 +00001794 for (typename StlContainer::const_iterator it = rhs_.begin();
zhanyong.wan6a896b52009-01-16 01:13:50 +00001795 it != rhs_.end(); ++it) {
zhanyong.wanb8243162009-06-04 05:48:20 +00001796 if (internal::ArrayAwareFind(
1797 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
1798 lhs_stl_container.end()) {
zhanyong.wan6a896b52009-01-16 01:13:50 +00001799 if (printed_header2) {
1800 *os << ", ";
1801 } else {
1802 *os << (printed_header ? "; not" : "Not") << " in actual: ";
1803 printed_header2 = true;
1804 }
zhanyong.wanb8243162009-06-04 05:48:20 +00001805 UniversalPrinter<typename StlContainer::value_type>::Print(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001806 }
1807 }
1808 }
1809 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00001810 const StlContainer rhs_;
zhanyong.wan6a896b52009-01-16 01:13:50 +00001811};
1812
zhanyong.wanb8243162009-06-04 05:48:20 +00001813template <typename LhsContainer, typename Container>
zhanyong.wan6a896b52009-01-16 01:13:50 +00001814void ExplainMatchResultTo(const ContainerEqMatcher<Container>& matcher,
zhanyong.wanb8243162009-06-04 05:48:20 +00001815 const LhsContainer& lhs,
zhanyong.wan6a896b52009-01-16 01:13:50 +00001816 ::std::ostream* os) {
1817 matcher.ExplainMatchResultTo(lhs, os);
1818}
1819
zhanyong.wanb8243162009-06-04 05:48:20 +00001820// Implements Contains(element_matcher) for the given argument type Container.
1821template <typename Container>
1822class ContainsMatcherImpl : public MatcherInterface<Container> {
1823 public:
1824 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
1825 typedef StlContainerView<RawContainer> View;
1826 typedef typename View::type StlContainer;
1827 typedef typename View::const_reference StlContainerReference;
1828 typedef typename StlContainer::value_type Element;
1829
1830 template <typename InnerMatcher>
1831 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
1832 : inner_matcher_(
1833 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
1834
1835 // Returns true iff 'container' matches.
1836 virtual bool Matches(Container container) const {
1837 StlContainerReference stl_container = View::ConstReference(container);
1838 for (typename StlContainer::const_iterator it = stl_container.begin();
1839 it != stl_container.end(); ++it) {
1840 if (inner_matcher_.Matches(*it))
1841 return true;
1842 }
1843 return false;
1844 }
1845
1846 // Describes what this matcher does.
1847 virtual void DescribeTo(::std::ostream* os) const {
1848 *os << "contains at least one element that ";
1849 inner_matcher_.DescribeTo(os);
1850 }
1851
1852 // Describes what the negation of this matcher does.
1853 virtual void DescribeNegationTo(::std::ostream* os) const {
1854 *os << "doesn't contain any element that ";
1855 inner_matcher_.DescribeTo(os);
1856 }
1857
1858 // Explains why 'container' matches, or doesn't match, this matcher.
1859 virtual void ExplainMatchResultTo(Container container,
1860 ::std::ostream* os) const {
1861 StlContainerReference stl_container = View::ConstReference(container);
1862
1863 // We need to explain which (if any) element matches inner_matcher_.
1864 typename StlContainer::const_iterator it = stl_container.begin();
1865 for (size_t i = 0; it != stl_container.end(); ++it, ++i) {
1866 if (inner_matcher_.Matches(*it)) {
1867 *os << "element " << i << " matches";
1868 return;
1869 }
1870 }
1871 }
1872
1873 private:
1874 const Matcher<const Element&> inner_matcher_;
1875};
1876
1877// Implements polymorphic Contains(element_matcher).
1878template <typename M>
1879class ContainsMatcher {
1880 public:
1881 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
1882
1883 template <typename Container>
1884 operator Matcher<Container>() const {
1885 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
1886 }
1887
1888 private:
1889 const M inner_matcher_;
1890};
1891
zhanyong.wanb5937da2009-07-16 20:26:41 +00001892// Implements Key(inner_matcher) for the given argument pair type.
1893// Key(inner_matcher) matches an std::pair whose 'first' field matches
1894// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
1895// std::map that contains at least one element whose key is >= 5.
1896template <typename PairType>
1897class KeyMatcherImpl : public MatcherInterface<PairType> {
1898 public:
1899 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
1900 typedef typename RawPairType::first_type KeyType;
1901
1902 template <typename InnerMatcher>
1903 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
1904 : inner_matcher_(
1905 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
1906 }
1907
1908 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
1909 virtual bool Matches(PairType key_value) const {
1910 return inner_matcher_.Matches(key_value.first);
1911 }
1912
1913 // Describes what this matcher does.
1914 virtual void DescribeTo(::std::ostream* os) const {
1915 *os << "has a key that ";
1916 inner_matcher_.DescribeTo(os);
1917 }
1918
1919 // Describes what the negation of this matcher does.
1920 virtual void DescribeNegationTo(::std::ostream* os) const {
1921 *os << "doesn't have a key that ";
1922 inner_matcher_.DescribeTo(os);
1923 }
1924
1925 // Explains why 'key_value' matches, or doesn't match, this matcher.
1926 virtual void ExplainMatchResultTo(PairType key_value,
1927 ::std::ostream* os) const {
1928 inner_matcher_.ExplainMatchResultTo(key_value.first, os);
1929 }
1930
1931 private:
1932 const Matcher<const KeyType&> inner_matcher_;
1933};
1934
1935// Implements polymorphic Key(matcher_for_key).
1936template <typename M>
1937class KeyMatcher {
1938 public:
1939 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
1940
1941 template <typename PairType>
1942 operator Matcher<PairType>() const {
1943 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
1944 }
1945
1946 private:
1947 const M matcher_for_key_;
1948};
1949
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001950// Implements Pair(first_matcher, second_matcher) for the given argument pair
1951// type with its two matchers. See Pair() function below.
1952template <typename PairType>
1953class PairMatcherImpl : public MatcherInterface<PairType> {
1954 public:
1955 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
1956 typedef typename RawPairType::first_type FirstType;
1957 typedef typename RawPairType::second_type SecondType;
1958
1959 template <typename FirstMatcher, typename SecondMatcher>
1960 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
1961 : first_matcher_(
1962 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
1963 second_matcher_(
1964 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
1965 }
1966
1967 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
1968 // matches second_matcher.
1969 virtual bool Matches(PairType a_pair) const {
1970 return first_matcher_.Matches(a_pair.first) &&
1971 second_matcher_.Matches(a_pair.second);
1972 }
1973
1974 // Describes what this matcher does.
1975 virtual void DescribeTo(::std::ostream* os) const {
1976 *os << "has a first field that ";
1977 first_matcher_.DescribeTo(os);
1978 *os << ", and has a second field that ";
1979 second_matcher_.DescribeTo(os);
1980 }
1981
1982 // Describes what the negation of this matcher does.
1983 virtual void DescribeNegationTo(::std::ostream* os) const {
1984 *os << "has a first field that ";
1985 first_matcher_.DescribeNegationTo(os);
1986 *os << ", or has a second field that ";
1987 second_matcher_.DescribeNegationTo(os);
1988 }
1989
1990 // Explains why 'a_pair' matches, or doesn't match, this matcher.
1991 virtual void ExplainMatchResultTo(PairType a_pair,
1992 ::std::ostream* os) const {
1993 ::std::stringstream ss1;
1994 first_matcher_.ExplainMatchResultTo(a_pair.first, &ss1);
1995 internal::string s1 = ss1.str();
1996 if (s1 != "") {
1997 s1 = "the first field " + s1;
1998 }
1999
2000 ::std::stringstream ss2;
2001 second_matcher_.ExplainMatchResultTo(a_pair.second, &ss2);
2002 internal::string s2 = ss2.str();
2003 if (s2 != "") {
2004 s2 = "the second field " + s2;
2005 }
2006
2007 *os << s1;
2008 if (s1 != "" && s2 != "") {
2009 *os << ", and ";
2010 }
2011 *os << s2;
2012 }
2013
2014 private:
2015 const Matcher<const FirstType&> first_matcher_;
2016 const Matcher<const SecondType&> second_matcher_;
2017};
2018
2019// Implements polymorphic Pair(first_matcher, second_matcher).
2020template <typename FirstMatcher, typename SecondMatcher>
2021class PairMatcher {
2022 public:
2023 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2024 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2025
2026 template <typename PairType>
2027 operator Matcher<PairType> () const {
2028 return MakeMatcher(
2029 new PairMatcherImpl<PairType>(
2030 first_matcher_, second_matcher_));
2031 }
2032
2033 private:
2034 const FirstMatcher first_matcher_;
2035 const SecondMatcher second_matcher_;
2036};
2037
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002038// Implements ElementsAre() and ElementsAreArray().
2039template <typename Container>
2040class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2041 public:
2042 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
2043 typedef internal::StlContainerView<RawContainer> View;
2044 typedef typename View::type StlContainer;
2045 typedef typename View::const_reference StlContainerReference;
2046 typedef typename StlContainer::value_type Element;
2047
2048 // Constructs the matcher from a sequence of element values or
2049 // element matchers.
2050 template <typename InputIter>
2051 ElementsAreMatcherImpl(InputIter first, size_t count) {
2052 matchers_.reserve(count);
2053 InputIter it = first;
2054 for (size_t i = 0; i != count; ++i, ++it) {
2055 matchers_.push_back(MatcherCast<const Element&>(*it));
2056 }
2057 }
2058
2059 // Returns true iff 'container' matches.
2060 virtual bool Matches(Container container) const {
2061 StlContainerReference stl_container = View::ConstReference(container);
2062 if (stl_container.size() != count())
2063 return false;
2064
2065 typename StlContainer::const_iterator it = stl_container.begin();
2066 for (size_t i = 0; i != count(); ++it, ++i) {
2067 if (!matchers_[i].Matches(*it))
2068 return false;
2069 }
2070
2071 return true;
2072 }
2073
2074 // Describes what this matcher does.
2075 virtual void DescribeTo(::std::ostream* os) const {
2076 if (count() == 0) {
2077 *os << "is empty";
2078 } else if (count() == 1) {
2079 *os << "has 1 element that ";
2080 matchers_[0].DescribeTo(os);
2081 } else {
2082 *os << "has " << Elements(count()) << " where\n";
2083 for (size_t i = 0; i != count(); ++i) {
2084 *os << "element " << i << " ";
2085 matchers_[i].DescribeTo(os);
2086 if (i + 1 < count()) {
2087 *os << ",\n";
2088 }
2089 }
2090 }
2091 }
2092
2093 // Describes what the negation of this matcher does.
2094 virtual void DescribeNegationTo(::std::ostream* os) const {
2095 if (count() == 0) {
2096 *os << "is not empty";
2097 return;
2098 }
2099
2100 *os << "does not have " << Elements(count()) << ", or\n";
2101 for (size_t i = 0; i != count(); ++i) {
2102 *os << "element " << i << " ";
2103 matchers_[i].DescribeNegationTo(os);
2104 if (i + 1 < count()) {
2105 *os << ", or\n";
2106 }
2107 }
2108 }
2109
2110 // Explains why 'container' matches, or doesn't match, this matcher.
2111 virtual void ExplainMatchResultTo(Container container,
2112 ::std::ostream* os) const {
2113 StlContainerReference stl_container = View::ConstReference(container);
2114 if (Matches(container)) {
2115 // We need to explain why *each* element matches (the obvious
2116 // ones can be skipped).
2117
2118 bool reason_printed = false;
2119 typename StlContainer::const_iterator it = stl_container.begin();
2120 for (size_t i = 0; i != count(); ++it, ++i) {
2121 ::std::stringstream ss;
2122 matchers_[i].ExplainMatchResultTo(*it, &ss);
2123
2124 const string s = ss.str();
2125 if (!s.empty()) {
2126 if (reason_printed) {
2127 *os << ",\n";
2128 }
2129 *os << "element " << i << " " << s;
2130 reason_printed = true;
2131 }
2132 }
2133 } else {
2134 // We need to explain why the container doesn't match.
2135 const size_t actual_count = stl_container.size();
2136 if (actual_count != count()) {
2137 // The element count doesn't match. If the container is
2138 // empty, there's no need to explain anything as Google Mock
2139 // already prints the empty container. Otherwise we just need
2140 // to show how many elements there actually are.
2141 if (actual_count != 0) {
2142 *os << "has " << Elements(actual_count);
2143 }
2144 return;
2145 }
2146
2147 // The container has the right size but at least one element
2148 // doesn't match expectation. We need to find this element and
2149 // explain why it doesn't match.
2150 typename StlContainer::const_iterator it = stl_container.begin();
2151 for (size_t i = 0; i != count(); ++it, ++i) {
2152 if (matchers_[i].Matches(*it)) {
2153 continue;
2154 }
2155
2156 *os << "element " << i << " doesn't match";
2157
2158 ::std::stringstream ss;
2159 matchers_[i].ExplainMatchResultTo(*it, &ss);
2160 const string s = ss.str();
2161 if (!s.empty()) {
2162 *os << " (" << s << ")";
2163 }
2164 return;
2165 }
2166 }
2167 }
2168
2169 private:
2170 static Message Elements(size_t count) {
2171 return Message() << count << (count == 1 ? " element" : " elements");
2172 }
2173
2174 size_t count() const { return matchers_.size(); }
2175 std::vector<Matcher<const Element&> > matchers_;
2176};
2177
2178// Implements ElementsAre() of 0 arguments.
2179class ElementsAreMatcher0 {
2180 public:
2181 ElementsAreMatcher0() {}
2182
2183 template <typename Container>
2184 operator Matcher<Container>() const {
2185 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2186 RawContainer;
2187 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2188 Element;
2189
2190 const Matcher<const Element&>* const matchers = NULL;
2191 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 0));
2192 }
2193};
2194
2195// Implements ElementsAreArray().
2196template <typename T>
2197class ElementsAreArrayMatcher {
2198 public:
2199 ElementsAreArrayMatcher(const T* first, size_t count) :
2200 first_(first), count_(count) {}
2201
2202 template <typename Container>
2203 operator Matcher<Container>() const {
2204 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2205 RawContainer;
2206 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2207 Element;
2208
2209 return MakeMatcher(new ElementsAreMatcherImpl<Container>(first_, count_));
2210 }
2211
2212 private:
2213 const T* const first_;
2214 const size_t count_;
2215};
2216
2217// Constants denoting interpolations in a matcher description string.
2218const int kTupleInterpolation = -1; // "%(*)s"
2219const int kPercentInterpolation = -2; // "%%"
2220const int kInvalidInterpolation = -3; // "%" followed by invalid text
2221
2222// Records the location and content of an interpolation.
2223struct Interpolation {
2224 Interpolation(const char* start, const char* end, int param)
2225 : start_pos(start), end_pos(end), param_index(param) {}
2226
2227 // Points to the start of the interpolation (the '%' character).
2228 const char* start_pos;
2229 // Points to the first character after the interpolation.
2230 const char* end_pos;
2231 // 0-based index of the interpolated matcher parameter;
2232 // kTupleInterpolation for "%(*)s"; kPercentInterpolation for "%%".
2233 int param_index;
2234};
2235
2236typedef ::std::vector<Interpolation> Interpolations;
2237
2238// Parses a matcher description string and returns a vector of
2239// interpolations that appear in the string; generates non-fatal
2240// failures iff 'description' is an invalid matcher description.
2241// 'param_names' is a NULL-terminated array of parameter names in the
2242// order they appear in the MATCHER_P*() parameter list.
2243Interpolations ValidateMatcherDescription(
2244 const char* param_names[], const char* description);
2245
2246// Returns the actual matcher description, given the matcher name,
2247// user-supplied description template string, interpolations in the
2248// string, and the printed values of the matcher parameters.
2249string FormatMatcherDescription(
2250 const char* matcher_name, const char* description,
2251 const Interpolations& interp, const Strings& param_values);
2252
shiqiane35fdd92008-12-10 05:08:54 +00002253} // namespace internal
2254
2255// Implements MatcherCast().
2256template <typename T, typename M>
2257inline Matcher<T> MatcherCast(M matcher) {
2258 return internal::MatcherCastImpl<T, M>::Cast(matcher);
2259}
2260
2261// _ is a matcher that matches anything of any type.
2262//
2263// This definition is fine as:
2264//
2265// 1. The C++ standard permits using the name _ in a namespace that
2266// is not the global namespace or ::std.
2267// 2. The AnythingMatcher class has no data member or constructor,
2268// so it's OK to create global variables of this type.
2269// 3. c-style has approved of using _ in this case.
2270const internal::AnythingMatcher _ = {};
2271// Creates a matcher that matches any value of the given type T.
2272template <typename T>
2273inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2274
2275// Creates a matcher that matches any value of the given type T.
2276template <typename T>
2277inline Matcher<T> An() { return A<T>(); }
2278
2279// Creates a polymorphic matcher that matches anything equal to x.
2280// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2281// wouldn't compile.
2282template <typename T>
2283inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2284
2285// Constructs a Matcher<T> from a 'value' of type T. The constructed
2286// matcher matches any value that's equal to 'value'.
2287template <typename T>
2288Matcher<T>::Matcher(T value) { *this = Eq(value); }
2289
2290// Creates a monomorphic matcher that matches anything with type Lhs
2291// and equal to rhs. A user may need to use this instead of Eq(...)
2292// in order to resolve an overloading ambiguity.
2293//
2294// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2295// or Matcher<T>(x), but more readable than the latter.
2296//
2297// We could define similar monomorphic matchers for other comparison
2298// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2299// it yet as those are used much less than Eq() in practice. A user
2300// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2301// for example.
2302template <typename Lhs, typename Rhs>
2303inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2304
2305// Creates a polymorphic matcher that matches anything >= x.
2306template <typename Rhs>
2307inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2308 return internal::GeMatcher<Rhs>(x);
2309}
2310
2311// Creates a polymorphic matcher that matches anything > x.
2312template <typename Rhs>
2313inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2314 return internal::GtMatcher<Rhs>(x);
2315}
2316
2317// Creates a polymorphic matcher that matches anything <= x.
2318template <typename Rhs>
2319inline internal::LeMatcher<Rhs> Le(Rhs x) {
2320 return internal::LeMatcher<Rhs>(x);
2321}
2322
2323// Creates a polymorphic matcher that matches anything < x.
2324template <typename Rhs>
2325inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2326 return internal::LtMatcher<Rhs>(x);
2327}
2328
2329// Creates a polymorphic matcher that matches anything != x.
2330template <typename Rhs>
2331inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2332 return internal::NeMatcher<Rhs>(x);
2333}
2334
zhanyong.wan2d970ee2009-09-24 21:41:36 +00002335// Creates a polymorphic matcher that matches any NULL pointer.
2336inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
2337 return MakePolymorphicMatcher(internal::IsNullMatcher());
2338}
2339
shiqiane35fdd92008-12-10 05:08:54 +00002340// Creates a polymorphic matcher that matches any non-NULL pointer.
2341// This is convenient as Not(NULL) doesn't compile (the compiler
2342// thinks that that expression is comparing a pointer with an integer).
2343inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2344 return MakePolymorphicMatcher(internal::NotNullMatcher());
2345}
2346
2347// Creates a polymorphic matcher that matches any argument that
2348// references variable x.
2349template <typename T>
2350inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2351 return internal::RefMatcher<T&>(x);
2352}
2353
2354// Creates a matcher that matches any double argument approximately
2355// equal to rhs, where two NANs are considered unequal.
2356inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2357 return internal::FloatingEqMatcher<double>(rhs, false);
2358}
2359
2360// Creates a matcher that matches any double argument approximately
2361// equal to rhs, including NaN values when rhs is NaN.
2362inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2363 return internal::FloatingEqMatcher<double>(rhs, true);
2364}
2365
2366// Creates a matcher that matches any float argument approximately
2367// equal to rhs, where two NANs are considered unequal.
2368inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2369 return internal::FloatingEqMatcher<float>(rhs, false);
2370}
2371
2372// Creates a matcher that matches any double argument approximately
2373// equal to rhs, including NaN values when rhs is NaN.
2374inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2375 return internal::FloatingEqMatcher<float>(rhs, true);
2376}
2377
2378// Creates a matcher that matches a pointer (raw or smart) that points
2379// to a value that matches inner_matcher.
2380template <typename InnerMatcher>
2381inline internal::PointeeMatcher<InnerMatcher> Pointee(
2382 const InnerMatcher& inner_matcher) {
2383 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2384}
2385
2386// Creates a matcher that matches an object whose given field matches
2387// 'matcher'. For example,
2388// Field(&Foo::number, Ge(5))
2389// matches a Foo object x iff x.number >= 5.
2390template <typename Class, typename FieldType, typename FieldMatcher>
2391inline PolymorphicMatcher<
2392 internal::FieldMatcher<Class, FieldType> > Field(
2393 FieldType Class::*field, const FieldMatcher& matcher) {
2394 return MakePolymorphicMatcher(
2395 internal::FieldMatcher<Class, FieldType>(
2396 field, MatcherCast<const FieldType&>(matcher)));
2397 // The call to MatcherCast() is required for supporting inner
2398 // matchers of compatible types. For example, it allows
2399 // Field(&Foo::bar, m)
2400 // to compile where bar is an int32 and m is a matcher for int64.
2401}
2402
2403// Creates a matcher that matches an object whose given property
2404// matches 'matcher'. For example,
2405// Property(&Foo::str, StartsWith("hi"))
2406// matches a Foo object x iff x.str() starts with "hi".
2407template <typename Class, typename PropertyType, typename PropertyMatcher>
2408inline PolymorphicMatcher<
2409 internal::PropertyMatcher<Class, PropertyType> > Property(
2410 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2411 return MakePolymorphicMatcher(
2412 internal::PropertyMatcher<Class, PropertyType>(
2413 property,
zhanyong.wane0d051e2009-02-19 00:33:37 +00002414 MatcherCast<GMOCK_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002415 // The call to MatcherCast() is required for supporting inner
2416 // matchers of compatible types. For example, it allows
2417 // Property(&Foo::bar, m)
2418 // to compile where bar() returns an int32 and m is a matcher for int64.
2419}
2420
2421// Creates a matcher that matches an object iff the result of applying
2422// a callable to x matches 'matcher'.
2423// For example,
2424// ResultOf(f, StartsWith("hi"))
2425// matches a Foo object x iff f(x) starts with "hi".
2426// callable parameter can be a function, function pointer, or a functor.
2427// Callable has to satisfy the following conditions:
2428// * It is required to keep no state affecting the results of
2429// the calls on it and make no assumptions about how many calls
2430// will be made. Any state it keeps must be protected from the
2431// concurrent access.
2432// * If it is a function object, it has to define type result_type.
2433// We recommend deriving your functor classes from std::unary_function.
2434template <typename Callable, typename ResultOfMatcher>
2435internal::ResultOfMatcher<Callable> ResultOf(
2436 Callable callable, const ResultOfMatcher& matcher) {
2437 return internal::ResultOfMatcher<Callable>(
2438 callable,
2439 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2440 matcher));
2441 // The call to MatcherCast() is required for supporting inner
2442 // matchers of compatible types. For example, it allows
2443 // ResultOf(Function, m)
2444 // to compile where Function() returns an int32 and m is a matcher for int64.
2445}
2446
2447// String matchers.
2448
2449// Matches a string equal to str.
2450inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2451 StrEq(const internal::string& str) {
2452 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2453 str, true, true));
2454}
2455
2456// Matches a string not equal to str.
2457inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2458 StrNe(const internal::string& str) {
2459 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2460 str, false, true));
2461}
2462
2463// Matches a string equal to str, ignoring case.
2464inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2465 StrCaseEq(const internal::string& str) {
2466 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2467 str, true, false));
2468}
2469
2470// Matches a string not equal to str, ignoring case.
2471inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2472 StrCaseNe(const internal::string& str) {
2473 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2474 str, false, false));
2475}
2476
2477// Creates a matcher that matches any string, std::string, or C string
2478// that contains the given substring.
2479inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2480 HasSubstr(const internal::string& substring) {
2481 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
2482 substring));
2483}
2484
2485// Matches a string that starts with 'prefix' (case-sensitive).
2486inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
2487 StartsWith(const internal::string& prefix) {
2488 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
2489 prefix));
2490}
2491
2492// Matches a string that ends with 'suffix' (case-sensitive).
2493inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
2494 EndsWith(const internal::string& suffix) {
2495 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
2496 suffix));
2497}
2498
2499#ifdef GMOCK_HAS_REGEX
2500
2501// Matches a string that fully matches regular expression 'regex'.
2502// The matcher takes ownership of 'regex'.
2503inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2504 const internal::RE* regex) {
2505 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2506}
2507inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2508 const internal::string& regex) {
2509 return MatchesRegex(new internal::RE(regex));
2510}
2511
2512// Matches a string that contains regular expression 'regex'.
2513// The matcher takes ownership of 'regex'.
2514inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2515 const internal::RE* regex) {
2516 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2517}
2518inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2519 const internal::string& regex) {
2520 return ContainsRegex(new internal::RE(regex));
2521}
2522
2523#endif // GMOCK_HAS_REGEX
2524
2525#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2526// Wide string matchers.
2527
2528// Matches a string equal to str.
2529inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2530 StrEq(const internal::wstring& str) {
2531 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2532 str, true, true));
2533}
2534
2535// Matches a string not equal to str.
2536inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2537 StrNe(const internal::wstring& str) {
2538 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2539 str, false, true));
2540}
2541
2542// Matches a string equal to str, ignoring case.
2543inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2544 StrCaseEq(const internal::wstring& str) {
2545 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2546 str, true, false));
2547}
2548
2549// Matches a string not equal to str, ignoring case.
2550inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2551 StrCaseNe(const internal::wstring& str) {
2552 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2553 str, false, false));
2554}
2555
2556// Creates a matcher that matches any wstring, std::wstring, or C wide string
2557// that contains the given substring.
2558inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2559 HasSubstr(const internal::wstring& substring) {
2560 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2561 substring));
2562}
2563
2564// Matches a string that starts with 'prefix' (case-sensitive).
2565inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2566 StartsWith(const internal::wstring& prefix) {
2567 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2568 prefix));
2569}
2570
2571// Matches a string that ends with 'suffix' (case-sensitive).
2572inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2573 EndsWith(const internal::wstring& suffix) {
2574 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2575 suffix));
2576}
2577
2578#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2579
2580// Creates a polymorphic matcher that matches a 2-tuple where the
2581// first field == the second field.
2582inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2583
2584// Creates a polymorphic matcher that matches a 2-tuple where the
2585// first field >= the second field.
2586inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2587
2588// Creates a polymorphic matcher that matches a 2-tuple where the
2589// first field > the second field.
2590inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2591
2592// Creates a polymorphic matcher that matches a 2-tuple where the
2593// first field <= the second field.
2594inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2595
2596// Creates a polymorphic matcher that matches a 2-tuple where the
2597// first field < the second field.
2598inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2599
2600// Creates a polymorphic matcher that matches a 2-tuple where the
2601// first field != the second field.
2602inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2603
2604// Creates a matcher that matches any value of type T that m doesn't
2605// match.
2606template <typename InnerMatcher>
2607inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2608 return internal::NotMatcher<InnerMatcher>(m);
2609}
2610
2611// Creates a matcher that matches any value that matches all of the
2612// given matchers.
2613//
2614// For now we only support up to 5 matchers. Support for more
2615// matchers can be added as needed, or the user can use nested
2616// AllOf()s.
2617template <typename Matcher1, typename Matcher2>
2618inline internal::BothOfMatcher<Matcher1, Matcher2>
2619AllOf(Matcher1 m1, Matcher2 m2) {
2620 return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2);
2621}
2622
2623template <typename Matcher1, typename Matcher2, typename Matcher3>
2624inline internal::BothOfMatcher<Matcher1,
2625 internal::BothOfMatcher<Matcher2, Matcher3> >
2626AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2627 return AllOf(m1, AllOf(m2, m3));
2628}
2629
2630template <typename Matcher1, typename Matcher2, typename Matcher3,
2631 typename Matcher4>
2632inline internal::BothOfMatcher<Matcher1,
2633 internal::BothOfMatcher<Matcher2,
2634 internal::BothOfMatcher<Matcher3, Matcher4> > >
2635AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2636 return AllOf(m1, AllOf(m2, m3, m4));
2637}
2638
2639template <typename Matcher1, typename Matcher2, typename Matcher3,
2640 typename Matcher4, typename Matcher5>
2641inline internal::BothOfMatcher<Matcher1,
2642 internal::BothOfMatcher<Matcher2,
2643 internal::BothOfMatcher<Matcher3,
2644 internal::BothOfMatcher<Matcher4, Matcher5> > > >
2645AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2646 return AllOf(m1, AllOf(m2, m3, m4, m5));
2647}
2648
2649// Creates a matcher that matches any value that matches at least one
2650// of the given matchers.
2651//
2652// For now we only support up to 5 matchers. Support for more
2653// matchers can be added as needed, or the user can use nested
2654// AnyOf()s.
2655template <typename Matcher1, typename Matcher2>
2656inline internal::EitherOfMatcher<Matcher1, Matcher2>
2657AnyOf(Matcher1 m1, Matcher2 m2) {
2658 return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2);
2659}
2660
2661template <typename Matcher1, typename Matcher2, typename Matcher3>
2662inline internal::EitherOfMatcher<Matcher1,
2663 internal::EitherOfMatcher<Matcher2, Matcher3> >
2664AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2665 return AnyOf(m1, AnyOf(m2, m3));
2666}
2667
2668template <typename Matcher1, typename Matcher2, typename Matcher3,
2669 typename Matcher4>
2670inline internal::EitherOfMatcher<Matcher1,
2671 internal::EitherOfMatcher<Matcher2,
2672 internal::EitherOfMatcher<Matcher3, Matcher4> > >
2673AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2674 return AnyOf(m1, AnyOf(m2, m3, m4));
2675}
2676
2677template <typename Matcher1, typename Matcher2, typename Matcher3,
2678 typename Matcher4, typename Matcher5>
2679inline internal::EitherOfMatcher<Matcher1,
2680 internal::EitherOfMatcher<Matcher2,
2681 internal::EitherOfMatcher<Matcher3,
2682 internal::EitherOfMatcher<Matcher4, Matcher5> > > >
2683AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2684 return AnyOf(m1, AnyOf(m2, m3, m4, m5));
2685}
2686
2687// Returns a matcher that matches anything that satisfies the given
2688// predicate. The predicate can be any unary function or functor
2689// whose return type can be implicitly converted to bool.
2690template <typename Predicate>
2691inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
2692Truly(Predicate pred) {
2693 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
2694}
2695
zhanyong.wan6a896b52009-01-16 01:13:50 +00002696// Returns a matcher that matches an equal container.
2697// This matcher behaves like Eq(), but in the event of mismatch lists the
2698// values that are included in one container but not the other. (Duplicate
2699// values and order differences are not explained.)
2700template <typename Container>
zhanyong.wanb8243162009-06-04 05:48:20 +00002701inline PolymorphicMatcher<internal::ContainerEqMatcher<
2702 GMOCK_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00002703 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002704 // This following line is for working around a bug in MSVC 8.0,
2705 // which causes Container to be a const type sometimes.
2706 typedef GMOCK_REMOVE_CONST_(Container) RawContainer;
2707 return MakePolymorphicMatcher(internal::ContainerEqMatcher<RawContainer>(rhs));
2708}
2709
2710// Matches an STL-style container or a native array that contains at
2711// least one element matching the given value or matcher.
2712//
2713// Examples:
2714// ::std::set<int> page_ids;
2715// page_ids.insert(3);
2716// page_ids.insert(1);
2717// EXPECT_THAT(page_ids, Contains(1));
2718// EXPECT_THAT(page_ids, Contains(Gt(2)));
2719// EXPECT_THAT(page_ids, Not(Contains(4)));
2720//
2721// ::std::map<int, size_t> page_lengths;
2722// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00002723// EXPECT_THAT(page_lengths,
2724// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00002725//
2726// const char* user_ids[] = { "joe", "mike", "tom" };
2727// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
2728template <typename M>
2729inline internal::ContainsMatcher<M> Contains(M matcher) {
2730 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002731}
2732
zhanyong.wanb5937da2009-07-16 20:26:41 +00002733// Key(inner_matcher) matches an std::pair whose 'first' field matches
2734// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2735// std::map that contains at least one element whose key is >= 5.
2736template <typename M>
2737inline internal::KeyMatcher<M> Key(M inner_matcher) {
2738 return internal::KeyMatcher<M>(inner_matcher);
2739}
2740
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002741// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
2742// matches first_matcher and whose 'second' field matches second_matcher. For
2743// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
2744// to match a std::map<int, string> that contains exactly one element whose key
2745// is >= 5 and whose value equals "foo".
2746template <typename FirstMatcher, typename SecondMatcher>
2747inline internal::PairMatcher<FirstMatcher, SecondMatcher>
2748Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
2749 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
2750 first_matcher, second_matcher);
2751}
2752
shiqiane35fdd92008-12-10 05:08:54 +00002753// Returns a predicate that is satisfied by anything that matches the
2754// given matcher.
2755template <typename M>
2756inline internal::MatcherAsPredicate<M> Matches(M matcher) {
2757 return internal::MatcherAsPredicate<M>(matcher);
2758}
2759
zhanyong.wanb8243162009-06-04 05:48:20 +00002760// Returns true iff the value matches the matcher.
2761template <typename T, typename M>
2762inline bool Value(const T& value, M matcher) {
2763 return testing::Matches(matcher)(value);
2764}
2765
zhanyong.wanbf550852009-06-09 06:09:53 +00002766// AllArgs(m) is a synonym of m. This is useful in
2767//
2768// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
2769//
2770// which is easier to read than
2771//
2772// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
2773template <typename InnerMatcher>
2774inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
2775
shiqiane35fdd92008-12-10 05:08:54 +00002776// These macros allow using matchers to check values in Google Test
2777// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
2778// succeed iff the value matches the matcher. If the assertion fails,
2779// the value and the description of the matcher will be printed.
2780#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
2781 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2782#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
2783 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2784
2785} // namespace testing
2786
2787#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_