1 // Copyright 2007, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30 // The Google C++ Testing and Mocking Framework (Google Test)
31 //
32 // This file implements just enough of the matcher interface to allow
33 // EXPECT_DEATH and friends to accept a matcher argument.
34
35 // IWYU pragma: private, include "testing/base/public/gunit.h"
36 // IWYU pragma: friend third_party/googletest/googlemock/.*
37 // IWYU pragma: friend third_party/googletest/googletest/.*
38
39 #ifndef GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
40 #define GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
41
42 #include <memory>
43 #include <ostream>
44 #include <string>
45
46 #include "gtest/gtest-printers.h"
47 #include "gtest/internal/gtest-internal.h"
48 #include "gtest/internal/gtest-port.h"
49
50 // MSVC warning C5046 is new as of VS2017 version 15.8.
51 #if defined(_MSC_VER) && _MSC_VER >= 1915
52 #define GTEST_MAYBE_5046_ 5046
53 #else
54 #define GTEST_MAYBE_5046_
55 #endif
56
57 GTEST_DISABLE_MSC_WARNINGS_PUSH_(
58 4251 GTEST_MAYBE_5046_ /* class A needs to have dll-interface to be used by
59 clients of class B */
60 /* Symbol involving type with internal linkage not defined */)
61
62 namespace testing {
63
64 // To implement a matcher Foo for type T, define:
65 // 1. a class FooMatcherImpl that implements the
66 // MatcherInterface<T> interface, and
67 // 2. a factory function that creates a Matcher<T> object from a
68 // FooMatcherImpl*.
69 //
70 // The two-level delegation design makes it possible to allow a user
71 // to write "v" instead of "Eq(v)" where a Matcher is expected, which
72 // is impossible if we pass matchers by pointers. It also eases
73 // ownership management as Matcher objects can now be copied like
74 // plain values.
75
76 // MatchResultListener is an abstract class. Its << operator can be
77 // used by a matcher to explain why a value matches or doesn't match.
78 //
79 class MatchResultListener {
80 public:
81 // Creates a listener object with the given underlying ostream. The
82 // listener does not own the ostream, and does not dereference it
83 // in the constructor or destructor.
MatchResultListener(::std::ostream * os)84 explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
85 virtual ~MatchResultListener() = 0; // Makes this class abstract.
86
87 // Streams x to the underlying ostream; does nothing if the ostream
88 // is NULL.
89 template <typename T>
90 MatchResultListener& operator<<(const T& x) {
91 if (stream_ != nullptr) *stream_ << x;
92 return *this;
93 }
94
95 // Returns the underlying ostream.
stream()96 ::std::ostream* stream() { return stream_; }
97
98 // Returns true iff the listener is interested in an explanation of
99 // the match result. A matcher's MatchAndExplain() method can use
100 // this information to avoid generating the explanation when no one
101 // intends to hear it.
IsInterested()102 bool IsInterested() const { return stream_ != nullptr; }
103
104 private:
105 ::std::ostream* const stream_;
106
107 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
108 };
109
~MatchResultListener()110 inline MatchResultListener::~MatchResultListener() {
111 }
112
113 // An instance of a subclass of this knows how to describe itself as a
114 // matcher.
115 class MatcherDescriberInterface {
116 public:
~MatcherDescriberInterface()117 virtual ~MatcherDescriberInterface() {}
118
119 // Describes this matcher to an ostream. The function should print
120 // a verb phrase that describes the property a value matching this
121 // matcher should have. The subject of the verb phrase is the value
122 // being matched. For example, the DescribeTo() method of the Gt(7)
123 // matcher prints "is greater than 7".
124 virtual void DescribeTo(::std::ostream* os) const = 0;
125
126 // Describes the negation of this matcher to an ostream. For
127 // example, if the description of this matcher is "is greater than
128 // 7", the negated description could be "is not greater than 7".
129 // You are not required to override this when implementing
130 // MatcherInterface, but it is highly advised so that your matcher
131 // can produce good error messages.
DescribeNegationTo(::std::ostream * os)132 virtual void DescribeNegationTo(::std::ostream* os) const {
133 *os << "not (";
134 DescribeTo(os);
135 *os << ")";
136 }
137 };
138
139 // The implementation of a matcher.
140 template <typename T>
141 class MatcherInterface : public MatcherDescriberInterface {
142 public:
143 // Returns true iff the matcher matches x; also explains the match
144 // result to 'listener' if necessary (see the next paragraph), in
145 // the form of a non-restrictive relative clause ("which ...",
146 // "whose ...", etc) that describes x. For example, the
147 // MatchAndExplain() method of the Pointee(...) matcher should
148 // generate an explanation like "which points to ...".
149 //
150 // Implementations of MatchAndExplain() should add an explanation of
151 // the match result *if and only if* they can provide additional
152 // information that's not already present (or not obvious) in the
153 // print-out of x and the matcher's description. Whether the match
154 // succeeds is not a factor in deciding whether an explanation is
155 // needed, as sometimes the caller needs to print a failure message
156 // when the match succeeds (e.g. when the matcher is used inside
157 // Not()).
158 //
159 // For example, a "has at least 10 elements" matcher should explain
160 // what the actual element count is, regardless of the match result,
161 // as it is useful information to the reader; on the other hand, an
162 // "is empty" matcher probably only needs to explain what the actual
163 // size is when the match fails, as it's redundant to say that the
164 // size is 0 when the value is already known to be empty.
165 //
166 // You should override this method when defining a new matcher.
167 //
168 // It's the responsibility of the caller (Google Test) to guarantee
169 // that 'listener' is not NULL. This helps to simplify a matcher's
170 // implementation when it doesn't care about the performance, as it
171 // can talk to 'listener' without checking its validity first.
172 // However, in order to implement dummy listeners efficiently,
173 // listener->stream() may be NULL.
174 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
175
176 // Inherits these methods from MatcherDescriberInterface:
177 // virtual void DescribeTo(::std::ostream* os) const = 0;
178 // virtual void DescribeNegationTo(::std::ostream* os) const;
179 };
180
181 namespace internal {
182
183 // Converts a MatcherInterface<T> to a MatcherInterface<const T&>.
184 template <typename T>
185 class MatcherInterfaceAdapter : public MatcherInterface<const T&> {
186 public:
MatcherInterfaceAdapter(const MatcherInterface<T> * impl)187 explicit MatcherInterfaceAdapter(const MatcherInterface<T>* impl)
188 : impl_(impl) {}
~MatcherInterfaceAdapter()189 ~MatcherInterfaceAdapter() override { delete impl_; }
190
DescribeTo(::std::ostream * os)191 void DescribeTo(::std::ostream* os) const override { impl_->DescribeTo(os); }
192
DescribeNegationTo(::std::ostream * os)193 void DescribeNegationTo(::std::ostream* os) const override {
194 impl_->DescribeNegationTo(os);
195 }
196
MatchAndExplain(const T & x,MatchResultListener * listener)197 bool MatchAndExplain(const T& x,
198 MatchResultListener* listener) const override {
199 return impl_->MatchAndExplain(x, listener);
200 }
201
202 private:
203 const MatcherInterface<T>* const impl_;
204
205 GTEST_DISALLOW_COPY_AND_ASSIGN_(MatcherInterfaceAdapter);
206 };
207
208 struct AnyEq {
209 template <typename A, typename B>
operatorAnyEq210 bool operator()(const A& a, const B& b) const { return a == b; }
211 };
212 struct AnyNe {
213 template <typename A, typename B>
operatorAnyNe214 bool operator()(const A& a, const B& b) const { return a != b; }
215 };
216 struct AnyLt {
217 template <typename A, typename B>
operatorAnyLt218 bool operator()(const A& a, const B& b) const { return a < b; }
219 };
220 struct AnyGt {
221 template <typename A, typename B>
operatorAnyGt222 bool operator()(const A& a, const B& b) const { return a > b; }
223 };
224 struct AnyLe {
225 template <typename A, typename B>
operatorAnyLe226 bool operator()(const A& a, const B& b) const { return a <= b; }
227 };
228 struct AnyGe {
229 template <typename A, typename B>
operatorAnyGe230 bool operator()(const A& a, const B& b) const { return a >= b; }
231 };
232
233 // A match result listener that ignores the explanation.
234 class DummyMatchResultListener : public MatchResultListener {
235 public:
DummyMatchResultListener()236 DummyMatchResultListener() : MatchResultListener(nullptr) {}
237
238 private:
239 GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
240 };
241
242 // A match result listener that forwards the explanation to a given
243 // ostream. The difference between this and MatchResultListener is
244 // that the former is concrete.
245 class StreamMatchResultListener : public MatchResultListener {
246 public:
StreamMatchResultListener(::std::ostream * os)247 explicit StreamMatchResultListener(::std::ostream* os)
248 : MatchResultListener(os) {}
249
250 private:
251 GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
252 };
253
254 // An internal class for implementing Matcher<T>, which will derive
255 // from it. We put functionalities common to all Matcher<T>
256 // specializations here to avoid code duplication.
257 template <typename T>
258 class MatcherBase {
259 public:
260 // Returns true iff the matcher matches x; also explains the match
261 // result to 'listener'.
MatchAndExplain(const T & x,MatchResultListener * listener)262 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
263 return impl_->MatchAndExplain(x, listener);
264 }
265
266 // Returns true iff this matcher matches x.
Matches(const T & x)267 bool Matches(const T& x) const {
268 DummyMatchResultListener dummy;
269 return MatchAndExplain(x, &dummy);
270 }
271
272 // Describes this matcher to an ostream.
DescribeTo(::std::ostream * os)273 void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
274
275 // Describes the negation of this matcher to an ostream.
DescribeNegationTo(::std::ostream * os)276 void DescribeNegationTo(::std::ostream* os) const {
277 impl_->DescribeNegationTo(os);
278 }
279
280 // Explains why x matches, or doesn't match, the matcher.
ExplainMatchResultTo(const T & x,::std::ostream * os)281 void ExplainMatchResultTo(const T& x, ::std::ostream* os) const {
282 StreamMatchResultListener listener(os);
283 MatchAndExplain(x, &listener);
284 }
285
286 // Returns the describer for this matcher object; retains ownership
287 // of the describer, which is only guaranteed to be alive when
288 // this matcher object is alive.
GetDescriber()289 const MatcherDescriberInterface* GetDescriber() const {
290 return impl_.get();
291 }
292
293 protected:
MatcherBase()294 MatcherBase() {}
295
296 // Constructs a matcher from its implementation.
MatcherBase(const MatcherInterface<const T &> * impl)297 explicit MatcherBase(const MatcherInterface<const T&>* impl) : impl_(impl) {}
298
299 template <typename U>
300 explicit MatcherBase(
301 const MatcherInterface<U>* impl,
302 typename internal::EnableIf<
303 !internal::IsSame<U, const U&>::value>::type* = nullptr)
impl_(new internal::MatcherInterfaceAdapter<U> (impl))304 : impl_(new internal::MatcherInterfaceAdapter<U>(impl)) {}
305
306 MatcherBase(const MatcherBase&) = default;
307 MatcherBase& operator=(const MatcherBase&) = default;
308 MatcherBase(MatcherBase&&) = default;
309 MatcherBase& operator=(MatcherBase&&) = default;
310
~MatcherBase()311 virtual ~MatcherBase() {}
312
313 private:
314 std::shared_ptr<const MatcherInterface<const T&>> impl_;
315 };
316
317 } // namespace internal
318
319 // A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
320 // object that can check whether a value of type T matches. The
321 // implementation of Matcher<T> is just a std::shared_ptr to const
322 // MatcherInterface<T>. Don't inherit from Matcher!
323 template <typename T>
324 class Matcher : public internal::MatcherBase<T> {
325 public:
326 // Constructs a null matcher. Needed for storing Matcher objects in STL
327 // containers. A default-constructed matcher is not yet initialized. You
328 // cannot use it until a valid value has been assigned to it.
Matcher()329 explicit Matcher() {} // NOLINT
330
331 // Constructs a matcher from its implementation.
Matcher(const MatcherInterface<const T &> * impl)332 explicit Matcher(const MatcherInterface<const T&>* impl)
333 : internal::MatcherBase<T>(impl) {}
334
335 template <typename U>
336 explicit Matcher(const MatcherInterface<U>* impl,
337 typename internal::EnableIf<
338 !internal::IsSame<U, const U&>::value>::type* = nullptr)
339 : internal::MatcherBase<T>(impl) {}
340
341 // Implicit constructor here allows people to write
342 // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
343 Matcher(T value); // NOLINT
344 };
345
346 // The following two specializations allow the user to write str
347 // instead of Eq(str) and "foo" instead of Eq("foo") when a std::string
348 // matcher is expected.
349 template <>
350 class GTEST_API_ Matcher<const std::string&>
351 : public internal::MatcherBase<const std::string&> {
352 public:
Matcher()353 Matcher() {}
354
Matcher(const MatcherInterface<const std::string &> * impl)355 explicit Matcher(const MatcherInterface<const std::string&>* impl)
356 : internal::MatcherBase<const std::string&>(impl) {}
357
358 // Allows the user to write str instead of Eq(str) sometimes, where
359 // str is a std::string object.
360 Matcher(const std::string& s); // NOLINT
361
362 // Allows the user to write "foo" instead of Eq("foo") sometimes.
363 Matcher(const char* s); // NOLINT
364 };
365
366 template <>
367 class GTEST_API_ Matcher<std::string>
368 : public internal::MatcherBase<std::string> {
369 public:
Matcher()370 Matcher() {}
371
Matcher(const MatcherInterface<const std::string &> * impl)372 explicit Matcher(const MatcherInterface<const std::string&>* impl)
373 : internal::MatcherBase<std::string>(impl) {}
Matcher(const MatcherInterface<std::string> * impl)374 explicit Matcher(const MatcherInterface<std::string>* impl)
375 : internal::MatcherBase<std::string>(impl) {}
376
377 // Allows the user to write str instead of Eq(str) sometimes, where
378 // str is a string object.
379 Matcher(const std::string& s); // NOLINT
380
381 // Allows the user to write "foo" instead of Eq("foo") sometimes.
382 Matcher(const char* s); // NOLINT
383 };
384
385 #if GTEST_HAS_ABSL
386 // The following two specializations allow the user to write str
387 // instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view
388 // matcher is expected.
389 template <>
390 class GTEST_API_ Matcher<const absl::string_view&>
391 : public internal::MatcherBase<const absl::string_view&> {
392 public:
Matcher()393 Matcher() {}
394
Matcher(const MatcherInterface<const absl::string_view &> * impl)395 explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
396 : internal::MatcherBase<const absl::string_view&>(impl) {}
397
398 // Allows the user to write str instead of Eq(str) sometimes, where
399 // str is a std::string object.
400 Matcher(const std::string& s); // NOLINT
401
402 // Allows the user to write "foo" instead of Eq("foo") sometimes.
403 Matcher(const char* s); // NOLINT
404
405 // Allows the user to pass absl::string_views directly.
406 Matcher(absl::string_view s); // NOLINT
407 };
408
409 template <>
410 class GTEST_API_ Matcher<absl::string_view>
411 : public internal::MatcherBase<absl::string_view> {
412 public:
Matcher()413 Matcher() {}
414
Matcher(const MatcherInterface<const absl::string_view &> * impl)415 explicit Matcher(const MatcherInterface<const absl::string_view&>* impl)
416 : internal::MatcherBase<absl::string_view>(impl) {}
Matcher(const MatcherInterface<absl::string_view> * impl)417 explicit Matcher(const MatcherInterface<absl::string_view>* impl)
418 : internal::MatcherBase<absl::string_view>(impl) {}
419
420 // Allows the user to write str instead of Eq(str) sometimes, where
421 // str is a std::string object.
422 Matcher(const std::string& s); // NOLINT
423
424 // Allows the user to write "foo" instead of Eq("foo") sometimes.
425 Matcher(const char* s); // NOLINT
426
427 // Allows the user to pass absl::string_views directly.
428 Matcher(absl::string_view s); // NOLINT
429 };
430 #endif // GTEST_HAS_ABSL
431
432 // Prints a matcher in a human-readable format.
433 template <typename T>
434 std::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {
435 matcher.DescribeTo(&os);
436 return os;
437 }
438
439 // The PolymorphicMatcher class template makes it easy to implement a
440 // polymorphic matcher (i.e. a matcher that can match values of more
441 // than one type, e.g. Eq(n) and NotNull()).
442 //
443 // To define a polymorphic matcher, a user should provide an Impl
444 // class that has a DescribeTo() method and a DescribeNegationTo()
445 // method, and define a member function (or member function template)
446 //
447 // bool MatchAndExplain(const Value& value,
448 // MatchResultListener* listener) const;
449 //
450 // See the definition of NotNull() for a complete example.
451 template <class Impl>
452 class PolymorphicMatcher {
453 public:
PolymorphicMatcher(const Impl & an_impl)454 explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
455
456 // Returns a mutable reference to the underlying matcher
457 // implementation object.
mutable_impl()458 Impl& mutable_impl() { return impl_; }
459
460 // Returns an immutable reference to the underlying matcher
461 // implementation object.
impl()462 const Impl& impl() const { return impl_; }
463
464 template <typename T>
465 operator Matcher<T>() const {
466 return Matcher<T>(new MonomorphicImpl<const T&>(impl_));
467 }
468
469 private:
470 template <typename T>
471 class MonomorphicImpl : public MatcherInterface<T> {
472 public:
MonomorphicImpl(const Impl & impl)473 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
474
DescribeTo(::std::ostream * os)475 virtual void DescribeTo(::std::ostream* os) const { impl_.DescribeTo(os); }
476
DescribeNegationTo(::std::ostream * os)477 virtual void DescribeNegationTo(::std::ostream* os) const {
478 impl_.DescribeNegationTo(os);
479 }
480
MatchAndExplain(T x,MatchResultListener * listener)481 virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
482 return impl_.MatchAndExplain(x, listener);
483 }
484
485 private:
486 const Impl impl_;
487 };
488
489 Impl impl_;
490 };
491
492 // Creates a matcher from its implementation.
493 // DEPRECATED: Especially in the generic code, prefer:
494 // Matcher<T>(new MyMatcherImpl<const T&>(...));
495 //
496 // MakeMatcher may create a Matcher that accepts its argument by value, which
497 // leads to unnecessary copies & lack of support for non-copyable types.
498 template <typename T>
MakeMatcher(const MatcherInterface<T> * impl)499 inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
500 return Matcher<T>(impl);
501 }
502
503 // Creates a polymorphic matcher from its implementation. This is
504 // easier to use than the PolymorphicMatcher<Impl> constructor as it
505 // doesn't require you to explicitly write the template argument, e.g.
506 //
507 // MakePolymorphicMatcher(foo);
508 // vs
509 // PolymorphicMatcher<TypeOfFoo>(foo);
510 template <class Impl>
MakePolymorphicMatcher(const Impl & impl)511 inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
512 return PolymorphicMatcher<Impl>(impl);
513 }
514
515 namespace internal {
516 // Implements a matcher that compares a given value with a
517 // pre-supplied value using one of the ==, <=, <, etc, operators. The
518 // two values being compared don't have to have the same type.
519 //
520 // The matcher defined here is polymorphic (for example, Eq(5) can be
521 // used to match an int, a short, a double, etc). Therefore we use
522 // a template type conversion operator in the implementation.
523 //
524 // The following template definition assumes that the Rhs parameter is
525 // a "bare" type (i.e. neither 'const T' nor 'T&').
526 template <typename D, typename Rhs, typename Op>
527 class ComparisonBase {
528 public:
ComparisonBase(const Rhs & rhs)529 explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}
530 template <typename Lhs>
531 operator Matcher<Lhs>() const {
532 return Matcher<Lhs>(new Impl<const Lhs&>(rhs_));
533 }
534
535 private:
536 template <typename T>
Unwrap(const T & v)537 static const T& Unwrap(const T& v) { return v; }
538 template <typename T>
Unwrap(std::reference_wrapper<T> v)539 static const T& Unwrap(std::reference_wrapper<T> v) { return v; }
540
541 template <typename Lhs, typename = Rhs>
542 class Impl : public MatcherInterface<Lhs> {
543 public:
Impl(const Rhs & rhs)544 explicit Impl(const Rhs& rhs) : rhs_(rhs) {}
MatchAndExplain(Lhs lhs,MatchResultListener *)545 bool MatchAndExplain(Lhs lhs,
546 MatchResultListener* /* listener */) const override {
547 return Op()(lhs, Unwrap(rhs_));
548 }
DescribeTo(::std::ostream * os)549 void DescribeTo(::std::ostream* os) const override {
550 *os << D::Desc() << " ";
551 UniversalPrint(Unwrap(rhs_), os);
552 }
DescribeNegationTo(::std::ostream * os)553 void DescribeNegationTo(::std::ostream* os) const override {
554 *os << D::NegatedDesc() << " ";
555 UniversalPrint(Unwrap(rhs_), os);
556 }
557
558 private:
559 Rhs rhs_;
560 };
561 Rhs rhs_;
562 };
563
564 template <typename Rhs>
565 class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {
566 public:
EqMatcher(const Rhs & rhs)567 explicit EqMatcher(const Rhs& rhs)
568 : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { }
Desc()569 static const char* Desc() { return "is equal to"; }
NegatedDesc()570 static const char* NegatedDesc() { return "isn't equal to"; }
571 };
572 template <typename Rhs>
573 class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {
574 public:
NeMatcher(const Rhs & rhs)575 explicit NeMatcher(const Rhs& rhs)
576 : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { }
Desc()577 static const char* Desc() { return "isn't equal to"; }
NegatedDesc()578 static const char* NegatedDesc() { return "is equal to"; }
579 };
580 template <typename Rhs>
581 class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {
582 public:
LtMatcher(const Rhs & rhs)583 explicit LtMatcher(const Rhs& rhs)
584 : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { }
Desc()585 static const char* Desc() { return "is <"; }
NegatedDesc()586 static const char* NegatedDesc() { return "isn't <"; }
587 };
588 template <typename Rhs>
589 class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {
590 public:
GtMatcher(const Rhs & rhs)591 explicit GtMatcher(const Rhs& rhs)
592 : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { }
Desc()593 static const char* Desc() { return "is >"; }
NegatedDesc()594 static const char* NegatedDesc() { return "isn't >"; }
595 };
596 template <typename Rhs>
597 class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {
598 public:
LeMatcher(const Rhs & rhs)599 explicit LeMatcher(const Rhs& rhs)
600 : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { }
Desc()601 static const char* Desc() { return "is <="; }
NegatedDesc()602 static const char* NegatedDesc() { return "isn't <="; }
603 };
604 template <typename Rhs>
605 class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {
606 public:
GeMatcher(const Rhs & rhs)607 explicit GeMatcher(const Rhs& rhs)
608 : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { }
Desc()609 static const char* Desc() { return "is >="; }
NegatedDesc()610 static const char* NegatedDesc() { return "isn't >="; }
611 };
612
613 // Implements polymorphic matchers MatchesRegex(regex) and
614 // ContainsRegex(regex), which can be used as a Matcher<T> as long as
615 // T can be converted to a string.
616 class MatchesRegexMatcher {
617 public:
MatchesRegexMatcher(const RE * regex,bool full_match)618 MatchesRegexMatcher(const RE* regex, bool full_match)
619 : regex_(regex), full_match_(full_match) {}
620
621 #if GTEST_HAS_ABSL
MatchAndExplain(const absl::string_view & s,MatchResultListener * listener)622 bool MatchAndExplain(const absl::string_view& s,
623 MatchResultListener* listener) const {
624 return MatchAndExplain(std::string(s), listener);
625 }
626 #endif // GTEST_HAS_ABSL
627
628 // Accepts pointer types, particularly:
629 // const char*
630 // char*
631 // const wchar_t*
632 // wchar_t*
633 template <typename CharType>
MatchAndExplain(CharType * s,MatchResultListener * listener)634 bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {
635 return s != nullptr && MatchAndExplain(std::string(s), listener);
636 }
637
638 // Matches anything that can convert to std::string.
639 //
640 // This is a template, not just a plain function with const std::string&,
641 // because absl::string_view has some interfering non-explicit constructors.
642 template <class MatcheeStringType>
MatchAndExplain(const MatcheeStringType & s,MatchResultListener *)643 bool MatchAndExplain(const MatcheeStringType& s,
644 MatchResultListener* /* listener */) const {
645 const std::string& s2(s);
646 return full_match_ ? RE::FullMatch(s2, *regex_)
647 : RE::PartialMatch(s2, *regex_);
648 }
649
DescribeTo(::std::ostream * os)650 void DescribeTo(::std::ostream* os) const {
651 *os << (full_match_ ? "matches" : "contains") << " regular expression ";
652 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
653 }
654
DescribeNegationTo(::std::ostream * os)655 void DescribeNegationTo(::std::ostream* os) const {
656 *os << "doesn't " << (full_match_ ? "match" : "contain")
657 << " regular expression ";
658 UniversalPrinter<std::string>::Print(regex_->pattern(), os);
659 }
660
661 private:
662 const std::shared_ptr<const RE> regex_;
663 const bool full_match_;
664 };
665 } // namespace internal
666
667 // Matches a string that fully matches regular expression 'regex'.
668 // The matcher takes ownership of 'regex'.
MatchesRegex(const internal::RE * regex)669 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
670 const internal::RE* regex) {
671 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
672 }
MatchesRegex(const std::string & regex)673 inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
674 const std::string& regex) {
675 return MatchesRegex(new internal::RE(regex));
676 }
677
678 // Matches a string that contains regular expression 'regex'.
679 // The matcher takes ownership of 'regex'.
ContainsRegex(const internal::RE * regex)680 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
681 const internal::RE* regex) {
682 return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
683 }
ContainsRegex(const std::string & regex)684 inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
685 const std::string& regex) {
686 return ContainsRegex(new internal::RE(regex));
687 }
688
689 // Creates a polymorphic matcher that matches anything equal to x.
690 // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
691 // wouldn't compile.
692 template <typename T>
Eq(T x)693 inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
694
695 // Constructs a Matcher<T> from a 'value' of type T. The constructed
696 // matcher matches any value that's equal to 'value'.
697 template <typename T>
Matcher(T value)698 Matcher<T>::Matcher(T value) { *this = Eq(value); }
699
700 // Creates a monomorphic matcher that matches anything with type Lhs
701 // and equal to rhs. A user may need to use this instead of Eq(...)
702 // in order to resolve an overloading ambiguity.
703 //
704 // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
705 // or Matcher<T>(x), but more readable than the latter.
706 //
707 // We could define similar monomorphic matchers for other comparison
708 // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
709 // it yet as those are used much less than Eq() in practice. A user
710 // can always write Matcher<T>(Lt(5)) to be explicit about the type,
711 // for example.
712 template <typename Lhs, typename Rhs>
TypedEq(const Rhs & rhs)713 inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
714
715 // Creates a polymorphic matcher that matches anything >= x.
716 template <typename Rhs>
Ge(Rhs x)717 inline internal::GeMatcher<Rhs> Ge(Rhs x) {
718 return internal::GeMatcher<Rhs>(x);
719 }
720
721 // Creates a polymorphic matcher that matches anything > x.
722 template <typename Rhs>
Gt(Rhs x)723 inline internal::GtMatcher<Rhs> Gt(Rhs x) {
724 return internal::GtMatcher<Rhs>(x);
725 }
726
727 // Creates a polymorphic matcher that matches anything <= x.
728 template <typename Rhs>
Le(Rhs x)729 inline internal::LeMatcher<Rhs> Le(Rhs x) {
730 return internal::LeMatcher<Rhs>(x);
731 }
732
733 // Creates a polymorphic matcher that matches anything < x.
734 template <typename Rhs>
Lt(Rhs x)735 inline internal::LtMatcher<Rhs> Lt(Rhs x) {
736 return internal::LtMatcher<Rhs>(x);
737 }
738
739 // Creates a polymorphic matcher that matches anything != x.
740 template <typename Rhs>
Ne(Rhs x)741 inline internal::NeMatcher<Rhs> Ne(Rhs x) {
742 return internal::NeMatcher<Rhs>(x);
743 }
744 } // namespace testing
745
746 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046
747
748 #endif // GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_
749