1 // Copyright 2007, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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 // The Google C++ Testing and Mocking Framework (Google Test)
32 // This file implements just enough of the matcher interface to allow
33 // EXPECT_DEATH and friends to accept a matcher argument.
35 // IWYU pragma: private, include "gtest/gtest.h"
36 // IWYU pragma: friend gtest/.*
37 // IWYU pragma: friend gmock/.*
39 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
40 #define GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
46 #include <type_traits>
48 #include "gtest/gtest-printers.h"
49 #include "gtest/internal/gtest-internal.h"
50 #include "gtest/internal/gtest-port.h"
52 // MSVC warning C5046 is new as of VS2017 version 15.8.
53 #if defined(_MSC_VER) && _MSC_VER >= 1915
54 #define GTEST_MAYBE_5046_ 5046
56 #define GTEST_MAYBE_5046_
59 GTEST_DISABLE_MSC_WARNINGS_PUSH_(
60 4251 GTEST_MAYBE_5046_ /* class A needs to have dll-interface to be used by
62 /* Symbol involving type with internal linkage not defined */)
66 // To implement a matcher Foo for type T, define:
67 // 1. a class FooMatcherMatcher that implements the matcher interface:
68 // using is_gtest_matcher = void;
69 // bool MatchAndExplain(const T&, std::ostream*);
70 // (MatchResultListener* can also be used instead of std::ostream*)
71 // void DescribeTo(std::ostream*);
72 // void DescribeNegationTo(std::ostream*);
74 // 2. a factory function that creates a Matcher<T> object from a
77 class MatchResultListener {
79 // Creates a listener object with the given underlying ostream. The
80 // listener does not own the ostream, and does not dereference it
81 // in the constructor or destructor.
82 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
83 virtual ~MatchResultListener() = 0; // Makes this class abstract.
85 // Streams x to the underlying ostream; does nothing if the ostream
88 MatchResultListener& operator<<(const T& x) {
89 if (stream_ != nullptr) *stream_ << x;
93 // Returns the underlying ostream.
94 ::std::ostream* stream() { return stream_; }
96 // Returns true if and only if the listener is interested in an explanation
97 // of the match result. A matcher's MatchAndExplain() method can use
98 // this information to avoid generating the explanation when no one
99 // intends to hear it.
100 bool IsInterested() const { return stream_ != nullptr; }
103 ::std::ostream* const stream_;
105 MatchResultListener(const MatchResultListener&) = delete;
106 MatchResultListener& operator=(const MatchResultListener&) = delete;
109 inline MatchResultListener::~MatchResultListener() {}
111 // An instance of a subclass of this knows how to describe itself as a
113 class GTEST_API_ MatcherDescriberInterface {
115 virtual ~MatcherDescriberInterface() {}
117 // Describes this matcher to an ostream. The function should print
118 // a verb phrase that describes the property a value matching this
119 // matcher should have. The subject of the verb phrase is the value
120 // being matched. For example, the DescribeTo() method of the Gt(7)
121 // matcher prints "is greater than 7".
122 virtual void DescribeTo(::std::ostream* os) const = 0;
124 // Describes the negation of this matcher to an ostream. For
125 // example, if the description of this matcher is "is greater than
126 // 7", the negated description could be "is not greater than 7".
127 // You are not required to override this when implementing
128 // MatcherInterface, but it is highly advised so that your matcher
129 // can produce good error messages.
130 virtual void DescribeNegationTo(::std::ostream* os) const {
137 // The implementation of a matcher.
138 template <typename T>
139 class MatcherInterface : public MatcherDescriberInterface {
141 // Returns true if and only if the matcher matches x; also explains the
142 // match result to 'listener' if necessary (see the next paragraph), in
143 // the form of a non-restrictive relative clause ("which ...",
144 // "whose ...", etc) that describes x. For example, the
145 // MatchAndExplain() method of the Pointee(...) matcher should
146 // generate an explanation like "which points to ...".
148 // Implementations of MatchAndExplain() should add an explanation of
149 // the match result *if and only if* they can provide additional
150 // information that's not already present (or not obvious) in the
151 // print-out of x and the matcher's description. Whether the match
152 // succeeds is not a factor in deciding whether an explanation is
153 // needed, as sometimes the caller needs to print a failure message
154 // when the match succeeds (e.g. when the matcher is used inside
157 // For example, a "has at least 10 elements" matcher should explain
158 // what the actual element count is, regardless of the match result,
159 // as it is useful information to the reader; on the other hand, an
160 // "is empty" matcher probably only needs to explain what the actual
161 // size is when the match fails, as it's redundant to say that the
162 // size is 0 when the value is already known to be empty.
164 // You should override this method when defining a new matcher.
166 // It's the responsibility of the caller (Google Test) to guarantee
167 // that 'listener' is not NULL. This helps to simplify a matcher's
168 // implementation when it doesn't care about the performance, as it
169 // can talk to 'listener' without checking its validity first.
170 // However, in order to implement dummy listeners efficiently,
171 // listener->stream() may be NULL.
172 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
174 // Inherits these methods from MatcherDescriberInterface:
175 // virtual void DescribeTo(::std::ostream* os) const = 0;
176 // virtual void DescribeNegationTo(::std::ostream* os) const;
182 template <typename A, typename B>
183 bool operator()(const A& a, const B& b) const {
188 template <typename A, typename B>
189 bool operator()(const A& a, const B& b) const {
194 template <typename A, typename B>
195 bool operator()(const A& a, const B& b) const {
200 template <typename A, typename B>
201 bool operator()(const A& a, const B& b) const {
206 template <typename A, typename B>
207 bool operator()(const A& a, const B& b) const {
212 template <typename A, typename B>
213 bool operator()(const A& a, const B& b) const {
218 // A match result listener that ignores the explanation.
219 class DummyMatchResultListener : public MatchResultListener {
221 DummyMatchResultListener() : MatchResultListener(nullptr) {}
224 DummyMatchResultListener(const DummyMatchResultListener&) = delete;
225 DummyMatchResultListener& operator=(const DummyMatchResultListener&) = delete;
228 // A match result listener that forwards the explanation to a given
229 // ostream. The difference between this and MatchResultListener is
230 // that the former is concrete.
231 class StreamMatchResultListener : public MatchResultListener {
233 explicit StreamMatchResultListener(::std::ostream* os)
234 : MatchResultListener(os) {}
237 StreamMatchResultListener(const StreamMatchResultListener&) = delete;
238 StreamMatchResultListener& operator=(const StreamMatchResultListener&) =
242 struct SharedPayloadBase {
243 std::atomic<int> ref{1};
244 void Ref() { ref.fetch_add(1, std::memory_order_relaxed); }
245 bool Unref() { return ref.fetch_sub(1, std::memory_order_acq_rel) == 1; }
248 template <typename T>
249 struct SharedPayload : SharedPayloadBase {
250 explicit SharedPayload(const T& v) : value(v) {}
251 explicit SharedPayload(T&& v) : value(std::move(v)) {}
253 static void Destroy(SharedPayloadBase* shared) {
254 delete static_cast<SharedPayload*>(shared);
260 // An internal class for implementing Matcher<T>, which will derive
261 // from it. We put functionalities common to all Matcher<T>
262 // specializations here to avoid code duplication.
263 template <typename T>
264 class MatcherBase : private MatcherDescriberInterface {
266 // Returns true if and only if the matcher matches x; also explains the
267 // match result to 'listener'.
268 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
269 GTEST_CHECK_(vtable_ != nullptr);
270 return vtable_->match_and_explain(*this, x, listener);
273 // Returns true if and only if this matcher matches x.
274 bool Matches(const T& x) const {
275 DummyMatchResultListener dummy;
276 return MatchAndExplain(x, &dummy);
279 // Describes this matcher to an ostream.
280 void DescribeTo(::std::ostream* os) const final {
281 GTEST_CHECK_(vtable_ != nullptr);
282 vtable_->describe(*this, os, false);
285 // Describes the negation of this matcher to an ostream.
286 void DescribeNegationTo(::std::ostream* os) const final {
287 GTEST_CHECK_(vtable_ != nullptr);
288 vtable_->describe(*this, os, true);
291 // Explains why x matches, or doesn't match, the matcher.
292 void ExplainMatchResultTo(const T& x, ::std::ostream* os) const {
293 StreamMatchResultListener listener(os);
294 MatchAndExplain(x, &listener);
297 // Returns the describer for this matcher object; retains ownership
298 // of the describer, which is only guaranteed to be alive when
299 // this matcher object is alive.
300 const MatcherDescriberInterface* GetDescriber() const {
301 if (vtable_ == nullptr) return nullptr;
302 return vtable_->get_describer(*this);
306 MatcherBase() : vtable_(nullptr), buffer_() {}
308 // Constructs a matcher from its implementation.
309 template <typename U>
310 explicit MatcherBase(const MatcherInterface<U>* impl)
311 : vtable_(nullptr), buffer_() {
315 template <typename M, typename = typename std::remove_reference<
316 M>::type::is_gtest_matcher>
317 MatcherBase(M&& m) : vtable_(nullptr), buffer_() { // NOLINT
318 Init(std::forward<M>(m));
321 MatcherBase(const MatcherBase& other)
322 : vtable_(other.vtable_), buffer_(other.buffer_) {
323 if (IsShared()) buffer_.shared->Ref();
326 MatcherBase& operator=(const MatcherBase& other) {
327 if (this == &other) return *this;
329 vtable_ = other.vtable_;
330 buffer_ = other.buffer_;
331 if (IsShared()) buffer_.shared->Ref();
335 MatcherBase(MatcherBase&& other)
336 : vtable_(other.vtable_), buffer_(other.buffer_) {
337 other.vtable_ = nullptr;
340 MatcherBase& operator=(MatcherBase&& other) {
341 if (this == &other) return *this;
343 vtable_ = other.vtable_;
344 buffer_ = other.buffer_;
345 other.vtable_ = nullptr;
349 ~MatcherBase() override { Destroy(); }
353 bool (*match_and_explain)(const MatcherBase&, const T&,
354 MatchResultListener*);
355 void (*describe)(const MatcherBase&, std::ostream*, bool negation);
356 // Returns the captured object if it implements the interface, otherwise
357 // returns the MatcherBase itself.
358 const MatcherDescriberInterface* (*get_describer)(const MatcherBase&);
359 // Called on shared instances when the reference count reaches 0.
360 void (*shared_destroy)(SharedPayloadBase*);
363 bool IsShared() const {
364 return vtable_ != nullptr && vtable_->shared_destroy != nullptr;
367 // If the implementation uses a listener, call that.
368 template <typename P>
369 static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
370 MatchResultListener* listener)
371 -> decltype(P::Get(m).MatchAndExplain(value, listener->stream())) {
372 return P::Get(m).MatchAndExplain(value, listener->stream());
375 template <typename P>
376 static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
377 MatchResultListener* listener)
378 -> decltype(P::Get(m).MatchAndExplain(value, listener)) {
379 return P::Get(m).MatchAndExplain(value, listener);
382 template <typename P>
383 static void DescribeImpl(const MatcherBase& m, std::ostream* os,
386 P::Get(m).DescribeNegationTo(os);
388 P::Get(m).DescribeTo(os);
392 template <typename P>
393 static const MatcherDescriberInterface* GetDescriberImpl(
394 const MatcherBase& m) {
395 // If the impl is a MatcherDescriberInterface, then return it.
396 // Otherwise use MatcherBase itself.
397 // This allows us to implement the GetDescriber() function without support
398 // from the impl, but some users really want to get their impl back when
399 // they call GetDescriber().
400 // We use std::get on a tuple as a workaround of not having `if constexpr`.
402 std::is_convertible<decltype(&P::Get(m)),
403 const MatcherDescriberInterface*>::value
405 : 0)>(std::make_tuple(&m, &P::Get(m)));
408 template <typename P>
409 const VTable* GetVTable() {
410 static constexpr VTable kVTable = {&MatchAndExplainImpl<P>,
411 &DescribeImpl<P>, &GetDescriberImpl<P>,
417 // Add some types to give Buffer some common alignment/size use cases.
421 // And add one for the out-of-line cases.
422 SharedPayloadBase* shared;
426 if (IsShared() && buffer_.shared->Unref()) {
427 vtable_->shared_destroy(buffer_.shared);
431 template <typename M>
432 static constexpr bool IsInlined() {
433 return sizeof(M) <= sizeof(Buffer) && alignof(M) <= alignof(Buffer) &&
434 std::is_trivially_copy_constructible<M>::value &&
435 std::is_trivially_destructible<M>::value;
438 template <typename M, bool = MatcherBase::IsInlined<M>()>
440 static const M& Get(const MatcherBase& m) {
441 // When inlined along with Init, need to be explicit to avoid violating
442 // strict aliasing rules.
444 static_cast<const M*>(static_cast<const void*>(&m.buffer_));
447 static void Init(MatcherBase& m, M impl) {
448 ::new (static_cast<void*>(&m.buffer_)) M(impl);
450 static constexpr auto shared_destroy = nullptr;
453 template <typename M>
454 struct ValuePolicy<M, false> {
455 using Shared = SharedPayload<M>;
456 static const M& Get(const MatcherBase& m) {
457 return static_cast<Shared*>(m.buffer_.shared)->value;
459 template <typename Arg>
460 static void Init(MatcherBase& m, Arg&& arg) {
461 m.buffer_.shared = new Shared(std::forward<Arg>(arg));
463 static constexpr auto shared_destroy = &Shared::Destroy;
466 template <typename U, bool B>
467 struct ValuePolicy<const MatcherInterface<U>*, B> {
468 using M = const MatcherInterface<U>;
469 using Shared = SharedPayload<std::unique_ptr<M>>;
470 static const M& Get(const MatcherBase& m) {
471 return *static_cast<Shared*>(m.buffer_.shared)->value;
473 static void Init(MatcherBase& m, M* impl) {
474 m.buffer_.shared = new Shared(std::unique_ptr<M>(impl));
477 static constexpr auto shared_destroy = &Shared::Destroy;
480 template <typename M>
482 using MM = typename std::decay<M>::type;
483 using Policy = ValuePolicy<MM>;
484 vtable_ = GetVTable<Policy>();
485 Policy::Init(*this, std::forward<M>(m));
488 const VTable* vtable_;
492 } // namespace internal
494 // A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
495 // object that can check whether a value of type T matches. The
496 // implementation of Matcher<T> is just a std::shared_ptr to const
497 // MatcherInterface<T>. Don't inherit from Matcher!
498 template <typename T>
499 class Matcher : public internal::MatcherBase<T> {
501 // Constructs a null matcher. Needed for storing Matcher objects in STL
502 // containers. A default-constructed matcher is not yet initialized. You
503 // cannot use it until a valid value has been assigned to it.
504 explicit Matcher() {} // NOLINT
506 // Constructs a matcher from its implementation.
507 explicit Matcher(const MatcherInterface<const T&>* impl)
508 : internal::MatcherBase<T>(impl) {}
510 template <typename U>
512 const MatcherInterface<U>* impl,
513 typename std::enable_if<!std::is_same<U, const U&>::value>::type* =
515 : internal::MatcherBase<T>(impl) {}
517 template <typename M, typename = typename std::remove_reference<
518 M>::type::is_gtest_matcher>
519 Matcher(M&& m) : internal::MatcherBase<T>(std::forward<M>(m)) {} // NOLINT
521 // Implicit constructor here allows people to write
522 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
523 Matcher(T value); // NOLINT
526 // The following two specializations allow the user to write str
527 // instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
528 // matcher is expected.
530 class GTEST_API_ Matcher<const std::string&>
531 : public internal::MatcherBase<const std::string&> {
535 explicit Matcher(const MatcherInterface<const std::string&>* impl)
536 : internal::MatcherBase<const std::string&>(impl) {}
538 template <typename M, typename = typename std::remove_reference<
539 M>::type::is_gtest_matcher>
540 Matcher(M&& m) // NOLINT
541 : internal::MatcherBase<const std::string&>(std::forward<M>(m)) {}
543 // Allows the user to write str instead of Eq(str) sometimes, where
544 // str is a std::string object.
545 Matcher(const std::string& s); // NOLINT
547 // Allows the user to write "foo" instead of Eq("foo") sometimes.
548 Matcher(const char* s); // NOLINT
552 class GTEST_API_ Matcher<std::string>
553 : public internal::MatcherBase<std::string> {
557 explicit Matcher(const MatcherInterface<const std::string&>* impl)
558 : internal::MatcherBase<std::string>(impl) {}
559 explicit Matcher(const MatcherInterface<std::string>* impl)
560 : internal::MatcherBase<std::string>(impl) {}
562 template <typename M, typename = typename std::remove_reference<
563 M>::type::is_gtest_matcher>
564 Matcher(M&& m) // NOLINT
565 : internal::MatcherBase<std::string>(std::forward<M>(m)) {}
567 // Allows the user to write str instead of Eq(str) sometimes, where
568 // str is a string object.
569 Matcher(const std::string& s); // NOLINT
571 // Allows the user to write "foo" instead of Eq("foo") sometimes.
572 Matcher(const char* s); // NOLINT
575 #if GTEST_INTERNAL_HAS_STRING_VIEW
576 // The following two specializations allow the user to write str
577 // instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
578 // matcher is expected.
580 class GTEST_API_ Matcher<const internal::StringView&>
581 : public internal::MatcherBase<const internal::StringView&> {
585 explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
586 : internal::MatcherBase<const internal::StringView&>(impl) {}
588 template <typename M, typename = typename std::remove_reference<
589 M>::type::is_gtest_matcher>
590 Matcher(M&& m) // NOLINT
591 : internal::MatcherBase<const internal::StringView&>(std::forward<M>(m)) {
594 // Allows the user to write str instead of Eq(str) sometimes, where
595 // str is a std::string object.
596 Matcher(const std::string& s); // NOLINT
598 // Allows the user to write "foo" instead of Eq("foo") sometimes.
599 Matcher(const char* s); // NOLINT
601 // Allows the user to pass absl::string_views or std::string_views directly.
602 Matcher(internal::StringView s); // NOLINT
606 class GTEST_API_ Matcher<internal::StringView>
607 : public internal::MatcherBase<internal::StringView> {
611 explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
612 : internal::MatcherBase<internal::StringView>(impl) {}
613 explicit Matcher(const MatcherInterface<internal::StringView>* impl)
614 : internal::MatcherBase<internal::StringView>(impl) {}
616 template <typename M, typename = typename std::remove_reference<
617 M>::type::is_gtest_matcher>
618 Matcher(M&& m) // NOLINT
619 : internal::MatcherBase<internal::StringView>(std::forward<M>(m)) {}
621 // Allows the user to write str instead of Eq(str) sometimes, where
622 // str is a std::string object.
623 Matcher(const std::string& s); // NOLINT
625 // Allows the user to write "foo" instead of Eq("foo") sometimes.
626 Matcher(const char* s); // NOLINT
628 // Allows the user to pass absl::string_views or std::string_views directly.
629 Matcher(internal::StringView s); // NOLINT
631 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
633 // Prints a matcher in a human-readable format.
634 template <typename T>
635 std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
636 matcher.DescribeTo(&os);
640 // The PolymorphicMatcher class template makes it easy to implement a
641 // polymorphic matcher (i.e. a matcher that can match values of more
642 // than one type, e.g. Eq(n) and NotNull()).
644 // To define a polymorphic matcher, a user should provide an Impl
645 // class that has a DescribeTo() method and a DescribeNegationTo()
646 // method, and define a member function (or member function template)
648 // bool MatchAndExplain(const Value& value,
649 // MatchResultListener* listener) const;
651 // See the definition of NotNull() for a complete example.
652 template <class Impl>
653 class PolymorphicMatcher {
655 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
657 // Returns a mutable reference to the underlying matcher
658 // implementation object.
659 Impl& mutable_impl() { return impl_; }
661 // Returns an immutable reference to the underlying matcher
662 // implementation object.
663 const Impl& impl() const { return impl_; }
665 template <typename T>
666 operator Matcher<T>() const {
667 return Matcher<T>(new MonomorphicImpl<const T&>(impl_));
671 template <typename T>
672 class MonomorphicImpl : public MatcherInterface<T> {
674 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
676 void DescribeTo(::std::ostream* os) const override { impl_.DescribeTo(os); }
678 void DescribeNegationTo(::std::ostream* os) const override {
679 impl_.DescribeNegationTo(os);
682 bool MatchAndExplain(T x, MatchResultListener* listener) const override {
683 return impl_.MatchAndExplain(x, listener);
693 // Creates a matcher from its implementation.
694 // DEPRECATED: Especially in the generic code, prefer:
695 // Matcher<T>(new MyMatcherImpl<const T&>(...));
697 // MakeMatcher may create a Matcher that accepts its argument by value, which
698 // leads to unnecessary copies & lack of support for non-copyable types.
699 template <typename T>
700 inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
701 return Matcher<T>(impl);
704 // Creates a polymorphic matcher from its implementation. This is
705 // easier to use than the PolymorphicMatcher<Impl> constructor as it
706 // doesn't require you to explicitly write the template argument, e.g.
708 // MakePolymorphicMatcher(foo);
710 // PolymorphicMatcher<TypeOfFoo>(foo);
711 template <class Impl>
712 inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
713 return PolymorphicMatcher<Impl>(impl);
717 // Implements a matcher that compares a given value with a
718 // pre-supplied value using one of the ==, <=, <, etc, operators. The
719 // two values being compared don't have to have the same type.
721 // The matcher defined here is polymorphic (for example, Eq(5) can be
722 // used to match an int, a short, a double, etc). Therefore we use
723 // a template type conversion operator in the implementation.
725 // The following template definition assumes that the Rhs parameter is
726 // a "bare" type (i.e. neither 'const T' nor 'T&').
727 template <typename D, typename Rhs, typename Op>
728 class ComparisonBase {
730 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
732 using is_gtest_matcher = void;
734 template <typename Lhs>
735 bool MatchAndExplain(const Lhs& lhs, std::ostream*) const {
736 return Op()(lhs, Unwrap(rhs_));
738 void DescribeTo(std::ostream* os) const {
739 *os << D::Desc() << " ";
740 UniversalPrint(Unwrap(rhs_), os);
742 void DescribeNegationTo(std::ostream* os) const {
743 *os << D::NegatedDesc() << " ";
744 UniversalPrint(Unwrap(rhs_), os);
748 template <typename T>
749 static const T& Unwrap(const T& v) {
752 template <typename T>
753 static const T& Unwrap(std::reference_wrapper<T> v) {
760 template <typename Rhs>
761 class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
763 explicit EqMatcher(const Rhs& rhs)
764 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) {}
765 static const char* Desc() { return "is equal to"; }
766 static const char* NegatedDesc() { return "isn't equal to"; }
768 template <typename Rhs>
769 class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
771 explicit NeMatcher(const Rhs& rhs)
772 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) {}
773 static const char* Desc() { return "isn't equal to"; }
774 static const char* NegatedDesc() { return "is equal to"; }
776 template <typename Rhs>
777 class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
779 explicit LtMatcher(const Rhs& rhs)
780 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) {}
781 static const char* Desc() { return "is <"; }
782 static const char* NegatedDesc() { return "isn't <"; }
784 template <typename Rhs>
785 class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
787 explicit GtMatcher(const Rhs& rhs)
788 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) {}
789 static const char* Desc() { return "is >"; }
790 static const char* NegatedDesc() { return "isn't >"; }
792 template <typename Rhs>
793 class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
795 explicit LeMatcher(const Rhs& rhs)
796 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) {}
797 static const char* Desc() { return "is <="; }
798 static const char* NegatedDesc() { return "isn't <="; }
800 template <typename Rhs>
801 class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
803 explicit GeMatcher(const Rhs& rhs)
804 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) {}
805 static const char* Desc() { return "is >="; }
806 static const char* NegatedDesc() { return "isn't >="; }
809 template <typename T, typename = typename std::enable_if<
810 std::is_constructible<std::string, T>::value>::type>
811 using StringLike = T;
813 // Implements polymorphic matchers MatchesRegex(regex) and
814 // ContainsRegex(regex), which can be used as a Matcher<T> as long as
815 // T can be converted to a string.
816 class MatchesRegexMatcher {
818 MatchesRegexMatcher(const RE* regex, bool full_match)
819 : regex_(regex), full_match_(full_match) {}
821 #if GTEST_INTERNAL_HAS_STRING_VIEW
822 bool MatchAndExplain(const internal::StringView& s,
823 MatchResultListener* listener) const {
824 return MatchAndExplain(std::string(s), listener);
826 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
828 // Accepts pointer types, particularly:
833 template <typename CharType>
834 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
835 return s != nullptr && MatchAndExplain(std::string(s), listener);
838 // Matches anything that can convert to std::string.
840 // This is a template, not just a plain function with const std::string&,
841 // because absl::string_view has some interfering non-explicit constructors.
842 template <class MatcheeStringType>
843 bool MatchAndExplain(const MatcheeStringType& s,
844 MatchResultListener* /* listener */) const {
845 const std::string& s2(s);
846 return full_match_ ? RE::FullMatch(s2, *regex_)
847 : RE::PartialMatch(s2, *regex_);
850 void DescribeTo(::std::ostream* os) const {
851 *os << (full_match_ ? "matches" : "contains") << " regular expression ";
852 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
855 void DescribeNegationTo(::std::ostream* os) const {
856 *os << "doesn't " << (full_match_ ? "match" : "contain")
857 << " regular expression ";
858 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
862 const std::shared_ptr<const RE> regex_;
863 const bool full_match_;
865 } // namespace internal
867 // Matches a string that fully matches regular expression 'regex'.
868 // The matcher takes ownership of 'regex'.
869 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
870 const internal::RE* regex) {
871 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
873 template <typename T = std::string>
874 PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
875 const internal::StringLike<T>& regex) {
876 return MatchesRegex(new internal::RE(std::string(regex)));
879 // Matches a string that contains regular expression 'regex'.
880 // The matcher takes ownership of 'regex'.
881 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
882 const internal::RE* regex) {
883 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
885 template <typename T = std::string>
886 PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
887 const internal::StringLike<T>& regex) {
888 return ContainsRegex(new internal::RE(std::string(regex)));
891 // Creates a polymorphic matcher that matches anything equal to x.
892 // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
894 template <typename T>
895 inline internal::EqMatcher<T> Eq(T x) {
896 return internal::EqMatcher<T>(x);
899 // Constructs a Matcher<T> from a 'value' of type T. The constructed
900 // matcher matches any value that's equal to 'value'.
901 template <typename T>
902 Matcher<T>::Matcher(T value) {
906 // Creates a monomorphic matcher that matches anything with type Lhs
907 // and equal to rhs. A user may need to use this instead of Eq(...)
908 // in order to resolve an overloading ambiguity.
910 // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
911 // or Matcher<T>(x), but more readable than the latter.
913 // We could define similar monomorphic matchers for other comparison
914 // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
915 // it yet as those are used much less than Eq() in practice. A user
916 // can always write Matcher<T>(Lt(5)) to be explicit about the type,
918 template <typename Lhs, typename Rhs>
919 inline Matcher<Lhs> TypedEq(const Rhs& rhs) {
923 // Creates a polymorphic matcher that matches anything >= x.
924 template <typename Rhs>
925 inline internal::GeMatcher<Rhs> Ge(Rhs x) {
926 return internal::GeMatcher<Rhs>(x);
929 // Creates a polymorphic matcher that matches anything > x.
930 template <typename Rhs>
931 inline internal::GtMatcher<Rhs> Gt(Rhs x) {
932 return internal::GtMatcher<Rhs>(x);
935 // Creates a polymorphic matcher that matches anything <= x.
936 template <typename Rhs>
937 inline internal::LeMatcher<Rhs> Le(Rhs x) {
938 return internal::LeMatcher<Rhs>(x);
941 // Creates a polymorphic matcher that matches anything < x.
942 template <typename Rhs>
943 inline internal::LtMatcher<Rhs> Lt(Rhs x) {
944 return internal::LtMatcher<Rhs>(x);
947 // Creates a polymorphic matcher that matches anything != x.
948 template <typename Rhs>
949 inline internal::NeMatcher<Rhs> Ne(Rhs x) {
950 return internal::NeMatcher<Rhs>(x);
952 } // namespace testing
954 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
956 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_