PageRenderTime 83ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

/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
Possible License(s): LGPL-3.0, BSD-3-Clause
  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_ has type Matcher<T>; if we just write
  1239. // matcher_.Matches(x), it won't compile when matcher_ is
  1240. // polymorphic, e.g. Eq(5).
  1241. //
  1242. // MatcherCast<const T&>() is necessary for making the code work
  1243. // in all of the above situations.
  1244. return MatcherCast<const T&>(matcher_).Matches(x);
  1245. }
  1246. private:
  1247. M matcher_;
  1248. GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate);
  1249. };
  1250. // For implementing ASSERT_THAT() and EXPECT_THAT(). The template
  1251. // argument M must be a type that can be converted to a matcher.
  1252. template <typename M>
  1253. class PredicateFormatterFromMatcher {
  1254. public:
  1255. explicit PredicateFormatterFromMatcher(const M& m) : matcher_(m) {}
  1256. // This template () operator allows a PredicateFormatterFromMatcher
  1257. // object to act as a predicate-formatter suitable for using with
  1258. // Google Test's EXPECT_PRED_FORMAT1() macro.
  1259. template <typename T>
  1260. AssertionResult operator()(const char* value_text, const T& x) const {
  1261. // We convert matcher_ to a Matcher<const T&> *now* instead of
  1262. // when the PredicateFormatterFromMatcher object was constructed,
  1263. // as matcher_ may be polymorphic (e.g. NotNull()) and we won't
  1264. // know which type to instantiate it to until we actually see the
  1265. // type of x here.
  1266. //
  1267. // We write MatcherCast<const T&>(matcher_) instead of
  1268. // Matcher<const T&>(matcher_), as the latter won't compile when
  1269. // matcher_ has type Matcher<T> (e.g. An<int>()).
  1270. const Matcher<const T&> matcher = MatcherCast<const T&>(matcher_);
  1271. StringMatchResultListener listener;
  1272. if (MatchPrintAndExplain(x, matcher, &listener))
  1273. return AssertionSuccess();
  1274. ::std::stringstream ss;
  1275. ss << "Value of: " << value_text << "\n"
  1276. << "Expected: ";
  1277. matcher.DescribeTo(&ss);
  1278. ss << "\n Actual: " << listener.str();
  1279. return AssertionFailure() << ss.str();
  1280. }
  1281. private:
  1282. const M matcher_;
  1283. GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher);
  1284. };
  1285. // A helper function for converting a matcher to a predicate-formatter
  1286. // without the user needing to explicitly write the type. This is
  1287. // used for implementing ASSERT_THAT() and EXPECT_THAT().
  1288. template <typename M>
  1289. inline PredicateFormatterFromMatcher<M>
  1290. MakePredicateFormatterFromMatcher(const M& matcher) {
  1291. return PredicateFormatterFromMatcher<M>(matcher);
  1292. }
  1293. // Implements the polymorphic floating point equality matcher, which
  1294. // matches two float values using ULP-based approximation. The
  1295. // template is meant to be instantiated with FloatType being either
  1296. // float or double.
  1297. template <typename FloatType>
  1298. class FloatingEqMatcher {
  1299. public:
  1300. // Constructor for FloatingEqMatcher.
  1301. // The matcher's input will be compared with rhs. The matcher treats two
  1302. // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards,
  1303. // equality comparisons between NANs will always return false.
  1304. FloatingEqMatcher(FloatType rhs, bool nan_eq_nan) :
  1305. rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
  1306. // Implements floating point equality matcher as a Matcher<T>.
  1307. template <typename T>
  1308. class Impl : public MatcherInterface<T> {
  1309. public:
  1310. Impl(FloatType rhs, bool nan_eq_nan) :
  1311. rhs_(rhs), nan_eq_nan_(nan_eq_nan) {}
  1312. virtual bool MatchAndExplain(T value,
  1313. MatchResultListener* /* listener */) const {
  1314. const FloatingPoint<FloatType> lhs(value), rhs(rhs_);
  1315. // Compares NaNs first, if nan_eq_nan_ is true.
  1316. if (nan_eq_nan_ && lhs.is_nan()) {
  1317. return rhs.is_nan();
  1318. }
  1319. return lhs.AlmostEquals(rhs);
  1320. }
  1321. virtual void DescribeTo(::std::ostream* os) const {
  1322. // os->precision() returns the previously set precision, which we
  1323. // store to restore the ostream to its original configuration
  1324. // after outputting.
  1325. const ::std::streamsize old_precision = os->precision(
  1326. ::std::numeric_limits<FloatType>::digits10 + 2);
  1327. if (FloatingPoint<FloatType>(rhs_).is_nan()) {
  1328. if (nan_eq_nan_) {
  1329. *os << "is NaN";
  1330. } else {
  1331. *os << "never matches";
  1332. }
  1333. } else {
  1334. *os << "is approximately " << rhs_;
  1335. }
  1336. os->precision(old_precision);
  1337. }
  1338. virtual void DescribeNegationTo(::std::ostream* os) const {
  1339. // As before, get original precision.
  1340. const ::std::streamsize old_precision = os->precision(
  1341. ::std::numeric_limits<FloatType>::digits10 + 2);
  1342. if (FloatingPoint<FloatType>(rhs_).is_nan()) {
  1343. if (nan_eq_nan_) {
  1344. *os << "isn't NaN";
  1345. } else {
  1346. *os << "is anything";
  1347. }
  1348. } else {
  1349. *os << "isn't approximately " << rhs_;
  1350. }
  1351. // Restore original precision.
  1352. os->precision(old_precision);
  1353. }
  1354. private:
  1355. const FloatType rhs_;
  1356. const bool nan_eq_nan_;
  1357. GTEST_DISALLOW_ASSIGN_(Impl);
  1358. };
  1359. // The following 3 type conversion operators allow FloatEq(rhs) and
  1360. // NanSensitiveFloatEq(rhs) to be used as a Matcher<float>, a
  1361. // Matcher<const float&>, or a Matcher<float&>, but nothing else.
  1362. // (While Google's C++ coding style doesn't allow arguments passed
  1363. // by non-const reference, we may see them in code not conforming to
  1364. // the style. Therefore Google Mock needs to support them.)
  1365. operator Matcher<FloatType>() const {
  1366. return MakeMatcher(new Impl<FloatType>(rhs_, nan_eq_nan_));
  1367. }
  1368. operator Matcher<const FloatType&>() const {
  1369. return MakeMatcher(new Impl<const FloatType&>(rhs_, nan_eq_nan_));
  1370. }
  1371. operator Matcher<FloatType&>() const {
  1372. return MakeMatcher(new Impl<FloatType&>(rhs_, nan_eq_nan_));
  1373. }
  1374. private:
  1375. const FloatType rhs_;
  1376. const bool nan_eq_nan_;
  1377. GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher);
  1378. };
  1379. // Implements the Pointee(m) matcher for matching a pointer whose
  1380. // pointee matches matcher m. The pointer can be either raw or smart.
  1381. template <typename InnerMatcher>
  1382. class PointeeMatcher {
  1383. public:
  1384. explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}
  1385. // This type conversion operator template allows Pointee(m) to be
  1386. // used as a matcher for any pointer type whose pointee type is
  1387. // compatible with the inner matcher, where type Pointer can be
  1388. // either a raw pointer or a smart pointer.
  1389. //
  1390. // The reason we do this instead of relying on
  1391. // MakePolymorphicMatcher() is that the latter is not flexible
  1392. // enough for implementing the DescribeTo() method of Pointee().
  1393. template <typename Pointer>
  1394. operator Matcher<Pointer>() const {
  1395. return MakeMatcher(new Impl<Pointer>(matcher_));
  1396. }
  1397. private:
  1398. // The monomorphic implementation that works for a particular pointer type.
  1399. template <typename Pointer>
  1400. class Impl : public MatcherInterface<Pointer> {
  1401. public:
  1402. typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT
  1403. GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee;
  1404. explicit Impl(const InnerMatcher& matcher)
  1405. : matcher_(MatcherCast<const Pointee&>(matcher)) {}
  1406. virtual void DescribeTo(::std::ostream* os) const {
  1407. *os << "points to a value that ";
  1408. matcher_.DescribeTo(os);
  1409. }
  1410. virtual void DescribeNegationTo(::std::ostream* os) const {
  1411. *os << "does not point to a value that ";
  1412. matcher_.DescribeTo(os);
  1413. }
  1414. virtual bool MatchAndExplain(Pointer pointer,
  1415. MatchResultListener* listener) const {
  1416. if (GetRawPointer(pointer) == NULL)
  1417. return false;
  1418. *listener << "which points to ";
  1419. return MatchPrintAndExplain(*pointer, matcher_, listener);
  1420. }
  1421. private:
  1422. const Matcher<const Pointee&> matcher_;
  1423. GTEST_DISALLOW_ASSIGN_(Impl);
  1424. };
  1425. const InnerMatcher matcher_;
  1426. GTEST_DISALLOW_ASSIGN_(PointeeMatcher);
  1427. };
  1428. // Implements the Field() matcher for matching a field (i.e. member
  1429. // variable) of an object.
  1430. template <typename Class, typename FieldType>
  1431. class FieldMatcher {
  1432. public:
  1433. FieldMatcher(FieldType Class::*field,
  1434. const Matcher<const FieldType&>& matcher)
  1435. : field_(field), matcher_(matcher) {}
  1436. void DescribeTo(::std::ostream* os) const {
  1437. *os << "is an object whose given field ";
  1438. matcher_.DescribeTo(os);
  1439. }
  1440. void DescribeNegationTo(::std::ostream* os) const {
  1441. *os << "is an object whose given field ";
  1442. matcher_.DescribeNegationTo(os);
  1443. }
  1444. template <typename T>
  1445. bool MatchAndExplain(const T& value, MatchResultListener* listener) const {
  1446. return MatchAndExplainImpl(
  1447. typename ::testing::internal::
  1448. is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
  1449. value, listener);
  1450. }
  1451. private:
  1452. // The first argument of MatchAndExplainImpl() is needed to help
  1453. // Symbian's C++ compiler choose which overload to use. Its type is
  1454. // true_type iff the Field() matcher is used to match a pointer.
  1455. bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
  1456. MatchResultListener* listener) const {
  1457. *listener << "whose given field is ";
  1458. return MatchPrintAndExplain(obj.*field_, matcher_, listener);
  1459. }
  1460. bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
  1461. MatchResultListener* listener) const {
  1462. if (p == NULL)
  1463. return false;
  1464. *listener << "which points to an object ";
  1465. // Since *p has a field, it must be a class/struct/union type and
  1466. // thus cannot be a pointer. Therefore we pass false_type() as
  1467. // the first argument.
  1468. return MatchAndExplainImpl(false_type(), *p, listener);
  1469. }
  1470. const FieldType Class::*field_;
  1471. const Matcher<const FieldType&> matcher_;
  1472. GTEST_DISALLOW_ASSIGN_(FieldMatcher);
  1473. };
  1474. // Implements the Property() matcher for matching a property
  1475. // (i.e. return value of a getter method) of an object.
  1476. template <typename Class, typename PropertyType>
  1477. class PropertyMatcher {
  1478. public:
  1479. // The property may have a reference type, so 'const PropertyType&'
  1480. // may cause double references and fail to compile. That's why we
  1481. // need GTEST_REFERENCE_TO_CONST, which works regardless of
  1482. // PropertyType being a reference or not.
  1483. typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty;
  1484. PropertyMatcher(PropertyType (Class::*property)() const,
  1485. const Matcher<RefToConstProperty>& matcher)
  1486. : property_(property), matcher_(matcher) {}
  1487. void DescribeTo(::std::ostream* os) const {
  1488. *os << "is an object whose given property ";
  1489. matcher_.DescribeTo(os);
  1490. }
  1491. void DescribeNegationTo(::std::ostream* os) const {
  1492. *os << "is an object whose given property ";
  1493. matcher_.DescribeNegationTo(os);
  1494. }
  1495. template <typename T>
  1496. bool MatchAndExplain(const T&value, MatchResultListener* listener) const {
  1497. return MatchAndExplainImpl(
  1498. typename ::testing::internal::
  1499. is_pointer<GTEST_REMOVE_CONST_(T)>::type(),
  1500. value, listener);
  1501. }
  1502. private:
  1503. // The first argument of MatchAndExplainImpl() is needed to help
  1504. // Symbian's C++ compiler choose which overload to use. Its type is
  1505. // true_type iff the Property() matcher is used to match a pointer.
  1506. bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj,
  1507. MatchResultListener* listener) const {
  1508. *listener << "whose given property is ";
  1509. // Cannot pass the return value (for example, int) to MatchPrintAndExplain,
  1510. // which takes a non-const reference as argument.
  1511. RefToConstProperty result = (obj.*property_)();
  1512. return MatchPrintAndExplain(result, matcher_, listener);
  1513. }
  1514. bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p,
  1515. MatchResultListener* listener) const {
  1516. if (p == NULL)
  1517. return false;
  1518. *listener << "which points to an object ";
  1519. // Since *p has a property method, it must be a class/struct/union
  1520. // type and thus cannot be a pointer. Therefore we pass
  1521. // false_type() as the first argument.
  1522. return MatchAndExplainImpl(false_type(), *p, listener);
  1523. }
  1524. PropertyType (Class::*property_)() const;
  1525. const Matcher<RefToConstProperty> matcher_;
  1526. GTEST_DISALLOW_ASSIGN_(PropertyMatcher);
  1527. };
  1528. // Type traits specifying various features of different functors for ResultOf.
  1529. // The default template specifies features for functor objects.
  1530. // Functor classes have to typedef argument_type and result_type
  1531. // to be compatible with ResultOf.
  1532. template <typename Functor>
  1533. struct CallableTraits {
  1534. typedef typename Functor::result_type ResultType;
  1535. typedef Functor StorageType;
  1536. static void CheckIsValid(Functor /* functor */) {}
  1537. template <typename T>
  1538. static ResultType Invoke(Functor f, T arg) { return f(arg); }
  1539. };
  1540. // Specialization for function pointers.
  1541. template <typename ArgType, typename ResType>
  1542. struct CallableTraits<ResType(*)(ArgType)> {
  1543. typedef ResType ResultType;
  1544. typedef ResType(*StorageType)(ArgType);
  1545. static void CheckIsValid(ResType(*f)(ArgType)) {
  1546. GTEST_CHECK_(f != NULL)
  1547. << "NULL function pointer is passed into ResultOf().";
  1548. }
  1549. template <typename T>
  1550. static ResType Invoke(ResType(*f)(ArgType), T arg) {
  1551. return (*f)(arg);
  1552. }
  1553. };
  1554. // Implements the ResultOf() matcher for matching a return value of a
  1555. // unary function of an object.
  1556. template <typename Callable>
  1557. class ResultOfMatcher {
  1558. public:
  1559. typedef typename CallableTraits<Callable>::ResultType ResultType;
  1560. ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher)
  1561. : callable_(callable), matcher_(matcher) {
  1562. CallableTraits<Callable>::CheckIsValid(callable_);
  1563. }
  1564. template <typename T>
  1565. operator Matcher<T>() const {
  1566. return Matcher<T>(new Impl<T>(callable_, matcher_));
  1567. }
  1568. private:
  1569. typedef typename CallableTraits<Callable>::StorageType CallableStorageType;
  1570. template <typename T>
  1571. class Impl : public MatcherInterface<T> {
  1572. public:
  1573. Impl(CallableStorageType callable, const Matcher<ResultType>& matcher)
  1574. : callable_(callable), matcher_(matcher) {}
  1575. virtual void DescribeTo(::std::ostream* os) const {
  1576. *os << "is mapped by the given callable to a value that ";
  1577. matcher_.DescribeTo(os);
  1578. }
  1579. virtual void DescribeNegationTo(::std::ostream* os) const {
  1580. *os << "is mapped by the given callable to a value that ";
  1581. matcher_.DescribeNegationTo(os);
  1582. }
  1583. virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const {
  1584. *listener << "which is mapped by the given callable to ";
  1585. // Cannot pass the return value (for example, int) to
  1586. // MatchPrintAndExplain, which takes a non-const reference as argument.
  1587. ResultType result =
  1588. CallableTraits<Callable>::template Invoke<T>(callable_, obj);
  1589. return MatchPrintAndExplain(result, matcher_, listener);
  1590. }
  1591. private:
  1592. // Functors often define operator() as non-const method even though
  1593. // they are actualy stateless. But we need to use them even when
  1594. // 'this' is a const pointer. It's the user's responsibility not to
  1595. // use stateful callables with ResultOf(), which does't guarantee
  1596. // how many times the callable will be invoked.
  1597. mutable CallableStorageType callable_;
  1598. const Matcher<ResultType> matcher_;
  1599. GTEST_DISALLOW_ASSIGN_(Impl);
  1600. }; // class Impl
  1601. const CallableStorageType callable_;
  1602. const Matcher<ResultType> matcher_;
  1603. GTEST_DISALLOW_ASSIGN_(ResultOfMatcher);
  1604. };
  1605. // Implements an equality matcher for any STL-style container whose elements
  1606. // support ==. This matcher is like Eq(), but its failure explanations provide
  1607. // more detailed information that is useful when the container is used as a set.
  1608. // The failure message reports elements that are in one of the operands but not
  1609. // the other. The failure messages do not report duplicate or out-of-order
  1610. // elements in the containers (which don't properly matter to sets, but can
  1611. // occur if the containers are vectors or lists, for example).
  1612. //
  1613. // Uses the container's const_iterator, value_type, operator ==,
  1614. // begin(), and end().
  1615. template <typename Container>
  1616. class ContainerEqMatcher {
  1617. public:
  1618. typedef internal::StlContainerView<Container> View;
  1619. typedef typename View::type StlContainer;
  1620. typedef typename View::const_reference StlContainerReference;
  1621. // We make a copy of rhs in case the elements in it are modified
  1622. // after this matcher is created.
  1623. explicit ContainerEqMatcher(const Container& rhs) : rhs_(View::Copy(rhs)) {
  1624. // Makes sure the user doesn't instantiate this class template
  1625. // with a const or reference type.
  1626. (void)testing::StaticAssertTypeEq<Container,
  1627. GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>();
  1628. }
  1629. void DescribeTo(::std::ostream* os) const {
  1630. *os << "equals ";
  1631. UniversalPrint(rhs_, os);
  1632. }
  1633. void DescribeNegationTo(::std::ostream* os) const {
  1634. *os << "does not equal ";
  1635. UniversalPrint(rhs_, os);
  1636. }
  1637. template <typename LhsContainer>
  1638. bool MatchAndExplain(const LhsContainer& lhs,
  1639. MatchResultListener* listener) const {
  1640. // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug
  1641. // that causes LhsContainer to be a const type sometimes.
  1642. typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)>
  1643. LhsView;
  1644. typedef typename LhsView::type LhsStlContainer;
  1645. StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
  1646. if (lhs_stl_container == rhs_)
  1647. return true;
  1648. ::std::ostream* const os = listener->stream();
  1649. if (os != NULL) {
  1650. // Something is different. Check for extra values first.
  1651. bool printed_header = false;
  1652. for (typename LhsStlContainer::const_iterator it =
  1653. lhs_stl_container.begin();
  1654. it != lhs_stl_container.end(); ++it) {
  1655. if (internal::ArrayAwareFind(rhs_.begin(), rhs_.end(), *it) ==
  1656. rhs_.end()) {
  1657. if (printed_header) {
  1658. *os << ", ";
  1659. } else {
  1660. *os << "which has these unexpected elements: ";
  1661. printed_header = true;
  1662. }
  1663. UniversalPrint(*it, os);
  1664. }
  1665. }
  1666. // Now check for missing values.
  1667. bool printed_header2 = false;
  1668. for (typename StlContainer::const_iterator it = rhs_.begin();
  1669. it != rhs_.end(); ++it) {
  1670. if (internal::ArrayAwareFind(
  1671. lhs_stl_container.begin(), lhs_stl_container.end(), *it) ==
  1672. lhs_stl_container.end()) {
  1673. if (printed_header2) {
  1674. *os << ", ";
  1675. } else {
  1676. *os << (printed_header ? ",\nand" : "which")
  1677. << " doesn't have these expected elements: ";
  1678. printed_header2 = true;
  1679. }
  1680. UniversalPrint(*it, os);
  1681. }
  1682. }
  1683. }
  1684. return false;
  1685. }
  1686. private:
  1687. const StlContainer rhs_;
  1688. GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher);
  1689. };
  1690. // Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher
  1691. // must be able to be safely cast to Matcher<tuple<const T1&, const
  1692. // T2&> >, where T1 and T2 are the types of elements in the LHS
  1693. // container and the RHS container respectively.
  1694. template <typename TupleMatcher, typename RhsContainer>
  1695. class PointwiseMatcher {
  1696. public:
  1697. typedef internal::StlContainerView<RhsContainer> RhsView;
  1698. typedef typename RhsView::type RhsStlContainer;
  1699. typedef typename RhsStlContainer::value_type RhsValue;
  1700. // Like ContainerEq, we make a copy of rhs in case the elements in
  1701. // it are modified after this matcher is created.
  1702. PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)
  1703. : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {
  1704. // Makes sure the user doesn't instantiate this class template
  1705. // with a const or reference type.
  1706. (void)testing::StaticAssertTypeEq<RhsContainer,
  1707. GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>();
  1708. }
  1709. template <typename LhsContainer>
  1710. operator Matcher<LhsContainer>() const {
  1711. return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_));
  1712. }
  1713. template <typename LhsContainer>
  1714. class Impl : public MatcherInterface<LhsContainer> {
  1715. public:
  1716. typedef internal::StlContainerView<
  1717. GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView;
  1718. typedef typename LhsView::type LhsStlContainer;
  1719. typedef typename LhsView::const_reference LhsStlContainerReference;
  1720. typedef typename LhsStlContainer::value_type LhsValue;
  1721. // We pass the LHS value and the RHS value to the inner matcher by
  1722. // reference, as they may be expensive to copy. We must use tuple
  1723. // instead of pair here, as a pair cannot hold references (C++ 98,
  1724. // 20.2.2 [lib.pairs]).
  1725. typedef std::tr1::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;
  1726. Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)
  1727. // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.
  1728. : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),
  1729. rhs_(rhs) {}
  1730. virtual void DescribeTo(::std::ostream* os) const {
  1731. *os << "contains " << rhs_.size()
  1732. << " values, where each value and its corresponding value in ";
  1733. UniversalPrinter<RhsStlContainer>::Print(rhs_, os);
  1734. *os << " ";
  1735. mono_tuple_matcher_.DescribeTo(os);
  1736. }
  1737. virtual void DescribeNegationTo(::std::ostream* os) const {
  1738. *os << "doesn't contain exactly " << rhs_.size()
  1739. << " values, or contains a value x at some index i"
  1740. << " where x and the i-th value of ";
  1741. UniversalPrint(rhs_, os);
  1742. *os << " ";
  1743. mono_tuple_matcher_.DescribeNegationTo(os);
  1744. }
  1745. virtual bool MatchAndExplain(LhsContainer lhs,
  1746. MatchResultListener* listener) const {
  1747. LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);
  1748. const size_t actual_size = lhs_stl_container.size();
  1749. if (actual_size != rhs_.size()) {
  1750. *listener << "which contains " << actual_size << " values";
  1751. return false;
  1752. }
  1753. typename LhsStlContainer::const_iterator left = lhs_stl_container.begin();
  1754. typename RhsStlContainer::const_iterator right = rhs_.begin();
  1755. for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {
  1756. const InnerMatcherArg value_pair(*left, *right);
  1757. if (listener->IsInterested()) {
  1758. StringMatchResultListener inner_listener;
  1759. if (!mono_tuple_matcher_.MatchAndExplain(
  1760. value_pair, &inner_listener)) {
  1761. *listener << "where the value pair (";
  1762. UniversalPrint(*left, listener->stream());
  1763. *listener << ", ";
  1764. UniversalPrint(*right, listener->stream());
  1765. *listener << ") at index #" << i << " don't match";
  1766. PrintIfNotEmpty(inner_listener.str(), listener->stream());
  1767. return false;
  1768. }
  1769. } else {
  1770. if (!mono_tuple_matcher_.Matches(value_pair))
  1771. return false;
  1772. }
  1773. }
  1774. return true;
  1775. }
  1776. private:
  1777. const Matcher<InnerMatcherArg> mono_tuple_matcher_;
  1778. const RhsStlContainer rhs_;
  1779. GTEST_DISALLOW_ASSIGN_(Impl);
  1780. };
  1781. private:
  1782. const TupleMatcher tuple_matcher_;
  1783. const RhsStlContainer rhs_;
  1784. GTEST_DISALLOW_ASSIGN_(PointwiseMatcher);
  1785. };
  1786. // Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.
  1787. template <typename Container>
  1788. class QuantifierMatcherImpl : public MatcherInterface<Container> {
  1789. public:
  1790. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
  1791. typedef StlContainerView<RawContainer> View;
  1792. typedef typename View::type StlContainer;
  1793. typedef typename View::const_reference StlContainerReference;
  1794. typedef typename StlContainer::value_type Element;
  1795. template <typename InnerMatcher>
  1796. explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)
  1797. : inner_matcher_(
  1798. testing::SafeMatcherCast<const Element&>(inner_matcher)) {}
  1799. // Checks whether:
  1800. // * All elements in the container match, if all_elements_should_match.
  1801. // * Any element in the container matches, if !all_elements_should_match.
  1802. bool MatchAndExplainImpl(bool all_elements_should_match,
  1803. Container container,
  1804. MatchResultListener* listener) const {
  1805. StlContainerReference stl_container = View::ConstReference(container);
  1806. size_t i = 0;
  1807. for (typename StlContainer::const_iterator it = stl_container.begin();
  1808. it != stl_container.end(); ++it, ++i) {
  1809. StringMatchResultListener inner_listener;
  1810. const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);
  1811. if (matches != all_elements_should_match) {
  1812. *listener << "whose element #" << i
  1813. << (matches ? " matches" : " doesn't match");
  1814. PrintIfNotEmpty(inner_listener.str(), listener->stream());
  1815. return !all_elements_should_match;
  1816. }
  1817. }
  1818. return all_elements_should_match;
  1819. }
  1820. protected:
  1821. const Matcher<const Element&> inner_matcher_;
  1822. GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl);
  1823. };
  1824. // Implements Contains(element_matcher) for the given argument type Container.
  1825. // Symmetric to EachMatcherImpl.
  1826. template <typename Container>
  1827. class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {
  1828. public:
  1829. template <typename InnerMatcher>
  1830. explicit ContainsMatcherImpl(InnerMatcher inner_matcher)
  1831. : QuantifierMatcherImpl<Container>(inner_matcher) {}
  1832. // Describes what this matcher does.
  1833. virtual void DescribeTo(::std::ostream* os) const {
  1834. *os << "contains at least one element that ";
  1835. this->inner_matcher_.DescribeTo(os);
  1836. }
  1837. virtual void DescribeNegationTo(::std::ostream* os) const {
  1838. *os << "doesn't contain any element that ";
  1839. this->inner_matcher_.DescribeTo(os);
  1840. }
  1841. virtual bool MatchAndExplain(Container container,
  1842. MatchResultListener* listener) const {
  1843. return this->MatchAndExplainImpl(false, container, listener);
  1844. }
  1845. private:
  1846. GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl);
  1847. };
  1848. // Implements Each(element_matcher) for the given argument type Container.
  1849. // Symmetric to ContainsMatcherImpl.
  1850. template <typename Container>
  1851. class EachMatcherImpl : public QuantifierMatcherImpl<Container> {
  1852. public:
  1853. template <typename InnerMatcher>
  1854. explicit EachMatcherImpl(InnerMatcher inner_matcher)
  1855. : QuantifierMatcherImpl<Container>(inner_matcher) {}
  1856. // Describes what this matcher does.
  1857. virtual void DescribeTo(::std::ostream* os) const {
  1858. *os << "only contains elements that ";
  1859. this->inner_matcher_.DescribeTo(os);
  1860. }
  1861. virtual void DescribeNegationTo(::std::ostream* os) const {
  1862. *os << "contains some element that ";
  1863. this->inner_matcher_.DescribeNegationTo(os);
  1864. }
  1865. virtual bool MatchAndExplain(Container container,
  1866. MatchResultListener* listener) const {
  1867. return this->MatchAndExplainImpl(true, container, listener);
  1868. }
  1869. private:
  1870. GTEST_DISALLOW_ASSIGN_(EachMatcherImpl);
  1871. };
  1872. // Implements polymorphic Contains(element_matcher).
  1873. template <typename M>
  1874. class ContainsMatcher {
  1875. public:
  1876. explicit ContainsMatcher(M m) : inner_matcher_(m) {}
  1877. template <typename Container>
  1878. operator Matcher<Container>() const {
  1879. return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_));
  1880. }
  1881. private:
  1882. const M inner_matcher_;
  1883. GTEST_DISALLOW_ASSIGN_(ContainsMatcher);
  1884. };
  1885. // Implements polymorphic Each(element_matcher).
  1886. template <typename M>
  1887. class EachMatcher {
  1888. public:
  1889. explicit EachMatcher(M m) : inner_matcher_(m) {}
  1890. template <typename Container>
  1891. operator Matcher<Container>() const {
  1892. return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_));
  1893. }
  1894. private:
  1895. const M inner_matcher_;
  1896. GTEST_DISALLOW_ASSIGN_(EachMatcher);
  1897. };
  1898. // Implements Key(inner_matcher) for the given argument pair type.
  1899. // Key(inner_matcher) matches an std::pair whose 'first' field matches
  1900. // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
  1901. // std::map that contains at least one element whose key is >= 5.
  1902. template <typename PairType>
  1903. class KeyMatcherImpl : public MatcherInterface<PairType> {
  1904. public:
  1905. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
  1906. typedef typename RawPairType::first_type KeyType;
  1907. template <typename InnerMatcher>
  1908. explicit KeyMatcherImpl(InnerMatcher inner_matcher)
  1909. : inner_matcher_(
  1910. testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {
  1911. }
  1912. // Returns true iff 'key_value.first' (the key) matches the inner matcher.
  1913. virtual bool MatchAndExplain(PairType key_value,
  1914. MatchResultListener* listener) const {
  1915. StringMatchResultListener inner_listener;
  1916. const bool match = inner_matcher_.MatchAndExplain(key_value.first,
  1917. &inner_listener);
  1918. const internal::string explanation = inner_listener.str();
  1919. if (explanation != "") {
  1920. *listener << "whose first field is a value " << explanation;
  1921. }
  1922. return match;
  1923. }
  1924. // Describes what this matcher does.
  1925. virtual void DescribeTo(::std::ostream* os) const {
  1926. *os << "has a key that ";
  1927. inner_matcher_.DescribeTo(os);
  1928. }
  1929. // Describes what the negation of this matcher does.
  1930. virtual void DescribeNegationTo(::std::ostream* os) const {
  1931. *os << "doesn't have a key that ";
  1932. inner_matcher_.DescribeTo(os);
  1933. }
  1934. private:
  1935. const Matcher<const KeyType&> inner_matcher_;
  1936. GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl);
  1937. };
  1938. // Implements polymorphic Key(matcher_for_key).
  1939. template <typename M>
  1940. class KeyMatcher {
  1941. public:
  1942. explicit KeyMatcher(M m) : matcher_for_key_(m) {}
  1943. template <typename PairType>
  1944. operator Matcher<PairType>() const {
  1945. return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_));
  1946. }
  1947. private:
  1948. const M matcher_for_key_;
  1949. GTEST_DISALLOW_ASSIGN_(KeyMatcher);
  1950. };
  1951. // Implements Pair(first_matcher, second_matcher) for the given argument pair
  1952. // type with its two matchers. See Pair() function below.
  1953. template <typename PairType>
  1954. class PairMatcherImpl : public MatcherInterface<PairType> {
  1955. public:
  1956. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;
  1957. typedef typename RawPairType::first_type FirstType;
  1958. typedef typename RawPairType::second_type SecondType;
  1959. template <typename FirstMatcher, typename SecondMatcher>
  1960. PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)
  1961. : first_matcher_(
  1962. testing::SafeMatcherCast<const FirstType&>(first_matcher)),
  1963. second_matcher_(
  1964. testing::SafeMatcherCast<const SecondType&>(second_matcher)) {
  1965. }
  1966. // Describes what this matcher does.
  1967. virtual void DescribeTo(::std::ostream* os) const {
  1968. *os << "has a first field that ";
  1969. first_matcher_.DescribeTo(os);
  1970. *os << ", and has a second field that ";
  1971. second_matcher_.DescribeTo(os);
  1972. }
  1973. // Describes what the negation of this matcher does.
  1974. virtual void DescribeNegationTo(::std::ostream* os) const {
  1975. *os << "has a first field that ";
  1976. first_matcher_.DescribeNegationTo(os);
  1977. *os << ", or has a second field that ";
  1978. second_matcher_.DescribeNegationTo(os);
  1979. }
  1980. // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second'
  1981. // matches second_matcher.
  1982. virtual bool MatchAndExplain(PairType a_pair,
  1983. MatchResultListener* listener) const {
  1984. if (!listener->IsInterested()) {
  1985. // If the listener is not interested, we don't need to construct the
  1986. // explanation.
  1987. return first_matcher_.Matches(a_pair.first) &&
  1988. second_matcher_.Matches(a_pair.second);
  1989. }
  1990. StringMatchResultListener first_inner_listener;
  1991. if (!first_matcher_.MatchAndExplain(a_pair.first,
  1992. &first_inner_listener)) {
  1993. *listener << "whose first field does not match";
  1994. PrintIfNotEmpty(first_inner_listener.str(), listener->stream());
  1995. return false;
  1996. }
  1997. StringMatchResultListener second_inner_listener;
  1998. if (!second_matcher_.MatchAndExplain(a_pair.second,
  1999. &second_inner_listener)) {
  2000. *listener << "whose second field does not match";
  2001. PrintIfNotEmpty(second_inner_listener.str(), listener->stream());
  2002. return false;
  2003. }
  2004. ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),
  2005. listener);
  2006. return true;
  2007. }
  2008. private:
  2009. void ExplainSuccess(const internal::string& first_explanation,
  2010. const internal::string& second_explanation,
  2011. MatchResultListener* listener) const {
  2012. *listener << "whose both fields match";
  2013. if (first_explanation != "") {
  2014. *listener << ", where the first field is a value " << first_explanation;
  2015. }
  2016. if (second_explanation != "") {
  2017. *listener << ", ";
  2018. if (first_explanation != "") {
  2019. *listener << "and ";
  2020. } else {
  2021. *listener << "where ";
  2022. }
  2023. *listener << "the second field is a value " << second_explanation;
  2024. }
  2025. }
  2026. const Matcher<const FirstType&> first_matcher_;
  2027. const Matcher<const SecondType&> second_matcher_;
  2028. GTEST_DISALLOW_ASSIGN_(PairMatcherImpl);
  2029. };
  2030. // Implements polymorphic Pair(first_matcher, second_matcher).
  2031. template <typename FirstMatcher, typename SecondMatcher>
  2032. class PairMatcher {
  2033. public:
  2034. PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)
  2035. : first_matcher_(first_matcher), second_matcher_(second_matcher) {}
  2036. template <typename PairType>
  2037. operator Matcher<PairType> () const {
  2038. return MakeMatcher(
  2039. new PairMatcherImpl<PairType>(
  2040. first_matcher_, second_matcher_));
  2041. }
  2042. private:
  2043. const FirstMatcher first_matcher_;
  2044. const SecondMatcher second_matcher_;
  2045. GTEST_DISALLOW_ASSIGN_(PairMatcher);
  2046. };
  2047. // Implements ElementsAre() and ElementsAreArray().
  2048. template <typename Container>
  2049. class ElementsAreMatcherImpl : public MatcherInterface<Container> {
  2050. public:
  2051. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
  2052. typedef internal::StlContainerView<RawContainer> View;
  2053. typedef typename View::type StlContainer;
  2054. typedef typename View::const_reference StlContainerReference;
  2055. typedef typename StlContainer::value_type Element;
  2056. // Constructs the matcher from a sequence of element values or
  2057. // element matchers.
  2058. template <typename InputIter>
  2059. ElementsAreMatcherImpl(InputIter first, size_t a_count) {
  2060. matchers_.reserve(a_count);
  2061. InputIter it = first;
  2062. for (size_t i = 0; i != a_count; ++i, ++it) {
  2063. matchers_.push_back(MatcherCast<const Element&>(*it));
  2064. }
  2065. }
  2066. // Describes what this matcher does.
  2067. virtual void DescribeTo(::std::ostream* os) const {
  2068. if (count() == 0) {
  2069. *os << "is empty";
  2070. } else if (count() == 1) {
  2071. *os << "has 1 element that ";
  2072. matchers_[0].DescribeTo(os);
  2073. } else {
  2074. *os << "has " << Elements(count()) << " where\n";
  2075. for (size_t i = 0; i != count(); ++i) {
  2076. *os << "element #" << i << " ";
  2077. matchers_[i].DescribeTo(os);
  2078. if (i + 1 < count()) {
  2079. *os << ",\n";
  2080. }
  2081. }
  2082. }
  2083. }
  2084. // Describes what the negation of this matcher does.
  2085. virtual void DescribeNegationTo(::std::ostream* os) const {
  2086. if (count() == 0) {
  2087. *os << "isn't empty";
  2088. return;
  2089. }
  2090. *os << "doesn't have " << Elements(count()) << ", or\n";
  2091. for (size_t i = 0; i != count(); ++i) {
  2092. *os << "element #" << i << " ";
  2093. matchers_[i].DescribeNegationTo(os);
  2094. if (i + 1 < count()) {
  2095. *os << ", or\n";
  2096. }
  2097. }
  2098. }
  2099. virtual bool MatchAndExplain(Container container,
  2100. MatchResultListener* listener) const {
  2101. StlContainerReference stl_container = View::ConstReference(container);
  2102. const size_t actual_count = stl_container.size();
  2103. if (actual_count != count()) {
  2104. // The element count doesn't match. If the container is empty,
  2105. // there's no need to explain anything as Google Mock already
  2106. // prints the empty container. Otherwise we just need to show
  2107. // how many elements there actually are.
  2108. if (actual_count != 0) {
  2109. *listener << "which has " << Elements(actual_count);
  2110. }
  2111. return false;
  2112. }
  2113. typename StlContainer::const_iterator it = stl_container.begin();
  2114. // explanations[i] is the explanation of the element at index i.
  2115. std::vector<internal::string> explanations(count());
  2116. for (size_t i = 0; i != count(); ++it, ++i) {
  2117. StringMatchResultListener s;
  2118. if (matchers_[i].MatchAndExplain(*it, &s)) {
  2119. explanations[i] = s.str();
  2120. } else {
  2121. // The container has the right size but the i-th element
  2122. // doesn't match its expectation.
  2123. *listener << "whose element #" << i << " doesn't match";
  2124. PrintIfNotEmpty(s.str(), listener->stream());
  2125. return false;
  2126. }
  2127. }
  2128. // Every element matches its expectation. We need to explain why
  2129. // (the obvious ones can be skipped).
  2130. bool reason_printed = false;
  2131. for (size_t i = 0; i != count(); ++i) {
  2132. const internal::string& s = explanations[i];
  2133. if (!s.empty()) {
  2134. if (reason_printed) {
  2135. *listener << ",\nand ";
  2136. }
  2137. *listener << "whose element #" << i << " matches, " << s;
  2138. reason_printed = true;
  2139. }
  2140. }
  2141. return true;
  2142. }
  2143. private:
  2144. static Message Elements(size_t count) {
  2145. return Message() << count << (count == 1 ? " element" : " elements");
  2146. }
  2147. size_t count() const { return matchers_.size(); }
  2148. std::vector<Matcher<const Element&> > matchers_;
  2149. GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl);
  2150. };
  2151. // Implements ElementsAre() of 0 arguments.
  2152. class ElementsAreMatcher0 {
  2153. public:
  2154. ElementsAreMatcher0() {}
  2155. template <typename Container>
  2156. operator Matcher<Container>() const {
  2157. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
  2158. typedef typename internal::StlContainerView<RawContainer>::type::value_type
  2159. Element;
  2160. const Matcher<const Element&>* const matchers = NULL;
  2161. return MakeMatcher(new ElementsAreMatcherImpl<Container>(matchers, 0));
  2162. }
  2163. };
  2164. // Implements ElementsAreArray().
  2165. template <typename T>
  2166. class ElementsAreArrayMatcher {
  2167. public:
  2168. ElementsAreArrayMatcher(const T* first, size_t count) :
  2169. first_(first), count_(count) {}
  2170. template <typename Container>
  2171. operator Matcher<Container>() const {
  2172. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;
  2173. typedef typename internal::StlContainerView<RawContainer>::type::value_type
  2174. Element;
  2175. return MakeMatcher(new ElementsAreMatcherImpl<Container>(first_, count_));
  2176. }
  2177. private:
  2178. const T* const first_;
  2179. const size_t count_;
  2180. GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher);
  2181. };
  2182. // Returns the description for a matcher defined using the MATCHER*()
  2183. // macro where the user-supplied description string is "", if
  2184. // 'negation' is false; otherwise returns the description of the
  2185. // negation of the matcher. 'param_values' contains a list of strings
  2186. // that are the print-out of the matcher's parameters.
  2187. string FormatMatcherDescription(bool negation, const char* matcher_name,
  2188. const Strings& param_values);
  2189. } // namespace internal
  2190. // Implements MatcherCast().
  2191. template <typename T, typename M>
  2192. inline Matcher<T> MatcherCast(M matcher) {
  2193. return internal::MatcherCastImpl<T, M>::Cast(matcher);
  2194. }
  2195. // _ is a matcher that matches anything of any type.
  2196. //
  2197. // This definition is fine as:
  2198. //
  2199. // 1. The C++ standard permits using the name _ in a namespace that
  2200. // is not the global namespace or ::std.
  2201. // 2. The AnythingMatcher class has no data member or constructor,
  2202. // so it's OK to create global variables of this type.
  2203. // 3. c-style has approved of using _ in this case.
  2204. const internal::AnythingMatcher _ = {};
  2205. // Creates a matcher that matches any value of the given type T.
  2206. template <typename T>
  2207. inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); }
  2208. // Creates a matcher that matches any value of the given type T.
  2209. template <typename T>
  2210. inline Matcher<T> An() { return A<T>(); }
  2211. // Creates a polymorphic matcher that matches anything equal to x.
  2212. // Note: if the parameter of Eq() were declared as const T&, Eq("foo")
  2213. // wouldn't compile.
  2214. template <typename T>
  2215. inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); }
  2216. // Constructs a Matcher<T> from a 'value' of type T. The constructed
  2217. // matcher matches any value that's equal to 'value'.
  2218. template <typename T>
  2219. Matcher<T>::Matcher(T value) { *this = Eq(value); }
  2220. // Creates a monomorphic matcher that matches anything with type Lhs
  2221. // and equal to rhs. A user may need to use this instead of Eq(...)
  2222. // in order to resolve an overloading ambiguity.
  2223. //
  2224. // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))
  2225. // or Matcher<T>(x), but more readable than the latter.
  2226. //
  2227. // We could define similar monomorphic matchers for other comparison
  2228. // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do
  2229. // it yet as those are used much less than Eq() in practice. A user
  2230. // can always write Matcher<T>(Lt(5)) to be explicit about the type,
  2231. // for example.
  2232. template <typename Lhs, typename Rhs>
  2233. inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); }
  2234. // Creates a polymorphic matcher that matches anything >= x.
  2235. template <typename Rhs>
  2236. inline internal::GeMatcher<Rhs> Ge(Rhs x) {
  2237. return internal::GeMatcher<Rhs>(x);
  2238. }
  2239. // Creates a polymorphic matcher that matches anything > x.
  2240. template <typename Rhs>
  2241. inline internal::GtMatcher<Rhs> Gt(Rhs x) {
  2242. return internal::GtMatcher<Rhs>(x);
  2243. }
  2244. // Creates a polymorphic matcher that matches anything <= x.
  2245. template <typename Rhs>
  2246. inline internal::LeMatcher<Rhs> Le(Rhs x) {
  2247. return internal::LeMatcher<Rhs>(x);
  2248. }
  2249. // Creates a polymorphic matcher that matches anything < x.
  2250. template <typename Rhs>
  2251. inline internal::LtMatcher<Rhs> Lt(Rhs x) {
  2252. return internal::LtMatcher<Rhs>(x);
  2253. }
  2254. // Creates a polymorphic matcher that matches anything != x.
  2255. template <typename Rhs>
  2256. inline internal::NeMatcher<Rhs> Ne(Rhs x) {
  2257. return internal::NeMatcher<Rhs>(x);
  2258. }
  2259. // Creates a polymorphic matcher that matches any NULL pointer.
  2260. inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() {
  2261. return MakePolymorphicMatcher(internal::IsNullMatcher());
  2262. }
  2263. // Creates a polymorphic matcher that matches any non-NULL pointer.
  2264. // This is convenient as Not(NULL) doesn't compile (the compiler
  2265. // thinks that that expression is comparing a pointer with an integer).
  2266. inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() {
  2267. return MakePolymorphicMatcher(internal::NotNullMatcher());
  2268. }
  2269. // Creates a polymorphic matcher that matches any argument that
  2270. // references variable x.
  2271. template <typename T>
  2272. inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT
  2273. return internal::RefMatcher<T&>(x);
  2274. }
  2275. // Creates a matcher that matches any double argument approximately
  2276. // equal to rhs, where two NANs are considered unequal.
  2277. inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {
  2278. return internal::FloatingEqMatcher<double>(rhs, false);
  2279. }
  2280. // Creates a matcher that matches any double argument approximately
  2281. // equal to rhs, including NaN values when rhs is NaN.
  2282. inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {
  2283. return internal::FloatingEqMatcher<double>(rhs, true);
  2284. }
  2285. // Creates a matcher that matches any float argument approximately
  2286. // equal to rhs, where two NANs are considered unequal.
  2287. inline internal::FloatingEqMatcher<float> FloatEq(float rhs) {
  2288. return internal::FloatingEqMatcher<float>(rhs, false);
  2289. }
  2290. // Creates a matcher that matches any double argument approximately
  2291. // equal to rhs, including NaN values when rhs is NaN.
  2292. inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {
  2293. return internal::FloatingEqMatcher<float>(rhs, true);
  2294. }
  2295. // Creates a matcher that matches a pointer (raw or smart) that points
  2296. // to a value that matches inner_matcher.
  2297. template <typename InnerMatcher>
  2298. inline internal::PointeeMatcher<InnerMatcher> Pointee(
  2299. const InnerMatcher& inner_matcher) {
  2300. return internal::PointeeMatcher<InnerMatcher>(inner_matcher);
  2301. }
  2302. // Creates a matcher that matches an object whose given field matches
  2303. // 'matcher'. For example,
  2304. // Field(&Foo::number, Ge(5))
  2305. // matches a Foo object x iff x.number >= 5.
  2306. template <typename Class, typename FieldType, typename FieldMatcher>
  2307. inline PolymorphicMatcher<
  2308. internal::FieldMatcher<Class, FieldType> > Field(
  2309. FieldType Class::*field, const FieldMatcher& matcher) {
  2310. return MakePolymorphicMatcher(
  2311. internal::FieldMatcher<Class, FieldType>(
  2312. field, MatcherCast<const FieldType&>(matcher)));
  2313. // The call to MatcherCast() is required for supporting inner
  2314. // matchers of compatible types. For example, it allows
  2315. // Field(&Foo::bar, m)
  2316. // to compile where bar is an int32 and m is a matcher for int64.
  2317. }
  2318. // Creates a matcher that matches an object whose given property
  2319. // matches 'matcher'. For example,
  2320. // Property(&Foo::str, StartsWith("hi"))
  2321. // matches a Foo object x iff x.str() starts with "hi".
  2322. template <typename Class, typename PropertyType, typename PropertyMatcher>
  2323. inline PolymorphicMatcher<
  2324. internal::PropertyMatcher<Class, PropertyType> > Property(
  2325. PropertyType (Class::*property)() const, const PropertyMatcher& matcher) {
  2326. return MakePolymorphicMatcher(
  2327. internal::PropertyMatcher<Class, PropertyType>(
  2328. property,
  2329. MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher)));
  2330. // The call to MatcherCast() is required for supporting inner
  2331. // matchers of compatible types. For example, it allows
  2332. // Property(&Foo::bar, m)
  2333. // to compile where bar() returns an int32 and m is a matcher for int64.
  2334. }
  2335. // Creates a matcher that matches an object iff the result of applying
  2336. // a callable to x matches 'matcher'.
  2337. // For example,
  2338. // ResultOf(f, StartsWith("hi"))
  2339. // matches a Foo object x iff f(x) starts with "hi".
  2340. // callable parameter can be a function, function pointer, or a functor.
  2341. // Callable has to satisfy the following conditions:
  2342. // * It is required to keep no state affecting the results of
  2343. // the calls on it and make no assumptions about how many calls
  2344. // will be made. Any state it keeps must be protected from the
  2345. // concurrent access.
  2346. // * If it is a function object, it has to define type result_type.
  2347. // We recommend deriving your functor classes from std::unary_function.
  2348. template <typename Callable, typename ResultOfMatcher>
  2349. internal::ResultOfMatcher<Callable> ResultOf(
  2350. Callable callable, const ResultOfMatcher& matcher) {
  2351. return internal::ResultOfMatcher<Callable>(
  2352. callable,
  2353. MatcherCast<typename internal::CallableTraits<Callable>::ResultType>(
  2354. matcher));
  2355. // The call to MatcherCast() is required for supporting inner
  2356. // matchers of compatible types. For example, it allows
  2357. // ResultOf(Function, m)
  2358. // to compile where Function() returns an int32 and m is a matcher for int64.
  2359. }
  2360. // String matchers.
  2361. // Matches a string equal to str.
  2362. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
  2363. StrEq(const internal::string& str) {
  2364. return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
  2365. str, true, true));
  2366. }
  2367. // Matches a string not equal to str.
  2368. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
  2369. StrNe(const internal::string& str) {
  2370. return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
  2371. str, false, true));
  2372. }
  2373. // Matches a string equal to str, ignoring case.
  2374. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
  2375. StrCaseEq(const internal::string& str) {
  2376. return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
  2377. str, true, false));
  2378. }
  2379. // Matches a string not equal to str, ignoring case.
  2380. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> >
  2381. StrCaseNe(const internal::string& str) {
  2382. return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>(
  2383. str, false, false));
  2384. }
  2385. // Creates a matcher that matches any string, std::string, or C string
  2386. // that contains the given substring.
  2387. inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> >
  2388. HasSubstr(const internal::string& substring) {
  2389. return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>(
  2390. substring));
  2391. }
  2392. // Matches a string that starts with 'prefix' (case-sensitive).
  2393. inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> >
  2394. StartsWith(const internal::string& prefix) {
  2395. return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>(
  2396. prefix));
  2397. }
  2398. // Matches a string that ends with 'suffix' (case-sensitive).
  2399. inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> >
  2400. EndsWith(const internal::string& suffix) {
  2401. return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>(
  2402. suffix));
  2403. }
  2404. // Matches a string that fully matches regular expression 'regex'.
  2405. // The matcher takes ownership of 'regex'.
  2406. inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
  2407. const internal::RE* regex) {
  2408. return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));
  2409. }
  2410. inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(
  2411. const internal::string& regex) {
  2412. return MatchesRegex(new internal::RE(regex));
  2413. }
  2414. // Matches a string that contains regular expression 'regex'.
  2415. // The matcher takes ownership of 'regex'.
  2416. inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
  2417. const internal::RE* regex) {
  2418. return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));
  2419. }
  2420. inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(
  2421. const internal::string& regex) {
  2422. return ContainsRegex(new internal::RE(regex));
  2423. }
  2424. #if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
  2425. // Wide string matchers.
  2426. // Matches a string equal to str.
  2427. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
  2428. StrEq(const internal::wstring& str) {
  2429. return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
  2430. str, true, true));
  2431. }
  2432. // Matches a string not equal to str.
  2433. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
  2434. StrNe(const internal::wstring& str) {
  2435. return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
  2436. str, false, true));
  2437. }
  2438. // Matches a string equal to str, ignoring case.
  2439. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
  2440. StrCaseEq(const internal::wstring& str) {
  2441. return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
  2442. str, true, false));
  2443. }
  2444. // Matches a string not equal to str, ignoring case.
  2445. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> >
  2446. StrCaseNe(const internal::wstring& str) {
  2447. return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>(
  2448. str, false, false));
  2449. }
  2450. // Creates a matcher that matches any wstring, std::wstring, or C wide string
  2451. // that contains the given substring.
  2452. inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> >
  2453. HasSubstr(const internal::wstring& substring) {
  2454. return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>(
  2455. substring));
  2456. }
  2457. // Matches a string that starts with 'prefix' (case-sensitive).
  2458. inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> >
  2459. StartsWith(const internal::wstring& prefix) {
  2460. return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>(
  2461. prefix));
  2462. }
  2463. // Matches a string that ends with 'suffix' (case-sensitive).
  2464. inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> >
  2465. EndsWith(const internal::wstring& suffix) {
  2466. return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>(
  2467. suffix));
  2468. }
  2469. #endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING
  2470. // Creates a polymorphic matcher that matches a 2-tuple where the
  2471. // first field == the second field.
  2472. inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }
  2473. // Creates a polymorphic matcher that matches a 2-tuple where the
  2474. // first field >= the second field.
  2475. inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }
  2476. // Creates a polymorphic matcher that matches a 2-tuple where the
  2477. // first field > the second field.
  2478. inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }
  2479. // Creates a polymorphic matcher that matches a 2-tuple where the
  2480. // first field <= the second field.
  2481. inline internal::Le2Matcher Le() { return internal::Le2Matcher(); }
  2482. // Creates a polymorphic matcher that matches a 2-tuple where the
  2483. // first field < the second field.
  2484. inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }
  2485. // Creates a polymorphic matcher that matches a 2-tuple where the
  2486. // first field != the second field.
  2487. inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }
  2488. // Creates a matcher that matches any value of type T that m doesn't
  2489. // match.
  2490. template <typename InnerMatcher>
  2491. inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {
  2492. return internal::NotMatcher<InnerMatcher>(m);
  2493. }
  2494. // Returns a matcher that matches anything that satisfies the given
  2495. // predicate. The predicate can be any unary function or functor
  2496. // whose return type can be implicitly converted to bool.
  2497. template <typename Predicate>
  2498. inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> >
  2499. Truly(Predicate pred) {
  2500. return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));
  2501. }
  2502. // Returns a matcher that matches an equal container.
  2503. // This matcher behaves like Eq(), but in the event of mismatch lists the
  2504. // values that are included in one container but not the other. (Duplicate
  2505. // values and order differences are not explained.)
  2506. template <typename Container>
  2507. inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT
  2508. GTEST_REMOVE_CONST_(Container)> >
  2509. ContainerEq(const Container& rhs) {
  2510. // This following line is for working around a bug in MSVC 8.0,
  2511. // which causes Container to be a const type sometimes.
  2512. typedef GTEST_REMOVE_CONST_(Container) RawContainer;
  2513. return MakePolymorphicMatcher(
  2514. internal::ContainerEqMatcher<RawContainer>(rhs));
  2515. }
  2516. // Matches an STL-style container or a native array that contains the
  2517. // same number of elements as in rhs, where its i-th element and rhs's
  2518. // i-th element (as a pair) satisfy the given pair matcher, for all i.
  2519. // TupleMatcher must be able to be safely cast to Matcher<tuple<const
  2520. // T1&, const T2&> >, where T1 and T2 are the types of elements in the
  2521. // LHS container and the RHS container respectively.
  2522. template <typename TupleMatcher, typename Container>
  2523. inline internal::PointwiseMatcher<TupleMatcher,
  2524. GTEST_REMOVE_CONST_(Container)>
  2525. Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {
  2526. // This following line is for working around a bug in MSVC 8.0,
  2527. // which causes Container to be a const type sometimes.
  2528. typedef GTEST_REMOVE_CONST_(Container) RawContainer;
  2529. return internal::PointwiseMatcher<TupleMatcher, RawContainer>(
  2530. tuple_matcher, rhs);
  2531. }
  2532. // Matches an STL-style container or a native array that contains at
  2533. // least one element matching the given value or matcher.
  2534. //
  2535. // Examples:
  2536. // ::std::set<int> page_ids;
  2537. // page_ids.insert(3);
  2538. // page_ids.insert(1);
  2539. // EXPECT_THAT(page_ids, Contains(1));
  2540. // EXPECT_THAT(page_ids, Contains(Gt(2)));
  2541. // EXPECT_THAT(page_ids, Not(Contains(4)));
  2542. //
  2543. // ::std::map<int, size_t> page_lengths;
  2544. // page_lengths[1] = 100;
  2545. // EXPECT_THAT(page_lengths,
  2546. // Contains(::std::pair<const int, size_t>(1, 100)));
  2547. //
  2548. // const char* user_ids[] = { "joe", "mike", "tom" };
  2549. // EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom"))));
  2550. template <typename M>
  2551. inline internal::ContainsMatcher<M> Contains(M matcher) {
  2552. return internal::ContainsMatcher<M>(matcher);
  2553. }
  2554. // Matches an STL-style container or a native array that contains only
  2555. // elements matching the given value or matcher.
  2556. //
  2557. // Each(m) is semantically equivalent to Not(Contains(Not(m))). Only
  2558. // the messages are different.
  2559. //
  2560. // Examples:
  2561. // ::std::set<int> page_ids;
  2562. // // Each(m) matches an empty container, regardless of what m is.
  2563. // EXPECT_THAT(page_ids, Each(Eq(1)));
  2564. // EXPECT_THAT(page_ids, Each(Eq(77)));
  2565. //
  2566. // page_ids.insert(3);
  2567. // EXPECT_THAT(page_ids, Each(Gt(0)));
  2568. // EXPECT_THAT(page_ids, Not(Each(Gt(4))));
  2569. // page_ids.insert(1);
  2570. // EXPECT_THAT(page_ids, Not(Each(Lt(2))));
  2571. //
  2572. // ::std::map<int, size_t> page_lengths;
  2573. // page_lengths[1] = 100;
  2574. // page_lengths[2] = 200;
  2575. // page_lengths[3] = 300;
  2576. // EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));
  2577. // EXPECT_THAT(page_lengths, Each(Key(Le(3))));
  2578. //
  2579. // const char* user_ids[] = { "joe", "mike", "tom" };
  2580. // EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom")))));
  2581. template <typename M>
  2582. inline internal::EachMatcher<M> Each(M matcher) {
  2583. return internal::EachMatcher<M>(matcher);
  2584. }
  2585. // Key(inner_matcher) matches an std::pair whose 'first' field matches
  2586. // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an
  2587. // std::map that contains at least one element whose key is >= 5.
  2588. template <typename M>
  2589. inline internal::KeyMatcher<M> Key(M inner_matcher) {
  2590. return internal::KeyMatcher<M>(inner_matcher);
  2591. }
  2592. // Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field
  2593. // matches first_matcher and whose 'second' field matches second_matcher. For
  2594. // example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used
  2595. // to match a std::map<int, string> that contains exactly one element whose key
  2596. // is >= 5 and whose value equals "foo".
  2597. template <typename FirstMatcher, typename SecondMatcher>
  2598. inline internal::PairMatcher<FirstMatcher, SecondMatcher>
  2599. Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) {
  2600. return internal::PairMatcher<FirstMatcher, SecondMatcher>(
  2601. first_matcher, second_matcher);
  2602. }
  2603. // Returns a predicate that is satisfied by anything that matches the
  2604. // given matcher.
  2605. template <typename M>
  2606. inline internal::MatcherAsPredicate<M> Matches(M matcher) {
  2607. return internal::MatcherAsPredicate<M>(matcher);
  2608. }
  2609. // Returns true iff the value matches the matcher.
  2610. template <typename T, typename M>
  2611. inline bool Value(const T& value, M matcher) {
  2612. return testing::Matches(matcher)(value);
  2613. }
  2614. // Matches the value against the given matcher and explains the match
  2615. // result to listener.
  2616. template <typename T, typename M>
  2617. inline bool ExplainMatchResult(
  2618. M matcher, const T& value, MatchResultListener* listener) {
  2619. return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);
  2620. }
  2621. // AllArgs(m) is a synonym of m. This is useful in
  2622. //
  2623. // EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));
  2624. //
  2625. // which is easier to read than
  2626. //
  2627. // EXPECT_CALL(foo, Bar(_, _)).With(Eq());
  2628. template <typename InnerMatcher>
  2629. inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; }
  2630. // These macros allow using matchers to check values in Google Test
  2631. // tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)
  2632. // succeed iff the value matches the matcher. If the assertion fails,
  2633. // the value and the description of the matcher will be printed.
  2634. #define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\
  2635. ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
  2636. #define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\
  2637. ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)
  2638. } // namespace testing
  2639. #endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_