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 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
36 #define GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
42 #include <type_traits>
44 #include "gtest/gtest-printers.h"
45 #include "gtest/internal/gtest-internal.h"
46 #include "gtest/internal/gtest-port.h"
48 // MSVC warning C5046 is new as of VS2017 version 15.8.
49 #if defined(_MSC_VER) && _MSC_VER >= 1915
50 #define GTEST_MAYBE_5046_ 5046
52 #define GTEST_MAYBE_5046_
55 GTEST_DISABLE_MSC_WARNINGS_PUSH_(
56 4251 GTEST_MAYBE_5046_ /* class A needs to have dll-interface to be used by
58 /* Symbol involving type with internal linkage not defined */)
62 // To implement a matcher Foo for type T, define:
63 // 1. a class FooMatcherMatcher that implements the matcher interface:
64 // using is_gtest_matcher = void;
65 // bool MatchAndExplain(const T&, std::ostream*);
66 // (MatchResultListener* can also be used instead of std::ostream*)
67 // void DescribeTo(std::ostream*);
68 // void DescribeNegationTo(std::ostream*);
70 // 2. a factory function that creates a Matcher<T> object from a
73 class MatchResultListener {
75 // Creates a listener object with the given underlying ostream. The
76 // listener does not own the ostream, and does not dereference it
77 // in the constructor or destructor.
78 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
79 virtual ~MatchResultListener() = 0; // Makes this class abstract.
81 // Streams x to the underlying ostream; does nothing if the ostream
84 MatchResultListener& operator<<(const T& x) {
85 if (stream_ != nullptr) *stream_ << x;
89 // Returns the underlying ostream.
90 ::std::ostream* stream() { return stream_; }
92 // Returns true if and only if the listener is interested in an explanation
93 // of the match result. A matcher's MatchAndExplain() method can use
94 // this information to avoid generating the explanation when no one
95 // intends to hear it.
96 bool IsInterested() const { return stream_ != nullptr; }
99 ::std::ostream* const stream_;
101 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
104 inline MatchResultListener::~MatchResultListener() {
107 // An instance of a subclass of this knows how to describe itself as a
109 class GTEST_API_ MatcherDescriberInterface {
111 virtual ~MatcherDescriberInterface() {}
113 // Describes this matcher to an ostream. The function should print
114 // a verb phrase that describes the property a value matching this
115 // matcher should have. The subject of the verb phrase is the value
116 // being matched. For example, the DescribeTo() method of the Gt(7)
117 // matcher prints "is greater than 7".
118 virtual void DescribeTo(::std::ostream* os) const = 0;
120 // Describes the negation of this matcher to an ostream. For
121 // example, if the description of this matcher is "is greater than
122 // 7", the negated description could be "is not greater than 7".
123 // You are not required to override this when implementing
124 // MatcherInterface, but it is highly advised so that your matcher
125 // can produce good error messages.
126 virtual void DescribeNegationTo(::std::ostream* os) const {
133 // The implementation of a matcher.
134 template <typename T>
135 class MatcherInterface : public MatcherDescriberInterface {
137 // Returns true if and only if the matcher matches x; also explains the
138 // match result to 'listener' if necessary (see the next paragraph), in
139 // the form of a non-restrictive relative clause ("which ...",
140 // "whose ...", etc) that describes x. For example, the
141 // MatchAndExplain() method of the Pointee(...) matcher should
142 // generate an explanation like "which points to ...".
144 // Implementations of MatchAndExplain() should add an explanation of
145 // the match result *if and only if* they can provide additional
146 // information that's not already present (or not obvious) in the
147 // print-out of x and the matcher's description. Whether the match
148 // succeeds is not a factor in deciding whether an explanation is
149 // needed, as sometimes the caller needs to print a failure message
150 // when the match succeeds (e.g. when the matcher is used inside
153 // For example, a "has at least 10 elements" matcher should explain
154 // what the actual element count is, regardless of the match result,
155 // as it is useful information to the reader; on the other hand, an
156 // "is empty" matcher probably only needs to explain what the actual
157 // size is when the match fails, as it's redundant to say that the
158 // size is 0 when the value is already known to be empty.
160 // You should override this method when defining a new matcher.
162 // It's the responsibility of the caller (Google Test) to guarantee
163 // that 'listener' is not NULL. This helps to simplify a matcher's
164 // implementation when it doesn't care about the performance, as it
165 // can talk to 'listener' without checking its validity first.
166 // However, in order to implement dummy listeners efficiently,
167 // listener->stream() may be NULL.
168 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
170 // Inherits these methods from MatcherDescriberInterface:
171 // virtual void DescribeTo(::std::ostream* os) const = 0;
172 // virtual void DescribeNegationTo(::std::ostream* os) const;
178 template <typename A, typename B>
179 bool operator()(const A& a, const B& b) const { return a == b; }
182 template <typename A, typename B>
183 bool operator()(const A& a, const B& b) const { return a != b; }
186 template <typename A, typename B>
187 bool operator()(const A& a, const B& b) const { return a < b; }
190 template <typename A, typename B>
191 bool operator()(const A& a, const B& b) const { return a > b; }
194 template <typename A, typename B>
195 bool operator()(const A& a, const B& b) const { return a <= b; }
198 template <typename A, typename B>
199 bool operator()(const A& a, const B& b) const { return a >= b; }
202 // A match result listener that ignores the explanation.
203 class DummyMatchResultListener : public MatchResultListener {
205 DummyMatchResultListener() : MatchResultListener(nullptr) {}
208 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
211 // A match result listener that forwards the explanation to a given
212 // ostream. The difference between this and MatchResultListener is
213 // that the former is concrete.
214 class StreamMatchResultListener : public MatchResultListener {
216 explicit StreamMatchResultListener(::std::ostream* os)
217 : MatchResultListener(os) {}
220 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
223 struct SharedPayloadBase {
224 std::atomic<int> ref{1};
225 void Ref() { ref.fetch_add(1, std::memory_order_relaxed); }
226 bool Unref() { return ref.fetch_sub(1, std::memory_order_acq_rel) == 1; }
229 template <typename T>
230 struct SharedPayload : SharedPayloadBase {
231 explicit SharedPayload(const T& v) : value(v) {}
232 explicit SharedPayload(T&& v) : value(std::move(v)) {}
234 static void Destroy(SharedPayloadBase* shared) {
235 delete static_cast<SharedPayload*>(shared);
241 // An internal class for implementing Matcher<T>, which will derive
242 // from it. We put functionalities common to all Matcher<T>
243 // specializations here to avoid code duplication.
244 template <typename T>
245 class MatcherBase : private MatcherDescriberInterface {
247 // Returns true if and only if the matcher matches x; also explains the
248 // match result to 'listener'.
249 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
250 GTEST_CHECK_(vtable_ != nullptr);
251 return vtable_->match_and_explain(*this, x, listener);
254 // Returns true if and only if this matcher matches x.
255 bool Matches(const T& x) const {
256 DummyMatchResultListener dummy;
257 return MatchAndExplain(x, &dummy);
260 // Describes this matcher to an ostream.
261 void DescribeTo(::std::ostream* os) const final {
262 GTEST_CHECK_(vtable_ != nullptr);
263 vtable_->describe(*this, os, false);
266 // Describes the negation of this matcher to an ostream.
267 void DescribeNegationTo(::std::ostream* os) const final {
268 GTEST_CHECK_(vtable_ != nullptr);
269 vtable_->describe(*this, os, true);
272 // Explains why x matches, or doesn't match, the matcher.
273 void ExplainMatchResultTo(const T& x, ::std::ostream* os) const {
274 StreamMatchResultListener listener(os);
275 MatchAndExplain(x, &listener);
278 // Returns the describer for this matcher object; retains ownership
279 // of the describer, which is only guaranteed to be alive when
280 // this matcher object is alive.
281 const MatcherDescriberInterface* GetDescriber() const {
282 if (vtable_ == nullptr) return nullptr;
283 return vtable_->get_describer(*this);
287 MatcherBase() : vtable_(nullptr) {}
289 // Constructs a matcher from its implementation.
290 template <typename U>
291 explicit MatcherBase(const MatcherInterface<U>* impl) {
295 template <typename M, typename = typename std::remove_reference<
296 M>::type::is_gtest_matcher>
297 MatcherBase(M&& m) { // NOLINT
298 Init(std::forward<M>(m));
301 MatcherBase(const MatcherBase& other)
302 : vtable_(other.vtable_), buffer_(other.buffer_) {
303 #ifndef __clang_analyzer__
304 if (IsShared()) buffer_.shared->Ref();
308 MatcherBase& operator=(const MatcherBase& other) {
309 if (this == &other) return *this;
311 vtable_ = other.vtable_;
312 buffer_ = other.buffer_;
313 if (IsShared()) buffer_.shared->Ref();
317 MatcherBase(MatcherBase&& other)
318 : vtable_(other.vtable_), buffer_(other.buffer_) {
319 other.vtable_ = nullptr;
322 MatcherBase& operator=(MatcherBase&& other) {
323 if (this == &other) return *this;
325 vtable_ = other.vtable_;
326 buffer_ = other.buffer_;
327 other.vtable_ = nullptr;
331 ~MatcherBase() override { Destroy(); }
335 bool (*match_and_explain)(const MatcherBase&, const T&,
336 MatchResultListener*);
337 void (*describe)(const MatcherBase&, std::ostream*, bool negation);
338 // Returns the captured object if it implements the interface, otherwise
339 // returns the MatcherBase itself.
340 const MatcherDescriberInterface* (*get_describer)(const MatcherBase&);
341 // Called on shared instances when the reference count reaches 0.
342 void (*shared_destroy)(SharedPayloadBase*);
345 bool IsShared() const {
346 return vtable_ != nullptr && vtable_->shared_destroy != nullptr;
349 // If the implementation uses a listener, call that.
350 template <typename P>
351 static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
352 MatchResultListener* listener)
353 -> decltype(P::Get(m).MatchAndExplain(value, listener->stream())) {
354 return P::Get(m).MatchAndExplain(value, listener->stream());
357 template <typename P>
358 static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,
359 MatchResultListener* listener)
360 -> decltype(P::Get(m).MatchAndExplain(value, listener)) {
361 return P::Get(m).MatchAndExplain(value, listener);
364 template <typename P>
365 static void DescribeImpl(const MatcherBase& m, std::ostream* os,
368 P::Get(m).DescribeNegationTo(os);
370 P::Get(m).DescribeTo(os);
374 template <typename P>
375 static const MatcherDescriberInterface* GetDescriberImpl(
376 const MatcherBase& m) {
377 // If the impl is a MatcherDescriberInterface, then return it.
378 // Otherwise use MatcherBase itself.
379 // This allows us to implement the GetDescriber() function without support
380 // from the impl, but some users really want to get their impl back when
381 // they call GetDescriber().
382 // We use std::get on a tuple as a workaround of not having `if constexpr`.
384 std::is_convertible<decltype(&P::Get(m)),
385 const MatcherDescriberInterface*>::value
387 : 0)>(std::make_tuple(&m, &P::Get(m)));
390 template <typename P>
391 const VTable* GetVTable() {
392 static constexpr VTable kVTable = {&MatchAndExplainImpl<P>,
393 &DescribeImpl<P>, &GetDescriberImpl<P>,
399 // Add some types to give Buffer some common alignment/size use cases.
403 // And add one for the out-of-line cases.
404 SharedPayloadBase* shared;
408 #ifndef __clang_analyzer__
409 if (IsShared() && buffer_.shared->Unref()) {
410 vtable_->shared_destroy(buffer_.shared);
415 template <typename M>
416 static constexpr bool IsInlined() {
417 return sizeof(M) <= sizeof(Buffer) && alignof(M) <= alignof(Buffer) &&
418 std::is_trivially_copy_constructible<M>::value &&
419 std::is_trivially_destructible<M>::value;
422 template <typename M, bool = MatcherBase::IsInlined<M>()>
424 static const M& Get(const MatcherBase& m) {
425 // When inlined along with Init, need to be explicit to avoid violating
426 // strict aliasing rules.
427 const M *ptr = static_cast<const M*>(
428 static_cast<const void*>(&m.buffer_));
431 static void Init(MatcherBase& m, M impl) {
432 ::new (static_cast<void*>(&m.buffer_)) M(impl);
434 static constexpr auto shared_destroy = nullptr;
437 template <typename M>
438 struct ValuePolicy<M, false> {
439 using Shared = SharedPayload<M>;
440 static const M& Get(const MatcherBase& m) {
441 return static_cast<Shared*>(m.buffer_.shared)->value;
443 template <typename Arg>
444 static void Init(MatcherBase& m, Arg&& arg) {
445 m.buffer_.shared = new Shared(std::forward<Arg>(arg));
447 static constexpr auto shared_destroy = &Shared::Destroy;
450 template <typename U, bool B>
451 struct ValuePolicy<const MatcherInterface<U>*, B> {
452 using M = const MatcherInterface<U>;
453 using Shared = SharedPayload<std::unique_ptr<M>>;
454 static const M& Get(const MatcherBase& m) {
455 return *static_cast<Shared*>(m.buffer_.shared)->value;
457 static void Init(MatcherBase& m, M* impl) {
458 m.buffer_.shared = new Shared(std::unique_ptr<M>(impl));
461 static constexpr auto shared_destroy = &Shared::Destroy;
464 template <typename M>
466 using MM = typename std::decay<M>::type;
467 using Policy = ValuePolicy<MM>;
468 vtable_ = GetVTable<Policy>();
469 Policy::Init(*this, std::forward<M>(m));
472 const VTable* vtable_;
476 } // namespace internal
478 // A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
479 // object that can check whether a value of type T matches. The
480 // implementation of Matcher<T> is just a std::shared_ptr to const
481 // MatcherInterface<T>. Don't inherit from Matcher!
482 template <typename T>
483 class Matcher : public internal::MatcherBase<T> {
485 // Constructs a null matcher. Needed for storing Matcher objects in STL
486 // containers. A default-constructed matcher is not yet initialized. You
487 // cannot use it until a valid value has been assigned to it.
488 explicit Matcher() {} // NOLINT
490 // Constructs a matcher from its implementation.
491 explicit Matcher(const MatcherInterface<const T&>* impl)
492 : internal::MatcherBase<T>(impl) {}
494 template <typename U>
496 const MatcherInterface<U>* impl,
497 typename std::enable_if<!std::is_same<U, const U&>::value>::type* =
499 : internal::MatcherBase<T>(impl) {}
501 template <typename M, typename = typename std::remove_reference<
502 M>::type::is_gtest_matcher>
503 Matcher(M&& m) : internal::MatcherBase<T>(std::forward<M>(m)) {} // NOLINT
505 // Implicit constructor here allows people to write
506 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
507 Matcher(T value); // NOLINT
510 // The following two specializations allow the user to write str
511 // instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
512 // matcher is expected.
514 class GTEST_API_ Matcher<const std::string&>
515 : public internal::MatcherBase<const std::string&> {
519 explicit Matcher(const MatcherInterface<const std::string&>* impl)
520 : internal::MatcherBase<const std::string&>(impl) {}
522 template <typename M, typename = typename std::remove_reference<
523 M>::type::is_gtest_matcher>
524 Matcher(M&& m) // NOLINT
525 : internal::MatcherBase<const std::string&>(std::forward<M>(m)) {}
527 // Allows the user to write str instead of Eq(str) sometimes, where
528 // str is a std::string object.
529 Matcher(const std::string& s); // NOLINT
531 // Allows the user to write "foo" instead of Eq("foo") sometimes.
532 Matcher(const char* s); // NOLINT
536 class GTEST_API_ Matcher<std::string>
537 : public internal::MatcherBase<std::string> {
541 explicit Matcher(const MatcherInterface<const std::string&>* impl)
542 : internal::MatcherBase<std::string>(impl) {}
543 explicit Matcher(const MatcherInterface<std::string>* impl)
544 : internal::MatcherBase<std::string>(impl) {}
546 template <typename M, typename = typename std::remove_reference<
547 M>::type::is_gtest_matcher>
548 Matcher(M&& m) // NOLINT
549 : internal::MatcherBase<std::string>(std::forward<M>(m)) {}
551 // Allows the user to write str instead of Eq(str) sometimes, where
552 // str is a string object.
553 Matcher(const std::string& s); // NOLINT
555 // Allows the user to write "foo" instead of Eq("foo") sometimes.
556 Matcher(const char* s); // NOLINT
559 #if GTEST_INTERNAL_HAS_STRING_VIEW
560 // The following two specializations allow the user to write str
561 // instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
562 // matcher is expected.
564 class GTEST_API_ Matcher<const internal::StringView&>
565 : public internal::MatcherBase<const internal::StringView&> {
569 explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
570 : internal::MatcherBase<const internal::StringView&>(impl) {}
572 template <typename M, typename = typename std::remove_reference<
573 M>::type::is_gtest_matcher>
574 Matcher(M&& m) // NOLINT
575 : internal::MatcherBase<const internal::StringView&>(std::forward<M>(m)) {
578 // Allows the user to write str instead of Eq(str) sometimes, where
579 // str is a std::string object.
580 Matcher(const std::string& s); // NOLINT
582 // Allows the user to write "foo" instead of Eq("foo") sometimes.
583 Matcher(const char* s); // NOLINT
585 // Allows the user to pass absl::string_views or std::string_views directly.
586 Matcher(internal::StringView s); // NOLINT
590 class GTEST_API_ Matcher<internal::StringView>
591 : public internal::MatcherBase<internal::StringView> {
595 explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)
596 : internal::MatcherBase<internal::StringView>(impl) {}
597 explicit Matcher(const MatcherInterface<internal::StringView>* impl)
598 : internal::MatcherBase<internal::StringView>(impl) {}
600 template <typename M, typename = typename std::remove_reference<
601 M>::type::is_gtest_matcher>
602 Matcher(M&& m) // NOLINT
603 : internal::MatcherBase<internal::StringView>(std::forward<M>(m)) {}
605 // Allows the user to write str instead of Eq(str) sometimes, where
606 // str is a std::string object.
607 Matcher(const std::string& s); // NOLINT
609 // Allows the user to write "foo" instead of Eq("foo") sometimes.
610 Matcher(const char* s); // NOLINT
612 // Allows the user to pass absl::string_views or std::string_views directly.
613 Matcher(internal::StringView s); // NOLINT
615 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
617 // Prints a matcher in a human-readable format.
618 template <typename T>
619 std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
620 matcher.DescribeTo(&os);
624 // The PolymorphicMatcher class template makes it easy to implement a
625 // polymorphic matcher (i.e. a matcher that can match values of more
626 // than one type, e.g. Eq(n) and NotNull()).
628 // To define a polymorphic matcher, a user should provide an Impl
629 // class that has a DescribeTo() method and a DescribeNegationTo()
630 // method, and define a member function (or member function template)
632 // bool MatchAndExplain(const Value& value,
633 // MatchResultListener* listener) const;
635 // See the definition of NotNull() for a complete example.
636 template <class Impl>
637 class PolymorphicMatcher {
639 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
641 // Returns a mutable reference to the underlying matcher
642 // implementation object.
643 Impl& mutable_impl() { return impl_; }
645 // Returns an immutable reference to the underlying matcher
646 // implementation object.
647 const Impl& impl() const { return impl_; }
649 template <typename T>
650 operator Matcher<T>() const {
651 return Matcher<T>(new MonomorphicImpl<const T&>(impl_));
655 template <typename T>
656 class MonomorphicImpl : public MatcherInterface<T> {
658 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
660 void DescribeTo(::std::ostream* os) const override { impl_.DescribeTo(os); }
662 void DescribeNegationTo(::std::ostream* os) const override {
663 impl_.DescribeNegationTo(os);
666 bool MatchAndExplain(T x, MatchResultListener* listener) const override {
667 return impl_.MatchAndExplain(x, listener);
677 // Creates a matcher from its implementation.
678 // DEPRECATED: Especially in the generic code, prefer:
679 // Matcher<T>(new MyMatcherImpl<const T&>(...));
681 // MakeMatcher may create a Matcher that accepts its argument by value, which
682 // leads to unnecessary copies & lack of support for non-copyable types.
683 template <typename T>
684 inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
685 return Matcher<T>(impl);
688 // Creates a polymorphic matcher from its implementation. This is
689 // easier to use than the PolymorphicMatcher<Impl> constructor as it
690 // doesn't require you to explicitly write the template argument, e.g.
692 // MakePolymorphicMatcher(foo);
694 // PolymorphicMatcher<TypeOfFoo>(foo);
695 template <class Impl>
696 inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
697 return PolymorphicMatcher<Impl>(impl);
701 // Implements a matcher that compares a given value with a
702 // pre-supplied value using one of the ==, <=, <, etc, operators. The
703 // two values being compared don't have to have the same type.
705 // The matcher defined here is polymorphic (for example, Eq(5) can be
706 // used to match an int, a short, a double, etc). Therefore we use
707 // a template type conversion operator in the implementation.
709 // The following template definition assumes that the Rhs parameter is
710 // a "bare" type (i.e. neither 'const T' nor 'T&').
711 template <typename D, typename Rhs, typename Op>
712 class ComparisonBase {
714 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
716 using is_gtest_matcher = void;
718 template <typename Lhs>
719 bool MatchAndExplain(const Lhs& lhs, std::ostream*) const {
720 return Op()(lhs, Unwrap(rhs_));
722 void DescribeTo(std::ostream* os) const {
723 *os << D::Desc() << " ";
724 UniversalPrint(Unwrap(rhs_), os);
726 void DescribeNegationTo(std::ostream* os) const {
727 *os << D::NegatedDesc() << " ";
728 UniversalPrint(Unwrap(rhs_), os);
732 template <typename T>
733 static const T& Unwrap(const T& v) {
736 template <typename T>
737 static const T& Unwrap(std::reference_wrapper<T> v) {
744 template <typename Rhs>
745 class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
747 explicit EqMatcher(const Rhs& rhs)
748 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
749 static const char* Desc() { return "is equal to"; }
750 static const char* NegatedDesc() { return "isn't equal to"; }
752 template <typename Rhs>
753 class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
755 explicit NeMatcher(const Rhs& rhs)
756 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
757 static const char* Desc() { return "isn't equal to"; }
758 static const char* NegatedDesc() { return "is equal to"; }
760 template <typename Rhs>
761 class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
763 explicit LtMatcher(const Rhs& rhs)
764 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
765 static const char* Desc() { return "is <"; }
766 static const char* NegatedDesc() { return "isn't <"; }
768 template <typename Rhs>
769 class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
771 explicit GtMatcher(const Rhs& rhs)
772 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
773 static const char* Desc() { return "is >"; }
774 static const char* NegatedDesc() { return "isn't >"; }
776 template <typename Rhs>
777 class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
779 explicit LeMatcher(const Rhs& rhs)
780 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
781 static const char* Desc() { return "is <="; }
782 static const char* NegatedDesc() { return "isn't <="; }
784 template <typename Rhs>
785 class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
787 explicit GeMatcher(const Rhs& rhs)
788 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
789 static const char* Desc() { return "is >="; }
790 static const char* NegatedDesc() { return "isn't >="; }
793 template <typename T, typename = typename std::enable_if<
794 std::is_constructible<std::string, T>::value>::type>
795 using StringLike = T;
797 // Implements polymorphic matchers MatchesRegex(regex) and
798 // ContainsRegex(regex), which can be used as a Matcher<T> as long as
799 // T can be converted to a string.
800 class MatchesRegexMatcher {
802 MatchesRegexMatcher(const RE* regex, bool full_match)
803 : regex_(regex), full_match_(full_match) {}
805 #if GTEST_INTERNAL_HAS_STRING_VIEW
806 bool MatchAndExplain(const internal::StringView& s,
807 MatchResultListener* listener) const {
808 return MatchAndExplain(std::string(s), listener);
810 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
812 // Accepts pointer types, particularly:
817 template <typename CharType>
818 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
819 return s != nullptr && MatchAndExplain(std::string(s), listener);
822 // Matches anything that can convert to std::string.
824 // This is a template, not just a plain function with const std::string&,
825 // because absl::string_view has some interfering non-explicit constructors.
826 template <class MatcheeStringType>
827 bool MatchAndExplain(const MatcheeStringType& s,
828 MatchResultListener* /* listener */) const {
829 const std::string& s2(s);
830 return full_match_ ? RE::FullMatch(s2, *regex_)
831 : RE::PartialMatch(s2, *regex_);
834 void DescribeTo(::std::ostream* os) const {
835 *os << (full_match_ ? "matches" : "contains") << " regular expression ";
836 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
839 void DescribeNegationTo(::std::ostream* os) const {
840 *os << "doesn't " << (full_match_ ? "match" : "contain")
841 << " regular expression ";
842 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
846 const std::shared_ptr<const RE> regex_;
847 const bool full_match_;
849 } // namespace internal
851 // Matches a string that fully matches regular expression 'regex'.
852 // The matcher takes ownership of 'regex'.
853 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
854 const internal::RE* regex) {
855 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
857 template <typename T = std::string>
858 PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
859 const internal::StringLike<T>& regex) {
860 return MatchesRegex(new internal::RE(std::string(regex)));
863 // Matches a string that contains regular expression 'regex'.
864 // The matcher takes ownership of 'regex'.
865 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
866 const internal::RE* regex) {
867 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
869 template <typename T = std::string>
870 PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
871 const internal::StringLike<T>& regex) {
872 return ContainsRegex(new internal::RE(std::string(regex)));
875 // Creates a polymorphic matcher that matches anything equal to x.
876 // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
878 template <typename T>
879 inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
881 // Constructs a Matcher<T> from a 'value' of type T. The constructed
882 // matcher matches any value that's equal to 'value'.
883 template <typename T>
884 Matcher<T>::Matcher(T value) { *this = Eq(value); }
886 // Creates a monomorphic matcher that matches anything with type Lhs
887 // and equal to rhs. A user may need to use this instead of Eq(...)
888 // in order to resolve an overloading ambiguity.
890 // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
891 // or Matcher<T>(x), but more readable than the latter.
893 // We could define similar monomorphic matchers for other comparison
894 // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
895 // it yet as those are used much less than Eq() in practice. A user
896 // can always write Matcher<T>(Lt(5)) to be explicit about the type,
898 template <typename Lhs, typename Rhs>
899 inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
901 // Creates a polymorphic matcher that matches anything >= x.
902 template <typename Rhs>
903 inline internal::GeMatcher<Rhs> Ge(Rhs x) {
904 return internal::GeMatcher<Rhs>(x);
907 // Creates a polymorphic matcher that matches anything > x.
908 template <typename Rhs>
909 inline internal::GtMatcher<Rhs> Gt(Rhs x) {
910 return internal::GtMatcher<Rhs>(x);
913 // Creates a polymorphic matcher that matches anything <= x.
914 template <typename Rhs>
915 inline internal::LeMatcher<Rhs> Le(Rhs x) {
916 return internal::LeMatcher<Rhs>(x);
919 // Creates a polymorphic matcher that matches anything < x.
920 template <typename Rhs>
921 inline internal::LtMatcher<Rhs> Lt(Rhs x) {
922 return internal::LtMatcher<Rhs>(x);
925 // Creates a polymorphic matcher that matches anything != x.
926 template <typename Rhs>
927 inline internal::NeMatcher<Rhs> Ne(Rhs x) {
928 return internal::NeMatcher<Rhs>(x);
930 } // namespace testing
932 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
934 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_