[InstCombine] Signed saturation patterns
[llvm-complete.git] / utils / unittest / googlemock / include / gmock / gmock-matchers.h
blobec8c237e25406ae7e1493e81989f6df3591876d8
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.
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.
30 // Author: wan@google.com (Zhanyong Wan)
32 // Google Mock - a framework for writing C++ mock classes.
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.
38 // IWYU pragma: private, include "gmock/gmock.h"
40 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
41 #define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
43 #include <math.h>
44 #include <algorithm>
45 #include <iterator>
46 #include <limits>
47 #include <ostream> // NOLINT
48 #include <sstream>
49 #include <string>
50 #include <utility>
51 #include <vector>
53 #include "gmock/internal/gmock-internal-utils.h"
54 #include "gmock/internal/gmock-port.h"
55 #include "gtest/gtest.h"
57 #if GTEST_HAS_STD_INITIALIZER_LIST_
58 # include <initializer_list> // NOLINT -- must be after gtest.h
59 #endif
61 namespace testing {
63 // To implement a matcher Foo for type T, define:
64 // 1. a class FooMatcherImpl that implements the
65 // MatcherInterface<T> interface, and
66 // 2. a factory function that creates a Matcher<T> object from a
67 // FooMatcherImpl*.
69 // The two-level delegation design makes it possible to allow a user
70 // to write "v" instead of "Eq(v)" where a Matcher is expected, which
71 // is impossible if we pass matchers by pointers. It also eases
72 // ownership management as Matcher objects can now be copied like
73 // plain values.
75 // MatchResultListener is an abstract class. Its << operator can be
76 // used by a matcher to explain why a value matches or doesn't match.
78 // TODO(wan@google.com): add method
79 // bool InterestedInWhy(bool result) const;
80 // to indicate whether the listener is interested in why the match
81 // result is 'result'.
82 class MatchResultListener {
83 public:
84 // Creates a listener object with the given underlying ostream. The
85 // listener does not own the ostream, and does not dereference it
86 // in the constructor or destructor.
87 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
88 virtual ~MatchResultListener() = 0; // Makes this class abstract.
90 // Streams x to the underlying ostream; does nothing if the ostream
91 // is NULL.
92 template <typename T>
93 MatchResultListener& operator<<(const T& x) {
94 if (stream_ != NULL)
95 *stream_ << x;
96 return *this;
99 // Returns the underlying ostream.
100 ::std::ostream* stream() { return stream_; }
102 // Returns true iff the listener is interested in an explanation of
103 // the match result. A matcher's MatchAndExplain() method can use
104 // this information to avoid generating the explanation when no one
105 // intends to hear it.
106 bool IsInterested() const { return stream_ != NULL; }
108 private:
109 ::std::ostream* const stream_;
111 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
114 inline MatchResultListener::~MatchResultListener() {
117 // An instance of a subclass of this knows how to describe itself as a
118 // matcher.
119 class MatcherDescriberInterface {
120 public:
121 virtual ~MatcherDescriberInterface() {}
123 // Describes this matcher to an ostream. The function should print
124 // a verb phrase that describes the property a value matching this
125 // matcher should have. The subject of the verb phrase is the value
126 // being matched. For example, the DescribeTo() method of the Gt(7)
127 // matcher prints "is greater than 7".
128 virtual void DescribeTo(::std::ostream* os) const = 0;
130 // Describes the negation of this matcher to an ostream. For
131 // example, if the description of this matcher is "is greater than
132 // 7", the negated description could be "is not greater than 7".
133 // You are not required to override this when implementing
134 // MatcherInterface, but it is highly advised so that your matcher
135 // can produce good error messages.
136 virtual void DescribeNegationTo(::std::ostream* os) const {
137 *os << "not (";
138 DescribeTo(os);
139 *os << ")";
143 // The implementation of a matcher.
144 template <typename T>
145 class MatcherInterface : public MatcherDescriberInterface {
146 public:
147 // Returns true iff the matcher matches x; also explains the match
148 // result to 'listener' if necessary (see the next paragraph), in
149 // the form of a non-restrictive relative clause ("which ...",
150 // "whose ...", etc) that describes x. For example, the
151 // MatchAndExplain() method of the Pointee(...) matcher should
152 // generate an explanation like "which points to ...".
154 // Implementations of MatchAndExplain() should add an explanation of
155 // the match result *if and only if* they can provide additional
156 // information that's not already present (or not obvious) in the
157 // print-out of x and the matcher's description. Whether the match
158 // succeeds is not a factor in deciding whether an explanation is
159 // needed, as sometimes the caller needs to print a failure message
160 // when the match succeeds (e.g. when the matcher is used inside
161 // Not()).
163 // For example, a "has at least 10 elements" matcher should explain
164 // what the actual element count is, regardless of the match result,
165 // as it is useful information to the reader; on the other hand, an
166 // "is empty" matcher probably only needs to explain what the actual
167 // size is when the match fails, as it's redundant to say that the
168 // size is 0 when the value is already known to be empty.
170 // You should override this method when defining a new matcher.
172 // It's the responsibility of the caller (Google Mock) to guarantee
173 // that 'listener' is not NULL. This helps to simplify a matcher's
174 // implementation when it doesn't care about the performance, as it
175 // can talk to 'listener' without checking its validity first.
176 // However, in order to implement dummy listeners efficiently,
177 // listener->stream() may be NULL.
178 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
180 // Inherits these methods from MatcherDescriberInterface:
181 // virtual void DescribeTo(::std::ostream* os) const = 0;
182 // virtual void DescribeNegationTo(::std::ostream* os) const;
185 // A match result listener that stores the explanation in a string.
186 class StringMatchResultListener : public MatchResultListener {
187 public:
188 StringMatchResultListener() : MatchResultListener(&ss_) {}
190 // Returns the explanation accumulated so far.
191 internal::string str() const { return ss_.str(); }
193 // Clears the explanation accumulated so far.
194 void Clear() { ss_.str(""); }
196 private:
197 ::std::stringstream ss_;
199 GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
202 namespace internal {
204 struct AnyEq {
205 template <typename A, typename B>
206 bool operator()(const A& a, const B& b) const { return a == b; }
208 struct AnyNe {
209 template <typename A, typename B>
210 bool operator()(const A& a, const B& b) const { return a != b; }
212 struct AnyLt {
213 template <typename A, typename B>
214 bool operator()(const A& a, const B& b) const { return a < b; }
216 struct AnyGt {
217 template <typename A, typename B>
218 bool operator()(const A& a, const B& b) const { return a > b; }
220 struct AnyLe {
221 template <typename A, typename B>
222 bool operator()(const A& a, const B& b) const { return a <= b; }
224 struct AnyGe {
225 template <typename A, typename B>
226 bool operator()(const A& a, const B& b) const { return a >= b; }
229 // A match result listener that ignores the explanation.
230 class DummyMatchResultListener : public MatchResultListener {
231 public:
232 DummyMatchResultListener() : MatchResultListener(NULL) {}
234 private:
235 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
238 // A match result listener that forwards the explanation to a given
239 // ostream. The difference between this and MatchResultListener is
240 // that the former is concrete.
241 class StreamMatchResultListener : public MatchResultListener {
242 public:
243 explicit StreamMatchResultListener(::std::ostream* os)
244 : MatchResultListener(os) {}
246 private:
247 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
250 // An internal class for implementing Matcher<T>, which will derive
251 // from it. We put functionalities common to all Matcher<T>
252 // specializations here to avoid code duplication.
253 template <typename T>
254 class MatcherBase {
255 public:
256 // Returns true iff the matcher matches x; also explains the match
257 // result to 'listener'.
258 bool MatchAndExplain(T x, MatchResultListener* listener) const {
259 return impl_->MatchAndExplain(x, listener);
262 // Returns true iff this matcher matches x.
263 bool Matches(T x) const {
264 DummyMatchResultListener dummy;
265 return MatchAndExplain(x, &dummy);
268 // Describes this matcher to an ostream.
269 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
271 // Describes the negation of this matcher to an ostream.
272 void DescribeNegationTo(::std::ostream* os) const {
273 impl_->DescribeNegationTo(os);
276 // Explains why x matches, or doesn't match, the matcher.
277 void ExplainMatchResultTo(T x, ::std::ostream* os) const {
278 StreamMatchResultListener listener(os);
279 MatchAndExplain(x, &listener);
282 // Returns the describer for this matcher object; retains ownership
283 // of the describer, which is only guaranteed to be alive when
284 // this matcher object is alive.
285 const MatcherDescriberInterface* GetDescriber() const {
286 return impl_.get();
289 protected:
290 MatcherBase() {}
292 // Constructs a matcher from its implementation.
293 explicit MatcherBase(const MatcherInterface<T>* impl)
294 : impl_(impl) {}
296 virtual ~MatcherBase() {}
298 private:
299 // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
300 // interfaces. The former dynamically allocates a chunk of memory
301 // to hold the reference count, while the latter tracks all
302 // references using a circular linked list without allocating
303 // memory. It has been observed that linked_ptr performs better in
304 // typical scenarios. However, shared_ptr can out-perform
305 // linked_ptr when there are many more uses of the copy constructor
306 // than the default constructor.
308 // If performance becomes a problem, we should see if using
309 // shared_ptr helps.
310 ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
313 } // namespace internal
315 // A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
316 // object that can check whether a value of type T matches. The
317 // implementation of Matcher<T> is just a linked_ptr to const
318 // MatcherInterface<T>, so copying is fairly cheap. Don't inherit
319 // from Matcher!
320 template <typename T>
321 class Matcher : public internal::MatcherBase<T> {
322 public:
323 // Constructs a null matcher. Needed for storing Matcher objects in STL
324 // containers. A default-constructed matcher is not yet initialized. You
325 // cannot use it until a valid value has been assigned to it.
326 explicit Matcher() {} // NOLINT
328 // Constructs a matcher from its implementation.
329 explicit Matcher(const MatcherInterface<T>* impl)
330 : internal::MatcherBase<T>(impl) {}
332 // Implicit constructor here allows people to write
333 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
334 Matcher(T value); // NOLINT
337 // The following two specializations allow the user to write str
338 // instead of Eq(str) and "foo" instead of Eq("foo") when a string
339 // matcher is expected.
340 template <>
341 class GTEST_API_ Matcher<const internal::string&>
342 : public internal::MatcherBase<const internal::string&> {
343 public:
344 Matcher() {}
346 explicit Matcher(const MatcherInterface<const internal::string&>* impl)
347 : internal::MatcherBase<const internal::string&>(impl) {}
349 // Allows the user to write str instead of Eq(str) sometimes, where
350 // str is a string object.
351 Matcher(const internal::string& s); // NOLINT
353 // Allows the user to write "foo" instead of Eq("foo") sometimes.
354 Matcher(const char* s); // NOLINT
357 template <>
358 class GTEST_API_ Matcher<internal::string>
359 : public internal::MatcherBase<internal::string> {
360 public:
361 Matcher() {}
363 explicit Matcher(const MatcherInterface<internal::string>* impl)
364 : internal::MatcherBase<internal::string>(impl) {}
366 // Allows the user to write str instead of Eq(str) sometimes, where
367 // str is a string object.
368 Matcher(const internal::string& s); // NOLINT
370 // Allows the user to write "foo" instead of Eq("foo") sometimes.
371 Matcher(const char* s); // NOLINT
374 #if GTEST_HAS_STRING_PIECE_
375 // The following two specializations allow the user to write str
376 // instead of Eq(str) and "foo" instead of Eq("foo") when a StringPiece
377 // matcher is expected.
378 template <>
379 class GTEST_API_ Matcher<const StringPiece&>
380 : public internal::MatcherBase<const StringPiece&> {
381 public:
382 Matcher() {}
384 explicit Matcher(const MatcherInterface<const StringPiece&>* impl)
385 : internal::MatcherBase<const StringPiece&>(impl) {}
387 // Allows the user to write str instead of Eq(str) sometimes, where
388 // str is a string object.
389 Matcher(const internal::string& s); // NOLINT
391 // Allows the user to write "foo" instead of Eq("foo") sometimes.
392 Matcher(const char* s); // NOLINT
394 // Allows the user to pass StringPieces directly.
395 Matcher(StringPiece s); // NOLINT
398 template <>
399 class GTEST_API_ Matcher<StringPiece>
400 : public internal::MatcherBase<StringPiece> {
401 public:
402 Matcher() {}
404 explicit Matcher(const MatcherInterface<StringPiece>* impl)
405 : internal::MatcherBase<StringPiece>(impl) {}
407 // Allows the user to write str instead of Eq(str) sometimes, where
408 // str is a string object.
409 Matcher(const internal::string& s); // NOLINT
411 // Allows the user to write "foo" instead of Eq("foo") sometimes.
412 Matcher(const char* s); // NOLINT
414 // Allows the user to pass StringPieces directly.
415 Matcher(StringPiece s); // NOLINT
417 #endif // GTEST_HAS_STRING_PIECE_
419 // The PolymorphicMatcher class template makes it easy to implement a
420 // polymorphic matcher (i.e. a matcher that can match values of more
421 // than one type, e.g. Eq(n) and NotNull()).
423 // To define a polymorphic matcher, a user should provide an Impl
424 // class that has a DescribeTo() method and a DescribeNegationTo()
425 // method, and define a member function (or member function template)
427 // bool MatchAndExplain(const Value& value,
428 // MatchResultListener* listener) const;
430 // See the definition of NotNull() for a complete example.
431 template <class Impl>
432 class PolymorphicMatcher {
433 public:
434 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
436 // Returns a mutable reference to the underlying matcher
437 // implementation object.
438 Impl& mutable_impl() { return impl_; }
440 // Returns an immutable reference to the underlying matcher
441 // implementation object.
442 const Impl& impl() const { return impl_; }
444 template <typename T>
445 operator Matcher<T>() const {
446 return Matcher<T>(new MonomorphicImpl<T>(impl_));
449 private:
450 template <typename T>
451 class MonomorphicImpl : public MatcherInterface<T> {
452 public:
453 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
455 virtual void DescribeTo(::std::ostream* os) const {
456 impl_.DescribeTo(os);
459 virtual void DescribeNegationTo(::std::ostream* os) const {
460 impl_.DescribeNegationTo(os);
463 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
464 return impl_.MatchAndExplain(x, listener);
467 private:
468 const Impl impl_;
470 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
473 Impl impl_;
475 GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
478 // Creates a matcher from its implementation. This is easier to use
479 // than the Matcher<T> constructor as it doesn't require you to
480 // explicitly write the template argument, e.g.
482 // MakeMatcher(foo);
483 // vs
484 // Matcher<const string&>(foo);
485 template <typename T>
486 inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
487 return Matcher<T>(impl);
490 // Creates a polymorphic matcher from its implementation. This is
491 // easier to use than the PolymorphicMatcher<Impl> constructor as it
492 // doesn't require you to explicitly write the template argument, e.g.
494 // MakePolymorphicMatcher(foo);
495 // vs
496 // PolymorphicMatcher<TypeOfFoo>(foo);
497 template <class Impl>
498 inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
499 return PolymorphicMatcher<Impl>(impl);
502 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
503 // and MUST NOT BE USED IN USER CODE!!!
504 namespace internal {
506 // The MatcherCastImpl class template is a helper for implementing
507 // MatcherCast(). We need this helper in order to partially
508 // specialize the implementation of MatcherCast() (C++ allows
509 // class/struct templates to be partially specialized, but not
510 // function templates.).
512 // This general version is used when MatcherCast()'s argument is a
513 // polymorphic matcher (i.e. something that can be converted to a
514 // Matcher but is not one yet; for example, Eq(value)) or a value (for
515 // example, "hello").
516 template <typename T, typename M>
517 class MatcherCastImpl {
518 public:
519 static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
520 // M can be a polymorhic matcher, in which case we want to use
521 // its conversion operator to create Matcher<T>. Or it can be a value
522 // that should be passed to the Matcher<T>'s constructor.
524 // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a
525 // polymorphic matcher because it'll be ambiguous if T has an implicit
526 // constructor from M (this usually happens when T has an implicit
527 // constructor from any type).
529 // It won't work to unconditionally implict_cast
530 // polymorphic_matcher_or_value to Matcher<T> because it won't trigger
531 // a user-defined conversion from M to T if one exists (assuming M is
532 // a value).
533 return CastImpl(
534 polymorphic_matcher_or_value,
535 BooleanConstant<
536 internal::ImplicitlyConvertible<M, Matcher<T> >::value>());
539 private:
540 static Matcher<T> CastImpl(const M& value, BooleanConstant<false>) {
541 // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic
542 // matcher. It must be a value then. Use direct initialization to create
543 // a matcher.
544 return Matcher<T>(ImplicitCast_<T>(value));
547 static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,
548 BooleanConstant<true>) {
549 // M is implicitly convertible to Matcher<T>, which means that either
550 // M is a polymorhpic matcher or Matcher<T> has an implicit constructor
551 // from M. In both cases using the implicit conversion will produce a
552 // matcher.
554 // Even if T has an implicit constructor from M, it won't be called because
555 // creating Matcher<T> would require a chain of two user-defined conversions
556 // (first to create T from M and then to create Matcher<T> from T).
557 return polymorphic_matcher_or_value;
561 // This more specialized version is used when MatcherCast()'s argument
562 // is already a Matcher. This only compiles when type T can be
563 // statically converted to type U.
564 template <typename T, typename U>
565 class MatcherCastImpl<T, Matcher<U> > {
566 public:
567 static Matcher<T> Cast(const Matcher<U>& source_matcher) {
568 return Matcher<T>(new Impl(source_matcher));
571 private:
572 class Impl : public MatcherInterface<T> {
573 public:
574 explicit Impl(const Matcher<U>& source_matcher)
575 : source_matcher_(source_matcher) {}
577 // We delegate the matching logic to the source matcher.
578 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
579 return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
582 virtual void DescribeTo(::std::ostream* os) const {
583 source_matcher_.DescribeTo(os);
586 virtual void DescribeNegationTo(::std::ostream* os) const {
587 source_matcher_.DescribeNegationTo(os);
590 private:
591 const Matcher<U> source_matcher_;
593 GTEST_DISALLOW_ASSIGN_(Impl);
597 // This even more specialized version is used for efficiently casting
598 // a matcher to its own type.
599 template <typename T>
600 class MatcherCastImpl<T, Matcher<T> > {
601 public:
602 static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
605 } // namespace internal
607 // In order to be safe and clear, casting between different matcher
608 // types is done explicitly via MatcherCast<T>(m), which takes a
609 // matcher m and returns a Matcher<T>. It compiles only when T can be
610 // statically converted to the argument type of m.
611 template <typename T, typename M>
612 inline Matcher<T> MatcherCast(const M& matcher) {
613 return internal::MatcherCastImpl<T, M>::Cast(matcher);
616 // Implements SafeMatcherCast().
618 // We use an intermediate class to do the actual safe casting as Nokia's
619 // Symbian compiler cannot decide between
620 // template <T, M> ... (M) and
621 // template <T, U> ... (const Matcher<U>&)
622 // for function templates but can for member function templates.
623 template <typename T>
624 class SafeMatcherCastImpl {
625 public:
626 // This overload handles polymorphic matchers and values only since
627 // monomorphic matchers are handled by the next one.
628 template <typename M>
629 static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) {
630 return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value);
633 // This overload handles monomorphic matchers.
635 // In general, if type T can be implicitly converted to type U, we can
636 // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
637 // contravariant): just keep a copy of the original Matcher<U>, convert the
638 // argument from type T to U, and then pass it to the underlying Matcher<U>.
639 // The only exception is when U is a reference and T is not, as the
640 // underlying Matcher<U> may be interested in the argument's address, which
641 // is not preserved in the conversion from T to U.
642 template <typename U>
643 static inline Matcher<T> Cast(const Matcher<U>& matcher) {
644 // Enforce that T can be implicitly converted to U.
645 GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
646 T_must_be_implicitly_convertible_to_U);
647 // Enforce that we are not converting a non-reference type T to a reference
648 // type U.
649 GTEST_COMPILE_ASSERT_(
650 internal::is_reference<T>::value || !internal::is_reference<U>::value,
651 cannot_convert_non_referentce_arg_to_reference);
652 // In case both T and U are arithmetic types, enforce that the
653 // conversion is not lossy.
654 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
655 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
656 const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
657 const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
658 GTEST_COMPILE_ASSERT_(
659 kTIsOther || kUIsOther ||
660 (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
661 conversion_of_arithmetic_types_must_be_lossless);
662 return MatcherCast<T>(matcher);
666 template <typename T, typename M>
667 inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
668 return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
671 // A<T>() returns a matcher that matches any value of type T.
672 template <typename T>
673 Matcher<T> A();
675 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
676 // and MUST NOT BE USED IN USER CODE!!!
677 namespace internal {
679 // If the explanation is not empty, prints it to the ostream.
680 inline void PrintIfNotEmpty(const internal::string& explanation,
681 ::std::ostream* os) {
682 if (explanation != "" && os != NULL) {
683 *os << ", " << explanation;
687 // Returns true if the given type name is easy to read by a human.
688 // This is used to decide whether printing the type of a value might
689 // be helpful.
690 inline bool IsReadableTypeName(const string& type_name) {
691 // We consider a type name readable if it's short or doesn't contain
692 // a template or function type.
693 return (type_name.length() <= 20 ||
694 type_name.find_first_of("<(") == string::npos);
697 // Matches the value against the given matcher, prints the value and explains
698 // the match result to the listener. Returns the match result.
699 // 'listener' must not be NULL.
700 // Value cannot be passed by const reference, because some matchers take a
701 // non-const argument.
702 template <typename Value, typename T>
703 bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
704 MatchResultListener* listener) {
705 if (!listener->IsInterested()) {
706 // If the listener is not interested, we do not need to construct the
707 // inner explanation.
708 return matcher.Matches(value);
711 StringMatchResultListener inner_listener;
712 const bool match = matcher.MatchAndExplain(value, &inner_listener);
714 UniversalPrint(value, listener->stream());
715 #if GTEST_HAS_RTTI
716 const string& type_name = GetTypeName<Value>();
717 if (IsReadableTypeName(type_name))
718 *listener->stream() << " (of type " << type_name << ")";
719 #endif
720 PrintIfNotEmpty(inner_listener.str(), listener->stream());
722 return match;
725 // An internal helper class for doing compile-time loop on a tuple's
726 // fields.
727 template <size_t N>
728 class TuplePrefix {
729 public:
730 // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
731 // iff the first N fields of matcher_tuple matches the first N
732 // fields of value_tuple, respectively.
733 template <typename MatcherTuple, typename ValueTuple>
734 static bool Matches(const MatcherTuple& matcher_tuple,
735 const ValueTuple& value_tuple) {
736 return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
737 && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
740 // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
741 // describes failures in matching the first N fields of matchers
742 // against the first N fields of values. If there is no failure,
743 // nothing will be streamed to os.
744 template <typename MatcherTuple, typename ValueTuple>
745 static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
746 const ValueTuple& values,
747 ::std::ostream* os) {
748 // First, describes failures in the first N - 1 fields.
749 TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
751 // Then describes the failure (if any) in the (N - 1)-th (0-based)
752 // field.
753 typename tuple_element<N - 1, MatcherTuple>::type matcher =
754 get<N - 1>(matchers);
755 typedef typename tuple_element<N - 1, ValueTuple>::type Value;
756 Value value = get<N - 1>(values);
757 StringMatchResultListener listener;
758 if (!matcher.MatchAndExplain(value, &listener)) {
759 // TODO(wan): include in the message the name of the parameter
760 // as used in MOCK_METHOD*() when possible.
761 *os << " Expected arg #" << N - 1 << ": ";
762 get<N - 1>(matchers).DescribeTo(os);
763 *os << "\n Actual: ";
764 // We remove the reference in type Value to prevent the
765 // universal printer from printing the address of value, which
766 // isn't interesting to the user most of the time. The
767 // matcher's MatchAndExplain() method handles the case when
768 // the address is interesting.
769 internal::UniversalPrint(value, os);
770 PrintIfNotEmpty(listener.str(), os);
771 *os << "\n";
776 // The base case.
777 template <>
778 class TuplePrefix<0> {
779 public:
780 template <typename MatcherTuple, typename ValueTuple>
781 static bool Matches(const MatcherTuple& /* matcher_tuple */,
782 const ValueTuple& /* value_tuple */) {
783 return true;
786 template <typename MatcherTuple, typename ValueTuple>
787 static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
788 const ValueTuple& /* values */,
789 ::std::ostream* /* os */) {}
792 // TupleMatches(matcher_tuple, value_tuple) returns true iff all
793 // matchers in matcher_tuple match the corresponding fields in
794 // value_tuple. It is a compiler error if matcher_tuple and
795 // value_tuple have different number of fields or incompatible field
796 // types.
797 template <typename MatcherTuple, typename ValueTuple>
798 bool TupleMatches(const MatcherTuple& matcher_tuple,
799 const ValueTuple& value_tuple) {
800 // Makes sure that matcher_tuple and value_tuple have the same
801 // number of fields.
802 GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
803 tuple_size<ValueTuple>::value,
804 matcher_and_value_have_different_numbers_of_fields);
805 return TuplePrefix<tuple_size<ValueTuple>::value>::
806 Matches(matcher_tuple, value_tuple);
809 // Describes failures in matching matchers against values. If there
810 // is no failure, nothing will be streamed to os.
811 template <typename MatcherTuple, typename ValueTuple>
812 void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
813 const ValueTuple& values,
814 ::std::ostream* os) {
815 TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
816 matchers, values, os);
819 // TransformTupleValues and its helper.
821 // TransformTupleValuesHelper hides the internal machinery that
822 // TransformTupleValues uses to implement a tuple traversal.
823 template <typename Tuple, typename Func, typename OutIter>
824 class TransformTupleValuesHelper {
825 private:
826 typedef ::testing::tuple_size<Tuple> TupleSize;
828 public:
829 // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.
830 // Returns the final value of 'out' in case the caller needs it.
831 static OutIter Run(Func f, const Tuple& t, OutIter out) {
832 return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);
835 private:
836 template <typename Tup, size_t kRemainingSize>
837 struct IterateOverTuple {
838 OutIter operator() (Func f, const Tup& t, OutIter out) const {
839 *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t));
840 return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);
843 template <typename Tup>
844 struct IterateOverTuple<Tup, 0> {
845 OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const {
846 return out;
851 // Successively invokes 'f(element)' on each element of the tuple 't',
852 // appending each result to the 'out' iterator. Returns the final value
853 // of 'out'.
854 template <typename Tuple, typename Func, typename OutIter>
855 OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {
856 return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);
859 // Implements A<T>().
860 template <typename T>
861 class AnyMatcherImpl : public MatcherInterface<T> {
862 public:
863 virtual bool MatchAndExplain(
864 T /* x */, MatchResultListener* /* listener */) const { return true; }
865 virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
866 virtual void DescribeNegationTo(::std::ostream* os) const {
867 // This is mostly for completeness' safe, as it's not very useful
868 // to write Not(A<bool>()). However we cannot completely rule out
869 // such a possibility, and it doesn't hurt to be prepared.
870 *os << "never matches";
874 // Implements _, a matcher that matches any value of any
875 // type. This is a polymorphic matcher, so we need a template type
876 // conversion operator to make it appearing as a Matcher<T> for any
877 // type T.
878 class AnythingMatcher {
879 public:
880 template <typename T>
881 operator Matcher<T>() const { return A<T>(); }
884 // Implements a matcher that compares a given value with a
885 // pre-supplied value using one of the ==, <=, <, etc, operators. The
886 // two values being compared don't have to have the same type.
888 // The matcher defined here is polymorphic (for example, Eq(5) can be
889 // used to match an int, a short, a double, etc). Therefore we use
890 // a template type conversion operator in the implementation.
892 // The following template definition assumes that the Rhs parameter is
893 // a "bare" type (i.e. neither 'const T' nor 'T&').
894 template <typename D, typename Rhs, typename Op>
895 class ComparisonBase {
896 public:
897 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
898 template <typename Lhs>
899 operator Matcher<Lhs>() const {
900 return MakeMatcher(new Impl<Lhs>(rhs_));
903 private:
904 template <typename Lhs>
905 class Impl : public MatcherInterface<Lhs> {
906 public:
907 explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
908 virtual bool MatchAndExplain(
909 Lhs lhs, MatchResultListener* /* listener */) const {
910 return Op()(lhs, rhs_);
912 virtual void DescribeTo(::std::ostream* os) const {
913 *os << D::Desc() << " ";
914 UniversalPrint(rhs_, os);
916 virtual void DescribeNegationTo(::std::ostream* os) const {
917 *os << D::NegatedDesc() << " ";
918 UniversalPrint(rhs_, os);
920 private:
921 Rhs rhs_;
922 GTEST_DISALLOW_ASSIGN_(Impl);
924 Rhs rhs_;
925 GTEST_DISALLOW_ASSIGN_(ComparisonBase);
928 template <typename Rhs>
929 class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
930 public:
931 explicit EqMatcher(const Rhs& rhs)
932 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
933 static const char* Desc() { return "is equal to"; }
934 static const char* NegatedDesc() { return "isn't equal to"; }
936 template <typename Rhs>
937 class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
938 public:
939 explicit NeMatcher(const Rhs& rhs)
940 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
941 static const char* Desc() { return "isn't equal to"; }
942 static const char* NegatedDesc() { return "is equal to"; }
944 template <typename Rhs>
945 class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
946 public:
947 explicit LtMatcher(const Rhs& rhs)
948 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
949 static const char* Desc() { return "is <"; }
950 static const char* NegatedDesc() { return "isn't <"; }
952 template <typename Rhs>
953 class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
954 public:
955 explicit GtMatcher(const Rhs& rhs)
956 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
957 static const char* Desc() { return "is >"; }
958 static const char* NegatedDesc() { return "isn't >"; }
960 template <typename Rhs>
961 class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
962 public:
963 explicit LeMatcher(const Rhs& rhs)
964 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
965 static const char* Desc() { return "is <="; }
966 static const char* NegatedDesc() { return "isn't <="; }
968 template <typename Rhs>
969 class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
970 public:
971 explicit GeMatcher(const Rhs& rhs)
972 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
973 static const char* Desc() { return "is >="; }
974 static const char* NegatedDesc() { return "isn't >="; }
977 // Implements the polymorphic IsNull() matcher, which matches any raw or smart
978 // pointer that is NULL.
979 class IsNullMatcher {
980 public:
981 template <typename Pointer>
982 bool MatchAndExplain(const Pointer& p,
983 MatchResultListener* /* listener */) const {
984 #if GTEST_LANG_CXX11
985 return p == nullptr;
986 #else // GTEST_LANG_CXX11
987 return GetRawPointer(p) == NULL;
988 #endif // GTEST_LANG_CXX11
991 void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
992 void DescribeNegationTo(::std::ostream* os) const {
993 *os << "isn't NULL";
997 // Implements the polymorphic NotNull() matcher, which matches any raw or smart
998 // pointer that is not NULL.
999 class NotNullMatcher {
1000 public:
1001 template <typename Pointer>
1002 bool MatchAndExplain(const Pointer& p,
1003 MatchResultListener* /* listener */) const {
1004 #if GTEST_LANG_CXX11
1005 return p != nullptr;
1006 #else // GTEST_LANG_CXX11
1007 return GetRawPointer(p) != NULL;
1008 #endif // GTEST_LANG_CXX11
1011 void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
1012 void DescribeNegationTo(::std::ostream* os) const {
1013 *os << "is NULL";
1017 // Ref(variable) matches any argument that is a reference to
1018 // 'variable'. This matcher is polymorphic as it can match any
1019 // super type of the type of 'variable'.
1021 // The RefMatcher template class implements Ref(variable). It can
1022 // only be instantiated with a reference type. This prevents a user
1023 // from mistakenly using Ref(x) to match a non-reference function
1024 // argument. For example, the following will righteously cause a
1025 // compiler error:
1027 // int n;
1028 // Matcher<int> m1 = Ref(n); // This won't compile.
1029 // Matcher<int&> m2 = Ref(n); // This will compile.
1030 template <typename T>
1031 class RefMatcher;
1033 template <typename T>
1034 class RefMatcher<T&> {
1035 // Google Mock is a generic framework and thus needs to support
1036 // mocking any function types, including those that take non-const
1037 // reference arguments. Therefore the template parameter T (and
1038 // Super below) can be instantiated to either a const type or a
1039 // non-const type.
1040 public:
1041 // RefMatcher() takes a T& instead of const T&, as we want the
1042 // compiler to catch using Ref(const_value) as a matcher for a
1043 // non-const reference.
1044 explicit RefMatcher(T& x) : object_(x) {} // NOLINT
1046 template <typename Super>
1047 operator Matcher<Super&>() const {
1048 // By passing object_ (type T&) to Impl(), which expects a Super&,
1049 // we make sure that Super is a super type of T. In particular,
1050 // this catches using Ref(const_value) as a matcher for a
1051 // non-const reference, as you cannot implicitly convert a const
1052 // reference to a non-const reference.
1053 return MakeMatcher(new Impl<Super>(object_));
1056 private:
1057 template <typename Super>
1058 class Impl : public MatcherInterface<Super&> {
1059 public:
1060 explicit Impl(Super& x) : object_(x) {} // NOLINT
1062 // MatchAndExplain() takes a Super& (as opposed to const Super&)
1063 // in order to match the interface MatcherInterface<Super&>.
1064 virtual bool MatchAndExplain(
1065 Super& x, MatchResultListener* listener) const {
1066 *listener << "which is located @" << static_cast<const void*>(&x);
1067 return &x == &object_;
1070 virtual void DescribeTo(::std::ostream* os) const {
1071 *os << "references the variable ";
1072 UniversalPrinter<Super&>::Print(object_, os);
1075 virtual void DescribeNegationTo(::std::ostream* os) const {
1076 *os << "does not reference the variable ";
1077 UniversalPrinter<Super&>::Print(object_, os);
1080 private:
1081 const Super& object_;
1083 GTEST_DISALLOW_ASSIGN_(Impl);
1086 T& object_;
1088 GTEST_DISALLOW_ASSIGN_(RefMatcher);
1091 // Polymorphic helper functions for narrow and wide string matchers.
1092 inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
1093 return String::CaseInsensitiveCStringEquals(lhs, rhs);
1096 inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
1097 const wchar_t* rhs) {
1098 return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
1101 // String comparison for narrow or wide strings that can have embedded NUL
1102 // characters.
1103 template <typename StringType>
1104 bool CaseInsensitiveStringEquals(const StringType& s1,
1105 const StringType& s2) {
1106 // Are the heads equal?
1107 if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
1108 return false;
1111 // Skip the equal heads.
1112 const typename StringType::value_type nul = 0;
1113 const size_t i1 = s1.find(nul), i2 = s2.find(nul);
1115 // Are we at the end of either s1 or s2?
1116 if (i1 == StringType::npos || i2 == StringType::npos) {
1117 return i1 == i2;
1120 // Are the tails equal?
1121 return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
1124 // String matchers.
1126 // Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
1127 template <typename StringType>
1128 class StrEqualityMatcher {
1129 public:
1130 StrEqualityMatcher(const StringType& str, bool expect_eq,
1131 bool case_sensitive)
1132 : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
1134 // Accepts pointer types, particularly:
1135 // const char*
1136 // char*
1137 // const wchar_t*
1138 // wchar_t*
1139 template <typename CharType>
1140 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1141 if (s == NULL) {
1142 return !expect_eq_;
1144 return MatchAndExplain(StringType(s), listener);
1147 // Matches anything that can convert to StringType.
1149 // This is a template, not just a plain function with const StringType&,
1150 // because StringPiece has some interfering non-explicit constructors.
1151 template <typename MatcheeStringType>
1152 bool MatchAndExplain(const MatcheeStringType& s,
1153 MatchResultListener* /* listener */) const {
1154 const StringType& s2(s);
1155 const bool eq = case_sensitive_ ? s2 == string_ :
1156 CaseInsensitiveStringEquals(s2, string_);
1157 return expect_eq_ == eq;
1160 void DescribeTo(::std::ostream* os) const {
1161 DescribeToHelper(expect_eq_, os);
1164 void DescribeNegationTo(::std::ostream* os) const {
1165 DescribeToHelper(!expect_eq_, os);
1168 private:
1169 void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
1170 *os << (expect_eq ? "is " : "isn't ");
1171 *os << "equal to ";
1172 if (!case_sensitive_) {
1173 *os << "(ignoring case) ";
1175 UniversalPrint(string_, os);
1178 const StringType string_;
1179 const bool expect_eq_;
1180 const bool case_sensitive_;
1182 GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
1185 // Implements the polymorphic HasSubstr(substring) matcher, which
1186 // can be used as a Matcher<T> as long as T can be converted to a
1187 // string.
1188 template <typename StringType>
1189 class HasSubstrMatcher {
1190 public:
1191 explicit HasSubstrMatcher(const StringType& substring)
1192 : substring_(substring) {}
1194 // Accepts pointer types, particularly:
1195 // const char*
1196 // char*
1197 // const wchar_t*
1198 // wchar_t*
1199 template <typename CharType>
1200 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1201 return s != NULL && MatchAndExplain(StringType(s), listener);
1204 // Matches anything that can convert to StringType.
1206 // This is a template, not just a plain function with const StringType&,
1207 // because StringPiece has some interfering non-explicit constructors.
1208 template <typename MatcheeStringType>
1209 bool MatchAndExplain(const MatcheeStringType& s,
1210 MatchResultListener* /* listener */) const {
1211 const StringType& s2(s);
1212 return s2.find(substring_) != StringType::npos;
1215 // Describes what this matcher matches.
1216 void DescribeTo(::std::ostream* os) const {
1217 *os << "has substring ";
1218 UniversalPrint(substring_, os);
1221 void DescribeNegationTo(::std::ostream* os) const {
1222 *os << "has no substring ";
1223 UniversalPrint(substring_, os);
1226 private:
1227 const StringType substring_;
1229 GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
1232 // Implements the polymorphic StartsWith(substring) matcher, which
1233 // can be used as a Matcher<T> as long as T can be converted to a
1234 // string.
1235 template <typename StringType>
1236 class StartsWithMatcher {
1237 public:
1238 explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
1241 // Accepts pointer types, particularly:
1242 // const char*
1243 // char*
1244 // const wchar_t*
1245 // wchar_t*
1246 template <typename CharType>
1247 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1248 return s != NULL && MatchAndExplain(StringType(s), listener);
1251 // Matches anything that can convert to StringType.
1253 // This is a template, not just a plain function with const StringType&,
1254 // because StringPiece has some interfering non-explicit constructors.
1255 template <typename MatcheeStringType>
1256 bool MatchAndExplain(const MatcheeStringType& s,
1257 MatchResultListener* /* listener */) const {
1258 const StringType& s2(s);
1259 return s2.length() >= prefix_.length() &&
1260 s2.substr(0, prefix_.length()) == prefix_;
1263 void DescribeTo(::std::ostream* os) const {
1264 *os << "starts with ";
1265 UniversalPrint(prefix_, os);
1268 void DescribeNegationTo(::std::ostream* os) const {
1269 *os << "doesn't start with ";
1270 UniversalPrint(prefix_, os);
1273 private:
1274 const StringType prefix_;
1276 GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
1279 // Implements the polymorphic EndsWith(substring) matcher, which
1280 // can be used as a Matcher<T> as long as T can be converted to a
1281 // string.
1282 template <typename StringType>
1283 class EndsWithMatcher {
1284 public:
1285 explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
1287 // Accepts pointer types, particularly:
1288 // const char*
1289 // char*
1290 // const wchar_t*
1291 // wchar_t*
1292 template <typename CharType>
1293 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1294 return s != NULL && MatchAndExplain(StringType(s), listener);
1297 // Matches anything that can convert to StringType.
1299 // This is a template, not just a plain function with const StringType&,
1300 // because StringPiece has some interfering non-explicit constructors.
1301 template <typename MatcheeStringType>
1302 bool MatchAndExplain(const MatcheeStringType& s,
1303 MatchResultListener* /* listener */) const {
1304 const StringType& s2(s);
1305 return s2.length() >= suffix_.length() &&
1306 s2.substr(s2.length() - suffix_.length()) == suffix_;
1309 void DescribeTo(::std::ostream* os) const {
1310 *os << "ends with ";
1311 UniversalPrint(suffix_, os);
1314 void DescribeNegationTo(::std::ostream* os) const {
1315 *os << "doesn't end with ";
1316 UniversalPrint(suffix_, os);
1319 private:
1320 const StringType suffix_;
1322 GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
1325 // Implements polymorphic matchers MatchesRegex(regex) and
1326 // ContainsRegex(regex), which can be used as a Matcher<T> as long as
1327 // T can be converted to a string.
1328 class MatchesRegexMatcher {
1329 public:
1330 MatchesRegexMatcher(const RE* regex, bool full_match)
1331 : regex_(regex), full_match_(full_match) {}
1333 // Accepts pointer types, particularly:
1334 // const char*
1335 // char*
1336 // const wchar_t*
1337 // wchar_t*
1338 template <typename CharType>
1339 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
1340 return s != NULL && MatchAndExplain(internal::string(s), listener);
1343 // Matches anything that can convert to internal::string.
1345 // This is a template, not just a plain function with const internal::string&,
1346 // because StringPiece has some interfering non-explicit constructors.
1347 template <class MatcheeStringType>
1348 bool MatchAndExplain(const MatcheeStringType& s,
1349 MatchResultListener* /* listener */) const {
1350 const internal::string& s2(s);
1351 return full_match_ ? RE::FullMatch(s2, *regex_) :
1352 RE::PartialMatch(s2, *regex_);
1355 void DescribeTo(::std::ostream* os) const {
1356 *os << (full_match_ ? "matches" : "contains")
1357 << " regular expression ";
1358 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1361 void DescribeNegationTo(::std::ostream* os) const {
1362 *os << "doesn't " << (full_match_ ? "match" : "contain")
1363 << " regular expression ";
1364 UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
1367 private:
1368 const internal::linked_ptr<const RE> regex_;
1369 const bool full_match_;
1371 GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
1374 // Implements a matcher that compares the two fields of a 2-tuple
1375 // using one of the ==, <=, <, etc, operators. The two fields being
1376 // compared don't have to have the same type.
1378 // The matcher defined here is polymorphic (for example, Eq() can be
1379 // used to match a tuple<int, short>, a tuple<const long&, double>,
1380 // etc). Therefore we use a template type conversion operator in the
1381 // implementation.
1382 template <typename D, typename Op>
1383 class PairMatchBase {
1384 public:
1385 template <typename T1, typename T2>
1386 operator Matcher< ::testing::tuple<T1, T2> >() const {
1387 return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >);
1389 template <typename T1, typename T2>
1390 operator Matcher<const ::testing::tuple<T1, T2>&>() const {
1391 return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>);
1394 private:
1395 static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT
1396 return os << D::Desc();
1399 template <typename Tuple>
1400 class Impl : public MatcherInterface<Tuple> {
1401 public:
1402 virtual bool MatchAndExplain(
1403 Tuple args,
1404 MatchResultListener* /* listener */) const {
1405 return Op()(::testing::get<0>(args), ::testing::get<1>(args));
1407 virtual void DescribeTo(::std::ostream* os) const {
1408 *os << "are " << GetDesc;
1410 virtual void DescribeNegationTo(::std::ostream* os) const {
1411 *os << "aren't " << GetDesc;
1416 class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {
1417 public:
1418 static const char* Desc() { return "an equal pair"; }
1420 class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {
1421 public:
1422 static const char* Desc() { return "an unequal pair"; }
1424 class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {
1425 public:
1426 static const char* Desc() { return "a pair where the first < the second"; }
1428 class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {
1429 public:
1430 static const char* Desc() { return "a pair where the first > the second"; }
1432 class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {
1433 public:
1434 static const char* Desc() { return "a pair where the first <= the second"; }
1436 class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {
1437 public:
1438 static const char* Desc() { return "a pair where the first >= the second"; }
1441 // Implements the Not(...) matcher for a particular argument type T.
1442 // We do not nest it inside the NotMatcher class template, as that
1443 // will prevent different instantiations of NotMatcher from sharing
1444 // the same NotMatcherImpl<T> class.
1445 template <typename T>
1446 class NotMatcherImpl : public MatcherInterface<T> {
1447 public:
1448 explicit NotMatcherImpl(const Matcher<T>& matcher)
1449 : matcher_(matcher) {}
1451 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1452 return !matcher_.MatchAndExplain(x, listener);
1455 virtual void DescribeTo(::std::ostream* os) const {
1456 matcher_.DescribeNegationTo(os);
1459 virtual void DescribeNegationTo(::std::ostream* os) const {
1460 matcher_.DescribeTo(os);
1463 private:
1464 const Matcher<T> matcher_;
1466 GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
1469 // Implements the Not(m) matcher, which matches a value that doesn't
1470 // match matcher m.
1471 template <typename InnerMatcher>
1472 class NotMatcher {
1473 public:
1474 explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
1476 // This template type conversion operator allows Not(m) to be used
1477 // to match any type m can match.
1478 template <typename T>
1479 operator Matcher<T>() const {
1480 return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
1483 private:
1484 InnerMatcher matcher_;
1486 GTEST_DISALLOW_ASSIGN_(NotMatcher);
1489 // Implements the AllOf(m1, m2) matcher for a particular argument type
1490 // T. We do not nest it inside the BothOfMatcher class template, as
1491 // that will prevent different instantiations of BothOfMatcher from
1492 // sharing the same BothOfMatcherImpl<T> class.
1493 template <typename T>
1494 class BothOfMatcherImpl : public MatcherInterface<T> {
1495 public:
1496 BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1497 : matcher1_(matcher1), matcher2_(matcher2) {}
1499 virtual void DescribeTo(::std::ostream* os) const {
1500 *os << "(";
1501 matcher1_.DescribeTo(os);
1502 *os << ") and (";
1503 matcher2_.DescribeTo(os);
1504 *os << ")";
1507 virtual void DescribeNegationTo(::std::ostream* os) const {
1508 *os << "(";
1509 matcher1_.DescribeNegationTo(os);
1510 *os << ") or (";
1511 matcher2_.DescribeNegationTo(os);
1512 *os << ")";
1515 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1516 // If either matcher1_ or matcher2_ doesn't match x, we only need
1517 // to explain why one of them fails.
1518 StringMatchResultListener listener1;
1519 if (!matcher1_.MatchAndExplain(x, &listener1)) {
1520 *listener << listener1.str();
1521 return false;
1524 StringMatchResultListener listener2;
1525 if (!matcher2_.MatchAndExplain(x, &listener2)) {
1526 *listener << listener2.str();
1527 return false;
1530 // Otherwise we need to explain why *both* of them match.
1531 const internal::string s1 = listener1.str();
1532 const internal::string s2 = listener2.str();
1534 if (s1 == "") {
1535 *listener << s2;
1536 } else {
1537 *listener << s1;
1538 if (s2 != "") {
1539 *listener << ", and " << s2;
1542 return true;
1545 private:
1546 const Matcher<T> matcher1_;
1547 const Matcher<T> matcher2_;
1549 GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
1552 #if GTEST_LANG_CXX11
1553 // MatcherList provides mechanisms for storing a variable number of matchers in
1554 // a list structure (ListType) and creating a combining matcher from such a
1555 // list.
1556 // The template is defined recursively using the following template paramters:
1557 // * kSize is the length of the MatcherList.
1558 // * Head is the type of the first matcher of the list.
1559 // * Tail denotes the types of the remaining matchers of the list.
1560 template <int kSize, typename Head, typename... Tail>
1561 struct MatcherList {
1562 typedef MatcherList<kSize - 1, Tail...> MatcherListTail;
1563 typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType;
1565 // BuildList stores variadic type values in a nested pair structure.
1566 // Example:
1567 // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return
1568 // the corresponding result of type pair<int, pair<string, float>>.
1569 static ListType BuildList(const Head& matcher, const Tail&... tail) {
1570 return ListType(matcher, MatcherListTail::BuildList(tail...));
1573 // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built
1574 // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the
1575 // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a
1576 // constructor taking two Matcher<T>s as input.
1577 template <typename T, template <typename /* T */> class CombiningMatcher>
1578 static Matcher<T> CreateMatcher(const ListType& matchers) {
1579 return Matcher<T>(new CombiningMatcher<T>(
1580 SafeMatcherCast<T>(matchers.first),
1581 MatcherListTail::template CreateMatcher<T, CombiningMatcher>(
1582 matchers.second)));
1586 // The following defines the base case for the recursive definition of
1587 // MatcherList.
1588 template <typename Matcher1, typename Matcher2>
1589 struct MatcherList<2, Matcher1, Matcher2> {
1590 typedef ::std::pair<Matcher1, Matcher2> ListType;
1592 static ListType BuildList(const Matcher1& matcher1,
1593 const Matcher2& matcher2) {
1594 return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2);
1597 template <typename T, template <typename /* T */> class CombiningMatcher>
1598 static Matcher<T> CreateMatcher(const ListType& matchers) {
1599 return Matcher<T>(new CombiningMatcher<T>(
1600 SafeMatcherCast<T>(matchers.first),
1601 SafeMatcherCast<T>(matchers.second)));
1605 // VariadicMatcher is used for the variadic implementation of
1606 // AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).
1607 // CombiningMatcher<T> is used to recursively combine the provided matchers
1608 // (of type Args...).
1609 template <template <typename T> class CombiningMatcher, typename... Args>
1610 class VariadicMatcher {
1611 public:
1612 VariadicMatcher(const Args&... matchers) // NOLINT
1613 : matchers_(MatcherListType::BuildList(matchers...)) {}
1615 // This template type conversion operator allows an
1616 // VariadicMatcher<Matcher1, Matcher2...> object to match any type that
1617 // all of the provided matchers (Matcher1, Matcher2, ...) can match.
1618 template <typename T>
1619 operator Matcher<T>() const {
1620 return MatcherListType::template CreateMatcher<T, CombiningMatcher>(
1621 matchers_);
1624 private:
1625 typedef MatcherList<sizeof...(Args), Args...> MatcherListType;
1627 const typename MatcherListType::ListType matchers_;
1629 GTEST_DISALLOW_ASSIGN_(VariadicMatcher);
1632 template <typename... Args>
1633 using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>;
1635 #endif // GTEST_LANG_CXX11
1637 // Used for implementing the AllOf(m_1, ..., m_n) matcher, which
1638 // matches a value that matches all of the matchers m_1, ..., and m_n.
1639 template <typename Matcher1, typename Matcher2>
1640 class BothOfMatcher {
1641 public:
1642 BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1643 : matcher1_(matcher1), matcher2_(matcher2) {}
1645 // This template type conversion operator allows a
1646 // BothOfMatcher<Matcher1, Matcher2> object to match any type that
1647 // both Matcher1 and Matcher2 can match.
1648 template <typename T>
1649 operator Matcher<T>() const {
1650 return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
1651 SafeMatcherCast<T>(matcher2_)));
1654 private:
1655 Matcher1 matcher1_;
1656 Matcher2 matcher2_;
1658 GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
1661 // Implements the AnyOf(m1, m2) matcher for a particular argument type
1662 // T. We do not nest it inside the AnyOfMatcher class template, as
1663 // that will prevent different instantiations of AnyOfMatcher from
1664 // sharing the same EitherOfMatcherImpl<T> class.
1665 template <typename T>
1666 class EitherOfMatcherImpl : public MatcherInterface<T> {
1667 public:
1668 EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
1669 : matcher1_(matcher1), matcher2_(matcher2) {}
1671 virtual void DescribeTo(::std::ostream* os) const {
1672 *os << "(";
1673 matcher1_.DescribeTo(os);
1674 *os << ") or (";
1675 matcher2_.DescribeTo(os);
1676 *os << ")";
1679 virtual void DescribeNegationTo(::std::ostream* os) const {
1680 *os << "(";
1681 matcher1_.DescribeNegationTo(os);
1682 *os << ") and (";
1683 matcher2_.DescribeNegationTo(os);
1684 *os << ")";
1687 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
1688 // If either matcher1_ or matcher2_ matches x, we just need to
1689 // explain why *one* of them matches.
1690 StringMatchResultListener listener1;
1691 if (matcher1_.MatchAndExplain(x, &listener1)) {
1692 *listener << listener1.str();
1693 return true;
1696 StringMatchResultListener listener2;
1697 if (matcher2_.MatchAndExplain(x, &listener2)) {
1698 *listener << listener2.str();
1699 return true;
1702 // Otherwise we need to explain why *both* of them fail.
1703 const internal::string s1 = listener1.str();
1704 const internal::string s2 = listener2.str();
1706 if (s1 == "") {
1707 *listener << s2;
1708 } else {
1709 *listener << s1;
1710 if (s2 != "") {
1711 *listener << ", and " << s2;
1714 return false;
1717 private:
1718 const Matcher<T> matcher1_;
1719 const Matcher<T> matcher2_;
1721 GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
1724 #if GTEST_LANG_CXX11
1725 // AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).
1726 template <typename... Args>
1727 using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>;
1729 #endif // GTEST_LANG_CXX11
1731 // Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
1732 // matches a value that matches at least one of the matchers m_1, ...,
1733 // and m_n.
1734 template <typename Matcher1, typename Matcher2>
1735 class EitherOfMatcher {
1736 public:
1737 EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
1738 : matcher1_(matcher1), matcher2_(matcher2) {}
1740 // This template type conversion operator allows a
1741 // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
1742 // both Matcher1 and Matcher2 can match.
1743 template <typename T>
1744 operator Matcher<T>() const {
1745 return Matcher<T>(new EitherOfMatcherImpl<T>(
1746 SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
1749 private:
1750 Matcher1 matcher1_;
1751 Matcher2 matcher2_;
1753 GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
1756 // Used for implementing Truly(pred), which turns a predicate into a
1757 // matcher.
1758 template <typename Predicate>
1759 class TrulyMatcher {
1760 public:
1761 explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
1763 // This method template allows Truly(pred) to be used as a matcher
1764 // for type T where T is the argument type of predicate 'pred'. The
1765 // argument is passed by reference as the predicate may be
1766 // interested in the address of the argument.
1767 template <typename T>
1768 bool MatchAndExplain(T& x, // NOLINT
1769 MatchResultListener* /* listener */) const {
1770 // Without the if-statement, MSVC sometimes warns about converting
1771 // a value to bool (warning 4800).
1773 // We cannot write 'return !!predicate_(x);' as that doesn't work
1774 // when predicate_(x) returns a class convertible to bool but
1775 // having no operator!().
1776 if (predicate_(x))
1777 return true;
1778 return false;
1781 void DescribeTo(::std::ostream* os) const {
1782 *os << "satisfies the given predicate";
1785 void DescribeNegationTo(::std::ostream* os) const {
1786 *os << "doesn't satisfy the given predicate";
1789 private:
1790 Predicate predicate_;
1792 GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
1795 // Used for implementing Matches(matcher), which turns a matcher into
1796 // a predicate.
1797 template <typename M>
1798 class MatcherAsPredicate {
1799 public:
1800 explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
1802 // This template operator() allows Matches(m) to be used as a
1803 // predicate on type T where m is a matcher on type T.
1805 // The argument x is passed by reference instead of by value, as
1806 // some matcher may be interested in its address (e.g. as in
1807 // Matches(Ref(n))(x)).
1808 template <typename T>
1809 bool operator()(const T& x) const {
1810 // We let matcher_ commit to a particular type here instead of
1811 // when the MatcherAsPredicate object was constructed. This
1812 // allows us to write Matches(m) where m is a polymorphic matcher
1813 // (e.g. Eq(5)).
1815 // If we write Matcher<T>(matcher_).Matches(x) here, it won't
1816 // compile when matcher_ has type Matcher<const T&>; if we write
1817 // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
1818 // when matcher_ has type Matcher<T>; if we just write
1819 // matcher_.Matches(x), it won't compile when matcher_ is
1820 // polymorphic, e.g. Eq(5).
1822 // MatcherCast<const T&>() is necessary for making the code work
1823 // in all of the above situations.
1824 return MatcherCast<const T&>(matcher_).Matches(x);
1827 private:
1828 M matcher_;
1830 GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
1833 // For implementing ASSERT_THAT() and EXPECT_THAT(). The template
1834 // argument M must be a type that can be converted to a matcher.
1835 template <typename M>
1836 class PredicateFormatterFromMatcher {
1837 public:
1838 explicit PredicateFormatterFromMatcher(M m) : matcher_(internal::move(m)) {}
1840 // This template () operator allows a PredicateFormatterFromMatcher
1841 // object to act as a predicate-formatter suitable for using with
1842 // Google Test's EXPECT_PRED_FORMAT1() macro.
1843 template <typename T>
1844 AssertionResult operator()(const char* value_text, const T& x) const {
1845 // We convert matcher_ to a Matcher<const T&> *now* instead of
1846 // when the PredicateFormatterFromMatcher object was constructed,
1847 // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
1848 // know which type to instantiate it to until we actually see the
1849 // type of x here.
1851 // We write SafeMatcherCast<const T&>(matcher_) instead of
1852 // Matcher<const T&>(matcher_), as the latter won't compile when
1853 // matcher_ has type Matcher<T> (e.g. An<int>()).
1854 // We don't write MatcherCast<const T&> either, as that allows
1855 // potentially unsafe downcasting of the matcher argument.
1856 const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);
1857 StringMatchResultListener listener;
1858 if (MatchPrintAndExplain(x, matcher, &listener))
1859 return AssertionSuccess();
1861 ::std::stringstream ss;
1862 ss << "Value of: " << value_text << "\n"
1863 << "Expected: ";
1864 matcher.DescribeTo(&ss);
1865 ss << "\n Actual: " << listener.str();
1866 return AssertionFailure() << ss.str();
1869 private:
1870 const M matcher_;
1872 GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
1875 // A helper function for converting a matcher to a predicate-formatter
1876 // without the user needing to explicitly write the type. This is
1877 // used for implementing ASSERT_THAT() and EXPECT_THAT().
1878 // Implementation detail: 'matcher' is received by-value to force decaying.
1879 template <typename M>
1880 inline PredicateFormatterFromMatcher<M>
1881 MakePredicateFormatterFromMatcher(M matcher) {
1882 return PredicateFormatterFromMatcher<M>(internal::move(matcher));
1885 // Implements the polymorphic floating point equality matcher, which matches
1886 // two float values using ULP-based approximation or, optionally, a
1887 // user-specified epsilon. The template is meant to be instantiated with
1888 // FloatType being either float or double.
1889 template <typename FloatType>
1890 class FloatingEqMatcher {
1891 public:
1892 // Constructor for FloatingEqMatcher.
1893 // The matcher's input will be compared with expected. The matcher treats two
1894 // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
1895 // equality comparisons between NANs will always return false. We specify a
1896 // negative max_abs_error_ term to indicate that ULP-based approximation will
1897 // be used for comparison.
1898 FloatingEqMatcher(FloatType expected, bool nan_eq_nan) :
1899 expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {
1902 // Constructor that supports a user-specified max_abs_error that will be used
1903 // for comparison instead of ULP-based approximation. The max absolute
1904 // should be non-negative.
1905 FloatingEqMatcher(FloatType expected, bool nan_eq_nan,
1906 FloatType max_abs_error)
1907 : expected_(expected),
1908 nan_eq_nan_(nan_eq_nan),
1909 max_abs_error_(max_abs_error) {
1910 GTEST_CHECK_(max_abs_error >= 0)
1911 << ", where max_abs_error is" << max_abs_error;
1914 // Implements floating point equality matcher as a Matcher<T>.
1915 template <typename T>
1916 class Impl : public MatcherInterface<T> {
1917 public:
1918 Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)
1919 : expected_(expected),
1920 nan_eq_nan_(nan_eq_nan),
1921 max_abs_error_(max_abs_error) {}
1923 virtual bool MatchAndExplain(T value,
1924 MatchResultListener* listener) const {
1925 const FloatingPoint<FloatType> actual(value), expected(expected_);
1927 // Compares NaNs first, if nan_eq_nan_ is true.
1928 if (actual.is_nan() || expected.is_nan()) {
1929 if (actual.is_nan() && expected.is_nan()) {
1930 return nan_eq_nan_;
1932 // One is nan; the other is not nan.
1933 return false;
1935 if (HasMaxAbsError()) {
1936 // We perform an equality check so that inf will match inf, regardless
1937 // of error bounds. If the result of value - expected_ would result in
1938 // overflow or if either value is inf, the default result is infinity,
1939 // which should only match if max_abs_error_ is also infinity.
1940 if (value == expected_) {
1941 return true;
1944 const FloatType diff = value - expected_;
1945 if (fabs(diff) <= max_abs_error_) {
1946 return true;
1949 if (listener->IsInterested()) {
1950 *listener << "which is " << diff << " from " << expected_;
1952 return false;
1953 } else {
1954 return actual.AlmostEquals(expected);
1958 virtual void DescribeTo(::std::ostream* os) const {
1959 // os->precision() returns the previously set precision, which we
1960 // store to restore the ostream to its original configuration
1961 // after outputting.
1962 const ::std::streamsize old_precision = os->precision(
1963 ::std::numeric_limits<FloatType>::digits10 + 2);
1964 if (FloatingPoint<FloatType>(expected_).is_nan()) {
1965 if (nan_eq_nan_) {
1966 *os << "is NaN";
1967 } else {
1968 *os << "never matches";
1970 } else {
1971 *os << "is approximately " << expected_;
1972 if (HasMaxAbsError()) {
1973 *os << " (absolute error <= " << max_abs_error_ << ")";
1976 os->precision(old_precision);
1979 virtual void DescribeNegationTo(::std::ostream* os) const {
1980 // As before, get original precision.
1981 const ::std::streamsize old_precision = os->precision(
1982 ::std::numeric_limits<FloatType>::digits10 + 2);
1983 if (FloatingPoint<FloatType>(expected_).is_nan()) {
1984 if (nan_eq_nan_) {
1985 *os << "isn't NaN";
1986 } else {
1987 *os << "is anything";
1989 } else {
1990 *os << "isn't approximately " << expected_;
1991 if (HasMaxAbsError()) {
1992 *os << " (absolute error > " << max_abs_error_ << ")";
1995 // Restore original precision.
1996 os->precision(old_precision);
1999 private:
2000 bool HasMaxAbsError() const {
2001 return max_abs_error_ >= 0;
2004 const FloatType expected_;
2005 const bool nan_eq_nan_;
2006 // max_abs_error will be used for value comparison when >= 0.
2007 const FloatType max_abs_error_;
2009 GTEST_DISALLOW_ASSIGN_(Impl);
2012 // The following 3 type conversion operators allow FloatEq(expected) and
2013 // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a
2014 // Matcher<const float&>, or a Matcher<float&>, but nothing else.
2015 // (While Google's C++ coding style doesn't allow arguments passed
2016 // by non-const reference, we may see them in code not conforming to
2017 // the style. Therefore Google Mock needs to support them.)
2018 operator Matcher<FloatType>() const {
2019 return MakeMatcher(
2020 new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));
2023 operator Matcher<const FloatType&>() const {
2024 return MakeMatcher(
2025 new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
2028 operator Matcher<FloatType&>() const {
2029 return MakeMatcher(
2030 new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));
2033 private:
2034 const FloatType expected_;
2035 const bool nan_eq_nan_;
2036 // max_abs_error will be used for value comparison when >= 0.
2037 const FloatType max_abs_error_;
2039 GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
2042 // Implements the Pointee(m) matcher for matching a pointer whose
2043 // pointee matches matcher m. The pointer can be either raw or smart.
2044 template <typename InnerMatcher>
2045 class PointeeMatcher {
2046 public:
2047 explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
2049 // This type conversion operator template allows Pointee(m) to be
2050 // used as a matcher for any pointer type whose pointee type is
2051 // compatible with the inner matcher, where type Pointer can be
2052 // either a raw pointer or a smart pointer.
2054 // The reason we do this instead of relying on
2055 // MakePolymorphicMatcher() is that the latter is not flexible
2056 // enough for implementing the DescribeTo() method of Pointee().
2057 template <typename Pointer>
2058 operator Matcher<Pointer>() const {
2059 return MakeMatcher(new Impl<Pointer>(matcher_));
2062 private:
2063 // The monomorphic implementation that works for a particular pointer type.
2064 template <typename Pointer>
2065 class Impl : public MatcherInterface<Pointer> {
2066 public:
2067 typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
2068 GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
2070 explicit Impl(const InnerMatcher& matcher)
2071 : matcher_(MatcherCast<const Pointee&>(matcher)) {}
2073 virtual void DescribeTo(::std::ostream* os) const {
2074 *os << "points to a value that ";
2075 matcher_.DescribeTo(os);
2078 virtual void DescribeNegationTo(::std::ostream* os) const {
2079 *os << "does not point to a value that ";
2080 matcher_.DescribeTo(os);
2083 virtual bool MatchAndExplain(Pointer pointer,
2084 MatchResultListener* listener) const {
2085 if (GetRawPointer(pointer) == NULL)
2086 return false;
2088 *listener << "which points to ";
2089 return MatchPrintAndExplain(*pointer, matcher_, listener);
2092 private:
2093 const Matcher<const Pointee&> matcher_;
2095 GTEST_DISALLOW_ASSIGN_(Impl);
2098 const InnerMatcher matcher_;
2100 GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
2103 // Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or
2104 // reference that matches inner_matcher when dynamic_cast<T> is applied.
2105 // The result of dynamic_cast<To> is forwarded to the inner matcher.
2106 // If To is a pointer and the cast fails, the inner matcher will receive NULL.
2107 // If To is a reference and the cast fails, this matcher returns false
2108 // immediately.
2109 template <typename To>
2110 class WhenDynamicCastToMatcherBase {
2111 public:
2112 explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)
2113 : matcher_(matcher) {}
2115 void DescribeTo(::std::ostream* os) const {
2116 GetCastTypeDescription(os);
2117 matcher_.DescribeTo(os);
2120 void DescribeNegationTo(::std::ostream* os) const {
2121 GetCastTypeDescription(os);
2122 matcher_.DescribeNegationTo(os);
2125 protected:
2126 const Matcher<To> matcher_;
2128 static string GetToName() {
2129 #if GTEST_HAS_RTTI
2130 return GetTypeName<To>();
2131 #else // GTEST_HAS_RTTI
2132 return "the target type";
2133 #endif // GTEST_HAS_RTTI
2136 private:
2137 static void GetCastTypeDescription(::std::ostream* os) {
2138 *os << "when dynamic_cast to " << GetToName() << ", ";
2141 GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase);
2144 // Primary template.
2145 // To is a pointer. Cast and forward the result.
2146 template <typename To>
2147 class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {
2148 public:
2149 explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)
2150 : WhenDynamicCastToMatcherBase<To>(matcher) {}
2152 template <typename From>
2153 bool MatchAndExplain(From from, MatchResultListener* listener) const {
2154 // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail?
2155 To to = dynamic_cast<To>(from);
2156 return MatchPrintAndExplain(to, this->matcher_, listener);
2160 // Specialize for references.
2161 // In this case we return false if the dynamic_cast fails.
2162 template <typename To>
2163 class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {
2164 public:
2165 explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)
2166 : WhenDynamicCastToMatcherBase<To&>(matcher) {}
2168 template <typename From>
2169 bool MatchAndExplain(From& from, MatchResultListener* listener) const {
2170 // We don't want an std::bad_cast here, so do the cast with pointers.
2171 To* to = dynamic_cast<To*>(&from);
2172 if (to == NULL) {
2173 *listener << "which cannot be dynamic_cast to " << this->GetToName();
2174 return false;
2176 return MatchPrintAndExplain(*to, this->matcher_, listener);
2180 // Implements the Field() matcher for matching a field (i.e. member
2181 // variable) of an object.
2182 template <typename Class, typename FieldType>
2183 class FieldMatcher {
2184 public:
2185 FieldMatcher(FieldType Class::*field,
2186 const Matcher<const FieldType&>& matcher)
2187 : field_(field), matcher_(matcher) {}
2189 void DescribeTo(::std::ostream* os) const {
2190 *os << "is an object whose given field ";
2191 matcher_.DescribeTo(os);
2194 void DescribeNegationTo(::std::ostream* os) const {
2195 *os << "is an object whose given field ";
2196 matcher_.DescribeNegationTo(os);
2199 template <typename T>
2200 bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
2201 return MatchAndExplainImpl(
2202 typename ::testing::internal::
2203 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
2204 value, listener);
2207 private:
2208 // The first argument of MatchAndExplainImpl() is needed to help
2209 // Symbian's C++ compiler choose which overload to use. Its type is
2210 // true_type iff the Field() matcher is used to match a pointer.
2211 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2212 MatchResultListener* listener) const {
2213 *listener << "whose given field is ";
2214 return MatchPrintAndExplain(obj.*field_, matcher_, listener);
2217 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2218 MatchResultListener* listener) const {
2219 if (p == NULL)
2220 return false;
2222 *listener << "which points to an object ";
2223 // Since *p has a field, it must be a class/struct/union type and
2224 // thus cannot be a pointer. Therefore we pass false_type() as
2225 // the first argument.
2226 return MatchAndExplainImpl(false_type(), *p, listener);
2229 const FieldType Class::*field_;
2230 const Matcher<const FieldType&> matcher_;
2232 GTEST_DISALLOW_ASSIGN_(FieldMatcher);
2235 // Implements the Property() matcher for matching a property
2236 // (i.e. return value of a getter method) of an object.
2237 template <typename Class, typename PropertyType>
2238 class PropertyMatcher {
2239 public:
2240 // The property may have a reference type, so 'const PropertyType&'
2241 // may cause double references and fail to compile. That's why we
2242 // need GTEST_REFERENCE_TO_CONST, which works regardless of
2243 // PropertyType being a reference or not.
2244 typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
2246 PropertyMatcher(PropertyType (Class::*property)() const,
2247 const Matcher<RefToConstProperty>& matcher)
2248 : property_(property), matcher_(matcher) {}
2250 void DescribeTo(::std::ostream* os) const {
2251 *os << "is an object whose given property ";
2252 matcher_.DescribeTo(os);
2255 void DescribeNegationTo(::std::ostream* os) const {
2256 *os << "is an object whose given property ";
2257 matcher_.DescribeNegationTo(os);
2260 template <typename T>
2261 bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
2262 return MatchAndExplainImpl(
2263 typename ::testing::internal::
2264 is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
2265 value, listener);
2268 private:
2269 // The first argument of MatchAndExplainImpl() is needed to help
2270 // Symbian's C++ compiler choose which overload to use. Its type is
2271 // true_type iff the Property() matcher is used to match a pointer.
2272 bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
2273 MatchResultListener* listener) const {
2274 *listener << "whose given property is ";
2275 // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
2276 // which takes a non-const reference as argument.
2277 #if defined(_PREFAST_ ) && _MSC_VER == 1800
2278 // Workaround bug in VC++ 2013's /analyze parser.
2279 // https://connect.microsoft.com/VisualStudio/feedback/details/1106363/internal-compiler-error-with-analyze-due-to-failure-to-infer-move
2280 posix::Abort(); // To make sure it is never run.
2281 return false;
2282 #else
2283 RefToConstProperty result = (obj.*property_)();
2284 return MatchPrintAndExplain(result, matcher_, listener);
2285 #endif
2288 bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
2289 MatchResultListener* listener) const {
2290 if (p == NULL)
2291 return false;
2293 *listener << "which points to an object ";
2294 // Since *p has a property method, it must be a class/struct/union
2295 // type and thus cannot be a pointer. Therefore we pass
2296 // false_type() as the first argument.
2297 return MatchAndExplainImpl(false_type(), *p, listener);
2300 PropertyType (Class::*property_)() const;
2301 const Matcher<RefToConstProperty> matcher_;
2303 GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
2306 // Type traits specifying various features of different functors for ResultOf.
2307 // The default template specifies features for functor objects.
2308 // Functor classes have to typedef argument_type and result_type
2309 // to be compatible with ResultOf.
2310 template <typename Functor>
2311 struct CallableTraits {
2312 typedef typename Functor::result_type ResultType;
2313 typedef Functor StorageType;
2315 static void CheckIsValid(Functor /* functor */) {}
2316 template <typename T>
2317 static ResultType Invoke(Functor f, T arg) { return f(arg); }
2320 // Specialization for function pointers.
2321 template <typename ArgType, typename ResType>
2322 struct CallableTraits<ResType(*)(ArgType)> {
2323 typedef ResType ResultType;
2324 typedef ResType(*StorageType)(ArgType);
2326 static void CheckIsValid(ResType(*f)(ArgType)) {
2327 GTEST_CHECK_(f != NULL)
2328 << "NULL function pointer is passed into ResultOf().";
2330 template <typename T>
2331 static ResType Invoke(ResType(*f)(ArgType), T arg) {
2332 return (*f)(arg);
2336 // Implements the ResultOf() matcher for matching a return value of a
2337 // unary function of an object.
2338 template <typename Callable>
2339 class ResultOfMatcher {
2340 public:
2341 typedef typename CallableTraits<Callable>::ResultType ResultType;
2343 ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
2344 : callable_(callable), matcher_(matcher) {
2345 CallableTraits<Callable>::CheckIsValid(callable_);
2348 template <typename T>
2349 operator Matcher<T>() const {
2350 return Matcher<T>(new Impl<T>(callable_, matcher_));
2353 private:
2354 typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
2356 template <typename T>
2357 class Impl : public MatcherInterface<T> {
2358 public:
2359 Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
2360 : callable_(callable), matcher_(matcher) {}
2362 virtual void DescribeTo(::std::ostream* os) const {
2363 *os << "is mapped by the given callable to a value that ";
2364 matcher_.DescribeTo(os);
2367 virtual void DescribeNegationTo(::std::ostream* os) const {
2368 *os << "is mapped by the given callable to a value that ";
2369 matcher_.DescribeNegationTo(os);
2372 virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
2373 *listener << "which is mapped by the given callable to ";
2374 // Cannot pass the return value (for example, int) to
2375 // MatchPrintAndExplain, which takes a non-const reference as argument.
2376 ResultType result =
2377 CallableTraits<Callable>::template Invoke<T>(callable_, obj);
2378 return MatchPrintAndExplain(result, matcher_, listener);
2381 private:
2382 // Functors often define operator() as non-const method even though
2383 // they are actualy stateless. But we need to use them even when
2384 // 'this' is a const pointer. It's the user's responsibility not to
2385 // use stateful callables with ResultOf(), which does't guarantee
2386 // how many times the callable will be invoked.
2387 mutable CallableStorageType callable_;
2388 const Matcher<ResultType> matcher_;
2390 GTEST_DISALLOW_ASSIGN_(Impl);
2391 }; // class Impl
2393 const CallableStorageType callable_;
2394 const Matcher<ResultType> matcher_;
2396 GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
2399 // Implements a matcher that checks the size of an STL-style container.
2400 template <typename SizeMatcher>
2401 class SizeIsMatcher {
2402 public:
2403 explicit SizeIsMatcher(const SizeMatcher& size_matcher)
2404 : size_matcher_(size_matcher) {
2407 template <typename Container>
2408 operator Matcher<Container>() const {
2409 return MakeMatcher(new Impl<Container>(size_matcher_));
2412 template <typename Container>
2413 class Impl : public MatcherInterface<Container> {
2414 public:
2415 typedef internal::StlContainerView<
2416 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView;
2417 typedef typename ContainerView::type::size_type SizeType;
2418 explicit Impl(const SizeMatcher& size_matcher)
2419 : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}
2421 virtual void DescribeTo(::std::ostream* os) const {
2422 *os << "size ";
2423 size_matcher_.DescribeTo(os);
2425 virtual void DescribeNegationTo(::std::ostream* os) const {
2426 *os << "size ";
2427 size_matcher_.DescribeNegationTo(os);
2430 virtual bool MatchAndExplain(Container container,
2431 MatchResultListener* listener) const {
2432 SizeType size = container.size();
2433 StringMatchResultListener size_listener;
2434 const bool result = size_matcher_.MatchAndExplain(size, &size_listener);
2435 *listener
2436 << "whose size " << size << (result ? " matches" : " doesn't match");
2437 PrintIfNotEmpty(size_listener.str(), listener->stream());
2438 return result;
2441 private:
2442 const Matcher<SizeType> size_matcher_;
2443 GTEST_DISALLOW_ASSIGN_(Impl);
2446 private:
2447 const SizeMatcher size_matcher_;
2448 GTEST_DISALLOW_ASSIGN_(SizeIsMatcher);
2451 // Implements a matcher that checks the begin()..end() distance of an STL-style
2452 // container.
2453 template <typename DistanceMatcher>
2454 class BeginEndDistanceIsMatcher {
2455 public:
2456 explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)
2457 : distance_matcher_(distance_matcher) {}
2459 template <typename Container>
2460 operator Matcher<Container>() const {
2461 return MakeMatcher(new Impl<Container>(distance_matcher_));
2464 template <typename Container>
2465 class Impl : public MatcherInterface<Container> {
2466 public:
2467 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
2468 typedef internal::StlContainerView<RawContainer> View;
2469 typedef typename View::type StlContainer;
2470 typedef typename View::const_reference StlContainerReference;
2471 typedef decltype(std::begin(
2472 std::declval<StlContainerReference>())) StlContainerConstIterator;
2473 typedef typename std::iterator_traits<
2474 StlContainerConstIterator>::difference_type DistanceType;
2475 explicit Impl(const DistanceMatcher& distance_matcher)
2476 : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}
2478 virtual void DescribeTo(::std::ostream* os) const {
2479 *os << "distance between begin() and end() ";
2480 distance_matcher_.DescribeTo(os);
2482 virtual void DescribeNegationTo(::std::ostream* os) const {
2483 *os << "distance between begin() and end() ";
2484 distance_matcher_.DescribeNegationTo(os);
2487 virtual bool MatchAndExplain(Container container,
2488 MatchResultListener* listener) const {
2489 #if GTEST_HAS_STD_BEGIN_AND_END_
2490 using std::begin;
2491 using std::end;
2492 DistanceType distance = std::distance(begin(container), end(container));
2493 #else
2494 DistanceType distance = std::distance(container.begin(), container.end());
2495 #endif
2496 StringMatchResultListener distance_listener;
2497 const bool result =
2498 distance_matcher_.MatchAndExplain(distance, &distance_listener);
2499 *listener << "whose distance between begin() and end() " << distance
2500 << (result ? " matches" : " doesn't match");
2501 PrintIfNotEmpty(distance_listener.str(), listener->stream());
2502 return result;
2505 private:
2506 const Matcher<DistanceType> distance_matcher_;
2507 GTEST_DISALLOW_ASSIGN_(Impl);
2510 private:
2511 const DistanceMatcher distance_matcher_;
2512 GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher);
2515 // Implements an equality matcher for any STL-style container whose elements
2516 // support ==. This matcher is like Eq(), but its failure explanations provide
2517 // more detailed information that is useful when the container is used as a set.
2518 // The failure message reports elements that are in one of the operands but not
2519 // the other. The failure messages do not report duplicate or out-of-order
2520 // elements in the containers (which don't properly matter to sets, but can
2521 // occur if the containers are vectors or lists, for example).
2523 // Uses the container's const_iterator, value_type, operator ==,
2524 // begin(), and end().
2525 template <typename Container>
2526 class ContainerEqMatcher {
2527 public:
2528 typedef internal::StlContainerView<Container> View;
2529 typedef typename View::type StlContainer;
2530 typedef typename View::const_reference StlContainerReference;
2532 // We make a copy of expected in case the elements in it are modified
2533 // after this matcher is created.
2534 explicit ContainerEqMatcher(const Container& expected)
2535 : expected_(View::Copy(expected)) {
2536 // Makes sure the user doesn't instantiate this class template
2537 // with a const or reference type.
2538 (void)testing::StaticAssertTypeEq<Container,
2539 GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
2542 void DescribeTo(::std::ostream* os) const {
2543 *os << "equals ";
2544 UniversalPrint(expected_, os);
2546 void DescribeNegationTo(::std::ostream* os) const {
2547 *os << "does not equal ";
2548 UniversalPrint(expected_, os);
2551 template <typename LhsContainer>
2552 bool MatchAndExplain(const LhsContainer& lhs,
2553 MatchResultListener* listener) const {
2554 // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
2555 // that causes LhsContainer to be a const type sometimes.
2556 typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
2557 LhsView;
2558 typedef typename LhsView::type LhsStlContainer;
2559 StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2560 if (lhs_stl_container == expected_)
2561 return true;
2563 ::std::ostream* const os = listener->stream();
2564 if (os != NULL) {
2565 // Something is different. Check for extra values first.
2566 bool printed_header = false;
2567 for (typename LhsStlContainer::const_iterator it =
2568 lhs_stl_container.begin();
2569 it != lhs_stl_container.end(); ++it) {
2570 if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==
2571 expected_.end()) {
2572 if (printed_header) {
2573 *os << ", ";
2574 } else {
2575 *os << "which has these unexpected elements: ";
2576 printed_header = true;
2578 UniversalPrint(*it, os);
2582 // Now check for missing values.
2583 bool printed_header2 = false;
2584 for (typename StlContainer::const_iterator it = expected_.begin();
2585 it != expected_.end(); ++it) {
2586 if (internal::ArrayAwareFind(
2587 lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
2588 lhs_stl_container.end()) {
2589 if (printed_header2) {
2590 *os << ", ";
2591 } else {
2592 *os << (printed_header ? ",\nand" : "which")
2593 << " doesn't have these expected elements: ";
2594 printed_header2 = true;
2596 UniversalPrint(*it, os);
2601 return false;
2604 private:
2605 const StlContainer expected_;
2607 GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
2610 // A comparator functor that uses the < operator to compare two values.
2611 struct LessComparator {
2612 template <typename T, typename U>
2613 bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; }
2616 // Implements WhenSortedBy(comparator, container_matcher).
2617 template <typename Comparator, typename ContainerMatcher>
2618 class WhenSortedByMatcher {
2619 public:
2620 WhenSortedByMatcher(const Comparator& comparator,
2621 const ContainerMatcher& matcher)
2622 : comparator_(comparator), matcher_(matcher) {}
2624 template <typename LhsContainer>
2625 operator Matcher<LhsContainer>() const {
2626 return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));
2629 template <typename LhsContainer>
2630 class Impl : public MatcherInterface<LhsContainer> {
2631 public:
2632 typedef internal::StlContainerView<
2633 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2634 typedef typename LhsView::type LhsStlContainer;
2635 typedef typename LhsView::const_reference LhsStlContainerReference;
2636 // Transforms std::pair<const Key, Value> into std::pair<Key, Value>
2637 // so that we can match associative containers.
2638 typedef typename RemoveConstFromKey<
2639 typename LhsStlContainer::value_type>::type LhsValue;
2641 Impl(const Comparator& comparator, const ContainerMatcher& matcher)
2642 : comparator_(comparator), matcher_(matcher) {}
2644 virtual void DescribeTo(::std::ostream* os) const {
2645 *os << "(when sorted) ";
2646 matcher_.DescribeTo(os);
2649 virtual void DescribeNegationTo(::std::ostream* os) const {
2650 *os << "(when sorted) ";
2651 matcher_.DescribeNegationTo(os);
2654 virtual bool MatchAndExplain(LhsContainer lhs,
2655 MatchResultListener* listener) const {
2656 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2657 ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),
2658 lhs_stl_container.end());
2659 ::std::sort(
2660 sorted_container.begin(), sorted_container.end(), comparator_);
2662 if (!listener->IsInterested()) {
2663 // If the listener is not interested, we do not need to
2664 // construct the inner explanation.
2665 return matcher_.Matches(sorted_container);
2668 *listener << "which is ";
2669 UniversalPrint(sorted_container, listener->stream());
2670 *listener << " when sorted";
2672 StringMatchResultListener inner_listener;
2673 const bool match = matcher_.MatchAndExplain(sorted_container,
2674 &inner_listener);
2675 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2676 return match;
2679 private:
2680 const Comparator comparator_;
2681 const Matcher<const ::std::vector<LhsValue>&> matcher_;
2683 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
2686 private:
2687 const Comparator comparator_;
2688 const ContainerMatcher matcher_;
2690 GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher);
2693 // Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
2694 // must be able to be safely cast to Matcher<tuple<const T1&, const
2695 // T2&> >, where T1 and T2 are the types of elements in the LHS
2696 // container and the RHS container respectively.
2697 template <typename TupleMatcher, typename RhsContainer>
2698 class PointwiseMatcher {
2699 public:
2700 typedef internal::StlContainerView<RhsContainer> RhsView;
2701 typedef typename RhsView::type RhsStlContainer;
2702 typedef typename RhsStlContainer::value_type RhsValue;
2704 // Like ContainerEq, we make a copy of rhs in case the elements in
2705 // it are modified after this matcher is created.
2706 PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
2707 : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
2708 // Makes sure the user doesn't instantiate this class template
2709 // with a const or reference type.
2710 (void)testing::StaticAssertTypeEq<RhsContainer,
2711 GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
2714 template <typename LhsContainer>
2715 operator Matcher<LhsContainer>() const {
2716 return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
2719 template <typename LhsContainer>
2720 class Impl : public MatcherInterface<LhsContainer> {
2721 public:
2722 typedef internal::StlContainerView<
2723 GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
2724 typedef typename LhsView::type LhsStlContainer;
2725 typedef typename LhsView::const_reference LhsStlContainerReference;
2726 typedef typename LhsStlContainer::value_type LhsValue;
2727 // We pass the LHS value and the RHS value to the inner matcher by
2728 // reference, as they may be expensive to copy. We must use tuple
2729 // instead of pair here, as a pair cannot hold references (C++ 98,
2730 // 20.2.2 [lib.pairs]).
2731 typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
2733 Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
2734 // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
2735 : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
2736 rhs_(rhs) {}
2738 virtual void DescribeTo(::std::ostream* os) const {
2739 *os << "contains " << rhs_.size()
2740 << " values, where each value and its corresponding value in ";
2741 UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
2742 *os << " ";
2743 mono_tuple_matcher_.DescribeTo(os);
2745 virtual void DescribeNegationTo(::std::ostream* os) const {
2746 *os << "doesn't contain exactly " << rhs_.size()
2747 << " values, or contains a value x at some index i"
2748 << " where x and the i-th value of ";
2749 UniversalPrint(rhs_, os);
2750 *os << " ";
2751 mono_tuple_matcher_.DescribeNegationTo(os);
2754 virtual bool MatchAndExplain(LhsContainer lhs,
2755 MatchResultListener* listener) const {
2756 LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
2757 const size_t actual_size = lhs_stl_container.size();
2758 if (actual_size != rhs_.size()) {
2759 *listener << "which contains " << actual_size << " values";
2760 return false;
2763 typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
2764 typename RhsStlContainer::const_iterator right = rhs_.begin();
2765 for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
2766 const InnerMatcherArg value_pair(*left, *right);
2768 if (listener->IsInterested()) {
2769 StringMatchResultListener inner_listener;
2770 if (!mono_tuple_matcher_.MatchAndExplain(
2771 value_pair, &inner_listener)) {
2772 *listener << "where the value pair (";
2773 UniversalPrint(*left, listener->stream());
2774 *listener << ", ";
2775 UniversalPrint(*right, listener->stream());
2776 *listener << ") at index #" << i << " don't match";
2777 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2778 return false;
2780 } else {
2781 if (!mono_tuple_matcher_.Matches(value_pair))
2782 return false;
2786 return true;
2789 private:
2790 const Matcher<InnerMatcherArg> mono_tuple_matcher_;
2791 const RhsStlContainer rhs_;
2793 GTEST_DISALLOW_ASSIGN_(Impl);
2796 private:
2797 const TupleMatcher tuple_matcher_;
2798 const RhsStlContainer rhs_;
2800 GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
2803 // Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
2804 template <typename Container>
2805 class QuantifierMatcherImpl : public MatcherInterface<Container> {
2806 public:
2807 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
2808 typedef StlContainerView<RawContainer> View;
2809 typedef typename View::type StlContainer;
2810 typedef typename View::const_reference StlContainerReference;
2811 typedef typename StlContainer::value_type Element;
2813 template <typename InnerMatcher>
2814 explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
2815 : inner_matcher_(
2816 testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
2818 // Checks whether:
2819 // * All elements in the container match, if all_elements_should_match.
2820 // * Any element in the container matches, if !all_elements_should_match.
2821 bool MatchAndExplainImpl(bool all_elements_should_match,
2822 Container container,
2823 MatchResultListener* listener) const {
2824 StlContainerReference stl_container = View::ConstReference(container);
2825 size_t i = 0;
2826 for (typename StlContainer::const_iterator it = stl_container.begin();
2827 it != stl_container.end(); ++it, ++i) {
2828 StringMatchResultListener inner_listener;
2829 const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
2831 if (matches != all_elements_should_match) {
2832 *listener << "whose element #" << i
2833 << (matches ? " matches" : " doesn't match");
2834 PrintIfNotEmpty(inner_listener.str(), listener->stream());
2835 return !all_elements_should_match;
2838 return all_elements_should_match;
2841 protected:
2842 const Matcher<const Element&> inner_matcher_;
2844 GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
2847 // Implements Contains(element_matcher) for the given argument type Container.
2848 // Symmetric to EachMatcherImpl.
2849 template <typename Container>
2850 class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
2851 public:
2852 template <typename InnerMatcher>
2853 explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
2854 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2856 // Describes what this matcher does.
2857 virtual void DescribeTo(::std::ostream* os) const {
2858 *os << "contains at least one element that ";
2859 this->inner_matcher_.DescribeTo(os);
2862 virtual void DescribeNegationTo(::std::ostream* os) const {
2863 *os << "doesn't contain any element that ";
2864 this->inner_matcher_.DescribeTo(os);
2867 virtual bool MatchAndExplain(Container container,
2868 MatchResultListener* listener) const {
2869 return this->MatchAndExplainImpl(false, container, listener);
2872 private:
2873 GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
2876 // Implements Each(element_matcher) for the given argument type Container.
2877 // Symmetric to ContainsMatcherImpl.
2878 template <typename Container>
2879 class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
2880 public:
2881 template <typename InnerMatcher>
2882 explicit EachMatcherImpl(InnerMatcher inner_matcher)
2883 : QuantifierMatcherImpl<Container>(inner_matcher) {}
2885 // Describes what this matcher does.
2886 virtual void DescribeTo(::std::ostream* os) const {
2887 *os << "only contains elements that ";
2888 this->inner_matcher_.DescribeTo(os);
2891 virtual void DescribeNegationTo(::std::ostream* os) const {
2892 *os << "contains some element that ";
2893 this->inner_matcher_.DescribeNegationTo(os);
2896 virtual bool MatchAndExplain(Container container,
2897 MatchResultListener* listener) const {
2898 return this->MatchAndExplainImpl(true, container, listener);
2901 private:
2902 GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
2905 // Implements polymorphic Contains(element_matcher).
2906 template <typename M>
2907 class ContainsMatcher {
2908 public:
2909 explicit ContainsMatcher(M m) : inner_matcher_(m) {}
2911 template <typename Container>
2912 operator Matcher<Container>() const {
2913 return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
2916 private:
2917 const M inner_matcher_;
2919 GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
2922 // Implements polymorphic Each(element_matcher).
2923 template <typename M>
2924 class EachMatcher {
2925 public:
2926 explicit EachMatcher(M m) : inner_matcher_(m) {}
2928 template <typename Container>
2929 operator Matcher<Container>() const {
2930 return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
2933 private:
2934 const M inner_matcher_;
2936 GTEST_DISALLOW_ASSIGN_(EachMatcher);
2939 // Implements Key(inner_matcher) for the given argument pair type.
2940 // Key(inner_matcher) matches an std::pair whose 'first' field matches
2941 // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
2942 // std::map that contains at least one element whose key is >= 5.
2943 template <typename PairType>
2944 class KeyMatcherImpl : public MatcherInterface<PairType> {
2945 public:
2946 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
2947 typedef typename RawPairType::first_type KeyType;
2949 template <typename InnerMatcher>
2950 explicit KeyMatcherImpl(InnerMatcher inner_matcher)
2951 : inner_matcher_(
2952 testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
2955 // Returns true iff 'key_value.first' (the key) matches the inner matcher.
2956 virtual bool MatchAndExplain(PairType key_value,
2957 MatchResultListener* listener) const {
2958 StringMatchResultListener inner_listener;
2959 const bool match = inner_matcher_.MatchAndExplain(key_value.first,
2960 &inner_listener);
2961 const internal::string explanation = inner_listener.str();
2962 if (explanation != "") {
2963 *listener << "whose first field is a value " << explanation;
2965 return match;
2968 // Describes what this matcher does.
2969 virtual void DescribeTo(::std::ostream* os) const {
2970 *os << "has a key that ";
2971 inner_matcher_.DescribeTo(os);
2974 // Describes what the negation of this matcher does.
2975 virtual void DescribeNegationTo(::std::ostream* os) const {
2976 *os << "doesn't have a key that ";
2977 inner_matcher_.DescribeTo(os);
2980 private:
2981 const Matcher<const KeyType&> inner_matcher_;
2983 GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
2986 // Implements polymorphic Key(matcher_for_key).
2987 template <typename M>
2988 class KeyMatcher {
2989 public:
2990 explicit KeyMatcher(M m) : matcher_for_key_(m) {}
2992 template <typename PairType>
2993 operator Matcher<PairType>() const {
2994 return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
2997 private:
2998 const M matcher_for_key_;
3000 GTEST_DISALLOW_ASSIGN_(KeyMatcher);
3003 // Implements Pair(first_matcher, second_matcher) for the given argument pair
3004 // type with its two matchers. See Pair() function below.
3005 template <typename PairType>
3006 class PairMatcherImpl : public MatcherInterface<PairType> {
3007 public:
3008 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
3009 typedef typename RawPairType::first_type FirstType;
3010 typedef typename RawPairType::second_type SecondType;
3012 template <typename FirstMatcher, typename SecondMatcher>
3013 PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
3014 : first_matcher_(
3015 testing::SafeMatcherCast<const FirstType&>(first_matcher)),
3016 second_matcher_(
3017 testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
3020 // Describes what this matcher does.
3021 virtual void DescribeTo(::std::ostream* os) const {
3022 *os << "has a first field that ";
3023 first_matcher_.DescribeTo(os);
3024 *os << ", and has a second field that ";
3025 second_matcher_.DescribeTo(os);
3028 // Describes what the negation of this matcher does.
3029 virtual void DescribeNegationTo(::std::ostream* os) const {
3030 *os << "has a first field that ";
3031 first_matcher_.DescribeNegationTo(os);
3032 *os << ", or has a second field that ";
3033 second_matcher_.DescribeNegationTo(os);
3036 // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
3037 // matches second_matcher.
3038 virtual bool MatchAndExplain(PairType a_pair,
3039 MatchResultListener* listener) const {
3040 if (!listener->IsInterested()) {
3041 // If the listener is not interested, we don't need to construct the
3042 // explanation.
3043 return first_matcher_.Matches(a_pair.first) &&
3044 second_matcher_.Matches(a_pair.second);
3046 StringMatchResultListener first_inner_listener;
3047 if (!first_matcher_.MatchAndExplain(a_pair.first,
3048 &first_inner_listener)) {
3049 *listener << "whose first field does not match";
3050 PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
3051 return false;
3053 StringMatchResultListener second_inner_listener;
3054 if (!second_matcher_.MatchAndExplain(a_pair.second,
3055 &second_inner_listener)) {
3056 *listener << "whose second field does not match";
3057 PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
3058 return false;
3060 ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
3061 listener);
3062 return true;
3065 private:
3066 void ExplainSuccess(const internal::string& first_explanation,
3067 const internal::string& second_explanation,
3068 MatchResultListener* listener) const {
3069 *listener << "whose both fields match";
3070 if (first_explanation != "") {
3071 *listener << ", where the first field is a value " << first_explanation;
3073 if (second_explanation != "") {
3074 *listener << ", ";
3075 if (first_explanation != "") {
3076 *listener << "and ";
3077 } else {
3078 *listener << "where ";
3080 *listener << "the second field is a value " << second_explanation;
3084 const Matcher<const FirstType&> first_matcher_;
3085 const Matcher<const SecondType&> second_matcher_;
3087 GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
3090 // Implements polymorphic Pair(first_matcher, second_matcher).
3091 template <typename FirstMatcher, typename SecondMatcher>
3092 class PairMatcher {
3093 public:
3094 PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
3095 : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
3097 template <typename PairType>
3098 operator Matcher<PairType> () const {
3099 return MakeMatcher(
3100 new PairMatcherImpl<PairType>(
3101 first_matcher_, second_matcher_));
3104 private:
3105 const FirstMatcher first_matcher_;
3106 const SecondMatcher second_matcher_;
3108 GTEST_DISALLOW_ASSIGN_(PairMatcher);
3111 // Implements ElementsAre() and ElementsAreArray().
3112 template <typename Container>
3113 class ElementsAreMatcherImpl : public MatcherInterface<Container> {
3114 public:
3115 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3116 typedef internal::StlContainerView<RawContainer> View;
3117 typedef typename View::type StlContainer;
3118 typedef typename View::const_reference StlContainerReference;
3119 typedef decltype(std::begin(
3120 std::declval<StlContainerReference>())) StlContainerConstIterator;
3121 typedef typename std::remove_reference<decltype(
3122 *std::declval<StlContainerConstIterator &>())>::type Element;
3124 // Constructs the matcher from a sequence of element values or
3125 // element matchers.
3126 template <typename InputIter>
3127 ElementsAreMatcherImpl(InputIter first, InputIter last) {
3128 while (first != last) {
3129 matchers_.push_back(MatcherCast<const Element&>(*first++));
3133 // Describes what this matcher does.
3134 virtual void DescribeTo(::std::ostream* os) const {
3135 if (count() == 0) {
3136 *os << "is empty";
3137 } else if (count() == 1) {
3138 *os << "has 1 element that ";
3139 matchers_[0].DescribeTo(os);
3140 } else {
3141 *os << "has " << Elements(count()) << " where\n";
3142 for (size_t i = 0; i != count(); ++i) {
3143 *os << "element #" << i << " ";
3144 matchers_[i].DescribeTo(os);
3145 if (i + 1 < count()) {
3146 *os << ",\n";
3152 // Describes what the negation of this matcher does.
3153 virtual void DescribeNegationTo(::std::ostream* os) const {
3154 if (count() == 0) {
3155 *os << "isn't empty";
3156 return;
3159 *os << "doesn't have " << Elements(count()) << ", or\n";
3160 for (size_t i = 0; i != count(); ++i) {
3161 *os << "element #" << i << " ";
3162 matchers_[i].DescribeNegationTo(os);
3163 if (i + 1 < count()) {
3164 *os << ", or\n";
3169 virtual bool MatchAndExplain(Container container,
3170 MatchResultListener* listener) const {
3171 // To work with stream-like "containers", we must only walk
3172 // through the elements in one pass.
3174 const bool listener_interested = listener->IsInterested();
3176 // explanations[i] is the explanation of the element at index i.
3177 ::std::vector<internal::string> explanations(count());
3178 StlContainerReference stl_container = View::ConstReference(container);
3179 StlContainerConstIterator it = stl_container.begin();
3180 size_t exam_pos = 0;
3181 bool mismatch_found = false; // Have we found a mismatched element yet?
3183 // Go through the elements and matchers in pairs, until we reach
3184 // the end of either the elements or the matchers, or until we find a
3185 // mismatch.
3186 for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {
3187 bool match; // Does the current element match the current matcher?
3188 if (listener_interested) {
3189 StringMatchResultListener s;
3190 match = matchers_[exam_pos].MatchAndExplain(*it, &s);
3191 explanations[exam_pos] = s.str();
3192 } else {
3193 match = matchers_[exam_pos].Matches(*it);
3196 if (!match) {
3197 mismatch_found = true;
3198 break;
3201 // If mismatch_found is true, 'exam_pos' is the index of the mismatch.
3203 // Find how many elements the actual container has. We avoid
3204 // calling size() s.t. this code works for stream-like "containers"
3205 // that don't define size().
3206 size_t actual_count = exam_pos;
3207 for (; it != stl_container.end(); ++it) {
3208 ++actual_count;
3211 if (actual_count != count()) {
3212 // The element count doesn't match. If the container is empty,
3213 // there's no need to explain anything as Google Mock already
3214 // prints the empty container. Otherwise we just need to show
3215 // how many elements there actually are.
3216 if (listener_interested && (actual_count != 0)) {
3217 *listener << "which has " << Elements(actual_count);
3219 return false;
3222 if (mismatch_found) {
3223 // The element count matches, but the exam_pos-th element doesn't match.
3224 if (listener_interested) {
3225 *listener << "whose element #" << exam_pos << " doesn't match";
3226 PrintIfNotEmpty(explanations[exam_pos], listener->stream());
3228 return false;
3231 // Every element matches its expectation. We need to explain why
3232 // (the obvious ones can be skipped).
3233 if (listener_interested) {
3234 bool reason_printed = false;
3235 for (size_t i = 0; i != count(); ++i) {
3236 const internal::string& s = explanations[i];
3237 if (!s.empty()) {
3238 if (reason_printed) {
3239 *listener << ",\nand ";
3241 *listener << "whose element #" << i << " matches, " << s;
3242 reason_printed = true;
3246 return true;
3249 private:
3250 static Message Elements(size_t count) {
3251 return Message() << count << (count == 1 ? " element" : " elements");
3254 size_t count() const { return matchers_.size(); }
3256 ::std::vector<Matcher<const Element&> > matchers_;
3258 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
3261 // Connectivity matrix of (elements X matchers), in element-major order.
3262 // Initially, there are no edges.
3263 // Use NextGraph() to iterate over all possible edge configurations.
3264 // Use Randomize() to generate a random edge configuration.
3265 class GTEST_API_ MatchMatrix {
3266 public:
3267 MatchMatrix(size_t num_elements, size_t num_matchers)
3268 : num_elements_(num_elements),
3269 num_matchers_(num_matchers),
3270 matched_(num_elements_* num_matchers_, 0) {
3273 size_t LhsSize() const { return num_elements_; }
3274 size_t RhsSize() const { return num_matchers_; }
3275 bool HasEdge(size_t ilhs, size_t irhs) const {
3276 return matched_[SpaceIndex(ilhs, irhs)] == 1;
3278 void SetEdge(size_t ilhs, size_t irhs, bool b) {
3279 matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;
3282 // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,
3283 // adds 1 to that number; returns false if incrementing the graph left it
3284 // empty.
3285 bool NextGraph();
3287 void Randomize();
3289 string DebugString() const;
3291 private:
3292 size_t SpaceIndex(size_t ilhs, size_t irhs) const {
3293 return ilhs * num_matchers_ + irhs;
3296 size_t num_elements_;
3297 size_t num_matchers_;
3299 // Each element is a char interpreted as bool. They are stored as a
3300 // flattened array in lhs-major order, use 'SpaceIndex()' to translate
3301 // a (ilhs, irhs) matrix coordinate into an offset.
3302 ::std::vector<char> matched_;
3305 typedef ::std::pair<size_t, size_t> ElementMatcherPair;
3306 typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;
3308 // Returns a maximum bipartite matching for the specified graph 'g'.
3309 // The matching is represented as a vector of {element, matcher} pairs.
3310 GTEST_API_ ElementMatcherPairs
3311 FindMaxBipartiteMatching(const MatchMatrix& g);
3313 GTEST_API_ bool FindPairing(const MatchMatrix& matrix,
3314 MatchResultListener* listener);
3316 // Untyped base class for implementing UnorderedElementsAre. By
3317 // putting logic that's not specific to the element type here, we
3318 // reduce binary bloat and increase compilation speed.
3319 class GTEST_API_ UnorderedElementsAreMatcherImplBase {
3320 protected:
3321 // A vector of matcher describers, one for each element matcher.
3322 // Does not own the describers (and thus can be used only when the
3323 // element matchers are alive).
3324 typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;
3326 // Describes this UnorderedElementsAre matcher.
3327 void DescribeToImpl(::std::ostream* os) const;
3329 // Describes the negation of this UnorderedElementsAre matcher.
3330 void DescribeNegationToImpl(::std::ostream* os) const;
3332 bool VerifyAllElementsAndMatchersAreMatched(
3333 const ::std::vector<string>& element_printouts,
3334 const MatchMatrix& matrix,
3335 MatchResultListener* listener) const;
3337 MatcherDescriberVec& matcher_describers() {
3338 return matcher_describers_;
3341 static Message Elements(size_t n) {
3342 return Message() << n << " element" << (n == 1 ? "" : "s");
3345 private:
3346 MatcherDescriberVec matcher_describers_;
3348 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase);
3351 // Implements unordered ElementsAre and unordered ElementsAreArray.
3352 template <typename Container>
3353 class UnorderedElementsAreMatcherImpl
3354 : public MatcherInterface<Container>,
3355 public UnorderedElementsAreMatcherImplBase {
3356 public:
3357 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3358 typedef internal::StlContainerView<RawContainer> View;
3359 typedef typename View::type StlContainer;
3360 typedef typename View::const_reference StlContainerReference;
3361 typedef decltype(std::begin(
3362 std::declval<StlContainerReference>())) StlContainerConstIterator;
3363 typedef typename std::remove_reference<decltype(
3364 *std::declval<StlContainerConstIterator &>())>::type Element;
3366 // Constructs the matcher from a sequence of element values or
3367 // element matchers.
3368 template <typename InputIter>
3369 UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) {
3370 for (; first != last; ++first) {
3371 matchers_.push_back(MatcherCast<const Element&>(*first));
3372 matcher_describers().push_back(matchers_.back().GetDescriber());
3376 // Describes what this matcher does.
3377 virtual void DescribeTo(::std::ostream* os) const {
3378 return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);
3381 // Describes what the negation of this matcher does.
3382 virtual void DescribeNegationTo(::std::ostream* os) const {
3383 return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);
3386 virtual bool MatchAndExplain(Container container,
3387 MatchResultListener* listener) const {
3388 StlContainerReference stl_container = View::ConstReference(container);
3389 ::std::vector<string> element_printouts;
3390 MatchMatrix matrix = AnalyzeElements(stl_container.begin(),
3391 stl_container.end(),
3392 &element_printouts,
3393 listener);
3395 const size_t actual_count = matrix.LhsSize();
3396 if (actual_count == 0 && matchers_.empty()) {
3397 return true;
3399 if (actual_count != matchers_.size()) {
3400 // The element count doesn't match. If the container is empty,
3401 // there's no need to explain anything as Google Mock already
3402 // prints the empty container. Otherwise we just need to show
3403 // how many elements there actually are.
3404 if (actual_count != 0 && listener->IsInterested()) {
3405 *listener << "which has " << Elements(actual_count);
3407 return false;
3410 return VerifyAllElementsAndMatchersAreMatched(element_printouts,
3411 matrix, listener) &&
3412 FindPairing(matrix, listener);
3415 private:
3416 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3418 template <typename ElementIter>
3419 MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,
3420 ::std::vector<string>* element_printouts,
3421 MatchResultListener* listener) const {
3422 element_printouts->clear();
3423 ::std::vector<char> did_match;
3424 size_t num_elements = 0;
3425 for (; elem_first != elem_last; ++num_elements, ++elem_first) {
3426 if (listener->IsInterested()) {
3427 element_printouts->push_back(PrintToString(*elem_first));
3429 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3430 did_match.push_back(Matches(matchers_[irhs])(*elem_first));
3434 MatchMatrix matrix(num_elements, matchers_.size());
3435 ::std::vector<char>::const_iterator did_match_iter = did_match.begin();
3436 for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {
3437 for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {
3438 matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);
3441 return matrix;
3444 MatcherVec matchers_;
3446 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl);
3449 // Functor for use in TransformTuple.
3450 // Performs MatcherCast<Target> on an input argument of any type.
3451 template <typename Target>
3452 struct CastAndAppendTransform {
3453 template <typename Arg>
3454 Matcher<Target> operator()(const Arg& a) const {
3455 return MatcherCast<Target>(a);
3459 // Implements UnorderedElementsAre.
3460 template <typename MatcherTuple>
3461 class UnorderedElementsAreMatcher {
3462 public:
3463 explicit UnorderedElementsAreMatcher(const MatcherTuple& args)
3464 : matchers_(args) {}
3466 template <typename Container>
3467 operator Matcher<Container>() const {
3468 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3469 typedef internal::StlContainerView<RawContainer> View;
3470 typedef typename View::const_reference StlContainerReference;
3471 typedef decltype(std::begin(
3472 std::declval<StlContainerReference>())) StlContainerConstIterator;
3473 typedef typename std::remove_reference<decltype(
3474 *std::declval<StlContainerConstIterator &>())>::type Element;
3475 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3476 MatcherVec matchers;
3477 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
3478 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3479 ::std::back_inserter(matchers));
3480 return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>(
3481 matchers.begin(), matchers.end()));
3484 private:
3485 const MatcherTuple matchers_;
3486 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher);
3489 // Implements ElementsAre.
3490 template <typename MatcherTuple>
3491 class ElementsAreMatcher {
3492 public:
3493 explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}
3495 template <typename Container>
3496 operator Matcher<Container>() const {
3497 typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
3498 typedef internal::StlContainerView<RawContainer> View;
3499 typedef typename View::const_reference StlContainerReference;
3500 typedef decltype(std::begin(
3501 std::declval<StlContainerReference>())) StlContainerConstIterator;
3502 typedef typename std::remove_reference<decltype(
3503 *std::declval<StlContainerConstIterator &>())>::type Element;
3504 typedef ::std::vector<Matcher<const Element&> > MatcherVec;
3505 MatcherVec matchers;
3506 matchers.reserve(::testing::tuple_size<MatcherTuple>::value);
3507 TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,
3508 ::std::back_inserter(matchers));
3509 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3510 matchers.begin(), matchers.end()));
3513 private:
3514 const MatcherTuple matchers_;
3515 GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher);
3518 // Implements UnorderedElementsAreArray().
3519 template <typename T>
3520 class UnorderedElementsAreArrayMatcher {
3521 public:
3522 UnorderedElementsAreArrayMatcher() {}
3524 template <typename Iter>
3525 UnorderedElementsAreArrayMatcher(Iter first, Iter last)
3526 : matchers_(first, last) {}
3528 template <typename Container>
3529 operator Matcher<Container>() const {
3530 return MakeMatcher(
3531 new UnorderedElementsAreMatcherImpl<Container>(matchers_.begin(),
3532 matchers_.end()));
3535 private:
3536 ::std::vector<T> matchers_;
3538 GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher);
3541 // Implements ElementsAreArray().
3542 template <typename T>
3543 class ElementsAreArrayMatcher {
3544 public:
3545 template <typename Iter>
3546 ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}
3548 template <typename Container>
3549 operator Matcher<Container>() const {
3550 return MakeMatcher(new ElementsAreMatcherImpl<Container>(
3551 matchers_.begin(), matchers_.end()));
3554 private:
3555 const ::std::vector<T> matchers_;
3557 GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
3560 // Given a 2-tuple matcher tm of type Tuple2Matcher and a value second
3561 // of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,
3562 // second) is a polymorphic matcher that matches a value x iff tm
3563 // matches tuple (x, second). Useful for implementing
3564 // UnorderedPointwise() in terms of UnorderedElementsAreArray().
3566 // BoundSecondMatcher is copyable and assignable, as we need to put
3567 // instances of this class in a vector when implementing
3568 // UnorderedPointwise().
3569 template <typename Tuple2Matcher, typename Second>
3570 class BoundSecondMatcher {
3571 public:
3572 BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)
3573 : tuple2_matcher_(tm), second_value_(second) {}
3575 template <typename T>
3576 operator Matcher<T>() const {
3577 return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));
3580 // We have to define this for UnorderedPointwise() to compile in
3581 // C++98 mode, as it puts BoundSecondMatcher instances in a vector,
3582 // which requires the elements to be assignable in C++98. The
3583 // compiler cannot generate the operator= for us, as Tuple2Matcher
3584 // and Second may not be assignable.
3586 // However, this should never be called, so the implementation just
3587 // need to assert.
3588 void operator=(const BoundSecondMatcher& /*rhs*/) {
3589 GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned.";
3592 private:
3593 template <typename T>
3594 class Impl : public MatcherInterface<T> {
3595 public:
3596 typedef ::testing::tuple<T, Second> ArgTuple;
3598 Impl(const Tuple2Matcher& tm, const Second& second)
3599 : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),
3600 second_value_(second) {}
3602 virtual void DescribeTo(::std::ostream* os) const {
3603 *os << "and ";
3604 UniversalPrint(second_value_, os);
3605 *os << " ";
3606 mono_tuple2_matcher_.DescribeTo(os);
3609 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
3610 return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),
3611 listener);
3614 private:
3615 const Matcher<const ArgTuple&> mono_tuple2_matcher_;
3616 const Second second_value_;
3618 GTEST_DISALLOW_ASSIGN_(Impl);
3621 const Tuple2Matcher tuple2_matcher_;
3622 const Second second_value_;
3625 // Given a 2-tuple matcher tm and a value second,
3626 // MatcherBindSecond(tm, second) returns a matcher that matches a
3627 // value x iff tm matches tuple (x, second). Useful for implementing
3628 // UnorderedPointwise() in terms of UnorderedElementsAreArray().
3629 template <typename Tuple2Matcher, typename Second>
3630 BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(
3631 const Tuple2Matcher& tm, const Second& second) {
3632 return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);
3635 // Returns the description for a matcher defined using the MATCHER*()
3636 // macro where the user-supplied description string is "", if
3637 // 'negation' is false; otherwise returns the description of the
3638 // negation of the matcher. 'param_values' contains a list of strings
3639 // that are the print-out of the matcher's parameters.
3640 GTEST_API_ string FormatMatcherDescription(bool negation,
3641 const char* matcher_name,
3642 const Strings& param_values);
3644 } // namespace internal
3646 // ElementsAreArray(first, last)
3647 // ElementsAreArray(pointer, count)
3648 // ElementsAreArray(array)
3649 // ElementsAreArray(container)
3650 // ElementsAreArray({ e1, e2, ..., en })
3652 // The ElementsAreArray() functions are like ElementsAre(...), except
3653 // that they are given a homogeneous sequence rather than taking each
3654 // element as a function argument. The sequence can be specified as an
3655 // array, a pointer and count, a vector, an initializer list, or an
3656 // STL iterator range. In each of these cases, the underlying sequence
3657 // can be either a sequence of values or a sequence of matchers.
3659 // All forms of ElementsAreArray() make a copy of the input matcher sequence.
3661 template <typename Iter>
3662 inline internal::ElementsAreArrayMatcher<
3663 typename ::std::iterator_traits<Iter>::value_type>
3664 ElementsAreArray(Iter first, Iter last) {
3665 typedef typename ::std::iterator_traits<Iter>::value_type T;
3666 return internal::ElementsAreArrayMatcher<T>(first, last);
3669 template <typename T>
3670 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3671 const T* pointer, size_t count) {
3672 return ElementsAreArray(pointer, pointer + count);
3675 template <typename T, size_t N>
3676 inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(
3677 const T (&array)[N]) {
3678 return ElementsAreArray(array, N);
3681 template <typename Container>
3682 inline internal::ElementsAreArrayMatcher<typename Container::value_type>
3683 ElementsAreArray(const Container& container) {
3684 return ElementsAreArray(container.begin(), container.end());
3687 #if GTEST_HAS_STD_INITIALIZER_LIST_
3688 template <typename T>
3689 inline internal::ElementsAreArrayMatcher<T>
3690 ElementsAreArray(::std::initializer_list<T> xs) {
3691 return ElementsAreArray(xs.begin(), xs.end());
3693 #endif
3695 // UnorderedElementsAreArray(first, last)
3696 // UnorderedElementsAreArray(pointer, count)
3697 // UnorderedElementsAreArray(array)
3698 // UnorderedElementsAreArray(container)
3699 // UnorderedElementsAreArray({ e1, e2, ..., en })
3701 // The UnorderedElementsAreArray() functions are like
3702 // ElementsAreArray(...), but allow matching the elements in any order.
3703 template <typename Iter>
3704 inline internal::UnorderedElementsAreArrayMatcher<
3705 typename ::std::iterator_traits<Iter>::value_type>
3706 UnorderedElementsAreArray(Iter first, Iter last) {
3707 typedef typename ::std::iterator_traits<Iter>::value_type T;
3708 return internal::UnorderedElementsAreArrayMatcher<T>(first, last);
3711 template <typename T>
3712 inline internal::UnorderedElementsAreArrayMatcher<T>
3713 UnorderedElementsAreArray(const T* pointer, size_t count) {
3714 return UnorderedElementsAreArray(pointer, pointer + count);
3717 template <typename T, size_t N>
3718 inline internal::UnorderedElementsAreArrayMatcher<T>
3719 UnorderedElementsAreArray(const T (&array)[N]) {
3720 return UnorderedElementsAreArray(array, N);
3723 template <typename Container>
3724 inline internal::UnorderedElementsAreArrayMatcher<
3725 typename Container::value_type>
3726 UnorderedElementsAreArray(const Container& container) {
3727 return UnorderedElementsAreArray(container.begin(), container.end());
3730 #if GTEST_HAS_STD_INITIALIZER_LIST_
3731 template <typename T>
3732 inline internal::UnorderedElementsAreArrayMatcher<T>
3733 UnorderedElementsAreArray(::std::initializer_list<T> xs) {
3734 return UnorderedElementsAreArray(xs.begin(), xs.end());
3736 #endif
3738 // _ is a matcher that matches anything of any type.
3740 // This definition is fine as:
3742 // 1. The C++ standard permits using the name _ in a namespace that
3743 // is not the global namespace or ::std.
3744 // 2. The AnythingMatcher class has no data member or constructor,
3745 // so it's OK to create global variables of this type.
3746 // 3. c-style has approved of using _ in this case.
3747 const internal::AnythingMatcher _ = {};
3748 // Creates a matcher that matches any value of the given type T.
3749 template <typename T>
3750 inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
3752 // Creates a matcher that matches any value of the given type T.
3753 template <typename T>
3754 inline Matcher<T> An() { return A<T>(); }
3756 // Creates a polymorphic matcher that matches anything equal to x.
3757 // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
3758 // wouldn't compile.
3759 template <typename T>
3760 inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
3762 // Constructs a Matcher<T> from a 'value' of type T. The constructed
3763 // matcher matches any value that's equal to 'value'.
3764 template <typename T>
3765 Matcher<T>::Matcher(T value) { *this = Eq(value); }
3767 // Creates a monomorphic matcher that matches anything with type Lhs
3768 // and equal to rhs. A user may need to use this instead of Eq(...)
3769 // in order to resolve an overloading ambiguity.
3771 // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
3772 // or Matcher<T>(x), but more readable than the latter.
3774 // We could define similar monomorphic matchers for other comparison
3775 // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
3776 // it yet as those are used much less than Eq() in practice. A user
3777 // can always write Matcher<T>(Lt(5)) to be explicit about the type,
3778 // for example.
3779 template <typename Lhs, typename Rhs>
3780 inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
3782 // Creates a polymorphic matcher that matches anything >= x.
3783 template <typename Rhs>
3784 inline internal::GeMatcher<Rhs> Ge(Rhs x) {
3785 return internal::GeMatcher<Rhs>(x);
3788 // Creates a polymorphic matcher that matches anything > x.
3789 template <typename Rhs>
3790 inline internal::GtMatcher<Rhs> Gt(Rhs x) {
3791 return internal::GtMatcher<Rhs>(x);
3794 // Creates a polymorphic matcher that matches anything <= x.
3795 template <typename Rhs>
3796 inline internal::LeMatcher<Rhs> Le(Rhs x) {
3797 return internal::LeMatcher<Rhs>(x);
3800 // Creates a polymorphic matcher that matches anything < x.
3801 template <typename Rhs>
3802 inline internal::LtMatcher<Rhs> Lt(Rhs x) {
3803 return internal::LtMatcher<Rhs>(x);
3806 // Creates a polymorphic matcher that matches anything != x.
3807 template <typename Rhs>
3808 inline internal::NeMatcher<Rhs> Ne(Rhs x) {
3809 return internal::NeMatcher<Rhs>(x);
3812 // Creates a polymorphic matcher that matches any NULL pointer.
3813 inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
3814 return MakePolymorphicMatcher(internal::IsNullMatcher());
3817 // Creates a polymorphic matcher that matches any non-NULL pointer.
3818 // This is convenient as Not(NULL) doesn't compile (the compiler
3819 // thinks that that expression is comparing a pointer with an integer).
3820 inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
3821 return MakePolymorphicMatcher(internal::NotNullMatcher());
3824 // Creates a polymorphic matcher that matches any argument that
3825 // references variable x.
3826 template <typename T>
3827 inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
3828 return internal::RefMatcher<T&>(x);
3831 // Creates a matcher that matches any double argument approximately
3832 // equal to rhs, where two NANs are considered unequal.
3833 inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
3834 return internal::FloatingEqMatcher<double>(rhs, false);
3837 // Creates a matcher that matches any double argument approximately
3838 // equal to rhs, including NaN values when rhs is NaN.
3839 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
3840 return internal::FloatingEqMatcher<double>(rhs, true);
3843 // Creates a matcher that matches any double argument approximately equal to
3844 // rhs, up to the specified max absolute error bound, where two NANs are
3845 // considered unequal. The max absolute error bound must be non-negative.
3846 inline internal::FloatingEqMatcher<double> DoubleNear(
3847 double rhs, double max_abs_error) {
3848 return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);
3851 // Creates a matcher that matches any double argument approximately equal to
3852 // rhs, up to the specified max absolute error bound, including NaN values when
3853 // rhs is NaN. The max absolute error bound must be non-negative.
3854 inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(
3855 double rhs, double max_abs_error) {
3856 return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);
3859 // Creates a matcher that matches any float argument approximately
3860 // equal to rhs, where two NANs are considered unequal.
3861 inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
3862 return internal::FloatingEqMatcher<float>(rhs, false);
3865 // Creates a matcher that matches any float argument approximately
3866 // equal to rhs, including NaN values when rhs is NaN.
3867 inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
3868 return internal::FloatingEqMatcher<float>(rhs, true);
3871 // Creates a matcher that matches any float argument approximately equal to
3872 // rhs, up to the specified max absolute error bound, where two NANs are
3873 // considered unequal. The max absolute error bound must be non-negative.
3874 inline internal::FloatingEqMatcher<float> FloatNear(
3875 float rhs, float max_abs_error) {
3876 return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);
3879 // Creates a matcher that matches any float argument approximately equal to
3880 // rhs, up to the specified max absolute error bound, including NaN values when
3881 // rhs is NaN. The max absolute error bound must be non-negative.
3882 inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(
3883 float rhs, float max_abs_error) {
3884 return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);
3887 // Creates a matcher that matches a pointer (raw or smart) that points
3888 // to a value that matches inner_matcher.
3889 template <typename InnerMatcher>
3890 inline internal::PointeeMatcher<InnerMatcher> Pointee(
3891 const InnerMatcher& inner_matcher) {
3892 return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
3895 // Creates a matcher that matches a pointer or reference that matches
3896 // inner_matcher when dynamic_cast<To> is applied.
3897 // The result of dynamic_cast<To> is forwarded to the inner matcher.
3898 // If To is a pointer and the cast fails, the inner matcher will receive NULL.
3899 // If To is a reference and the cast fails, this matcher returns false
3900 // immediately.
3901 template <typename To>
3902 inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> >
3903 WhenDynamicCastTo(const Matcher<To>& inner_matcher) {
3904 return MakePolymorphicMatcher(
3905 internal::WhenDynamicCastToMatcher<To>(inner_matcher));
3908 // Creates a matcher that matches an object whose given field matches
3909 // 'matcher'. For example,
3910 // Field(&Foo::number, Ge(5))
3911 // matches a Foo object x iff x.number >= 5.
3912 template <typename Class, typename FieldType, typename FieldMatcher>
3913 inline PolymorphicMatcher<
3914 internal::FieldMatcher<Class, FieldType> > Field(
3915 FieldType Class::*field, const FieldMatcher& matcher) {
3916 return MakePolymorphicMatcher(
3917 internal::FieldMatcher<Class, FieldType>(
3918 field, MatcherCast<const FieldType&>(matcher)));
3919 // The call to MatcherCast() is required for supporting inner
3920 // matchers of compatible types. For example, it allows
3921 // Field(&Foo::bar, m)
3922 // to compile where bar is an int32 and m is a matcher for int64.
3925 // Creates a matcher that matches an object whose given property
3926 // matches 'matcher'. For example,
3927 // Property(&Foo::str, StartsWith("hi"))
3928 // matches a Foo object x iff x.str() starts with "hi".
3929 template <typename Class, typename PropertyType, typename PropertyMatcher>
3930 inline PolymorphicMatcher<
3931 internal::PropertyMatcher<Class, PropertyType> > Property(
3932 PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
3933 return MakePolymorphicMatcher(
3934 internal::PropertyMatcher<Class, PropertyType>(
3935 property,
3936 MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
3937 // The call to MatcherCast() is required for supporting inner
3938 // matchers of compatible types. For example, it allows
3939 // Property(&Foo::bar, m)
3940 // to compile where bar() returns an int32 and m is a matcher for int64.
3943 // Creates a matcher that matches an object iff the result of applying
3944 // a callable to x matches 'matcher'.
3945 // For example,
3946 // ResultOf(f, StartsWith("hi"))
3947 // matches a Foo object x iff f(x) starts with "hi".
3948 // callable parameter can be a function, function pointer, or a functor.
3949 // Callable has to satisfy the following conditions:
3950 // * It is required to keep no state affecting the results of
3951 // the calls on it and make no assumptions about how many calls
3952 // will be made. Any state it keeps must be protected from the
3953 // concurrent access.
3954 // * If it is a function object, it has to define type result_type.
3955 // We recommend deriving your functor classes from std::unary_function.
3956 template <typename Callable, typename ResultOfMatcher>
3957 internal::ResultOfMatcher<Callable> ResultOf(
3958 Callable callable, const ResultOfMatcher& matcher) {
3959 return internal::ResultOfMatcher<Callable>(
3960 callable,
3961 MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
3962 matcher));
3963 // The call to MatcherCast() is required for supporting inner
3964 // matchers of compatible types. For example, it allows
3965 // ResultOf(Function, m)
3966 // to compile where Function() returns an int32 and m is a matcher for int64.
3969 // String matchers.
3971 // Matches a string equal to str.
3972 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3973 StrEq(const internal::string& str) {
3974 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3975 str, true, true));
3978 // Matches a string not equal to str.
3979 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3980 StrNe(const internal::string& str) {
3981 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3982 str, false, true));
3985 // Matches a string equal to str, ignoring case.
3986 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3987 StrCaseEq(const internal::string& str) {
3988 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3989 str, true, false));
3992 // Matches a string not equal to str, ignoring case.
3993 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
3994 StrCaseNe(const internal::string& str) {
3995 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
3996 str, false, false));
3999 // Creates a matcher that matches any string, std::string, or C string
4000 // that contains the given substring.
4001 inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
4002 HasSubstr(const internal::string& substring) {
4003 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
4004 substring));
4007 // Matches a string that starts with 'prefix' (case-sensitive).
4008 inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
4009 StartsWith(const internal::string& prefix) {
4010 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
4011 prefix));
4014 // Matches a string that ends with 'suffix' (case-sensitive).
4015 inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
4016 EndsWith(const internal::string& suffix) {
4017 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
4018 suffix));
4021 // Matches a string that fully matches regular expression 'regex'.
4022 // The matcher takes ownership of 'regex'.
4023 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4024 const internal::RE* regex) {
4025 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
4027 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
4028 const internal::string& regex) {
4029 return MatchesRegex(new internal::RE(regex));
4032 // Matches a string that contains regular expression 'regex'.
4033 // The matcher takes ownership of 'regex'.
4034 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4035 const internal::RE* regex) {
4036 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
4038 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
4039 const internal::string& regex) {
4040 return ContainsRegex(new internal::RE(regex));
4043 #if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4044 // Wide string matchers.
4046 // Matches a string equal to str.
4047 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4048 StrEq(const internal::wstring& str) {
4049 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4050 str, true, true));
4053 // Matches a string not equal to str.
4054 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4055 StrNe(const internal::wstring& str) {
4056 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4057 str, false, true));
4060 // Matches a string equal to str, ignoring case.
4061 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4062 StrCaseEq(const internal::wstring& str) {
4063 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4064 str, true, false));
4067 // Matches a string not equal to str, ignoring case.
4068 inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
4069 StrCaseNe(const internal::wstring& str) {
4070 return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
4071 str, false, false));
4074 // Creates a matcher that matches any wstring, std::wstring, or C wide string
4075 // that contains the given substring.
4076 inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
4077 HasSubstr(const internal::wstring& substring) {
4078 return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
4079 substring));
4082 // Matches a string that starts with 'prefix' (case-sensitive).
4083 inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
4084 StartsWith(const internal::wstring& prefix) {
4085 return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
4086 prefix));
4089 // Matches a string that ends with 'suffix' (case-sensitive).
4090 inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
4091 EndsWith(const internal::wstring& suffix) {
4092 return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
4093 suffix));
4096 #endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
4098 // Creates a polymorphic matcher that matches a 2-tuple where the
4099 // first field == the second field.
4100 inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
4102 // Creates a polymorphic matcher that matches a 2-tuple where the
4103 // first field >= the second field.
4104 inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
4106 // Creates a polymorphic matcher that matches a 2-tuple where the
4107 // first field > the second field.
4108 inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
4110 // Creates a polymorphic matcher that matches a 2-tuple where the
4111 // first field <= the second field.
4112 inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
4114 // Creates a polymorphic matcher that matches a 2-tuple where the
4115 // first field < the second field.
4116 inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
4118 // Creates a polymorphic matcher that matches a 2-tuple where the
4119 // first field != the second field.
4120 inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
4122 // Creates a matcher that matches any value of type T that m doesn't
4123 // match.
4124 template <typename InnerMatcher>
4125 inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
4126 return internal::NotMatcher<InnerMatcher>(m);
4129 // Returns a matcher that matches anything that satisfies the given
4130 // predicate. The predicate can be any unary function or functor
4131 // whose return type can be implicitly converted to bool.
4132 template <typename Predicate>
4133 inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
4134 Truly(Predicate pred) {
4135 return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
4138 // Returns a matcher that matches the container size. The container must
4139 // support both size() and size_type which all STL-like containers provide.
4140 // Note that the parameter 'size' can be a value of type size_type as well as
4141 // matcher. For instance:
4142 // EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements.
4143 // EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2.
4144 template <typename SizeMatcher>
4145 inline internal::SizeIsMatcher<SizeMatcher>
4146 SizeIs(const SizeMatcher& size_matcher) {
4147 return internal::SizeIsMatcher<SizeMatcher>(size_matcher);
4150 // Returns a matcher that matches the distance between the container's begin()
4151 // iterator and its end() iterator, i.e. the size of the container. This matcher
4152 // can be used instead of SizeIs with containers such as std::forward_list which
4153 // do not implement size(). The container must provide const_iterator (with
4154 // valid iterator_traits), begin() and end().
4155 template <typename DistanceMatcher>
4156 inline internal::BeginEndDistanceIsMatcher<DistanceMatcher>
4157 BeginEndDistanceIs(const DistanceMatcher& distance_matcher) {
4158 return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);
4161 // Returns a matcher that matches an equal container.
4162 // This matcher behaves like Eq(), but in the event of mismatch lists the
4163 // values that are included in one container but not the other. (Duplicate
4164 // values and order differences are not explained.)
4165 template <typename Container>
4166 inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
4167 GTEST_REMOVE_CONST_(Container)> >
4168 ContainerEq(const Container& rhs) {
4169 // This following line is for working around a bug in MSVC 8.0,
4170 // which causes Container to be a const type sometimes.
4171 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4172 return MakePolymorphicMatcher(
4173 internal::ContainerEqMatcher<RawContainer>(rhs));
4176 // Returns a matcher that matches a container that, when sorted using
4177 // the given comparator, matches container_matcher.
4178 template <typename Comparator, typename ContainerMatcher>
4179 inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher>
4180 WhenSortedBy(const Comparator& comparator,
4181 const ContainerMatcher& container_matcher) {
4182 return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(
4183 comparator, container_matcher);
4186 // Returns a matcher that matches a container that, when sorted using
4187 // the < operator, matches container_matcher.
4188 template <typename ContainerMatcher>
4189 inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>
4190 WhenSorted(const ContainerMatcher& container_matcher) {
4191 return
4192 internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>(
4193 internal::LessComparator(), container_matcher);
4196 // Matches an STL-style container or a native array that contains the
4197 // same number of elements as in rhs, where its i-th element and rhs's
4198 // i-th element (as a pair) satisfy the given pair matcher, for all i.
4199 // TupleMatcher must be able to be safely cast to Matcher<tuple<const
4200 // T1&, const T2&> >, where T1 and T2 are the types of elements in the
4201 // LHS container and the RHS container respectively.
4202 template <typename TupleMatcher, typename Container>
4203 inline internal::PointwiseMatcher<TupleMatcher,
4204 GTEST_REMOVE_CONST_(Container)>
4205 Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
4206 // This following line is for working around a bug in MSVC 8.0,
4207 // which causes Container to be a const type sometimes (e.g. when
4208 // rhs is a const int[])..
4209 typedef GTEST_REMOVE_CONST_(Container) RawContainer;
4210 return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
4211 tuple_matcher, rhs);
4214 #if GTEST_HAS_STD_INITIALIZER_LIST_
4216 // Supports the Pointwise(m, {a, b, c}) syntax.
4217 template <typename TupleMatcher, typename T>
4218 inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise(
4219 const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {
4220 return Pointwise(tuple_matcher, std::vector<T>(rhs));
4223 #endif // GTEST_HAS_STD_INITIALIZER_LIST_
4225 // UnorderedPointwise(pair_matcher, rhs) matches an STL-style
4226 // container or a native array that contains the same number of
4227 // elements as in rhs, where in some permutation of the container, its
4228 // i-th element and rhs's i-th element (as a pair) satisfy the given
4229 // pair matcher, for all i. Tuple2Matcher must be able to be safely
4230 // cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are
4231 // the types of elements in the LHS container and the RHS container
4232 // respectively.
4234 // This is like Pointwise(pair_matcher, rhs), except that the element
4235 // order doesn't matter.
4236 template <typename Tuple2Matcher, typename RhsContainer>
4237 inline internal::UnorderedElementsAreArrayMatcher<
4238 typename internal::BoundSecondMatcher<
4239 Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_(
4240 RhsContainer)>::type::value_type> >
4241 UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4242 const RhsContainer& rhs_container) {
4243 // This following line is for working around a bug in MSVC 8.0,
4244 // which causes RhsContainer to be a const type sometimes (e.g. when
4245 // rhs_container is a const int[]).
4246 typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer;
4248 // RhsView allows the same code to handle RhsContainer being a
4249 // STL-style container and it being a native C-style array.
4250 typedef typename internal::StlContainerView<RawRhsContainer> RhsView;
4251 typedef typename RhsView::type RhsStlContainer;
4252 typedef typename RhsStlContainer::value_type Second;
4253 const RhsStlContainer& rhs_stl_container =
4254 RhsView::ConstReference(rhs_container);
4256 // Create a matcher for each element in rhs_container.
4257 ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers;
4258 for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin();
4259 it != rhs_stl_container.end(); ++it) {
4260 matchers.push_back(
4261 internal::MatcherBindSecond(tuple2_matcher, *it));
4264 // Delegate the work to UnorderedElementsAreArray().
4265 return UnorderedElementsAreArray(matchers);
4268 #if GTEST_HAS_STD_INITIALIZER_LIST_
4270 // Supports the UnorderedPointwise(m, {a, b, c}) syntax.
4271 template <typename Tuple2Matcher, typename T>
4272 inline internal::UnorderedElementsAreArrayMatcher<
4273 typename internal::BoundSecondMatcher<Tuple2Matcher, T> >
4274 UnorderedPointwise(const Tuple2Matcher& tuple2_matcher,
4275 std::initializer_list<T> rhs) {
4276 return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));
4279 #endif // GTEST_HAS_STD_INITIALIZER_LIST_
4281 // Matches an STL-style container or a native array that contains at
4282 // least one element matching the given value or matcher.
4284 // Examples:
4285 // ::std::set<int> page_ids;
4286 // page_ids.insert(3);
4287 // page_ids.insert(1);
4288 // EXPECT_THAT(page_ids, Contains(1));
4289 // EXPECT_THAT(page_ids, Contains(Gt(2)));
4290 // EXPECT_THAT(page_ids, Not(Contains(4)));
4292 // ::std::map<int, size_t> page_lengths;
4293 // page_lengths[1] = 100;
4294 // EXPECT_THAT(page_lengths,
4295 // Contains(::std::pair<const int, size_t>(1, 100)));
4297 // const char* user_ids[] = { "joe", "mike", "tom" };
4298 // EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
4299 template <typename M>
4300 inline internal::ContainsMatcher<M> Contains(M matcher) {
4301 return internal::ContainsMatcher<M>(matcher);
4304 // Matches an STL-style container or a native array that contains only
4305 // elements matching the given value or matcher.
4307 // Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
4308 // the messages are different.
4310 // Examples:
4311 // ::std::set<int> page_ids;
4312 // // Each(m) matches an empty container, regardless of what m is.
4313 // EXPECT_THAT(page_ids, Each(Eq(1)));
4314 // EXPECT_THAT(page_ids, Each(Eq(77)));
4316 // page_ids.insert(3);
4317 // EXPECT_THAT(page_ids, Each(Gt(0)));
4318 // EXPECT_THAT(page_ids, Not(Each(Gt(4))));
4319 // page_ids.insert(1);
4320 // EXPECT_THAT(page_ids, Not(Each(Lt(2))));
4322 // ::std::map<int, size_t> page_lengths;
4323 // page_lengths[1] = 100;
4324 // page_lengths[2] = 200;
4325 // page_lengths[3] = 300;
4326 // EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
4327 // EXPECT_THAT(page_lengths, Each(Key(Le(3))));
4329 // const char* user_ids[] = { "joe", "mike", "tom" };
4330 // EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
4331 template <typename M>
4332 inline internal::EachMatcher<M> Each(M matcher) {
4333 return internal::EachMatcher<M>(matcher);
4336 // Key(inner_matcher) matches an std::pair whose 'first' field matches
4337 // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
4338 // std::map that contains at least one element whose key is >= 5.
4339 template <typename M>
4340 inline internal::KeyMatcher<M> Key(M inner_matcher) {
4341 return internal::KeyMatcher<M>(inner_matcher);
4344 // Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
4345 // matches first_matcher and whose 'second' field matches second_matcher. For
4346 // example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
4347 // to match a std::map<int, string> that contains exactly one element whose key
4348 // is >= 5 and whose value equals "foo".
4349 template <typename FirstMatcher, typename SecondMatcher>
4350 inline internal::PairMatcher<FirstMatcher, SecondMatcher>
4351 Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
4352 return internal::PairMatcher<FirstMatcher, SecondMatcher>(
4353 first_matcher, second_matcher);
4356 // Returns a predicate that is satisfied by anything that matches the
4357 // given matcher.
4358 template <typename M>
4359 inline internal::MatcherAsPredicate<M> Matches(M matcher) {
4360 return internal::MatcherAsPredicate<M>(matcher);
4363 // Returns true iff the value matches the matcher.
4364 template <typename T, typename M>
4365 inline bool Value(const T& value, M matcher) {
4366 return testing::Matches(matcher)(value);
4369 // Matches the value against the given matcher and explains the match
4370 // result to listener.
4371 template <typename T, typename M>
4372 inline bool ExplainMatchResult(
4373 M matcher, const T& value, MatchResultListener* listener) {
4374 return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
4377 #if GTEST_LANG_CXX11
4378 // Define variadic matcher versions. They are overloaded in
4379 // gmock-generated-matchers.h for the cases supported by pre C++11 compilers.
4380 template <typename... Args>
4381 inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) {
4382 return internal::AllOfMatcher<Args...>(matchers...);
4385 template <typename... Args>
4386 inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) {
4387 return internal::AnyOfMatcher<Args...>(matchers...);
4390 #endif // GTEST_LANG_CXX11
4392 // AllArgs(m) is a synonym of m. This is useful in
4394 // EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
4396 // which is easier to read than
4398 // EXPECT_CALL(foo, Bar(_, _)).With(Eq());
4399 template <typename InnerMatcher>
4400 inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
4402 // These macros allow using matchers to check values in Google Test
4403 // tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
4404 // succeed iff the value matches the matcher. If the assertion fails,
4405 // the value and the description of the matcher will be printed.
4406 #define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
4407 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4408 #define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
4409 ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
4411 } // namespace testing
4413 // Include any custom callback matchers added by the local installation.
4414 // We must include this header at the end to make sure it can use the
4415 // declarations from this file.
4416 #include "gmock/internal/custom/gmock-matchers.h"
4417 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_