You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

930 lines
32 KiB

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