gtest-matchers.h 32 KB

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