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