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