/third_party/gmock/test/gmock-matchers_test.cc

https://code.google.com/ · C++ · 5247 lines · 3835 code · 837 blank · 575 comment · 70 complexity · 66027d3769968bdc28b9a9671a8d1e39 MD5 · raw file

  1. // Copyright 2007, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. //
  30. // Author: wan@google.com (Zhanyong Wan)
  31. // Google Mock - a framework for writing C++ mock classes.
  32. //
  33. // This file tests some commonly used argument matchers.
  34. #include "gmock/gmock-matchers.h"
  35. #include "gmock/gmock-more-matchers.h"
  36. #include <string.h>
  37. #include <time.h>
  38. #include <deque>
  39. #include <functional>
  40. #include <iostream>
  41. #include <iterator>
  42. #include <limits>
  43. #include <list>
  44. #include <map>
  45. #include <set>
  46. #include <sstream>
  47. #include <string>
  48. #include <utility>
  49. #include <vector>
  50. #include "gmock/gmock.h"
  51. #include "gtest/gtest.h"
  52. #include "gtest/gtest-spi.h"
  53. namespace testing {
  54. namespace internal {
  55. GTEST_API_ string JoinAsTuple(const Strings& fields);
  56. } // namespace internal
  57. namespace gmock_matchers_test {
  58. using std::greater;
  59. using std::less;
  60. using std::list;
  61. using std::make_pair;
  62. using std::map;
  63. using std::multimap;
  64. using std::multiset;
  65. using std::ostream;
  66. using std::pair;
  67. using std::set;
  68. using std::stringstream;
  69. using std::tr1::get;
  70. using std::tr1::make_tuple;
  71. using std::tr1::tuple;
  72. using std::vector;
  73. using testing::A;
  74. using testing::AllArgs;
  75. using testing::AllOf;
  76. using testing::An;
  77. using testing::AnyOf;
  78. using testing::ByRef;
  79. using testing::ContainsRegex;
  80. using testing::DoubleEq;
  81. using testing::DoubleNear;
  82. using testing::EndsWith;
  83. using testing::Eq;
  84. using testing::ExplainMatchResult;
  85. using testing::Field;
  86. using testing::FloatEq;
  87. using testing::FloatNear;
  88. using testing::Ge;
  89. using testing::Gt;
  90. using testing::HasSubstr;
  91. using testing::IsEmpty;
  92. using testing::IsNull;
  93. using testing::Key;
  94. using testing::Le;
  95. using testing::Lt;
  96. using testing::MakeMatcher;
  97. using testing::MakePolymorphicMatcher;
  98. using testing::MatchResultListener;
  99. using testing::Matcher;
  100. using testing::MatcherCast;
  101. using testing::MatcherInterface;
  102. using testing::Matches;
  103. using testing::MatchesRegex;
  104. using testing::NanSensitiveDoubleEq;
  105. using testing::NanSensitiveDoubleNear;
  106. using testing::NanSensitiveFloatEq;
  107. using testing::NanSensitiveFloatNear;
  108. using testing::Ne;
  109. using testing::Not;
  110. using testing::NotNull;
  111. using testing::Pair;
  112. using testing::Pointee;
  113. using testing::Pointwise;
  114. using testing::PolymorphicMatcher;
  115. using testing::Property;
  116. using testing::Ref;
  117. using testing::ResultOf;
  118. using testing::SizeIs;
  119. using testing::StartsWith;
  120. using testing::StringMatchResultListener;
  121. using testing::StrCaseEq;
  122. using testing::StrCaseNe;
  123. using testing::StrEq;
  124. using testing::StrNe;
  125. using testing::Truly;
  126. using testing::TypedEq;
  127. using testing::Value;
  128. using testing::WhenSorted;
  129. using testing::WhenSortedBy;
  130. using testing::_;
  131. using testing::internal::DummyMatchResultListener;
  132. using testing::internal::ElementMatcherPair;
  133. using testing::internal::ElementMatcherPairs;
  134. using testing::internal::ExplainMatchFailureTupleTo;
  135. using testing::internal::FloatingEqMatcher;
  136. using testing::internal::FormatMatcherDescription;
  137. using testing::internal::IsReadableTypeName;
  138. using testing::internal::JoinAsTuple;
  139. using testing::internal::MatchMatrix;
  140. using testing::internal::RE;
  141. using testing::internal::StreamMatchResultListener;
  142. using testing::internal::Strings;
  143. using testing::internal::linked_ptr;
  144. using testing::internal::scoped_ptr;
  145. using testing::internal::string;
  146. // Evaluates to the number of elements in 'array'.
  147. #define GMOCK_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0]))
  148. // For testing ExplainMatchResultTo().
  149. class GreaterThanMatcher : public MatcherInterface<int> {
  150. public:
  151. explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
  152. virtual void DescribeTo(ostream* os) const {
  153. *os << "is > " << rhs_;
  154. }
  155. virtual bool MatchAndExplain(int lhs,
  156. MatchResultListener* listener) const {
  157. const int diff = lhs - rhs_;
  158. if (diff > 0) {
  159. *listener << "which is " << diff << " more than " << rhs_;
  160. } else if (diff == 0) {
  161. *listener << "which is the same as " << rhs_;
  162. } else {
  163. *listener << "which is " << -diff << " less than " << rhs_;
  164. }
  165. return lhs > rhs_;
  166. }
  167. private:
  168. int rhs_;
  169. };
  170. Matcher<int> GreaterThan(int n) {
  171. return MakeMatcher(new GreaterThanMatcher(n));
  172. }
  173. string OfType(const string& type_name) {
  174. #if GTEST_HAS_RTTI
  175. return " (of type " + type_name + ")";
  176. #else
  177. return "";
  178. #endif
  179. }
  180. // Returns the description of the given matcher.
  181. template <typename T>
  182. string Describe(const Matcher<T>& m) {
  183. stringstream ss;
  184. m.DescribeTo(&ss);
  185. return ss.str();
  186. }
  187. // Returns the description of the negation of the given matcher.
  188. template <typename T>
  189. string DescribeNegation(const Matcher<T>& m) {
  190. stringstream ss;
  191. m.DescribeNegationTo(&ss);
  192. return ss.str();
  193. }
  194. // Returns the reason why x matches, or doesn't match, m.
  195. template <typename MatcherType, typename Value>
  196. string Explain(const MatcherType& m, const Value& x) {
  197. StringMatchResultListener listener;
  198. ExplainMatchResult(m, x, &listener);
  199. return listener.str();
  200. }
  201. TEST(MatchResultListenerTest, StreamingWorks) {
  202. StringMatchResultListener listener;
  203. listener << "hi" << 5;
  204. EXPECT_EQ("hi5", listener.str());
  205. listener.Clear();
  206. EXPECT_EQ("", listener.str());
  207. listener << 42;
  208. EXPECT_EQ("42", listener.str());
  209. // Streaming shouldn't crash when the underlying ostream is NULL.
  210. DummyMatchResultListener dummy;
  211. dummy << "hi" << 5;
  212. }
  213. TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
  214. EXPECT_TRUE(DummyMatchResultListener().stream() == NULL);
  215. EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL);
  216. EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
  217. }
  218. TEST(MatchResultListenerTest, IsInterestedWorks) {
  219. EXPECT_TRUE(StringMatchResultListener().IsInterested());
  220. EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
  221. EXPECT_FALSE(DummyMatchResultListener().IsInterested());
  222. EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested());
  223. }
  224. // Makes sure that the MatcherInterface<T> interface doesn't
  225. // change.
  226. class EvenMatcherImpl : public MatcherInterface<int> {
  227. public:
  228. virtual bool MatchAndExplain(int x,
  229. MatchResultListener* /* listener */) const {
  230. return x % 2 == 0;
  231. }
  232. virtual void DescribeTo(ostream* os) const {
  233. *os << "is an even number";
  234. }
  235. // We deliberately don't define DescribeNegationTo() and
  236. // ExplainMatchResultTo() here, to make sure the definition of these
  237. // two methods is optional.
  238. };
  239. // Makes sure that the MatcherInterface API doesn't change.
  240. TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
  241. EvenMatcherImpl m;
  242. }
  243. // Tests implementing a monomorphic matcher using MatchAndExplain().
  244. class NewEvenMatcherImpl : public MatcherInterface<int> {
  245. public:
  246. virtual bool MatchAndExplain(int x, MatchResultListener* listener) const {
  247. const bool match = x % 2 == 0;
  248. // Verifies that we can stream to a listener directly.
  249. *listener << "value % " << 2;
  250. if (listener->stream() != NULL) {
  251. // Verifies that we can stream to a listener's underlying stream
  252. // too.
  253. *listener->stream() << " == " << (x % 2);
  254. }
  255. return match;
  256. }
  257. virtual void DescribeTo(ostream* os) const {
  258. *os << "is an even number";
  259. }
  260. };
  261. TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
  262. Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
  263. EXPECT_TRUE(m.Matches(2));
  264. EXPECT_FALSE(m.Matches(3));
  265. EXPECT_EQ("value % 2 == 0", Explain(m, 2));
  266. EXPECT_EQ("value % 2 == 1", Explain(m, 3));
  267. }
  268. // Tests default-constructing a matcher.
  269. TEST(MatcherTest, CanBeDefaultConstructed) {
  270. Matcher<double> m;
  271. }
  272. // Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
  273. TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
  274. const MatcherInterface<int>* impl = new EvenMatcherImpl;
  275. Matcher<int> m(impl);
  276. EXPECT_TRUE(m.Matches(4));
  277. EXPECT_FALSE(m.Matches(5));
  278. }
  279. // Tests that value can be used in place of Eq(value).
  280. TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
  281. Matcher<int> m1 = 5;
  282. EXPECT_TRUE(m1.Matches(5));
  283. EXPECT_FALSE(m1.Matches(6));
  284. }
  285. // Tests that NULL can be used in place of Eq(NULL).
  286. TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
  287. Matcher<int*> m1 = NULL;
  288. EXPECT_TRUE(m1.Matches(NULL));
  289. int n = 0;
  290. EXPECT_FALSE(m1.Matches(&n));
  291. }
  292. // Tests that matchers are copyable.
  293. TEST(MatcherTest, IsCopyable) {
  294. // Tests the copy constructor.
  295. Matcher<bool> m1 = Eq(false);
  296. EXPECT_TRUE(m1.Matches(false));
  297. EXPECT_FALSE(m1.Matches(true));
  298. // Tests the assignment operator.
  299. m1 = Eq(true);
  300. EXPECT_TRUE(m1.Matches(true));
  301. EXPECT_FALSE(m1.Matches(false));
  302. }
  303. // Tests that Matcher<T>::DescribeTo() calls
  304. // MatcherInterface<T>::DescribeTo().
  305. TEST(MatcherTest, CanDescribeItself) {
  306. EXPECT_EQ("is an even number",
  307. Describe(Matcher<int>(new EvenMatcherImpl)));
  308. }
  309. // Tests Matcher<T>::MatchAndExplain().
  310. TEST(MatcherTest, MatchAndExplain) {
  311. Matcher<int> m = GreaterThan(0);
  312. StringMatchResultListener listener1;
  313. EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
  314. EXPECT_EQ("which is 42 more than 0", listener1.str());
  315. StringMatchResultListener listener2;
  316. EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
  317. EXPECT_EQ("which is 9 less than 0", listener2.str());
  318. }
  319. // Tests that a C-string literal can be implicitly converted to a
  320. // Matcher<string> or Matcher<const string&>.
  321. TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
  322. Matcher<string> m1 = "hi";
  323. EXPECT_TRUE(m1.Matches("hi"));
  324. EXPECT_FALSE(m1.Matches("hello"));
  325. Matcher<const string&> m2 = "hi";
  326. EXPECT_TRUE(m2.Matches("hi"));
  327. EXPECT_FALSE(m2.Matches("hello"));
  328. }
  329. // Tests that a string object can be implicitly converted to a
  330. // Matcher<string> or Matcher<const string&>.
  331. TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
  332. Matcher<string> m1 = string("hi");
  333. EXPECT_TRUE(m1.Matches("hi"));
  334. EXPECT_FALSE(m1.Matches("hello"));
  335. Matcher<const string&> m2 = string("hi");
  336. EXPECT_TRUE(m2.Matches("hi"));
  337. EXPECT_FALSE(m2.Matches("hello"));
  338. }
  339. #if GTEST_HAS_STRING_PIECE_
  340. // Tests that a C-string literal can be implicitly converted to a
  341. // Matcher<StringPiece> or Matcher<const StringPiece&>.
  342. TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
  343. Matcher<StringPiece> m1 = "cats";
  344. EXPECT_TRUE(m1.Matches("cats"));
  345. EXPECT_FALSE(m1.Matches("dogs"));
  346. Matcher<const StringPiece&> m2 = "cats";
  347. EXPECT_TRUE(m2.Matches("cats"));
  348. EXPECT_FALSE(m2.Matches("dogs"));
  349. }
  350. // Tests that a string object can be implicitly converted to a
  351. // Matcher<StringPiece> or Matcher<const StringPiece&>.
  352. TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromString) {
  353. Matcher<StringPiece> m1 = string("cats");
  354. EXPECT_TRUE(m1.Matches("cats"));
  355. EXPECT_FALSE(m1.Matches("dogs"));
  356. Matcher<const StringPiece&> m2 = string("cats");
  357. EXPECT_TRUE(m2.Matches("cats"));
  358. EXPECT_FALSE(m2.Matches("dogs"));
  359. }
  360. // Tests that a StringPiece object can be implicitly converted to a
  361. // Matcher<StringPiece> or Matcher<const StringPiece&>.
  362. TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromStringPiece) {
  363. Matcher<StringPiece> m1 = StringPiece("cats");
  364. EXPECT_TRUE(m1.Matches("cats"));
  365. EXPECT_FALSE(m1.Matches("dogs"));
  366. Matcher<const StringPiece&> m2 = StringPiece("cats");
  367. EXPECT_TRUE(m2.Matches("cats"));
  368. EXPECT_FALSE(m2.Matches("dogs"));
  369. }
  370. #endif // GTEST_HAS_STRING_PIECE_
  371. // Tests that MakeMatcher() constructs a Matcher<T> from a
  372. // MatcherInterface* without requiring the user to explicitly
  373. // write the type.
  374. TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
  375. const MatcherInterface<int>* dummy_impl = NULL;
  376. Matcher<int> m = MakeMatcher(dummy_impl);
  377. }
  378. // Tests that MakePolymorphicMatcher() can construct a polymorphic
  379. // matcher from its implementation using the old API.
  380. const int g_bar = 1;
  381. class ReferencesBarOrIsZeroImpl {
  382. public:
  383. template <typename T>
  384. bool MatchAndExplain(const T& x,
  385. MatchResultListener* /* listener */) const {
  386. const void* p = &x;
  387. return p == &g_bar || x == 0;
  388. }
  389. void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
  390. void DescribeNegationTo(ostream* os) const {
  391. *os << "doesn't reference g_bar and is not zero";
  392. }
  393. };
  394. // This function verifies that MakePolymorphicMatcher() returns a
  395. // PolymorphicMatcher<T> where T is the argument's type.
  396. PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
  397. return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
  398. }
  399. TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
  400. // Using a polymorphic matcher to match a reference type.
  401. Matcher<const int&> m1 = ReferencesBarOrIsZero();
  402. EXPECT_TRUE(m1.Matches(0));
  403. // Verifies that the identity of a by-reference argument is preserved.
  404. EXPECT_TRUE(m1.Matches(g_bar));
  405. EXPECT_FALSE(m1.Matches(1));
  406. EXPECT_EQ("g_bar or zero", Describe(m1));
  407. // Using a polymorphic matcher to match a value type.
  408. Matcher<double> m2 = ReferencesBarOrIsZero();
  409. EXPECT_TRUE(m2.Matches(0.0));
  410. EXPECT_FALSE(m2.Matches(0.1));
  411. EXPECT_EQ("g_bar or zero", Describe(m2));
  412. }
  413. // Tests implementing a polymorphic matcher using MatchAndExplain().
  414. class PolymorphicIsEvenImpl {
  415. public:
  416. void DescribeTo(ostream* os) const { *os << "is even"; }
  417. void DescribeNegationTo(ostream* os) const {
  418. *os << "is odd";
  419. }
  420. template <typename T>
  421. bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
  422. // Verifies that we can stream to the listener directly.
  423. *listener << "% " << 2;
  424. if (listener->stream() != NULL) {
  425. // Verifies that we can stream to the listener's underlying stream
  426. // too.
  427. *listener->stream() << " == " << (x % 2);
  428. }
  429. return (x % 2) == 0;
  430. }
  431. };
  432. PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
  433. return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
  434. }
  435. TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
  436. // Using PolymorphicIsEven() as a Matcher<int>.
  437. const Matcher<int> m1 = PolymorphicIsEven();
  438. EXPECT_TRUE(m1.Matches(42));
  439. EXPECT_FALSE(m1.Matches(43));
  440. EXPECT_EQ("is even", Describe(m1));
  441. const Matcher<int> not_m1 = Not(m1);
  442. EXPECT_EQ("is odd", Describe(not_m1));
  443. EXPECT_EQ("% 2 == 0", Explain(m1, 42));
  444. // Using PolymorphicIsEven() as a Matcher<char>.
  445. const Matcher<char> m2 = PolymorphicIsEven();
  446. EXPECT_TRUE(m2.Matches('\x42'));
  447. EXPECT_FALSE(m2.Matches('\x43'));
  448. EXPECT_EQ("is even", Describe(m2));
  449. const Matcher<char> not_m2 = Not(m2);
  450. EXPECT_EQ("is odd", Describe(not_m2));
  451. EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
  452. }
  453. // Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
  454. TEST(MatcherCastTest, FromPolymorphicMatcher) {
  455. Matcher<int> m = MatcherCast<int>(Eq(5));
  456. EXPECT_TRUE(m.Matches(5));
  457. EXPECT_FALSE(m.Matches(6));
  458. }
  459. // For testing casting matchers between compatible types.
  460. class IntValue {
  461. public:
  462. // An int can be statically (although not implicitly) cast to a
  463. // IntValue.
  464. explicit IntValue(int a_value) : value_(a_value) {}
  465. int value() const { return value_; }
  466. private:
  467. int value_;
  468. };
  469. // For testing casting matchers between compatible types.
  470. bool IsPositiveIntValue(const IntValue& foo) {
  471. return foo.value() > 0;
  472. }
  473. // Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
  474. // can be statically converted to U.
  475. TEST(MatcherCastTest, FromCompatibleType) {
  476. Matcher<double> m1 = Eq(2.0);
  477. Matcher<int> m2 = MatcherCast<int>(m1);
  478. EXPECT_TRUE(m2.Matches(2));
  479. EXPECT_FALSE(m2.Matches(3));
  480. Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
  481. Matcher<int> m4 = MatcherCast<int>(m3);
  482. // In the following, the arguments 1 and 0 are statically converted
  483. // to IntValue objects, and then tested by the IsPositiveIntValue()
  484. // predicate.
  485. EXPECT_TRUE(m4.Matches(1));
  486. EXPECT_FALSE(m4.Matches(0));
  487. }
  488. // Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
  489. TEST(MatcherCastTest, FromConstReferenceToNonReference) {
  490. Matcher<const int&> m1 = Eq(0);
  491. Matcher<int> m2 = MatcherCast<int>(m1);
  492. EXPECT_TRUE(m2.Matches(0));
  493. EXPECT_FALSE(m2.Matches(1));
  494. }
  495. // Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
  496. TEST(MatcherCastTest, FromReferenceToNonReference) {
  497. Matcher<int&> m1 = Eq(0);
  498. Matcher<int> m2 = MatcherCast<int>(m1);
  499. EXPECT_TRUE(m2.Matches(0));
  500. EXPECT_FALSE(m2.Matches(1));
  501. }
  502. // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
  503. TEST(MatcherCastTest, FromNonReferenceToConstReference) {
  504. Matcher<int> m1 = Eq(0);
  505. Matcher<const int&> m2 = MatcherCast<const int&>(m1);
  506. EXPECT_TRUE(m2.Matches(0));
  507. EXPECT_FALSE(m2.Matches(1));
  508. }
  509. // Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
  510. TEST(MatcherCastTest, FromNonReferenceToReference) {
  511. Matcher<int> m1 = Eq(0);
  512. Matcher<int&> m2 = MatcherCast<int&>(m1);
  513. int n = 0;
  514. EXPECT_TRUE(m2.Matches(n));
  515. n = 1;
  516. EXPECT_FALSE(m2.Matches(n));
  517. }
  518. // Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
  519. TEST(MatcherCastTest, FromSameType) {
  520. Matcher<int> m1 = Eq(0);
  521. Matcher<int> m2 = MatcherCast<int>(m1);
  522. EXPECT_TRUE(m2.Matches(0));
  523. EXPECT_FALSE(m2.Matches(1));
  524. }
  525. // Implicitly convertible form any type.
  526. struct ConvertibleFromAny {
  527. ConvertibleFromAny(int a_value) : value(a_value) {}
  528. template <typename T>
  529. ConvertibleFromAny(const T& a_value) : value(-1) {
  530. ADD_FAILURE() << "Conversion constructor called";
  531. }
  532. int value;
  533. };
  534. bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
  535. return a.value == b.value;
  536. }
  537. ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
  538. return os << a.value;
  539. }
  540. TEST(MatcherCastTest, ConversionConstructorIsUsed) {
  541. Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
  542. EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
  543. EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
  544. }
  545. TEST(MatcherCastTest, FromConvertibleFromAny) {
  546. Matcher<ConvertibleFromAny> m =
  547. MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
  548. EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
  549. EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
  550. }
  551. class Base {};
  552. class Derived : public Base {};
  553. // Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
  554. TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
  555. Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
  556. EXPECT_TRUE(m2.Matches(' '));
  557. EXPECT_FALSE(m2.Matches('\n'));
  558. }
  559. // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
  560. // T and U are arithmetic types and T can be losslessly converted to
  561. // U.
  562. TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
  563. Matcher<double> m1 = DoubleEq(1.0);
  564. Matcher<float> m2 = SafeMatcherCast<float>(m1);
  565. EXPECT_TRUE(m2.Matches(1.0f));
  566. EXPECT_FALSE(m2.Matches(2.0f));
  567. Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
  568. EXPECT_TRUE(m3.Matches('a'));
  569. EXPECT_FALSE(m3.Matches('b'));
  570. }
  571. // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
  572. // are pointers or references to a derived and a base class, correspondingly.
  573. TEST(SafeMatcherCastTest, FromBaseClass) {
  574. Derived d, d2;
  575. Matcher<Base*> m1 = Eq(&d);
  576. Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
  577. EXPECT_TRUE(m2.Matches(&d));
  578. EXPECT_FALSE(m2.Matches(&d2));
  579. Matcher<Base&> m3 = Ref(d);
  580. Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
  581. EXPECT_TRUE(m4.Matches(d));
  582. EXPECT_FALSE(m4.Matches(d2));
  583. }
  584. // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
  585. TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
  586. int n = 0;
  587. Matcher<const int&> m1 = Ref(n);
  588. Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
  589. int n1 = 0;
  590. EXPECT_TRUE(m2.Matches(n));
  591. EXPECT_FALSE(m2.Matches(n1));
  592. }
  593. // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
  594. TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
  595. Matcher<int> m1 = Eq(0);
  596. Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
  597. EXPECT_TRUE(m2.Matches(0));
  598. EXPECT_FALSE(m2.Matches(1));
  599. }
  600. // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
  601. TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
  602. Matcher<int> m1 = Eq(0);
  603. Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
  604. int n = 0;
  605. EXPECT_TRUE(m2.Matches(n));
  606. n = 1;
  607. EXPECT_FALSE(m2.Matches(n));
  608. }
  609. // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
  610. TEST(SafeMatcherCastTest, FromSameType) {
  611. Matcher<int> m1 = Eq(0);
  612. Matcher<int> m2 = SafeMatcherCast<int>(m1);
  613. EXPECT_TRUE(m2.Matches(0));
  614. EXPECT_FALSE(m2.Matches(1));
  615. }
  616. TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
  617. Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
  618. EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
  619. EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
  620. }
  621. TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
  622. Matcher<ConvertibleFromAny> m =
  623. SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
  624. EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
  625. EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
  626. }
  627. // Tests that A<T>() matches any value of type T.
  628. TEST(ATest, MatchesAnyValue) {
  629. // Tests a matcher for a value type.
  630. Matcher<double> m1 = A<double>();
  631. EXPECT_TRUE(m1.Matches(91.43));
  632. EXPECT_TRUE(m1.Matches(-15.32));
  633. // Tests a matcher for a reference type.
  634. int a = 2;
  635. int b = -6;
  636. Matcher<int&> m2 = A<int&>();
  637. EXPECT_TRUE(m2.Matches(a));
  638. EXPECT_TRUE(m2.Matches(b));
  639. }
  640. TEST(ATest, WorksForDerivedClass) {
  641. Base base;
  642. Derived derived;
  643. EXPECT_THAT(&base, A<Base*>());
  644. // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
  645. EXPECT_THAT(&derived, A<Base*>());
  646. EXPECT_THAT(&derived, A<Derived*>());
  647. }
  648. // Tests that A<T>() describes itself properly.
  649. TEST(ATest, CanDescribeSelf) {
  650. EXPECT_EQ("is anything", Describe(A<bool>()));
  651. }
  652. // Tests that An<T>() matches any value of type T.
  653. TEST(AnTest, MatchesAnyValue) {
  654. // Tests a matcher for a value type.
  655. Matcher<int> m1 = An<int>();
  656. EXPECT_TRUE(m1.Matches(9143));
  657. EXPECT_TRUE(m1.Matches(-1532));
  658. // Tests a matcher for a reference type.
  659. int a = 2;
  660. int b = -6;
  661. Matcher<int&> m2 = An<int&>();
  662. EXPECT_TRUE(m2.Matches(a));
  663. EXPECT_TRUE(m2.Matches(b));
  664. }
  665. // Tests that An<T>() describes itself properly.
  666. TEST(AnTest, CanDescribeSelf) {
  667. EXPECT_EQ("is anything", Describe(An<int>()));
  668. }
  669. // Tests that _ can be used as a matcher for any type and matches any
  670. // value of that type.
  671. TEST(UnderscoreTest, MatchesAnyValue) {
  672. // Uses _ as a matcher for a value type.
  673. Matcher<int> m1 = _;
  674. EXPECT_TRUE(m1.Matches(123));
  675. EXPECT_TRUE(m1.Matches(-242));
  676. // Uses _ as a matcher for a reference type.
  677. bool a = false;
  678. const bool b = true;
  679. Matcher<const bool&> m2 = _;
  680. EXPECT_TRUE(m2.Matches(a));
  681. EXPECT_TRUE(m2.Matches(b));
  682. }
  683. // Tests that _ describes itself properly.
  684. TEST(UnderscoreTest, CanDescribeSelf) {
  685. Matcher<int> m = _;
  686. EXPECT_EQ("is anything", Describe(m));
  687. }
  688. // Tests that Eq(x) matches any value equal to x.
  689. TEST(EqTest, MatchesEqualValue) {
  690. // 2 C-strings with same content but different addresses.
  691. const char a1[] = "hi";
  692. const char a2[] = "hi";
  693. Matcher<const char*> m1 = Eq(a1);
  694. EXPECT_TRUE(m1.Matches(a1));
  695. EXPECT_FALSE(m1.Matches(a2));
  696. }
  697. // Tests that Eq(v) describes itself properly.
  698. class Unprintable {
  699. public:
  700. Unprintable() : c_('a') {}
  701. bool operator==(const Unprintable& /* rhs */) { return true; }
  702. private:
  703. char c_;
  704. };
  705. TEST(EqTest, CanDescribeSelf) {
  706. Matcher<Unprintable> m = Eq(Unprintable());
  707. EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
  708. }
  709. // Tests that Eq(v) can be used to match any type that supports
  710. // comparing with type T, where T is v's type.
  711. TEST(EqTest, IsPolymorphic) {
  712. Matcher<int> m1 = Eq(1);
  713. EXPECT_TRUE(m1.Matches(1));
  714. EXPECT_FALSE(m1.Matches(2));
  715. Matcher<char> m2 = Eq(1);
  716. EXPECT_TRUE(m2.Matches('\1'));
  717. EXPECT_FALSE(m2.Matches('a'));
  718. }
  719. // Tests that TypedEq<T>(v) matches values of type T that's equal to v.
  720. TEST(TypedEqTest, ChecksEqualityForGivenType) {
  721. Matcher<char> m1 = TypedEq<char>('a');
  722. EXPECT_TRUE(m1.Matches('a'));
  723. EXPECT_FALSE(m1.Matches('b'));
  724. Matcher<int> m2 = TypedEq<int>(6);
  725. EXPECT_TRUE(m2.Matches(6));
  726. EXPECT_FALSE(m2.Matches(7));
  727. }
  728. // Tests that TypedEq(v) describes itself properly.
  729. TEST(TypedEqTest, CanDescribeSelf) {
  730. EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
  731. }
  732. // Tests that TypedEq<T>(v) has type Matcher<T>.
  733. // Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
  734. // is a "bare" type (i.e. not in the form of const U or U&). If v's
  735. // type is not T, the compiler will generate a message about
  736. // "undefined referece".
  737. template <typename T>
  738. struct Type {
  739. static bool IsTypeOf(const T& /* v */) { return true; }
  740. template <typename T2>
  741. static void IsTypeOf(T2 v);
  742. };
  743. TEST(TypedEqTest, HasSpecifiedType) {
  744. // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
  745. Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
  746. Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
  747. }
  748. // Tests that Ge(v) matches anything >= v.
  749. TEST(GeTest, ImplementsGreaterThanOrEqual) {
  750. Matcher<int> m1 = Ge(0);
  751. EXPECT_TRUE(m1.Matches(1));
  752. EXPECT_TRUE(m1.Matches(0));
  753. EXPECT_FALSE(m1.Matches(-1));
  754. }
  755. // Tests that Ge(v) describes itself properly.
  756. TEST(GeTest, CanDescribeSelf) {
  757. Matcher<int> m = Ge(5);
  758. EXPECT_EQ("is >= 5", Describe(m));
  759. }
  760. // Tests that Gt(v) matches anything > v.
  761. TEST(GtTest, ImplementsGreaterThan) {
  762. Matcher<double> m1 = Gt(0);
  763. EXPECT_TRUE(m1.Matches(1.0));
  764. EXPECT_FALSE(m1.Matches(0.0));
  765. EXPECT_FALSE(m1.Matches(-1.0));
  766. }
  767. // Tests that Gt(v) describes itself properly.
  768. TEST(GtTest, CanDescribeSelf) {
  769. Matcher<int> m = Gt(5);
  770. EXPECT_EQ("is > 5", Describe(m));
  771. }
  772. // Tests that Le(v) matches anything <= v.
  773. TEST(LeTest, ImplementsLessThanOrEqual) {
  774. Matcher<char> m1 = Le('b');
  775. EXPECT_TRUE(m1.Matches('a'));
  776. EXPECT_TRUE(m1.Matches('b'));
  777. EXPECT_FALSE(m1.Matches('c'));
  778. }
  779. // Tests that Le(v) describes itself properly.
  780. TEST(LeTest, CanDescribeSelf) {
  781. Matcher<int> m = Le(5);
  782. EXPECT_EQ("is <= 5", Describe(m));
  783. }
  784. // Tests that Lt(v) matches anything < v.
  785. TEST(LtTest, ImplementsLessThan) {
  786. Matcher<const string&> m1 = Lt("Hello");
  787. EXPECT_TRUE(m1.Matches("Abc"));
  788. EXPECT_FALSE(m1.Matches("Hello"));
  789. EXPECT_FALSE(m1.Matches("Hello, world!"));
  790. }
  791. // Tests that Lt(v) describes itself properly.
  792. TEST(LtTest, CanDescribeSelf) {
  793. Matcher<int> m = Lt(5);
  794. EXPECT_EQ("is < 5", Describe(m));
  795. }
  796. // Tests that Ne(v) matches anything != v.
  797. TEST(NeTest, ImplementsNotEqual) {
  798. Matcher<int> m1 = Ne(0);
  799. EXPECT_TRUE(m1.Matches(1));
  800. EXPECT_TRUE(m1.Matches(-1));
  801. EXPECT_FALSE(m1.Matches(0));
  802. }
  803. // Tests that Ne(v) describes itself properly.
  804. TEST(NeTest, CanDescribeSelf) {
  805. Matcher<int> m = Ne(5);
  806. EXPECT_EQ("isn't equal to 5", Describe(m));
  807. }
  808. // Tests that IsNull() matches any NULL pointer of any type.
  809. TEST(IsNullTest, MatchesNullPointer) {
  810. Matcher<int*> m1 = IsNull();
  811. int* p1 = NULL;
  812. int n = 0;
  813. EXPECT_TRUE(m1.Matches(p1));
  814. EXPECT_FALSE(m1.Matches(&n));
  815. Matcher<const char*> m2 = IsNull();
  816. const char* p2 = NULL;
  817. EXPECT_TRUE(m2.Matches(p2));
  818. EXPECT_FALSE(m2.Matches("hi"));
  819. #if !GTEST_OS_SYMBIAN
  820. // Nokia's Symbian compiler generates:
  821. // gmock-matchers.h: ambiguous access to overloaded function
  822. // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
  823. // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
  824. // MatcherInterface<void *> *)'
  825. // gmock-matchers.h: (point of instantiation: 'testing::
  826. // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
  827. // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc
  828. Matcher<void*> m3 = IsNull();
  829. void* p3 = NULL;
  830. EXPECT_TRUE(m3.Matches(p3));
  831. EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
  832. #endif
  833. }
  834. TEST(IsNullTest, LinkedPtr) {
  835. const Matcher<linked_ptr<int> > m = IsNull();
  836. const linked_ptr<int> null_p;
  837. const linked_ptr<int> non_null_p(new int);
  838. EXPECT_TRUE(m.Matches(null_p));
  839. EXPECT_FALSE(m.Matches(non_null_p));
  840. }
  841. TEST(IsNullTest, ReferenceToConstLinkedPtr) {
  842. const Matcher<const linked_ptr<double>&> m = IsNull();
  843. const linked_ptr<double> null_p;
  844. const linked_ptr<double> non_null_p(new double);
  845. EXPECT_TRUE(m.Matches(null_p));
  846. EXPECT_FALSE(m.Matches(non_null_p));
  847. }
  848. TEST(IsNullTest, ReferenceToConstScopedPtr) {
  849. const Matcher<const scoped_ptr<double>&> m = IsNull();
  850. const scoped_ptr<double> null_p;
  851. const scoped_ptr<double> non_null_p(new double);
  852. EXPECT_TRUE(m.Matches(null_p));
  853. EXPECT_FALSE(m.Matches(non_null_p));
  854. }
  855. // Tests that IsNull() describes itself properly.
  856. TEST(IsNullTest, CanDescribeSelf) {
  857. Matcher<int*> m = IsNull();
  858. EXPECT_EQ("is NULL", Describe(m));
  859. EXPECT_EQ("isn't NULL", DescribeNegation(m));
  860. }
  861. // Tests that NotNull() matches any non-NULL pointer of any type.
  862. TEST(NotNullTest, MatchesNonNullPointer) {
  863. Matcher<int*> m1 = NotNull();
  864. int* p1 = NULL;
  865. int n = 0;
  866. EXPECT_FALSE(m1.Matches(p1));
  867. EXPECT_TRUE(m1.Matches(&n));
  868. Matcher<const char*> m2 = NotNull();
  869. const char* p2 = NULL;
  870. EXPECT_FALSE(m2.Matches(p2));
  871. EXPECT_TRUE(m2.Matches("hi"));
  872. }
  873. TEST(NotNullTest, LinkedPtr) {
  874. const Matcher<linked_ptr<int> > m = NotNull();
  875. const linked_ptr<int> null_p;
  876. const linked_ptr<int> non_null_p(new int);
  877. EXPECT_FALSE(m.Matches(null_p));
  878. EXPECT_TRUE(m.Matches(non_null_p));
  879. }
  880. TEST(NotNullTest, ReferenceToConstLinkedPtr) {
  881. const Matcher<const linked_ptr<double>&> m = NotNull();
  882. const linked_ptr<double> null_p;
  883. const linked_ptr<double> non_null_p(new double);
  884. EXPECT_FALSE(m.Matches(null_p));
  885. EXPECT_TRUE(m.Matches(non_null_p));
  886. }
  887. TEST(NotNullTest, ReferenceToConstScopedPtr) {
  888. const Matcher<const scoped_ptr<double>&> m = NotNull();
  889. const scoped_ptr<double> null_p;
  890. const scoped_ptr<double> non_null_p(new double);
  891. EXPECT_FALSE(m.Matches(null_p));
  892. EXPECT_TRUE(m.Matches(non_null_p));
  893. }
  894. // Tests that NotNull() describes itself properly.
  895. TEST(NotNullTest, CanDescribeSelf) {
  896. Matcher<int*> m = NotNull();
  897. EXPECT_EQ("isn't NULL", Describe(m));
  898. }
  899. // Tests that Ref(variable) matches an argument that references
  900. // 'variable'.
  901. TEST(RefTest, MatchesSameVariable) {
  902. int a = 0;
  903. int b = 0;
  904. Matcher<int&> m = Ref(a);
  905. EXPECT_TRUE(m.Matches(a));
  906. EXPECT_FALSE(m.Matches(b));
  907. }
  908. // Tests that Ref(variable) describes itself properly.
  909. TEST(RefTest, CanDescribeSelf) {
  910. int n = 5;
  911. Matcher<int&> m = Ref(n);
  912. stringstream ss;
  913. ss << "references the variable @" << &n << " 5";
  914. EXPECT_EQ(string(ss.str()), Describe(m));
  915. }
  916. // Test that Ref(non_const_varialbe) can be used as a matcher for a
  917. // const reference.
  918. TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
  919. int a = 0;
  920. int b = 0;
  921. Matcher<const int&> m = Ref(a);
  922. EXPECT_TRUE(m.Matches(a));
  923. EXPECT_FALSE(m.Matches(b));
  924. }
  925. // Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
  926. // used wherever Ref(base) can be used (Ref(derived) is a sub-type
  927. // of Ref(base), but not vice versa.
  928. TEST(RefTest, IsCovariant) {
  929. Base base, base2;
  930. Derived derived;
  931. Matcher<const Base&> m1 = Ref(base);
  932. EXPECT_TRUE(m1.Matches(base));
  933. EXPECT_FALSE(m1.Matches(base2));
  934. EXPECT_FALSE(m1.Matches(derived));
  935. m1 = Ref(derived);
  936. EXPECT_TRUE(m1.Matches(derived));
  937. EXPECT_FALSE(m1.Matches(base));
  938. EXPECT_FALSE(m1.Matches(base2));
  939. }
  940. TEST(RefTest, ExplainsResult) {
  941. int n = 0;
  942. EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
  943. StartsWith("which is located @"));
  944. int m = 0;
  945. EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
  946. StartsWith("which is located @"));
  947. }
  948. // Tests string comparison matchers.
  949. TEST(StrEqTest, MatchesEqualString) {
  950. Matcher<const char*> m = StrEq(string("Hello"));
  951. EXPECT_TRUE(m.Matches("Hello"));
  952. EXPECT_FALSE(m.Matches("hello"));
  953. EXPECT_FALSE(m.Matches(NULL));
  954. Matcher<const string&> m2 = StrEq("Hello");
  955. EXPECT_TRUE(m2.Matches("Hello"));
  956. EXPECT_FALSE(m2.Matches("Hi"));
  957. }
  958. TEST(StrEqTest, CanDescribeSelf) {
  959. Matcher<string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
  960. EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
  961. Describe(m));
  962. string str("01204500800");
  963. str[3] = '\0';
  964. Matcher<string> m2 = StrEq(str);
  965. EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
  966. str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
  967. Matcher<string> m3 = StrEq(str);
  968. EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
  969. }
  970. TEST(StrNeTest, MatchesUnequalString) {
  971. Matcher<const char*> m = StrNe("Hello");
  972. EXPECT_TRUE(m.Matches(""));
  973. EXPECT_TRUE(m.Matches(NULL));
  974. EXPECT_FALSE(m.Matches("Hello"));
  975. Matcher<string> m2 = StrNe(string("Hello"));
  976. EXPECT_TRUE(m2.Matches("hello"));
  977. EXPECT_FALSE(m2.Matches("Hello"));
  978. }
  979. TEST(StrNeTest, CanDescribeSelf) {
  980. Matcher<const char*> m = StrNe("Hi");
  981. EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
  982. }
  983. TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
  984. Matcher<const char*> m = StrCaseEq(string("Hello"));
  985. EXPECT_TRUE(m.Matches("Hello"));
  986. EXPECT_TRUE(m.Matches("hello"));
  987. EXPECT_FALSE(m.Matches("Hi"));
  988. EXPECT_FALSE(m.Matches(NULL));
  989. Matcher<const string&> m2 = StrCaseEq("Hello");
  990. EXPECT_TRUE(m2.Matches("hello"));
  991. EXPECT_FALSE(m2.Matches("Hi"));
  992. }
  993. TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
  994. string str1("oabocdooeoo");
  995. string str2("OABOCDOOEOO");
  996. Matcher<const string&> m0 = StrCaseEq(str1);
  997. EXPECT_FALSE(m0.Matches(str2 + string(1, '\0')));
  998. str1[3] = str2[3] = '\0';
  999. Matcher<const string&> m1 = StrCaseEq(str1);
  1000. EXPECT_TRUE(m1.Matches(str2));
  1001. str1[0] = str1[6] = str1[7] = str1[10] = '\0';
  1002. str2[0] = str2[6] = str2[7] = str2[10] = '\0';
  1003. Matcher<const string&> m2 = StrCaseEq(str1);
  1004. str1[9] = str2[9] = '\0';
  1005. EXPECT_FALSE(m2.Matches(str2));
  1006. Matcher<const string&> m3 = StrCaseEq(str1);
  1007. EXPECT_TRUE(m3.Matches(str2));
  1008. EXPECT_FALSE(m3.Matches(str2 + "x"));
  1009. str2.append(1, '\0');
  1010. EXPECT_FALSE(m3.Matches(str2));
  1011. EXPECT_FALSE(m3.Matches(string(str2, 0, 9)));
  1012. }
  1013. TEST(StrCaseEqTest, CanDescribeSelf) {
  1014. Matcher<string> m = StrCaseEq("Hi");
  1015. EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
  1016. }
  1017. TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
  1018. Matcher<const char*> m = StrCaseNe("Hello");
  1019. EXPECT_TRUE(m.Matches("Hi"));
  1020. EXPECT_TRUE(m.Matches(NULL));
  1021. EXPECT_FALSE(m.Matches("Hello"));
  1022. EXPECT_FALSE(m.Matches("hello"));
  1023. Matcher<string> m2 = StrCaseNe(string("Hello"));
  1024. EXPECT_TRUE(m2.Matches(""));
  1025. EXPECT_FALSE(m2.Matches("Hello"));
  1026. }
  1027. TEST(StrCaseNeTest, CanDescribeSelf) {
  1028. Matcher<const char*> m = StrCaseNe("Hi");
  1029. EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
  1030. }
  1031. // Tests that HasSubstr() works for matching string-typed values.
  1032. TEST(HasSubstrTest, WorksForStringClasses) {
  1033. const Matcher<string> m1 = HasSubstr("foo");
  1034. EXPECT_TRUE(m1.Matches(string("I love food.")));
  1035. EXPECT_FALSE(m1.Matches(string("tofo")));
  1036. const Matcher<const std::string&> m2 = HasSubstr("foo");
  1037. EXPECT_TRUE(m2.Matches(std::string("I love food.")));
  1038. EXPECT_FALSE(m2.Matches(std::string("tofo")));
  1039. }
  1040. // Tests that HasSubstr() works for matching C-string-typed values.
  1041. TEST(HasSubstrTest, WorksForCStrings) {
  1042. const Matcher<char*> m1 = HasSubstr("foo");
  1043. EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
  1044. EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
  1045. EXPECT_FALSE(m1.Matches(NULL));
  1046. const Matcher<const char*> m2 = HasSubstr("foo");
  1047. EXPECT_TRUE(m2.Matches("I love food."));
  1048. EXPECT_FALSE(m2.Matches("tofo"));
  1049. EXPECT_FALSE(m2.Matches(NULL));
  1050. }
  1051. // Tests that HasSubstr(s) describes itself properly.
  1052. TEST(HasSubstrTest, CanDescribeSelf) {
  1053. Matcher<string> m = HasSubstr("foo\n\"");
  1054. EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
  1055. }
  1056. TEST(KeyTest, CanDescribeSelf) {
  1057. Matcher<const pair<std::string, int>&> m = Key("foo");
  1058. EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
  1059. EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
  1060. }
  1061. TEST(KeyTest, ExplainsResult) {
  1062. Matcher<pair<int, bool> > m = Key(GreaterThan(10));
  1063. EXPECT_EQ("whose first field is a value which is 5 less than 10",
  1064. Explain(m, make_pair(5, true)));
  1065. EXPECT_EQ("whose first field is a value which is 5 more than 10",
  1066. Explain(m, make_pair(15, true)));
  1067. }
  1068. TEST(KeyTest, MatchesCorrectly) {
  1069. pair<int, std::string> p(25, "foo");
  1070. EXPECT_THAT(p, Key(25));
  1071. EXPECT_THAT(p, Not(Key(42)));
  1072. EXPECT_THAT(p, Key(Ge(20)));
  1073. EXPECT_THAT(p, Not(Key(Lt(25))));
  1074. }
  1075. TEST(KeyTest, SafelyCastsInnerMatcher) {
  1076. Matcher<int> is_positive = Gt(0);
  1077. Matcher<int> is_negative = Lt(0);
  1078. pair<char, bool> p('a', true);
  1079. EXPECT_THAT(p, Key(is_positive));
  1080. EXPECT_THAT(p, Not(Key(is_negative)));
  1081. }
  1082. TEST(KeyTest, InsideContainsUsingMap) {
  1083. map<int, char> container;
  1084. container.insert(make_pair(1, 'a'));
  1085. container.insert(make_pair(2, 'b'));
  1086. container.insert(make_pair(4, 'c'));
  1087. EXPECT_THAT(container, Contains(Key(1)));
  1088. EXPECT_THAT(container, Not(Contains(Key(3))));
  1089. }
  1090. TEST(KeyTest, InsideContainsUsingMultimap) {
  1091. multimap<int, char> container;
  1092. container.insert(make_pair(1, 'a'));
  1093. container.insert(make_pair(2, 'b'));
  1094. container.insert(make_pair(4, 'c'));
  1095. EXPECT_THAT(container, Not(Contains(Key(25))));
  1096. container.insert(make_pair(25, 'd'));
  1097. EXPECT_THAT(container, Contains(Key(25)));
  1098. container.insert(make_pair(25, 'e'));
  1099. EXPECT_THAT(container, Contains(Key(25)));
  1100. EXPECT_THAT(container, Contains(Key(1)));
  1101. EXPECT_THAT(container, Not(Contains(Key(3))));
  1102. }
  1103. TEST(PairTest, Typing) {
  1104. // Test verifies the following type conversions can be compiled.
  1105. Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
  1106. Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
  1107. Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
  1108. Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
  1109. Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
  1110. }
  1111. TEST(PairTest, CanDescribeSelf) {
  1112. Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
  1113. EXPECT_EQ("has a first field that is equal to \"foo\""
  1114. ", and has a second field that is equal to 42",
  1115. Describe(m1));
  1116. EXPECT_EQ("has a first field that isn't equal to \"foo\""
  1117. ", or has a second field that isn't equal to 42",
  1118. DescribeNegation(m1));
  1119. // Double and triple negation (1 or 2 times not and description of negation).
  1120. Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
  1121. EXPECT_EQ("has a first field that isn't equal to 13"
  1122. ", and has a second field that is equal to 42",
  1123. DescribeNegation(m2));
  1124. }
  1125. TEST(PairTest, CanExplainMatchResultTo) {
  1126. // If neither field matches, Pair() should explain about the first
  1127. // field.
  1128. const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
  1129. EXPECT_EQ("whose first field does not match, which is 1 less than 0",
  1130. Explain(m, make_pair(-1, -2)));
  1131. // If the first field matches but the second doesn't, Pair() should
  1132. // explain about the second field.
  1133. EXPECT_EQ("whose second field does not match, which is 2 less than 0",
  1134. Explain(m, make_pair(1, -2)));
  1135. // If the first field doesn't match but the second does, Pair()
  1136. // should explain about the first field.
  1137. EXPECT_EQ("whose first field does not match, which is 1 less than 0",
  1138. Explain(m, make_pair(-1, 2)));
  1139. // If both fields match, Pair() should explain about them both.
  1140. EXPECT_EQ("whose both fields match, where the first field is a value "
  1141. "which is 1 more than 0, and the second field is a value "
  1142. "which is 2 more than 0",
  1143. Explain(m, make_pair(1, 2)));
  1144. // If only the first match has an explanation, only this explanation should
  1145. // be printed.
  1146. const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
  1147. EXPECT_EQ("whose both fields match, where the first field is a value "
  1148. "which is 1 more than 0",
  1149. Explain(explain_first, make_pair(1, 0)));
  1150. // If only the second match has an explanation, only this explanation should
  1151. // be printed.
  1152. const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
  1153. EXPECT_EQ("whose both fields match, where the second field is a value "
  1154. "which is 1 more than 0",
  1155. Explain(explain_second, make_pair(0, 1)));
  1156. }
  1157. TEST(PairTest, MatchesCorrectly) {
  1158. pair<int, std::string> p(25, "foo");
  1159. // Both fields match.
  1160. EXPECT_THAT(p, Pair(25, "foo"));
  1161. EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
  1162. // 'first' doesnt' match, but 'second' matches.
  1163. EXPECT_THAT(p, Not(Pair(42, "foo")));
  1164. EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
  1165. // 'first' matches, but 'second' doesn't match.
  1166. EXPECT_THAT(p, Not(Pair(25, "bar")));
  1167. EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
  1168. // Neither field matches.
  1169. EXPECT_THAT(p, Not(Pair(13, "bar")));
  1170. EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
  1171. }
  1172. TEST(PairTest, SafelyCastsInnerMatchers) {
  1173. Matcher<int> is_positive = Gt(0);
  1174. Matcher<int> is_negative = Lt(0);
  1175. pair<char, bool> p('a', true);
  1176. EXPECT_THAT(p, Pair(is_positive, _));
  1177. EXPECT_THAT(p, Not(Pair(is_negative, _)));
  1178. EXPECT_THAT(p, Pair(_, is_positive));
  1179. EXPECT_THAT(p, Not(Pair(_, is_negative)));
  1180. }
  1181. TEST(PairTest, InsideContainsUsingMap) {
  1182. map<int, char> container;
  1183. container.insert(make_pair(1, 'a'));
  1184. container.insert(make_pair(2, 'b'));
  1185. container.insert(make_pair(4, 'c'));
  1186. EXPECT_THAT(container, Contains(Pair(1, 'a')));
  1187. EXPECT_THAT(container, Contains(Pair(1, _)));
  1188. EXPECT_THAT(container, Contains(Pair(_, 'a')));
  1189. EXPECT_THAT(container, Not(Contains(Pair(3, _))));
  1190. }
  1191. // Tests StartsWith(s).
  1192. TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
  1193. const Matcher<const char*> m1 = StartsWith(string(""));
  1194. EXPECT_TRUE(m1.Matches("Hi"));
  1195. EXPECT_TRUE(m1.Matches(""));
  1196. EXPECT_FALSE(m1.Matches(NULL));
  1197. const Matcher<const string&> m2 = StartsWith("Hi");
  1198. EXPECT_TRUE(m2.Matches("Hi"));
  1199. EXPECT_TRUE(m2.Matches("Hi Hi!"));
  1200. EXPECT_TRUE(m2.Matches("High"));
  1201. EXPECT_FALSE(m2.Matches("H"));
  1202. EXPECT_FALSE(m2.Matches(" Hi"));
  1203. }
  1204. TEST(StartsWithTest, CanDescribeSelf) {
  1205. Matcher<const std::string> m = StartsWith("Hi");
  1206. EXPECT_EQ("starts with \"Hi\"", Describe(m));
  1207. }
  1208. // Tests EndsWith(s).
  1209. TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
  1210. const Matcher<const char*> m1 = EndsWith("");
  1211. EXPECT_TRUE(m1.Matches("Hi"));
  1212. EXPECT_TRUE(m1.Matches(""));
  1213. EXPECT_FALSE(m1.Matches(NULL));
  1214. const Matcher<const string&> m2 = EndsWith(string("Hi"));
  1215. EXPECT_TRUE(m2.Matches("Hi"));
  1216. EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
  1217. EXPECT_TRUE(m2.Matches("Super Hi"));
  1218. EXPECT_FALSE(m2.Matches("i"));
  1219. EXPECT_FALSE(m2.Matches("Hi "));
  1220. }
  1221. TEST(EndsWithTest, CanDescribeSelf) {
  1222. Matcher<const std::string> m = EndsWith("Hi");
  1223. EXPECT_EQ("ends with \"Hi\"", Describe(m));
  1224. }
  1225. // Tests MatchesRegex().
  1226. TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
  1227. const Matcher<const char*> m1 = MatchesRegex("a.*z");
  1228. EXPECT_TRUE(m1.Matches("az"));
  1229. EXPECT_TRUE(m1.Matches("abcz"));
  1230. EXPECT_FALSE(m1.Matches(NULL));
  1231. const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z"));
  1232. EXPECT_TRUE(m2.Matches("azbz"));
  1233. EXPECT_FALSE(m2.Matches("az1"));
  1234. EXPECT_FALSE(m2.Matches("1az"));
  1235. }
  1236. TEST(MatchesRegexTest, CanDescribeSelf) {
  1237. Matcher<const std::string> m1 = MatchesRegex(string("Hi.*"));
  1238. EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
  1239. Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
  1240. EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
  1241. }
  1242. // Tests ContainsRegex().
  1243. TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
  1244. const Matcher<const char*> m1 = ContainsRegex(string("a.*z"));
  1245. EXPECT_TRUE(m1.Matches("az"));
  1246. EXPECT_TRUE(m1.Matches("0abcz1"));
  1247. EXPECT_FALSE(m1.Matches(NULL));
  1248. const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z"));
  1249. EXPECT_TRUE(m2.Matches("azbz"));
  1250. EXPECT_TRUE(m2.Matches("az1"));
  1251. EXPECT_FALSE(m2.Matches("1a"));
  1252. }
  1253. TEST(ContainsRegexTest, CanDescribeSelf) {
  1254. Matcher<const std::string> m1 = ContainsRegex("Hi.*");
  1255. EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
  1256. Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
  1257. EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
  1258. }
  1259. // Tests for wide strings.
  1260. #if GTEST_HAS_STD_WSTRING
  1261. TEST(StdWideStrEqTest, MatchesEqual) {
  1262. Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
  1263. EXPECT_TRUE(m.Matches(L"Hello"));
  1264. EXPECT_FALSE(m.Matches(L"hello"));
  1265. EXPECT_FALSE(m.Matches(NULL));
  1266. Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
  1267. EXPECT_TRUE(m2.Matches(L"Hello"));
  1268. EXPECT_FALSE(m2.Matches(L"Hi"));
  1269. Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
  1270. EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
  1271. EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
  1272. ::std::wstring str(L"01204500800");
  1273. str[3] = L'\0';
  1274. Matcher<const ::std::wstring&> m4 = StrEq(str);
  1275. EXPECT_TRUE(m4.Matches(str));
  1276. str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
  1277. Matcher<const ::std::wstring&> m5 = StrEq(str);
  1278. EXPECT_TRUE(m5.Matches(str));
  1279. }
  1280. TEST(StdWideStrEqTest, CanDescribeSelf) {
  1281. Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
  1282. EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
  1283. Describe(m));
  1284. Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
  1285. EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
  1286. Describe(m2));
  1287. ::std::wstring str(L"01204500800");
  1288. str[3] = L'\0';
  1289. Matcher<const ::std::wstring&> m4 = StrEq(str);
  1290. EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
  1291. str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
  1292. Matcher<const ::std::wstring&> m5 = StrEq(str);
  1293. EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
  1294. }
  1295. TEST(StdWideStrNeTest, MatchesUnequalString) {
  1296. Matcher<const wchar_t*> m = StrNe(L"Hello");
  1297. EXPECT_TRUE(m.Matches(L""));
  1298. EXPECT_TRUE(m.Matches(NULL));
  1299. EXPECT_FALSE(m.Matches(L"Hello"));
  1300. Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
  1301. EXPECT_TRUE(m2.Matches(L"hello"));
  1302. EXPECT_FALSE(m2.Matches(L"Hello"));
  1303. }
  1304. TEST(StdWideStrNeTest, CanDescribeSelf) {
  1305. Matcher<const wchar_t*> m = StrNe(L"Hi");
  1306. EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
  1307. }
  1308. TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
  1309. Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
  1310. EXPECT_TRUE(m.Matches(L"Hello"));
  1311. EXPECT_TRUE(m.Matches(L"hello"));
  1312. EXPECT_FALSE(m.Matches(L"Hi"));
  1313. EXPECT_FALSE(m.Matches(NULL));
  1314. Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
  1315. EXPECT_TRUE(m2.Matches(L"hello"));
  1316. EXPECT_FALSE(m2.Matches(L"Hi"));
  1317. }
  1318. TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
  1319. ::std::wstring str1(L"oabocdooeoo");
  1320. ::std::wstring str2(L"OABOCDOOEOO");
  1321. Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
  1322. EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
  1323. str1[3] = str2[3] = L'\0';
  1324. Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
  1325. EXPECT_TRUE(m1.Matches(str2));
  1326. str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
  1327. str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
  1328. Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
  1329. str1[9] = str2[9] = L'\0';
  1330. EXPECT_FALSE(m2.Matches(str2));
  1331. Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
  1332. EXPECT_TRUE(m3.Matches(str2));
  1333. EXPECT_FALSE(m3.Matches(str2 + L"x"));
  1334. str2.append(1, L'\0');
  1335. EXPECT_FALSE(m3.Matches(str2));
  1336. EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
  1337. }
  1338. TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
  1339. Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
  1340. EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
  1341. }
  1342. TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
  1343. Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
  1344. EXPECT_TRUE(m.Matches(L"Hi"));
  1345. EXPECT_TRUE(m.Matches(NULL));
  1346. EXPECT_FALSE(m.Matches(L"Hello"));
  1347. EXPECT_FALSE(m.Matches(L"hello"));
  1348. Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
  1349. EXPECT_TRUE(m2.Matches(L""));
  1350. EXPECT_FALSE(m2.Matches(L"Hello"));
  1351. }
  1352. TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
  1353. Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
  1354. EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
  1355. }
  1356. // Tests that HasSubstr() works for matching wstring-typed values.
  1357. TEST(StdWideHasSubstrTest, WorksForStringClasses) {
  1358. const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
  1359. EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
  1360. EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
  1361. const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
  1362. EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
  1363. EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
  1364. }
  1365. // Tests that HasSubstr() works for matching C-wide-string-typed values.
  1366. TEST(StdWideHasSubstrTest, WorksForCStrings) {
  1367. const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
  1368. EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
  1369. EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
  1370. EXPECT_FALSE(m1.Matches(NULL));
  1371. const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
  1372. EXPECT_TRUE(m2.Matches(L"I love food."));
  1373. EXPECT_FALSE(m2.Matches(L"tofo"));
  1374. EXPECT_FALSE(m2.Matches(NULL));
  1375. }
  1376. // Tests that HasSubstr(s) describes itself properly.
  1377. TEST(StdWideHasSubstrTest, CanDescribeSelf) {
  1378. Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
  1379. EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
  1380. }
  1381. // Tests StartsWith(s).
  1382. TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
  1383. const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
  1384. EXPECT_TRUE(m1.Matches(L"Hi"));
  1385. EXPECT_TRUE(m1.Matches(L""));
  1386. EXPECT_FALSE(m1.Matches(NULL));
  1387. const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
  1388. EXPECT_TRUE(m2.Matches(L"Hi"));
  1389. EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
  1390. EXPECT_TRUE(m2.Matches(L"High"));
  1391. EXPECT_FALSE(m2.Matches(L"H"));
  1392. EXPECT_FALSE(m2.Matches(L" Hi"));
  1393. }
  1394. TEST(StdWideStartsWithTest, CanDescribeSelf) {
  1395. Matcher<const ::std::wstring> m = StartsWith(L"Hi");
  1396. EXPECT_EQ("starts with L\"Hi\"", Describe(m));
  1397. }
  1398. // Tests EndsWith(s).
  1399. TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
  1400. const Matcher<const wchar_t*> m1 = EndsWith(L"");
  1401. EXPECT_TRUE(m1.Matches(L"Hi"));
  1402. EXPECT_TRUE(m1.Matches(L""));
  1403. EXPECT_FALSE(m1.Matches(NULL));
  1404. const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
  1405. EXPECT_TRUE(m2.Matches(L"Hi"));
  1406. EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
  1407. EXPECT_TRUE(m2.Matches(L"Super Hi"));
  1408. EXPECT_FALSE(m2.Matches(L"i"));
  1409. EXPECT_FALSE(m2.Matches(L"Hi "));
  1410. }
  1411. TEST(StdWideEndsWithTest, CanDescribeSelf) {
  1412. Matcher<const ::std::wstring> m = EndsWith(L"Hi");
  1413. EXPECT_EQ("ends with L\"Hi\"", Describe(m));
  1414. }
  1415. #endif // GTEST_HAS_STD_WSTRING
  1416. #if GTEST_HAS_GLOBAL_WSTRING
  1417. TEST(GlobalWideStrEqTest, MatchesEqual) {
  1418. Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
  1419. EXPECT_TRUE(m.Matches(L"Hello"));
  1420. EXPECT_FALSE(m.Matches(L"hello"));
  1421. EXPECT_FALSE(m.Matches(NULL));
  1422. Matcher<const ::wstring&> m2 = StrEq(L"Hello");
  1423. EXPECT_TRUE(m2.Matches(L"Hello"));
  1424. EXPECT_FALSE(m2.Matches(L"Hi"));
  1425. Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
  1426. EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
  1427. EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
  1428. ::wstring str(L"01204500800");
  1429. str[3] = L'\0';
  1430. Matcher<const ::wstring&> m4 = StrEq(str);
  1431. EXPECT_TRUE(m4.Matches(str));
  1432. str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
  1433. Matcher<const ::wstring&> m5 = StrEq(str);
  1434. EXPECT_TRUE(m5.Matches(str));
  1435. }
  1436. TEST(GlobalWideStrEqTest, CanDescribeSelf) {
  1437. Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
  1438. EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
  1439. Describe(m));
  1440. Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
  1441. EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
  1442. Describe(m2));
  1443. ::wstring str(L"01204500800");
  1444. str[3] = L'\0';
  1445. Matcher<const ::wstring&> m4 = StrEq(str);
  1446. EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
  1447. str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
  1448. Matcher<const ::wstring&> m5 = StrEq(str);
  1449. EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
  1450. }
  1451. TEST(GlobalWideStrNeTest, MatchesUnequalString) {
  1452. Matcher<const wchar_t*> m = StrNe(L"Hello");
  1453. EXPECT_TRUE(m.Matches(L""));
  1454. EXPECT_TRUE(m.Matches(NULL));
  1455. EXPECT_FALSE(m.Matches(L"Hello"));
  1456. Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
  1457. EXPECT_TRUE(m2.Matches(L"hello"));
  1458. EXPECT_FALSE(m2.Matches(L"Hello"));
  1459. }
  1460. TEST(GlobalWideStrNeTest, CanDescribeSelf) {
  1461. Matcher<const wchar_t*> m = StrNe(L"Hi");
  1462. EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
  1463. }
  1464. TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
  1465. Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
  1466. EXPECT_TRUE(m.Matches(L"Hello"));
  1467. EXPECT_TRUE(m.Matches(L"hello"));
  1468. EXPECT_FALSE(m.Matches(L"Hi"));
  1469. EXPECT_FALSE(m.Matches(NULL));
  1470. Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
  1471. EXPECT_TRUE(m2.Matches(L"hello"));
  1472. EXPECT_FALSE(m2.Matches(L"Hi"));
  1473. }
  1474. TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
  1475. ::wstring str1(L"oabocdooeoo");
  1476. ::wstring str2(L"OABOCDOOEOO");
  1477. Matcher<const ::wstring&> m0 = StrCaseEq(str1);
  1478. EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
  1479. str1[3] = str2[3] = L'\0';
  1480. Matcher<const ::wstring&> m1 = StrCaseEq(str1);
  1481. EXPECT_TRUE(m1.Matches(str2));
  1482. str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
  1483. str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
  1484. Matcher<const ::wstring&> m2 = StrCaseEq(str1);
  1485. str1[9] = str2[9] = L'\0';
  1486. EXPECT_FALSE(m2.Matches(str2));
  1487. Matcher<const ::wstring&> m3 = StrCaseEq(str1);
  1488. EXPECT_TRUE(m3.Matches(str2));
  1489. EXPECT_FALSE(m3.Matches(str2 + L"x"));
  1490. str2.append(1, L'\0');
  1491. EXPECT_FALSE(m3.Matches(str2));
  1492. EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
  1493. }
  1494. TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
  1495. Matcher< ::wstring> m = StrCaseEq(L"Hi");
  1496. EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
  1497. }
  1498. TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
  1499. Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
  1500. EXPECT_TRUE(m.Matches(L"Hi"));
  1501. EXPECT_TRUE(m.Matches(NULL));
  1502. EXPECT_FALSE(m.Matches(L"Hello"));
  1503. EXPECT_FALSE(m.Matches(L"hello"));
  1504. Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
  1505. EXPECT_TRUE(m2.Matches(L""));
  1506. EXPECT_FALSE(m2.Matches(L"Hello"));
  1507. }
  1508. TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
  1509. Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
  1510. EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
  1511. }
  1512. // Tests that HasSubstr() works for matching wstring-typed values.
  1513. TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
  1514. const Matcher< ::wstring> m1 = HasSubstr(L"foo");
  1515. EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
  1516. EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
  1517. const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
  1518. EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
  1519. EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
  1520. }
  1521. // Tests that HasSubstr() works for matching C-wide-string-typed values.
  1522. TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
  1523. const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
  1524. EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
  1525. EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
  1526. EXPECT_FALSE(m1.Matches(NULL));
  1527. const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
  1528. EXPECT_TRUE(m2.Matches(L"I love food."));
  1529. EXPECT_FALSE(m2.Matches(L"tofo"));
  1530. EXPECT_FALSE(m2.Matches(NULL));
  1531. }
  1532. // Tests that HasSubstr(s) describes itself properly.
  1533. TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
  1534. Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
  1535. EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
  1536. }
  1537. // Tests StartsWith(s).
  1538. TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
  1539. const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
  1540. EXPECT_TRUE(m1.Matches(L"Hi"));
  1541. EXPECT_TRUE(m1.Matches(L""));
  1542. EXPECT_FALSE(m1.Matches(NULL));
  1543. const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
  1544. EXPECT_TRUE(m2.Matches(L"Hi"));
  1545. EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
  1546. EXPECT_TRUE(m2.Matches(L"High"));
  1547. EXPECT_FALSE(m2.Matches(L"H"));
  1548. EXPECT_FALSE(m2.Matches(L" Hi"));
  1549. }
  1550. TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
  1551. Matcher<const ::wstring> m = StartsWith(L"Hi");
  1552. EXPECT_EQ("starts with L\"Hi\"", Describe(m));
  1553. }
  1554. // Tests EndsWith(s).
  1555. TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
  1556. const Matcher<const wchar_t*> m1 = EndsWith(L"");
  1557. EXPECT_TRUE(m1.Matches(L"Hi"));
  1558. EXPECT_TRUE(m1.Matches(L""));
  1559. EXPECT_FALSE(m1.Matches(NULL));
  1560. const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
  1561. EXPECT_TRUE(m2.Matches(L"Hi"));
  1562. EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
  1563. EXPECT_TRUE(m2.Matches(L"Super Hi"));
  1564. EXPECT_FALSE(m2.Matches(L"i"));
  1565. EXPECT_FALSE(m2.Matches(L"Hi "));
  1566. }
  1567. TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
  1568. Matcher<const ::wstring> m = EndsWith(L"Hi");
  1569. EXPECT_EQ("ends with L\"Hi\"", Describe(m));
  1570. }
  1571. #endif // GTEST_HAS_GLOBAL_WSTRING
  1572. typedef ::std::tr1::tuple<long, int> Tuple2; // NOLINT
  1573. // Tests that Eq() matches a 2-tuple where the first field == the
  1574. // second field.
  1575. TEST(Eq2Test, MatchesEqualArguments) {
  1576. Matcher<const Tuple2&> m = Eq();
  1577. EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
  1578. EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
  1579. }
  1580. // Tests that Eq() describes itself properly.
  1581. TEST(Eq2Test, CanDescribeSelf) {
  1582. Matcher<const Tuple2&> m = Eq();
  1583. EXPECT_EQ("are an equal pair", Describe(m));
  1584. }
  1585. // Tests that Ge() matches a 2-tuple where the first field >= the
  1586. // second field.
  1587. TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
  1588. Matcher<const Tuple2&> m = Ge();
  1589. EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
  1590. EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
  1591. EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
  1592. }
  1593. // Tests that Ge() describes itself properly.
  1594. TEST(Ge2Test, CanDescribeSelf) {
  1595. Matcher<const Tuple2&> m = Ge();
  1596. EXPECT_EQ("are a pair where the first >= the second", Describe(m));
  1597. }
  1598. // Tests that Gt() matches a 2-tuple where the first field > the
  1599. // second field.
  1600. TEST(Gt2Test, MatchesGreaterThanArguments) {
  1601. Matcher<const Tuple2&> m = Gt();
  1602. EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
  1603. EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
  1604. EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
  1605. }
  1606. // Tests that Gt() describes itself properly.
  1607. TEST(Gt2Test, CanDescribeSelf) {
  1608. Matcher<const Tuple2&> m = Gt();
  1609. EXPECT_EQ("are a pair where the first > the second", Describe(m));
  1610. }
  1611. // Tests that Le() matches a 2-tuple where the first field <= the
  1612. // second field.
  1613. TEST(Le2Test, MatchesLessThanOrEqualArguments) {
  1614. Matcher<const Tuple2&> m = Le();
  1615. EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
  1616. EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
  1617. EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
  1618. }
  1619. // Tests that Le() describes itself properly.
  1620. TEST(Le2Test, CanDescribeSelf) {
  1621. Matcher<const Tuple2&> m = Le();
  1622. EXPECT_EQ("are a pair where the first <= the second", Describe(m));
  1623. }
  1624. // Tests that Lt() matches a 2-tuple where the first field < the
  1625. // second field.
  1626. TEST(Lt2Test, MatchesLessThanArguments) {
  1627. Matcher<const Tuple2&> m = Lt();
  1628. EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
  1629. EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
  1630. EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
  1631. }
  1632. // Tests that Lt() describes itself properly.
  1633. TEST(Lt2Test, CanDescribeSelf) {
  1634. Matcher<const Tuple2&> m = Lt();
  1635. EXPECT_EQ("are a pair where the first < the second", Describe(m));
  1636. }
  1637. // Tests that Ne() matches a 2-tuple where the first field != the
  1638. // second field.
  1639. TEST(Ne2Test, MatchesUnequalArguments) {
  1640. Matcher<const Tuple2&> m = Ne();
  1641. EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
  1642. EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
  1643. EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
  1644. }
  1645. // Tests that Ne() describes itself properly.
  1646. TEST(Ne2Test, CanDescribeSelf) {
  1647. Matcher<const Tuple2&> m = Ne();
  1648. EXPECT_EQ("are an unequal pair", Describe(m));
  1649. }
  1650. // Tests that Not(m) matches any value that doesn't match m.
  1651. TEST(NotTest, NegatesMatcher) {
  1652. Matcher<int> m;
  1653. m = Not(Eq(2));
  1654. EXPECT_TRUE(m.Matches(3));
  1655. EXPECT_FALSE(m.Matches(2));
  1656. }
  1657. // Tests that Not(m) describes itself properly.
  1658. TEST(NotTest, CanDescribeSelf) {
  1659. Matcher<int> m = Not(Eq(5));
  1660. EXPECT_EQ("isn't equal to 5", Describe(m));
  1661. }
  1662. // Tests that monomorphic matchers are safely cast by the Not matcher.
  1663. TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
  1664. // greater_than_5 is a monomorphic matcher.
  1665. Matcher<int> greater_than_5 = Gt(5);
  1666. Matcher<const int&> m = Not(greater_than_5);
  1667. Matcher<int&> m2 = Not(greater_than_5);
  1668. Matcher<int&> m3 = Not(m);
  1669. }
  1670. // Helper to allow easy testing of AllOf matchers with num parameters.
  1671. void AllOfMatches(int num, const Matcher<int>& m) {
  1672. SCOPED_TRACE(Describe(m));
  1673. EXPECT_TRUE(m.Matches(0));
  1674. for (int i = 1; i <= num; ++i) {
  1675. EXPECT_FALSE(m.Matches(i));
  1676. }
  1677. EXPECT_TRUE(m.Matches(num + 1));
  1678. }
  1679. // Tests that AllOf(m1, ..., mn) matches any value that matches all of
  1680. // the given matchers.
  1681. TEST(AllOfTest, MatchesWhenAllMatch) {
  1682. Matcher<int> m;
  1683. m = AllOf(Le(2), Ge(1));
  1684. EXPECT_TRUE(m.Matches(1));
  1685. EXPECT_TRUE(m.Matches(2));
  1686. EXPECT_FALSE(m.Matches(0));
  1687. EXPECT_FALSE(m.Matches(3));
  1688. m = AllOf(Gt(0), Ne(1), Ne(2));
  1689. EXPECT_TRUE(m.Matches(3));
  1690. EXPECT_FALSE(m.Matches(2));
  1691. EXPECT_FALSE(m.Matches(1));
  1692. EXPECT_FALSE(m.Matches(0));
  1693. m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
  1694. EXPECT_TRUE(m.Matches(4));
  1695. EXPECT_FALSE(m.Matches(3));
  1696. EXPECT_FALSE(m.Matches(2));
  1697. EXPECT_FALSE(m.Matches(1));
  1698. EXPECT_FALSE(m.Matches(0));
  1699. m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
  1700. EXPECT_TRUE(m.Matches(0));
  1701. EXPECT_TRUE(m.Matches(1));
  1702. EXPECT_FALSE(m.Matches(3));
  1703. // The following tests for varying number of sub-matchers. Due to the way
  1704. // the sub-matchers are handled it is enough to test every sub-matcher once
  1705. // with sub-matchers using the same matcher type. Varying matcher types are
  1706. // checked for above.
  1707. AllOfMatches(2, AllOf(Ne(1), Ne(2)));
  1708. AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
  1709. AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
  1710. AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
  1711. AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
  1712. AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
  1713. AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
  1714. Ne(8)));
  1715. AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
  1716. Ne(8), Ne(9)));
  1717. AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
  1718. Ne(9), Ne(10)));
  1719. }
  1720. #if GTEST_LANG_CXX11
  1721. // Tests the variadic version of the AllOfMatcher.
  1722. TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
  1723. // Make sure AllOf is defined in the right namespace and does not depend on
  1724. // ADL.
  1725. ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
  1726. Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
  1727. Ne(9), Ne(10), Ne(11));
  1728. EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))"));
  1729. AllOfMatches(11, m);
  1730. AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
  1731. Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
  1732. Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22),
  1733. Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29),
  1734. Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36),
  1735. Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43),
  1736. Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
  1737. Ne(50)));
  1738. }
  1739. #endif // GTEST_LANG_CXX11
  1740. // Tests that AllOf(m1, ..., mn) describes itself properly.
  1741. TEST(AllOfTest, CanDescribeSelf) {
  1742. Matcher<int> m;
  1743. m = AllOf(Le(2), Ge(1));
  1744. EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
  1745. m = AllOf(Gt(0), Ne(1), Ne(2));
  1746. EXPECT_EQ("(is > 0) and "
  1747. "((isn't equal to 1) and "
  1748. "(isn't equal to 2))",
  1749. Describe(m));
  1750. m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
  1751. EXPECT_EQ("((is > 0) and "
  1752. "(isn't equal to 1)) and "
  1753. "((isn't equal to 2) and "
  1754. "(isn't equal to 3))",
  1755. Describe(m));
  1756. m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
  1757. EXPECT_EQ("((is >= 0) and "
  1758. "(is < 10)) and "
  1759. "((isn't equal to 3) and "
  1760. "((isn't equal to 5) and "
  1761. "(isn't equal to 7)))",
  1762. Describe(m));
  1763. }
  1764. // Tests that AllOf(m1, ..., mn) describes its negation properly.
  1765. TEST(AllOfTest, CanDescribeNegation) {
  1766. Matcher<int> m;
  1767. m = AllOf(Le(2), Ge(1));
  1768. EXPECT_EQ("(isn't <= 2) or "
  1769. "(isn't >= 1)",
  1770. DescribeNegation(m));
  1771. m = AllOf(Gt(0), Ne(1), Ne(2));
  1772. EXPECT_EQ("(isn't > 0) or "
  1773. "((is equal to 1) or "
  1774. "(is equal to 2))",
  1775. DescribeNegation(m));
  1776. m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
  1777. EXPECT_EQ("((isn't > 0) or "
  1778. "(is equal to 1)) or "
  1779. "((is equal to 2) or "
  1780. "(is equal to 3))",
  1781. DescribeNegation(m));
  1782. m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
  1783. EXPECT_EQ("((isn't >= 0) or "
  1784. "(isn't < 10)) or "
  1785. "((is equal to 3) or "
  1786. "((is equal to 5) or "
  1787. "(is equal to 7)))",
  1788. DescribeNegation(m));
  1789. }
  1790. // Tests that monomorphic matchers are safely cast by the AllOf matcher.
  1791. TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
  1792. // greater_than_5 and less_than_10 are monomorphic matchers.
  1793. Matcher<int> greater_than_5 = Gt(5);
  1794. Matcher<int> less_than_10 = Lt(10);
  1795. Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
  1796. Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
  1797. Matcher<int&> m3 = AllOf(greater_than_5, m2);
  1798. // Tests that BothOf works when composing itself.
  1799. Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
  1800. Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
  1801. }
  1802. TEST(AllOfTest, ExplainsResult) {
  1803. Matcher<int> m;
  1804. // Successful match. Both matchers need to explain. The second
  1805. // matcher doesn't give an explanation, so only the first matcher's
  1806. // explanation is printed.
  1807. m = AllOf(GreaterThan(10), Lt(30));
  1808. EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
  1809. // Successful match. Both matchers need to explain.
  1810. m = AllOf(GreaterThan(10), GreaterThan(20));
  1811. EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
  1812. Explain(m, 30));
  1813. // Successful match. All matchers need to explain. The second
  1814. // matcher doesn't given an explanation.
  1815. m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
  1816. EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
  1817. Explain(m, 25));
  1818. // Successful match. All matchers need to explain.
  1819. m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
  1820. EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
  1821. "and which is 10 more than 30",
  1822. Explain(m, 40));
  1823. // Failed match. The first matcher, which failed, needs to
  1824. // explain.
  1825. m = AllOf(GreaterThan(10), GreaterThan(20));
  1826. EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
  1827. // Failed match. The second matcher, which failed, needs to
  1828. // explain. Since it doesn't given an explanation, nothing is
  1829. // printed.
  1830. m = AllOf(GreaterThan(10), Lt(30));
  1831. EXPECT_EQ("", Explain(m, 40));
  1832. // Failed match. The second matcher, which failed, needs to
  1833. // explain.
  1834. m = AllOf(GreaterThan(10), GreaterThan(20));
  1835. EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
  1836. }
  1837. // Helper to allow easy testing of AnyOf matchers with num parameters.
  1838. void AnyOfMatches(int num, const Matcher<int>& m) {
  1839. SCOPED_TRACE(Describe(m));
  1840. EXPECT_FALSE(m.Matches(0));
  1841. for (int i = 1; i <= num; ++i) {
  1842. EXPECT_TRUE(m.Matches(i));
  1843. }
  1844. EXPECT_FALSE(m.Matches(num + 1));
  1845. }
  1846. // Tests that AnyOf(m1, ..., mn) matches any value that matches at
  1847. // least one of the given matchers.
  1848. TEST(AnyOfTest, MatchesWhenAnyMatches) {
  1849. Matcher<int> m;
  1850. m = AnyOf(Le(1), Ge(3));
  1851. EXPECT_TRUE(m.Matches(1));
  1852. EXPECT_TRUE(m.Matches(4));
  1853. EXPECT_FALSE(m.Matches(2));
  1854. m = AnyOf(Lt(0), Eq(1), Eq(2));
  1855. EXPECT_TRUE(m.Matches(-1));
  1856. EXPECT_TRUE(m.Matches(1));
  1857. EXPECT_TRUE(m.Matches(2));
  1858. EXPECT_FALSE(m.Matches(0));
  1859. m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
  1860. EXPECT_TRUE(m.Matches(-1));
  1861. EXPECT_TRUE(m.Matches(1));
  1862. EXPECT_TRUE(m.Matches(2));
  1863. EXPECT_TRUE(m.Matches(3));
  1864. EXPECT_FALSE(m.Matches(0));
  1865. m = AnyOf(Le(0), Gt(10), 3, 5, 7);
  1866. EXPECT_TRUE(m.Matches(0));
  1867. EXPECT_TRUE(m.Matches(11));
  1868. EXPECT_TRUE(m.Matches(3));
  1869. EXPECT_FALSE(m.Matches(2));
  1870. // The following tests for varying number of sub-matchers. Due to the way
  1871. // the sub-matchers are handled it is enough to test every sub-matcher once
  1872. // with sub-matchers using the same matcher type. Varying matcher types are
  1873. // checked for above.
  1874. AnyOfMatches(2, AnyOf(1, 2));
  1875. AnyOfMatches(3, AnyOf(1, 2, 3));
  1876. AnyOfMatches(4, AnyOf(1, 2, 3, 4));
  1877. AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
  1878. AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
  1879. AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
  1880. AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
  1881. AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
  1882. AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
  1883. }
  1884. #if GTEST_LANG_CXX11
  1885. // Tests the variadic version of the AnyOfMatcher.
  1886. TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
  1887. // Also make sure AnyOf is defined in the right namespace and does not depend
  1888. // on ADL.
  1889. Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
  1890. EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))"));
  1891. AnyOfMatches(11, m);
  1892. AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
  1893. 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
  1894. 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
  1895. 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  1896. 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
  1897. }
  1898. #endif // GTEST_LANG_CXX11
  1899. // Tests that AnyOf(m1, ..., mn) describes itself properly.
  1900. TEST(AnyOfTest, CanDescribeSelf) {
  1901. Matcher<int> m;
  1902. m = AnyOf(Le(1), Ge(3));
  1903. EXPECT_EQ("(is <= 1) or (is >= 3)",
  1904. Describe(m));
  1905. m = AnyOf(Lt(0), Eq(1), Eq(2));
  1906. EXPECT_EQ("(is < 0) or "
  1907. "((is equal to 1) or (is equal to 2))",
  1908. Describe(m));
  1909. m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
  1910. EXPECT_EQ("((is < 0) or "
  1911. "(is equal to 1)) or "
  1912. "((is equal to 2) or "
  1913. "(is equal to 3))",
  1914. Describe(m));
  1915. m = AnyOf(Le(0), Gt(10), 3, 5, 7);
  1916. EXPECT_EQ("((is <= 0) or "
  1917. "(is > 10)) or "
  1918. "((is equal to 3) or "
  1919. "((is equal to 5) or "
  1920. "(is equal to 7)))",
  1921. Describe(m));
  1922. }
  1923. // Tests that AnyOf(m1, ..., mn) describes its negation properly.
  1924. TEST(AnyOfTest, CanDescribeNegation) {
  1925. Matcher<int> m;
  1926. m = AnyOf(Le(1), Ge(3));
  1927. EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
  1928. DescribeNegation(m));
  1929. m = AnyOf(Lt(0), Eq(1), Eq(2));
  1930. EXPECT_EQ("(isn't < 0) and "
  1931. "((isn't equal to 1) and (isn't equal to 2))",
  1932. DescribeNegation(m));
  1933. m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
  1934. EXPECT_EQ("((isn't < 0) and "
  1935. "(isn't equal to 1)) and "
  1936. "((isn't equal to 2) and "
  1937. "(isn't equal to 3))",
  1938. DescribeNegation(m));
  1939. m = AnyOf(Le(0), Gt(10), 3, 5, 7);
  1940. EXPECT_EQ("((isn't <= 0) and "
  1941. "(isn't > 10)) and "
  1942. "((isn't equal to 3) and "
  1943. "((isn't equal to 5) and "
  1944. "(isn't equal to 7)))",
  1945. DescribeNegation(m));
  1946. }
  1947. // Tests that monomorphic matchers are safely cast by the AnyOf matcher.
  1948. TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
  1949. // greater_than_5 and less_than_10 are monomorphic matchers.
  1950. Matcher<int> greater_than_5 = Gt(5);
  1951. Matcher<int> less_than_10 = Lt(10);
  1952. Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
  1953. Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
  1954. Matcher<int&> m3 = AnyOf(greater_than_5, m2);
  1955. // Tests that EitherOf works when composing itself.
  1956. Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
  1957. Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
  1958. }
  1959. TEST(AnyOfTest, ExplainsResult) {
  1960. Matcher<int> m;
  1961. // Failed match. Both matchers need to explain. The second
  1962. // matcher doesn't give an explanation, so only the first matcher's
  1963. // explanation is printed.
  1964. m = AnyOf(GreaterThan(10), Lt(0));
  1965. EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
  1966. // Failed match. Both matchers need to explain.
  1967. m = AnyOf(GreaterThan(10), GreaterThan(20));
  1968. EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
  1969. Explain(m, 5));
  1970. // Failed match. All matchers need to explain. The second
  1971. // matcher doesn't given an explanation.
  1972. m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
  1973. EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
  1974. Explain(m, 5));
  1975. // Failed match. All matchers need to explain.
  1976. m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
  1977. EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
  1978. "and which is 25 less than 30",
  1979. Explain(m, 5));
  1980. // Successful match. The first matcher, which succeeded, needs to
  1981. // explain.
  1982. m = AnyOf(GreaterThan(10), GreaterThan(20));
  1983. EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
  1984. // Successful match. The second matcher, which succeeded, needs to
  1985. // explain. Since it doesn't given an explanation, nothing is
  1986. // printed.
  1987. m = AnyOf(GreaterThan(10), Lt(30));
  1988. EXPECT_EQ("", Explain(m, 0));
  1989. // Successful match. The second matcher, which succeeded, needs to
  1990. // explain.
  1991. m = AnyOf(GreaterThan(30), GreaterThan(20));
  1992. EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
  1993. }
  1994. // The following predicate function and predicate functor are for
  1995. // testing the Truly(predicate) matcher.
  1996. // Returns non-zero if the input is positive. Note that the return
  1997. // type of this function is not bool. It's OK as Truly() accepts any
  1998. // unary function or functor whose return type can be implicitly
  1999. // converted to bool.
  2000. int IsPositive(double x) {
  2001. return x > 0 ? 1 : 0;
  2002. }
  2003. // This functor returns true if the input is greater than the given
  2004. // number.
  2005. class IsGreaterThan {
  2006. public:
  2007. explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
  2008. bool operator()(int n) const { return n > threshold_; }
  2009. private:
  2010. int threshold_;
  2011. };
  2012. // For testing Truly().
  2013. const int foo = 0;
  2014. // This predicate returns true iff the argument references foo and has
  2015. // a zero value.
  2016. bool ReferencesFooAndIsZero(const int& n) {
  2017. return (&n == &foo) && (n == 0);
  2018. }
  2019. // Tests that Truly(predicate) matches what satisfies the given
  2020. // predicate.
  2021. TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
  2022. Matcher<double> m = Truly(IsPositive);
  2023. EXPECT_TRUE(m.Matches(2.0));
  2024. EXPECT_FALSE(m.Matches(-1.5));
  2025. }
  2026. // Tests that Truly(predicate_functor) works too.
  2027. TEST(TrulyTest, CanBeUsedWithFunctor) {
  2028. Matcher<int> m = Truly(IsGreaterThan(5));
  2029. EXPECT_TRUE(m.Matches(6));
  2030. EXPECT_FALSE(m.Matches(4));
  2031. }
  2032. // A class that can be implicitly converted to bool.
  2033. class ConvertibleToBool {
  2034. public:
  2035. explicit ConvertibleToBool(int number) : number_(number) {}
  2036. operator bool() const { return number_ != 0; }
  2037. private:
  2038. int number_;
  2039. };
  2040. ConvertibleToBool IsNotZero(int number) {
  2041. return ConvertibleToBool(number);
  2042. }
  2043. // Tests that the predicate used in Truly() may return a class that's
  2044. // implicitly convertible to bool, even when the class has no
  2045. // operator!().
  2046. TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
  2047. Matcher<int> m = Truly(IsNotZero);
  2048. EXPECT_TRUE(m.Matches(1));
  2049. EXPECT_FALSE(m.Matches(0));
  2050. }
  2051. // Tests that Truly(predicate) can describe itself properly.
  2052. TEST(TrulyTest, CanDescribeSelf) {
  2053. Matcher<double> m = Truly(IsPositive);
  2054. EXPECT_EQ("satisfies the given predicate",
  2055. Describe(m));
  2056. }
  2057. // Tests that Truly(predicate) works when the matcher takes its
  2058. // argument by reference.
  2059. TEST(TrulyTest, WorksForByRefArguments) {
  2060. Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
  2061. EXPECT_TRUE(m.Matches(foo));
  2062. int n = 0;
  2063. EXPECT_FALSE(m.Matches(n));
  2064. }
  2065. // Tests that Matches(m) is a predicate satisfied by whatever that
  2066. // matches matcher m.
  2067. TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
  2068. EXPECT_TRUE(Matches(Ge(0))(1));
  2069. EXPECT_FALSE(Matches(Eq('a'))('b'));
  2070. }
  2071. // Tests that Matches(m) works when the matcher takes its argument by
  2072. // reference.
  2073. TEST(MatchesTest, WorksOnByRefArguments) {
  2074. int m = 0, n = 0;
  2075. EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
  2076. EXPECT_FALSE(Matches(Ref(m))(n));
  2077. }
  2078. // Tests that a Matcher on non-reference type can be used in
  2079. // Matches().
  2080. TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
  2081. Matcher<int> eq5 = Eq(5);
  2082. EXPECT_TRUE(Matches(eq5)(5));
  2083. EXPECT_FALSE(Matches(eq5)(2));
  2084. }
  2085. // Tests Value(value, matcher). Since Value() is a simple wrapper for
  2086. // Matches(), which has been tested already, we don't spend a lot of
  2087. // effort on testing Value().
  2088. TEST(ValueTest, WorksWithPolymorphicMatcher) {
  2089. EXPECT_TRUE(Value("hi", StartsWith("h")));
  2090. EXPECT_FALSE(Value(5, Gt(10)));
  2091. }
  2092. TEST(ValueTest, WorksWithMonomorphicMatcher) {
  2093. const Matcher<int> is_zero = Eq(0);
  2094. EXPECT_TRUE(Value(0, is_zero));
  2095. EXPECT_FALSE(Value('a', is_zero));
  2096. int n = 0;
  2097. const Matcher<const int&> ref_n = Ref(n);
  2098. EXPECT_TRUE(Value(n, ref_n));
  2099. EXPECT_FALSE(Value(1, ref_n));
  2100. }
  2101. TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
  2102. StringMatchResultListener listener1;
  2103. EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
  2104. EXPECT_EQ("% 2 == 0", listener1.str());
  2105. StringMatchResultListener listener2;
  2106. EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
  2107. EXPECT_EQ("", listener2.str());
  2108. }
  2109. TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
  2110. const Matcher<int> is_even = PolymorphicIsEven();
  2111. StringMatchResultListener listener1;
  2112. EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
  2113. EXPECT_EQ("% 2 == 0", listener1.str());
  2114. const Matcher<const double&> is_zero = Eq(0);
  2115. StringMatchResultListener listener2;
  2116. EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
  2117. EXPECT_EQ("", listener2.str());
  2118. }
  2119. MATCHER_P(Really, inner_matcher, "") {
  2120. return ExplainMatchResult(inner_matcher, arg, result_listener);
  2121. }
  2122. TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
  2123. EXPECT_THAT(0, Really(Eq(0)));
  2124. }
  2125. TEST(AllArgsTest, WorksForTuple) {
  2126. EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
  2127. EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
  2128. }
  2129. TEST(AllArgsTest, WorksForNonTuple) {
  2130. EXPECT_THAT(42, AllArgs(Gt(0)));
  2131. EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
  2132. }
  2133. class AllArgsHelper {
  2134. public:
  2135. AllArgsHelper() {}
  2136. MOCK_METHOD2(Helper, int(char x, int y));
  2137. private:
  2138. GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
  2139. };
  2140. TEST(AllArgsTest, WorksInWithClause) {
  2141. AllArgsHelper helper;
  2142. ON_CALL(helper, Helper(_, _))
  2143. .With(AllArgs(Lt()))
  2144. .WillByDefault(Return(1));
  2145. EXPECT_CALL(helper, Helper(_, _));
  2146. EXPECT_CALL(helper, Helper(_, _))
  2147. .With(AllArgs(Gt()))
  2148. .WillOnce(Return(2));
  2149. EXPECT_EQ(1, helper.Helper('\1', 2));
  2150. EXPECT_EQ(2, helper.Helper('a', 1));
  2151. }
  2152. // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
  2153. // matches the matcher.
  2154. TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
  2155. ASSERT_THAT(5, Ge(2)) << "This should succeed.";
  2156. ASSERT_THAT("Foo", EndsWith("oo"));
  2157. EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
  2158. EXPECT_THAT("Hello", StartsWith("Hell"));
  2159. }
  2160. // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
  2161. // doesn't match the matcher.
  2162. TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
  2163. // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
  2164. // which cannot reference auto variables.
  2165. static unsigned short n; // NOLINT
  2166. n = 5;
  2167. // VC++ prior to version 8.0 SP1 has a bug where it will not see any
  2168. // functions declared in the namespace scope from within nested classes.
  2169. // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
  2170. // namespace-level functions invoked inside them need to be explicitly
  2171. // resolved.
  2172. EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
  2173. "Value of: n\n"
  2174. "Expected: is > 10\n"
  2175. " Actual: 5" + OfType("unsigned short"));
  2176. n = 0;
  2177. EXPECT_NONFATAL_FAILURE(
  2178. EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
  2179. "Value of: n\n"
  2180. "Expected: (is <= 7) and (is >= 5)\n"
  2181. " Actual: 0" + OfType("unsigned short"));
  2182. }
  2183. // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
  2184. // has a reference type.
  2185. TEST(MatcherAssertionTest, WorksForByRefArguments) {
  2186. // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
  2187. // reference auto variables.
  2188. static int n;
  2189. n = 0;
  2190. EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
  2191. EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
  2192. "Value of: n\n"
  2193. "Expected: does not reference the variable @");
  2194. // Tests the "Actual" part.
  2195. EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
  2196. "Actual: 0" + OfType("int") + ", which is located @");
  2197. }
  2198. #if !GTEST_OS_SYMBIAN
  2199. // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
  2200. // monomorphic.
  2201. // ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
  2202. // Symbian compiler: it tries to compile
  2203. // template<T, U> class MatcherCastImpl { ...
  2204. // virtual bool MatchAndExplain(T x, ...) const {
  2205. // return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
  2206. // with U == string and T == const char*
  2207. // With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
  2208. // the compiler silently crashes with no output.
  2209. // If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
  2210. // the code compiles but the converted string is bogus.
  2211. TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
  2212. Matcher<const char*> starts_with_he = StartsWith("he");
  2213. ASSERT_THAT("hello", starts_with_he);
  2214. Matcher<const string&> ends_with_ok = EndsWith("ok");
  2215. ASSERT_THAT("book", ends_with_ok);
  2216. const string bad = "bad";
  2217. EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
  2218. "Value of: bad\n"
  2219. "Expected: ends with \"ok\"\n"
  2220. " Actual: \"bad\"");
  2221. Matcher<int> is_greater_than_5 = Gt(5);
  2222. EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
  2223. "Value of: 5\n"
  2224. "Expected: is > 5\n"
  2225. " Actual: 5" + OfType("int"));
  2226. }
  2227. #endif // !GTEST_OS_SYMBIAN
  2228. // Tests floating-point matchers.
  2229. template <typename RawType>
  2230. class FloatingPointTest : public testing::Test {
  2231. protected:
  2232. typedef testing::internal::FloatingPoint<RawType> Floating;
  2233. typedef typename Floating::Bits Bits;
  2234. FloatingPointTest()
  2235. : max_ulps_(Floating::kMaxUlps),
  2236. zero_bits_(Floating(0).bits()),
  2237. one_bits_(Floating(1).bits()),
  2238. infinity_bits_(Floating(Floating::Infinity()).bits()),
  2239. close_to_positive_zero_(
  2240. Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
  2241. close_to_negative_zero_(
  2242. -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
  2243. further_from_negative_zero_(-Floating::ReinterpretBits(
  2244. zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
  2245. close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
  2246. further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
  2247. infinity_(Floating::Infinity()),
  2248. close_to_infinity_(
  2249. Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
  2250. further_from_infinity_(
  2251. Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
  2252. max_(Floating::Max()),
  2253. nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
  2254. nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
  2255. }
  2256. void TestSize() {
  2257. EXPECT_EQ(sizeof(RawType), sizeof(Bits));
  2258. }
  2259. // A battery of tests for FloatingEqMatcher::Matches.
  2260. // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
  2261. void TestMatches(
  2262. testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
  2263. Matcher<RawType> m1 = matcher_maker(0.0);
  2264. EXPECT_TRUE(m1.Matches(-0.0));
  2265. EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
  2266. EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
  2267. EXPECT_FALSE(m1.Matches(1.0));
  2268. Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
  2269. EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
  2270. Matcher<RawType> m3 = matcher_maker(1.0);
  2271. EXPECT_TRUE(m3.Matches(close_to_one_));
  2272. EXPECT_FALSE(m3.Matches(further_from_one_));
  2273. // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
  2274. EXPECT_FALSE(m3.Matches(0.0));
  2275. Matcher<RawType> m4 = matcher_maker(-infinity_);
  2276. EXPECT_TRUE(m4.Matches(-close_to_infinity_));
  2277. Matcher<RawType> m5 = matcher_maker(infinity_);
  2278. EXPECT_TRUE(m5.Matches(close_to_infinity_));
  2279. // This is interesting as the representations of infinity_ and nan1_
  2280. // are only 1 DLP apart.
  2281. EXPECT_FALSE(m5.Matches(nan1_));
  2282. // matcher_maker can produce a Matcher<const RawType&>, which is needed in
  2283. // some cases.
  2284. Matcher<const RawType&> m6 = matcher_maker(0.0);
  2285. EXPECT_TRUE(m6.Matches(-0.0));
  2286. EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
  2287. EXPECT_FALSE(m6.Matches(1.0));
  2288. // matcher_maker can produce a Matcher<RawType&>, which is needed in some
  2289. // cases.
  2290. Matcher<RawType&> m7 = matcher_maker(0.0);
  2291. RawType x = 0.0;
  2292. EXPECT_TRUE(m7.Matches(x));
  2293. x = 0.01f;
  2294. EXPECT_FALSE(m7.Matches(x));
  2295. }
  2296. // Pre-calculated numbers to be used by the tests.
  2297. const size_t max_ulps_;
  2298. const Bits zero_bits_; // The bits that represent 0.0.
  2299. const Bits one_bits_; // The bits that represent 1.0.
  2300. const Bits infinity_bits_; // The bits that represent +infinity.
  2301. // Some numbers close to 0.0.
  2302. const RawType close_to_positive_zero_;
  2303. const RawType close_to_negative_zero_;
  2304. const RawType further_from_negative_zero_;
  2305. // Some numbers close to 1.0.
  2306. const RawType close_to_one_;
  2307. const RawType further_from_one_;
  2308. // Some numbers close to +infinity.
  2309. const RawType infinity_;
  2310. const RawType close_to_infinity_;
  2311. const RawType further_from_infinity_;
  2312. // Maximum representable value that's not infinity.
  2313. const RawType max_;
  2314. // Some NaNs.
  2315. const RawType nan1_;
  2316. const RawType nan2_;
  2317. };
  2318. // Tests floating-point matchers with fixed epsilons.
  2319. template <typename RawType>
  2320. class FloatingPointNearTest : public FloatingPointTest<RawType> {
  2321. protected:
  2322. typedef FloatingPointTest<RawType> ParentType;
  2323. // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
  2324. // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
  2325. void TestNearMatches(
  2326. testing::internal::FloatingEqMatcher<RawType>
  2327. (*matcher_maker)(RawType, RawType)) {
  2328. Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
  2329. EXPECT_TRUE(m1.Matches(0.0));
  2330. EXPECT_TRUE(m1.Matches(-0.0));
  2331. EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
  2332. EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
  2333. EXPECT_FALSE(m1.Matches(1.0));
  2334. Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
  2335. EXPECT_TRUE(m2.Matches(0.0));
  2336. EXPECT_TRUE(m2.Matches(-0.0));
  2337. EXPECT_TRUE(m2.Matches(1.0));
  2338. EXPECT_TRUE(m2.Matches(-1.0));
  2339. EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
  2340. EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
  2341. // Check that inf matches inf, regardless of the of the specified max
  2342. // absolute error.
  2343. Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
  2344. EXPECT_TRUE(m3.Matches(ParentType::infinity_));
  2345. EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
  2346. EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
  2347. Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
  2348. EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
  2349. EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
  2350. EXPECT_FALSE(m4.Matches(ParentType::infinity_));
  2351. // Test various overflow scenarios.
  2352. Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
  2353. EXPECT_TRUE(m5.Matches(ParentType::max_));
  2354. EXPECT_FALSE(m5.Matches(-ParentType::max_));
  2355. Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
  2356. EXPECT_FALSE(m6.Matches(ParentType::max_));
  2357. EXPECT_TRUE(m6.Matches(-ParentType::max_));
  2358. Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
  2359. EXPECT_TRUE(m7.Matches(ParentType::max_));
  2360. EXPECT_FALSE(m7.Matches(-ParentType::max_));
  2361. Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
  2362. EXPECT_FALSE(m8.Matches(ParentType::max_));
  2363. EXPECT_TRUE(m8.Matches(-ParentType::max_));
  2364. // The difference between max() and -max() normally overflows to infinity,
  2365. // but it should still match if the max_abs_error is also infinity.
  2366. Matcher<RawType> m9 = matcher_maker(
  2367. ParentType::max_, ParentType::infinity_);
  2368. EXPECT_TRUE(m8.Matches(-ParentType::max_));
  2369. // matcher_maker can produce a Matcher<const RawType&>, which is needed in
  2370. // some cases.
  2371. Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
  2372. EXPECT_TRUE(m10.Matches(-0.0));
  2373. EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
  2374. EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
  2375. // matcher_maker can produce a Matcher<RawType&>, which is needed in some
  2376. // cases.
  2377. Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
  2378. RawType x = 0.0;
  2379. EXPECT_TRUE(m11.Matches(x));
  2380. x = 1.0f;
  2381. EXPECT_TRUE(m11.Matches(x));
  2382. x = -1.0f;
  2383. EXPECT_TRUE(m11.Matches(x));
  2384. x = 1.1f;
  2385. EXPECT_FALSE(m11.Matches(x));
  2386. x = -1.1f;
  2387. EXPECT_FALSE(m11.Matches(x));
  2388. }
  2389. };
  2390. // Instantiate FloatingPointTest for testing floats.
  2391. typedef FloatingPointTest<float> FloatTest;
  2392. TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
  2393. TestMatches(&FloatEq);
  2394. }
  2395. TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
  2396. TestMatches(&NanSensitiveFloatEq);
  2397. }
  2398. TEST_F(FloatTest, FloatEqCannotMatchNaN) {
  2399. // FloatEq never matches NaN.
  2400. Matcher<float> m = FloatEq(nan1_);
  2401. EXPECT_FALSE(m.Matches(nan1_));
  2402. EXPECT_FALSE(m.Matches(nan2_));
  2403. EXPECT_FALSE(m.Matches(1.0));
  2404. }
  2405. TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
  2406. // NanSensitiveFloatEq will match NaN.
  2407. Matcher<float> m = NanSensitiveFloatEq(nan1_);
  2408. EXPECT_TRUE(m.Matches(nan1_));
  2409. EXPECT_TRUE(m.Matches(nan2_));
  2410. EXPECT_FALSE(m.Matches(1.0));
  2411. }
  2412. TEST_F(FloatTest, FloatEqCanDescribeSelf) {
  2413. Matcher<float> m1 = FloatEq(2.0f);
  2414. EXPECT_EQ("is approximately 2", Describe(m1));
  2415. EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
  2416. Matcher<float> m2 = FloatEq(0.5f);
  2417. EXPECT_EQ("is approximately 0.5", Describe(m2));
  2418. EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
  2419. Matcher<float> m3 = FloatEq(nan1_);
  2420. EXPECT_EQ("never matches", Describe(m3));
  2421. EXPECT_EQ("is anything", DescribeNegation(m3));
  2422. }
  2423. TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
  2424. Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
  2425. EXPECT_EQ("is approximately 2", Describe(m1));
  2426. EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
  2427. Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
  2428. EXPECT_EQ("is approximately 0.5", Describe(m2));
  2429. EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
  2430. Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
  2431. EXPECT_EQ("is NaN", Describe(m3));
  2432. EXPECT_EQ("isn't NaN", DescribeNegation(m3));
  2433. }
  2434. // Instantiate FloatingPointTest for testing floats with a user-specified
  2435. // max absolute error.
  2436. typedef FloatingPointNearTest<float> FloatNearTest;
  2437. TEST_F(FloatNearTest, FloatNearMatches) {
  2438. TestNearMatches(&FloatNear);
  2439. }
  2440. TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
  2441. TestNearMatches(&NanSensitiveFloatNear);
  2442. }
  2443. TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
  2444. Matcher<float> m1 = FloatNear(2.0f, 0.5f);
  2445. EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
  2446. EXPECT_EQ(
  2447. "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
  2448. Matcher<float> m2 = FloatNear(0.5f, 0.5f);
  2449. EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
  2450. EXPECT_EQ(
  2451. "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
  2452. Matcher<float> m3 = FloatNear(nan1_, 0.0);
  2453. EXPECT_EQ("never matches", Describe(m3));
  2454. EXPECT_EQ("is anything", DescribeNegation(m3));
  2455. }
  2456. TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
  2457. Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
  2458. EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
  2459. EXPECT_EQ(
  2460. "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
  2461. Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
  2462. EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
  2463. EXPECT_EQ(
  2464. "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
  2465. Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
  2466. EXPECT_EQ("is NaN", Describe(m3));
  2467. EXPECT_EQ("isn't NaN", DescribeNegation(m3));
  2468. }
  2469. TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
  2470. // FloatNear never matches NaN.
  2471. Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
  2472. EXPECT_FALSE(m.Matches(nan1_));
  2473. EXPECT_FALSE(m.Matches(nan2_));
  2474. EXPECT_FALSE(m.Matches(1.0));
  2475. }
  2476. TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
  2477. // NanSensitiveFloatNear will match NaN.
  2478. Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
  2479. EXPECT_TRUE(m.Matches(nan1_));
  2480. EXPECT_TRUE(m.Matches(nan2_));
  2481. EXPECT_FALSE(m.Matches(1.0));
  2482. }
  2483. // Instantiate FloatingPointTest for testing doubles.
  2484. typedef FloatingPointTest<double> DoubleTest;
  2485. TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
  2486. TestMatches(&DoubleEq);
  2487. }
  2488. TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
  2489. TestMatches(&NanSensitiveDoubleEq);
  2490. }
  2491. TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
  2492. // DoubleEq never matches NaN.
  2493. Matcher<double> m = DoubleEq(nan1_);
  2494. EXPECT_FALSE(m.Matches(nan1_));
  2495. EXPECT_FALSE(m.Matches(nan2_));
  2496. EXPECT_FALSE(m.Matches(1.0));
  2497. }
  2498. TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
  2499. // NanSensitiveDoubleEq will match NaN.
  2500. Matcher<double> m = NanSensitiveDoubleEq(nan1_);
  2501. EXPECT_TRUE(m.Matches(nan1_));
  2502. EXPECT_TRUE(m.Matches(nan2_));
  2503. EXPECT_FALSE(m.Matches(1.0));
  2504. }
  2505. TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
  2506. Matcher<double> m1 = DoubleEq(2.0);
  2507. EXPECT_EQ("is approximately 2", Describe(m1));
  2508. EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
  2509. Matcher<double> m2 = DoubleEq(0.5);
  2510. EXPECT_EQ("is approximately 0.5", Describe(m2));
  2511. EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
  2512. Matcher<double> m3 = DoubleEq(nan1_);
  2513. EXPECT_EQ("never matches", Describe(m3));
  2514. EXPECT_EQ("is anything", DescribeNegation(m3));
  2515. }
  2516. TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
  2517. Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
  2518. EXPECT_EQ("is approximately 2", Describe(m1));
  2519. EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
  2520. Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
  2521. EXPECT_EQ("is approximately 0.5", Describe(m2));
  2522. EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
  2523. Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
  2524. EXPECT_EQ("is NaN", Describe(m3));
  2525. EXPECT_EQ("isn't NaN", DescribeNegation(m3));
  2526. }
  2527. // Instantiate FloatingPointTest for testing floats with a user-specified
  2528. // max absolute error.
  2529. typedef FloatingPointNearTest<double> DoubleNearTest;
  2530. TEST_F(DoubleNearTest, DoubleNearMatches) {
  2531. TestNearMatches(&DoubleNear);
  2532. }
  2533. TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
  2534. TestNearMatches(&NanSensitiveDoubleNear);
  2535. }
  2536. TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
  2537. Matcher<double> m1 = DoubleNear(2.0, 0.5);
  2538. EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
  2539. EXPECT_EQ(
  2540. "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
  2541. Matcher<double> m2 = DoubleNear(0.5, 0.5);
  2542. EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
  2543. EXPECT_EQ(
  2544. "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
  2545. Matcher<double> m3 = DoubleNear(nan1_, 0.0);
  2546. EXPECT_EQ("never matches", Describe(m3));
  2547. EXPECT_EQ("is anything", DescribeNegation(m3));
  2548. }
  2549. TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
  2550. Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
  2551. EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
  2552. EXPECT_EQ(
  2553. "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
  2554. Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
  2555. EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
  2556. EXPECT_EQ(
  2557. "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
  2558. Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
  2559. EXPECT_EQ("is NaN", Describe(m3));
  2560. EXPECT_EQ("isn't NaN", DescribeNegation(m3));
  2561. }
  2562. TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
  2563. // DoubleNear never matches NaN.
  2564. Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
  2565. EXPECT_FALSE(m.Matches(nan1_));
  2566. EXPECT_FALSE(m.Matches(nan2_));
  2567. EXPECT_FALSE(m.Matches(1.0));
  2568. }
  2569. TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
  2570. // NanSensitiveDoubleNear will match NaN.
  2571. Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
  2572. EXPECT_TRUE(m.Matches(nan1_));
  2573. EXPECT_TRUE(m.Matches(nan2_));
  2574. EXPECT_FALSE(m.Matches(1.0));
  2575. }
  2576. TEST(PointeeTest, RawPointer) {
  2577. const Matcher<int*> m = Pointee(Ge(0));
  2578. int n = 1;
  2579. EXPECT_TRUE(m.Matches(&n));
  2580. n = -1;
  2581. EXPECT_FALSE(m.Matches(&n));
  2582. EXPECT_FALSE(m.Matches(NULL));
  2583. }
  2584. TEST(PointeeTest, RawPointerToConst) {
  2585. const Matcher<const double*> m = Pointee(Ge(0));
  2586. double x = 1;
  2587. EXPECT_TRUE(m.Matches(&x));
  2588. x = -1;
  2589. EXPECT_FALSE(m.Matches(&x));
  2590. EXPECT_FALSE(m.Matches(NULL));
  2591. }
  2592. TEST(PointeeTest, ReferenceToConstRawPointer) {
  2593. const Matcher<int* const &> m = Pointee(Ge(0));
  2594. int n = 1;
  2595. EXPECT_TRUE(m.Matches(&n));
  2596. n = -1;
  2597. EXPECT_FALSE(m.Matches(&n));
  2598. EXPECT_FALSE(m.Matches(NULL));
  2599. }
  2600. TEST(PointeeTest, ReferenceToNonConstRawPointer) {
  2601. const Matcher<double* &> m = Pointee(Ge(0));
  2602. double x = 1.0;
  2603. double* p = &x;
  2604. EXPECT_TRUE(m.Matches(p));
  2605. x = -1;
  2606. EXPECT_FALSE(m.Matches(p));
  2607. p = NULL;
  2608. EXPECT_FALSE(m.Matches(p));
  2609. }
  2610. // Minimal const-propagating pointer.
  2611. template <typename T>
  2612. class ConstPropagatingPtr {
  2613. public:
  2614. typedef T element_type;
  2615. ConstPropagatingPtr() : val_() {}
  2616. explicit ConstPropagatingPtr(T* t) : val_(t) {}
  2617. ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
  2618. T* get() { return val_; }
  2619. T& operator*() { return *val_; }
  2620. // Most smart pointers return non-const T* and T& from the next methods.
  2621. const T* get() const { return val_; }
  2622. const T& operator*() const { return *val_; }
  2623. private:
  2624. T* val_;
  2625. };
  2626. TEST(PointeeTest, WorksWithConstPropagatingPointers) {
  2627. const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
  2628. int three = 3;
  2629. const ConstPropagatingPtr<int> co(&three);
  2630. ConstPropagatingPtr<int> o(&three);
  2631. EXPECT_TRUE(m.Matches(o));
  2632. EXPECT_TRUE(m.Matches(co));
  2633. *o = 6;
  2634. EXPECT_FALSE(m.Matches(o));
  2635. EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
  2636. }
  2637. TEST(PointeeTest, NeverMatchesNull) {
  2638. const Matcher<const char*> m = Pointee(_);
  2639. EXPECT_FALSE(m.Matches(NULL));
  2640. }
  2641. // Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
  2642. TEST(PointeeTest, MatchesAgainstAValue) {
  2643. const Matcher<int*> m = Pointee(5);
  2644. int n = 5;
  2645. EXPECT_TRUE(m.Matches(&n));
  2646. n = -1;
  2647. EXPECT_FALSE(m.Matches(&n));
  2648. EXPECT_FALSE(m.Matches(NULL));
  2649. }
  2650. TEST(PointeeTest, CanDescribeSelf) {
  2651. const Matcher<int*> m = Pointee(Gt(3));
  2652. EXPECT_EQ("points to a value that is > 3", Describe(m));
  2653. EXPECT_EQ("does not point to a value that is > 3",
  2654. DescribeNegation(m));
  2655. }
  2656. TEST(PointeeTest, CanExplainMatchResult) {
  2657. const Matcher<const string*> m = Pointee(StartsWith("Hi"));
  2658. EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL)));
  2659. const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
  2660. long n = 3; // NOLINT
  2661. EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
  2662. Explain(m2, &n));
  2663. }
  2664. TEST(PointeeTest, AlwaysExplainsPointee) {
  2665. const Matcher<int*> m = Pointee(0);
  2666. int n = 42;
  2667. EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
  2668. }
  2669. // An uncopyable class.
  2670. class Uncopyable {
  2671. public:
  2672. explicit Uncopyable(int a_value) : value_(a_value) {}
  2673. int value() const { return value_; }
  2674. private:
  2675. const int value_;
  2676. GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
  2677. };
  2678. // Returns true iff x.value() is positive.
  2679. bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
  2680. // A user-defined struct for testing Field().
  2681. struct AStruct {
  2682. AStruct() : x(0), y(1.0), z(5), p(NULL) {}
  2683. AStruct(const AStruct& rhs)
  2684. : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
  2685. int x; // A non-const field.
  2686. const double y; // A const field.
  2687. Uncopyable z; // An uncopyable field.
  2688. const char* p; // A pointer field.
  2689. private:
  2690. GTEST_DISALLOW_ASSIGN_(AStruct);
  2691. };
  2692. // A derived struct for testing Field().
  2693. struct DerivedStruct : public AStruct {
  2694. char ch;
  2695. private:
  2696. GTEST_DISALLOW_ASSIGN_(DerivedStruct);
  2697. };
  2698. // Tests that Field(&Foo::field, ...) works when field is non-const.
  2699. TEST(FieldTest, WorksForNonConstField) {
  2700. Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
  2701. AStruct a;
  2702. EXPECT_TRUE(m.Matches(a));
  2703. a.x = -1;
  2704. EXPECT_FALSE(m.Matches(a));
  2705. }
  2706. // Tests that Field(&Foo::field, ...) works when field is const.
  2707. TEST(FieldTest, WorksForConstField) {
  2708. AStruct a;
  2709. Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
  2710. EXPECT_TRUE(m.Matches(a));
  2711. m = Field(&AStruct::y, Le(0.0));
  2712. EXPECT_FALSE(m.Matches(a));
  2713. }
  2714. // Tests that Field(&Foo::field, ...) works when field is not copyable.
  2715. TEST(FieldTest, WorksForUncopyableField) {
  2716. AStruct a;
  2717. Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
  2718. EXPECT_TRUE(m.Matches(a));
  2719. m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
  2720. EXPECT_FALSE(m.Matches(a));
  2721. }
  2722. // Tests that Field(&Foo::field, ...) works when field is a pointer.
  2723. TEST(FieldTest, WorksForPointerField) {
  2724. // Matching against NULL.
  2725. Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
  2726. AStruct a;
  2727. EXPECT_TRUE(m.Matches(a));
  2728. a.p = "hi";
  2729. EXPECT_FALSE(m.Matches(a));
  2730. // Matching a pointer that is not NULL.
  2731. m = Field(&AStruct::p, StartsWith("hi"));
  2732. a.p = "hill";
  2733. EXPECT_TRUE(m.Matches(a));
  2734. a.p = "hole";
  2735. EXPECT_FALSE(m.Matches(a));
  2736. }
  2737. // Tests that Field() works when the object is passed by reference.
  2738. TEST(FieldTest, WorksForByRefArgument) {
  2739. Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
  2740. AStruct a;
  2741. EXPECT_TRUE(m.Matches(a));
  2742. a.x = -1;
  2743. EXPECT_FALSE(m.Matches(a));
  2744. }
  2745. // Tests that Field(&Foo::field, ...) works when the argument's type
  2746. // is a sub-type of Foo.
  2747. TEST(FieldTest, WorksForArgumentOfSubType) {
  2748. // Note that the matcher expects DerivedStruct but we say AStruct
  2749. // inside Field().
  2750. Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
  2751. DerivedStruct d;
  2752. EXPECT_TRUE(m.Matches(d));
  2753. d.x = -1;
  2754. EXPECT_FALSE(m.Matches(d));
  2755. }
  2756. // Tests that Field(&Foo::field, m) works when field's type and m's
  2757. // argument type are compatible but not the same.
  2758. TEST(FieldTest, WorksForCompatibleMatcherType) {
  2759. // The field is an int, but the inner matcher expects a signed char.
  2760. Matcher<const AStruct&> m = Field(&AStruct::x,
  2761. Matcher<signed char>(Ge(0)));
  2762. AStruct a;
  2763. EXPECT_TRUE(m.Matches(a));
  2764. a.x = -1;
  2765. EXPECT_FALSE(m.Matches(a));
  2766. }
  2767. // Tests that Field() can describe itself.
  2768. TEST(FieldTest, CanDescribeSelf) {
  2769. Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
  2770. EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
  2771. EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
  2772. }
  2773. // Tests that Field() can explain the match result.
  2774. TEST(FieldTest, CanExplainMatchResult) {
  2775. Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
  2776. AStruct a;
  2777. a.x = 1;
  2778. EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
  2779. m = Field(&AStruct::x, GreaterThan(0));
  2780. EXPECT_EQ(
  2781. "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
  2782. Explain(m, a));
  2783. }
  2784. // Tests that Field() works when the argument is a pointer to const.
  2785. TEST(FieldForPointerTest, WorksForPointerToConst) {
  2786. Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
  2787. AStruct a;
  2788. EXPECT_TRUE(m.Matches(&a));
  2789. a.x = -1;
  2790. EXPECT_FALSE(m.Matches(&a));
  2791. }
  2792. // Tests that Field() works when the argument is a pointer to non-const.
  2793. TEST(FieldForPointerTest, WorksForPointerToNonConst) {
  2794. Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
  2795. AStruct a;
  2796. EXPECT_TRUE(m.Matches(&a));
  2797. a.x = -1;
  2798. EXPECT_FALSE(m.Matches(&a));
  2799. }
  2800. // Tests that Field() works when the argument is a reference to a const pointer.
  2801. TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
  2802. Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
  2803. AStruct a;
  2804. EXPECT_TRUE(m.Matches(&a));
  2805. a.x = -1;
  2806. EXPECT_FALSE(m.Matches(&a));
  2807. }
  2808. // Tests that Field() does not match the NULL pointer.
  2809. TEST(FieldForPointerTest, DoesNotMatchNull) {
  2810. Matcher<const AStruct*> m = Field(&AStruct::x, _);
  2811. EXPECT_FALSE(m.Matches(NULL));
  2812. }
  2813. // Tests that Field(&Foo::field, ...) works when the argument's type
  2814. // is a sub-type of const Foo*.
  2815. TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
  2816. // Note that the matcher expects DerivedStruct but we say AStruct
  2817. // inside Field().
  2818. Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
  2819. DerivedStruct d;
  2820. EXPECT_TRUE(m.Matches(&d));
  2821. d.x = -1;
  2822. EXPECT_FALSE(m.Matches(&d));
  2823. }
  2824. // Tests that Field() can describe itself when used to match a pointer.
  2825. TEST(FieldForPointerTest, CanDescribeSelf) {
  2826. Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
  2827. EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
  2828. EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
  2829. }
  2830. // Tests that Field() can explain the result of matching a pointer.
  2831. TEST(FieldForPointerTest, CanExplainMatchResult) {
  2832. Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
  2833. AStruct a;
  2834. a.x = 1;
  2835. EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
  2836. EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
  2837. Explain(m, &a));
  2838. m = Field(&AStruct::x, GreaterThan(0));
  2839. EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
  2840. ", which is 1 more than 0", Explain(m, &a));
  2841. }
  2842. // A user-defined class for testing Property().
  2843. class AClass {
  2844. public:
  2845. AClass() : n_(0) {}
  2846. // A getter that returns a non-reference.
  2847. int n() const { return n_; }
  2848. void set_n(int new_n) { n_ = new_n; }
  2849. // A getter that returns a reference to const.
  2850. const string& s() const { return s_; }
  2851. void set_s(const string& new_s) { s_ = new_s; }
  2852. // A getter that returns a reference to non-const.
  2853. double& x() const { return x_; }
  2854. private:
  2855. int n_;
  2856. string s_;
  2857. static double x_;
  2858. };
  2859. double AClass::x_ = 0.0;
  2860. // A derived class for testing Property().
  2861. class DerivedClass : public AClass {
  2862. private:
  2863. int k_;
  2864. };
  2865. // Tests that Property(&Foo::property, ...) works when property()
  2866. // returns a non-reference.
  2867. TEST(PropertyTest, WorksForNonReferenceProperty) {
  2868. Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
  2869. AClass a;
  2870. a.set_n(1);
  2871. EXPECT_TRUE(m.Matches(a));
  2872. a.set_n(-1);
  2873. EXPECT_FALSE(m.Matches(a));
  2874. }
  2875. // Tests that Property(&Foo::property, ...) works when property()
  2876. // returns a reference to const.
  2877. TEST(PropertyTest, WorksForReferenceToConstProperty) {
  2878. Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
  2879. AClass a;
  2880. a.set_s("hill");
  2881. EXPECT_TRUE(m.Matches(a));
  2882. a.set_s("hole");
  2883. EXPECT_FALSE(m.Matches(a));
  2884. }
  2885. // Tests that Property(&Foo::property, ...) works when property()
  2886. // returns a reference to non-const.
  2887. TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
  2888. double x = 0.0;
  2889. AClass a;
  2890. Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
  2891. EXPECT_FALSE(m.Matches(a));
  2892. m = Property(&AClass::x, Not(Ref(x)));
  2893. EXPECT_TRUE(m.Matches(a));
  2894. }
  2895. // Tests that Property(&Foo::property, ...) works when the argument is
  2896. // passed by value.
  2897. TEST(PropertyTest, WorksForByValueArgument) {
  2898. Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
  2899. AClass a;
  2900. a.set_s("hill");
  2901. EXPECT_TRUE(m.Matches(a));
  2902. a.set_s("hole");
  2903. EXPECT_FALSE(m.Matches(a));
  2904. }
  2905. // Tests that Property(&Foo::property, ...) works when the argument's
  2906. // type is a sub-type of Foo.
  2907. TEST(PropertyTest, WorksForArgumentOfSubType) {
  2908. // The matcher expects a DerivedClass, but inside the Property() we
  2909. // say AClass.
  2910. Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
  2911. DerivedClass d;
  2912. d.set_n(1);
  2913. EXPECT_TRUE(m.Matches(d));
  2914. d.set_n(-1);
  2915. EXPECT_FALSE(m.Matches(d));
  2916. }
  2917. // Tests that Property(&Foo::property, m) works when property()'s type
  2918. // and m's argument type are compatible but different.
  2919. TEST(PropertyTest, WorksForCompatibleMatcherType) {
  2920. // n() returns an int but the inner matcher expects a signed char.
  2921. Matcher<const AClass&> m = Property(&AClass::n,
  2922. Matcher<signed char>(Ge(0)));
  2923. AClass a;
  2924. EXPECT_TRUE(m.Matches(a));
  2925. a.set_n(-1);
  2926. EXPECT_FALSE(m.Matches(a));
  2927. }
  2928. // Tests that Property() can describe itself.
  2929. TEST(PropertyTest, CanDescribeSelf) {
  2930. Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
  2931. EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
  2932. EXPECT_EQ("is an object whose given property isn't >= 0",
  2933. DescribeNegation(m));
  2934. }
  2935. // Tests that Property() can explain the match result.
  2936. TEST(PropertyTest, CanExplainMatchResult) {
  2937. Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
  2938. AClass a;
  2939. a.set_n(1);
  2940. EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
  2941. m = Property(&AClass::n, GreaterThan(0));
  2942. EXPECT_EQ(
  2943. "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
  2944. Explain(m, a));
  2945. }
  2946. // Tests that Property() works when the argument is a pointer to const.
  2947. TEST(PropertyForPointerTest, WorksForPointerToConst) {
  2948. Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
  2949. AClass a;
  2950. a.set_n(1);
  2951. EXPECT_TRUE(m.Matches(&a));
  2952. a.set_n(-1);
  2953. EXPECT_FALSE(m.Matches(&a));
  2954. }
  2955. // Tests that Property() works when the argument is a pointer to non-const.
  2956. TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
  2957. Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
  2958. AClass a;
  2959. a.set_s("hill");
  2960. EXPECT_TRUE(m.Matches(&a));
  2961. a.set_s("hole");
  2962. EXPECT_FALSE(m.Matches(&a));
  2963. }
  2964. // Tests that Property() works when the argument is a reference to a
  2965. // const pointer.
  2966. TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
  2967. Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
  2968. AClass a;
  2969. a.set_s("hill");
  2970. EXPECT_TRUE(m.Matches(&a));
  2971. a.set_s("hole");
  2972. EXPECT_FALSE(m.Matches(&a));
  2973. }
  2974. // Tests that Property() does not match the NULL pointer.
  2975. TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
  2976. Matcher<const AClass*> m = Property(&AClass::x, _);
  2977. EXPECT_FALSE(m.Matches(NULL));
  2978. }
  2979. // Tests that Property(&Foo::property, ...) works when the argument's
  2980. // type is a sub-type of const Foo*.
  2981. TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
  2982. // The matcher expects a DerivedClass, but inside the Property() we
  2983. // say AClass.
  2984. Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
  2985. DerivedClass d;
  2986. d.set_n(1);
  2987. EXPECT_TRUE(m.Matches(&d));
  2988. d.set_n(-1);
  2989. EXPECT_FALSE(m.Matches(&d));
  2990. }
  2991. // Tests that Property() can describe itself when used to match a pointer.
  2992. TEST(PropertyForPointerTest, CanDescribeSelf) {
  2993. Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
  2994. EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
  2995. EXPECT_EQ("is an object whose given property isn't >= 0",
  2996. DescribeNegation(m));
  2997. }
  2998. // Tests that Property() can explain the result of matching a pointer.
  2999. TEST(PropertyForPointerTest, CanExplainMatchResult) {
  3000. Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
  3001. AClass a;
  3002. a.set_n(1);
  3003. EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
  3004. EXPECT_EQ(
  3005. "which points to an object whose given property is 1" + OfType("int"),
  3006. Explain(m, &a));
  3007. m = Property(&AClass::n, GreaterThan(0));
  3008. EXPECT_EQ("which points to an object whose given property is 1" +
  3009. OfType("int") + ", which is 1 more than 0",
  3010. Explain(m, &a));
  3011. }
  3012. // Tests ResultOf.
  3013. // Tests that ResultOf(f, ...) compiles and works as expected when f is a
  3014. // function pointer.
  3015. string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; }
  3016. TEST(ResultOfTest, WorksForFunctionPointers) {
  3017. Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo")));
  3018. EXPECT_TRUE(matcher.Matches(1));
  3019. EXPECT_FALSE(matcher.Matches(2));
  3020. }
  3021. // Tests that ResultOf() can describe itself.
  3022. TEST(ResultOfTest, CanDescribeItself) {
  3023. Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
  3024. EXPECT_EQ("is mapped by the given callable to a value that "
  3025. "is equal to \"foo\"", Describe(matcher));
  3026. EXPECT_EQ("is mapped by the given callable to a value that "
  3027. "isn't equal to \"foo\"", DescribeNegation(matcher));
  3028. }
  3029. // Tests that ResultOf() can explain the match result.
  3030. int IntFunction(int input) { return input == 42 ? 80 : 90; }
  3031. TEST(ResultOfTest, CanExplainMatchResult) {
  3032. Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
  3033. EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
  3034. Explain(matcher, 36));
  3035. matcher = ResultOf(&IntFunction, GreaterThan(85));
  3036. EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
  3037. ", which is 5 more than 85", Explain(matcher, 36));
  3038. }
  3039. // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
  3040. // returns a non-reference.
  3041. TEST(ResultOfTest, WorksForNonReferenceResults) {
  3042. Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
  3043. EXPECT_TRUE(matcher.Matches(42));
  3044. EXPECT_FALSE(matcher.Matches(36));
  3045. }
  3046. // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
  3047. // returns a reference to non-const.
  3048. double& DoubleFunction(double& input) { return input; } // NOLINT
  3049. Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
  3050. return obj;
  3051. }
  3052. TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
  3053. double x = 3.14;
  3054. double x2 = x;
  3055. Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
  3056. EXPECT_TRUE(matcher.Matches(x));
  3057. EXPECT_FALSE(matcher.Matches(x2));
  3058. // Test that ResultOf works with uncopyable objects
  3059. Uncopyable obj(0);
  3060. Uncopyable obj2(0);
  3061. Matcher<Uncopyable&> matcher2 =
  3062. ResultOf(&RefUncopyableFunction, Ref(obj));
  3063. EXPECT_TRUE(matcher2.Matches(obj));
  3064. EXPECT_FALSE(matcher2.Matches(obj2));
  3065. }
  3066. // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
  3067. // returns a reference to const.
  3068. const string& StringFunction(const string& input) { return input; }
  3069. TEST(ResultOfTest, WorksForReferenceToConstResults) {
  3070. string s = "foo";
  3071. string s2 = s;
  3072. Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s));
  3073. EXPECT_TRUE(matcher.Matches(s));
  3074. EXPECT_FALSE(matcher.Matches(s2));
  3075. }
  3076. // Tests that ResultOf(f, m) works when f(x) and m's
  3077. // argument types are compatible but different.
  3078. TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
  3079. // IntFunction() returns int but the inner matcher expects a signed char.
  3080. Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
  3081. EXPECT_TRUE(matcher.Matches(36));
  3082. EXPECT_FALSE(matcher.Matches(42));
  3083. }
  3084. // Tests that the program aborts when ResultOf is passed
  3085. // a NULL function pointer.
  3086. TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
  3087. EXPECT_DEATH_IF_SUPPORTED(
  3088. ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))),
  3089. "NULL function pointer is passed into ResultOf\\(\\)\\.");
  3090. }
  3091. // Tests that ResultOf(f, ...) compiles and works as expected when f is a
  3092. // function reference.
  3093. TEST(ResultOfTest, WorksForFunctionReferences) {
  3094. Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
  3095. EXPECT_TRUE(matcher.Matches(1));
  3096. EXPECT_FALSE(matcher.Matches(2));
  3097. }
  3098. // Tests that ResultOf(f, ...) compiles and works as expected when f is a
  3099. // function object.
  3100. struct Functor : public ::std::unary_function<int, string> {
  3101. result_type operator()(argument_type input) const {
  3102. return IntToStringFunction(input);
  3103. }
  3104. };
  3105. TEST(ResultOfTest, WorksForFunctors) {
  3106. Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo")));
  3107. EXPECT_TRUE(matcher.Matches(1));
  3108. EXPECT_FALSE(matcher.Matches(2));
  3109. }
  3110. // Tests that ResultOf(f, ...) compiles and works as expected when f is a
  3111. // functor with more then one operator() defined. ResultOf() must work
  3112. // for each defined operator().
  3113. struct PolymorphicFunctor {
  3114. typedef int result_type;
  3115. int operator()(int n) { return n; }
  3116. int operator()(const char* s) { return static_cast<int>(strlen(s)); }
  3117. };
  3118. TEST(ResultOfTest, WorksForPolymorphicFunctors) {
  3119. Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
  3120. EXPECT_TRUE(matcher_int.Matches(10));
  3121. EXPECT_FALSE(matcher_int.Matches(2));
  3122. Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
  3123. EXPECT_TRUE(matcher_string.Matches("long string"));
  3124. EXPECT_FALSE(matcher_string.Matches("shrt"));
  3125. }
  3126. const int* ReferencingFunction(const int& n) { return &n; }
  3127. struct ReferencingFunctor {
  3128. typedef const int* result_type;
  3129. result_type operator()(const int& n) { return &n; }
  3130. };
  3131. TEST(ResultOfTest, WorksForReferencingCallables) {
  3132. const int n = 1;
  3133. const int n2 = 1;
  3134. Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
  3135. EXPECT_TRUE(matcher2.Matches(n));
  3136. EXPECT_FALSE(matcher2.Matches(n2));
  3137. Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
  3138. EXPECT_TRUE(matcher3.Matches(n));
  3139. EXPECT_FALSE(matcher3.Matches(n2));
  3140. }
  3141. class DivisibleByImpl {
  3142. public:
  3143. explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
  3144. // For testing using ExplainMatchResultTo() with polymorphic matchers.
  3145. template <typename T>
  3146. bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
  3147. *listener << "which is " << (n % divider_) << " modulo "
  3148. << divider_;
  3149. return (n % divider_) == 0;
  3150. }
  3151. void DescribeTo(ostream* os) const {
  3152. *os << "is divisible by " << divider_;
  3153. }
  3154. void DescribeNegationTo(ostream* os) const {
  3155. *os << "is not divisible by " << divider_;
  3156. }
  3157. void set_divider(int a_divider) { divider_ = a_divider; }
  3158. int divider() const { return divider_; }
  3159. private:
  3160. int divider_;
  3161. };
  3162. PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
  3163. return MakePolymorphicMatcher(DivisibleByImpl(n));
  3164. }
  3165. // Tests that when AllOf() fails, only the first failing matcher is
  3166. // asked to explain why.
  3167. TEST(ExplainMatchResultTest, AllOf_False_False) {
  3168. const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
  3169. EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
  3170. }
  3171. // Tests that when AllOf() fails, only the first failing matcher is
  3172. // asked to explain why.
  3173. TEST(ExplainMatchResultTest, AllOf_False_True) {
  3174. const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
  3175. EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
  3176. }
  3177. // Tests that when AllOf() fails, only the first failing matcher is
  3178. // asked to explain why.
  3179. TEST(ExplainMatchResultTest, AllOf_True_False) {
  3180. const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
  3181. EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
  3182. }
  3183. // Tests that when AllOf() succeeds, all matchers are asked to explain
  3184. // why.
  3185. TEST(ExplainMatchResultTest, AllOf_True_True) {
  3186. const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
  3187. EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
  3188. }
  3189. TEST(ExplainMatchResultTest, AllOf_True_True_2) {
  3190. const Matcher<int> m = AllOf(Ge(2), Le(3));
  3191. EXPECT_EQ("", Explain(m, 2));
  3192. }
  3193. TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
  3194. const Matcher<int> m = GreaterThan(5);
  3195. EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
  3196. }
  3197. // The following two tests verify that values without a public copy
  3198. // ctor can be used as arguments to matchers like Eq(), Ge(), and etc
  3199. // with the help of ByRef().
  3200. class NotCopyable {
  3201. public:
  3202. explicit NotCopyable(int a_value) : value_(a_value) {}
  3203. int value() const { return value_; }
  3204. bool operator==(const NotCopyable& rhs) const {
  3205. return value() == rhs.value();
  3206. }
  3207. bool operator>=(const NotCopyable& rhs) const {
  3208. return value() >= rhs.value();
  3209. }
  3210. private:
  3211. int value_;
  3212. GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
  3213. };
  3214. TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
  3215. const NotCopyable const_value1(1);
  3216. const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
  3217. const NotCopyable n1(1), n2(2);
  3218. EXPECT_TRUE(m.Matches(n1));
  3219. EXPECT_FALSE(m.Matches(n2));
  3220. }
  3221. TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
  3222. NotCopyable value2(2);
  3223. const Matcher<NotCopyable&> m = Ge(ByRef(value2));
  3224. NotCopyable n1(1), n2(2);
  3225. EXPECT_FALSE(m.Matches(n1));
  3226. EXPECT_TRUE(m.Matches(n2));
  3227. }
  3228. TEST(IsEmptyTest, ImplementsIsEmpty) {
  3229. vector<int> container;
  3230. EXPECT_THAT(container, IsEmpty());
  3231. container.push_back(0);
  3232. EXPECT_THAT(container, Not(IsEmpty()));
  3233. container.push_back(1);
  3234. EXPECT_THAT(container, Not(IsEmpty()));
  3235. }
  3236. TEST(IsEmptyTest, WorksWithString) {
  3237. string text;
  3238. EXPECT_THAT(text, IsEmpty());
  3239. text = "foo";
  3240. EXPECT_THAT(text, Not(IsEmpty()));
  3241. text = string("\0", 1);
  3242. EXPECT_THAT(text, Not(IsEmpty()));
  3243. }
  3244. TEST(IsEmptyTest, CanDescribeSelf) {
  3245. Matcher<vector<int> > m = IsEmpty();
  3246. EXPECT_EQ("is empty", Describe(m));
  3247. EXPECT_EQ("isn't empty", DescribeNegation(m));
  3248. }
  3249. TEST(IsEmptyTest, ExplainsResult) {
  3250. Matcher<vector<int> > m = IsEmpty();
  3251. vector<int> container;
  3252. EXPECT_EQ("", Explain(m, container));
  3253. container.push_back(0);
  3254. EXPECT_EQ("whose size is 1", Explain(m, container));
  3255. }
  3256. TEST(SizeIsTest, ImplementsSizeIs) {
  3257. vector<int> container;
  3258. EXPECT_THAT(container, SizeIs(0));
  3259. EXPECT_THAT(container, Not(SizeIs(1)));
  3260. container.push_back(0);
  3261. EXPECT_THAT(container, Not(SizeIs(0)));
  3262. EXPECT_THAT(container, SizeIs(1));
  3263. container.push_back(0);
  3264. EXPECT_THAT(container, Not(SizeIs(0)));
  3265. EXPECT_THAT(container, SizeIs(2));
  3266. }
  3267. TEST(SizeIsTest, WorksWithMap) {
  3268. map<string, int> container;
  3269. EXPECT_THAT(container, SizeIs(0));
  3270. EXPECT_THAT(container, Not(SizeIs(1)));
  3271. container.insert(make_pair("foo", 1));
  3272. EXPECT_THAT(container, Not(SizeIs(0)));
  3273. EXPECT_THAT(container, SizeIs(1));
  3274. container.insert(make_pair("bar", 2));
  3275. EXPECT_THAT(container, Not(SizeIs(0)));
  3276. EXPECT_THAT(container, SizeIs(2));
  3277. }
  3278. TEST(SizeIsTest, WorksWithReferences) {
  3279. vector<int> container;
  3280. Matcher<const vector<int>&> m = SizeIs(1);
  3281. EXPECT_THAT(container, Not(m));
  3282. container.push_back(0);
  3283. EXPECT_THAT(container, m);
  3284. }
  3285. TEST(SizeIsTest, CanDescribeSelf) {
  3286. Matcher<vector<int> > m = SizeIs(2);
  3287. EXPECT_EQ("size is equal to 2", Describe(m));
  3288. EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
  3289. }
  3290. TEST(SizeIsTest, ExplainsResult) {
  3291. Matcher<vector<int> > m1 = SizeIs(2);
  3292. Matcher<vector<int> > m2 = SizeIs(Lt(2u));
  3293. Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
  3294. Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
  3295. vector<int> container;
  3296. EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
  3297. EXPECT_EQ("whose size 0 matches", Explain(m2, container));
  3298. EXPECT_EQ("whose size 0 matches", Explain(m3, container));
  3299. EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
  3300. Explain(m4, container));
  3301. container.push_back(0);
  3302. container.push_back(0);
  3303. EXPECT_EQ("whose size 2 matches", Explain(m1, container));
  3304. EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
  3305. EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
  3306. EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
  3307. Explain(m4, container));
  3308. }
  3309. #if GTEST_HAS_TYPED_TEST
  3310. // Tests ContainerEq with different container types, and
  3311. // different element types.
  3312. template <typename T>
  3313. class ContainerEqTest : public testing::Test {};
  3314. typedef testing::Types<
  3315. set<int>,
  3316. vector<size_t>,
  3317. multiset<size_t>,
  3318. list<int> >
  3319. ContainerEqTestTypes;
  3320. TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
  3321. // Tests that the filled container is equal to itself.
  3322. TYPED_TEST(ContainerEqTest, EqualsSelf) {
  3323. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3324. TypeParam my_set(vals, vals + 6);
  3325. const Matcher<TypeParam> m = ContainerEq(my_set);
  3326. EXPECT_TRUE(m.Matches(my_set));
  3327. EXPECT_EQ("", Explain(m, my_set));
  3328. }
  3329. // Tests that missing values are reported.
  3330. TYPED_TEST(ContainerEqTest, ValueMissing) {
  3331. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3332. static const int test_vals[] = {2, 1, 8, 5};
  3333. TypeParam my_set(vals, vals + 6);
  3334. TypeParam test_set(test_vals, test_vals + 4);
  3335. const Matcher<TypeParam> m = ContainerEq(my_set);
  3336. EXPECT_FALSE(m.Matches(test_set));
  3337. EXPECT_EQ("which doesn't have these expected elements: 3",
  3338. Explain(m, test_set));
  3339. }
  3340. // Tests that added values are reported.
  3341. TYPED_TEST(ContainerEqTest, ValueAdded) {
  3342. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3343. static const int test_vals[] = {1, 2, 3, 5, 8, 46};
  3344. TypeParam my_set(vals, vals + 6);
  3345. TypeParam test_set(test_vals, test_vals + 6);
  3346. const Matcher<const TypeParam&> m = ContainerEq(my_set);
  3347. EXPECT_FALSE(m.Matches(test_set));
  3348. EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
  3349. }
  3350. // Tests that added and missing values are reported together.
  3351. TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
  3352. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3353. static const int test_vals[] = {1, 2, 3, 8, 46};
  3354. TypeParam my_set(vals, vals + 6);
  3355. TypeParam test_set(test_vals, test_vals + 5);
  3356. const Matcher<TypeParam> m = ContainerEq(my_set);
  3357. EXPECT_FALSE(m.Matches(test_set));
  3358. EXPECT_EQ("which has these unexpected elements: 46,\n"
  3359. "and doesn't have these expected elements: 5",
  3360. Explain(m, test_set));
  3361. }
  3362. // Tests duplicated value -- expect no explanation.
  3363. TYPED_TEST(ContainerEqTest, DuplicateDifference) {
  3364. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3365. static const int test_vals[] = {1, 2, 3, 5, 8};
  3366. TypeParam my_set(vals, vals + 6);
  3367. TypeParam test_set(test_vals, test_vals + 5);
  3368. const Matcher<const TypeParam&> m = ContainerEq(my_set);
  3369. // Depending on the container, match may be true or false
  3370. // But in any case there should be no explanation.
  3371. EXPECT_EQ("", Explain(m, test_set));
  3372. }
  3373. #endif // GTEST_HAS_TYPED_TEST
  3374. // Tests that mutliple missing values are reported.
  3375. // Using just vector here, so order is predicatble.
  3376. TEST(ContainerEqExtraTest, MultipleValuesMissing) {
  3377. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3378. static const int test_vals[] = {2, 1, 5};
  3379. vector<int> my_set(vals, vals + 6);
  3380. vector<int> test_set(test_vals, test_vals + 3);
  3381. const Matcher<vector<int> > m = ContainerEq(my_set);
  3382. EXPECT_FALSE(m.Matches(test_set));
  3383. EXPECT_EQ("which doesn't have these expected elements: 3, 8",
  3384. Explain(m, test_set));
  3385. }
  3386. // Tests that added values are reported.
  3387. // Using just vector here, so order is predicatble.
  3388. TEST(ContainerEqExtraTest, MultipleValuesAdded) {
  3389. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3390. static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
  3391. list<size_t> my_set(vals, vals + 6);
  3392. list<size_t> test_set(test_vals, test_vals + 7);
  3393. const Matcher<const list<size_t>&> m = ContainerEq(my_set);
  3394. EXPECT_FALSE(m.Matches(test_set));
  3395. EXPECT_EQ("which has these unexpected elements: 92, 46",
  3396. Explain(m, test_set));
  3397. }
  3398. // Tests that added and missing values are reported together.
  3399. TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
  3400. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3401. static const int test_vals[] = {1, 2, 3, 92, 46};
  3402. list<size_t> my_set(vals, vals + 6);
  3403. list<size_t> test_set(test_vals, test_vals + 5);
  3404. const Matcher<const list<size_t> > m = ContainerEq(my_set);
  3405. EXPECT_FALSE(m.Matches(test_set));
  3406. EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
  3407. "and doesn't have these expected elements: 5, 8",
  3408. Explain(m, test_set));
  3409. }
  3410. // Tests to see that duplicate elements are detected,
  3411. // but (as above) not reported in the explanation.
  3412. TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
  3413. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3414. static const int test_vals[] = {1, 2, 3, 5, 8};
  3415. vector<int> my_set(vals, vals + 6);
  3416. vector<int> test_set(test_vals, test_vals + 5);
  3417. const Matcher<vector<int> > m = ContainerEq(my_set);
  3418. EXPECT_TRUE(m.Matches(my_set));
  3419. EXPECT_FALSE(m.Matches(test_set));
  3420. // There is nothing to report when both sets contain all the same values.
  3421. EXPECT_EQ("", Explain(m, test_set));
  3422. }
  3423. // Tests that ContainerEq works for non-trivial associative containers,
  3424. // like maps.
  3425. TEST(ContainerEqExtraTest, WorksForMaps) {
  3426. map<int, std::string> my_map;
  3427. my_map[0] = "a";
  3428. my_map[1] = "b";
  3429. map<int, std::string> test_map;
  3430. test_map[0] = "aa";
  3431. test_map[1] = "b";
  3432. const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
  3433. EXPECT_TRUE(m.Matches(my_map));
  3434. EXPECT_FALSE(m.Matches(test_map));
  3435. EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
  3436. "and doesn't have these expected elements: (0, \"a\")",
  3437. Explain(m, test_map));
  3438. }
  3439. TEST(ContainerEqExtraTest, WorksForNativeArray) {
  3440. int a1[] = { 1, 2, 3 };
  3441. int a2[] = { 1, 2, 3 };
  3442. int b[] = { 1, 2, 4 };
  3443. EXPECT_THAT(a1, ContainerEq(a2));
  3444. EXPECT_THAT(a1, Not(ContainerEq(b)));
  3445. }
  3446. TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
  3447. const char a1[][3] = { "hi", "lo" };
  3448. const char a2[][3] = { "hi", "lo" };
  3449. const char b[][3] = { "lo", "hi" };
  3450. // Tests using ContainerEq() in the first dimension.
  3451. EXPECT_THAT(a1, ContainerEq(a2));
  3452. EXPECT_THAT(a1, Not(ContainerEq(b)));
  3453. // Tests using ContainerEq() in the second dimension.
  3454. EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
  3455. EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
  3456. }
  3457. TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
  3458. const int a1[] = { 1, 2, 3 };
  3459. const int a2[] = { 1, 2, 3 };
  3460. const int b[] = { 1, 2, 3, 4 };
  3461. const int* const p1 = a1;
  3462. EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
  3463. EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
  3464. const int c[] = { 1, 3, 2 };
  3465. EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
  3466. }
  3467. TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
  3468. std::string a1[][3] = {
  3469. { "hi", "hello", "ciao" },
  3470. { "bye", "see you", "ciao" }
  3471. };
  3472. std::string a2[][3] = {
  3473. { "hi", "hello", "ciao" },
  3474. { "bye", "see you", "ciao" }
  3475. };
  3476. const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
  3477. EXPECT_THAT(a1, m);
  3478. a2[0][0] = "ha";
  3479. EXPECT_THAT(a1, m);
  3480. }
  3481. TEST(WhenSortedByTest, WorksForEmptyContainer) {
  3482. const vector<int> numbers;
  3483. EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
  3484. EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
  3485. }
  3486. TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
  3487. vector<unsigned> numbers;
  3488. numbers.push_back(3);
  3489. numbers.push_back(1);
  3490. numbers.push_back(2);
  3491. numbers.push_back(2);
  3492. EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
  3493. ElementsAre(3, 2, 2, 1)));
  3494. EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
  3495. ElementsAre(1, 2, 2, 3))));
  3496. }
  3497. TEST(WhenSortedByTest, WorksForNonVectorContainer) {
  3498. list<string> words;
  3499. words.push_back("say");
  3500. words.push_back("hello");
  3501. words.push_back("world");
  3502. EXPECT_THAT(words, WhenSortedBy(less<string>(),
  3503. ElementsAre("hello", "say", "world")));
  3504. EXPECT_THAT(words, Not(WhenSortedBy(less<string>(),
  3505. ElementsAre("say", "hello", "world"))));
  3506. }
  3507. TEST(WhenSortedByTest, WorksForNativeArray) {
  3508. const int numbers[] = { 1, 3, 2, 4 };
  3509. const int sorted_numbers[] = { 1, 2, 3, 4 };
  3510. EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
  3511. EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
  3512. ElementsAreArray(sorted_numbers)));
  3513. EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
  3514. }
  3515. TEST(WhenSortedByTest, CanDescribeSelf) {
  3516. const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
  3517. EXPECT_EQ("(when sorted) has 2 elements where\n"
  3518. "element #0 is equal to 1,\n"
  3519. "element #1 is equal to 2",
  3520. Describe(m));
  3521. EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
  3522. "element #0 isn't equal to 1, or\n"
  3523. "element #1 isn't equal to 2",
  3524. DescribeNegation(m));
  3525. }
  3526. TEST(WhenSortedByTest, ExplainsMatchResult) {
  3527. const int a[] = { 2, 1 };
  3528. EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
  3529. Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
  3530. EXPECT_EQ("which is { 1, 2 } when sorted",
  3531. Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
  3532. }
  3533. // WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
  3534. // need to test it as exhaustively as we test the latter.
  3535. TEST(WhenSortedTest, WorksForEmptyContainer) {
  3536. const vector<int> numbers;
  3537. EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
  3538. EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
  3539. }
  3540. TEST(WhenSortedTest, WorksForNonEmptyContainer) {
  3541. list<string> words;
  3542. words.push_back("3");
  3543. words.push_back("1");
  3544. words.push_back("2");
  3545. words.push_back("2");
  3546. EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
  3547. EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
  3548. }
  3549. TEST(WhenSortedTest, WorksForMapTypes) {
  3550. map<string, int> word_counts;
  3551. word_counts["and"] = 1;
  3552. word_counts["the"] = 1;
  3553. word_counts["buffalo"] = 2;
  3554. EXPECT_THAT(word_counts, WhenSorted(ElementsAre(
  3555. Pair("and", 1), Pair("buffalo", 2), Pair("the", 1))));
  3556. EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre(
  3557. Pair("and", 1), Pair("the", 1), Pair("buffalo", 2)))));
  3558. }
  3559. TEST(WhenSortedTest, WorksForMultiMapTypes) {
  3560. multimap<int, int> ifib;
  3561. ifib.insert(make_pair(8, 6));
  3562. ifib.insert(make_pair(2, 3));
  3563. ifib.insert(make_pair(1, 1));
  3564. ifib.insert(make_pair(3, 4));
  3565. ifib.insert(make_pair(1, 2));
  3566. ifib.insert(make_pair(5, 5));
  3567. EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
  3568. Pair(1, 2),
  3569. Pair(2, 3),
  3570. Pair(3, 4),
  3571. Pair(5, 5),
  3572. Pair(8, 6))));
  3573. EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
  3574. Pair(2, 3),
  3575. Pair(1, 1),
  3576. Pair(3, 4),
  3577. Pair(1, 2),
  3578. Pair(5, 5)))));
  3579. }
  3580. TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
  3581. std::deque<int> d;
  3582. d.push_back(2);
  3583. d.push_back(1);
  3584. EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
  3585. EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
  3586. }
  3587. TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
  3588. std::deque<int> d;
  3589. d.push_back(2);
  3590. d.push_back(1);
  3591. Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
  3592. EXPECT_THAT(d, WhenSorted(vector_match));
  3593. Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
  3594. EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
  3595. }
  3596. // Deliberately bare pseudo-container.
  3597. // Offers only begin() and end() accessors, yielding InputIterator.
  3598. template <typename T>
  3599. class Streamlike {
  3600. private:
  3601. class ConstIter;
  3602. public:
  3603. typedef ConstIter const_iterator;
  3604. typedef T value_type;
  3605. template <typename InIter>
  3606. Streamlike(InIter first, InIter last) : remainder_(first, last) {}
  3607. const_iterator begin() const {
  3608. return const_iterator(this, remainder_.begin());
  3609. }
  3610. const_iterator end() const {
  3611. return const_iterator(this, remainder_.end());
  3612. }
  3613. private:
  3614. class ConstIter : public std::iterator<std::input_iterator_tag,
  3615. value_type,
  3616. ptrdiff_t,
  3617. const value_type&,
  3618. const value_type*> {
  3619. public:
  3620. ConstIter(const Streamlike* s,
  3621. typename std::list<value_type>::iterator pos)
  3622. : s_(s), pos_(pos) {}
  3623. const value_type& operator*() const { return *pos_; }
  3624. const value_type* operator->() const { return &*pos_; }
  3625. ConstIter& operator++() {
  3626. s_->remainder_.erase(pos_++);
  3627. return *this;
  3628. }
  3629. // *iter++ is required to work (see std::istreambuf_iterator).
  3630. // (void)iter++ is also required to work.
  3631. class PostIncrProxy {
  3632. public:
  3633. explicit PostIncrProxy(const value_type& value) : value_(value) {}
  3634. value_type operator*() const { return value_; }
  3635. private:
  3636. value_type value_;
  3637. };
  3638. PostIncrProxy operator++(int) {
  3639. PostIncrProxy proxy(**this);
  3640. ++(*this);
  3641. return proxy;
  3642. }
  3643. friend bool operator==(const ConstIter& a, const ConstIter& b) {
  3644. return a.s_ == b.s_ && a.pos_ == b.pos_;
  3645. }
  3646. friend bool operator!=(const ConstIter& a, const ConstIter& b) {
  3647. return !(a == b);
  3648. }
  3649. private:
  3650. const Streamlike* s_;
  3651. typename std::list<value_type>::iterator pos_;
  3652. };
  3653. friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
  3654. os << "[";
  3655. typedef typename std::list<value_type>::const_iterator Iter;
  3656. const char* sep = "";
  3657. for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
  3658. os << sep << *it;
  3659. sep = ",";
  3660. }
  3661. os << "]";
  3662. return os;
  3663. }
  3664. mutable std::list<value_type> remainder_; // modified by iteration
  3665. };
  3666. TEST(StreamlikeTest, Iteration) {
  3667. const int a[5] = { 2, 1, 4, 5, 3 };
  3668. Streamlike<int> s(a, a + 5);
  3669. Streamlike<int>::const_iterator it = s.begin();
  3670. const int* ip = a;
  3671. while (it != s.end()) {
  3672. SCOPED_TRACE(ip - a);
  3673. EXPECT_EQ(*ip++, *it++);
  3674. }
  3675. }
  3676. TEST(WhenSortedTest, WorksForStreamlike) {
  3677. // Streamlike 'container' provides only minimal iterator support.
  3678. // Its iterators are tagged with input_iterator_tag.
  3679. const int a[5] = { 2, 1, 4, 5, 3 };
  3680. Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
  3681. EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
  3682. EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
  3683. }
  3684. TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
  3685. const int a[] = { 2, 1, 4, 5, 3 };
  3686. Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
  3687. Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
  3688. EXPECT_THAT(s, WhenSorted(vector_match));
  3689. EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
  3690. }
  3691. // Tests using ElementsAre() and ElementsAreArray() with stream-like
  3692. // "containers".
  3693. TEST(ElemensAreStreamTest, WorksForStreamlike) {
  3694. const int a[5] = { 1, 2, 3, 4, 5 };
  3695. Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
  3696. EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
  3697. EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
  3698. }
  3699. TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
  3700. const int a[5] = { 1, 2, 3, 4, 5 };
  3701. Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
  3702. vector<int> expected;
  3703. expected.push_back(1);
  3704. expected.push_back(2);
  3705. expected.push_back(3);
  3706. expected.push_back(4);
  3707. expected.push_back(5);
  3708. EXPECT_THAT(s, ElementsAreArray(expected));
  3709. expected[3] = 0;
  3710. EXPECT_THAT(s, Not(ElementsAreArray(expected)));
  3711. }
  3712. // Tests for UnorderedElementsAreArray()
  3713. TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
  3714. const int a[] = { 0, 1, 2, 3, 4 };
  3715. std::vector<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
  3716. do {
  3717. StringMatchResultListener listener;
  3718. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
  3719. s, &listener)) << listener.str();
  3720. } while (std::next_permutation(s.begin(), s.end()));
  3721. }
  3722. TEST(UnorderedElementsAreArrayTest, VectorBool) {
  3723. const bool a[] = { 0, 1, 0, 1, 1 };
  3724. const bool b[] = { 1, 0, 1, 1, 0 };
  3725. std::vector<bool> expected(a, a + GMOCK_ARRAY_SIZE_(a));
  3726. std::vector<bool> actual(b, b + GMOCK_ARRAY_SIZE_(b));
  3727. StringMatchResultListener listener;
  3728. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
  3729. actual, &listener)) << listener.str();
  3730. }
  3731. TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
  3732. // Streamlike 'container' provides only minimal iterator support.
  3733. // Its iterators are tagged with input_iterator_tag, and it has no
  3734. // size() or empty() methods.
  3735. const int a[5] = { 2, 1, 4, 5, 3 };
  3736. Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
  3737. ::std::vector<int> expected;
  3738. expected.push_back(1);
  3739. expected.push_back(2);
  3740. expected.push_back(3);
  3741. expected.push_back(4);
  3742. expected.push_back(5);
  3743. EXPECT_THAT(s, UnorderedElementsAreArray(expected));
  3744. expected.push_back(6);
  3745. EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
  3746. }
  3747. #if GTEST_LANG_CXX11
  3748. TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
  3749. const int a[5] = { 2, 1, 4, 5, 3 };
  3750. EXPECT_THAT(a, UnorderedElementsAreArray({ 1, 2, 3, 4, 5 }));
  3751. EXPECT_THAT(a, Not(UnorderedElementsAreArray({ 1, 2, 3, 4, 6 })));
  3752. }
  3753. TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
  3754. const string a[5] = { "a", "b", "c", "d", "e" };
  3755. EXPECT_THAT(a, UnorderedElementsAreArray({ "a", "b", "c", "d", "e" }));
  3756. EXPECT_THAT(a, Not(UnorderedElementsAreArray({ "a", "b", "c", "d", "ef" })));
  3757. }
  3758. TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
  3759. const int a[5] = { 2, 1, 4, 5, 3 };
  3760. EXPECT_THAT(a, UnorderedElementsAreArray(
  3761. { Eq(1), Eq(2), Eq(3), Eq(4), Eq(5) }));
  3762. EXPECT_THAT(a, Not(UnorderedElementsAreArray(
  3763. { Eq(1), Eq(2), Eq(3), Eq(4), Eq(6) })));
  3764. }
  3765. TEST(UnorderedElementsAreArrayTest,
  3766. TakesInitializerListOfDifferentTypedMatchers) {
  3767. const int a[5] = { 2, 1, 4, 5, 3 };
  3768. // The compiler cannot infer the type of the initializer list if its
  3769. // elements have different types. We must explicitly specify the
  3770. // unified element type in this case.
  3771. EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
  3772. { Eq(1), Ne(-2), Ge(3), Le(4), Eq(5) }));
  3773. EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
  3774. { Eq(1), Ne(-2), Ge(3), Le(4), Eq(6) })));
  3775. }
  3776. #endif // GTEST_LANG_CXX11
  3777. class UnorderedElementsAreTest : public testing::Test {
  3778. protected:
  3779. typedef std::vector<int> IntVec;
  3780. };
  3781. TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
  3782. const int a[] = { 1, 2, 3 };
  3783. std::vector<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
  3784. do {
  3785. StringMatchResultListener listener;
  3786. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
  3787. s, &listener)) << listener.str();
  3788. } while (std::next_permutation(s.begin(), s.end()));
  3789. }
  3790. TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
  3791. const int a[] = { 1, 2, 3 };
  3792. std::vector<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
  3793. std::vector<Matcher<int> > mv;
  3794. mv.push_back(1);
  3795. mv.push_back(2);
  3796. mv.push_back(2);
  3797. // The element with value '3' matches nothing: fail fast.
  3798. StringMatchResultListener listener;
  3799. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
  3800. s, &listener)) << listener.str();
  3801. }
  3802. TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
  3803. // Streamlike 'container' provides only minimal iterator support.
  3804. // Its iterators are tagged with input_iterator_tag, and it has no
  3805. // size() or empty() methods.
  3806. const int a[5] = { 2, 1, 4, 5, 3 };
  3807. Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
  3808. EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
  3809. EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
  3810. }
  3811. // One naive implementation of the matcher runs in O(N!) time, which is too
  3812. // slow for many real-world inputs. This test shows that our matcher can match
  3813. // 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
  3814. // iterations and obviously effectively incomputable.
  3815. // [ RUN ] UnorderedElementsAreTest.Performance
  3816. // [ OK ] UnorderedElementsAreTest.Performance (4 ms)
  3817. TEST_F(UnorderedElementsAreTest, Performance) {
  3818. std::vector<int> s;
  3819. std::vector<Matcher<int> > mv;
  3820. for (int i = 0; i < 100; ++i) {
  3821. s.push_back(i);
  3822. mv.push_back(_);
  3823. }
  3824. mv[50] = Eq(0);
  3825. StringMatchResultListener listener;
  3826. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
  3827. s, &listener)) << listener.str();
  3828. }
  3829. // Another variant of 'Performance' with similar expectations.
  3830. // [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
  3831. // [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
  3832. TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
  3833. std::vector<int> s;
  3834. std::vector<Matcher<int> > mv;
  3835. for (int i = 0; i < 100; ++i) {
  3836. s.push_back(i);
  3837. if (i & 1) {
  3838. mv.push_back(_);
  3839. } else {
  3840. mv.push_back(i);
  3841. }
  3842. }
  3843. StringMatchResultListener listener;
  3844. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
  3845. s, &listener)) << listener.str();
  3846. }
  3847. TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
  3848. std::vector<int> v;
  3849. v.push_back(4);
  3850. StringMatchResultListener listener;
  3851. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
  3852. v, &listener)) << listener.str();
  3853. EXPECT_THAT(listener.str(), Eq("which has 1 element"));
  3854. }
  3855. TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
  3856. std::vector<int> v;
  3857. StringMatchResultListener listener;
  3858. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
  3859. v, &listener)) << listener.str();
  3860. EXPECT_THAT(listener.str(), Eq(""));
  3861. }
  3862. TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
  3863. std::vector<int> v;
  3864. v.push_back(1);
  3865. v.push_back(1);
  3866. StringMatchResultListener listener;
  3867. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
  3868. v, &listener)) << listener.str();
  3869. EXPECT_THAT(
  3870. listener.str(),
  3871. Eq("where the following matchers don't match any elements:\n"
  3872. "matcher #1: is equal to 2"));
  3873. }
  3874. TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
  3875. std::vector<int> v;
  3876. v.push_back(1);
  3877. v.push_back(2);
  3878. StringMatchResultListener listener;
  3879. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
  3880. v, &listener)) << listener.str();
  3881. EXPECT_THAT(
  3882. listener.str(),
  3883. Eq("where the following elements don't match any matchers:\n"
  3884. "element #1: 2"));
  3885. }
  3886. TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
  3887. std::vector<int> v;
  3888. v.push_back(2);
  3889. v.push_back(3);
  3890. StringMatchResultListener listener;
  3891. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
  3892. v, &listener)) << listener.str();
  3893. EXPECT_THAT(
  3894. listener.str(),
  3895. Eq("where"
  3896. " the following matchers don't match any elements:\n"
  3897. "matcher #0: is equal to 1\n"
  3898. "and"
  3899. " where"
  3900. " the following elements don't match any matchers:\n"
  3901. "element #1: 3"));
  3902. }
  3903. // Test helper for formatting element, matcher index pairs in expectations.
  3904. static string EMString(int element, int matcher) {
  3905. stringstream ss;
  3906. ss << "(element #" << element << ", matcher #" << matcher << ")";
  3907. return ss.str();
  3908. }
  3909. TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
  3910. // A situation where all elements and matchers have a match
  3911. // associated with them, but the max matching is not perfect.
  3912. std::vector<string> v;
  3913. v.push_back("a");
  3914. v.push_back("b");
  3915. v.push_back("c");
  3916. StringMatchResultListener listener;
  3917. EXPECT_FALSE(ExplainMatchResult(
  3918. UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
  3919. << listener.str();
  3920. string prefix =
  3921. "where no permutation of the elements can satisfy all matchers, "
  3922. "and the closest match is 2 of 3 matchers with the "
  3923. "pairings:\n";
  3924. // We have to be a bit loose here, because there are 4 valid max matches.
  3925. EXPECT_THAT(
  3926. listener.str(),
  3927. AnyOf(prefix + "{\n " + EMString(0, 0) +
  3928. ",\n " + EMString(1, 2) + "\n}",
  3929. prefix + "{\n " + EMString(0, 1) +
  3930. ",\n " + EMString(1, 2) + "\n}",
  3931. prefix + "{\n " + EMString(0, 0) +
  3932. ",\n " + EMString(2, 2) + "\n}",
  3933. prefix + "{\n " + EMString(0, 1) +
  3934. ",\n " + EMString(2, 2) + "\n}"));
  3935. }
  3936. TEST_F(UnorderedElementsAreTest, Describe) {
  3937. EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
  3938. Eq("is empty"));
  3939. EXPECT_THAT(
  3940. Describe<IntVec>(UnorderedElementsAre(345)),
  3941. Eq("has 1 element and that element is equal to 345"));
  3942. EXPECT_THAT(
  3943. Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
  3944. Eq("has 3 elements and there exists some permutation "
  3945. "of elements such that:\n"
  3946. " - element #0 is equal to 111, and\n"
  3947. " - element #1 is equal to 222, and\n"
  3948. " - element #2 is equal to 333"));
  3949. }
  3950. TEST_F(UnorderedElementsAreTest, DescribeNegation) {
  3951. EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
  3952. Eq("isn't empty"));
  3953. EXPECT_THAT(
  3954. DescribeNegation<IntVec>(UnorderedElementsAre(345)),
  3955. Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
  3956. EXPECT_THAT(
  3957. DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
  3958. Eq("doesn't have 3 elements, or there exists no permutation "
  3959. "of elements such that:\n"
  3960. " - element #0 is equal to 123, and\n"
  3961. " - element #1 is equal to 234, and\n"
  3962. " - element #2 is equal to 345"));
  3963. }
  3964. namespace {
  3965. // Used as a check on the more complex max flow method used in the
  3966. // real testing::internal::FindMaxBipartiteMatching. This method is
  3967. // compatible but runs in worst-case factorial time, so we only
  3968. // use it in testing for small problem sizes.
  3969. template <typename Graph>
  3970. class BacktrackingMaxBPMState {
  3971. public:
  3972. // Does not take ownership of 'g'.
  3973. explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
  3974. ElementMatcherPairs Compute() {
  3975. if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
  3976. return best_so_far_;
  3977. }
  3978. lhs_used_.assign(graph_->LhsSize(), kUnused);
  3979. rhs_used_.assign(graph_->RhsSize(), kUnused);
  3980. for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
  3981. matches_.clear();
  3982. RecurseInto(irhs);
  3983. if (best_so_far_.size() == graph_->RhsSize())
  3984. break;
  3985. }
  3986. return best_so_far_;
  3987. }
  3988. private:
  3989. static const size_t kUnused = static_cast<size_t>(-1);
  3990. void PushMatch(size_t lhs, size_t rhs) {
  3991. matches_.push_back(ElementMatcherPair(lhs, rhs));
  3992. lhs_used_[lhs] = rhs;
  3993. rhs_used_[rhs] = lhs;
  3994. if (matches_.size() > best_so_far_.size()) {
  3995. best_so_far_ = matches_;
  3996. }
  3997. }
  3998. void PopMatch() {
  3999. const ElementMatcherPair& back = matches_.back();
  4000. lhs_used_[back.first] = kUnused;
  4001. rhs_used_[back.second] = kUnused;
  4002. matches_.pop_back();
  4003. }
  4004. bool RecurseInto(size_t irhs) {
  4005. if (rhs_used_[irhs] != kUnused) {
  4006. return true;
  4007. }
  4008. for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
  4009. if (lhs_used_[ilhs] != kUnused) {
  4010. continue;
  4011. }
  4012. if (!graph_->HasEdge(ilhs, irhs)) {
  4013. continue;
  4014. }
  4015. PushMatch(ilhs, irhs);
  4016. if (best_so_far_.size() == graph_->RhsSize()) {
  4017. return false;
  4018. }
  4019. for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
  4020. if (!RecurseInto(mi)) return false;
  4021. }
  4022. PopMatch();
  4023. }
  4024. return true;
  4025. }
  4026. const Graph* graph_; // not owned
  4027. std::vector<size_t> lhs_used_;
  4028. std::vector<size_t> rhs_used_;
  4029. ElementMatcherPairs matches_;
  4030. ElementMatcherPairs best_so_far_;
  4031. };
  4032. template <typename Graph>
  4033. const size_t BacktrackingMaxBPMState<Graph>::kUnused;
  4034. } // namespace
  4035. // Implement a simple backtracking algorithm to determine if it is possible
  4036. // to find one element per matcher, without reusing elements.
  4037. template <typename Graph>
  4038. ElementMatcherPairs
  4039. FindBacktrackingMaxBPM(const Graph& g) {
  4040. return BacktrackingMaxBPMState<Graph>(&g).Compute();
  4041. }
  4042. class BacktrackingBPMTest : public ::testing::Test { };
  4043. // Tests the MaxBipartiteMatching algorithm with square matrices.
  4044. // The single int param is the # of nodes on each of the left and right sides.
  4045. class BipartiteTest : public ::testing::TestWithParam<int> { };
  4046. // Verify all match graphs up to some moderate number of edges.
  4047. TEST_P(BipartiteTest, Exhaustive) {
  4048. int nodes = GetParam();
  4049. MatchMatrix graph(nodes, nodes);
  4050. do {
  4051. ElementMatcherPairs matches =
  4052. internal::FindMaxBipartiteMatching(graph);
  4053. EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
  4054. << "graph: " << graph.DebugString();
  4055. // Check that all elements of matches are in the graph.
  4056. // Check that elements of first and second are unique.
  4057. std::vector<bool> seen_element(graph.LhsSize());
  4058. std::vector<bool> seen_matcher(graph.RhsSize());
  4059. SCOPED_TRACE(PrintToString(matches));
  4060. for (size_t i = 0; i < matches.size(); ++i) {
  4061. size_t ilhs = matches[i].first;
  4062. size_t irhs = matches[i].second;
  4063. EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
  4064. EXPECT_FALSE(seen_element[ilhs]);
  4065. EXPECT_FALSE(seen_matcher[irhs]);
  4066. seen_element[ilhs] = true;
  4067. seen_matcher[irhs] = true;
  4068. }
  4069. } while (graph.NextGraph());
  4070. }
  4071. INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest,
  4072. ::testing::Range(0, 5));
  4073. // Parameterized by a pair interpreted as (LhsSize, RhsSize).
  4074. class BipartiteNonSquareTest
  4075. : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
  4076. };
  4077. TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
  4078. // .......
  4079. // 0:-----\ :
  4080. // 1:---\ | :
  4081. // 2:---\ | :
  4082. // 3:-\ | | :
  4083. // :.......:
  4084. // 0 1 2
  4085. MatchMatrix g(4, 3);
  4086. static const int kEdges[][2] = { {0, 2}, {1, 1}, {2, 1}, {3, 0} };
  4087. for (size_t i = 0; i < GMOCK_ARRAY_SIZE_(kEdges); ++i) {
  4088. g.SetEdge(kEdges[i][0], kEdges[i][1], true);
  4089. }
  4090. EXPECT_THAT(FindBacktrackingMaxBPM(g),
  4091. ElementsAre(Pair(3, 0),
  4092. Pair(AnyOf(1, 2), 1),
  4093. Pair(0, 2))) << g.DebugString();
  4094. }
  4095. // Verify a few nonsquare matrices.
  4096. TEST_P(BipartiteNonSquareTest, Exhaustive) {
  4097. size_t nlhs = GetParam().first;
  4098. size_t nrhs = GetParam().second;
  4099. MatchMatrix graph(nlhs, nrhs);
  4100. do {
  4101. EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
  4102. internal::FindMaxBipartiteMatching(graph).size())
  4103. << "graph: " << graph.DebugString()
  4104. << "\nbacktracking: "
  4105. << PrintToString(FindBacktrackingMaxBPM(graph))
  4106. << "\nmax flow: "
  4107. << PrintToString(internal::FindMaxBipartiteMatching(graph));
  4108. } while (graph.NextGraph());
  4109. }
  4110. INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest,
  4111. testing::Values(
  4112. std::make_pair(1, 2),
  4113. std::make_pair(2, 1),
  4114. std::make_pair(3, 2),
  4115. std::make_pair(2, 3),
  4116. std::make_pair(4, 1),
  4117. std::make_pair(1, 4),
  4118. std::make_pair(4, 3),
  4119. std::make_pair(3, 4)));
  4120. class BipartiteRandomTest
  4121. : public ::testing::TestWithParam<std::pair<int, int> > {
  4122. };
  4123. // Verifies a large sample of larger graphs.
  4124. TEST_P(BipartiteRandomTest, LargerNets) {
  4125. int nodes = GetParam().first;
  4126. int iters = GetParam().second;
  4127. MatchMatrix graph(nodes, nodes);
  4128. testing::internal::Int32 seed = GTEST_FLAG(random_seed);
  4129. if (seed == 0) {
  4130. seed = static_cast<testing::internal::Int32>(time(NULL));
  4131. }
  4132. for (; iters > 0; --iters, ++seed) {
  4133. srand(static_cast<int>(seed));
  4134. graph.Randomize();
  4135. EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
  4136. internal::FindMaxBipartiteMatching(graph).size())
  4137. << " graph: " << graph.DebugString()
  4138. << "\nTo reproduce the failure, rerun the test with the flag"
  4139. " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
  4140. }
  4141. }
  4142. // Test argument is a std::pair<int, int> representing (nodes, iters).
  4143. INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest,
  4144. testing::Values(
  4145. std::make_pair(5, 10000),
  4146. std::make_pair(6, 5000),
  4147. std::make_pair(7, 2000),
  4148. std::make_pair(8, 500),
  4149. std::make_pair(9, 100)));
  4150. // Tests IsReadableTypeName().
  4151. TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
  4152. EXPECT_TRUE(IsReadableTypeName("int"));
  4153. EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
  4154. EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
  4155. EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
  4156. }
  4157. TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
  4158. EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
  4159. EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
  4160. EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
  4161. }
  4162. TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
  4163. EXPECT_FALSE(
  4164. IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
  4165. EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
  4166. }
  4167. TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
  4168. EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
  4169. }
  4170. // Tests JoinAsTuple().
  4171. TEST(JoinAsTupleTest, JoinsEmptyTuple) {
  4172. EXPECT_EQ("", JoinAsTuple(Strings()));
  4173. }
  4174. TEST(JoinAsTupleTest, JoinsOneTuple) {
  4175. const char* fields[] = { "1" };
  4176. EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
  4177. }
  4178. TEST(JoinAsTupleTest, JoinsTwoTuple) {
  4179. const char* fields[] = { "1", "a" };
  4180. EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
  4181. }
  4182. TEST(JoinAsTupleTest, JoinsTenTuple) {
  4183. const char* fields[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
  4184. EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
  4185. JoinAsTuple(Strings(fields, fields + 10)));
  4186. }
  4187. // Tests FormatMatcherDescription().
  4188. TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
  4189. EXPECT_EQ("is even",
  4190. FormatMatcherDescription(false, "IsEven", Strings()));
  4191. EXPECT_EQ("not (is even)",
  4192. FormatMatcherDescription(true, "IsEven", Strings()));
  4193. const char* params[] = { "5" };
  4194. EXPECT_EQ("equals 5",
  4195. FormatMatcherDescription(false, "Equals",
  4196. Strings(params, params + 1)));
  4197. const char* params2[] = { "5", "8" };
  4198. EXPECT_EQ("is in range (5, 8)",
  4199. FormatMatcherDescription(false, "IsInRange",
  4200. Strings(params2, params2 + 2)));
  4201. }
  4202. // Tests PolymorphicMatcher::mutable_impl().
  4203. TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
  4204. PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
  4205. DivisibleByImpl& impl = m.mutable_impl();
  4206. EXPECT_EQ(42, impl.divider());
  4207. impl.set_divider(0);
  4208. EXPECT_EQ(0, m.mutable_impl().divider());
  4209. }
  4210. // Tests PolymorphicMatcher::impl().
  4211. TEST(PolymorphicMatcherTest, CanAccessImpl) {
  4212. const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
  4213. const DivisibleByImpl& impl = m.impl();
  4214. EXPECT_EQ(42, impl.divider());
  4215. }
  4216. TEST(MatcherTupleTest, ExplainsMatchFailure) {
  4217. stringstream ss1;
  4218. ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
  4219. make_tuple('a', 10), &ss1);
  4220. EXPECT_EQ("", ss1.str()); // Successful match.
  4221. stringstream ss2;
  4222. ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
  4223. make_tuple(2, 'b'), &ss2);
  4224. EXPECT_EQ(" Expected arg #0: is > 5\n"
  4225. " Actual: 2, which is 3 less than 5\n"
  4226. " Expected arg #1: is equal to 'a' (97, 0x61)\n"
  4227. " Actual: 'b' (98, 0x62)\n",
  4228. ss2.str()); // Failed match where both arguments need explanation.
  4229. stringstream ss3;
  4230. ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
  4231. make_tuple(2, 'a'), &ss3);
  4232. EXPECT_EQ(" Expected arg #0: is > 5\n"
  4233. " Actual: 2, which is 3 less than 5\n",
  4234. ss3.str()); // Failed match where only one argument needs
  4235. // explanation.
  4236. }
  4237. // Tests Each().
  4238. TEST(EachTest, ExplainsMatchResultCorrectly) {
  4239. set<int> a; // empty
  4240. Matcher<set<int> > m = Each(2);
  4241. EXPECT_EQ("", Explain(m, a));
  4242. Matcher<const int(&)[1]> n = Each(1); // NOLINT
  4243. const int b[1] = { 1 };
  4244. EXPECT_EQ("", Explain(n, b));
  4245. n = Each(3);
  4246. EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
  4247. a.insert(1);
  4248. a.insert(2);
  4249. a.insert(3);
  4250. m = Each(GreaterThan(0));
  4251. EXPECT_EQ("", Explain(m, a));
  4252. m = Each(GreaterThan(10));
  4253. EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
  4254. Explain(m, a));
  4255. }
  4256. TEST(EachTest, DescribesItselfCorrectly) {
  4257. Matcher<vector<int> > m = Each(1);
  4258. EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
  4259. Matcher<vector<int> > m2 = Not(m);
  4260. EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
  4261. }
  4262. TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
  4263. vector<int> some_vector;
  4264. EXPECT_THAT(some_vector, Each(1));
  4265. some_vector.push_back(3);
  4266. EXPECT_THAT(some_vector, Not(Each(1)));
  4267. EXPECT_THAT(some_vector, Each(3));
  4268. some_vector.push_back(1);
  4269. some_vector.push_back(2);
  4270. EXPECT_THAT(some_vector, Not(Each(3)));
  4271. EXPECT_THAT(some_vector, Each(Lt(3.5)));
  4272. vector<string> another_vector;
  4273. another_vector.push_back("fee");
  4274. EXPECT_THAT(another_vector, Each(string("fee")));
  4275. another_vector.push_back("fie");
  4276. another_vector.push_back("foe");
  4277. another_vector.push_back("fum");
  4278. EXPECT_THAT(another_vector, Not(Each(string("fee"))));
  4279. }
  4280. TEST(EachTest, MatchesMapWhenAllElementsMatch) {
  4281. map<const char*, int> my_map;
  4282. const char* bar = "a string";
  4283. my_map[bar] = 2;
  4284. EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
  4285. map<string, int> another_map;
  4286. EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
  4287. another_map["fee"] = 1;
  4288. EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
  4289. another_map["fie"] = 2;
  4290. another_map["foe"] = 3;
  4291. another_map["fum"] = 4;
  4292. EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1))));
  4293. EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1))));
  4294. EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
  4295. }
  4296. TEST(EachTest, AcceptsMatcher) {
  4297. const int a[] = { 1, 2, 3 };
  4298. EXPECT_THAT(a, Each(Gt(0)));
  4299. EXPECT_THAT(a, Not(Each(Gt(1))));
  4300. }
  4301. TEST(EachTest, WorksForNativeArrayAsTuple) {
  4302. const int a[] = { 1, 2 };
  4303. const int* const pointer = a;
  4304. EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
  4305. EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
  4306. }
  4307. // For testing Pointwise().
  4308. class IsHalfOfMatcher {
  4309. public:
  4310. template <typename T1, typename T2>
  4311. bool MatchAndExplain(const tuple<T1, T2>& a_pair,
  4312. MatchResultListener* listener) const {
  4313. if (get<0>(a_pair) == get<1>(a_pair)/2) {
  4314. *listener << "where the second is " << get<1>(a_pair);
  4315. return true;
  4316. } else {
  4317. *listener << "where the second/2 is " << get<1>(a_pair)/2;
  4318. return false;
  4319. }
  4320. }
  4321. void DescribeTo(ostream* os) const {
  4322. *os << "are a pair where the first is half of the second";
  4323. }
  4324. void DescribeNegationTo(ostream* os) const {
  4325. *os << "are a pair where the first isn't half of the second";
  4326. }
  4327. };
  4328. PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
  4329. return MakePolymorphicMatcher(IsHalfOfMatcher());
  4330. }
  4331. TEST(PointwiseTest, DescribesSelf) {
  4332. vector<int> rhs;
  4333. rhs.push_back(1);
  4334. rhs.push_back(2);
  4335. rhs.push_back(3);
  4336. const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
  4337. EXPECT_EQ("contains 3 values, where each value and its corresponding value "
  4338. "in { 1, 2, 3 } are a pair where the first is half of the second",
  4339. Describe(m));
  4340. EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
  4341. "index i where x and the i-th value of { 1, 2, 3 } are a pair "
  4342. "where the first isn't half of the second",
  4343. DescribeNegation(m));
  4344. }
  4345. TEST(PointwiseTest, MakesCopyOfRhs) {
  4346. list<signed char> rhs;
  4347. rhs.push_back(2);
  4348. rhs.push_back(4);
  4349. int lhs[] = { 1, 2 };
  4350. const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
  4351. EXPECT_THAT(lhs, m);
  4352. // Changing rhs now shouldn't affect m, which made a copy of rhs.
  4353. rhs.push_back(6);
  4354. EXPECT_THAT(lhs, m);
  4355. }
  4356. TEST(PointwiseTest, WorksForLhsNativeArray) {
  4357. const int lhs[] = { 1, 2, 3 };
  4358. vector<int> rhs;
  4359. rhs.push_back(2);
  4360. rhs.push_back(4);
  4361. rhs.push_back(6);
  4362. EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
  4363. EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
  4364. }
  4365. TEST(PointwiseTest, WorksForRhsNativeArray) {
  4366. const int rhs[] = { 1, 2, 3 };
  4367. vector<int> lhs;
  4368. lhs.push_back(2);
  4369. lhs.push_back(4);
  4370. lhs.push_back(6);
  4371. EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
  4372. EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
  4373. }
  4374. TEST(PointwiseTest, RejectsWrongSize) {
  4375. const double lhs[2] = { 1, 2 };
  4376. const int rhs[1] = { 0 };
  4377. EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
  4378. EXPECT_EQ("which contains 2 values",
  4379. Explain(Pointwise(Gt(), rhs), lhs));
  4380. const int rhs2[3] = { 0, 1, 2 };
  4381. EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
  4382. }
  4383. TEST(PointwiseTest, RejectsWrongContent) {
  4384. const double lhs[3] = { 1, 2, 3 };
  4385. const int rhs[3] = { 2, 6, 4 };
  4386. EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
  4387. EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
  4388. "where the second/2 is 3",
  4389. Explain(Pointwise(IsHalfOf(), rhs), lhs));
  4390. }
  4391. TEST(PointwiseTest, AcceptsCorrectContent) {
  4392. const double lhs[3] = { 1, 2, 3 };
  4393. const int rhs[3] = { 2, 4, 6 };
  4394. EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
  4395. EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
  4396. }
  4397. TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
  4398. const double lhs[3] = { 1, 2, 3 };
  4399. const int rhs[3] = { 2, 4, 6 };
  4400. const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
  4401. EXPECT_THAT(lhs, Pointwise(m1, rhs));
  4402. EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
  4403. // This type works as a tuple<const double&, const int&> can be
  4404. // implicitly cast to tuple<double, int>.
  4405. const Matcher<tuple<double, int> > m2 = IsHalfOf();
  4406. EXPECT_THAT(lhs, Pointwise(m2, rhs));
  4407. EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
  4408. }
  4409. } // namespace gmock_matchers_test
  4410. } // namespace testing