gtest-matchers.h 33 KB

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