blob: 688ce64fb8cf4e1af6af3c23c9a1f24f817864e1 [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
624// Implements the polymorphic NotNull() matcher, which matches any
625// pointer that is not NULL.
626class NotNullMatcher {
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 not NULL"; }
632 void DescribeNegationTo(::std::ostream* os) const {
633 *os << "is NULL";
634 }
635};
636
637// Ref(variable) matches any argument that is a reference to
638// 'variable'. This matcher is polymorphic as it can match any
639// super type of the type of 'variable'.
640//
641// The RefMatcher template class implements Ref(variable). It can
642// only be instantiated with a reference type. This prevents a user
643// from mistakenly using Ref(x) to match a non-reference function
644// argument. For example, the following will righteously cause a
645// compiler error:
646//
647// int n;
648// Matcher<int> m1 = Ref(n); // This won't compile.
649// Matcher<int&> m2 = Ref(n); // This will compile.
650template <typename T>
651class RefMatcher;
652
653template <typename T>
654class RefMatcher<T&> {
655 // Google Mock is a generic framework and thus needs to support
656 // mocking any function types, including those that take non-const
657 // reference arguments. Therefore the template parameter T (and
658 // Super below) can be instantiated to either a const type or a
659 // non-const type.
660 public:
661 // RefMatcher() takes a T& instead of const T&, as we want the
662 // compiler to catch using Ref(const_value) as a matcher for a
663 // non-const reference.
664 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
665
666 template <typename Super>
667 operator Matcher<Super&>() const {
668 // By passing object_ (type T&) to Impl(), which expects a Super&,
669 // we make sure that Super is a super type of T. In particular,
670 // this catches using Ref(const_value) as a matcher for a
671 // non-const reference, as you cannot implicitly convert a const
672 // reference to a non-const reference.
673 return MakeMatcher(new Impl<Super>(object_));
674 }
675 private:
676 template <typename Super>
677 class Impl : public MatcherInterface<Super&> {
678 public:
679 explicit Impl(Super& x) : object_(x) {} // NOLINT
680
681 // Matches() takes a Super& (as opposed to const Super&) in
682 // order to match the interface MatcherInterface<Super&>.
683 virtual bool Matches(Super& x) const { return &x == &object_; } // NOLINT
684
685 virtual void DescribeTo(::std::ostream* os) const {
686 *os << "references the variable ";
687 UniversalPrinter<Super&>::Print(object_, os);
688 }
689
690 virtual void DescribeNegationTo(::std::ostream* os) const {
691 *os << "does not reference the variable ";
692 UniversalPrinter<Super&>::Print(object_, os);
693 }
694
695 virtual void ExplainMatchResultTo(Super& x, // NOLINT
696 ::std::ostream* os) const {
697 *os << "is located @" << static_cast<const void*>(&x);
698 }
699 private:
700 const Super& object_;
701 };
702
703 T& object_;
704};
705
706// Polymorphic helper functions for narrow and wide string matchers.
707inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
708 return String::CaseInsensitiveCStringEquals(lhs, rhs);
709}
710
711inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
712 const wchar_t* rhs) {
713 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
714}
715
716// String comparison for narrow or wide strings that can have embedded NUL
717// characters.
718template <typename StringType>
719bool CaseInsensitiveStringEquals(const StringType& s1,
720 const StringType& s2) {
721 // Are the heads equal?
722 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
723 return false;
724 }
725
726 // Skip the equal heads.
727 const typename StringType::value_type nul = 0;
728 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
729
730 // Are we at the end of either s1 or s2?
731 if (i1 == StringType::npos || i2 == StringType::npos) {
732 return i1 == i2;
733 }
734
735 // Are the tails equal?
736 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
737}
738
739// String matchers.
740
741// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
742template <typename StringType>
743class StrEqualityMatcher {
744 public:
745 typedef typename StringType::const_pointer ConstCharPointer;
746
747 StrEqualityMatcher(const StringType& str, bool expect_eq,
748 bool case_sensitive)
749 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
750
751 // When expect_eq_ is true, returns true iff s is equal to string_;
752 // otherwise returns true iff s is not equal to string_.
753 bool Matches(ConstCharPointer s) const {
754 if (s == NULL) {
755 return !expect_eq_;
756 }
757 return Matches(StringType(s));
758 }
759
760 bool Matches(const StringType& s) const {
761 const bool eq = case_sensitive_ ? s == string_ :
762 CaseInsensitiveStringEquals(s, string_);
763 return expect_eq_ == eq;
764 }
765
766 void DescribeTo(::std::ostream* os) const {
767 DescribeToHelper(expect_eq_, os);
768 }
769
770 void DescribeNegationTo(::std::ostream* os) const {
771 DescribeToHelper(!expect_eq_, os);
772 }
773 private:
774 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
775 *os << "is ";
776 if (!expect_eq) {
777 *os << "not ";
778 }
779 *os << "equal to ";
780 if (!case_sensitive_) {
781 *os << "(ignoring case) ";
782 }
783 UniversalPrinter<StringType>::Print(string_, os);
784 }
785
786 const StringType string_;
787 const bool expect_eq_;
788 const bool case_sensitive_;
789};
790
791// Implements the polymorphic HasSubstr(substring) matcher, which
792// can be used as a Matcher<T> as long as T can be converted to a
793// string.
794template <typename StringType>
795class HasSubstrMatcher {
796 public:
797 typedef typename StringType::const_pointer ConstCharPointer;
798
799 explicit HasSubstrMatcher(const StringType& substring)
800 : substring_(substring) {}
801
802 // These overloaded methods allow HasSubstr(substring) to be used as a
803 // Matcher<T> as long as T can be converted to string. Returns true
804 // iff s contains substring_ as a substring.
805 bool Matches(ConstCharPointer s) const {
806 return s != NULL && Matches(StringType(s));
807 }
808
809 bool Matches(const StringType& s) const {
810 return s.find(substring_) != StringType::npos;
811 }
812
813 // Describes what this matcher matches.
814 void DescribeTo(::std::ostream* os) const {
815 *os << "has substring ";
816 UniversalPrinter<StringType>::Print(substring_, os);
817 }
818
819 void DescribeNegationTo(::std::ostream* os) const {
820 *os << "has no substring ";
821 UniversalPrinter<StringType>::Print(substring_, os);
822 }
823 private:
824 const StringType substring_;
825};
826
827// Implements the polymorphic StartsWith(substring) matcher, which
828// can be used as a Matcher<T> as long as T can be converted to a
829// string.
830template <typename StringType>
831class StartsWithMatcher {
832 public:
833 typedef typename StringType::const_pointer ConstCharPointer;
834
835 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
836 }
837
838 // These overloaded methods allow StartsWith(prefix) to be used as a
839 // Matcher<T> as long as T can be converted to string. Returns true
840 // iff s starts with prefix_.
841 bool Matches(ConstCharPointer s) const {
842 return s != NULL && Matches(StringType(s));
843 }
844
845 bool Matches(const StringType& s) const {
846 return s.length() >= prefix_.length() &&
847 s.substr(0, prefix_.length()) == prefix_;
848 }
849
850 void DescribeTo(::std::ostream* os) const {
851 *os << "starts with ";
852 UniversalPrinter<StringType>::Print(prefix_, os);
853 }
854
855 void DescribeNegationTo(::std::ostream* os) const {
856 *os << "doesn't start with ";
857 UniversalPrinter<StringType>::Print(prefix_, os);
858 }
859 private:
860 const StringType prefix_;
861};
862
863// Implements the polymorphic EndsWith(substring) matcher, which
864// can be used as a Matcher<T> as long as T can be converted to a
865// string.
866template <typename StringType>
867class EndsWithMatcher {
868 public:
869 typedef typename StringType::const_pointer ConstCharPointer;
870
871 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
872
873 // These overloaded methods allow EndsWith(suffix) to be used as a
874 // Matcher<T> as long as T can be converted to string. Returns true
875 // iff s ends with suffix_.
876 bool Matches(ConstCharPointer s) const {
877 return s != NULL && Matches(StringType(s));
878 }
879
880 bool Matches(const StringType& s) const {
881 return s.length() >= suffix_.length() &&
882 s.substr(s.length() - suffix_.length()) == suffix_;
883 }
884
885 void DescribeTo(::std::ostream* os) const {
886 *os << "ends with ";
887 UniversalPrinter<StringType>::Print(suffix_, os);
888 }
889
890 void DescribeNegationTo(::std::ostream* os) const {
891 *os << "doesn't end with ";
892 UniversalPrinter<StringType>::Print(suffix_, os);
893 }
894 private:
895 const StringType suffix_;
896};
897
898#if GMOCK_HAS_REGEX
899
900// Implements polymorphic matchers MatchesRegex(regex) and
901// ContainsRegex(regex), which can be used as a Matcher<T> as long as
902// T can be converted to a string.
903class MatchesRegexMatcher {
904 public:
905 MatchesRegexMatcher(const RE* regex, bool full_match)
906 : regex_(regex), full_match_(full_match) {}
907
908 // These overloaded methods allow MatchesRegex(regex) to be used as
909 // a Matcher<T> as long as T can be converted to string. Returns
910 // true iff s matches regular expression regex. When full_match_ is
911 // true, a full match is done; otherwise a partial match is done.
912 bool Matches(const char* s) const {
913 return s != NULL && Matches(internal::string(s));
914 }
915
916 bool Matches(const internal::string& s) const {
917 return full_match_ ? RE::FullMatch(s, *regex_) :
918 RE::PartialMatch(s, *regex_);
919 }
920
921 void DescribeTo(::std::ostream* os) const {
922 *os << (full_match_ ? "matches" : "contains")
923 << " regular expression ";
924 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
925 }
926
927 void DescribeNegationTo(::std::ostream* os) const {
928 *os << "doesn't " << (full_match_ ? "match" : "contain")
929 << " regular expression ";
930 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
931 }
932 private:
933 const internal::linked_ptr<const RE> regex_;
934 const bool full_match_;
935};
936
937#endif // GMOCK_HAS_REGEX
938
939// Implements a matcher that compares the two fields of a 2-tuple
940// using one of the ==, <=, <, etc, operators. The two fields being
941// compared don't have to have the same type.
942//
943// The matcher defined here is polymorphic (for example, Eq() can be
944// used to match a tuple<int, short>, a tuple<const long&, double>,
945// etc). Therefore we use a template type conversion operator in the
946// implementation.
947//
948// We define this as a macro in order to eliminate duplicated source
949// code.
zhanyong.wan2661c682009-06-09 05:42:12 +0000950#define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op) \
shiqiane35fdd92008-12-10 05:08:54 +0000951 class name##2Matcher { \
952 public: \
953 template <typename T1, typename T2> \
954 operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
955 return MakeMatcher(new Impl<T1, T2>); \
956 } \
957 private: \
958 template <typename T1, typename T2> \
959 class Impl : public MatcherInterface<const ::std::tr1::tuple<T1, T2>&> { \
960 public: \
961 virtual bool Matches(const ::std::tr1::tuple<T1, T2>& args) const { \
962 return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
963 } \
964 virtual void DescribeTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +0000965 *os << "are a pair (x, y) where x " #op " y"; \
shiqiane35fdd92008-12-10 05:08:54 +0000966 } \
967 virtual void DescribeNegationTo(::std::ostream* os) const { \
zhanyong.wan2661c682009-06-09 05:42:12 +0000968 *os << "are a pair (x, y) where x " #op " y is false"; \
shiqiane35fdd92008-12-10 05:08:54 +0000969 } \
970 }; \
971 }
972
973// Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
zhanyong.wan2661c682009-06-09 05:42:12 +0000974GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==);
975GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ge, >=);
976GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Gt, >);
977GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Le, <=);
978GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Lt, <);
979GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=);
shiqiane35fdd92008-12-10 05:08:54 +0000980
zhanyong.wane0d051e2009-02-19 00:33:37 +0000981#undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
shiqiane35fdd92008-12-10 05:08:54 +0000982
zhanyong.wanc6a41232009-05-13 23:38:40 +0000983// Implements the Not(...) matcher for a particular argument type T.
984// We do not nest it inside the NotMatcher class template, as that
985// will prevent different instantiations of NotMatcher from sharing
986// the same NotMatcherImpl<T> class.
987template <typename T>
988class NotMatcherImpl : public MatcherInterface<T> {
989 public:
990 explicit NotMatcherImpl(const Matcher<T>& matcher)
991 : matcher_(matcher) {}
992
993 virtual bool Matches(T x) const {
994 return !matcher_.Matches(x);
995 }
996
997 virtual void DescribeTo(::std::ostream* os) const {
998 matcher_.DescribeNegationTo(os);
999 }
1000
1001 virtual void DescribeNegationTo(::std::ostream* os) const {
1002 matcher_.DescribeTo(os);
1003 }
1004
1005 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1006 matcher_.ExplainMatchResultTo(x, os);
1007 }
1008 private:
1009 const Matcher<T> matcher_;
1010};
1011
shiqiane35fdd92008-12-10 05:08:54 +00001012// Implements the Not(m) matcher, which matches a value that doesn't
1013// match matcher m.
1014template <typename InnerMatcher>
1015class NotMatcher {
1016 public:
1017 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1018
1019 // This template type conversion operator allows Not(m) to be used
1020 // to match any type m can match.
1021 template <typename T>
1022 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001023 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
shiqiane35fdd92008-12-10 05:08:54 +00001024 }
1025 private:
shiqiane35fdd92008-12-10 05:08:54 +00001026 InnerMatcher matcher_;
1027};
1028
zhanyong.wanc6a41232009-05-13 23:38:40 +00001029// Implements the AllOf(m1, m2) matcher for a particular argument type
1030// T. We do not nest it inside the BothOfMatcher class template, as
1031// that will prevent different instantiations of BothOfMatcher from
1032// sharing the same BothOfMatcherImpl<T> class.
1033template <typename T>
1034class BothOfMatcherImpl : public MatcherInterface<T> {
1035 public:
1036 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1037 : matcher1_(matcher1), matcher2_(matcher2) {}
1038
1039 virtual bool Matches(T x) const {
1040 return matcher1_.Matches(x) && matcher2_.Matches(x);
1041 }
1042
1043 virtual void DescribeTo(::std::ostream* os) const {
1044 *os << "(";
1045 matcher1_.DescribeTo(os);
1046 *os << ") and (";
1047 matcher2_.DescribeTo(os);
1048 *os << ")";
1049 }
1050
1051 virtual void DescribeNegationTo(::std::ostream* os) const {
1052 *os << "not ";
1053 DescribeTo(os);
1054 }
1055
1056 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1057 if (Matches(x)) {
1058 // When both matcher1_ and matcher2_ match x, we need to
1059 // explain why *both* of them match.
1060 ::std::stringstream ss1;
1061 matcher1_.ExplainMatchResultTo(x, &ss1);
1062 const internal::string s1 = ss1.str();
1063
1064 ::std::stringstream ss2;
1065 matcher2_.ExplainMatchResultTo(x, &ss2);
1066 const internal::string s2 = ss2.str();
1067
1068 if (s1 == "") {
1069 *os << s2;
1070 } else {
1071 *os << s1;
1072 if (s2 != "") {
1073 *os << "; " << s2;
1074 }
1075 }
1076 } else {
1077 // Otherwise we only need to explain why *one* of them fails
1078 // to match.
1079 if (!matcher1_.Matches(x)) {
1080 matcher1_.ExplainMatchResultTo(x, os);
1081 } else {
1082 matcher2_.ExplainMatchResultTo(x, os);
1083 }
1084 }
1085 }
1086 private:
1087 const Matcher<T> matcher1_;
1088 const Matcher<T> matcher2_;
1089};
1090
shiqiane35fdd92008-12-10 05:08:54 +00001091// Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1092// matches a value that matches all of the matchers m_1, ..., and m_n.
1093template <typename Matcher1, typename Matcher2>
1094class BothOfMatcher {
1095 public:
1096 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1097 : matcher1_(matcher1), matcher2_(matcher2) {}
1098
1099 // This template type conversion operator allows a
1100 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1101 // both Matcher1 and Matcher2 can match.
1102 template <typename T>
1103 operator Matcher<T>() const {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001104 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1105 SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001106 }
1107 private:
zhanyong.wanc6a41232009-05-13 23:38:40 +00001108 Matcher1 matcher1_;
1109 Matcher2 matcher2_;
1110};
shiqiane35fdd92008-12-10 05:08:54 +00001111
zhanyong.wanc6a41232009-05-13 23:38:40 +00001112// Implements the AnyOf(m1, m2) matcher for a particular argument type
1113// T. We do not nest it inside the AnyOfMatcher class template, as
1114// that will prevent different instantiations of AnyOfMatcher from
1115// sharing the same EitherOfMatcherImpl<T> class.
1116template <typename T>
1117class EitherOfMatcherImpl : public MatcherInterface<T> {
1118 public:
1119 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1120 : matcher1_(matcher1), matcher2_(matcher2) {}
shiqiane35fdd92008-12-10 05:08:54 +00001121
zhanyong.wanc6a41232009-05-13 23:38:40 +00001122 virtual bool Matches(T x) const {
1123 return matcher1_.Matches(x) || matcher2_.Matches(x);
1124 }
shiqiane35fdd92008-12-10 05:08:54 +00001125
zhanyong.wanc6a41232009-05-13 23:38:40 +00001126 virtual void DescribeTo(::std::ostream* os) const {
1127 *os << "(";
1128 matcher1_.DescribeTo(os);
1129 *os << ") or (";
1130 matcher2_.DescribeTo(os);
1131 *os << ")";
1132 }
shiqiane35fdd92008-12-10 05:08:54 +00001133
zhanyong.wanc6a41232009-05-13 23:38:40 +00001134 virtual void DescribeNegationTo(::std::ostream* os) const {
1135 *os << "not ";
1136 DescribeTo(os);
1137 }
shiqiane35fdd92008-12-10 05:08:54 +00001138
zhanyong.wanc6a41232009-05-13 23:38:40 +00001139 virtual void ExplainMatchResultTo(T x, ::std::ostream* os) const {
1140 if (Matches(x)) {
1141 // If either matcher1_ or matcher2_ matches x, we just need
1142 // to explain why *one* of them matches.
1143 if (matcher1_.Matches(x)) {
1144 matcher1_.ExplainMatchResultTo(x, os);
shiqiane35fdd92008-12-10 05:08:54 +00001145 } else {
zhanyong.wanc6a41232009-05-13 23:38:40 +00001146 matcher2_.ExplainMatchResultTo(x, os);
1147 }
1148 } else {
1149 // Otherwise we need to explain why *neither* matches.
1150 ::std::stringstream ss1;
1151 matcher1_.ExplainMatchResultTo(x, &ss1);
1152 const internal::string s1 = ss1.str();
1153
1154 ::std::stringstream ss2;
1155 matcher2_.ExplainMatchResultTo(x, &ss2);
1156 const internal::string s2 = ss2.str();
1157
1158 if (s1 == "") {
1159 *os << s2;
1160 } else {
1161 *os << s1;
1162 if (s2 != "") {
1163 *os << "; " << s2;
shiqiane35fdd92008-12-10 05:08:54 +00001164 }
1165 }
1166 }
zhanyong.wanc6a41232009-05-13 23:38:40 +00001167 }
1168 private:
1169 const Matcher<T> matcher1_;
1170 const Matcher<T> matcher2_;
shiqiane35fdd92008-12-10 05:08:54 +00001171};
1172
1173// Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1174// matches a value that matches at least one of the matchers m_1, ...,
1175// and m_n.
1176template <typename Matcher1, typename Matcher2>
1177class EitherOfMatcher {
1178 public:
1179 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1180 : matcher1_(matcher1), matcher2_(matcher2) {}
1181
1182 // This template type conversion operator allows a
1183 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1184 // both Matcher1 and Matcher2 can match.
1185 template <typename T>
1186 operator Matcher<T>() const {
zhanyong.wan16cf4732009-05-14 20:55:30 +00001187 return Matcher<T>(new EitherOfMatcherImpl<T>(
1188 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
shiqiane35fdd92008-12-10 05:08:54 +00001189 }
1190 private:
shiqiane35fdd92008-12-10 05:08:54 +00001191 Matcher1 matcher1_;
1192 Matcher2 matcher2_;
1193};
1194
1195// Used for implementing Truly(pred), which turns a predicate into a
1196// matcher.
1197template <typename Predicate>
1198class TrulyMatcher {
1199 public:
1200 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1201
1202 // This method template allows Truly(pred) to be used as a matcher
1203 // for type T where T is the argument type of predicate 'pred'. The
1204 // argument is passed by reference as the predicate may be
1205 // interested in the address of the argument.
1206 template <typename T>
zhanyong.wan16cf4732009-05-14 20:55:30 +00001207 bool Matches(T& x) const { // NOLINT
zhanyong.wan652540a2009-02-23 23:37:29 +00001208#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001209 // MSVC warns about converting a value into bool (warning 4800).
1210#pragma warning(push) // Saves the current warning state.
1211#pragma warning(disable:4800) // Temporarily disables warning 4800.
1212#endif // GTEST_OS_WINDOWS
1213 return predicate_(x);
zhanyong.wan652540a2009-02-23 23:37:29 +00001214#if GTEST_OS_WINDOWS
shiqiane35fdd92008-12-10 05:08:54 +00001215#pragma warning(pop) // Restores the warning state.
1216#endif // GTEST_OS_WINDOWS
1217 }
1218
1219 void DescribeTo(::std::ostream* os) const {
1220 *os << "satisfies the given predicate";
1221 }
1222
1223 void DescribeNegationTo(::std::ostream* os) const {
1224 *os << "doesn't satisfy the given predicate";
1225 }
1226 private:
1227 Predicate predicate_;
1228};
1229
1230// Used for implementing Matches(matcher), which turns a matcher into
1231// a predicate.
1232template <typename M>
1233class MatcherAsPredicate {
1234 public:
1235 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1236
1237 // This template operator() allows Matches(m) to be used as a
1238 // predicate on type T where m is a matcher on type T.
1239 //
1240 // The argument x is passed by reference instead of by value, as
1241 // some matcher may be interested in its address (e.g. as in
1242 // Matches(Ref(n))(x)).
1243 template <typename T>
1244 bool operator()(const T& x) const {
1245 // We let matcher_ commit to a particular type here instead of
1246 // when the MatcherAsPredicate object was constructed. This
1247 // allows us to write Matches(m) where m is a polymorphic matcher
1248 // (e.g. Eq(5)).
1249 //
1250 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1251 // compile when matcher_ has type Matcher<const T&>; if we write
1252 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1253 // when matcher_ has type Matcher<T>; if we just write
1254 // matcher_.Matches(x), it won't compile when matcher_ is
1255 // polymorphic, e.g. Eq(5).
1256 //
1257 // MatcherCast<const T&>() is necessary for making the code work
1258 // in all of the above situations.
1259 return MatcherCast<const T&>(matcher_).Matches(x);
1260 }
1261 private:
1262 M matcher_;
1263};
1264
1265// For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1266// argument M must be a type that can be converted to a matcher.
1267template <typename M>
1268class PredicateFormatterFromMatcher {
1269 public:
1270 explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
1271
1272 // This template () operator allows a PredicateFormatterFromMatcher
1273 // object to act as a predicate-formatter suitable for using with
1274 // Google Test's EXPECT_PRED_FORMAT1() macro.
1275 template <typename T>
1276 AssertionResult operator()(const char* value_text, const T& x) const {
1277 // We convert matcher_ to a Matcher<const T&> *now* instead of
1278 // when the PredicateFormatterFromMatcher object was constructed,
1279 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1280 // know which type to instantiate it to until we actually see the
1281 // type of x here.
1282 //
1283 // We write MatcherCast<const T&>(matcher_) instead of
1284 // Matcher<const T&>(matcher_), as the latter won't compile when
1285 // matcher_ has type Matcher<T> (e.g. An<int>()).
1286 const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
1287 if (matcher.Matches(x)) {
1288 return AssertionSuccess();
1289 } else {
1290 ::std::stringstream ss;
1291 ss << "Value of: " << value_text << "\n"
1292 << "Expected: ";
1293 matcher.DescribeTo(&ss);
1294 ss << "\n Actual: ";
1295 UniversalPrinter<T>::Print(x, &ss);
1296 ExplainMatchResultAsNeededTo<const T&>(matcher, x, &ss);
1297 return AssertionFailure(Message() << ss.str());
1298 }
1299 }
1300 private:
1301 const M matcher_;
1302};
1303
1304// A helper function for converting a matcher to a predicate-formatter
1305// without the user needing to explicitly write the type. This is
1306// used for implementing ASSERT_THAT() and EXPECT_THAT().
1307template <typename M>
1308inline PredicateFormatterFromMatcher<M>
1309MakePredicateFormatterFromMatcher(const M& matcher) {
1310 return PredicateFormatterFromMatcher<M>(matcher);
1311}
1312
1313// Implements the polymorphic floating point equality matcher, which
1314// matches two float values using ULP-based approximation. The
1315// template is meant to be instantiated with FloatType being either
1316// float or double.
1317template <typename FloatType>
1318class FloatingEqMatcher {
1319 public:
1320 // Constructor for FloatingEqMatcher.
1321 // The matcher's input will be compared with rhs. The matcher treats two
1322 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1323 // equality comparisons between NANs will always return false.
1324 FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
1325 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1326
1327 // Implements floating point equality matcher as a Matcher<T>.
1328 template <typename T>
1329 class Impl : public MatcherInterface<T> {
1330 public:
1331 Impl(FloatType rhs, bool nan_eq_nan) :
1332 rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
1333
1334 virtual bool Matches(T value) const {
1335 const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
1336
1337 // Compares NaNs first, if nan_eq_nan_ is true.
1338 if (nan_eq_nan_ && lhs.is_nan()) {
1339 return rhs.is_nan();
1340 }
1341
1342 return lhs.AlmostEquals(rhs);
1343 }
1344
1345 virtual void DescribeTo(::std::ostream* os) const {
1346 // os->precision() returns the previously set precision, which we
1347 // store to restore the ostream to its original configuration
1348 // after outputting.
1349 const ::std::streamsize old_precision = os->precision(
1350 ::std::numeric_limits<FloatType>::digits10 + 2);
1351 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1352 if (nan_eq_nan_) {
1353 *os << "is NaN";
1354 } else {
1355 *os << "never matches";
1356 }
1357 } else {
1358 *os << "is approximately " << rhs_;
1359 }
1360 os->precision(old_precision);
1361 }
1362
1363 virtual void DescribeNegationTo(::std::ostream* os) const {
1364 // As before, get original precision.
1365 const ::std::streamsize old_precision = os->precision(
1366 ::std::numeric_limits<FloatType>::digits10 + 2);
1367 if (FloatingPoint<FloatType>(rhs_).is_nan()) {
1368 if (nan_eq_nan_) {
1369 *os << "is not NaN";
1370 } else {
1371 *os << "is anything";
1372 }
1373 } else {
1374 *os << "is not approximately " << rhs_;
1375 }
1376 // Restore original precision.
1377 os->precision(old_precision);
1378 }
1379
1380 private:
1381 const FloatType rhs_;
1382 const bool nan_eq_nan_;
1383 };
1384
1385 // The following 3 type conversion operators allow FloatEq(rhs) and
1386 // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
1387 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
1388 // (While Google's C++ coding style doesn't allow arguments passed
1389 // by non-const reference, we may see them in code not conforming to
1390 // the style. Therefore Google Mock needs to support them.)
1391 operator Matcher<FloatType>() const {
1392 return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
1393 }
1394
1395 operator Matcher<const FloatType&>() const {
1396 return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
1397 }
1398
1399 operator Matcher<FloatType&>() const {
1400 return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
1401 }
1402 private:
1403 const FloatType rhs_;
1404 const bool nan_eq_nan_;
1405};
1406
1407// Implements the Pointee(m) matcher for matching a pointer whose
1408// pointee matches matcher m. The pointer can be either raw or smart.
1409template <typename InnerMatcher>
1410class PointeeMatcher {
1411 public:
1412 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
1413
1414 // This type conversion operator template allows Pointee(m) to be
1415 // used as a matcher for any pointer type whose pointee type is
1416 // compatible with the inner matcher, where type Pointer can be
1417 // either a raw pointer or a smart pointer.
1418 //
1419 // The reason we do this instead of relying on
1420 // MakePolymorphicMatcher() is that the latter is not flexible
1421 // enough for implementing the DescribeTo() method of Pointee().
1422 template <typename Pointer>
1423 operator Matcher<Pointer>() const {
1424 return MakeMatcher(new Impl<Pointer>(matcher_));
1425 }
1426 private:
1427 // The monomorphic implementation that works for a particular pointer type.
1428 template <typename Pointer>
1429 class Impl : public MatcherInterface<Pointer> {
1430 public:
zhanyong.wane0d051e2009-02-19 00:33:37 +00001431 typedef typename PointeeOf<GMOCK_REMOVE_CONST_( // NOLINT
1432 GMOCK_REMOVE_REFERENCE_(Pointer))>::type Pointee;
shiqiane35fdd92008-12-10 05:08:54 +00001433
1434 explicit Impl(const InnerMatcher& matcher)
1435 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
1436
1437 virtual bool Matches(Pointer p) const {
1438 return GetRawPointer(p) != NULL && matcher_.Matches(*p);
1439 }
1440
1441 virtual void DescribeTo(::std::ostream* os) const {
1442 *os << "points to a value that ";
1443 matcher_.DescribeTo(os);
1444 }
1445
1446 virtual void DescribeNegationTo(::std::ostream* os) const {
1447 *os << "does not point to a value that ";
1448 matcher_.DescribeTo(os);
1449 }
1450
1451 virtual void ExplainMatchResultTo(Pointer pointer,
1452 ::std::ostream* os) const {
1453 if (GetRawPointer(pointer) == NULL)
1454 return;
1455
1456 ::std::stringstream ss;
1457 matcher_.ExplainMatchResultTo(*pointer, &ss);
1458 const internal::string s = ss.str();
1459 if (s != "") {
1460 *os << "points to a value that " << s;
1461 }
1462 }
1463 private:
1464 const Matcher<const Pointee&> matcher_;
1465 };
1466
1467 const InnerMatcher matcher_;
1468};
1469
1470// Implements the Field() matcher for matching a field (i.e. member
1471// variable) of an object.
1472template <typename Class, typename FieldType>
1473class FieldMatcher {
1474 public:
1475 FieldMatcher(FieldType Class::*field,
1476 const Matcher<const FieldType&>& matcher)
1477 : field_(field), matcher_(matcher) {}
1478
1479 // Returns true iff the inner matcher matches obj.field.
1480 bool Matches(const Class& obj) const {
1481 return matcher_.Matches(obj.*field_);
1482 }
1483
1484 // Returns true iff the inner matcher matches obj->field.
1485 bool Matches(const Class* p) const {
1486 return (p != NULL) && matcher_.Matches(p->*field_);
1487 }
1488
1489 void DescribeTo(::std::ostream* os) const {
1490 *os << "the given field ";
1491 matcher_.DescribeTo(os);
1492 }
1493
1494 void DescribeNegationTo(::std::ostream* os) const {
1495 *os << "the given field ";
1496 matcher_.DescribeNegationTo(os);
1497 }
1498
zhanyong.wan18490652009-05-11 18:54:08 +00001499 // The first argument of ExplainMatchResultTo() is needed to help
1500 // Symbian's C++ compiler choose which overload to use. Its type is
1501 // true_type iff the Field() matcher is used to match a pointer.
1502 void ExplainMatchResultTo(false_type /* is_not_pointer */, const Class& obj,
1503 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001504 ::std::stringstream ss;
1505 matcher_.ExplainMatchResultTo(obj.*field_, &ss);
1506 const internal::string s = ss.str();
1507 if (s != "") {
1508 *os << "the given field " << s;
1509 }
1510 }
1511
zhanyong.wan18490652009-05-11 18:54:08 +00001512 void ExplainMatchResultTo(true_type /* is_pointer */, const Class* p,
1513 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001514 if (p != NULL) {
zhanyong.wan18490652009-05-11 18:54:08 +00001515 // Since *p has a field, it must be a class/struct/union type
1516 // and thus cannot be a pointer. Therefore we pass false_type()
1517 // as the first argument.
1518 ExplainMatchResultTo(false_type(), *p, os);
shiqiane35fdd92008-12-10 05:08:54 +00001519 }
1520 }
1521 private:
1522 const FieldType Class::*field_;
1523 const Matcher<const FieldType&> matcher_;
1524};
1525
zhanyong.wan18490652009-05-11 18:54:08 +00001526// Explains the result of matching an object or pointer against a field matcher.
1527template <typename Class, typename FieldType, typename T>
shiqiane35fdd92008-12-10 05:08:54 +00001528void ExplainMatchResultTo(const FieldMatcher<Class, FieldType>& matcher,
zhanyong.wan18490652009-05-11 18:54:08 +00001529 const T& value, ::std::ostream* os) {
1530 matcher.ExplainMatchResultTo(
1531 typename ::testing::internal::is_pointer<T>::type(), value, os);
shiqiane35fdd92008-12-10 05:08:54 +00001532}
1533
1534// Implements the Property() matcher for matching a property
1535// (i.e. return value of a getter method) of an object.
1536template <typename Class, typename PropertyType>
1537class PropertyMatcher {
1538 public:
1539 // The property may have a reference type, so 'const PropertyType&'
1540 // may cause double references and fail to compile. That's why we
1541 // need GMOCK_REFERENCE_TO_CONST, which works regardless of
1542 // PropertyType being a reference or not.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001543 typedef GMOCK_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
shiqiane35fdd92008-12-10 05:08:54 +00001544
1545 PropertyMatcher(PropertyType (Class::*property)() const,
1546 const Matcher<RefToConstProperty>& matcher)
1547 : property_(property), matcher_(matcher) {}
1548
1549 // Returns true iff obj.property() matches the inner matcher.
1550 bool Matches(const Class& obj) const {
1551 return matcher_.Matches((obj.*property_)());
1552 }
1553
1554 // Returns true iff p->property() matches the inner matcher.
1555 bool Matches(const Class* p) const {
1556 return (p != NULL) && matcher_.Matches((p->*property_)());
1557 }
1558
1559 void DescribeTo(::std::ostream* os) const {
1560 *os << "the given property ";
1561 matcher_.DescribeTo(os);
1562 }
1563
1564 void DescribeNegationTo(::std::ostream* os) const {
1565 *os << "the given property ";
1566 matcher_.DescribeNegationTo(os);
1567 }
1568
zhanyong.wan18490652009-05-11 18:54:08 +00001569 // The first argument of ExplainMatchResultTo() is needed to help
1570 // Symbian's C++ compiler choose which overload to use. Its type is
1571 // true_type iff the Property() matcher is used to match a pointer.
1572 void ExplainMatchResultTo(false_type /* is_not_pointer */, const Class& obj,
1573 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001574 ::std::stringstream ss;
1575 matcher_.ExplainMatchResultTo((obj.*property_)(), &ss);
1576 const internal::string s = ss.str();
1577 if (s != "") {
1578 *os << "the given property " << s;
1579 }
1580 }
1581
zhanyong.wan18490652009-05-11 18:54:08 +00001582 void ExplainMatchResultTo(true_type /* is_pointer */, const Class* p,
1583 ::std::ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00001584 if (p != NULL) {
zhanyong.wan18490652009-05-11 18:54:08 +00001585 // Since *p has a property method, it must be a
1586 // class/struct/union type and thus cannot be a pointer.
1587 // Therefore we pass false_type() as the first argument.
1588 ExplainMatchResultTo(false_type(), *p, os);
shiqiane35fdd92008-12-10 05:08:54 +00001589 }
1590 }
1591 private:
1592 PropertyType (Class::*property_)() const;
1593 const Matcher<RefToConstProperty> matcher_;
1594};
1595
zhanyong.wan18490652009-05-11 18:54:08 +00001596// Explains the result of matching an object or pointer against a
1597// property matcher.
1598template <typename Class, typename PropertyType, typename T>
shiqiane35fdd92008-12-10 05:08:54 +00001599void ExplainMatchResultTo(const PropertyMatcher<Class, PropertyType>& matcher,
zhanyong.wan18490652009-05-11 18:54:08 +00001600 const T& value, ::std::ostream* os) {
1601 matcher.ExplainMatchResultTo(
1602 typename ::testing::internal::is_pointer<T>::type(), value, os);
shiqiane35fdd92008-12-10 05:08:54 +00001603}
1604
1605// Type traits specifying various features of different functors for ResultOf.
1606// The default template specifies features for functor objects.
1607// Functor classes have to typedef argument_type and result_type
1608// to be compatible with ResultOf.
1609template <typename Functor>
1610struct CallableTraits {
1611 typedef typename Functor::result_type ResultType;
1612 typedef Functor StorageType;
1613
1614 static void CheckIsValid(Functor functor) {}
1615 template <typename T>
1616 static ResultType Invoke(Functor f, T arg) { return f(arg); }
1617};
1618
1619// Specialization for function pointers.
1620template <typename ArgType, typename ResType>
1621struct CallableTraits<ResType(*)(ArgType)> {
1622 typedef ResType ResultType;
1623 typedef ResType(*StorageType)(ArgType);
1624
1625 static void CheckIsValid(ResType(*f)(ArgType)) {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001626 GTEST_CHECK_(f != NULL)
shiqiane35fdd92008-12-10 05:08:54 +00001627 << "NULL function pointer is passed into ResultOf().";
1628 }
1629 template <typename T>
1630 static ResType Invoke(ResType(*f)(ArgType), T arg) {
1631 return (*f)(arg);
1632 }
1633};
1634
1635// Implements the ResultOf() matcher for matching a return value of a
1636// unary function of an object.
1637template <typename Callable>
1638class ResultOfMatcher {
1639 public:
1640 typedef typename CallableTraits<Callable>::ResultType ResultType;
1641
1642 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
1643 : callable_(callable), matcher_(matcher) {
1644 CallableTraits<Callable>::CheckIsValid(callable_);
1645 }
1646
1647 template <typename T>
1648 operator Matcher<T>() const {
1649 return Matcher<T>(new Impl<T>(callable_, matcher_));
1650 }
1651
1652 private:
1653 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
1654
1655 template <typename T>
1656 class Impl : public MatcherInterface<T> {
1657 public:
1658 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
1659 : callable_(callable), matcher_(matcher) {}
1660 // Returns true iff callable_(obj) matches the inner matcher.
1661 // The calling syntax is different for different types of callables
1662 // so we abstract it in CallableTraits<Callable>::Invoke().
1663 virtual bool Matches(T obj) const {
1664 return matcher_.Matches(
1665 CallableTraits<Callable>::template Invoke<T>(callable_, obj));
1666 }
1667
1668 virtual void DescribeTo(::std::ostream* os) const {
1669 *os << "result of the given callable ";
1670 matcher_.DescribeTo(os);
1671 }
1672
1673 virtual void DescribeNegationTo(::std::ostream* os) const {
1674 *os << "result of the given callable ";
1675 matcher_.DescribeNegationTo(os);
1676 }
1677
1678 virtual void ExplainMatchResultTo(T obj, ::std::ostream* os) const {
1679 ::std::stringstream ss;
1680 matcher_.ExplainMatchResultTo(
1681 CallableTraits<Callable>::template Invoke<T>(callable_, obj),
1682 &ss);
1683 const internal::string s = ss.str();
1684 if (s != "")
1685 *os << "result of the given callable " << s;
1686 }
1687 private:
1688 // Functors often define operator() as non-const method even though
1689 // they are actualy stateless. But we need to use them even when
1690 // 'this' is a const pointer. It's the user's responsibility not to
1691 // use stateful callables with ResultOf(), which does't guarantee
1692 // how many times the callable will be invoked.
1693 mutable CallableStorageType callable_;
1694 const Matcher<ResultType> matcher_;
1695 }; // class Impl
1696
1697 const CallableStorageType callable_;
1698 const Matcher<ResultType> matcher_;
1699};
1700
1701// Explains the result of matching a value against a functor matcher.
1702template <typename T, typename Callable>
1703void ExplainMatchResultTo(const ResultOfMatcher<Callable>& matcher,
1704 T obj, ::std::ostream* os) {
1705 matcher.ExplainMatchResultTo(obj, os);
1706}
1707
zhanyong.wan6a896b52009-01-16 01:13:50 +00001708// Implements an equality matcher for any STL-style container whose elements
1709// support ==. This matcher is like Eq(), but its failure explanations provide
1710// more detailed information that is useful when the container is used as a set.
1711// The failure message reports elements that are in one of the operands but not
1712// the other. The failure messages do not report duplicate or out-of-order
1713// elements in the containers (which don't properly matter to sets, but can
1714// occur if the containers are vectors or lists, for example).
1715//
1716// Uses the container's const_iterator, value_type, operator ==,
1717// begin(), and end().
1718template <typename Container>
1719class ContainerEqMatcher {
1720 public:
zhanyong.wanb8243162009-06-04 05:48:20 +00001721 typedef internal::StlContainerView<Container> View;
1722 typedef typename View::type StlContainer;
1723 typedef typename View::const_reference StlContainerReference;
1724
1725 // We make a copy of rhs in case the elements in it are modified
1726 // after this matcher is created.
1727 explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
1728 // Makes sure the user doesn't instantiate this class template
1729 // with a const or reference type.
1730 testing::StaticAssertTypeEq<Container,
1731 GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))>();
1732 }
1733
1734 template <typename LhsContainer>
1735 bool Matches(const LhsContainer& lhs) const {
1736 // GMOCK_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
1737 // that causes LhsContainer to be a const type sometimes.
1738 typedef internal::StlContainerView<GMOCK_REMOVE_CONST_(LhsContainer)>
1739 LhsView;
1740 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
1741 return lhs_stl_container == rhs_;
1742 }
zhanyong.wan6a896b52009-01-16 01:13:50 +00001743 void DescribeTo(::std::ostream* os) const {
1744 *os << "equals ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001745 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001746 }
1747 void DescribeNegationTo(::std::ostream* os) const {
1748 *os << "does not equal ";
zhanyong.wanb8243162009-06-04 05:48:20 +00001749 UniversalPrinter<StlContainer>::Print(rhs_, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001750 }
1751
zhanyong.wanb8243162009-06-04 05:48:20 +00001752 template <typename LhsContainer>
1753 void ExplainMatchResultTo(const LhsContainer& lhs,
zhanyong.wan6a896b52009-01-16 01:13:50 +00001754 ::std::ostream* os) const {
zhanyong.wanb8243162009-06-04 05:48:20 +00001755 // GMOCK_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
1756 // that causes LhsContainer to be a const type sometimes.
1757 typedef internal::StlContainerView<GMOCK_REMOVE_CONST_(LhsContainer)>
1758 LhsView;
1759 typedef typename LhsView::type LhsStlContainer;
1760 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
1761
zhanyong.wan6a896b52009-01-16 01:13:50 +00001762 // Something is different. Check for missing values first.
1763 bool printed_header = false;
zhanyong.wanb8243162009-06-04 05:48:20 +00001764 for (typename LhsStlContainer::const_iterator it =
1765 lhs_stl_container.begin();
1766 it != lhs_stl_container.end(); ++it) {
1767 if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
1768 rhs_.end()) {
zhanyong.wan6a896b52009-01-16 01:13:50 +00001769 if (printed_header) {
1770 *os << ", ";
1771 } else {
1772 *os << "Only in actual: ";
1773 printed_header = true;
1774 }
zhanyong.wanb8243162009-06-04 05:48:20 +00001775 UniversalPrinter<typename LhsStlContainer::value_type>::Print(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001776 }
1777 }
1778
1779 // Now check for extra values.
1780 bool printed_header2 = false;
zhanyong.wanb8243162009-06-04 05:48:20 +00001781 for (typename StlContainer::const_iterator it = rhs_.begin();
zhanyong.wan6a896b52009-01-16 01:13:50 +00001782 it != rhs_.end(); ++it) {
zhanyong.wanb8243162009-06-04 05:48:20 +00001783 if (internal::ArrayAwareFind(
1784 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
1785 lhs_stl_container.end()) {
zhanyong.wan6a896b52009-01-16 01:13:50 +00001786 if (printed_header2) {
1787 *os << ", ";
1788 } else {
1789 *os << (printed_header ? "; not" : "Not") << " in actual: ";
1790 printed_header2 = true;
1791 }
zhanyong.wanb8243162009-06-04 05:48:20 +00001792 UniversalPrinter<typename StlContainer::value_type>::Print(*it, os);
zhanyong.wan6a896b52009-01-16 01:13:50 +00001793 }
1794 }
1795 }
1796 private:
zhanyong.wanb8243162009-06-04 05:48:20 +00001797 const StlContainer rhs_;
zhanyong.wan6a896b52009-01-16 01:13:50 +00001798};
1799
zhanyong.wanb8243162009-06-04 05:48:20 +00001800template <typename LhsContainer, typename Container>
zhanyong.wan6a896b52009-01-16 01:13:50 +00001801void ExplainMatchResultTo(const ContainerEqMatcher<Container>& matcher,
zhanyong.wanb8243162009-06-04 05:48:20 +00001802 const LhsContainer& lhs,
zhanyong.wan6a896b52009-01-16 01:13:50 +00001803 ::std::ostream* os) {
1804 matcher.ExplainMatchResultTo(lhs, os);
1805}
1806
zhanyong.wanb8243162009-06-04 05:48:20 +00001807// Implements Contains(element_matcher) for the given argument type Container.
1808template <typename Container>
1809class ContainsMatcherImpl : public MatcherInterface<Container> {
1810 public:
1811 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
1812 typedef StlContainerView<RawContainer> View;
1813 typedef typename View::type StlContainer;
1814 typedef typename View::const_reference StlContainerReference;
1815 typedef typename StlContainer::value_type Element;
1816
1817 template <typename InnerMatcher>
1818 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
1819 : inner_matcher_(
1820 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
1821
1822 // Returns true iff 'container' matches.
1823 virtual bool Matches(Container container) const {
1824 StlContainerReference stl_container = View::ConstReference(container);
1825 for (typename StlContainer::const_iterator it = stl_container.begin();
1826 it != stl_container.end(); ++it) {
1827 if (inner_matcher_.Matches(*it))
1828 return true;
1829 }
1830 return false;
1831 }
1832
1833 // Describes what this matcher does.
1834 virtual void DescribeTo(::std::ostream* os) const {
1835 *os << "contains at least one element that ";
1836 inner_matcher_.DescribeTo(os);
1837 }
1838
1839 // Describes what the negation of this matcher does.
1840 virtual void DescribeNegationTo(::std::ostream* os) const {
1841 *os << "doesn't contain any element that ";
1842 inner_matcher_.DescribeTo(os);
1843 }
1844
1845 // Explains why 'container' matches, or doesn't match, this matcher.
1846 virtual void ExplainMatchResultTo(Container container,
1847 ::std::ostream* os) const {
1848 StlContainerReference stl_container = View::ConstReference(container);
1849
1850 // We need to explain which (if any) element matches inner_matcher_.
1851 typename StlContainer::const_iterator it = stl_container.begin();
1852 for (size_t i = 0; it != stl_container.end(); ++it, ++i) {
1853 if (inner_matcher_.Matches(*it)) {
1854 *os << "element " << i << " matches";
1855 return;
1856 }
1857 }
1858 }
1859
1860 private:
1861 const Matcher<const Element&> inner_matcher_;
1862};
1863
1864// Implements polymorphic Contains(element_matcher).
1865template <typename M>
1866class ContainsMatcher {
1867 public:
1868 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
1869
1870 template <typename Container>
1871 operator Matcher<Container>() const {
1872 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
1873 }
1874
1875 private:
1876 const M inner_matcher_;
1877};
1878
zhanyong.wanb5937da2009-07-16 20:26:41 +00001879// Implements Key(inner_matcher) for the given argument pair type.
1880// Key(inner_matcher) matches an std::pair whose 'first' field matches
1881// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
1882// std::map that contains at least one element whose key is >= 5.
1883template <typename PairType>
1884class KeyMatcherImpl : public MatcherInterface<PairType> {
1885 public:
1886 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
1887 typedef typename RawPairType::first_type KeyType;
1888
1889 template <typename InnerMatcher>
1890 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
1891 : inner_matcher_(
1892 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
1893 }
1894
1895 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
1896 virtual bool Matches(PairType key_value) const {
1897 return inner_matcher_.Matches(key_value.first);
1898 }
1899
1900 // Describes what this matcher does.
1901 virtual void DescribeTo(::std::ostream* os) const {
1902 *os << "has a key that ";
1903 inner_matcher_.DescribeTo(os);
1904 }
1905
1906 // Describes what the negation of this matcher does.
1907 virtual void DescribeNegationTo(::std::ostream* os) const {
1908 *os << "doesn't have a key that ";
1909 inner_matcher_.DescribeTo(os);
1910 }
1911
1912 // Explains why 'key_value' matches, or doesn't match, this matcher.
1913 virtual void ExplainMatchResultTo(PairType key_value,
1914 ::std::ostream* os) const {
1915 inner_matcher_.ExplainMatchResultTo(key_value.first, os);
1916 }
1917
1918 private:
1919 const Matcher<const KeyType&> inner_matcher_;
1920};
1921
1922// Implements polymorphic Key(matcher_for_key).
1923template <typename M>
1924class KeyMatcher {
1925 public:
1926 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
1927
1928 template <typename PairType>
1929 operator Matcher<PairType>() const {
1930 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
1931 }
1932
1933 private:
1934 const M matcher_for_key_;
1935};
1936
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001937// Implements Pair(first_matcher, second_matcher) for the given argument pair
1938// type with its two matchers. See Pair() function below.
1939template <typename PairType>
1940class PairMatcherImpl : public MatcherInterface<PairType> {
1941 public:
1942 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(PairType)) RawPairType;
1943 typedef typename RawPairType::first_type FirstType;
1944 typedef typename RawPairType::second_type SecondType;
1945
1946 template <typename FirstMatcher, typename SecondMatcher>
1947 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
1948 : first_matcher_(
1949 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
1950 second_matcher_(
1951 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
1952 }
1953
1954 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
1955 // matches second_matcher.
1956 virtual bool Matches(PairType a_pair) const {
1957 return first_matcher_.Matches(a_pair.first) &&
1958 second_matcher_.Matches(a_pair.second);
1959 }
1960
1961 // Describes what this matcher does.
1962 virtual void DescribeTo(::std::ostream* os) const {
1963 *os << "has a first field that ";
1964 first_matcher_.DescribeTo(os);
1965 *os << ", and has a second field that ";
1966 second_matcher_.DescribeTo(os);
1967 }
1968
1969 // Describes what the negation of this matcher does.
1970 virtual void DescribeNegationTo(::std::ostream* os) const {
1971 *os << "has a first field that ";
1972 first_matcher_.DescribeNegationTo(os);
1973 *os << ", or has a second field that ";
1974 second_matcher_.DescribeNegationTo(os);
1975 }
1976
1977 // Explains why 'a_pair' matches, or doesn't match, this matcher.
1978 virtual void ExplainMatchResultTo(PairType a_pair,
1979 ::std::ostream* os) const {
1980 ::std::stringstream ss1;
1981 first_matcher_.ExplainMatchResultTo(a_pair.first, &ss1);
1982 internal::string s1 = ss1.str();
1983 if (s1 != "") {
1984 s1 = "the first field " + s1;
1985 }
1986
1987 ::std::stringstream ss2;
1988 second_matcher_.ExplainMatchResultTo(a_pair.second, &ss2);
1989 internal::string s2 = ss2.str();
1990 if (s2 != "") {
1991 s2 = "the second field " + s2;
1992 }
1993
1994 *os << s1;
1995 if (s1 != "" && s2 != "") {
1996 *os << ", and ";
1997 }
1998 *os << s2;
1999 }
2000
2001 private:
2002 const Matcher<const FirstType&> first_matcher_;
2003 const Matcher<const SecondType&> second_matcher_;
2004};
2005
2006// Implements polymorphic Pair(first_matcher, second_matcher).
2007template <typename FirstMatcher, typename SecondMatcher>
2008class PairMatcher {
2009 public:
2010 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
2011 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
2012
2013 template <typename PairType>
2014 operator Matcher<PairType> () const {
2015 return MakeMatcher(
2016 new PairMatcherImpl<PairType>(
2017 first_matcher_, second_matcher_));
2018 }
2019
2020 private:
2021 const FirstMatcher first_matcher_;
2022 const SecondMatcher second_matcher_;
2023};
2024
zhanyong.wan1afe1c72009-07-21 23:26:31 +00002025// Implements ElementsAre() and ElementsAreArray().
2026template <typename Container>
2027class ElementsAreMatcherImpl : public MatcherInterface<Container> {
2028 public:
2029 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container)) RawContainer;
2030 typedef internal::StlContainerView<RawContainer> View;
2031 typedef typename View::type StlContainer;
2032 typedef typename View::const_reference StlContainerReference;
2033 typedef typename StlContainer::value_type Element;
2034
2035 // Constructs the matcher from a sequence of element values or
2036 // element matchers.
2037 template <typename InputIter>
2038 ElementsAreMatcherImpl(InputIter first, size_t count) {
2039 matchers_.reserve(count);
2040 InputIter it = first;
2041 for (size_t i = 0; i != count; ++i, ++it) {
2042 matchers_.push_back(MatcherCast<const Element&>(*it));
2043 }
2044 }
2045
2046 // Returns true iff 'container' matches.
2047 virtual bool Matches(Container container) const {
2048 StlContainerReference stl_container = View::ConstReference(container);
2049 if (stl_container.size() != count())
2050 return false;
2051
2052 typename StlContainer::const_iterator it = stl_container.begin();
2053 for (size_t i = 0; i != count(); ++it, ++i) {
2054 if (!matchers_[i].Matches(*it))
2055 return false;
2056 }
2057
2058 return true;
2059 }
2060
2061 // Describes what this matcher does.
2062 virtual void DescribeTo(::std::ostream* os) const {
2063 if (count() == 0) {
2064 *os << "is empty";
2065 } else if (count() == 1) {
2066 *os << "has 1 element that ";
2067 matchers_[0].DescribeTo(os);
2068 } else {
2069 *os << "has " << Elements(count()) << " where\n";
2070 for (size_t i = 0; i != count(); ++i) {
2071 *os << "element " << i << " ";
2072 matchers_[i].DescribeTo(os);
2073 if (i + 1 < count()) {
2074 *os << ",\n";
2075 }
2076 }
2077 }
2078 }
2079
2080 // Describes what the negation of this matcher does.
2081 virtual void DescribeNegationTo(::std::ostream* os) const {
2082 if (count() == 0) {
2083 *os << "is not empty";
2084 return;
2085 }
2086
2087 *os << "does not have " << Elements(count()) << ", or\n";
2088 for (size_t i = 0; i != count(); ++i) {
2089 *os << "element " << i << " ";
2090 matchers_[i].DescribeNegationTo(os);
2091 if (i + 1 < count()) {
2092 *os << ", or\n";
2093 }
2094 }
2095 }
2096
2097 // Explains why 'container' matches, or doesn't match, this matcher.
2098 virtual void ExplainMatchResultTo(Container container,
2099 ::std::ostream* os) const {
2100 StlContainerReference stl_container = View::ConstReference(container);
2101 if (Matches(container)) {
2102 // We need to explain why *each* element matches (the obvious
2103 // ones can be skipped).
2104
2105 bool reason_printed = false;
2106 typename StlContainer::const_iterator it = stl_container.begin();
2107 for (size_t i = 0; i != count(); ++it, ++i) {
2108 ::std::stringstream ss;
2109 matchers_[i].ExplainMatchResultTo(*it, &ss);
2110
2111 const string s = ss.str();
2112 if (!s.empty()) {
2113 if (reason_printed) {
2114 *os << ",\n";
2115 }
2116 *os << "element " << i << " " << s;
2117 reason_printed = true;
2118 }
2119 }
2120 } else {
2121 // We need to explain why the container doesn't match.
2122 const size_t actual_count = stl_container.size();
2123 if (actual_count != count()) {
2124 // The element count doesn't match. If the container is
2125 // empty, there's no need to explain anything as Google Mock
2126 // already prints the empty container. Otherwise we just need
2127 // to show how many elements there actually are.
2128 if (actual_count != 0) {
2129 *os << "has " << Elements(actual_count);
2130 }
2131 return;
2132 }
2133
2134 // The container has the right size but at least one element
2135 // doesn't match expectation. We need to find this element and
2136 // explain why it doesn't match.
2137 typename StlContainer::const_iterator it = stl_container.begin();
2138 for (size_t i = 0; i != count(); ++it, ++i) {
2139 if (matchers_[i].Matches(*it)) {
2140 continue;
2141 }
2142
2143 *os << "element " << i << " doesn't match";
2144
2145 ::std::stringstream ss;
2146 matchers_[i].ExplainMatchResultTo(*it, &ss);
2147 const string s = ss.str();
2148 if (!s.empty()) {
2149 *os << " (" << s << ")";
2150 }
2151 return;
2152 }
2153 }
2154 }
2155
2156 private:
2157 static Message Elements(size_t count) {
2158 return Message() << count << (count == 1 ? " element" : " elements");
2159 }
2160
2161 size_t count() const { return matchers_.size(); }
2162 std::vector<Matcher<const Element&> > matchers_;
2163};
2164
2165// Implements ElementsAre() of 0 arguments.
2166class ElementsAreMatcher0 {
2167 public:
2168 ElementsAreMatcher0() {}
2169
2170 template <typename Container>
2171 operator Matcher<Container>() const {
2172 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2173 RawContainer;
2174 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2175 Element;
2176
2177 const Matcher<const Element&>* const matchers = NULL;
2178 return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 0));
2179 }
2180};
2181
2182// Implements ElementsAreArray().
2183template <typename T>
2184class ElementsAreArrayMatcher {
2185 public:
2186 ElementsAreArrayMatcher(const T* first, size_t count) :
2187 first_(first), count_(count) {}
2188
2189 template <typename Container>
2190 operator Matcher<Container>() const {
2191 typedef GMOCK_REMOVE_CONST_(GMOCK_REMOVE_REFERENCE_(Container))
2192 RawContainer;
2193 typedef typename internal::StlContainerView<RawContainer>::type::value_type
2194 Element;
2195
2196 return MakeMatcher(new ElementsAreMatcherImpl<Container>(first_, count_));
2197 }
2198
2199 private:
2200 const T* const first_;
2201 const size_t count_;
2202};
2203
2204// Constants denoting interpolations in a matcher description string.
2205const int kTupleInterpolation = -1; // "%(*)s"
2206const int kPercentInterpolation = -2; // "%%"
2207const int kInvalidInterpolation = -3; // "%" followed by invalid text
2208
2209// Records the location and content of an interpolation.
2210struct Interpolation {
2211 Interpolation(const char* start, const char* end, int param)
2212 : start_pos(start), end_pos(end), param_index(param) {}
2213
2214 // Points to the start of the interpolation (the '%' character).
2215 const char* start_pos;
2216 // Points to the first character after the interpolation.
2217 const char* end_pos;
2218 // 0-based index of the interpolated matcher parameter;
2219 // kTupleInterpolation for "%(*)s"; kPercentInterpolation for "%%".
2220 int param_index;
2221};
2222
2223typedef ::std::vector<Interpolation> Interpolations;
2224
2225// Parses a matcher description string and returns a vector of
2226// interpolations that appear in the string; generates non-fatal
2227// failures iff 'description' is an invalid matcher description.
2228// 'param_names' is a NULL-terminated array of parameter names in the
2229// order they appear in the MATCHER_P*() parameter list.
2230Interpolations ValidateMatcherDescription(
2231 const char* param_names[], const char* description);
2232
2233// Returns the actual matcher description, given the matcher name,
2234// user-supplied description template string, interpolations in the
2235// string, and the printed values of the matcher parameters.
2236string FormatMatcherDescription(
2237 const char* matcher_name, const char* description,
2238 const Interpolations& interp, const Strings& param_values);
2239
shiqiane35fdd92008-12-10 05:08:54 +00002240} // namespace internal
2241
2242// Implements MatcherCast().
2243template <typename T, typename M>
2244inline Matcher<T> MatcherCast(M matcher) {
2245 return internal::MatcherCastImpl<T, M>::Cast(matcher);
2246}
2247
2248// _ is a matcher that matches anything of any type.
2249//
2250// This definition is fine as:
2251//
2252// 1. The C++ standard permits using the name _ in a namespace that
2253// is not the global namespace or ::std.
2254// 2. The AnythingMatcher class has no data member or constructor,
2255// so it's OK to create global variables of this type.
2256// 3. c-style has approved of using _ in this case.
2257const internal::AnythingMatcher _ = {};
2258// Creates a matcher that matches any value of the given type T.
2259template <typename T>
2260inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
2261
2262// Creates a matcher that matches any value of the given type T.
2263template <typename T>
2264inline Matcher<T> An() { return A<T>(); }
2265
2266// Creates a polymorphic matcher that matches anything equal to x.
2267// Note: if the parameter of Eq() were declared as const T&, Eq("foo")
2268// wouldn't compile.
2269template <typename T>
2270inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
2271
2272// Constructs a Matcher<T> from a 'value' of type T. The constructed
2273// matcher matches any value that's equal to 'value'.
2274template <typename T>
2275Matcher<T>::Matcher(T value) { *this = Eq(value); }
2276
2277// Creates a monomorphic matcher that matches anything with type Lhs
2278// and equal to rhs. A user may need to use this instead of Eq(...)
2279// in order to resolve an overloading ambiguity.
2280//
2281// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
2282// or Matcher<T>(x), but more readable than the latter.
2283//
2284// We could define similar monomorphic matchers for other comparison
2285// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
2286// it yet as those are used much less than Eq() in practice. A user
2287// can always write Matcher<T>(Lt(5)) to be explicit about the type,
2288// for example.
2289template <typename Lhs, typename Rhs>
2290inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
2291
2292// Creates a polymorphic matcher that matches anything >= x.
2293template <typename Rhs>
2294inline internal::GeMatcher<Rhs> Ge(Rhs x) {
2295 return internal::GeMatcher<Rhs>(x);
2296}
2297
2298// Creates a polymorphic matcher that matches anything > x.
2299template <typename Rhs>
2300inline internal::GtMatcher<Rhs> Gt(Rhs x) {
2301 return internal::GtMatcher<Rhs>(x);
2302}
2303
2304// Creates a polymorphic matcher that matches anything <= x.
2305template <typename Rhs>
2306inline internal::LeMatcher<Rhs> Le(Rhs x) {
2307 return internal::LeMatcher<Rhs>(x);
2308}
2309
2310// Creates a polymorphic matcher that matches anything < x.
2311template <typename Rhs>
2312inline internal::LtMatcher<Rhs> Lt(Rhs x) {
2313 return internal::LtMatcher<Rhs>(x);
2314}
2315
2316// Creates a polymorphic matcher that matches anything != x.
2317template <typename Rhs>
2318inline internal::NeMatcher<Rhs> Ne(Rhs x) {
2319 return internal::NeMatcher<Rhs>(x);
2320}
2321
2322// Creates a polymorphic matcher that matches any non-NULL pointer.
2323// This is convenient as Not(NULL) doesn't compile (the compiler
2324// thinks that that expression is comparing a pointer with an integer).
2325inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
2326 return MakePolymorphicMatcher(internal::NotNullMatcher());
2327}
2328
2329// Creates a polymorphic matcher that matches any argument that
2330// references variable x.
2331template <typename T>
2332inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
2333 return internal::RefMatcher<T&>(x);
2334}
2335
2336// Creates a matcher that matches any double argument approximately
2337// equal to rhs, where two NANs are considered unequal.
2338inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
2339 return internal::FloatingEqMatcher<double>(rhs, false);
2340}
2341
2342// Creates a matcher that matches any double argument approximately
2343// equal to rhs, including NaN values when rhs is NaN.
2344inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
2345 return internal::FloatingEqMatcher<double>(rhs, true);
2346}
2347
2348// Creates a matcher that matches any float argument approximately
2349// equal to rhs, where two NANs are considered unequal.
2350inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
2351 return internal::FloatingEqMatcher<float>(rhs, false);
2352}
2353
2354// Creates a matcher that matches any double argument approximately
2355// equal to rhs, including NaN values when rhs is NaN.
2356inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
2357 return internal::FloatingEqMatcher<float>(rhs, true);
2358}
2359
2360// Creates a matcher that matches a pointer (raw or smart) that points
2361// to a value that matches inner_matcher.
2362template <typename InnerMatcher>
2363inline internal::PointeeMatcher<InnerMatcher> Pointee(
2364 const InnerMatcher& inner_matcher) {
2365 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
2366}
2367
2368// Creates a matcher that matches an object whose given field matches
2369// 'matcher'. For example,
2370// Field(&Foo::number, Ge(5))
2371// matches a Foo object x iff x.number >= 5.
2372template <typename Class, typename FieldType, typename FieldMatcher>
2373inline PolymorphicMatcher<
2374 internal::FieldMatcher<Class, FieldType> > Field(
2375 FieldType Class::*field, const FieldMatcher& matcher) {
2376 return MakePolymorphicMatcher(
2377 internal::FieldMatcher<Class, FieldType>(
2378 field, MatcherCast<const FieldType&>(matcher)));
2379 // The call to MatcherCast() is required for supporting inner
2380 // matchers of compatible types. For example, it allows
2381 // Field(&Foo::bar, m)
2382 // to compile where bar is an int32 and m is a matcher for int64.
2383}
2384
2385// Creates a matcher that matches an object whose given property
2386// matches 'matcher'. For example,
2387// Property(&Foo::str, StartsWith("hi"))
2388// matches a Foo object x iff x.str() starts with "hi".
2389template <typename Class, typename PropertyType, typename PropertyMatcher>
2390inline PolymorphicMatcher<
2391 internal::PropertyMatcher<Class, PropertyType> > Property(
2392 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
2393 return MakePolymorphicMatcher(
2394 internal::PropertyMatcher<Class, PropertyType>(
2395 property,
zhanyong.wane0d051e2009-02-19 00:33:37 +00002396 MatcherCast<GMOCK_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
shiqiane35fdd92008-12-10 05:08:54 +00002397 // The call to MatcherCast() is required for supporting inner
2398 // matchers of compatible types. For example, it allows
2399 // Property(&Foo::bar, m)
2400 // to compile where bar() returns an int32 and m is a matcher for int64.
2401}
2402
2403// Creates a matcher that matches an object iff the result of applying
2404// a callable to x matches 'matcher'.
2405// For example,
2406// ResultOf(f, StartsWith("hi"))
2407// matches a Foo object x iff f(x) starts with "hi".
2408// callable parameter can be a function, function pointer, or a functor.
2409// Callable has to satisfy the following conditions:
2410// * It is required to keep no state affecting the results of
2411// the calls on it and make no assumptions about how many calls
2412// will be made. Any state it keeps must be protected from the
2413// concurrent access.
2414// * If it is a function object, it has to define type result_type.
2415// We recommend deriving your functor classes from std::unary_function.
2416template <typename Callable, typename ResultOfMatcher>
2417internal::ResultOfMatcher<Callable> ResultOf(
2418 Callable callable, const ResultOfMatcher& matcher) {
2419 return internal::ResultOfMatcher<Callable>(
2420 callable,
2421 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
2422 matcher));
2423 // The call to MatcherCast() is required for supporting inner
2424 // matchers of compatible types. For example, it allows
2425 // ResultOf(Function, m)
2426 // to compile where Function() returns an int32 and m is a matcher for int64.
2427}
2428
2429// String matchers.
2430
2431// Matches a string equal to str.
2432inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2433 StrEq(const internal::string& str) {
2434 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2435 str, true, true));
2436}
2437
2438// Matches a string not equal to str.
2439inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2440 StrNe(const internal::string& str) {
2441 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2442 str, false, true));
2443}
2444
2445// Matches a string equal to str, ignoring case.
2446inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2447 StrCaseEq(const internal::string& str) {
2448 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2449 str, true, false));
2450}
2451
2452// Matches a string not equal to str, ignoring case.
2453inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
2454 StrCaseNe(const internal::string& str) {
2455 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
2456 str, false, false));
2457}
2458
2459// Creates a matcher that matches any string, std::string, or C string
2460// that contains the given substring.
2461inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
2462 HasSubstr(const internal::string& substring) {
2463 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
2464 substring));
2465}
2466
2467// Matches a string that starts with 'prefix' (case-sensitive).
2468inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
2469 StartsWith(const internal::string& prefix) {
2470 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
2471 prefix));
2472}
2473
2474// Matches a string that ends with 'suffix' (case-sensitive).
2475inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
2476 EndsWith(const internal::string& suffix) {
2477 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
2478 suffix));
2479}
2480
2481#ifdef GMOCK_HAS_REGEX
2482
2483// Matches a string that fully matches regular expression 'regex'.
2484// The matcher takes ownership of 'regex'.
2485inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2486 const internal::RE* regex) {
2487 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
2488}
2489inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
2490 const internal::string& regex) {
2491 return MatchesRegex(new internal::RE(regex));
2492}
2493
2494// Matches a string that contains regular expression 'regex'.
2495// The matcher takes ownership of 'regex'.
2496inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2497 const internal::RE* regex) {
2498 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
2499}
2500inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
2501 const internal::string& regex) {
2502 return ContainsRegex(new internal::RE(regex));
2503}
2504
2505#endif // GMOCK_HAS_REGEX
2506
2507#if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2508// Wide string matchers.
2509
2510// Matches a string equal to str.
2511inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2512 StrEq(const internal::wstring& str) {
2513 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2514 str, true, true));
2515}
2516
2517// Matches a string not equal to str.
2518inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2519 StrNe(const internal::wstring& str) {
2520 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2521 str, false, true));
2522}
2523
2524// Matches a string equal to str, ignoring case.
2525inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2526 StrCaseEq(const internal::wstring& str) {
2527 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2528 str, true, false));
2529}
2530
2531// Matches a string not equal to str, ignoring case.
2532inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
2533 StrCaseNe(const internal::wstring& str) {
2534 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
2535 str, false, false));
2536}
2537
2538// Creates a matcher that matches any wstring, std::wstring, or C wide string
2539// that contains the given substring.
2540inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
2541 HasSubstr(const internal::wstring& substring) {
2542 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
2543 substring));
2544}
2545
2546// Matches a string that starts with 'prefix' (case-sensitive).
2547inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
2548 StartsWith(const internal::wstring& prefix) {
2549 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
2550 prefix));
2551}
2552
2553// Matches a string that ends with 'suffix' (case-sensitive).
2554inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
2555 EndsWith(const internal::wstring& suffix) {
2556 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
2557 suffix));
2558}
2559
2560#endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
2561
2562// Creates a polymorphic matcher that matches a 2-tuple where the
2563// first field == the second field.
2564inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
2565
2566// Creates a polymorphic matcher that matches a 2-tuple where the
2567// first field >= the second field.
2568inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
2569
2570// Creates a polymorphic matcher that matches a 2-tuple where the
2571// first field > the second field.
2572inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
2573
2574// Creates a polymorphic matcher that matches a 2-tuple where the
2575// first field <= the second field.
2576inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
2577
2578// Creates a polymorphic matcher that matches a 2-tuple where the
2579// first field < the second field.
2580inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
2581
2582// Creates a polymorphic matcher that matches a 2-tuple where the
2583// first field != the second field.
2584inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
2585
2586// Creates a matcher that matches any value of type T that m doesn't
2587// match.
2588template <typename InnerMatcher>
2589inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
2590 return internal::NotMatcher<InnerMatcher>(m);
2591}
2592
2593// Creates a matcher that matches any value that matches all of the
2594// given matchers.
2595//
2596// For now we only support up to 5 matchers. Support for more
2597// matchers can be added as needed, or the user can use nested
2598// AllOf()s.
2599template <typename Matcher1, typename Matcher2>
2600inline internal::BothOfMatcher<Matcher1, Matcher2>
2601AllOf(Matcher1 m1, Matcher2 m2) {
2602 return internal::BothOfMatcher<Matcher1, Matcher2>(m1, m2);
2603}
2604
2605template <typename Matcher1, typename Matcher2, typename Matcher3>
2606inline internal::BothOfMatcher<Matcher1,
2607 internal::BothOfMatcher<Matcher2, Matcher3> >
2608AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2609 return AllOf(m1, AllOf(m2, m3));
2610}
2611
2612template <typename Matcher1, typename Matcher2, typename Matcher3,
2613 typename Matcher4>
2614inline internal::BothOfMatcher<Matcher1,
2615 internal::BothOfMatcher<Matcher2,
2616 internal::BothOfMatcher<Matcher3, Matcher4> > >
2617AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2618 return AllOf(m1, AllOf(m2, m3, m4));
2619}
2620
2621template <typename Matcher1, typename Matcher2, typename Matcher3,
2622 typename Matcher4, typename Matcher5>
2623inline internal::BothOfMatcher<Matcher1,
2624 internal::BothOfMatcher<Matcher2,
2625 internal::BothOfMatcher<Matcher3,
2626 internal::BothOfMatcher<Matcher4, Matcher5> > > >
2627AllOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2628 return AllOf(m1, AllOf(m2, m3, m4, m5));
2629}
2630
2631// Creates a matcher that matches any value that matches at least one
2632// of the given matchers.
2633//
2634// For now we only support up to 5 matchers. Support for more
2635// matchers can be added as needed, or the user can use nested
2636// AnyOf()s.
2637template <typename Matcher1, typename Matcher2>
2638inline internal::EitherOfMatcher<Matcher1, Matcher2>
2639AnyOf(Matcher1 m1, Matcher2 m2) {
2640 return internal::EitherOfMatcher<Matcher1, Matcher2>(m1, m2);
2641}
2642
2643template <typename Matcher1, typename Matcher2, typename Matcher3>
2644inline internal::EitherOfMatcher<Matcher1,
2645 internal::EitherOfMatcher<Matcher2, Matcher3> >
2646AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3) {
2647 return AnyOf(m1, AnyOf(m2, m3));
2648}
2649
2650template <typename Matcher1, typename Matcher2, typename Matcher3,
2651 typename Matcher4>
2652inline internal::EitherOfMatcher<Matcher1,
2653 internal::EitherOfMatcher<Matcher2,
2654 internal::EitherOfMatcher<Matcher3, Matcher4> > >
2655AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4) {
2656 return AnyOf(m1, AnyOf(m2, m3, m4));
2657}
2658
2659template <typename Matcher1, typename Matcher2, typename Matcher3,
2660 typename Matcher4, typename Matcher5>
2661inline internal::EitherOfMatcher<Matcher1,
2662 internal::EitherOfMatcher<Matcher2,
2663 internal::EitherOfMatcher<Matcher3,
2664 internal::EitherOfMatcher<Matcher4, Matcher5> > > >
2665AnyOf(Matcher1 m1, Matcher2 m2, Matcher3 m3, Matcher4 m4, Matcher5 m5) {
2666 return AnyOf(m1, AnyOf(m2, m3, m4, m5));
2667}
2668
2669// Returns a matcher that matches anything that satisfies the given
2670// predicate. The predicate can be any unary function or functor
2671// whose return type can be implicitly converted to bool.
2672template <typename Predicate>
2673inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
2674Truly(Predicate pred) {
2675 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
2676}
2677
zhanyong.wan6a896b52009-01-16 01:13:50 +00002678// Returns a matcher that matches an equal container.
2679// This matcher behaves like Eq(), but in the event of mismatch lists the
2680// values that are included in one container but not the other. (Duplicate
2681// values and order differences are not explained.)
2682template <typename Container>
zhanyong.wanb8243162009-06-04 05:48:20 +00002683inline PolymorphicMatcher<internal::ContainerEqMatcher<
2684 GMOCK_REMOVE_CONST_(Container)> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00002685 ContainerEq(const Container& rhs) {
zhanyong.wanb8243162009-06-04 05:48:20 +00002686 // This following line is for working around a bug in MSVC 8.0,
2687 // which causes Container to be a const type sometimes.
2688 typedef GMOCK_REMOVE_CONST_(Container) RawContainer;
2689 return MakePolymorphicMatcher(internal::ContainerEqMatcher<RawContainer>(rhs));
2690}
2691
2692// Matches an STL-style container or a native array that contains at
2693// least one element matching the given value or matcher.
2694//
2695// Examples:
2696// ::std::set<int> page_ids;
2697// page_ids.insert(3);
2698// page_ids.insert(1);
2699// EXPECT_THAT(page_ids, Contains(1));
2700// EXPECT_THAT(page_ids, Contains(Gt(2)));
2701// EXPECT_THAT(page_ids, Not(Contains(4)));
2702//
2703// ::std::map<int, size_t> page_lengths;
2704// page_lengths[1] = 100;
zhanyong.wan40198192009-07-01 05:03:39 +00002705// EXPECT_THAT(page_lengths,
2706// Contains(::std::pair<const int, size_t>(1, 100)));
zhanyong.wanb8243162009-06-04 05:48:20 +00002707//
2708// const char* user_ids[] = { "joe", "mike", "tom" };
2709// EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
2710template <typename M>
2711inline internal::ContainsMatcher<M> Contains(M matcher) {
2712 return internal::ContainsMatcher<M>(matcher);
zhanyong.wan6a896b52009-01-16 01:13:50 +00002713}
2714
zhanyong.wanb5937da2009-07-16 20:26:41 +00002715// Key(inner_matcher) matches an std::pair whose 'first' field matches
2716// inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2717// std::map that contains at least one element whose key is >= 5.
2718template <typename M>
2719inline internal::KeyMatcher<M> Key(M inner_matcher) {
2720 return internal::KeyMatcher<M>(inner_matcher);
2721}
2722
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00002723// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
2724// matches first_matcher and whose 'second' field matches second_matcher. For
2725// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
2726// to match a std::map<int, string> that contains exactly one element whose key
2727// is >= 5 and whose value equals "foo".
2728template <typename FirstMatcher, typename SecondMatcher>
2729inline internal::PairMatcher<FirstMatcher, SecondMatcher>
2730Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
2731 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
2732 first_matcher, second_matcher);
2733}
2734
shiqiane35fdd92008-12-10 05:08:54 +00002735// Returns a predicate that is satisfied by anything that matches the
2736// given matcher.
2737template <typename M>
2738inline internal::MatcherAsPredicate<M> Matches(M matcher) {
2739 return internal::MatcherAsPredicate<M>(matcher);
2740}
2741
zhanyong.wanb8243162009-06-04 05:48:20 +00002742// Returns true iff the value matches the matcher.
2743template <typename T, typename M>
2744inline bool Value(const T& value, M matcher) {
2745 return testing::Matches(matcher)(value);
2746}
2747
zhanyong.wanbf550852009-06-09 06:09:53 +00002748// AllArgs(m) is a synonym of m. This is useful in
2749//
2750// EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
2751//
2752// which is easier to read than
2753//
2754// EXPECT_CALL(foo, Bar(_, _)).With(Eq());
2755template <typename InnerMatcher>
2756inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
2757
shiqiane35fdd92008-12-10 05:08:54 +00002758// These macros allow using matchers to check values in Google Test
2759// tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
2760// succeed iff the value matches the matcher. If the assertion fails,
2761// the value and the description of the matcher will be printed.
2762#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
2763 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2764#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
2765 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
2766
2767} // namespace testing
2768
2769#endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_