/testlibs/gmock/include/gmock/gmock-matchers.h

https://github.com/deltaforge/nebu-app-mongo · C Header · 3066 lines · 1846 code · 427 blank · 793 comment · 142 complexity · 0993f8cc8b4762f2903ce55c8ea73ade MD5 · raw file

Large files are truncated click here to view the full file

  1. // Copyright 2007, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. //
  30. // Author: wan@google.com (Zhanyong Wan)
  31. // Google Mock - a framework for writing C++ mock classes.
  32. //
  33. // This file implements some commonly used argument matchers. More
  34. // matchers can be defined by the user implementing the
  35. // MatcherInterface<T> interface if necessary.
  36. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
  37. #define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
  38. #include <algorithm>
  39. #include <limits>
  40. #include <ostream> // NOLINT
  41. #include <sstream>
  42. #include <string>
  43. #include <utility>
  44. #include <vector>
  45. #include "gmock/internal/gmock-internal-utils.h"
  46. #include "gmock/internal/gmock-port.h"
  47. #include "gtest/gtest.h"
  48. namespace testing {
  49. // To implement a matcher Foo for type T, define:
  50. // 1. a class FooMatcherImpl that implements the
  51. // MatcherInterface<T> interface, and
  52. // 2. a factory function that creates a Matcher<T> object from a
  53. // FooMatcherImpl*.
  54. //
  55. // The two-level delegation design makes it possible to allow a user
  56. // to write "v" instead of "Eq(v)" where a Matcher is expected, which
  57. // is impossible if we pass matchers by pointers. It also eases
  58. // ownership management as Matcher objects can now be copied like
  59. // plain values.
  60. // MatchResultListener is an abstract class. Its << operator can be
  61. // used by a matcher to explain why a value matches or doesn't match.
  62. //
  63. // TODO(wan@google.com): add method
  64. // bool InterestedInWhy(bool result) const;
  65. // to indicate whether the listener is interested in why the match
  66. // result is 'result'.
  67. class MatchResultListener {
  68. public:
  69. // Creates a listener object with the given underlying ostream. The
  70. // listener does not own the ostream.
  71. explicit MatchResultListener(::std::ostream* os) : stream_(os) {}
  72. virtual ~MatchResultListener() = 0; // Makes this class abstract.
  73. // Streams x to the underlying ostream; does nothing if the ostream
  74. // is NULL.
  75. template <typename T>
  76. MatchResultListener& operator<<(const T& x) {
  77. if (stream_ != NULL)
  78. *stream_ << x;
  79. return *this;
  80. }
  81. // Returns the underlying ostream.
  82. ::std::ostream* stream() { return stream_; }
  83. // Returns true iff the listener is interested in an explanation of
  84. // 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_ != NULL; }
  88. private:
  89. ::std::ostream* const stream_;
  90. GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener);
  91. };
  92. inline MatchResultListener::~MatchResultListener() {
  93. }
  94. // The implementation of a matcher.
  95. template <typename T>
  96. class MatcherInterface {
  97. public:
  98. virtual ~MatcherInterface() {}
  99. // Returns true iff the matcher matches x; also explains the match
  100. // result to 'listener', in the form of a non-restrictive relative
  101. // clause ("which ...", "whose ...", etc) that describes x. For
  102. // example, the MatchAndExplain() method of the Pointee(...) matcher
  103. // should generate an explanation like "which points to ...".
  104. //
  105. // You should override this method when defining a new matcher.
  106. //
  107. // It's the responsibility of the caller (Google Mock) to guarantee
  108. // that 'listener' is not NULL. This helps to simplify a matcher's
  109. // implementation when it doesn't care about the performance, as it
  110. // can talk to 'listener' without checking its validity first.
  111. // However, in order to implement dummy listeners efficiently,
  112. // listener->stream() may be NULL.
  113. virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
  114. // Describes this matcher to an ostream. The function should print
  115. // a verb phrase that describes the property a value matching this
  116. // matcher should have. The subject of the verb phrase is the value
  117. // being matched. For example, the DescribeTo() method of the Gt(7)
  118. // matcher prints "is greater than 7".
  119. virtual void DescribeTo(::std::ostream* os) const = 0;
  120. // Describes the negation of this matcher to an ostream. For
  121. // example, if the description of this matcher is "is greater than
  122. // 7", the negated description could be "is not greater than 7".
  123. // You are not required to override this when implementing
  124. // MatcherInterface, but it is highly advised so that your matcher
  125. // can produce good error messages.
  126. virtual void DescribeNegationTo(::std::ostream* os) const {
  127. *os << "not (";
  128. DescribeTo(os);
  129. *os << ")";
  130. }
  131. };
  132. namespace internal {
  133. // A match result listener that ignores the explanation.
  134. class DummyMatchResultListener : public MatchResultListener {
  135. public:
  136. DummyMatchResultListener() : MatchResultListener(NULL) {}
  137. private:
  138. GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener);
  139. };
  140. // A match result listener that forwards the explanation to a given
  141. // ostream. The difference between this and MatchResultListener is
  142. // that the former is concrete.
  143. class StreamMatchResultListener : public MatchResultListener {
  144. public:
  145. explicit StreamMatchResultListener(::std::ostream* os)
  146. : MatchResultListener(os) {}
  147. private:
  148. GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener);
  149. };
  150. // A match result listener that stores the explanation in a string.
  151. class StringMatchResultListener : public MatchResultListener {
  152. public:
  153. StringMatchResultListener() : MatchResultListener(&ss_) {}
  154. // Returns the explanation heard so far.
  155. internal::string str() const { return ss_.str(); }
  156. private:
  157. ::std::stringstream ss_;
  158. GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener);
  159. };
  160. // An internal class for implementing Matcher<T>, which will derive
  161. // from it. We put functionalities common to all Matcher<T>
  162. // specializations here to avoid code duplication.
  163. template <typename T>
  164. class MatcherBase {
  165. public:
  166. // Returns true iff the matcher matches x; also explains the match
  167. // result to 'listener'.
  168. bool MatchAndExplain(T x, MatchResultListener* listener) const {
  169. return impl_->MatchAndExplain(x, listener);
  170. }
  171. // Returns true iff this matcher matches x.
  172. bool Matches(T x) const {
  173. DummyMatchResultListener dummy;
  174. return MatchAndExplain(x, &dummy);
  175. }
  176. // Describes this matcher to an ostream.
  177. void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
  178. // Describes the negation of this matcher to an ostream.
  179. void DescribeNegationTo(::std::ostream* os) const {
  180. impl_->DescribeNegationTo(os);
  181. }
  182. // Explains why x matches, or doesn't match, the matcher.
  183. void ExplainMatchResultTo(T x, ::std::ostream* os) const {
  184. StreamMatchResultListener listener(os);
  185. MatchAndExplain(x, &listener);
  186. }
  187. protected:
  188. MatcherBase() {}
  189. // Constructs a matcher from its implementation.
  190. explicit MatcherBase(const MatcherInterface<T>* impl)
  191. : impl_(impl) {}
  192. virtual ~MatcherBase() {}
  193. private:
  194. // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar
  195. // interfaces. The former dynamically allocates a chunk of memory
  196. // to hold the reference count, while the latter tracks all
  197. // references using a circular linked list without allocating
  198. // memory. It has been observed that linked_ptr performs better in
  199. // typical scenarios. However, shared_ptr can out-perform
  200. // linked_ptr when there are many more uses of the copy constructor
  201. // than the default constructor.
  202. //
  203. // If performance becomes a problem, we should see if using
  204. // shared_ptr helps.
  205. ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_;
  206. };
  207. } // namespace internal
  208. // A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
  209. // object that can check whether a value of type T matches. The
  210. // implementation of Matcher<T> is just a linked_ptr to const
  211. // MatcherInterface<T>, so copying is fairly cheap. Don't inherit
  212. // from Matcher!
  213. template <typename T>
  214. class Matcher : public internal::MatcherBase<T> {
  215. public:
  216. // Constructs a null matcher. Needed for storing Matcher objects in STL
  217. // containers. A default-constructed matcher is not yet initialized. You
  218. // cannot use it until a valid value has been assigned to it.
  219. Matcher() {}
  220. // Constructs a matcher from its implementation.
  221. explicit Matcher(const MatcherInterface<T>* impl)
  222. : internal::MatcherBase<T>(impl) {}
  223. // Implicit constructor here allows people to write
  224. // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes
  225. Matcher(T value); // NOLINT
  226. };
  227. // The following two specializations allow the user to write str
  228. // instead of Eq(str) and "foo" instead of Eq("foo") when a string
  229. // matcher is expected.
  230. template <>
  231. class Matcher<const internal::string&>
  232. : public internal::MatcherBase<const internal::string&> {
  233. public:
  234. Matcher() {}
  235. explicit Matcher(const MatcherInterface<const internal::string&>* impl)
  236. : internal::MatcherBase<const internal::string&>(impl) {}
  237. // Allows the user to write str instead of Eq(str) sometimes, where
  238. // str is a string object.
  239. Matcher(const internal::string& s); // NOLINT
  240. // Allows the user to write "foo" instead of Eq("foo") sometimes.
  241. Matcher(const char* s); // NOLINT
  242. };
  243. template <>
  244. class Matcher<internal::string>
  245. : public internal::MatcherBase<internal::string> {
  246. public:
  247. Matcher() {}
  248. explicit Matcher(const MatcherInterface<internal::string>* impl)
  249. : internal::MatcherBase<internal::string>(impl) {}
  250. // Allows the user to write str instead of Eq(str) sometimes, where
  251. // str is a string object.
  252. Matcher(const internal::string& s); // NOLINT
  253. // Allows the user to write "foo" instead of Eq("foo") sometimes.
  254. Matcher(const char* s); // NOLINT
  255. };
  256. // The PolymorphicMatcher class template makes it easy to implement a
  257. // polymorphic matcher (i.e. a matcher that can match values of more
  258. // than one type, e.g. Eq(n) and NotNull()).
  259. //
  260. // To define a polymorphic matcher, a user should provide an Impl
  261. // class that has a DescribeTo() method and a DescribeNegationTo()
  262. // method, and define a member function (or member function template)
  263. //
  264. // bool MatchAndExplain(const Value& value,
  265. // MatchResultListener* listener) const;
  266. //
  267. // See the definition of NotNull() for a complete example.
  268. template <class Impl>
  269. class PolymorphicMatcher {
  270. public:
  271. explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}
  272. // Returns a mutable reference to the underlying matcher
  273. // implementation object.
  274. Impl& mutable_impl() { return impl_; }
  275. // Returns an immutable reference to the underlying matcher
  276. // implementation object.
  277. const Impl& impl() const { return impl_; }
  278. template <typename T>
  279. operator Matcher<T>() const {
  280. return Matcher<T>(new MonomorphicImpl<T>(impl_));
  281. }
  282. private:
  283. template <typename T>
  284. class MonomorphicImpl : public MatcherInterface<T> {
  285. public:
  286. explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
  287. virtual void DescribeTo(::std::ostream* os) const {
  288. impl_.DescribeTo(os);
  289. }
  290. virtual void DescribeNegationTo(::std::ostream* os) const {
  291. impl_.DescribeNegationTo(os);
  292. }
  293. virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
  294. return impl_.MatchAndExplain(x, listener);
  295. }
  296. private:
  297. const Impl impl_;
  298. GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
  299. };
  300. Impl impl_;
  301. GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher);
  302. };
  303. // Creates a matcher from its implementation. This is easier to use
  304. // than the Matcher<T> constructor as it doesn't require you to
  305. // explicitly write the template argument, e.g.
  306. //
  307. // MakeMatcher(foo);
  308. // vs
  309. // Matcher<const string&>(foo);
  310. template <typename T>
  311. inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {
  312. return Matcher<T>(impl);
  313. };
  314. // Creates a polymorphic matcher from its implementation. This is
  315. // easier to use than the PolymorphicMatcher<Impl> constructor as it
  316. // doesn't require you to explicitly write the template argument, e.g.
  317. //
  318. // MakePolymorphicMatcher(foo);
  319. // vs
  320. // PolymorphicMatcher<TypeOfFoo>(foo);
  321. template <class Impl>
  322. inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {
  323. return PolymorphicMatcher<Impl>(impl);
  324. }
  325. // In order to be safe and clear, casting between different matcher
  326. // types is done explicitly via MatcherCast<T>(m), which takes a
  327. // matcher m and returns a Matcher<T>. It compiles only when T can be
  328. // statically converted to the argument type of m.
  329. template <typename T, typename M>
  330. Matcher<T> MatcherCast(M m);
  331. // Implements SafeMatcherCast().
  332. //
  333. // We use an intermediate class to do the actual safe casting as Nokia's
  334. // Symbian compiler cannot decide between
  335. // template <T, M> ... (M) and
  336. // template <T, U> ... (const Matcher<U>&)
  337. // for function templates but can for member function templates.
  338. template <typename T>
  339. class SafeMatcherCastImpl {
  340. public:
  341. // This overload handles polymorphic matchers only since monomorphic
  342. // matchers are handled by the next one.
  343. template <typename M>
  344. static inline Matcher<T> Cast(M polymorphic_matcher) {
  345. return Matcher<T>(polymorphic_matcher);
  346. }
  347. // This overload handles monomorphic matchers.
  348. //
  349. // In general, if type T can be implicitly converted to type U, we can
  350. // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is
  351. // contravariant): just keep a copy of the original Matcher<U>, convert the
  352. // argument from type T to U, and then pass it to the underlying Matcher<U>.
  353. // The only exception is when U is a reference and T is not, as the
  354. // underlying Matcher<U> may be interested in the argument's address, which
  355. // is not preserved in the conversion from T to U.
  356. template <typename U>
  357. static inline Matcher<T> Cast(const Matcher<U>& matcher) {
  358. // Enforce that T can be implicitly converted to U.
  359. GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value),
  360. T_must_be_implicitly_convertible_to_U);
  361. // Enforce that we are not converting a non-reference type T to a reference
  362. // type U.
  363. GTEST_COMPILE_ASSERT_(
  364. internal::is_reference<T>::value || !internal::is_reference<U>::value,
  365. cannot_convert_non_referentce_arg_to_reference);
  366. // In case both T and U are arithmetic types, enforce that the
  367. // conversion is not lossy.
  368. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;
  369. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;
  370. const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;
  371. const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;
  372. GTEST_COMPILE_ASSERT_(
  373. kTIsOther || kUIsOther ||
  374. (internal::LosslessArithmeticConvertible<RawT, RawU>::value),
  375. conversion_of_arithmetic_types_must_be_lossless);
  376. return MatcherCast<T>(matcher);
  377. }
  378. };
  379. template <typename T, typename M>
  380. inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) {
  381. return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher);
  382. }
  383. // A<T>() returns a matcher that matches any value of type T.
  384. template <typename T>
  385. Matcher<T> A();
  386. // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
  387. // and MUST NOT BE USED IN USER CODE!!!
  388. namespace internal {
  389. // If the explanation is not empty, prints it to the ostream.
  390. inline void PrintIfNotEmpty(const internal::string& explanation,
  391. std::ostream* os) {
  392. if (explanation != "" && os != NULL) {
  393. *os << ", " << explanation;
  394. }
  395. }
  396. // Returns true if the given type name is easy to read by a human.
  397. // This is used to decide whether printing the type of a value might
  398. // be helpful.
  399. inline bool IsReadableTypeName(const string& type_name) {
  400. // We consider a type name readable if it's short or doesn't contain
  401. // a template or function type.
  402. return (type_name.length() <= 20 ||
  403. type_name.find_first_of("<(") == string::npos);
  404. }
  405. // Matches the value against the given matcher, prints the value and explains
  406. // the match result to the listener. Returns the match result.
  407. // 'listener' must not be NULL.
  408. // Value cannot be passed by const reference, because some matchers take a
  409. // non-const argument.
  410. template <typename Value, typename T>
  411. bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,
  412. MatchResultListener* listener) {
  413. if (!listener->IsInterested()) {
  414. // If the listener is not interested, we do not need to construct the
  415. // inner explanation.
  416. return matcher.Matches(value);
  417. }
  418. StringMatchResultListener inner_listener;
  419. const bool match = matcher.MatchAndExplain(value, &inner_listener);
  420. UniversalPrint(value, listener->stream());
  421. #if GTEST_HAS_RTTI
  422. const string& type_name = GetTypeName<Value>();
  423. if (IsReadableTypeName(type_name))
  424. *listener->stream() << " (of type " << type_name << ")";
  425. #endif
  426. PrintIfNotEmpty(inner_listener.str(), listener->stream());
  427. return match;
  428. }
  429. // An internal helper class for doing compile-time loop on a tuple's
  430. // fields.
  431. template <size_t N>
  432. class TuplePrefix {
  433. public:
  434. // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true
  435. // iff the first N fields of matcher_tuple matches the first N
  436. // fields of value_tuple, respectively.
  437. template <typename MatcherTuple, typename ValueTuple>
  438. static bool Matches(const MatcherTuple& matcher_tuple,
  439. const ValueTuple& value_tuple) {
  440. using ::std::tr1::get;
  441. return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple)
  442. && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple));
  443. }
  444. // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)
  445. // describes failures in matching the first N fields of matchers
  446. // against the first N fields of values. If there is no failure,
  447. // nothing will be streamed to os.
  448. template <typename MatcherTuple, typename ValueTuple>
  449. static void ExplainMatchFailuresTo(const MatcherTuple& matchers,
  450. const ValueTuple& values,
  451. ::std::ostream* os) {
  452. using ::std::tr1::tuple_element;
  453. using ::std::tr1::get;
  454. // First, describes failures in the first N - 1 fields.
  455. TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);
  456. // Then describes the failure (if any) in the (N - 1)-th (0-based)
  457. // field.
  458. typename tuple_element<N - 1, MatcherTuple>::type matcher =
  459. get<N - 1>(matchers);
  460. typedef typename tuple_element<N - 1, ValueTuple>::type Value;
  461. Value value = get<N - 1>(values);
  462. StringMatchResultListener listener;
  463. if (!matcher.MatchAndExplain(value, &listener)) {
  464. // TODO(wan): include in the message the name of the parameter
  465. // as used in MOCK_METHOD*() when possible.
  466. *os << " Expected arg #" << N - 1 << ": ";
  467. get<N - 1>(matchers).DescribeTo(os);
  468. *os << "\n Actual: ";
  469. // We remove the reference in type Value to prevent the
  470. // universal printer from printing the address of value, which
  471. // isn't interesting to the user most of the time. The
  472. // matcher's MatchAndExplain() method handles the case when
  473. // the address is interesting.
  474. internal::UniversalPrint(value, os);
  475. PrintIfNotEmpty(listener.str(), os);
  476. *os << "\n";
  477. }
  478. }
  479. };
  480. // The base case.
  481. template <>
  482. class TuplePrefix<0> {
  483. public:
  484. template <typename MatcherTuple, typename ValueTuple>
  485. static bool Matches(const MatcherTuple& /* matcher_tuple */,
  486. const ValueTuple& /* value_tuple */) {
  487. return true;
  488. }
  489. template <typename MatcherTuple, typename ValueTuple>
  490. static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,
  491. const ValueTuple& /* values */,
  492. ::std::ostream* /* os */) {}
  493. };
  494. // TupleMatches(matcher_tuple, value_tuple) returns true iff all
  495. // matchers in matcher_tuple match the corresponding fields in
  496. // value_tuple. It is a compiler error if matcher_tuple and
  497. // value_tuple have different number of fields or incompatible field
  498. // types.
  499. template <typename MatcherTuple, typename ValueTuple>
  500. bool TupleMatches(const MatcherTuple& matcher_tuple,
  501. const ValueTuple& value_tuple) {
  502. using ::std::tr1::tuple_size;
  503. // Makes sure that matcher_tuple and value_tuple have the same
  504. // number of fields.
  505. GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value ==
  506. tuple_size<ValueTuple>::value,
  507. matcher_and_value_have_different_numbers_of_fields);
  508. return TuplePrefix<tuple_size<ValueTuple>::value>::
  509. Matches(matcher_tuple, value_tuple);
  510. }
  511. // Describes failures in matching matchers against values. If there
  512. // is no failure, nothing will be streamed to os.
  513. template <typename MatcherTuple, typename ValueTuple>
  514. void ExplainMatchFailureTupleTo(const MatcherTuple& matchers,
  515. const ValueTuple& values,
  516. ::std::ostream* os) {
  517. using ::std::tr1::tuple_size;
  518. TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(
  519. matchers, values, os);
  520. }
  521. // The MatcherCastImpl class template is a helper for implementing
  522. // MatcherCast(). We need this helper in order to partially
  523. // specialize the implementation of MatcherCast() (C++ allows
  524. // class/struct templates to be partially specialized, but not
  525. // function templates.).
  526. // This general version is used when MatcherCast()'s argument is a
  527. // polymorphic matcher (i.e. something that can be converted to a
  528. // Matcher but is not one yet; for example, Eq(value)).
  529. template <typename T, typename M>
  530. class MatcherCastImpl {
  531. public:
  532. static Matcher<T> Cast(M polymorphic_matcher) {
  533. return Matcher<T>(polymorphic_matcher);
  534. }
  535. };
  536. // This more specialized version is used when MatcherCast()'s argument
  537. // is already a Matcher. This only compiles when type T can be
  538. // statically converted to type U.
  539. template <typename T, typename U>
  540. class MatcherCastImpl<T, Matcher<U> > {
  541. public:
  542. static Matcher<T> Cast(const Matcher<U>& source_matcher) {
  543. return Matcher<T>(new Impl(source_matcher));
  544. }
  545. private:
  546. class Impl : public MatcherInterface<T> {
  547. public:
  548. explicit Impl(const Matcher<U>& source_matcher)
  549. : source_matcher_(source_matcher) {}
  550. // We delegate the matching logic to the source matcher.
  551. virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
  552. return source_matcher_.MatchAndExplain(static_cast<U>(x), listener);
  553. }
  554. virtual void DescribeTo(::std::ostream* os) const {
  555. source_matcher_.DescribeTo(os);
  556. }
  557. virtual void DescribeNegationTo(::std::ostream* os) const {
  558. source_matcher_.DescribeNegationTo(os);
  559. }
  560. private:
  561. const Matcher<U> source_matcher_;
  562. GTEST_DISALLOW_ASSIGN_(Impl);
  563. };
  564. };
  565. // This even more specialized version is used for efficiently casting
  566. // a matcher to its own type.
  567. template <typename T>
  568. class MatcherCastImpl<T, Matcher<T> > {
  569. public:
  570. static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }
  571. };
  572. // Implements A<T>().
  573. template <typename T>
  574. class AnyMatcherImpl : public MatcherInterface<T> {
  575. public:
  576. virtual bool MatchAndExplain(
  577. T /* x */, MatchResultListener* /* listener */) const { return true; }
  578. virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; }
  579. virtual void DescribeNegationTo(::std::ostream* os) const {
  580. // This is mostly for completeness' safe, as it's not very useful
  581. // to write Not(A<bool>()). However we cannot completely rule out
  582. // such a possibility, and it doesn't hurt to be prepared.
  583. *os << "never matches";
  584. }
  585. };
  586. // Implements _, a matcher that matches any value of any
  587. // type. This is a polymorphic matcher, so we need a template type
  588. // conversion operator to make it appearing as a Matcher<T> for any
  589. // type T.
  590. class AnythingMatcher {
  591. public:
  592. template <typename T>
  593. operator Matcher<T>() const { return A<T>(); }
  594. };
  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. // We define this as a macro in order to eliminate duplicated source
  604. // code.
  605. //
  606. // The following template definition assumes that the Rhs parameter is
  607. // a "bare" type (i.e. neither 'const T' nor 'T&').
  608. #define GMOCK_IMPLEMENT_COMPARISON_MATCHER_( \
  609. name, op, relation, negated_relation) \
  610. template <typename Rhs> class name##Matcher { \
  611. public: \
  612. explicit name##Matcher(const Rhs& rhs) : rhs_(rhs) {} \
  613. template <typename Lhs> \
  614. operator Matcher<Lhs>() const { \
  615. return MakeMatcher(new Impl<Lhs>(rhs_)); \
  616. } \
  617. private: \
  618. template <typename Lhs> \
  619. class Impl : public MatcherInterface<Lhs> { \
  620. public: \
  621. explicit Impl(const Rhs& rhs) : rhs_(rhs) {} \
  622. virtual bool MatchAndExplain(\
  623. Lhs lhs, MatchResultListener* /* listener */) const { \
  624. return lhs op rhs_; \
  625. } \
  626. virtual void DescribeTo(::std::ostream* os) const { \
  627. *os << relation " "; \
  628. UniversalPrint(rhs_, os); \
  629. } \
  630. virtual void DescribeNegationTo(::std::ostream* os) const { \
  631. *os << negated_relation " "; \
  632. UniversalPrint(rhs_, os); \
  633. } \
  634. private: \
  635. Rhs rhs_; \
  636. GTEST_DISALLOW_ASSIGN_(Impl); \
  637. }; \
  638. Rhs rhs_; \
  639. GTEST_DISALLOW_ASSIGN_(name##Matcher); \
  640. }
  641. // Implements Eq(v), Ge(v), Gt(v), Le(v), Lt(v), and Ne(v)
  642. // respectively.
  643. GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Eq, ==, "is equal to", "isn't equal to");
  644. GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ge, >=, "is >=", "isn't >=");
  645. GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Gt, >, "is >", "isn't >");
  646. GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Le, <=, "is <=", "isn't <=");
  647. GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Lt, <, "is <", "isn't <");
  648. GMOCK_IMPLEMENT_COMPARISON_MATCHER_(Ne, !=, "isn't equal to", "is equal to");
  649. #undef GMOCK_IMPLEMENT_COMPARISON_MATCHER_
  650. // Implements the polymorphic IsNull() matcher, which matches any raw or smart
  651. // pointer that is NULL.
  652. class IsNullMatcher {
  653. public:
  654. template <typename Pointer>
  655. bool MatchAndExplain(const Pointer& p,
  656. MatchResultListener* /* listener */) const {
  657. return GetRawPointer(p) == NULL;
  658. }
  659. void DescribeTo(::std::ostream* os) const { *os << "is NULL"; }
  660. void DescribeNegationTo(::std::ostream* os) const {
  661. *os << "isn't NULL";
  662. }
  663. };
  664. // Implements the polymorphic NotNull() matcher, which matches any raw or smart
  665. // pointer that is not NULL.
  666. class NotNullMatcher {
  667. public:
  668. template <typename Pointer>
  669. bool MatchAndExplain(const Pointer& p,
  670. MatchResultListener* /* listener */) const {
  671. return GetRawPointer(p) != NULL;
  672. }
  673. void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; }
  674. void DescribeNegationTo(::std::ostream* os) const {
  675. *os << "is NULL";
  676. }
  677. };
  678. // Ref(variable) matches any argument that is a reference to
  679. // 'variable'. This matcher is polymorphic as it can match any
  680. // super type of the type of 'variable'.
  681. //
  682. // The RefMatcher template class implements Ref(variable). It can
  683. // only be instantiated with a reference type. This prevents a user
  684. // from mistakenly using Ref(x) to match a non-reference function
  685. // argument. For example, the following will righteously cause a
  686. // compiler error:
  687. //
  688. // int n;
  689. // Matcher<int> m1 = Ref(n); // This won't compile.
  690. // Matcher<int&> m2 = Ref(n); // This will compile.
  691. template <typename T>
  692. class RefMatcher;
  693. template <typename T>
  694. class RefMatcher<T&> {
  695. // Google Mock is a generic framework and thus needs to support
  696. // mocking any function types, including those that take non-const
  697. // reference arguments. Therefore the template parameter T (and
  698. // Super below) can be instantiated to either a const type or a
  699. // non-const type.
  700. public:
  701. // RefMatcher() takes a T& instead of const T&, as we want the
  702. // compiler to catch using Ref(const_value) as a matcher for a
  703. // non-const reference.
  704. explicit RefMatcher(T& x) : object_(x) {} // NOLINT
  705. template <typename Super>
  706. operator Matcher<Super&>() const {
  707. // By passing object_ (type T&) to Impl(), which expects a Super&,
  708. // we make sure that Super is a super type of T. In particular,
  709. // this catches using Ref(const_value) as a matcher for a
  710. // non-const reference, as you cannot implicitly convert a const
  711. // reference to a non-const reference.
  712. return MakeMatcher(new Impl<Super>(object_));
  713. }
  714. private:
  715. template <typename Super>
  716. class Impl : public MatcherInterface<Super&> {
  717. public:
  718. explicit Impl(Super& x) : object_(x) {} // NOLINT
  719. // MatchAndExplain() takes a Super& (as opposed to const Super&)
  720. // in order to match the interface MatcherInterface<Super&>.
  721. virtual bool MatchAndExplain(
  722. Super& x, MatchResultListener* listener) const {
  723. *listener << "which is located @" << static_cast<const void*>(&x);
  724. return &x == &object_;
  725. }
  726. virtual void DescribeTo(::std::ostream* os) const {
  727. *os << "references the variable ";
  728. UniversalPrinter<Super&>::Print(object_, os);
  729. }
  730. virtual void DescribeNegationTo(::std::ostream* os) const {
  731. *os << "does not reference the variable ";
  732. UniversalPrinter<Super&>::Print(object_, os);
  733. }
  734. private:
  735. const Super& object_;
  736. GTEST_DISALLOW_ASSIGN_(Impl);
  737. };
  738. T& object_;
  739. GTEST_DISALLOW_ASSIGN_(RefMatcher);
  740. };
  741. // Polymorphic helper functions for narrow and wide string matchers.
  742. inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {
  743. return String::CaseInsensitiveCStringEquals(lhs, rhs);
  744. }
  745. inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,
  746. const wchar_t* rhs) {
  747. return String::CaseInsensitiveWideCStringEquals(lhs, rhs);
  748. }
  749. // String comparison for narrow or wide strings that can have embedded NUL
  750. // characters.
  751. template <typename StringType>
  752. bool CaseInsensitiveStringEquals(const StringType& s1,
  753. const StringType& s2) {
  754. // Are the heads equal?
  755. if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {
  756. return false;
  757. }
  758. // Skip the equal heads.
  759. const typename StringType::value_type nul = 0;
  760. const size_t i1 = s1.find(nul), i2 = s2.find(nul);
  761. // Are we at the end of either s1 or s2?
  762. if (i1 == StringType::npos || i2 == StringType::npos) {
  763. return i1 == i2;
  764. }
  765. // Are the tails equal?
  766. return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));
  767. }
  768. // String matchers.
  769. // Implements equality-based string matchers like StrEq, StrCaseNe, and etc.
  770. template <typename StringType>
  771. class StrEqualityMatcher {
  772. public:
  773. typedef typename StringType::const_pointer ConstCharPointer;
  774. StrEqualityMatcher(const StringType& str, bool expect_eq,
  775. bool case_sensitive)
  776. : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {}
  777. // When expect_eq_ is true, returns true iff s is equal to string_;
  778. // otherwise returns true iff s is not equal to string_.
  779. bool MatchAndExplain(ConstCharPointer s,
  780. MatchResultListener* listener) const {
  781. if (s == NULL) {
  782. return !expect_eq_;
  783. }
  784. return MatchAndExplain(StringType(s), listener);
  785. }
  786. bool MatchAndExplain(const StringType& s,
  787. MatchResultListener* /* listener */) const {
  788. const bool eq = case_sensitive_ ? s == string_ :
  789. CaseInsensitiveStringEquals(s, string_);
  790. return expect_eq_ == eq;
  791. }
  792. void DescribeTo(::std::ostream* os) const {
  793. DescribeToHelper(expect_eq_, os);
  794. }
  795. void DescribeNegationTo(::std::ostream* os) const {
  796. DescribeToHelper(!expect_eq_, os);
  797. }
  798. private:
  799. void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {
  800. *os << (expect_eq ? "is " : "isn't ");
  801. *os << "equal to ";
  802. if (!case_sensitive_) {
  803. *os << "(ignoring case) ";
  804. }
  805. UniversalPrint(string_, os);
  806. }
  807. const StringType string_;
  808. const bool expect_eq_;
  809. const bool case_sensitive_;
  810. GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher);
  811. };
  812. // Implements the polymorphic HasSubstr(substring) matcher, which
  813. // can be used as a Matcher<T> as long as T can be converted to a
  814. // string.
  815. template <typename StringType>
  816. class HasSubstrMatcher {
  817. public:
  818. typedef typename StringType::const_pointer ConstCharPointer;
  819. explicit HasSubstrMatcher(const StringType& substring)
  820. : substring_(substring) {}
  821. // These overloaded methods allow HasSubstr(substring) to be used as a
  822. // Matcher<T> as long as T can be converted to string. Returns true
  823. // iff s contains substring_ as a substring.
  824. bool MatchAndExplain(ConstCharPointer s,
  825. MatchResultListener* listener) const {
  826. return s != NULL && MatchAndExplain(StringType(s), listener);
  827. }
  828. bool MatchAndExplain(const StringType& s,
  829. MatchResultListener* /* listener */) const {
  830. return s.find(substring_) != StringType::npos;
  831. }
  832. // Describes what this matcher matches.
  833. void DescribeTo(::std::ostream* os) const {
  834. *os << "has substring ";
  835. UniversalPrint(substring_, os);
  836. }
  837. void DescribeNegationTo(::std::ostream* os) const {
  838. *os << "has no substring ";
  839. UniversalPrint(substring_, os);
  840. }
  841. private:
  842. const StringType substring_;
  843. GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher);
  844. };
  845. // Implements the polymorphic StartsWith(substring) matcher, which
  846. // can be used as a Matcher<T> as long as T can be converted to a
  847. // string.
  848. template <typename StringType>
  849. class StartsWithMatcher {
  850. public:
  851. typedef typename StringType::const_pointer ConstCharPointer;
  852. explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {
  853. }
  854. // These overloaded methods allow StartsWith(prefix) to be used as a
  855. // Matcher<T> as long as T can be converted to string. Returns true
  856. // iff s starts with prefix_.
  857. bool MatchAndExplain(ConstCharPointer s,
  858. MatchResultListener* listener) const {
  859. return s != NULL && MatchAndExplain(StringType(s), listener);
  860. }
  861. bool MatchAndExplain(const StringType& s,
  862. MatchResultListener* /* listener */) const {
  863. return s.length() >= prefix_.length() &&
  864. s.substr(0, prefix_.length()) == prefix_;
  865. }
  866. void DescribeTo(::std::ostream* os) const {
  867. *os << "starts with ";
  868. UniversalPrint(prefix_, os);
  869. }
  870. void DescribeNegationTo(::std::ostream* os) const {
  871. *os << "doesn't start with ";
  872. UniversalPrint(prefix_, os);
  873. }
  874. private:
  875. const StringType prefix_;
  876. GTEST_DISALLOW_ASSIGN_(StartsWithMatcher);
  877. };
  878. // Implements the polymorphic EndsWith(substring) matcher, which
  879. // can be used as a Matcher<T> as long as T can be converted to a
  880. // string.
  881. template <typename StringType>
  882. class EndsWithMatcher {
  883. public:
  884. typedef typename StringType::const_pointer ConstCharPointer;
  885. explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}
  886. // These overloaded methods allow EndsWith(suffix) to be used as a
  887. // Matcher<T> as long as T can be converted to string. Returns true
  888. // iff s ends with suffix_.
  889. bool MatchAndExplain(ConstCharPointer s,
  890. MatchResultListener* listener) const {
  891. return s != NULL && MatchAndExplain(StringType(s), listener);
  892. }
  893. bool MatchAndExplain(const StringType& s,
  894. MatchResultListener* /* listener */) const {
  895. return s.length() >= suffix_.length() &&
  896. s.substr(s.length() - suffix_.length()) == suffix_;
  897. }
  898. void DescribeTo(::std::ostream* os) const {
  899. *os << "ends with ";
  900. UniversalPrint(suffix_, os);
  901. }
  902. void DescribeNegationTo(::std::ostream* os) const {
  903. *os << "doesn't end with ";
  904. UniversalPrint(suffix_, os);
  905. }
  906. private:
  907. const StringType suffix_;
  908. GTEST_DISALLOW_ASSIGN_(EndsWithMatcher);
  909. };
  910. // Implements polymorphic matchers MatchesRegex(regex) and
  911. // ContainsRegex(regex), which can be used as a Matcher<T> as long as
  912. // T can be converted to a string.
  913. class MatchesRegexMatcher {
  914. public:
  915. MatchesRegexMatcher(const RE* regex, bool full_match)
  916. : regex_(regex), full_match_(full_match) {}
  917. // These overloaded methods allow MatchesRegex(regex) to be used as
  918. // a Matcher<T> as long as T can be converted to string. Returns
  919. // true iff s matches regular expression regex. When full_match_ is
  920. // true, a full match is done; otherwise a partial match is done.
  921. bool MatchAndExplain(const char* s,
  922. MatchResultListener* listener) const {
  923. return s != NULL && MatchAndExplain(internal::string(s), listener);
  924. }
  925. bool MatchAndExplain(const internal::string& s,
  926. MatchResultListener* /* listener */) const {
  927. return full_match_ ? RE::FullMatch(s, *regex_) :
  928. RE::PartialMatch(s, *regex_);
  929. }
  930. void DescribeTo(::std::ostream* os) const {
  931. *os << (full_match_ ? "matches" : "contains")
  932. << " regular expression ";
  933. UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
  934. }
  935. void DescribeNegationTo(::std::ostream* os) const {
  936. *os << "doesn't " << (full_match_ ? "match" : "contain")
  937. << " regular expression ";
  938. UniversalPrinter<internal::string>::Print(regex_->pattern(), os);
  939. }
  940. private:
  941. const internal::linked_ptr<const RE> regex_;
  942. const bool full_match_;
  943. GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);
  944. };
  945. // Implements a matcher that compares the two fields of a 2-tuple
  946. // using one of the ==, <=, <, etc, operators. The two fields being
  947. // compared don't have to have the same type.
  948. //
  949. // The matcher defined here is polymorphic (for example, Eq() can be
  950. // used to match a tuple<int, short>, a tuple<const long&, double>,
  951. // etc). Therefore we use a template type conversion operator in the
  952. // implementation.
  953. //
  954. // We define this as a macro in order to eliminate duplicated source
  955. // code.
  956. #define GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(name, op, relation) \
  957. class name##2Matcher { \
  958. public: \
  959. template <typename T1, typename T2> \
  960. operator Matcher< ::std::tr1::tuple<T1, T2> >() const { \
  961. return MakeMatcher(new Impl< ::std::tr1::tuple<T1, T2> >); \
  962. } \
  963. template <typename T1, typename T2> \
  964. operator Matcher<const ::std::tr1::tuple<T1, T2>&>() const { \
  965. return MakeMatcher(new Impl<const ::std::tr1::tuple<T1, T2>&>); \
  966. } \
  967. private: \
  968. template <typename Tuple> \
  969. class Impl : public MatcherInterface<Tuple> { \
  970. public: \
  971. virtual bool MatchAndExplain( \
  972. Tuple args, \
  973. MatchResultListener* /* listener */) const { \
  974. return ::std::tr1::get<0>(args) op ::std::tr1::get<1>(args); \
  975. } \
  976. virtual void DescribeTo(::std::ostream* os) const { \
  977. *os << "are " relation; \
  978. } \
  979. virtual void DescribeNegationTo(::std::ostream* os) const { \
  980. *os << "aren't " relation; \
  981. } \
  982. }; \
  983. }
  984. // Implements Eq(), Ge(), Gt(), Le(), Lt(), and Ne() respectively.
  985. GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Eq, ==, "an equal pair");
  986. GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
  987. Ge, >=, "a pair where the first >= the second");
  988. GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
  989. Gt, >, "a pair where the first > the second");
  990. GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
  991. Le, <=, "a pair where the first <= the second");
  992. GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(
  993. Lt, <, "a pair where the first < the second");
  994. GMOCK_IMPLEMENT_COMPARISON2_MATCHER_(Ne, !=, "an unequal pair");
  995. #undef GMOCK_IMPLEMENT_COMPARISON2_MATCHER_
  996. // Implements the Not(...) matcher for a particular argument type T.
  997. // We do not nest it inside the NotMatcher class template, as that
  998. // will prevent different instantiations of NotMatcher from sharing
  999. // the same NotMatcherImpl<T> class.
  1000. template <typename T>
  1001. class NotMatcherImpl : public MatcherInterface<T> {
  1002. public:
  1003. explicit NotMatcherImpl(const Matcher<T>& matcher)
  1004. : matcher_(matcher) {}
  1005. virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
  1006. return !matcher_.MatchAndExplain(x, listener);
  1007. }
  1008. virtual void DescribeTo(::std::ostream* os) const {
  1009. matcher_.DescribeNegationTo(os);
  1010. }
  1011. virtual void DescribeNegationTo(::std::ostream* os) const {
  1012. matcher_.DescribeTo(os);
  1013. }
  1014. private:
  1015. const Matcher<T> matcher_;
  1016. GTEST_DISALLOW_ASSIGN_(NotMatcherImpl);
  1017. };
  1018. // Implements the Not(m) matcher, which matches a value that doesn't
  1019. // match matcher m.
  1020. template <typename InnerMatcher>
  1021. class NotMatcher {
  1022. public:
  1023. explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}
  1024. // This template type conversion operator allows Not(m) to be used
  1025. // to match any type m can match.
  1026. template <typename T>
  1027. operator Matcher<T>() const {
  1028. return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));
  1029. }
  1030. private:
  1031. InnerMatcher matcher_;
  1032. GTEST_DISALLOW_ASSIGN_(NotMatcher);
  1033. };
  1034. // Implements the AllOf(m1, m2) matcher for a particular argument type
  1035. // T. We do not nest it inside the BothOfMatcher class template, as
  1036. // that will prevent different instantiations of BothOfMatcher from
  1037. // sharing the same BothOfMatcherImpl<T> class.
  1038. template <typename T>
  1039. class BothOfMatcherImpl : public MatcherInterface<T> {
  1040. public:
  1041. BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
  1042. : matcher1_(matcher1), matcher2_(matcher2) {}
  1043. virtual void DescribeTo(::std::ostream* os) const {
  1044. *os << "(";
  1045. matcher1_.DescribeTo(os);
  1046. *os << ") and (";
  1047. matcher2_.DescribeTo(os);
  1048. *os << ")";
  1049. }
  1050. virtual void DescribeNegationTo(::std::ostream* os) const {
  1051. *os << "(";
  1052. matcher1_.DescribeNegationTo(os);
  1053. *os << ") or (";
  1054. matcher2_.DescribeNegationTo(os);
  1055. *os << ")";
  1056. }
  1057. virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
  1058. // If either matcher1_ or matcher2_ doesn't match x, we only need
  1059. // to explain why one of them fails.
  1060. StringMatchResultListener listener1;
  1061. if (!matcher1_.MatchAndExplain(x, &listener1)) {
  1062. *listener << listener1.str();
  1063. return false;
  1064. }
  1065. StringMatchResultListener listener2;
  1066. if (!matcher2_.MatchAndExplain(x, &listener2)) {
  1067. *listener << listener2.str();
  1068. return false;
  1069. }
  1070. // Otherwise we need to explain why *both* of them match.
  1071. const internal::string s1 = listener1.str();
  1072. const internal::string s2 = listener2.str();
  1073. if (s1 == "") {
  1074. *listener << s2;
  1075. } else {
  1076. *listener << s1;
  1077. if (s2 != "") {
  1078. *listener << ", and " << s2;
  1079. }
  1080. }
  1081. return true;
  1082. }
  1083. private:
  1084. const Matcher<T> matcher1_;
  1085. const Matcher<T> matcher2_;
  1086. GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl);
  1087. };
  1088. // Used for implementing the AllOf(m_1, ..., m_n) matcher, which
  1089. // matches a value that matches all of the matchers m_1, ..., and m_n.
  1090. template <typename Matcher1, typename Matcher2>
  1091. class BothOfMatcher {
  1092. public:
  1093. BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
  1094. : matcher1_(matcher1), matcher2_(matcher2) {}
  1095. // This template type conversion operator allows a
  1096. // BothOfMatcher<Matcher1, Matcher2> object to match any type that
  1097. // both Matcher1 and Matcher2 can match.
  1098. template <typename T>
  1099. operator Matcher<T>() const {
  1100. return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_),
  1101. SafeMatcherCast<T>(matcher2_)));
  1102. }
  1103. private:
  1104. Matcher1 matcher1_;
  1105. Matcher2 matcher2_;
  1106. GTEST_DISALLOW_ASSIGN_(BothOfMatcher);
  1107. };
  1108. // Implements the AnyOf(m1, m2) matcher for a particular argument type
  1109. // T. We do not nest it inside the AnyOfMatcher class template, as
  1110. // that will prevent different instantiations of AnyOfMatcher from
  1111. // sharing the same EitherOfMatcherImpl<T> class.
  1112. template <typename T>
  1113. class EitherOfMatcherImpl : public MatcherInterface<T> {
  1114. public:
  1115. EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2)
  1116. : matcher1_(matcher1), matcher2_(matcher2) {}
  1117. virtual void DescribeTo(::std::ostream* os) const {
  1118. *os << "(";
  1119. matcher1_.DescribeTo(os);
  1120. *os << ") or (";
  1121. matcher2_.DescribeTo(os);
  1122. *os << ")";
  1123. }
  1124. virtual void DescribeNegationTo(::std::ostream* os) const {
  1125. *os << "(";
  1126. matcher1_.DescribeNegationTo(os);
  1127. *os << ") and (";
  1128. matcher2_.DescribeNegationTo(os);
  1129. *os << ")";
  1130. }
  1131. virtual bool MatchAndExplain(T x, MatchResultListener* listener) const {
  1132. // If either matcher1_ or matcher2_ matches x, we just need to
  1133. // explain why *one* of them matches.
  1134. StringMatchResultListener listener1;
  1135. if (matcher1_.MatchAndExplain(x, &listener1)) {
  1136. *listener << listener1.str();
  1137. return true;
  1138. }
  1139. StringMatchResultListener listener2;
  1140. if (matcher2_.MatchAndExplain(x, &listener2)) {
  1141. *listener << listener2.str();
  1142. return true;
  1143. }
  1144. // Otherwise we need to explain why *both* of them fail.
  1145. const internal::string s1 = listener1.str();
  1146. const internal::string s2 = listener2.str();
  1147. if (s1 == "") {
  1148. *listener << s2;
  1149. } else {
  1150. *listener << s1;
  1151. if (s2 != "") {
  1152. *listener << ", and " << s2;
  1153. }
  1154. }
  1155. return false;
  1156. }
  1157. private:
  1158. const Matcher<T> matcher1_;
  1159. const Matcher<T> matcher2_;
  1160. GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl);
  1161. };
  1162. // Used for implementing the AnyOf(m_1, ..., m_n) matcher, which
  1163. // matches a value that matches at least one of the matchers m_1, ...,
  1164. // and m_n.
  1165. template <typename Matcher1, typename Matcher2>
  1166. class EitherOfMatcher {
  1167. public:
  1168. EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2)
  1169. : matcher1_(matcher1), matcher2_(matcher2) {}
  1170. // This template type conversion operator allows a
  1171. // EitherOfMatcher<Matcher1, Matcher2> object to match any type that
  1172. // both Matcher1 and Matcher2 can match.
  1173. template <typename T>
  1174. operator Matcher<T>() const {
  1175. return Matcher<T>(new EitherOfMatcherImpl<T>(
  1176. SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_)));
  1177. }
  1178. private:
  1179. Matcher1 matcher1_;
  1180. Matcher2 matcher2_;
  1181. GTEST_DISALLOW_ASSIGN_(EitherOfMatcher);
  1182. };
  1183. // Used for implementing Truly(pred), which turns a predicate into a
  1184. // matcher.
  1185. template <typename Predicate>
  1186. class TrulyMatcher {
  1187. public:
  1188. explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}
  1189. // This method template allows Truly(pred) to be used as a matcher
  1190. // for type T where T is the argument type of predicate 'pred'. The
  1191. // argument is passed by reference as the predicate may be
  1192. // interested in the address of the argument.
  1193. template <typename T>
  1194. bool MatchAndExplain(T& x, // NOLINT
  1195. MatchResultListener* /* listener */) const {
  1196. // Without the if-statement, MSVC sometimes warns about converting
  1197. // a value to bool (warning 4800).
  1198. //
  1199. // We cannot write 'return !!predicate_(x);' as that doesn't work
  1200. // when predicate_(x) returns a class convertible to bool but
  1201. // having no operator!().
  1202. if (predicate_(x))
  1203. return true;
  1204. return false;
  1205. }
  1206. void DescribeTo(::std::ostream* os) const {
  1207. *os << "satisfies the given predicate";
  1208. }
  1209. void DescribeNegationTo(::std::ostream* os) const {
  1210. *os << "doesn't satisfy the given predicate";
  1211. }
  1212. private:
  1213. Predicate predicate_;
  1214. GTEST_DISALLOW_ASSIGN_(TrulyMatcher);
  1215. };
  1216. // Used for implementing Matches(matcher), which turns a matcher into
  1217. // a predicate.
  1218. template <typename M>
  1219. class MatcherAsPredicate {
  1220. public:
  1221. explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}
  1222. // This template operator() allows Matches(m) to be used as a
  1223. // predicate on type T where m is a matcher on type T.
  1224. //
  1225. // The argument x is passed by reference instead of by value, as
  1226. // some matcher may be interested in its address (e.g. as in
  1227. // Matches(Ref(n))(x)).
  1228. template <typename T>
  1229. bool operator()(const T& x) const {
  1230. // We let matcher_ commit to a particular type here instead of
  1231. // when the MatcherAsPredicate object was constructed. This
  1232. // allows us to write Matches(m) where m is a polymorphic matcher
  1233. // (e.g. Eq(5)).
  1234. //
  1235. // If we write Matcher<T>(matcher_).Matches(x) here, it won't
  1236. // compile when matcher_ has type Matcher<const T&>; if we write
  1237. // Matcher<const T&>(matcher_).Matches(x) here, it won't compile
  1238. // when matcher_ h…