You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6801 lines
219 KiB

  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. // Google Mock - a framework for writing C++ mock classes.
  30. //
  31. // This file tests some commonly used argument matchers.
  32. // Silence warning C4244: 'initializing': conversion from 'int' to 'short',
  33. // possible loss of data and C4100, unreferenced local parameter
  34. #ifdef _MSC_VER
  35. # pragma warning(push)
  36. # pragma warning(disable:4244)
  37. # pragma warning(disable:4100)
  38. #endif
  39. #include "gmock/gmock-matchers.h"
  40. #include "gmock/gmock-more-matchers.h"
  41. #include <string.h>
  42. #include <time.h>
  43. #include <deque>
  44. #include <forward_list>
  45. #include <functional>
  46. #include <iostream>
  47. #include <iterator>
  48. #include <limits>
  49. #include <list>
  50. #include <map>
  51. #include <memory>
  52. #include <set>
  53. #include <sstream>
  54. #include <string>
  55. #include <type_traits>
  56. #include <utility>
  57. #include <vector>
  58. #include "gmock/gmock.h"
  59. #include "gtest/gtest.h"
  60. #include "gtest/gtest-spi.h"
  61. namespace testing {
  62. namespace gmock_matchers_test {
  63. namespace {
  64. using std::greater;
  65. using std::less;
  66. using std::list;
  67. using std::make_pair;
  68. using std::map;
  69. using std::multimap;
  70. using std::multiset;
  71. using std::ostream;
  72. using std::pair;
  73. using std::set;
  74. using std::stringstream;
  75. using std::vector;
  76. using testing::internal::DummyMatchResultListener;
  77. using testing::internal::ElementMatcherPair;
  78. using testing::internal::ElementMatcherPairs;
  79. using testing::internal::ExplainMatchFailureTupleTo;
  80. using testing::internal::FloatingEqMatcher;
  81. using testing::internal::FormatMatcherDescription;
  82. using testing::internal::IsReadableTypeName;
  83. using testing::internal::MatchMatrix;
  84. using testing::internal::PredicateFormatterFromMatcher;
  85. using testing::internal::RE;
  86. using testing::internal::StreamMatchResultListener;
  87. using testing::internal::Strings;
  88. // Helper for testing container-valued matchers in mock method context. It is
  89. // important to test matchers in this context, since it requires additional type
  90. // deduction beyond what EXPECT_THAT does, thus making it more restrictive.
  91. struct ContainerHelper {
  92. MOCK_METHOD1(Call, void(std::vector<std::unique_ptr<int>>));
  93. };
  94. std::vector<std::unique_ptr<int>> MakeUniquePtrs(const std::vector<int>& ints) {
  95. std::vector<std::unique_ptr<int>> pointers;
  96. for (int i : ints) pointers.emplace_back(new int(i));
  97. return pointers;
  98. }
  99. // For testing ExplainMatchResultTo().
  100. class GreaterThanMatcher : public MatcherInterface<int> {
  101. public:
  102. explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
  103. void DescribeTo(ostream* os) const override { *os << "is > " << rhs_; }
  104. bool MatchAndExplain(int lhs, MatchResultListener* listener) const override {
  105. const int diff = lhs - rhs_;
  106. if (diff > 0) {
  107. *listener << "which is " << diff << " more than " << rhs_;
  108. } else if (diff == 0) {
  109. *listener << "which is the same as " << rhs_;
  110. } else {
  111. *listener << "which is " << -diff << " less than " << rhs_;
  112. }
  113. return lhs > rhs_;
  114. }
  115. private:
  116. int rhs_;
  117. };
  118. Matcher<int> GreaterThan(int n) {
  119. return MakeMatcher(new GreaterThanMatcher(n));
  120. }
  121. std::string OfType(const std::string& type_name) {
  122. #if GTEST_HAS_RTTI
  123. return " (of type " + type_name + ")";
  124. #else
  125. return "";
  126. #endif
  127. }
  128. // Returns the description of the given matcher.
  129. template <typename T>
  130. std::string Describe(const Matcher<T>& m) {
  131. return DescribeMatcher<T>(m);
  132. }
  133. // Returns the description of the negation of the given matcher.
  134. template <typename T>
  135. std::string DescribeNegation(const Matcher<T>& m) {
  136. return DescribeMatcher<T>(m, true);
  137. }
  138. // Returns the reason why x matches, or doesn't match, m.
  139. template <typename MatcherType, typename Value>
  140. std::string Explain(const MatcherType& m, const Value& x) {
  141. StringMatchResultListener listener;
  142. ExplainMatchResult(m, x, &listener);
  143. return listener.str();
  144. }
  145. TEST(MonotonicMatcherTest, IsPrintable) {
  146. stringstream ss;
  147. ss << GreaterThan(5);
  148. EXPECT_EQ("is > 5", ss.str());
  149. }
  150. TEST(MatchResultListenerTest, StreamingWorks) {
  151. StringMatchResultListener listener;
  152. listener << "hi" << 5;
  153. EXPECT_EQ("hi5", listener.str());
  154. listener.Clear();
  155. EXPECT_EQ("", listener.str());
  156. listener << 42;
  157. EXPECT_EQ("42", listener.str());
  158. // Streaming shouldn't crash when the underlying ostream is NULL.
  159. DummyMatchResultListener dummy;
  160. dummy << "hi" << 5;
  161. }
  162. TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
  163. EXPECT_TRUE(DummyMatchResultListener().stream() == nullptr);
  164. EXPECT_TRUE(StreamMatchResultListener(nullptr).stream() == nullptr);
  165. EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
  166. }
  167. TEST(MatchResultListenerTest, IsInterestedWorks) {
  168. EXPECT_TRUE(StringMatchResultListener().IsInterested());
  169. EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
  170. EXPECT_FALSE(DummyMatchResultListener().IsInterested());
  171. EXPECT_FALSE(StreamMatchResultListener(nullptr).IsInterested());
  172. }
  173. // Makes sure that the MatcherInterface<T> interface doesn't
  174. // change.
  175. class EvenMatcherImpl : public MatcherInterface<int> {
  176. public:
  177. bool MatchAndExplain(int x,
  178. MatchResultListener* /* listener */) const override {
  179. return x % 2 == 0;
  180. }
  181. void DescribeTo(ostream* os) const override { *os << "is an even number"; }
  182. // We deliberately don't define DescribeNegationTo() and
  183. // ExplainMatchResultTo() here, to make sure the definition of these
  184. // two methods is optional.
  185. };
  186. // Makes sure that the MatcherInterface API doesn't change.
  187. TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
  188. EvenMatcherImpl m;
  189. }
  190. // Tests implementing a monomorphic matcher using MatchAndExplain().
  191. class NewEvenMatcherImpl : public MatcherInterface<int> {
  192. public:
  193. bool MatchAndExplain(int x, MatchResultListener* listener) const override {
  194. const bool match = x % 2 == 0;
  195. // Verifies that we can stream to a listener directly.
  196. *listener << "value % " << 2;
  197. if (listener->stream() != nullptr) {
  198. // Verifies that we can stream to a listener's underlying stream
  199. // too.
  200. *listener->stream() << " == " << (x % 2);
  201. }
  202. return match;
  203. }
  204. void DescribeTo(ostream* os) const override { *os << "is an even number"; }
  205. };
  206. TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
  207. Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
  208. EXPECT_TRUE(m.Matches(2));
  209. EXPECT_FALSE(m.Matches(3));
  210. EXPECT_EQ("value % 2 == 0", Explain(m, 2));
  211. EXPECT_EQ("value % 2 == 1", Explain(m, 3));
  212. }
  213. // Tests default-constructing a matcher.
  214. TEST(MatcherTest, CanBeDefaultConstructed) {
  215. Matcher<double> m;
  216. }
  217. // Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
  218. TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
  219. const MatcherInterface<int>* impl = new EvenMatcherImpl;
  220. Matcher<int> m(impl);
  221. EXPECT_TRUE(m.Matches(4));
  222. EXPECT_FALSE(m.Matches(5));
  223. }
  224. // Tests that value can be used in place of Eq(value).
  225. TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
  226. Matcher<int> m1 = 5;
  227. EXPECT_TRUE(m1.Matches(5));
  228. EXPECT_FALSE(m1.Matches(6));
  229. }
  230. // Tests that NULL can be used in place of Eq(NULL).
  231. TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
  232. Matcher<int*> m1 = nullptr;
  233. EXPECT_TRUE(m1.Matches(nullptr));
  234. int n = 0;
  235. EXPECT_FALSE(m1.Matches(&n));
  236. }
  237. // Tests that matchers can be constructed from a variable that is not properly
  238. // defined. This should be illegal, but many users rely on this accidentally.
  239. struct Undefined {
  240. virtual ~Undefined() = 0;
  241. static const int kInt = 1;
  242. };
  243. TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) {
  244. Matcher<int> m1 = Undefined::kInt;
  245. EXPECT_TRUE(m1.Matches(1));
  246. EXPECT_FALSE(m1.Matches(2));
  247. }
  248. // Test that a matcher parameterized with an abstract class compiles.
  249. TEST(MatcherTest, CanAcceptAbstractClass) { Matcher<const Undefined&> m = _; }
  250. // Tests that matchers are copyable.
  251. TEST(MatcherTest, IsCopyable) {
  252. // Tests the copy constructor.
  253. Matcher<bool> m1 = Eq(false);
  254. EXPECT_TRUE(m1.Matches(false));
  255. EXPECT_FALSE(m1.Matches(true));
  256. // Tests the assignment operator.
  257. m1 = Eq(true);
  258. EXPECT_TRUE(m1.Matches(true));
  259. EXPECT_FALSE(m1.Matches(false));
  260. }
  261. // Tests that Matcher<T>::DescribeTo() calls
  262. // MatcherInterface<T>::DescribeTo().
  263. TEST(MatcherTest, CanDescribeItself) {
  264. EXPECT_EQ("is an even number",
  265. Describe(Matcher<int>(new EvenMatcherImpl)));
  266. }
  267. // Tests Matcher<T>::MatchAndExplain().
  268. TEST(MatcherTest, MatchAndExplain) {
  269. Matcher<int> m = GreaterThan(0);
  270. StringMatchResultListener listener1;
  271. EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
  272. EXPECT_EQ("which is 42 more than 0", listener1.str());
  273. StringMatchResultListener listener2;
  274. EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
  275. EXPECT_EQ("which is 9 less than 0", listener2.str());
  276. }
  277. // Tests that a C-string literal can be implicitly converted to a
  278. // Matcher<std::string> or Matcher<const std::string&>.
  279. TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
  280. Matcher<std::string> m1 = "hi";
  281. EXPECT_TRUE(m1.Matches("hi"));
  282. EXPECT_FALSE(m1.Matches("hello"));
  283. Matcher<const std::string&> m2 = "hi";
  284. EXPECT_TRUE(m2.Matches("hi"));
  285. EXPECT_FALSE(m2.Matches("hello"));
  286. }
  287. // Tests that a string object can be implicitly converted to a
  288. // Matcher<std::string> or Matcher<const std::string&>.
  289. TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
  290. Matcher<std::string> m1 = std::string("hi");
  291. EXPECT_TRUE(m1.Matches("hi"));
  292. EXPECT_FALSE(m1.Matches("hello"));
  293. Matcher<const std::string&> m2 = std::string("hi");
  294. EXPECT_TRUE(m2.Matches("hi"));
  295. EXPECT_FALSE(m2.Matches("hello"));
  296. }
  297. #if GTEST_HAS_ABSL
  298. // Tests that a C-string literal can be implicitly converted to a
  299. // Matcher<absl::string_view> or Matcher<const absl::string_view&>.
  300. TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
  301. Matcher<absl::string_view> m1 = "cats";
  302. EXPECT_TRUE(m1.Matches("cats"));
  303. EXPECT_FALSE(m1.Matches("dogs"));
  304. Matcher<const absl::string_view&> m2 = "cats";
  305. EXPECT_TRUE(m2.Matches("cats"));
  306. EXPECT_FALSE(m2.Matches("dogs"));
  307. }
  308. // Tests that a std::string object can be implicitly converted to a
  309. // Matcher<absl::string_view> or Matcher<const absl::string_view&>.
  310. TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {
  311. Matcher<absl::string_view> m1 = std::string("cats");
  312. EXPECT_TRUE(m1.Matches("cats"));
  313. EXPECT_FALSE(m1.Matches("dogs"));
  314. Matcher<const absl::string_view&> m2 = std::string("cats");
  315. EXPECT_TRUE(m2.Matches("cats"));
  316. EXPECT_FALSE(m2.Matches("dogs"));
  317. }
  318. // Tests that a absl::string_view object can be implicitly converted to a
  319. // Matcher<absl::string_view> or Matcher<const absl::string_view&>.
  320. TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {
  321. Matcher<absl::string_view> m1 = absl::string_view("cats");
  322. EXPECT_TRUE(m1.Matches("cats"));
  323. EXPECT_FALSE(m1.Matches("dogs"));
  324. Matcher<const absl::string_view&> m2 = absl::string_view("cats");
  325. EXPECT_TRUE(m2.Matches("cats"));
  326. EXPECT_FALSE(m2.Matches("dogs"));
  327. }
  328. #endif // GTEST_HAS_ABSL
  329. // Tests that a std::reference_wrapper<std::string> object can be implicitly
  330. // converted to a Matcher<std::string> or Matcher<const std::string&> via Eq().
  331. TEST(StringMatcherTest,
  332. CanBeImplicitlyConstructedFromEqReferenceWrapperString) {
  333. std::string value = "cats";
  334. Matcher<std::string> m1 = Eq(std::ref(value));
  335. EXPECT_TRUE(m1.Matches("cats"));
  336. EXPECT_FALSE(m1.Matches("dogs"));
  337. Matcher<const std::string&> m2 = Eq(std::ref(value));
  338. EXPECT_TRUE(m2.Matches("cats"));
  339. EXPECT_FALSE(m2.Matches("dogs"));
  340. }
  341. // Tests that MakeMatcher() constructs a Matcher<T> from a
  342. // MatcherInterface* without requiring the user to explicitly
  343. // write the type.
  344. TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
  345. const MatcherInterface<int>* dummy_impl = nullptr;
  346. Matcher<int> m = MakeMatcher(dummy_impl);
  347. }
  348. // Tests that MakePolymorphicMatcher() can construct a polymorphic
  349. // matcher from its implementation using the old API.
  350. const int g_bar = 1;
  351. class ReferencesBarOrIsZeroImpl {
  352. public:
  353. template <typename T>
  354. bool MatchAndExplain(const T& x,
  355. MatchResultListener* /* listener */) const {
  356. const void* p = &x;
  357. return p == &g_bar || x == 0;
  358. }
  359. void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
  360. void DescribeNegationTo(ostream* os) const {
  361. *os << "doesn't reference g_bar and is not zero";
  362. }
  363. };
  364. // This function verifies that MakePolymorphicMatcher() returns a
  365. // PolymorphicMatcher<T> where T is the argument's type.
  366. PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
  367. return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
  368. }
  369. TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
  370. // Using a polymorphic matcher to match a reference type.
  371. Matcher<const int&> m1 = ReferencesBarOrIsZero();
  372. EXPECT_TRUE(m1.Matches(0));
  373. // Verifies that the identity of a by-reference argument is preserved.
  374. EXPECT_TRUE(m1.Matches(g_bar));
  375. EXPECT_FALSE(m1.Matches(1));
  376. EXPECT_EQ("g_bar or zero", Describe(m1));
  377. // Using a polymorphic matcher to match a value type.
  378. Matcher<double> m2 = ReferencesBarOrIsZero();
  379. EXPECT_TRUE(m2.Matches(0.0));
  380. EXPECT_FALSE(m2.Matches(0.1));
  381. EXPECT_EQ("g_bar or zero", Describe(m2));
  382. }
  383. // Tests implementing a polymorphic matcher using MatchAndExplain().
  384. class PolymorphicIsEvenImpl {
  385. public:
  386. void DescribeTo(ostream* os) const { *os << "is even"; }
  387. void DescribeNegationTo(ostream* os) const {
  388. *os << "is odd";
  389. }
  390. template <typename T>
  391. bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
  392. // Verifies that we can stream to the listener directly.
  393. *listener << "% " << 2;
  394. if (listener->stream() != nullptr) {
  395. // Verifies that we can stream to the listener's underlying stream
  396. // too.
  397. *listener->stream() << " == " << (x % 2);
  398. }
  399. return (x % 2) == 0;
  400. }
  401. };
  402. PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
  403. return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
  404. }
  405. TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
  406. // Using PolymorphicIsEven() as a Matcher<int>.
  407. const Matcher<int> m1 = PolymorphicIsEven();
  408. EXPECT_TRUE(m1.Matches(42));
  409. EXPECT_FALSE(m1.Matches(43));
  410. EXPECT_EQ("is even", Describe(m1));
  411. const Matcher<int> not_m1 = Not(m1);
  412. EXPECT_EQ("is odd", Describe(not_m1));
  413. EXPECT_EQ("% 2 == 0", Explain(m1, 42));
  414. // Using PolymorphicIsEven() as a Matcher<char>.
  415. const Matcher<char> m2 = PolymorphicIsEven();
  416. EXPECT_TRUE(m2.Matches('\x42'));
  417. EXPECT_FALSE(m2.Matches('\x43'));
  418. EXPECT_EQ("is even", Describe(m2));
  419. const Matcher<char> not_m2 = Not(m2);
  420. EXPECT_EQ("is odd", Describe(not_m2));
  421. EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
  422. }
  423. // Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
  424. TEST(MatcherCastTest, FromPolymorphicMatcher) {
  425. Matcher<int> m = MatcherCast<int>(Eq(5));
  426. EXPECT_TRUE(m.Matches(5));
  427. EXPECT_FALSE(m.Matches(6));
  428. }
  429. // For testing casting matchers between compatible types.
  430. class IntValue {
  431. public:
  432. // An int can be statically (although not implicitly) cast to a
  433. // IntValue.
  434. explicit IntValue(int a_value) : value_(a_value) {}
  435. int value() const { return value_; }
  436. private:
  437. int value_;
  438. };
  439. // For testing casting matchers between compatible types.
  440. bool IsPositiveIntValue(const IntValue& foo) {
  441. return foo.value() > 0;
  442. }
  443. // Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
  444. // can be statically converted to U.
  445. TEST(MatcherCastTest, FromCompatibleType) {
  446. Matcher<double> m1 = Eq(2.0);
  447. Matcher<int> m2 = MatcherCast<int>(m1);
  448. EXPECT_TRUE(m2.Matches(2));
  449. EXPECT_FALSE(m2.Matches(3));
  450. Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
  451. Matcher<int> m4 = MatcherCast<int>(m3);
  452. // In the following, the arguments 1 and 0 are statically converted
  453. // to IntValue objects, and then tested by the IsPositiveIntValue()
  454. // predicate.
  455. EXPECT_TRUE(m4.Matches(1));
  456. EXPECT_FALSE(m4.Matches(0));
  457. }
  458. // Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
  459. TEST(MatcherCastTest, FromConstReferenceToNonReference) {
  460. Matcher<const int&> m1 = Eq(0);
  461. Matcher<int> m2 = MatcherCast<int>(m1);
  462. EXPECT_TRUE(m2.Matches(0));
  463. EXPECT_FALSE(m2.Matches(1));
  464. }
  465. // Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
  466. TEST(MatcherCastTest, FromReferenceToNonReference) {
  467. Matcher<int&> m1 = Eq(0);
  468. Matcher<int> m2 = MatcherCast<int>(m1);
  469. EXPECT_TRUE(m2.Matches(0));
  470. EXPECT_FALSE(m2.Matches(1));
  471. }
  472. // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
  473. TEST(MatcherCastTest, FromNonReferenceToConstReference) {
  474. Matcher<int> m1 = Eq(0);
  475. Matcher<const int&> m2 = MatcherCast<const int&>(m1);
  476. EXPECT_TRUE(m2.Matches(0));
  477. EXPECT_FALSE(m2.Matches(1));
  478. }
  479. // Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
  480. TEST(MatcherCastTest, FromNonReferenceToReference) {
  481. Matcher<int> m1 = Eq(0);
  482. Matcher<int&> m2 = MatcherCast<int&>(m1);
  483. int n = 0;
  484. EXPECT_TRUE(m2.Matches(n));
  485. n = 1;
  486. EXPECT_FALSE(m2.Matches(n));
  487. }
  488. // Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
  489. TEST(MatcherCastTest, FromSameType) {
  490. Matcher<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 value of the same type as the
  496. // value type of the Matcher.
  497. TEST(MatcherCastTest, FromAValue) {
  498. Matcher<int> m = MatcherCast<int>(42);
  499. EXPECT_TRUE(m.Matches(42));
  500. EXPECT_FALSE(m.Matches(239));
  501. }
  502. // Tests that MatcherCast<T>(m) works when m is a value of the type implicitly
  503. // convertible to the value type of the Matcher.
  504. TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) {
  505. const int kExpected = 'c';
  506. Matcher<int> m = MatcherCast<int>('c');
  507. EXPECT_TRUE(m.Matches(kExpected));
  508. EXPECT_FALSE(m.Matches(kExpected + 1));
  509. }
  510. struct NonImplicitlyConstructibleTypeWithOperatorEq {
  511. friend bool operator==(
  512. const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */,
  513. int rhs) {
  514. return 42 == rhs;
  515. }
  516. friend bool operator==(
  517. int lhs,
  518. const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) {
  519. return lhs == 42;
  520. }
  521. };
  522. // Tests that MatcherCast<T>(m) works when m is a neither a matcher nor
  523. // implicitly convertible to the value type of the Matcher, but the value type
  524. // of the matcher has operator==() overload accepting m.
  525. TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) {
  526. Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m1 =
  527. MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(42);
  528. EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
  529. Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m2 =
  530. MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(239);
  531. EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
  532. // When updating the following lines please also change the comment to
  533. // namespace convertible_from_any.
  534. Matcher<int> m3 =
  535. MatcherCast<int>(NonImplicitlyConstructibleTypeWithOperatorEq());
  536. EXPECT_TRUE(m3.Matches(42));
  537. EXPECT_FALSE(m3.Matches(239));
  538. }
  539. // ConvertibleFromAny does not work with MSVC. resulting in
  540. // error C2440: 'initializing': cannot convert from 'Eq' to 'M'
  541. // No constructor could take the source type, or constructor overload
  542. // resolution was ambiguous
  543. #if !defined _MSC_VER
  544. // The below ConvertibleFromAny struct is implicitly constructible from anything
  545. // and when in the same namespace can interact with other tests. In particular,
  546. // if it is in the same namespace as other tests and one removes
  547. // NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...);
  548. // then the corresponding test still compiles (and it should not!) by implicitly
  549. // converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny
  550. // in m3.Matcher().
  551. namespace convertible_from_any {
  552. // Implicitly convertible from any type.
  553. struct ConvertibleFromAny {
  554. ConvertibleFromAny(int a_value) : value(a_value) {}
  555. template <typename T>
  556. ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
  557. ADD_FAILURE() << "Conversion constructor called";
  558. }
  559. int value;
  560. };
  561. bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
  562. return a.value == b.value;
  563. }
  564. ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
  565. return os << a.value;
  566. }
  567. TEST(MatcherCastTest, ConversionConstructorIsUsed) {
  568. Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
  569. EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
  570. EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
  571. }
  572. TEST(MatcherCastTest, FromConvertibleFromAny) {
  573. Matcher<ConvertibleFromAny> m =
  574. MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
  575. EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
  576. EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
  577. }
  578. } // namespace convertible_from_any
  579. #endif // !defined _MSC_VER
  580. struct IntReferenceWrapper {
  581. IntReferenceWrapper(const int& a_value) : value(&a_value) {}
  582. const int* value;
  583. };
  584. bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
  585. return a.value == b.value;
  586. }
  587. TEST(MatcherCastTest, ValueIsNotCopied) {
  588. int n = 42;
  589. Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
  590. // Verify that the matcher holds a reference to n, not to its temporary copy.
  591. EXPECT_TRUE(m.Matches(n));
  592. }
  593. class Base {
  594. public:
  595. virtual ~Base() {}
  596. Base() {}
  597. private:
  598. GTEST_DISALLOW_COPY_AND_ASSIGN_(Base);
  599. };
  600. class Derived : public Base {
  601. public:
  602. Derived() : Base() {}
  603. int i;
  604. };
  605. class OtherDerived : public Base {};
  606. // Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
  607. TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
  608. Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
  609. EXPECT_TRUE(m2.Matches(' '));
  610. EXPECT_FALSE(m2.Matches('\n'));
  611. }
  612. // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
  613. // T and U are arithmetic types and T can be losslessly converted to
  614. // U.
  615. TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
  616. Matcher<double> m1 = DoubleEq(1.0);
  617. Matcher<float> m2 = SafeMatcherCast<float>(m1);
  618. EXPECT_TRUE(m2.Matches(1.0f));
  619. EXPECT_FALSE(m2.Matches(2.0f));
  620. Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
  621. EXPECT_TRUE(m3.Matches('a'));
  622. EXPECT_FALSE(m3.Matches('b'));
  623. }
  624. // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
  625. // are pointers or references to a derived and a base class, correspondingly.
  626. TEST(SafeMatcherCastTest, FromBaseClass) {
  627. Derived d, d2;
  628. Matcher<Base*> m1 = Eq(&d);
  629. Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
  630. EXPECT_TRUE(m2.Matches(&d));
  631. EXPECT_FALSE(m2.Matches(&d2));
  632. Matcher<Base&> m3 = Ref(d);
  633. Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
  634. EXPECT_TRUE(m4.Matches(d));
  635. EXPECT_FALSE(m4.Matches(d2));
  636. }
  637. // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
  638. TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
  639. int n = 0;
  640. Matcher<const int&> m1 = Ref(n);
  641. Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
  642. int n1 = 0;
  643. EXPECT_TRUE(m2.Matches(n));
  644. EXPECT_FALSE(m2.Matches(n1));
  645. }
  646. // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
  647. TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
  648. Matcher<int> m1 = Eq(0);
  649. Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
  650. EXPECT_TRUE(m2.Matches(0));
  651. EXPECT_FALSE(m2.Matches(1));
  652. }
  653. // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
  654. TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
  655. Matcher<int> m1 = Eq(0);
  656. Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
  657. int n = 0;
  658. EXPECT_TRUE(m2.Matches(n));
  659. n = 1;
  660. EXPECT_FALSE(m2.Matches(n));
  661. }
  662. // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
  663. TEST(SafeMatcherCastTest, FromSameType) {
  664. Matcher<int> m1 = Eq(0);
  665. Matcher<int> m2 = SafeMatcherCast<int>(m1);
  666. EXPECT_TRUE(m2.Matches(0));
  667. EXPECT_FALSE(m2.Matches(1));
  668. }
  669. #if !defined _MSC_VER
  670. namespace convertible_from_any {
  671. TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
  672. Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
  673. EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
  674. EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
  675. }
  676. TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
  677. Matcher<ConvertibleFromAny> m =
  678. SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
  679. EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
  680. EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
  681. }
  682. } // namespace convertible_from_any
  683. #endif // !defined _MSC_VER
  684. TEST(SafeMatcherCastTest, ValueIsNotCopied) {
  685. int n = 42;
  686. Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
  687. // Verify that the matcher holds a reference to n, not to its temporary copy.
  688. EXPECT_TRUE(m.Matches(n));
  689. }
  690. TEST(ExpectThat, TakesLiterals) {
  691. EXPECT_THAT(1, 1);
  692. EXPECT_THAT(1.0, 1.0);
  693. EXPECT_THAT(std::string(), "");
  694. }
  695. TEST(ExpectThat, TakesFunctions) {
  696. struct Helper {
  697. static void Func() {}
  698. };
  699. void (*func)() = Helper::Func;
  700. EXPECT_THAT(func, Helper::Func);
  701. EXPECT_THAT(func, &Helper::Func);
  702. }
  703. // Tests that A<T>() matches any value of type T.
  704. TEST(ATest, MatchesAnyValue) {
  705. // Tests a matcher for a value type.
  706. Matcher<double> m1 = A<double>();
  707. EXPECT_TRUE(m1.Matches(91.43));
  708. EXPECT_TRUE(m1.Matches(-15.32));
  709. // Tests a matcher for a reference type.
  710. int a = 2;
  711. int b = -6;
  712. Matcher<int&> m2 = A<int&>();
  713. EXPECT_TRUE(m2.Matches(a));
  714. EXPECT_TRUE(m2.Matches(b));
  715. }
  716. TEST(ATest, WorksForDerivedClass) {
  717. Base base;
  718. Derived derived;
  719. EXPECT_THAT(&base, A<Base*>());
  720. // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
  721. EXPECT_THAT(&derived, A<Base*>());
  722. EXPECT_THAT(&derived, A<Derived*>());
  723. }
  724. // Tests that A<T>() describes itself properly.
  725. TEST(ATest, CanDescribeSelf) {
  726. EXPECT_EQ("is anything", Describe(A<bool>()));
  727. }
  728. // Tests that An<T>() matches any value of type T.
  729. TEST(AnTest, MatchesAnyValue) {
  730. // Tests a matcher for a value type.
  731. Matcher<int> m1 = An<int>();
  732. EXPECT_TRUE(m1.Matches(9143));
  733. EXPECT_TRUE(m1.Matches(-1532));
  734. // Tests a matcher for a reference type.
  735. int a = 2;
  736. int b = -6;
  737. Matcher<int&> m2 = An<int&>();
  738. EXPECT_TRUE(m2.Matches(a));
  739. EXPECT_TRUE(m2.Matches(b));
  740. }
  741. // Tests that An<T>() describes itself properly.
  742. TEST(AnTest, CanDescribeSelf) {
  743. EXPECT_EQ("is anything", Describe(An<int>()));
  744. }
  745. // Tests that _ can be used as a matcher for any type and matches any
  746. // value of that type.
  747. TEST(UnderscoreTest, MatchesAnyValue) {
  748. // Uses _ as a matcher for a value type.
  749. Matcher<int> m1 = _;
  750. EXPECT_TRUE(m1.Matches(123));
  751. EXPECT_TRUE(m1.Matches(-242));
  752. // Uses _ as a matcher for a reference type.
  753. bool a = false;
  754. const bool b = true;
  755. Matcher<const bool&> m2 = _;
  756. EXPECT_TRUE(m2.Matches(a));
  757. EXPECT_TRUE(m2.Matches(b));
  758. }
  759. // Tests that _ describes itself properly.
  760. TEST(UnderscoreTest, CanDescribeSelf) {
  761. Matcher<int> m = _;
  762. EXPECT_EQ("is anything", Describe(m));
  763. }
  764. // Tests that Eq(x) matches any value equal to x.
  765. TEST(EqTest, MatchesEqualValue) {
  766. // 2 C-strings with same content but different addresses.
  767. const char a1[] = "hi";
  768. const char a2[] = "hi";
  769. Matcher<const char*> m1 = Eq(a1);
  770. EXPECT_TRUE(m1.Matches(a1));
  771. EXPECT_FALSE(m1.Matches(a2));
  772. }
  773. // Tests that Eq(v) describes itself properly.
  774. class Unprintable {
  775. public:
  776. Unprintable() : c_('a') {}
  777. bool operator==(const Unprintable& /* rhs */) const { return true; }
  778. // -Wunused-private-field: dummy accessor for `c_`.
  779. char dummy_c() { return c_; }
  780. private:
  781. char c_;
  782. };
  783. TEST(EqTest, CanDescribeSelf) {
  784. Matcher<Unprintable> m = Eq(Unprintable());
  785. EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
  786. }
  787. // Tests that Eq(v) can be used to match any type that supports
  788. // comparing with type T, where T is v's type.
  789. TEST(EqTest, IsPolymorphic) {
  790. Matcher<int> m1 = Eq(1);
  791. EXPECT_TRUE(m1.Matches(1));
  792. EXPECT_FALSE(m1.Matches(2));
  793. Matcher<char> m2 = Eq(1);
  794. EXPECT_TRUE(m2.Matches('\1'));
  795. EXPECT_FALSE(m2.Matches('a'));
  796. }
  797. // Tests that TypedEq<T>(v) matches values of type T that's equal to v.
  798. TEST(TypedEqTest, ChecksEqualityForGivenType) {
  799. Matcher<char> m1 = TypedEq<char>('a');
  800. EXPECT_TRUE(m1.Matches('a'));
  801. EXPECT_FALSE(m1.Matches('b'));
  802. Matcher<int> m2 = TypedEq<int>(6);
  803. EXPECT_TRUE(m2.Matches(6));
  804. EXPECT_FALSE(m2.Matches(7));
  805. }
  806. // Tests that TypedEq(v) describes itself properly.
  807. TEST(TypedEqTest, CanDescribeSelf) {
  808. EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
  809. }
  810. // Tests that TypedEq<T>(v) has type Matcher<T>.
  811. // Type<T>::IsTypeOf(v) compiles if and only if the type of value v is T, where
  812. // T is a "bare" type (i.e. not in the form of const U or U&). If v's type is
  813. // not T, the compiler will generate a message about "undefined reference".
  814. template <typename T>
  815. struct Type {
  816. static bool IsTypeOf(const T& /* v */) { return true; }
  817. template <typename T2>
  818. static void IsTypeOf(T2 v);
  819. };
  820. TEST(TypedEqTest, HasSpecifiedType) {
  821. // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
  822. Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
  823. Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
  824. }
  825. // Tests that Ge(v) matches anything >= v.
  826. TEST(GeTest, ImplementsGreaterThanOrEqual) {
  827. Matcher<int> m1 = Ge(0);
  828. EXPECT_TRUE(m1.Matches(1));
  829. EXPECT_TRUE(m1.Matches(0));
  830. EXPECT_FALSE(m1.Matches(-1));
  831. }
  832. // Tests that Ge(v) describes itself properly.
  833. TEST(GeTest, CanDescribeSelf) {
  834. Matcher<int> m = Ge(5);
  835. EXPECT_EQ("is >= 5", Describe(m));
  836. }
  837. // Tests that Gt(v) matches anything > v.
  838. TEST(GtTest, ImplementsGreaterThan) {
  839. Matcher<double> m1 = Gt(0);
  840. EXPECT_TRUE(m1.Matches(1.0));
  841. EXPECT_FALSE(m1.Matches(0.0));
  842. EXPECT_FALSE(m1.Matches(-1.0));
  843. }
  844. // Tests that Gt(v) describes itself properly.
  845. TEST(GtTest, CanDescribeSelf) {
  846. Matcher<int> m = Gt(5);
  847. EXPECT_EQ("is > 5", Describe(m));
  848. }
  849. // Tests that Le(v) matches anything <= v.
  850. TEST(LeTest, ImplementsLessThanOrEqual) {
  851. Matcher<char> m1 = Le('b');
  852. EXPECT_TRUE(m1.Matches('a'));
  853. EXPECT_TRUE(m1.Matches('b'));
  854. EXPECT_FALSE(m1.Matches('c'));
  855. }
  856. // Tests that Le(v) describes itself properly.
  857. TEST(LeTest, CanDescribeSelf) {
  858. Matcher<int> m = Le(5);
  859. EXPECT_EQ("is <= 5", Describe(m));
  860. }
  861. // Tests that Lt(v) matches anything < v.
  862. TEST(LtTest, ImplementsLessThan) {
  863. Matcher<const std::string&> m1 = Lt("Hello");
  864. EXPECT_TRUE(m1.Matches("Abc"));
  865. EXPECT_FALSE(m1.Matches("Hello"));
  866. EXPECT_FALSE(m1.Matches("Hello, world!"));
  867. }
  868. // Tests that Lt(v) describes itself properly.
  869. TEST(LtTest, CanDescribeSelf) {
  870. Matcher<int> m = Lt(5);
  871. EXPECT_EQ("is < 5", Describe(m));
  872. }
  873. // Tests that Ne(v) matches anything != v.
  874. TEST(NeTest, ImplementsNotEqual) {
  875. Matcher<int> m1 = Ne(0);
  876. EXPECT_TRUE(m1.Matches(1));
  877. EXPECT_TRUE(m1.Matches(-1));
  878. EXPECT_FALSE(m1.Matches(0));
  879. }
  880. // Tests that Ne(v) describes itself properly.
  881. TEST(NeTest, CanDescribeSelf) {
  882. Matcher<int> m = Ne(5);
  883. EXPECT_EQ("isn't equal to 5", Describe(m));
  884. }
  885. class MoveOnly {
  886. public:
  887. explicit MoveOnly(int i) : i_(i) {}
  888. MoveOnly(const MoveOnly&) = delete;
  889. MoveOnly(MoveOnly&&) = default;
  890. MoveOnly& operator=(const MoveOnly&) = delete;
  891. MoveOnly& operator=(MoveOnly&&) = default;
  892. bool operator==(const MoveOnly& other) const { return i_ == other.i_; }
  893. bool operator!=(const MoveOnly& other) const { return i_ != other.i_; }
  894. bool operator<(const MoveOnly& other) const { return i_ < other.i_; }
  895. bool operator<=(const MoveOnly& other) const { return i_ <= other.i_; }
  896. bool operator>(const MoveOnly& other) const { return i_ > other.i_; }
  897. bool operator>=(const MoveOnly& other) const { return i_ >= other.i_; }
  898. private:
  899. int i_;
  900. };
  901. struct MoveHelper {
  902. MOCK_METHOD1(Call, void(MoveOnly));
  903. };
  904. TEST(ComparisonBaseTest, WorksWithMoveOnly) {
  905. MoveOnly m{0};
  906. MoveHelper helper;
  907. EXPECT_CALL(helper, Call(Eq(ByRef(m))));
  908. helper.Call(MoveOnly(0));
  909. EXPECT_CALL(helper, Call(Ne(ByRef(m))));
  910. helper.Call(MoveOnly(1));
  911. EXPECT_CALL(helper, Call(Le(ByRef(m))));
  912. helper.Call(MoveOnly(0));
  913. EXPECT_CALL(helper, Call(Lt(ByRef(m))));
  914. helper.Call(MoveOnly(-1));
  915. EXPECT_CALL(helper, Call(Ge(ByRef(m))));
  916. helper.Call(MoveOnly(0));
  917. EXPECT_CALL(helper, Call(Gt(ByRef(m))));
  918. helper.Call(MoveOnly(1));
  919. }
  920. // Tests that IsNull() matches any NULL pointer of any type.
  921. TEST(IsNullTest, MatchesNullPointer) {
  922. Matcher<int*> m1 = IsNull();
  923. int* p1 = nullptr;
  924. int n = 0;
  925. EXPECT_TRUE(m1.Matches(p1));
  926. EXPECT_FALSE(m1.Matches(&n));
  927. Matcher<const char*> m2 = IsNull();
  928. const char* p2 = nullptr;
  929. EXPECT_TRUE(m2.Matches(p2));
  930. EXPECT_FALSE(m2.Matches("hi"));
  931. Matcher<void*> m3 = IsNull();
  932. void* p3 = nullptr;
  933. EXPECT_TRUE(m3.Matches(p3));
  934. EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
  935. }
  936. TEST(IsNullTest, StdFunction) {
  937. const Matcher<std::function<void()>> m = IsNull();
  938. EXPECT_TRUE(m.Matches(std::function<void()>()));
  939. EXPECT_FALSE(m.Matches([]{}));
  940. }
  941. // Tests that IsNull() describes itself properly.
  942. TEST(IsNullTest, CanDescribeSelf) {
  943. Matcher<int*> m = IsNull();
  944. EXPECT_EQ("is NULL", Describe(m));
  945. EXPECT_EQ("isn't NULL", DescribeNegation(m));
  946. }
  947. // Tests that NotNull() matches any non-NULL pointer of any type.
  948. TEST(NotNullTest, MatchesNonNullPointer) {
  949. Matcher<int*> m1 = NotNull();
  950. int* p1 = nullptr;
  951. int n = 0;
  952. EXPECT_FALSE(m1.Matches(p1));
  953. EXPECT_TRUE(m1.Matches(&n));
  954. Matcher<const char*> m2 = NotNull();
  955. const char* p2 = nullptr;
  956. EXPECT_FALSE(m2.Matches(p2));
  957. EXPECT_TRUE(m2.Matches("hi"));
  958. }
  959. TEST(NotNullTest, LinkedPtr) {
  960. const Matcher<std::shared_ptr<int>> m = NotNull();
  961. const std::shared_ptr<int> null_p;
  962. const std::shared_ptr<int> non_null_p(new int);
  963. EXPECT_FALSE(m.Matches(null_p));
  964. EXPECT_TRUE(m.Matches(non_null_p));
  965. }
  966. TEST(NotNullTest, ReferenceToConstLinkedPtr) {
  967. const Matcher<const std::shared_ptr<double>&> m = NotNull();
  968. const std::shared_ptr<double> null_p;
  969. const std::shared_ptr<double> non_null_p(new double);
  970. EXPECT_FALSE(m.Matches(null_p));
  971. EXPECT_TRUE(m.Matches(non_null_p));
  972. }
  973. TEST(NotNullTest, StdFunction) {
  974. const Matcher<std::function<void()>> m = NotNull();
  975. EXPECT_TRUE(m.Matches([]{}));
  976. EXPECT_FALSE(m.Matches(std::function<void()>()));
  977. }
  978. // Tests that NotNull() describes itself properly.
  979. TEST(NotNullTest, CanDescribeSelf) {
  980. Matcher<int*> m = NotNull();
  981. EXPECT_EQ("isn't NULL", Describe(m));
  982. }
  983. // Tests that Ref(variable) matches an argument that references
  984. // 'variable'.
  985. TEST(RefTest, MatchesSameVariable) {
  986. int a = 0;
  987. int b = 0;
  988. Matcher<int&> m = Ref(a);
  989. EXPECT_TRUE(m.Matches(a));
  990. EXPECT_FALSE(m.Matches(b));
  991. }
  992. // Tests that Ref(variable) describes itself properly.
  993. TEST(RefTest, CanDescribeSelf) {
  994. int n = 5;
  995. Matcher<int&> m = Ref(n);
  996. stringstream ss;
  997. ss << "references the variable @" << &n << " 5";
  998. EXPECT_EQ(ss.str(), Describe(m));
  999. }
  1000. // Test that Ref(non_const_varialbe) can be used as a matcher for a
  1001. // const reference.
  1002. TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
  1003. int a = 0;
  1004. int b = 0;
  1005. Matcher<const int&> m = Ref(a);
  1006. EXPECT_TRUE(m.Matches(a));
  1007. EXPECT_FALSE(m.Matches(b));
  1008. }
  1009. // Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
  1010. // used wherever Ref(base) can be used (Ref(derived) is a sub-type
  1011. // of Ref(base), but not vice versa.
  1012. TEST(RefTest, IsCovariant) {
  1013. Base base, base2;
  1014. Derived derived;
  1015. Matcher<const Base&> m1 = Ref(base);
  1016. EXPECT_TRUE(m1.Matches(base));
  1017. EXPECT_FALSE(m1.Matches(base2));
  1018. EXPECT_FALSE(m1.Matches(derived));
  1019. m1 = Ref(derived);
  1020. EXPECT_TRUE(m1.Matches(derived));
  1021. EXPECT_FALSE(m1.Matches(base));
  1022. EXPECT_FALSE(m1.Matches(base2));
  1023. }
  1024. TEST(RefTest, ExplainsResult) {
  1025. int n = 0;
  1026. EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
  1027. StartsWith("which is located @"));
  1028. int m = 0;
  1029. EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
  1030. StartsWith("which is located @"));
  1031. }
  1032. // Tests string comparison matchers.
  1033. TEST(StrEqTest, MatchesEqualString) {
  1034. Matcher<const char*> m = StrEq(std::string("Hello"));
  1035. EXPECT_TRUE(m.Matches("Hello"));
  1036. EXPECT_FALSE(m.Matches("hello"));
  1037. EXPECT_FALSE(m.Matches(nullptr));
  1038. Matcher<const std::string&> m2 = StrEq("Hello");
  1039. EXPECT_TRUE(m2.Matches("Hello"));
  1040. EXPECT_FALSE(m2.Matches("Hi"));
  1041. #if GTEST_HAS_ABSL
  1042. Matcher<const absl::string_view&> m3 = StrEq("Hello");
  1043. EXPECT_TRUE(m3.Matches(absl::string_view("Hello")));
  1044. EXPECT_FALSE(m3.Matches(absl::string_view("hello")));
  1045. EXPECT_FALSE(m3.Matches(absl::string_view()));
  1046. Matcher<const absl::string_view&> m_empty = StrEq("");
  1047. EXPECT_TRUE(m_empty.Matches(absl::string_view("")));
  1048. EXPECT_TRUE(m_empty.Matches(absl::string_view()));
  1049. EXPECT_FALSE(m_empty.Matches(absl::string_view("hello")));
  1050. #endif // GTEST_HAS_ABSL
  1051. }
  1052. TEST(StrEqTest, CanDescribeSelf) {
  1053. Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
  1054. EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
  1055. Describe(m));
  1056. std::string str("01204500800");
  1057. str[3] = '\0';
  1058. Matcher<std::string> m2 = StrEq(str);
  1059. EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
  1060. str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
  1061. Matcher<std::string> m3 = StrEq(str);
  1062. EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
  1063. }
  1064. TEST(StrNeTest, MatchesUnequalString) {
  1065. Matcher<const char*> m = StrNe("Hello");
  1066. EXPECT_TRUE(m.Matches(""));
  1067. EXPECT_TRUE(m.Matches(nullptr));
  1068. EXPECT_FALSE(m.Matches("Hello"));
  1069. Matcher<std::string> m2 = StrNe(std::string("Hello"));
  1070. EXPECT_TRUE(m2.Matches("hello"));
  1071. EXPECT_FALSE(m2.Matches("Hello"));
  1072. #if GTEST_HAS_ABSL
  1073. Matcher<const absl::string_view> m3 = StrNe("Hello");
  1074. EXPECT_TRUE(m3.Matches(absl::string_view("")));
  1075. EXPECT_TRUE(m3.Matches(absl::string_view()));
  1076. EXPECT_FALSE(m3.Matches(absl::string_view("Hello")));
  1077. #endif // GTEST_HAS_ABSL
  1078. }
  1079. TEST(StrNeTest, CanDescribeSelf) {
  1080. Matcher<const char*> m = StrNe("Hi");
  1081. EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
  1082. }
  1083. TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
  1084. Matcher<const char*> m = StrCaseEq(std::string("Hello"));
  1085. EXPECT_TRUE(m.Matches("Hello"));
  1086. EXPECT_TRUE(m.Matches("hello"));
  1087. EXPECT_FALSE(m.Matches("Hi"));
  1088. EXPECT_FALSE(m.Matches(nullptr));
  1089. Matcher<const std::string&> m2 = StrCaseEq("Hello");
  1090. EXPECT_TRUE(m2.Matches("hello"));
  1091. EXPECT_FALSE(m2.Matches("Hi"));
  1092. #if GTEST_HAS_ABSL
  1093. Matcher<const absl::string_view&> m3 = StrCaseEq(std::string("Hello"));
  1094. EXPECT_TRUE(m3.Matches(absl::string_view("Hello")));
  1095. EXPECT_TRUE(m3.Matches(absl::string_view("hello")));
  1096. EXPECT_FALSE(m3.Matches(absl::string_view("Hi")));
  1097. EXPECT_FALSE(m3.Matches(absl::string_view()));
  1098. #endif // GTEST_HAS_ABSL
  1099. }
  1100. TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
  1101. std::string str1("oabocdooeoo");
  1102. std::string str2("OABOCDOOEOO");
  1103. Matcher<const std::string&> m0 = StrCaseEq(str1);
  1104. EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0')));
  1105. str1[3] = str2[3] = '\0';
  1106. Matcher<const std::string&> m1 = StrCaseEq(str1);
  1107. EXPECT_TRUE(m1.Matches(str2));
  1108. str1[0] = str1[6] = str1[7] = str1[10] = '\0';
  1109. str2[0] = str2[6] = str2[7] = str2[10] = '\0';
  1110. Matcher<const std::string&> m2 = StrCaseEq(str1);
  1111. str1[9] = str2[9] = '\0';
  1112. EXPECT_FALSE(m2.Matches(str2));
  1113. Matcher<const std::string&> m3 = StrCaseEq(str1);
  1114. EXPECT_TRUE(m3.Matches(str2));
  1115. EXPECT_FALSE(m3.Matches(str2 + "x"));
  1116. str2.append(1, '\0');
  1117. EXPECT_FALSE(m3.Matches(str2));
  1118. EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9)));
  1119. }
  1120. TEST(StrCaseEqTest, CanDescribeSelf) {
  1121. Matcher<std::string> m = StrCaseEq("Hi");
  1122. EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
  1123. }
  1124. TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
  1125. Matcher<const char*> m = StrCaseNe("Hello");
  1126. EXPECT_TRUE(m.Matches("Hi"));
  1127. EXPECT_TRUE(m.Matches(nullptr));
  1128. EXPECT_FALSE(m.Matches("Hello"));
  1129. EXPECT_FALSE(m.Matches("hello"));
  1130. Matcher<std::string> m2 = StrCaseNe(std::string("Hello"));
  1131. EXPECT_TRUE(m2.Matches(""));
  1132. EXPECT_FALSE(m2.Matches("Hello"));
  1133. #if GTEST_HAS_ABSL
  1134. Matcher<const absl::string_view> m3 = StrCaseNe("Hello");
  1135. EXPECT_TRUE(m3.Matches(absl::string_view("Hi")));
  1136. EXPECT_TRUE(m3.Matches(absl::string_view()));
  1137. EXPECT_FALSE(m3.Matches(absl::string_view("Hello")));
  1138. EXPECT_FALSE(m3.Matches(absl::string_view("hello")));
  1139. #endif // GTEST_HAS_ABSL
  1140. }
  1141. TEST(StrCaseNeTest, CanDescribeSelf) {
  1142. Matcher<const char*> m = StrCaseNe("Hi");
  1143. EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
  1144. }
  1145. // Tests that HasSubstr() works for matching string-typed values.
  1146. TEST(HasSubstrTest, WorksForStringClasses) {
  1147. const Matcher<std::string> m1 = HasSubstr("foo");
  1148. EXPECT_TRUE(m1.Matches(std::string("I love food.")));
  1149. EXPECT_FALSE(m1.Matches(std::string("tofo")));
  1150. const Matcher<const std::string&> m2 = HasSubstr("foo");
  1151. EXPECT_TRUE(m2.Matches(std::string("I love food.")));
  1152. EXPECT_FALSE(m2.Matches(std::string("tofo")));
  1153. const Matcher<std::string> m_empty = HasSubstr("");
  1154. EXPECT_TRUE(m_empty.Matches(std::string()));
  1155. EXPECT_TRUE(m_empty.Matches(std::string("not empty")));
  1156. }
  1157. // Tests that HasSubstr() works for matching C-string-typed values.
  1158. TEST(HasSubstrTest, WorksForCStrings) {
  1159. const Matcher<char*> m1 = HasSubstr("foo");
  1160. EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
  1161. EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
  1162. EXPECT_FALSE(m1.Matches(nullptr));
  1163. const Matcher<const char*> m2 = HasSubstr("foo");
  1164. EXPECT_TRUE(m2.Matches("I love food."));
  1165. EXPECT_FALSE(m2.Matches("tofo"));
  1166. EXPECT_FALSE(m2.Matches(nullptr));
  1167. const Matcher<const char*> m_empty = HasSubstr("");
  1168. EXPECT_TRUE(m_empty.Matches("not empty"));
  1169. EXPECT_TRUE(m_empty.Matches(""));
  1170. EXPECT_FALSE(m_empty.Matches(nullptr));
  1171. }
  1172. #if GTEST_HAS_ABSL
  1173. // Tests that HasSubstr() works for matching absl::string_view-typed values.
  1174. TEST(HasSubstrTest, WorksForStringViewClasses) {
  1175. const Matcher<absl::string_view> m1 = HasSubstr("foo");
  1176. EXPECT_TRUE(m1.Matches(absl::string_view("I love food.")));
  1177. EXPECT_FALSE(m1.Matches(absl::string_view("tofo")));
  1178. EXPECT_FALSE(m1.Matches(absl::string_view()));
  1179. const Matcher<const absl::string_view&> m2 = HasSubstr("foo");
  1180. EXPECT_TRUE(m2.Matches(absl::string_view("I love food.")));
  1181. EXPECT_FALSE(m2.Matches(absl::string_view("tofo")));
  1182. EXPECT_FALSE(m2.Matches(absl::string_view()));
  1183. const Matcher<const absl::string_view&> m3 = HasSubstr("");
  1184. EXPECT_TRUE(m3.Matches(absl::string_view("foo")));
  1185. EXPECT_TRUE(m3.Matches(absl::string_view("")));
  1186. EXPECT_TRUE(m3.Matches(absl::string_view()));
  1187. }
  1188. #endif // GTEST_HAS_ABSL
  1189. // Tests that HasSubstr(s) describes itself properly.
  1190. TEST(HasSubstrTest, CanDescribeSelf) {
  1191. Matcher<std::string> m = HasSubstr("foo\n\"");
  1192. EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
  1193. }
  1194. TEST(KeyTest, CanDescribeSelf) {
  1195. Matcher<const pair<std::string, int>&> m = Key("foo");
  1196. EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
  1197. EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
  1198. }
  1199. TEST(KeyTest, ExplainsResult) {
  1200. Matcher<pair<int, bool> > m = Key(GreaterThan(10));
  1201. EXPECT_EQ("whose first field is a value which is 5 less than 10",
  1202. Explain(m, make_pair(5, true)));
  1203. EXPECT_EQ("whose first field is a value which is 5 more than 10",
  1204. Explain(m, make_pair(15, true)));
  1205. }
  1206. TEST(KeyTest, MatchesCorrectly) {
  1207. pair<int, std::string> p(25, "foo");
  1208. EXPECT_THAT(p, Key(25));
  1209. EXPECT_THAT(p, Not(Key(42)));
  1210. EXPECT_THAT(p, Key(Ge(20)));
  1211. EXPECT_THAT(p, Not(Key(Lt(25))));
  1212. }
  1213. TEST(KeyTest, WorksWithMoveOnly) {
  1214. pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
  1215. EXPECT_THAT(p, Key(Eq(nullptr)));
  1216. }
  1217. template <size_t I>
  1218. struct Tag {};
  1219. struct PairWithGet {
  1220. int member_1;
  1221. std::string member_2;
  1222. using first_type = int;
  1223. using second_type = std::string;
  1224. const int& GetImpl(Tag<0>) const { return member_1; }
  1225. const std::string& GetImpl(Tag<1>) const { return member_2; }
  1226. };
  1227. template <size_t I>
  1228. auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag<I>())) {
  1229. return value.GetImpl(Tag<I>());
  1230. }
  1231. TEST(PairTest, MatchesPairWithGetCorrectly) {
  1232. PairWithGet p{25, "foo"};
  1233. EXPECT_THAT(p, Key(25));
  1234. EXPECT_THAT(p, Not(Key(42)));
  1235. EXPECT_THAT(p, Key(Ge(20)));
  1236. EXPECT_THAT(p, Not(Key(Lt(25))));
  1237. std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
  1238. EXPECT_THAT(v, Contains(Key(29)));
  1239. }
  1240. TEST(KeyTest, SafelyCastsInnerMatcher) {
  1241. Matcher<int> is_positive = Gt(0);
  1242. Matcher<int> is_negative = Lt(0);
  1243. pair<char, bool> p('a', true);
  1244. EXPECT_THAT(p, Key(is_positive));
  1245. EXPECT_THAT(p, Not(Key(is_negative)));
  1246. }
  1247. TEST(KeyTest, InsideContainsUsingMap) {
  1248. map<int, char> container;
  1249. container.insert(make_pair(1, 'a'));
  1250. container.insert(make_pair(2, 'b'));
  1251. container.insert(make_pair(4, 'c'));
  1252. EXPECT_THAT(container, Contains(Key(1)));
  1253. EXPECT_THAT(container, Not(Contains(Key(3))));
  1254. }
  1255. TEST(KeyTest, InsideContainsUsingMultimap) {
  1256. multimap<int, char> container;
  1257. container.insert(make_pair(1, 'a'));
  1258. container.insert(make_pair(2, 'b'));
  1259. container.insert(make_pair(4, 'c'));
  1260. EXPECT_THAT(container, Not(Contains(Key(25))));
  1261. container.insert(make_pair(25, 'd'));
  1262. EXPECT_THAT(container, Contains(Key(25)));
  1263. container.insert(make_pair(25, 'e'));
  1264. EXPECT_THAT(container, Contains(Key(25)));
  1265. EXPECT_THAT(container, Contains(Key(1)));
  1266. EXPECT_THAT(container, Not(Contains(Key(3))));
  1267. }
  1268. TEST(PairTest, Typing) {
  1269. // Test verifies the following type conversions can be compiled.
  1270. Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
  1271. Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
  1272. Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
  1273. Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
  1274. Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
  1275. }
  1276. TEST(PairTest, CanDescribeSelf) {
  1277. Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
  1278. EXPECT_EQ("has a first field that is equal to \"foo\""
  1279. ", and has a second field that is equal to 42",
  1280. Describe(m1));
  1281. EXPECT_EQ("has a first field that isn't equal to \"foo\""
  1282. ", or has a second field that isn't equal to 42",
  1283. DescribeNegation(m1));
  1284. // Double and triple negation (1 or 2 times not and description of negation).
  1285. Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
  1286. EXPECT_EQ("has a first field that isn't equal to 13"
  1287. ", and has a second field that is equal to 42",
  1288. DescribeNegation(m2));
  1289. }
  1290. TEST(PairTest, CanExplainMatchResultTo) {
  1291. // If neither field matches, Pair() should explain about the first
  1292. // field.
  1293. const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
  1294. EXPECT_EQ("whose first field does not match, which is 1 less than 0",
  1295. Explain(m, make_pair(-1, -2)));
  1296. // If the first field matches but the second doesn't, Pair() should
  1297. // explain about the second field.
  1298. EXPECT_EQ("whose second field does not match, which is 2 less than 0",
  1299. Explain(m, make_pair(1, -2)));
  1300. // If the first field doesn't match but the second does, Pair()
  1301. // should explain about the first field.
  1302. EXPECT_EQ("whose first field does not match, which is 1 less than 0",
  1303. Explain(m, make_pair(-1, 2)));
  1304. // If both fields match, Pair() should explain about them both.
  1305. EXPECT_EQ("whose both fields match, where the first field is a value "
  1306. "which is 1 more than 0, and the second field is a value "
  1307. "which is 2 more than 0",
  1308. Explain(m, make_pair(1, 2)));
  1309. // If only the first match has an explanation, only this explanation should
  1310. // be printed.
  1311. const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
  1312. EXPECT_EQ("whose both fields match, where the first field is a value "
  1313. "which is 1 more than 0",
  1314. Explain(explain_first, make_pair(1, 0)));
  1315. // If only the second match has an explanation, only this explanation should
  1316. // be printed.
  1317. const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
  1318. EXPECT_EQ("whose both fields match, where the second field is a value "
  1319. "which is 1 more than 0",
  1320. Explain(explain_second, make_pair(0, 1)));
  1321. }
  1322. TEST(PairTest, MatchesCorrectly) {
  1323. pair<int, std::string> p(25, "foo");
  1324. // Both fields match.
  1325. EXPECT_THAT(p, Pair(25, "foo"));
  1326. EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
  1327. // 'first' doesnt' match, but 'second' matches.
  1328. EXPECT_THAT(p, Not(Pair(42, "foo")));
  1329. EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
  1330. // 'first' matches, but 'second' doesn't match.
  1331. EXPECT_THAT(p, Not(Pair(25, "bar")));
  1332. EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
  1333. // Neither field matches.
  1334. EXPECT_THAT(p, Not(Pair(13, "bar")));
  1335. EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
  1336. }
  1337. TEST(PairTest, WorksWithMoveOnly) {
  1338. pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
  1339. p.second.reset(new int(7));
  1340. EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr)));
  1341. }
  1342. TEST(PairTest, SafelyCastsInnerMatchers) {
  1343. Matcher<int> is_positive = Gt(0);
  1344. Matcher<int> is_negative = Lt(0);
  1345. pair<char, bool> p('a', true);
  1346. EXPECT_THAT(p, Pair(is_positive, _));
  1347. EXPECT_THAT(p, Not(Pair(is_negative, _)));
  1348. EXPECT_THAT(p, Pair(_, is_positive));
  1349. EXPECT_THAT(p, Not(Pair(_, is_negative)));
  1350. }
  1351. TEST(PairTest, InsideContainsUsingMap) {
  1352. map<int, char> container;
  1353. container.insert(make_pair(1, 'a'));
  1354. container.insert(make_pair(2, 'b'));
  1355. container.insert(make_pair(4, 'c'));
  1356. EXPECT_THAT(container, Contains(Pair(1, 'a')));
  1357. EXPECT_THAT(container, Contains(Pair(1, _)));
  1358. EXPECT_THAT(container, Contains(Pair(_, 'a')));
  1359. EXPECT_THAT(container, Not(Contains(Pair(3, _))));
  1360. }
  1361. TEST(ContainsTest, WorksWithMoveOnly) {
  1362. ContainerHelper helper;
  1363. EXPECT_CALL(helper, Call(Contains(Pointee(2))));
  1364. helper.Call(MakeUniquePtrs({1, 2}));
  1365. }
  1366. TEST(PairTest, UseGetInsteadOfMembers) {
  1367. PairWithGet pair{7, "ABC"};
  1368. EXPECT_THAT(pair, Pair(7, "ABC"));
  1369. EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB")));
  1370. EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC")));
  1371. std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
  1372. EXPECT_THAT(v,
  1373. ElementsAre(Pair(11, std::string("Foo")), Pair(Ge(10), Not(""))));
  1374. }
  1375. // Tests StartsWith(s).
  1376. TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
  1377. const Matcher<const char*> m1 = StartsWith(std::string(""));
  1378. EXPECT_TRUE(m1.Matches("Hi"));
  1379. EXPECT_TRUE(m1.Matches(""));
  1380. EXPECT_FALSE(m1.Matches(nullptr));
  1381. const Matcher<const std::string&> m2 = StartsWith("Hi");
  1382. EXPECT_TRUE(m2.Matches("Hi"));
  1383. EXPECT_TRUE(m2.Matches("Hi Hi!"));
  1384. EXPECT_TRUE(m2.Matches("High"));
  1385. EXPECT_FALSE(m2.Matches("H"));
  1386. EXPECT_FALSE(m2.Matches(" Hi"));
  1387. #if GTEST_HAS_ABSL
  1388. const Matcher<absl::string_view> m_empty = StartsWith("");
  1389. EXPECT_TRUE(m_empty.Matches(absl::string_view()));
  1390. EXPECT_TRUE(m_empty.Matches(absl::string_view("")));
  1391. EXPECT_TRUE(m_empty.Matches(absl::string_view("not empty")));
  1392. #endif // GTEST_HAS_ABSL
  1393. }
  1394. TEST(StartsWithTest, CanDescribeSelf) {
  1395. Matcher<const std::string> m = StartsWith("Hi");
  1396. EXPECT_EQ("starts with \"Hi\"", Describe(m));
  1397. }
  1398. // Tests EndsWith(s).
  1399. TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
  1400. const Matcher<const char*> m1 = EndsWith("");
  1401. EXPECT_TRUE(m1.Matches("Hi"));
  1402. EXPECT_TRUE(m1.Matches(""));
  1403. EXPECT_FALSE(m1.Matches(nullptr));
  1404. const Matcher<const std::string&> m2 = EndsWith(std::string("Hi"));
  1405. EXPECT_TRUE(m2.Matches("Hi"));
  1406. EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
  1407. EXPECT_TRUE(m2.Matches("Super Hi"));
  1408. EXPECT_FALSE(m2.Matches("i"));
  1409. EXPECT_FALSE(m2.Matches("Hi "));
  1410. #if GTEST_HAS_ABSL
  1411. const Matcher<const absl::string_view&> m4 = EndsWith("");
  1412. EXPECT_TRUE(m4.Matches("Hi"));
  1413. EXPECT_TRUE(m4.Matches(""));
  1414. EXPECT_TRUE(m4.Matches(absl::string_view()));
  1415. EXPECT_TRUE(m4.Matches(absl::string_view("")));
  1416. #endif // GTEST_HAS_ABSL
  1417. }
  1418. TEST(EndsWithTest, CanDescribeSelf) {
  1419. Matcher<const std::string> m = EndsWith("Hi");
  1420. EXPECT_EQ("ends with \"Hi\"", Describe(m));
  1421. }
  1422. // Tests MatchesRegex().
  1423. TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
  1424. const Matcher<const char*> m1 = MatchesRegex("a.*z");
  1425. EXPECT_TRUE(m1.Matches("az"));
  1426. EXPECT_TRUE(m1.Matches("abcz"));
  1427. EXPECT_FALSE(m1.Matches(nullptr));
  1428. const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z"));
  1429. EXPECT_TRUE(m2.Matches("azbz"));
  1430. EXPECT_FALSE(m2.Matches("az1"));
  1431. EXPECT_FALSE(m2.Matches("1az"));
  1432. #if GTEST_HAS_ABSL
  1433. const Matcher<const absl::string_view&> m3 = MatchesRegex("a.*z");
  1434. EXPECT_TRUE(m3.Matches(absl::string_view("az")));
  1435. EXPECT_TRUE(m3.Matches(absl::string_view("abcz")));
  1436. EXPECT_FALSE(m3.Matches(absl::string_view("1az")));
  1437. EXPECT_FALSE(m3.Matches(absl::string_view()));
  1438. const Matcher<const absl::string_view&> m4 = MatchesRegex("");
  1439. EXPECT_TRUE(m4.Matches(absl::string_view("")));
  1440. EXPECT_TRUE(m4.Matches(absl::string_view()));
  1441. #endif // GTEST_HAS_ABSL
  1442. }
  1443. TEST(MatchesRegexTest, CanDescribeSelf) {
  1444. Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*"));
  1445. EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
  1446. Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
  1447. EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
  1448. #if GTEST_HAS_ABSL
  1449. Matcher<const absl::string_view> m3 = MatchesRegex(new RE("0.*"));
  1450. EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3));
  1451. #endif // GTEST_HAS_ABSL
  1452. }
  1453. // Tests ContainsRegex().
  1454. TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
  1455. const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z"));
  1456. EXPECT_TRUE(m1.Matches("az"));
  1457. EXPECT_TRUE(m1.Matches("0abcz1"));
  1458. EXPECT_FALSE(m1.Matches(nullptr));
  1459. const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z"));
  1460. EXPECT_TRUE(m2.Matches("azbz"));
  1461. EXPECT_TRUE(m2.Matches("az1"));
  1462. EXPECT_FALSE(m2.Matches("1a"));
  1463. #if GTEST_HAS_ABSL
  1464. const Matcher<const absl::string_view&> m3 = ContainsRegex(new RE("a.*z"));
  1465. EXPECT_TRUE(m3.Matches(absl::string_view("azbz")));
  1466. EXPECT_TRUE(m3.Matches(absl::string_view("az1")));
  1467. EXPECT_FALSE(m3.Matches(absl::string_view("1a")));
  1468. EXPECT_FALSE(m3.Matches(absl::string_view()));
  1469. const Matcher<const absl::string_view&> m4 = ContainsRegex("");
  1470. EXPECT_TRUE(m4.Matches(absl::string_view("")));
  1471. EXPECT_TRUE(m4.Matches(absl::string_view()));
  1472. #endif // GTEST_HAS_ABSL
  1473. }
  1474. TEST(ContainsRegexTest, CanDescribeSelf) {
  1475. Matcher<const std::string> m1 = ContainsRegex("Hi.*");
  1476. EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
  1477. Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
  1478. EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
  1479. #if GTEST_HAS_ABSL
  1480. Matcher<const absl::string_view> m3 = ContainsRegex(new RE("0.*"));
  1481. EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3));
  1482. #endif // GTEST_HAS_ABSL
  1483. }
  1484. // Tests for wide strings.
  1485. #if GTEST_HAS_STD_WSTRING
  1486. TEST(StdWideStrEqTest, MatchesEqual) {
  1487. Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
  1488. EXPECT_TRUE(m.Matches(L"Hello"));
  1489. EXPECT_FALSE(m.Matches(L"hello"));
  1490. EXPECT_FALSE(m.Matches(nullptr));
  1491. Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
  1492. EXPECT_TRUE(m2.Matches(L"Hello"));
  1493. EXPECT_FALSE(m2.Matches(L"Hi"));
  1494. Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
  1495. EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
  1496. EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
  1497. ::std::wstring str(L"01204500800");
  1498. str[3] = L'\0';
  1499. Matcher<const ::std::wstring&> m4 = StrEq(str);
  1500. EXPECT_TRUE(m4.Matches(str));
  1501. str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
  1502. Matcher<const ::std::wstring&> m5 = StrEq(str);
  1503. EXPECT_TRUE(m5.Matches(str));
  1504. }
  1505. TEST(StdWideStrEqTest, CanDescribeSelf) {
  1506. Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
  1507. EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
  1508. Describe(m));
  1509. Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
  1510. EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
  1511. Describe(m2));
  1512. ::std::wstring str(L"01204500800");
  1513. str[3] = L'\0';
  1514. Matcher<const ::std::wstring&> m4 = StrEq(str);
  1515. EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
  1516. str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
  1517. Matcher<const ::std::wstring&> m5 = StrEq(str);
  1518. EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
  1519. }
  1520. TEST(StdWideStrNeTest, MatchesUnequalString) {
  1521. Matcher<const wchar_t*> m = StrNe(L"Hello");
  1522. EXPECT_TRUE(m.Matches(L""));
  1523. EXPECT_TRUE(m.Matches(nullptr));
  1524. EXPECT_FALSE(m.Matches(L"Hello"));
  1525. Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
  1526. EXPECT_TRUE(m2.Matches(L"hello"));
  1527. EXPECT_FALSE(m2.Matches(L"Hello"));
  1528. }
  1529. TEST(StdWideStrNeTest, CanDescribeSelf) {
  1530. Matcher<const wchar_t*> m = StrNe(L"Hi");
  1531. EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
  1532. }
  1533. TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
  1534. Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
  1535. EXPECT_TRUE(m.Matches(L"Hello"));
  1536. EXPECT_TRUE(m.Matches(L"hello"));
  1537. EXPECT_FALSE(m.Matches(L"Hi"));
  1538. EXPECT_FALSE(m.Matches(nullptr));
  1539. Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
  1540. EXPECT_TRUE(m2.Matches(L"hello"));
  1541. EXPECT_FALSE(m2.Matches(L"Hi"));
  1542. }
  1543. TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
  1544. ::std::wstring str1(L"oabocdooeoo");
  1545. ::std::wstring str2(L"OABOCDOOEOO");
  1546. Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
  1547. EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
  1548. str1[3] = str2[3] = L'\0';
  1549. Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
  1550. EXPECT_TRUE(m1.Matches(str2));
  1551. str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
  1552. str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
  1553. Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
  1554. str1[9] = str2[9] = L'\0';
  1555. EXPECT_FALSE(m2.Matches(str2));
  1556. Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
  1557. EXPECT_TRUE(m3.Matches(str2));
  1558. EXPECT_FALSE(m3.Matches(str2 + L"x"));
  1559. str2.append(1, L'\0');
  1560. EXPECT_FALSE(m3.Matches(str2));
  1561. EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
  1562. }
  1563. TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
  1564. Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
  1565. EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
  1566. }
  1567. TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
  1568. Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
  1569. EXPECT_TRUE(m.Matches(L"Hi"));
  1570. EXPECT_TRUE(m.Matches(nullptr));
  1571. EXPECT_FALSE(m.Matches(L"Hello"));
  1572. EXPECT_FALSE(m.Matches(L"hello"));
  1573. Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
  1574. EXPECT_TRUE(m2.Matches(L""));
  1575. EXPECT_FALSE(m2.Matches(L"Hello"));
  1576. }
  1577. TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
  1578. Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
  1579. EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
  1580. }
  1581. // Tests that HasSubstr() works for matching wstring-typed values.
  1582. TEST(StdWideHasSubstrTest, WorksForStringClasses) {
  1583. const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
  1584. EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
  1585. EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
  1586. const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
  1587. EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
  1588. EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
  1589. }
  1590. // Tests that HasSubstr() works for matching C-wide-string-typed values.
  1591. TEST(StdWideHasSubstrTest, WorksForCStrings) {
  1592. const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
  1593. EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
  1594. EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
  1595. EXPECT_FALSE(m1.Matches(nullptr));
  1596. const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
  1597. EXPECT_TRUE(m2.Matches(L"I love food."));
  1598. EXPECT_FALSE(m2.Matches(L"tofo"));
  1599. EXPECT_FALSE(m2.Matches(nullptr));
  1600. }
  1601. // Tests that HasSubstr(s) describes itself properly.
  1602. TEST(StdWideHasSubstrTest, CanDescribeSelf) {
  1603. Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
  1604. EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
  1605. }
  1606. // Tests StartsWith(s).
  1607. TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
  1608. const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
  1609. EXPECT_TRUE(m1.Matches(L"Hi"));
  1610. EXPECT_TRUE(m1.Matches(L""));
  1611. EXPECT_FALSE(m1.Matches(nullptr));
  1612. const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
  1613. EXPECT_TRUE(m2.Matches(L"Hi"));
  1614. EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
  1615. EXPECT_TRUE(m2.Matches(L"High"));
  1616. EXPECT_FALSE(m2.Matches(L"H"));
  1617. EXPECT_FALSE(m2.Matches(L" Hi"));
  1618. }
  1619. TEST(StdWideStartsWithTest, CanDescribeSelf) {
  1620. Matcher<const ::std::wstring> m = StartsWith(L"Hi");
  1621. EXPECT_EQ("starts with L\"Hi\"", Describe(m));
  1622. }
  1623. // Tests EndsWith(s).
  1624. TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
  1625. const Matcher<const wchar_t*> m1 = EndsWith(L"");
  1626. EXPECT_TRUE(m1.Matches(L"Hi"));
  1627. EXPECT_TRUE(m1.Matches(L""));
  1628. EXPECT_FALSE(m1.Matches(nullptr));
  1629. const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
  1630. EXPECT_TRUE(m2.Matches(L"Hi"));
  1631. EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
  1632. EXPECT_TRUE(m2.Matches(L"Super Hi"));
  1633. EXPECT_FALSE(m2.Matches(L"i"));
  1634. EXPECT_FALSE(m2.Matches(L"Hi "));
  1635. }
  1636. TEST(StdWideEndsWithTest, CanDescribeSelf) {
  1637. Matcher<const ::std::wstring> m = EndsWith(L"Hi");
  1638. EXPECT_EQ("ends with L\"Hi\"", Describe(m));
  1639. }
  1640. #endif // GTEST_HAS_STD_WSTRING
  1641. typedef ::std::tuple<long, int> Tuple2; // NOLINT
  1642. // Tests that Eq() matches a 2-tuple where the first field == the
  1643. // second field.
  1644. TEST(Eq2Test, MatchesEqualArguments) {
  1645. Matcher<const Tuple2&> m = Eq();
  1646. EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
  1647. EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
  1648. }
  1649. // Tests that Eq() describes itself properly.
  1650. TEST(Eq2Test, CanDescribeSelf) {
  1651. Matcher<const Tuple2&> m = Eq();
  1652. EXPECT_EQ("are an equal pair", Describe(m));
  1653. }
  1654. // Tests that Ge() matches a 2-tuple where the first field >= the
  1655. // second field.
  1656. TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
  1657. Matcher<const Tuple2&> m = Ge();
  1658. EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
  1659. EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
  1660. EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
  1661. }
  1662. // Tests that Ge() describes itself properly.
  1663. TEST(Ge2Test, CanDescribeSelf) {
  1664. Matcher<const Tuple2&> m = Ge();
  1665. EXPECT_EQ("are a pair where the first >= the second", Describe(m));
  1666. }
  1667. // Tests that Gt() matches a 2-tuple where the first field > the
  1668. // second field.
  1669. TEST(Gt2Test, MatchesGreaterThanArguments) {
  1670. Matcher<const Tuple2&> m = Gt();
  1671. EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
  1672. EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
  1673. EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
  1674. }
  1675. // Tests that Gt() describes itself properly.
  1676. TEST(Gt2Test, CanDescribeSelf) {
  1677. Matcher<const Tuple2&> m = Gt();
  1678. EXPECT_EQ("are a pair where the first > the second", Describe(m));
  1679. }
  1680. // Tests that Le() matches a 2-tuple where the first field <= the
  1681. // second field.
  1682. TEST(Le2Test, MatchesLessThanOrEqualArguments) {
  1683. Matcher<const Tuple2&> m = Le();
  1684. EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
  1685. EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
  1686. EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
  1687. }
  1688. // Tests that Le() describes itself properly.
  1689. TEST(Le2Test, CanDescribeSelf) {
  1690. Matcher<const Tuple2&> m = Le();
  1691. EXPECT_EQ("are a pair where the first <= the second", Describe(m));
  1692. }
  1693. // Tests that Lt() matches a 2-tuple where the first field < the
  1694. // second field.
  1695. TEST(Lt2Test, MatchesLessThanArguments) {
  1696. Matcher<const Tuple2&> m = Lt();
  1697. EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
  1698. EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
  1699. EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
  1700. }
  1701. // Tests that Lt() describes itself properly.
  1702. TEST(Lt2Test, CanDescribeSelf) {
  1703. Matcher<const Tuple2&> m = Lt();
  1704. EXPECT_EQ("are a pair where the first < the second", Describe(m));
  1705. }
  1706. // Tests that Ne() matches a 2-tuple where the first field != the
  1707. // second field.
  1708. TEST(Ne2Test, MatchesUnequalArguments) {
  1709. Matcher<const Tuple2&> m = Ne();
  1710. EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
  1711. EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
  1712. EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
  1713. }
  1714. // Tests that Ne() describes itself properly.
  1715. TEST(Ne2Test, CanDescribeSelf) {
  1716. Matcher<const Tuple2&> m = Ne();
  1717. EXPECT_EQ("are an unequal pair", Describe(m));
  1718. }
  1719. TEST(PairMatchBaseTest, WorksWithMoveOnly) {
  1720. using Pointers = std::tuple<std::unique_ptr<int>, std::unique_ptr<int>>;
  1721. Matcher<Pointers> matcher = Eq();
  1722. Pointers pointers;
  1723. // Tested values don't matter; the point is that matcher does not copy the
  1724. // matched values.
  1725. EXPECT_TRUE(matcher.Matches(pointers));
  1726. }
  1727. // Tests that FloatEq() matches a 2-tuple where
  1728. // FloatEq(first field) matches the second field.
  1729. TEST(FloatEq2Test, MatchesEqualArguments) {
  1730. typedef ::std::tuple<float, float> Tpl;
  1731. Matcher<const Tpl&> m = FloatEq();
  1732. EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
  1733. EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f)));
  1734. EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
  1735. }
  1736. // Tests that FloatEq() describes itself properly.
  1737. TEST(FloatEq2Test, CanDescribeSelf) {
  1738. Matcher<const ::std::tuple<float, float>&> m = FloatEq();
  1739. EXPECT_EQ("are an almost-equal pair", Describe(m));
  1740. }
  1741. // Tests that NanSensitiveFloatEq() matches a 2-tuple where
  1742. // NanSensitiveFloatEq(first field) matches the second field.
  1743. TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) {
  1744. typedef ::std::tuple<float, float> Tpl;
  1745. Matcher<const Tpl&> m = NanSensitiveFloatEq();
  1746. EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
  1747. EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
  1748. std::numeric_limits<float>::quiet_NaN())));
  1749. EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
  1750. EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
  1751. EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
  1752. }
  1753. // Tests that NanSensitiveFloatEq() describes itself properly.
  1754. TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) {
  1755. Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatEq();
  1756. EXPECT_EQ("are an almost-equal pair", Describe(m));
  1757. }
  1758. // Tests that DoubleEq() matches a 2-tuple where
  1759. // DoubleEq(first field) matches the second field.
  1760. TEST(DoubleEq2Test, MatchesEqualArguments) {
  1761. typedef ::std::tuple<double, double> Tpl;
  1762. Matcher<const Tpl&> m = DoubleEq();
  1763. EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
  1764. EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1)));
  1765. EXPECT_FALSE(m.Matches(Tpl(1.1, 1.0)));
  1766. }
  1767. // Tests that DoubleEq() describes itself properly.
  1768. TEST(DoubleEq2Test, CanDescribeSelf) {
  1769. Matcher<const ::std::tuple<double, double>&> m = DoubleEq();
  1770. EXPECT_EQ("are an almost-equal pair", Describe(m));
  1771. }
  1772. // Tests that NanSensitiveDoubleEq() matches a 2-tuple where
  1773. // NanSensitiveDoubleEq(first field) matches the second field.
  1774. TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) {
  1775. typedef ::std::tuple<double, double> Tpl;
  1776. Matcher<const Tpl&> m = NanSensitiveDoubleEq();
  1777. EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
  1778. EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
  1779. std::numeric_limits<double>::quiet_NaN())));
  1780. EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
  1781. EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
  1782. EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
  1783. }
  1784. // Tests that DoubleEq() describes itself properly.
  1785. TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) {
  1786. Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleEq();
  1787. EXPECT_EQ("are an almost-equal pair", Describe(m));
  1788. }
  1789. // Tests that FloatEq() matches a 2-tuple where
  1790. // FloatNear(first field, max_abs_error) matches the second field.
  1791. TEST(FloatNear2Test, MatchesEqualArguments) {
  1792. typedef ::std::tuple<float, float> Tpl;
  1793. Matcher<const Tpl&> m = FloatNear(0.5f);
  1794. EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
  1795. EXPECT_TRUE(m.Matches(Tpl(1.3f, 1.0f)));
  1796. EXPECT_FALSE(m.Matches(Tpl(1.8f, 1.0f)));
  1797. }
  1798. // Tests that FloatNear() describes itself properly.
  1799. TEST(FloatNear2Test, CanDescribeSelf) {
  1800. Matcher<const ::std::tuple<float, float>&> m = FloatNear(0.5f);
  1801. EXPECT_EQ("are an almost-equal pair", Describe(m));
  1802. }
  1803. // Tests that NanSensitiveFloatNear() matches a 2-tuple where
  1804. // NanSensitiveFloatNear(first field) matches the second field.
  1805. TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) {
  1806. typedef ::std::tuple<float, float> Tpl;
  1807. Matcher<const Tpl&> m = NanSensitiveFloatNear(0.5f);
  1808. EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
  1809. EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
  1810. EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
  1811. std::numeric_limits<float>::quiet_NaN())));
  1812. EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
  1813. EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
  1814. EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
  1815. }
  1816. // Tests that NanSensitiveFloatNear() describes itself properly.
  1817. TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) {
  1818. Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatNear(0.5f);
  1819. EXPECT_EQ("are an almost-equal pair", Describe(m));
  1820. }
  1821. // Tests that FloatEq() matches a 2-tuple where
  1822. // DoubleNear(first field, max_abs_error) matches the second field.
  1823. TEST(DoubleNear2Test, MatchesEqualArguments) {
  1824. typedef ::std::tuple<double, double> Tpl;
  1825. Matcher<const Tpl&> m = DoubleNear(0.5);
  1826. EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
  1827. EXPECT_TRUE(m.Matches(Tpl(1.3, 1.0)));
  1828. EXPECT_FALSE(m.Matches(Tpl(1.8, 1.0)));
  1829. }
  1830. // Tests that DoubleNear() describes itself properly.
  1831. TEST(DoubleNear2Test, CanDescribeSelf) {
  1832. Matcher<const ::std::tuple<double, double>&> m = DoubleNear(0.5);
  1833. EXPECT_EQ("are an almost-equal pair", Describe(m));
  1834. }
  1835. // Tests that NanSensitiveDoubleNear() matches a 2-tuple where
  1836. // NanSensitiveDoubleNear(first field) matches the second field.
  1837. TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) {
  1838. typedef ::std::tuple<double, double> Tpl;
  1839. Matcher<const Tpl&> m = NanSensitiveDoubleNear(0.5f);
  1840. EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
  1841. EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
  1842. EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
  1843. std::numeric_limits<double>::quiet_NaN())));
  1844. EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
  1845. EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
  1846. EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
  1847. }
  1848. // Tests that NanSensitiveDoubleNear() describes itself properly.
  1849. TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) {
  1850. Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleNear(0.5f);
  1851. EXPECT_EQ("are an almost-equal pair", Describe(m));
  1852. }
  1853. // Tests that Not(m) matches any value that doesn't match m.
  1854. TEST(NotTest, NegatesMatcher) {
  1855. Matcher<int> m;
  1856. m = Not(Eq(2));
  1857. EXPECT_TRUE(m.Matches(3));
  1858. EXPECT_FALSE(m.Matches(2));
  1859. }
  1860. // Tests that Not(m) describes itself properly.
  1861. TEST(NotTest, CanDescribeSelf) {
  1862. Matcher<int> m = Not(Eq(5));
  1863. EXPECT_EQ("isn't equal to 5", Describe(m));
  1864. }
  1865. // Tests that monomorphic matchers are safely cast by the Not matcher.
  1866. TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
  1867. // greater_than_5 is a monomorphic matcher.
  1868. Matcher<int> greater_than_5 = Gt(5);
  1869. Matcher<const int&> m = Not(greater_than_5);
  1870. Matcher<int&> m2 = Not(greater_than_5);
  1871. Matcher<int&> m3 = Not(m);
  1872. }
  1873. // Helper to allow easy testing of AllOf matchers with num parameters.
  1874. void AllOfMatches(int num, const Matcher<int>& m) {
  1875. SCOPED_TRACE(Describe(m));
  1876. EXPECT_TRUE(m.Matches(0));
  1877. for (int i = 1; i <= num; ++i) {
  1878. EXPECT_FALSE(m.Matches(i));
  1879. }
  1880. EXPECT_TRUE(m.Matches(num + 1));
  1881. }
  1882. // Tests that AllOf(m1, ..., mn) matches any value that matches all of
  1883. // the given matchers.
  1884. TEST(AllOfTest, MatchesWhenAllMatch) {
  1885. Matcher<int> m;
  1886. m = AllOf(Le(2), Ge(1));
  1887. EXPECT_TRUE(m.Matches(1));
  1888. EXPECT_TRUE(m.Matches(2));
  1889. EXPECT_FALSE(m.Matches(0));
  1890. EXPECT_FALSE(m.Matches(3));
  1891. m = AllOf(Gt(0), Ne(1), Ne(2));
  1892. EXPECT_TRUE(m.Matches(3));
  1893. EXPECT_FALSE(m.Matches(2));
  1894. EXPECT_FALSE(m.Matches(1));
  1895. EXPECT_FALSE(m.Matches(0));
  1896. m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
  1897. EXPECT_TRUE(m.Matches(4));
  1898. EXPECT_FALSE(m.Matches(3));
  1899. EXPECT_FALSE(m.Matches(2));
  1900. EXPECT_FALSE(m.Matches(1));
  1901. EXPECT_FALSE(m.Matches(0));
  1902. m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
  1903. EXPECT_TRUE(m.Matches(0));
  1904. EXPECT_TRUE(m.Matches(1));
  1905. EXPECT_FALSE(m.Matches(3));
  1906. // The following tests for varying number of sub-matchers. Due to the way
  1907. // the sub-matchers are handled it is enough to test every sub-matcher once
  1908. // with sub-matchers using the same matcher type. Varying matcher types are
  1909. // checked for above.
  1910. AllOfMatches(2, AllOf(Ne(1), Ne(2)));
  1911. AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
  1912. AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
  1913. AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
  1914. AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
  1915. AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
  1916. AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
  1917. Ne(8)));
  1918. AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
  1919. Ne(8), Ne(9)));
  1920. AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
  1921. Ne(9), Ne(10)));
  1922. AllOfMatches(
  1923. 50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
  1924. Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), Ne(16), Ne(17),
  1925. Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), Ne(23), Ne(24), Ne(25),
  1926. Ne(26), Ne(27), Ne(28), Ne(29), Ne(30), Ne(31), Ne(32), Ne(33),
  1927. Ne(34), Ne(35), Ne(36), Ne(37), Ne(38), Ne(39), Ne(40), Ne(41),
  1928. Ne(42), Ne(43), Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
  1929. Ne(50)));
  1930. }
  1931. // Tests that AllOf(m1, ..., mn) describes itself properly.
  1932. TEST(AllOfTest, CanDescribeSelf) {
  1933. Matcher<int> m;
  1934. m = AllOf(Le(2), Ge(1));
  1935. EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
  1936. m = AllOf(Gt(0), Ne(1), Ne(2));
  1937. std::string expected_descr1 =
  1938. "(is > 0) and (isn't equal to 1) and (isn't equal to 2)";
  1939. EXPECT_EQ(expected_descr1, Describe(m));
  1940. m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
  1941. std::string expected_descr2 =
  1942. "(is > 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't equal "
  1943. "to 3)";
  1944. EXPECT_EQ(expected_descr2, Describe(m));
  1945. m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
  1946. std::string expected_descr3 =
  1947. "(is >= 0) and (is < 10) and (isn't equal to 3) and (isn't equal to 5) "
  1948. "and (isn't equal to 7)";
  1949. EXPECT_EQ(expected_descr3, Describe(m));
  1950. }
  1951. // Tests that AllOf(m1, ..., mn) describes its negation properly.
  1952. TEST(AllOfTest, CanDescribeNegation) {
  1953. Matcher<int> m;
  1954. m = AllOf(Le(2), Ge(1));
  1955. std::string expected_descr4 = "(isn't <= 2) or (isn't >= 1)";
  1956. EXPECT_EQ(expected_descr4, DescribeNegation(m));
  1957. m = AllOf(Gt(0), Ne(1), Ne(2));
  1958. std::string expected_descr5 =
  1959. "(isn't > 0) or (is equal to 1) or (is equal to 2)";
  1960. EXPECT_EQ(expected_descr5, DescribeNegation(m));
  1961. m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
  1962. std::string expected_descr6 =
  1963. "(isn't > 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)";
  1964. EXPECT_EQ(expected_descr6, DescribeNegation(m));
  1965. m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
  1966. std::string expected_desr7 =
  1967. "(isn't >= 0) or (isn't < 10) or (is equal to 3) or (is equal to 5) or "
  1968. "(is equal to 7)";
  1969. EXPECT_EQ(expected_desr7, DescribeNegation(m));
  1970. m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
  1971. Ne(10), Ne(11));
  1972. AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
  1973. EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)"));
  1974. AllOfMatches(11, m);
  1975. }
  1976. // Tests that monomorphic matchers are safely cast by the AllOf matcher.
  1977. TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
  1978. // greater_than_5 and less_than_10 are monomorphic matchers.
  1979. Matcher<int> greater_than_5 = Gt(5);
  1980. Matcher<int> less_than_10 = Lt(10);
  1981. Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
  1982. Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
  1983. Matcher<int&> m3 = AllOf(greater_than_5, m2);
  1984. // Tests that BothOf works when composing itself.
  1985. Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
  1986. Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
  1987. }
  1988. TEST(AllOfTest, ExplainsResult) {
  1989. Matcher<int> m;
  1990. // Successful match. Both matchers need to explain. The second
  1991. // matcher doesn't give an explanation, so only the first matcher's
  1992. // explanation is printed.
  1993. m = AllOf(GreaterThan(10), Lt(30));
  1994. EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
  1995. // Successful match. Both matchers need to explain.
  1996. m = AllOf(GreaterThan(10), GreaterThan(20));
  1997. EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
  1998. Explain(m, 30));
  1999. // Successful match. All matchers need to explain. The second
  2000. // matcher doesn't given an explanation.
  2001. m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
  2002. EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
  2003. Explain(m, 25));
  2004. // Successful match. All matchers need to explain.
  2005. m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
  2006. EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
  2007. "and which is 10 more than 30",
  2008. Explain(m, 40));
  2009. // Failed match. The first matcher, which failed, needs to
  2010. // explain.
  2011. m = AllOf(GreaterThan(10), GreaterThan(20));
  2012. EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
  2013. // Failed match. The second matcher, which failed, needs to
  2014. // explain. Since it doesn't given an explanation, nothing is
  2015. // printed.
  2016. m = AllOf(GreaterThan(10), Lt(30));
  2017. EXPECT_EQ("", Explain(m, 40));
  2018. // Failed match. The second matcher, which failed, needs to
  2019. // explain.
  2020. m = AllOf(GreaterThan(10), GreaterThan(20));
  2021. EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
  2022. }
  2023. // Helper to allow easy testing of AnyOf matchers with num parameters.
  2024. static void AnyOfMatches(int num, const Matcher<int>& m) {
  2025. SCOPED_TRACE(Describe(m));
  2026. EXPECT_FALSE(m.Matches(0));
  2027. for (int i = 1; i <= num; ++i) {
  2028. EXPECT_TRUE(m.Matches(i));
  2029. }
  2030. EXPECT_FALSE(m.Matches(num + 1));
  2031. }
  2032. static void AnyOfStringMatches(int num, const Matcher<std::string>& m) {
  2033. SCOPED_TRACE(Describe(m));
  2034. EXPECT_FALSE(m.Matches(std::to_string(0)));
  2035. for (int i = 1; i <= num; ++i) {
  2036. EXPECT_TRUE(m.Matches(std::to_string(i)));
  2037. }
  2038. EXPECT_FALSE(m.Matches(std::to_string(num + 1)));
  2039. }
  2040. // Tests that AnyOf(m1, ..., mn) matches any value that matches at
  2041. // least one of the given matchers.
  2042. TEST(AnyOfTest, MatchesWhenAnyMatches) {
  2043. Matcher<int> m;
  2044. m = AnyOf(Le(1), Ge(3));
  2045. EXPECT_TRUE(m.Matches(1));
  2046. EXPECT_TRUE(m.Matches(4));
  2047. EXPECT_FALSE(m.Matches(2));
  2048. m = AnyOf(Lt(0), Eq(1), Eq(2));
  2049. EXPECT_TRUE(m.Matches(-1));
  2050. EXPECT_TRUE(m.Matches(1));
  2051. EXPECT_TRUE(m.Matches(2));
  2052. EXPECT_FALSE(m.Matches(0));
  2053. m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
  2054. EXPECT_TRUE(m.Matches(-1));
  2055. EXPECT_TRUE(m.Matches(1));
  2056. EXPECT_TRUE(m.Matches(2));
  2057. EXPECT_TRUE(m.Matches(3));
  2058. EXPECT_FALSE(m.Matches(0));
  2059. m = AnyOf(Le(0), Gt(10), 3, 5, 7);
  2060. EXPECT_TRUE(m.Matches(0));
  2061. EXPECT_TRUE(m.Matches(11));
  2062. EXPECT_TRUE(m.Matches(3));
  2063. EXPECT_FALSE(m.Matches(2));
  2064. // The following tests for varying number of sub-matchers. Due to the way
  2065. // the sub-matchers are handled it is enough to test every sub-matcher once
  2066. // with sub-matchers using the same matcher type. Varying matcher types are
  2067. // checked for above.
  2068. AnyOfMatches(2, AnyOf(1, 2));
  2069. AnyOfMatches(3, AnyOf(1, 2, 3));
  2070. AnyOfMatches(4, AnyOf(1, 2, 3, 4));
  2071. AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
  2072. AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
  2073. AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
  2074. AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
  2075. AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
  2076. AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
  2077. }
  2078. // Tests the variadic version of the AnyOfMatcher.
  2079. TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
  2080. // Also make sure AnyOf is defined in the right namespace and does not depend
  2081. // on ADL.
  2082. Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
  2083. EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)"));
  2084. AnyOfMatches(11, m);
  2085. AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
  2086. 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
  2087. 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
  2088. 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  2089. 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
  2090. AnyOfStringMatches(
  2091. 50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
  2092. "13", "14", "15", "16", "17", "18", "19", "20", "21", "22",
  2093. "23", "24", "25", "26", "27", "28", "29", "30", "31", "32",
  2094. "33", "34", "35", "36", "37", "38", "39", "40", "41", "42",
  2095. "43", "44", "45", "46", "47", "48", "49", "50"));
  2096. }
  2097. // Tests the variadic version of the ElementsAreMatcher
  2098. TEST(ElementsAreTest, HugeMatcher) {
  2099. vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
  2100. EXPECT_THAT(test_vector,
  2101. ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7),
  2102. Eq(8), Eq(9), Eq(10), Gt(1), Eq(12)));
  2103. }
  2104. // Tests the variadic version of the UnorderedElementsAreMatcher
  2105. TEST(ElementsAreTest, HugeMatcherStr) {
  2106. vector<std::string> test_vector{
  2107. "literal_string", "", "", "", "", "", "", "", "", "", "", ""};
  2108. EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _,
  2109. _, _, _, _, _, _));
  2110. }
  2111. // Tests the variadic version of the UnorderedElementsAreMatcher
  2112. TEST(ElementsAreTest, HugeMatcherUnordered) {
  2113. vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};
  2114. EXPECT_THAT(test_vector, UnorderedElementsAre(
  2115. Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7),
  2116. Eq(3), Eq(9), Eq(12), Eq(11), Ne(122)));
  2117. }
  2118. // Tests that AnyOf(m1, ..., mn) describes itself properly.
  2119. TEST(AnyOfTest, CanDescribeSelf) {
  2120. Matcher<int> m;
  2121. m = AnyOf(Le(1), Ge(3));
  2122. EXPECT_EQ("(is <= 1) or (is >= 3)",
  2123. Describe(m));
  2124. m = AnyOf(Lt(0), Eq(1), Eq(2));
  2125. EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2)", Describe(m));
  2126. m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
  2127. EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)",
  2128. Describe(m));
  2129. m = AnyOf(Le(0), Gt(10), 3, 5, 7);
  2130. EXPECT_EQ(
  2131. "(is <= 0) or (is > 10) or (is equal to 3) or (is equal to 5) or (is "
  2132. "equal to 7)",
  2133. Describe(m));
  2134. }
  2135. // Tests that AnyOf(m1, ..., mn) describes its negation properly.
  2136. TEST(AnyOfTest, CanDescribeNegation) {
  2137. Matcher<int> m;
  2138. m = AnyOf(Le(1), Ge(3));
  2139. EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
  2140. DescribeNegation(m));
  2141. m = AnyOf(Lt(0), Eq(1), Eq(2));
  2142. EXPECT_EQ("(isn't < 0) and (isn't equal to 1) and (isn't equal to 2)",
  2143. DescribeNegation(m));
  2144. m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
  2145. EXPECT_EQ(
  2146. "(isn't < 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't "
  2147. "equal to 3)",
  2148. DescribeNegation(m));
  2149. m = AnyOf(Le(0), Gt(10), 3, 5, 7);
  2150. EXPECT_EQ(
  2151. "(isn't <= 0) and (isn't > 10) and (isn't equal to 3) and (isn't equal "
  2152. "to 5) and (isn't equal to 7)",
  2153. DescribeNegation(m));
  2154. }
  2155. // Tests that monomorphic matchers are safely cast by the AnyOf matcher.
  2156. TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
  2157. // greater_than_5 and less_than_10 are monomorphic matchers.
  2158. Matcher<int> greater_than_5 = Gt(5);
  2159. Matcher<int> less_than_10 = Lt(10);
  2160. Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
  2161. Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
  2162. Matcher<int&> m3 = AnyOf(greater_than_5, m2);
  2163. // Tests that EitherOf works when composing itself.
  2164. Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
  2165. Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
  2166. }
  2167. TEST(AnyOfTest, ExplainsResult) {
  2168. Matcher<int> m;
  2169. // Failed match. Both matchers need to explain. The second
  2170. // matcher doesn't give an explanation, so only the first matcher's
  2171. // explanation is printed.
  2172. m = AnyOf(GreaterThan(10), Lt(0));
  2173. EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
  2174. // Failed match. Both matchers need to explain.
  2175. m = AnyOf(GreaterThan(10), GreaterThan(20));
  2176. EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
  2177. Explain(m, 5));
  2178. // Failed match. All matchers need to explain. The second
  2179. // matcher doesn't given an explanation.
  2180. m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
  2181. EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
  2182. Explain(m, 5));
  2183. // Failed match. All matchers need to explain.
  2184. m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
  2185. EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
  2186. "and which is 25 less than 30",
  2187. Explain(m, 5));
  2188. // Successful match. The first matcher, which succeeded, needs to
  2189. // explain.
  2190. m = AnyOf(GreaterThan(10), GreaterThan(20));
  2191. EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
  2192. // Successful match. The second matcher, which succeeded, needs to
  2193. // explain. Since it doesn't given an explanation, nothing is
  2194. // printed.
  2195. m = AnyOf(GreaterThan(10), Lt(30));
  2196. EXPECT_EQ("", Explain(m, 0));
  2197. // Successful match. The second matcher, which succeeded, needs to
  2198. // explain.
  2199. m = AnyOf(GreaterThan(30), GreaterThan(20));
  2200. EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
  2201. }
  2202. // The following predicate function and predicate functor are for
  2203. // testing the Truly(predicate) matcher.
  2204. // Returns non-zero if the input is positive. Note that the return
  2205. // type of this function is not bool. It's OK as Truly() accepts any
  2206. // unary function or functor whose return type can be implicitly
  2207. // converted to bool.
  2208. int IsPositive(double x) {
  2209. return x > 0 ? 1 : 0;
  2210. }
  2211. // This functor returns true if the input is greater than the given
  2212. // number.
  2213. class IsGreaterThan {
  2214. public:
  2215. explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
  2216. bool operator()(int n) const { return n > threshold_; }
  2217. private:
  2218. int threshold_;
  2219. };
  2220. // For testing Truly().
  2221. const int foo = 0;
  2222. // This predicate returns true if and only if the argument references foo and
  2223. // has a zero value.
  2224. bool ReferencesFooAndIsZero(const int& n) {
  2225. return (&n == &foo) && (n == 0);
  2226. }
  2227. // Tests that Truly(predicate) matches what satisfies the given
  2228. // predicate.
  2229. TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
  2230. Matcher<double> m = Truly(IsPositive);
  2231. EXPECT_TRUE(m.Matches(2.0));
  2232. EXPECT_FALSE(m.Matches(-1.5));
  2233. }
  2234. // Tests that Truly(predicate_functor) works too.
  2235. TEST(TrulyTest, CanBeUsedWithFunctor) {
  2236. Matcher<int> m = Truly(IsGreaterThan(5));
  2237. EXPECT_TRUE(m.Matches(6));
  2238. EXPECT_FALSE(m.Matches(4));
  2239. }
  2240. // A class that can be implicitly converted to bool.
  2241. class ConvertibleToBool {
  2242. public:
  2243. explicit ConvertibleToBool(int number) : number_(number) {}
  2244. operator bool() const { return number_ != 0; }
  2245. private:
  2246. int number_;
  2247. };
  2248. ConvertibleToBool IsNotZero(int number) {
  2249. return ConvertibleToBool(number);
  2250. }
  2251. // Tests that the predicate used in Truly() may return a class that's
  2252. // implicitly convertible to bool, even when the class has no
  2253. // operator!().
  2254. TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
  2255. Matcher<int> m = Truly(IsNotZero);
  2256. EXPECT_TRUE(m.Matches(1));
  2257. EXPECT_FALSE(m.Matches(0));
  2258. }
  2259. // Tests that Truly(predicate) can describe itself properly.
  2260. TEST(TrulyTest, CanDescribeSelf) {
  2261. Matcher<double> m = Truly(IsPositive);
  2262. EXPECT_EQ("satisfies the given predicate",
  2263. Describe(m));
  2264. }
  2265. // Tests that Truly(predicate) works when the matcher takes its
  2266. // argument by reference.
  2267. TEST(TrulyTest, WorksForByRefArguments) {
  2268. Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
  2269. EXPECT_TRUE(m.Matches(foo));
  2270. int n = 0;
  2271. EXPECT_FALSE(m.Matches(n));
  2272. }
  2273. // Tests that Matches(m) is a predicate satisfied by whatever that
  2274. // matches matcher m.
  2275. TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
  2276. EXPECT_TRUE(Matches(Ge(0))(1));
  2277. EXPECT_FALSE(Matches(Eq('a'))('b'));
  2278. }
  2279. // Tests that Matches(m) works when the matcher takes its argument by
  2280. // reference.
  2281. TEST(MatchesTest, WorksOnByRefArguments) {
  2282. int m = 0, n = 0;
  2283. EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
  2284. EXPECT_FALSE(Matches(Ref(m))(n));
  2285. }
  2286. // Tests that a Matcher on non-reference type can be used in
  2287. // Matches().
  2288. TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
  2289. Matcher<int> eq5 = Eq(5);
  2290. EXPECT_TRUE(Matches(eq5)(5));
  2291. EXPECT_FALSE(Matches(eq5)(2));
  2292. }
  2293. // Tests Value(value, matcher). Since Value() is a simple wrapper for
  2294. // Matches(), which has been tested already, we don't spend a lot of
  2295. // effort on testing Value().
  2296. TEST(ValueTest, WorksWithPolymorphicMatcher) {
  2297. EXPECT_TRUE(Value("hi", StartsWith("h")));
  2298. EXPECT_FALSE(Value(5, Gt(10)));
  2299. }
  2300. TEST(ValueTest, WorksWithMonomorphicMatcher) {
  2301. const Matcher<int> is_zero = Eq(0);
  2302. EXPECT_TRUE(Value(0, is_zero));
  2303. EXPECT_FALSE(Value('a', is_zero));
  2304. int n = 0;
  2305. const Matcher<const int&> ref_n = Ref(n);
  2306. EXPECT_TRUE(Value(n, ref_n));
  2307. EXPECT_FALSE(Value(1, ref_n));
  2308. }
  2309. TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
  2310. StringMatchResultListener listener1;
  2311. EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
  2312. EXPECT_EQ("% 2 == 0", listener1.str());
  2313. StringMatchResultListener listener2;
  2314. EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
  2315. EXPECT_EQ("", listener2.str());
  2316. }
  2317. TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
  2318. const Matcher<int> is_even = PolymorphicIsEven();
  2319. StringMatchResultListener listener1;
  2320. EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
  2321. EXPECT_EQ("% 2 == 0", listener1.str());
  2322. const Matcher<const double&> is_zero = Eq(0);
  2323. StringMatchResultListener listener2;
  2324. EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
  2325. EXPECT_EQ("", listener2.str());
  2326. }
  2327. MATCHER_P(Really, inner_matcher, "") {
  2328. return ExplainMatchResult(inner_matcher, arg, result_listener);
  2329. }
  2330. TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
  2331. EXPECT_THAT(0, Really(Eq(0)));
  2332. }
  2333. TEST(DescribeMatcherTest, WorksWithValue) {
  2334. EXPECT_EQ("is equal to 42", DescribeMatcher<int>(42));
  2335. EXPECT_EQ("isn't equal to 42", DescribeMatcher<int>(42, true));
  2336. }
  2337. TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) {
  2338. const Matcher<int> monomorphic = Le(0);
  2339. EXPECT_EQ("is <= 0", DescribeMatcher<int>(monomorphic));
  2340. EXPECT_EQ("isn't <= 0", DescribeMatcher<int>(monomorphic, true));
  2341. }
  2342. TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) {
  2343. EXPECT_EQ("is even", DescribeMatcher<int>(PolymorphicIsEven()));
  2344. EXPECT_EQ("is odd", DescribeMatcher<int>(PolymorphicIsEven(), true));
  2345. }
  2346. TEST(AllArgsTest, WorksForTuple) {
  2347. EXPECT_THAT(std::make_tuple(1, 2L), AllArgs(Lt()));
  2348. EXPECT_THAT(std::make_tuple(2L, 1), Not(AllArgs(Lt())));
  2349. }
  2350. TEST(AllArgsTest, WorksForNonTuple) {
  2351. EXPECT_THAT(42, AllArgs(Gt(0)));
  2352. EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
  2353. }
  2354. class AllArgsHelper {
  2355. public:
  2356. AllArgsHelper() {}
  2357. MOCK_METHOD2(Helper, int(char x, int y));
  2358. private:
  2359. GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
  2360. };
  2361. TEST(AllArgsTest, WorksInWithClause) {
  2362. AllArgsHelper helper;
  2363. ON_CALL(helper, Helper(_, _))
  2364. .With(AllArgs(Lt()))
  2365. .WillByDefault(Return(1));
  2366. EXPECT_CALL(helper, Helper(_, _));
  2367. EXPECT_CALL(helper, Helper(_, _))
  2368. .With(AllArgs(Gt()))
  2369. .WillOnce(Return(2));
  2370. EXPECT_EQ(1, helper.Helper('\1', 2));
  2371. EXPECT_EQ(2, helper.Helper('a', 1));
  2372. }
  2373. class OptionalMatchersHelper {
  2374. public:
  2375. OptionalMatchersHelper() {}
  2376. MOCK_METHOD0(NoArgs, int());
  2377. MOCK_METHOD1(OneArg, int(int y));
  2378. MOCK_METHOD2(TwoArgs, int(char x, int y));
  2379. MOCK_METHOD1(Overloaded, int(char x));
  2380. MOCK_METHOD2(Overloaded, int(char x, int y));
  2381. private:
  2382. GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper);
  2383. };
  2384. TEST(AllArgsTest, WorksWithoutMatchers) {
  2385. OptionalMatchersHelper helper;
  2386. ON_CALL(helper, NoArgs).WillByDefault(Return(10));
  2387. ON_CALL(helper, OneArg).WillByDefault(Return(20));
  2388. ON_CALL(helper, TwoArgs).WillByDefault(Return(30));
  2389. EXPECT_EQ(10, helper.NoArgs());
  2390. EXPECT_EQ(20, helper.OneArg(1));
  2391. EXPECT_EQ(30, helper.TwoArgs('\1', 2));
  2392. EXPECT_CALL(helper, NoArgs).Times(1);
  2393. EXPECT_CALL(helper, OneArg).WillOnce(Return(100));
  2394. EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200));
  2395. EXPECT_CALL(helper, TwoArgs).Times(0);
  2396. EXPECT_EQ(10, helper.NoArgs());
  2397. EXPECT_EQ(100, helper.OneArg(1));
  2398. EXPECT_EQ(200, helper.OneArg(17));
  2399. }
  2400. // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
  2401. // matches the matcher.
  2402. TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
  2403. ASSERT_THAT(5, Ge(2)) << "This should succeed.";
  2404. ASSERT_THAT("Foo", EndsWith("oo"));
  2405. EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
  2406. EXPECT_THAT("Hello", StartsWith("Hell"));
  2407. }
  2408. // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
  2409. // doesn't match the matcher.
  2410. TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
  2411. // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
  2412. // which cannot reference auto variables.
  2413. static unsigned short n; // NOLINT
  2414. n = 5;
  2415. // VC++ prior to version 8.0 SP1 has a bug where it will not see any
  2416. // functions declared in the namespace scope from within nested classes.
  2417. // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
  2418. // namespace-level functions invoked inside them need to be explicitly
  2419. // resolved.
  2420. EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
  2421. "Value of: n\n"
  2422. "Expected: is > 10\n"
  2423. " Actual: 5" + OfType("unsigned short"));
  2424. n = 0;
  2425. EXPECT_NONFATAL_FAILURE(
  2426. EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
  2427. "Value of: n\n"
  2428. "Expected: (is <= 7) and (is >= 5)\n"
  2429. " Actual: 0" + OfType("unsigned short"));
  2430. }
  2431. // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
  2432. // has a reference type.
  2433. TEST(MatcherAssertionTest, WorksForByRefArguments) {
  2434. // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
  2435. // reference auto variables.
  2436. static int n;
  2437. n = 0;
  2438. EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
  2439. EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
  2440. "Value of: n\n"
  2441. "Expected: does not reference the variable @");
  2442. // Tests the "Actual" part.
  2443. EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
  2444. "Actual: 0" + OfType("int") + ", which is located @");
  2445. }
  2446. // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
  2447. // monomorphic.
  2448. TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
  2449. Matcher<const char*> starts_with_he = StartsWith("he");
  2450. ASSERT_THAT("hello", starts_with_he);
  2451. Matcher<const std::string&> ends_with_ok = EndsWith("ok");
  2452. ASSERT_THAT("book", ends_with_ok);
  2453. const std::string bad = "bad";
  2454. EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
  2455. "Value of: bad\n"
  2456. "Expected: ends with \"ok\"\n"
  2457. " Actual: \"bad\"");
  2458. Matcher<int> is_greater_than_5 = Gt(5);
  2459. EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
  2460. "Value of: 5\n"
  2461. "Expected: is > 5\n"
  2462. " Actual: 5" + OfType("int"));
  2463. }
  2464. // Tests floating-point matchers.
  2465. template <typename RawType>
  2466. class FloatingPointTest : public testing::Test {
  2467. protected:
  2468. typedef testing::internal::FloatingPoint<RawType> Floating;
  2469. typedef typename Floating::Bits Bits;
  2470. FloatingPointTest()
  2471. : max_ulps_(Floating::kMaxUlps),
  2472. zero_bits_(Floating(0).bits()),
  2473. one_bits_(Floating(1).bits()),
  2474. infinity_bits_(Floating(Floating::Infinity()).bits()),
  2475. close_to_positive_zero_(
  2476. Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
  2477. close_to_negative_zero_(
  2478. -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
  2479. further_from_negative_zero_(-Floating::ReinterpretBits(
  2480. zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
  2481. close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
  2482. further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
  2483. infinity_(Floating::Infinity()),
  2484. close_to_infinity_(
  2485. Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
  2486. further_from_infinity_(
  2487. Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
  2488. max_(Floating::Max()),
  2489. nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
  2490. nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
  2491. }
  2492. void TestSize() {
  2493. EXPECT_EQ(sizeof(RawType), sizeof(Bits));
  2494. }
  2495. // A battery of tests for FloatingEqMatcher::Matches.
  2496. // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
  2497. void TestMatches(
  2498. testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
  2499. Matcher<RawType> m1 = matcher_maker(0.0);
  2500. EXPECT_TRUE(m1.Matches(-0.0));
  2501. EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
  2502. EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
  2503. EXPECT_FALSE(m1.Matches(1.0));
  2504. Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
  2505. EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
  2506. Matcher<RawType> m3 = matcher_maker(1.0);
  2507. EXPECT_TRUE(m3.Matches(close_to_one_));
  2508. EXPECT_FALSE(m3.Matches(further_from_one_));
  2509. // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
  2510. EXPECT_FALSE(m3.Matches(0.0));
  2511. Matcher<RawType> m4 = matcher_maker(-infinity_);
  2512. EXPECT_TRUE(m4.Matches(-close_to_infinity_));
  2513. Matcher<RawType> m5 = matcher_maker(infinity_);
  2514. EXPECT_TRUE(m5.Matches(close_to_infinity_));
  2515. // This is interesting as the representations of infinity_ and nan1_
  2516. // are only 1 DLP apart.
  2517. EXPECT_FALSE(m5.Matches(nan1_));
  2518. // matcher_maker can produce a Matcher<const RawType&>, which is needed in
  2519. // some cases.
  2520. Matcher<const RawType&> m6 = matcher_maker(0.0);
  2521. EXPECT_TRUE(m6.Matches(-0.0));
  2522. EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
  2523. EXPECT_FALSE(m6.Matches(1.0));
  2524. // matcher_maker can produce a Matcher<RawType&>, which is needed in some
  2525. // cases.
  2526. Matcher<RawType&> m7 = matcher_maker(0.0);
  2527. RawType x = 0.0;
  2528. EXPECT_TRUE(m7.Matches(x));
  2529. x = 0.01f;
  2530. EXPECT_FALSE(m7.Matches(x));
  2531. }
  2532. // Pre-calculated numbers to be used by the tests.
  2533. const Bits max_ulps_;
  2534. const Bits zero_bits_; // The bits that represent 0.0.
  2535. const Bits one_bits_; // The bits that represent 1.0.
  2536. const Bits infinity_bits_; // The bits that represent +infinity.
  2537. // Some numbers close to 0.0.
  2538. const RawType close_to_positive_zero_;
  2539. const RawType close_to_negative_zero_;
  2540. const RawType further_from_negative_zero_;
  2541. // Some numbers close to 1.0.
  2542. const RawType close_to_one_;
  2543. const RawType further_from_one_;
  2544. // Some numbers close to +infinity.
  2545. const RawType infinity_;
  2546. const RawType close_to_infinity_;
  2547. const RawType further_from_infinity_;
  2548. // Maximum representable value that's not infinity.
  2549. const RawType max_;
  2550. // Some NaNs.
  2551. const RawType nan1_;
  2552. const RawType nan2_;
  2553. };
  2554. // Tests floating-point matchers with fixed epsilons.
  2555. template <typename RawType>
  2556. class FloatingPointNearTest : public FloatingPointTest<RawType> {
  2557. protected:
  2558. typedef FloatingPointTest<RawType> ParentType;
  2559. // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
  2560. // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
  2561. void TestNearMatches(
  2562. testing::internal::FloatingEqMatcher<RawType>
  2563. (*matcher_maker)(RawType, RawType)) {
  2564. Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
  2565. EXPECT_TRUE(m1.Matches(0.0));
  2566. EXPECT_TRUE(m1.Matches(-0.0));
  2567. EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
  2568. EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
  2569. EXPECT_FALSE(m1.Matches(1.0));
  2570. Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
  2571. EXPECT_TRUE(m2.Matches(0.0));
  2572. EXPECT_TRUE(m2.Matches(-0.0));
  2573. EXPECT_TRUE(m2.Matches(1.0));
  2574. EXPECT_TRUE(m2.Matches(-1.0));
  2575. EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
  2576. EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
  2577. // Check that inf matches inf, regardless of the of the specified max
  2578. // absolute error.
  2579. Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
  2580. EXPECT_TRUE(m3.Matches(ParentType::infinity_));
  2581. EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
  2582. EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
  2583. Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
  2584. EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
  2585. EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
  2586. EXPECT_FALSE(m4.Matches(ParentType::infinity_));
  2587. // Test various overflow scenarios.
  2588. Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
  2589. EXPECT_TRUE(m5.Matches(ParentType::max_));
  2590. EXPECT_FALSE(m5.Matches(-ParentType::max_));
  2591. Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
  2592. EXPECT_FALSE(m6.Matches(ParentType::max_));
  2593. EXPECT_TRUE(m6.Matches(-ParentType::max_));
  2594. Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
  2595. EXPECT_TRUE(m7.Matches(ParentType::max_));
  2596. EXPECT_FALSE(m7.Matches(-ParentType::max_));
  2597. Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
  2598. EXPECT_FALSE(m8.Matches(ParentType::max_));
  2599. EXPECT_TRUE(m8.Matches(-ParentType::max_));
  2600. // The difference between max() and -max() normally overflows to infinity,
  2601. // but it should still match if the max_abs_error is also infinity.
  2602. Matcher<RawType> m9 = matcher_maker(
  2603. ParentType::max_, ParentType::infinity_);
  2604. EXPECT_TRUE(m8.Matches(-ParentType::max_));
  2605. // matcher_maker can produce a Matcher<const RawType&>, which is needed in
  2606. // some cases.
  2607. Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
  2608. EXPECT_TRUE(m10.Matches(-0.0));
  2609. EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
  2610. EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
  2611. // matcher_maker can produce a Matcher<RawType&>, which is needed in some
  2612. // cases.
  2613. Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
  2614. RawType x = 0.0;
  2615. EXPECT_TRUE(m11.Matches(x));
  2616. x = 1.0f;
  2617. EXPECT_TRUE(m11.Matches(x));
  2618. x = -1.0f;
  2619. EXPECT_TRUE(m11.Matches(x));
  2620. x = 1.1f;
  2621. EXPECT_FALSE(m11.Matches(x));
  2622. x = -1.1f;
  2623. EXPECT_FALSE(m11.Matches(x));
  2624. }
  2625. };
  2626. // Instantiate FloatingPointTest for testing floats.
  2627. typedef FloatingPointTest<float> FloatTest;
  2628. TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
  2629. TestMatches(&FloatEq);
  2630. }
  2631. TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
  2632. TestMatches(&NanSensitiveFloatEq);
  2633. }
  2634. TEST_F(FloatTest, FloatEqCannotMatchNaN) {
  2635. // FloatEq never matches NaN.
  2636. Matcher<float> m = FloatEq(nan1_);
  2637. EXPECT_FALSE(m.Matches(nan1_));
  2638. EXPECT_FALSE(m.Matches(nan2_));
  2639. EXPECT_FALSE(m.Matches(1.0));
  2640. }
  2641. TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
  2642. // NanSensitiveFloatEq will match NaN.
  2643. Matcher<float> m = NanSensitiveFloatEq(nan1_);
  2644. EXPECT_TRUE(m.Matches(nan1_));
  2645. EXPECT_TRUE(m.Matches(nan2_));
  2646. EXPECT_FALSE(m.Matches(1.0));
  2647. }
  2648. TEST_F(FloatTest, FloatEqCanDescribeSelf) {
  2649. Matcher<float> m1 = FloatEq(2.0f);
  2650. EXPECT_EQ("is approximately 2", Describe(m1));
  2651. EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
  2652. Matcher<float> m2 = FloatEq(0.5f);
  2653. EXPECT_EQ("is approximately 0.5", Describe(m2));
  2654. EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
  2655. Matcher<float> m3 = FloatEq(nan1_);
  2656. EXPECT_EQ("never matches", Describe(m3));
  2657. EXPECT_EQ("is anything", DescribeNegation(m3));
  2658. }
  2659. TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
  2660. Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
  2661. EXPECT_EQ("is approximately 2", Describe(m1));
  2662. EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
  2663. Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
  2664. EXPECT_EQ("is approximately 0.5", Describe(m2));
  2665. EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
  2666. Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
  2667. EXPECT_EQ("is NaN", Describe(m3));
  2668. EXPECT_EQ("isn't NaN", DescribeNegation(m3));
  2669. }
  2670. // Instantiate FloatingPointTest for testing floats with a user-specified
  2671. // max absolute error.
  2672. typedef FloatingPointNearTest<float> FloatNearTest;
  2673. TEST_F(FloatNearTest, FloatNearMatches) {
  2674. TestNearMatches(&FloatNear);
  2675. }
  2676. TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
  2677. TestNearMatches(&NanSensitiveFloatNear);
  2678. }
  2679. TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
  2680. Matcher<float> m1 = FloatNear(2.0f, 0.5f);
  2681. EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
  2682. EXPECT_EQ(
  2683. "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
  2684. Matcher<float> m2 = FloatNear(0.5f, 0.5f);
  2685. EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
  2686. EXPECT_EQ(
  2687. "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
  2688. Matcher<float> m3 = FloatNear(nan1_, 0.0);
  2689. EXPECT_EQ("never matches", Describe(m3));
  2690. EXPECT_EQ("is anything", DescribeNegation(m3));
  2691. }
  2692. TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
  2693. Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
  2694. EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
  2695. EXPECT_EQ(
  2696. "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
  2697. Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
  2698. EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
  2699. EXPECT_EQ(
  2700. "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
  2701. Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
  2702. EXPECT_EQ("is NaN", Describe(m3));
  2703. EXPECT_EQ("isn't NaN", DescribeNegation(m3));
  2704. }
  2705. TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
  2706. // FloatNear never matches NaN.
  2707. Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
  2708. EXPECT_FALSE(m.Matches(nan1_));
  2709. EXPECT_FALSE(m.Matches(nan2_));
  2710. EXPECT_FALSE(m.Matches(1.0));
  2711. }
  2712. TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
  2713. // NanSensitiveFloatNear will match NaN.
  2714. Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
  2715. EXPECT_TRUE(m.Matches(nan1_));
  2716. EXPECT_TRUE(m.Matches(nan2_));
  2717. EXPECT_FALSE(m.Matches(1.0));
  2718. }
  2719. // Instantiate FloatingPointTest for testing doubles.
  2720. typedef FloatingPointTest<double> DoubleTest;
  2721. TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
  2722. TestMatches(&DoubleEq);
  2723. }
  2724. TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
  2725. TestMatches(&NanSensitiveDoubleEq);
  2726. }
  2727. TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
  2728. // DoubleEq never matches NaN.
  2729. Matcher<double> m = DoubleEq(nan1_);
  2730. EXPECT_FALSE(m.Matches(nan1_));
  2731. EXPECT_FALSE(m.Matches(nan2_));
  2732. EXPECT_FALSE(m.Matches(1.0));
  2733. }
  2734. TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
  2735. // NanSensitiveDoubleEq will match NaN.
  2736. Matcher<double> m = NanSensitiveDoubleEq(nan1_);
  2737. EXPECT_TRUE(m.Matches(nan1_));
  2738. EXPECT_TRUE(m.Matches(nan2_));
  2739. EXPECT_FALSE(m.Matches(1.0));
  2740. }
  2741. TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
  2742. Matcher<double> m1 = DoubleEq(2.0);
  2743. EXPECT_EQ("is approximately 2", Describe(m1));
  2744. EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
  2745. Matcher<double> m2 = DoubleEq(0.5);
  2746. EXPECT_EQ("is approximately 0.5", Describe(m2));
  2747. EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
  2748. Matcher<double> m3 = DoubleEq(nan1_);
  2749. EXPECT_EQ("never matches", Describe(m3));
  2750. EXPECT_EQ("is anything", DescribeNegation(m3));
  2751. }
  2752. TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
  2753. Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
  2754. EXPECT_EQ("is approximately 2", Describe(m1));
  2755. EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
  2756. Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
  2757. EXPECT_EQ("is approximately 0.5", Describe(m2));
  2758. EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
  2759. Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
  2760. EXPECT_EQ("is NaN", Describe(m3));
  2761. EXPECT_EQ("isn't NaN", DescribeNegation(m3));
  2762. }
  2763. // Instantiate FloatingPointTest for testing floats with a user-specified
  2764. // max absolute error.
  2765. typedef FloatingPointNearTest<double> DoubleNearTest;
  2766. TEST_F(DoubleNearTest, DoubleNearMatches) {
  2767. TestNearMatches(&DoubleNear);
  2768. }
  2769. TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
  2770. TestNearMatches(&NanSensitiveDoubleNear);
  2771. }
  2772. TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
  2773. Matcher<double> m1 = DoubleNear(2.0, 0.5);
  2774. EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
  2775. EXPECT_EQ(
  2776. "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
  2777. Matcher<double> m2 = DoubleNear(0.5, 0.5);
  2778. EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
  2779. EXPECT_EQ(
  2780. "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
  2781. Matcher<double> m3 = DoubleNear(nan1_, 0.0);
  2782. EXPECT_EQ("never matches", Describe(m3));
  2783. EXPECT_EQ("is anything", DescribeNegation(m3));
  2784. }
  2785. TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
  2786. EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
  2787. EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
  2788. EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
  2789. const std::string explanation =
  2790. Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
  2791. // Different C++ implementations may print floating-point numbers
  2792. // slightly differently.
  2793. EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC
  2794. explanation == "which is 1.2e-010 from 2.1") // MSVC
  2795. << " where explanation is \"" << explanation << "\".";
  2796. }
  2797. TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
  2798. Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
  2799. EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
  2800. EXPECT_EQ(
  2801. "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
  2802. Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
  2803. EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
  2804. EXPECT_EQ(
  2805. "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
  2806. Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
  2807. EXPECT_EQ("is NaN", Describe(m3));
  2808. EXPECT_EQ("isn't NaN", DescribeNegation(m3));
  2809. }
  2810. TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
  2811. // DoubleNear never matches NaN.
  2812. Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
  2813. EXPECT_FALSE(m.Matches(nan1_));
  2814. EXPECT_FALSE(m.Matches(nan2_));
  2815. EXPECT_FALSE(m.Matches(1.0));
  2816. }
  2817. TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
  2818. // NanSensitiveDoubleNear will match NaN.
  2819. Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
  2820. EXPECT_TRUE(m.Matches(nan1_));
  2821. EXPECT_TRUE(m.Matches(nan2_));
  2822. EXPECT_FALSE(m.Matches(1.0));
  2823. }
  2824. TEST(PointeeTest, RawPointer) {
  2825. const Matcher<int*> m = Pointee(Ge(0));
  2826. int n = 1;
  2827. EXPECT_TRUE(m.Matches(&n));
  2828. n = -1;
  2829. EXPECT_FALSE(m.Matches(&n));
  2830. EXPECT_FALSE(m.Matches(nullptr));
  2831. }
  2832. TEST(PointeeTest, RawPointerToConst) {
  2833. const Matcher<const double*> m = Pointee(Ge(0));
  2834. double x = 1;
  2835. EXPECT_TRUE(m.Matches(&x));
  2836. x = -1;
  2837. EXPECT_FALSE(m.Matches(&x));
  2838. EXPECT_FALSE(m.Matches(nullptr));
  2839. }
  2840. TEST(PointeeTest, ReferenceToConstRawPointer) {
  2841. const Matcher<int* const &> m = Pointee(Ge(0));
  2842. int n = 1;
  2843. EXPECT_TRUE(m.Matches(&n));
  2844. n = -1;
  2845. EXPECT_FALSE(m.Matches(&n));
  2846. EXPECT_FALSE(m.Matches(nullptr));
  2847. }
  2848. TEST(PointeeTest, ReferenceToNonConstRawPointer) {
  2849. const Matcher<double* &> m = Pointee(Ge(0));
  2850. double x = 1.0;
  2851. double* p = &x;
  2852. EXPECT_TRUE(m.Matches(p));
  2853. x = -1;
  2854. EXPECT_FALSE(m.Matches(p));
  2855. p = nullptr;
  2856. EXPECT_FALSE(m.Matches(p));
  2857. }
  2858. MATCHER_P(FieldIIs, inner_matcher, "") {
  2859. return ExplainMatchResult(inner_matcher, arg.i, result_listener);
  2860. }
  2861. #if GTEST_HAS_RTTI
  2862. TEST(WhenDynamicCastToTest, SameType) {
  2863. Derived derived;
  2864. derived.i = 4;
  2865. // Right type. A pointer is passed down.
  2866. Base* as_base_ptr = &derived;
  2867. EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
  2868. EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
  2869. EXPECT_THAT(as_base_ptr,
  2870. Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
  2871. }
  2872. TEST(WhenDynamicCastToTest, WrongTypes) {
  2873. Base base;
  2874. Derived derived;
  2875. OtherDerived other_derived;
  2876. // Wrong types. NULL is passed.
  2877. EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
  2878. EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
  2879. Base* as_base_ptr = &derived;
  2880. EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
  2881. EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
  2882. as_base_ptr = &other_derived;
  2883. EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
  2884. EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
  2885. }
  2886. TEST(WhenDynamicCastToTest, AlreadyNull) {
  2887. // Already NULL.
  2888. Base* as_base_ptr = nullptr;
  2889. EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
  2890. }
  2891. struct AmbiguousCastTypes {
  2892. class VirtualDerived : public virtual Base {};
  2893. class DerivedSub1 : public VirtualDerived {};
  2894. class DerivedSub2 : public VirtualDerived {};
  2895. class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
  2896. };
  2897. TEST(WhenDynamicCastToTest, AmbiguousCast) {
  2898. AmbiguousCastTypes::DerivedSub1 sub1;
  2899. AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
  2900. // Multiply derived from Base. dynamic_cast<> returns NULL.
  2901. Base* as_base_ptr =
  2902. static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
  2903. EXPECT_THAT(as_base_ptr,
  2904. WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
  2905. as_base_ptr = &sub1;
  2906. EXPECT_THAT(
  2907. as_base_ptr,
  2908. WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
  2909. }
  2910. TEST(WhenDynamicCastToTest, Describe) {
  2911. Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
  2912. const std::string prefix =
  2913. "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
  2914. EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
  2915. EXPECT_EQ(prefix + "does not point to a value that is anything",
  2916. DescribeNegation(matcher));
  2917. }
  2918. TEST(WhenDynamicCastToTest, Explain) {
  2919. Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
  2920. Base* null = nullptr;
  2921. EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
  2922. Derived derived;
  2923. EXPECT_TRUE(matcher.Matches(&derived));
  2924. EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
  2925. // With references, the matcher itself can fail. Test for that one.
  2926. Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
  2927. EXPECT_THAT(Explain(ref_matcher, derived),
  2928. HasSubstr("which cannot be dynamic_cast"));
  2929. }
  2930. TEST(WhenDynamicCastToTest, GoodReference) {
  2931. Derived derived;
  2932. derived.i = 4;
  2933. Base& as_base_ref = derived;
  2934. EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
  2935. EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
  2936. }
  2937. TEST(WhenDynamicCastToTest, BadReference) {
  2938. Derived derived;
  2939. Base& as_base_ref = derived;
  2940. EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
  2941. }
  2942. #endif // GTEST_HAS_RTTI
  2943. // Minimal const-propagating pointer.
  2944. template <typename T>
  2945. class ConstPropagatingPtr {
  2946. public:
  2947. typedef T element_type;
  2948. ConstPropagatingPtr() : val_() {}
  2949. explicit ConstPropagatingPtr(T* t) : val_(t) {}
  2950. ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
  2951. T* get() { return val_; }
  2952. T& operator*() { return *val_; }
  2953. // Most smart pointers return non-const T* and T& from the next methods.
  2954. const T* get() const { return val_; }
  2955. const T& operator*() const { return *val_; }
  2956. private:
  2957. T* val_;
  2958. };
  2959. TEST(PointeeTest, WorksWithConstPropagatingPointers) {
  2960. const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
  2961. int three = 3;
  2962. const ConstPropagatingPtr<int> co(&three);
  2963. ConstPropagatingPtr<int> o(&three);
  2964. EXPECT_TRUE(m.Matches(o));
  2965. EXPECT_TRUE(m.Matches(co));
  2966. *o = 6;
  2967. EXPECT_FALSE(m.Matches(o));
  2968. EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
  2969. }
  2970. TEST(PointeeTest, NeverMatchesNull) {
  2971. const Matcher<const char*> m = Pointee(_);
  2972. EXPECT_FALSE(m.Matches(nullptr));
  2973. }
  2974. // Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
  2975. TEST(PointeeTest, MatchesAgainstAValue) {
  2976. const Matcher<int*> m = Pointee(5);
  2977. int n = 5;
  2978. EXPECT_TRUE(m.Matches(&n));
  2979. n = -1;
  2980. EXPECT_FALSE(m.Matches(&n));
  2981. EXPECT_FALSE(m.Matches(nullptr));
  2982. }
  2983. TEST(PointeeTest, CanDescribeSelf) {
  2984. const Matcher<int*> m = Pointee(Gt(3));
  2985. EXPECT_EQ("points to a value that is > 3", Describe(m));
  2986. EXPECT_EQ("does not point to a value that is > 3",
  2987. DescribeNegation(m));
  2988. }
  2989. TEST(PointeeTest, CanExplainMatchResult) {
  2990. const Matcher<const std::string*> m = Pointee(StartsWith("Hi"));
  2991. EXPECT_EQ("", Explain(m, static_cast<const std::string*>(nullptr)));
  2992. const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
  2993. long n = 3; // NOLINT
  2994. EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
  2995. Explain(m2, &n));
  2996. }
  2997. TEST(PointeeTest, AlwaysExplainsPointee) {
  2998. const Matcher<int*> m = Pointee(0);
  2999. int n = 42;
  3000. EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
  3001. }
  3002. // An uncopyable class.
  3003. class Uncopyable {
  3004. public:
  3005. Uncopyable() : value_(-1) {}
  3006. explicit Uncopyable(int a_value) : value_(a_value) {}
  3007. int value() const { return value_; }
  3008. void set_value(int i) { value_ = i; }
  3009. private:
  3010. int value_;
  3011. GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
  3012. };
  3013. // Returns true if and only if x.value() is positive.
  3014. bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
  3015. MATCHER_P(UncopyableIs, inner_matcher, "") {
  3016. return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
  3017. }
  3018. // A user-defined struct for testing Field().
  3019. struct AStruct {
  3020. AStruct() : x(0), y(1.0), z(5), p(nullptr) {}
  3021. AStruct(const AStruct& rhs)
  3022. : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
  3023. int x; // A non-const field.
  3024. const double y; // A const field.
  3025. Uncopyable z; // An uncopyable field.
  3026. const char* p; // A pointer field.
  3027. private:
  3028. GTEST_DISALLOW_ASSIGN_(AStruct);
  3029. };
  3030. // A derived struct for testing Field().
  3031. struct DerivedStruct : public AStruct {
  3032. char ch;
  3033. private:
  3034. GTEST_DISALLOW_ASSIGN_(DerivedStruct);
  3035. };
  3036. // Tests that Field(&Foo::field, ...) works when field is non-const.
  3037. TEST(FieldTest, WorksForNonConstField) {
  3038. Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
  3039. Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0));
  3040. AStruct a;
  3041. EXPECT_TRUE(m.Matches(a));
  3042. EXPECT_TRUE(m_with_name.Matches(a));
  3043. a.x = -1;
  3044. EXPECT_FALSE(m.Matches(a));
  3045. EXPECT_FALSE(m_with_name.Matches(a));
  3046. }
  3047. // Tests that Field(&Foo::field, ...) works when field is const.
  3048. TEST(FieldTest, WorksForConstField) {
  3049. AStruct a;
  3050. Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
  3051. Matcher<AStruct> m_with_name = Field("y", &AStruct::y, Ge(0.0));
  3052. EXPECT_TRUE(m.Matches(a));
  3053. EXPECT_TRUE(m_with_name.Matches(a));
  3054. m = Field(&AStruct::y, Le(0.0));
  3055. m_with_name = Field("y", &AStruct::y, Le(0.0));
  3056. EXPECT_FALSE(m.Matches(a));
  3057. EXPECT_FALSE(m_with_name.Matches(a));
  3058. }
  3059. // Tests that Field(&Foo::field, ...) works when field is not copyable.
  3060. TEST(FieldTest, WorksForUncopyableField) {
  3061. AStruct a;
  3062. Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
  3063. EXPECT_TRUE(m.Matches(a));
  3064. m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
  3065. EXPECT_FALSE(m.Matches(a));
  3066. }
  3067. // Tests that Field(&Foo::field, ...) works when field is a pointer.
  3068. TEST(FieldTest, WorksForPointerField) {
  3069. // Matching against NULL.
  3070. Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr));
  3071. AStruct a;
  3072. EXPECT_TRUE(m.Matches(a));
  3073. a.p = "hi";
  3074. EXPECT_FALSE(m.Matches(a));
  3075. // Matching a pointer that is not NULL.
  3076. m = Field(&AStruct::p, StartsWith("hi"));
  3077. a.p = "hill";
  3078. EXPECT_TRUE(m.Matches(a));
  3079. a.p = "hole";
  3080. EXPECT_FALSE(m.Matches(a));
  3081. }
  3082. // Tests that Field() works when the object is passed by reference.
  3083. TEST(FieldTest, WorksForByRefArgument) {
  3084. Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
  3085. AStruct a;
  3086. EXPECT_TRUE(m.Matches(a));
  3087. a.x = -1;
  3088. EXPECT_FALSE(m.Matches(a));
  3089. }
  3090. // Tests that Field(&Foo::field, ...) works when the argument's type
  3091. // is a sub-type of Foo.
  3092. TEST(FieldTest, WorksForArgumentOfSubType) {
  3093. // Note that the matcher expects DerivedStruct but we say AStruct
  3094. // inside Field().
  3095. Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
  3096. DerivedStruct d;
  3097. EXPECT_TRUE(m.Matches(d));
  3098. d.x = -1;
  3099. EXPECT_FALSE(m.Matches(d));
  3100. }
  3101. // Tests that Field(&Foo::field, m) works when field's type and m's
  3102. // argument type are compatible but not the same.
  3103. TEST(FieldTest, WorksForCompatibleMatcherType) {
  3104. // The field is an int, but the inner matcher expects a signed char.
  3105. Matcher<const AStruct&> m = Field(&AStruct::x,
  3106. Matcher<signed char>(Ge(0)));
  3107. AStruct a;
  3108. EXPECT_TRUE(m.Matches(a));
  3109. a.x = -1;
  3110. EXPECT_FALSE(m.Matches(a));
  3111. }
  3112. // Tests that Field() can describe itself.
  3113. TEST(FieldTest, CanDescribeSelf) {
  3114. Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
  3115. EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
  3116. EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
  3117. }
  3118. TEST(FieldTest, CanDescribeSelfWithFieldName) {
  3119. Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
  3120. EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
  3121. EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
  3122. DescribeNegation(m));
  3123. }
  3124. // Tests that Field() can explain the match result.
  3125. TEST(FieldTest, CanExplainMatchResult) {
  3126. Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
  3127. AStruct a;
  3128. a.x = 1;
  3129. EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
  3130. m = Field(&AStruct::x, GreaterThan(0));
  3131. EXPECT_EQ(
  3132. "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
  3133. Explain(m, a));
  3134. }
  3135. TEST(FieldTest, CanExplainMatchResultWithFieldName) {
  3136. Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
  3137. AStruct a;
  3138. a.x = 1;
  3139. EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a));
  3140. m = Field("field_name", &AStruct::x, GreaterThan(0));
  3141. EXPECT_EQ("whose field `field_name` is 1" + OfType("int") +
  3142. ", which is 1 more than 0",
  3143. Explain(m, a));
  3144. }
  3145. // Tests that Field() works when the argument is a pointer to const.
  3146. TEST(FieldForPointerTest, WorksForPointerToConst) {
  3147. Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
  3148. AStruct a;
  3149. EXPECT_TRUE(m.Matches(&a));
  3150. a.x = -1;
  3151. EXPECT_FALSE(m.Matches(&a));
  3152. }
  3153. // Tests that Field() works when the argument is a pointer to non-const.
  3154. TEST(FieldForPointerTest, WorksForPointerToNonConst) {
  3155. Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
  3156. AStruct a;
  3157. EXPECT_TRUE(m.Matches(&a));
  3158. a.x = -1;
  3159. EXPECT_FALSE(m.Matches(&a));
  3160. }
  3161. // Tests that Field() works when the argument is a reference to a const pointer.
  3162. TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
  3163. Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
  3164. AStruct a;
  3165. EXPECT_TRUE(m.Matches(&a));
  3166. a.x = -1;
  3167. EXPECT_FALSE(m.Matches(&a));
  3168. }
  3169. // Tests that Field() does not match the NULL pointer.
  3170. TEST(FieldForPointerTest, DoesNotMatchNull) {
  3171. Matcher<const AStruct*> m = Field(&AStruct::x, _);
  3172. EXPECT_FALSE(m.Matches(nullptr));
  3173. }
  3174. // Tests that Field(&Foo::field, ...) works when the argument's type
  3175. // is a sub-type of const Foo*.
  3176. TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
  3177. // Note that the matcher expects DerivedStruct but we say AStruct
  3178. // inside Field().
  3179. Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
  3180. DerivedStruct d;
  3181. EXPECT_TRUE(m.Matches(&d));
  3182. d.x = -1;
  3183. EXPECT_FALSE(m.Matches(&d));
  3184. }
  3185. // Tests that Field() can describe itself when used to match a pointer.
  3186. TEST(FieldForPointerTest, CanDescribeSelf) {
  3187. Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
  3188. EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
  3189. EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
  3190. }
  3191. TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) {
  3192. Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
  3193. EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
  3194. EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
  3195. DescribeNegation(m));
  3196. }
  3197. // Tests that Field() can explain the result of matching a pointer.
  3198. TEST(FieldForPointerTest, CanExplainMatchResult) {
  3199. Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
  3200. AStruct a;
  3201. a.x = 1;
  3202. EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
  3203. EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
  3204. Explain(m, &a));
  3205. m = Field(&AStruct::x, GreaterThan(0));
  3206. EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
  3207. ", which is 1 more than 0", Explain(m, &a));
  3208. }
  3209. TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) {
  3210. Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
  3211. AStruct a;
  3212. a.x = 1;
  3213. EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
  3214. EXPECT_EQ(
  3215. "which points to an object whose field `field_name` is 1" + OfType("int"),
  3216. Explain(m, &a));
  3217. m = Field("field_name", &AStruct::x, GreaterThan(0));
  3218. EXPECT_EQ("which points to an object whose field `field_name` is 1" +
  3219. OfType("int") + ", which is 1 more than 0",
  3220. Explain(m, &a));
  3221. }
  3222. // A user-defined class for testing Property().
  3223. class AClass {
  3224. public:
  3225. AClass() : n_(0) {}
  3226. // A getter that returns a non-reference.
  3227. int n() const { return n_; }
  3228. void set_n(int new_n) { n_ = new_n; }
  3229. // A getter that returns a reference to const.
  3230. const std::string& s() const { return s_; }
  3231. const std::string& s_ref() const & { return s_; }
  3232. void set_s(const std::string& new_s) { s_ = new_s; }
  3233. // A getter that returns a reference to non-const.
  3234. double& x() const { return x_; }
  3235. private:
  3236. int n_;
  3237. std::string s_;
  3238. static double x_;
  3239. };
  3240. double AClass::x_ = 0.0;
  3241. // A derived class for testing Property().
  3242. class DerivedClass : public AClass {
  3243. public:
  3244. int k() const { return k_; }
  3245. private:
  3246. int k_;
  3247. };
  3248. // Tests that Property(&Foo::property, ...) works when property()
  3249. // returns a non-reference.
  3250. TEST(PropertyTest, WorksForNonReferenceProperty) {
  3251. Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
  3252. Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0));
  3253. AClass a;
  3254. a.set_n(1);
  3255. EXPECT_TRUE(m.Matches(a));
  3256. EXPECT_TRUE(m_with_name.Matches(a));
  3257. a.set_n(-1);
  3258. EXPECT_FALSE(m.Matches(a));
  3259. EXPECT_FALSE(m_with_name.Matches(a));
  3260. }
  3261. // Tests that Property(&Foo::property, ...) works when property()
  3262. // returns a reference to const.
  3263. TEST(PropertyTest, WorksForReferenceToConstProperty) {
  3264. Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
  3265. Matcher<const AClass&> m_with_name =
  3266. Property("s", &AClass::s, StartsWith("hi"));
  3267. AClass a;
  3268. a.set_s("hill");
  3269. EXPECT_TRUE(m.Matches(a));
  3270. EXPECT_TRUE(m_with_name.Matches(a));
  3271. a.set_s("hole");
  3272. EXPECT_FALSE(m.Matches(a));
  3273. EXPECT_FALSE(m_with_name.Matches(a));
  3274. }
  3275. // Tests that Property(&Foo::property, ...) works when property() is
  3276. // ref-qualified.
  3277. TEST(PropertyTest, WorksForRefQualifiedProperty) {
  3278. Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi"));
  3279. Matcher<const AClass&> m_with_name =
  3280. Property("s", &AClass::s_ref, StartsWith("hi"));
  3281. AClass a;
  3282. a.set_s("hill");
  3283. EXPECT_TRUE(m.Matches(a));
  3284. EXPECT_TRUE(m_with_name.Matches(a));
  3285. a.set_s("hole");
  3286. EXPECT_FALSE(m.Matches(a));
  3287. EXPECT_FALSE(m_with_name.Matches(a));
  3288. }
  3289. // Tests that Property(&Foo::property, ...) works when property()
  3290. // returns a reference to non-const.
  3291. TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
  3292. double x = 0.0;
  3293. AClass a;
  3294. Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
  3295. EXPECT_FALSE(m.Matches(a));
  3296. m = Property(&AClass::x, Not(Ref(x)));
  3297. EXPECT_TRUE(m.Matches(a));
  3298. }
  3299. // Tests that Property(&Foo::property, ...) works when the argument is
  3300. // passed by value.
  3301. TEST(PropertyTest, WorksForByValueArgument) {
  3302. Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
  3303. AClass a;
  3304. a.set_s("hill");
  3305. EXPECT_TRUE(m.Matches(a));
  3306. a.set_s("hole");
  3307. EXPECT_FALSE(m.Matches(a));
  3308. }
  3309. // Tests that Property(&Foo::property, ...) works when the argument's
  3310. // type is a sub-type of Foo.
  3311. TEST(PropertyTest, WorksForArgumentOfSubType) {
  3312. // The matcher expects a DerivedClass, but inside the Property() we
  3313. // say AClass.
  3314. Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
  3315. DerivedClass d;
  3316. d.set_n(1);
  3317. EXPECT_TRUE(m.Matches(d));
  3318. d.set_n(-1);
  3319. EXPECT_FALSE(m.Matches(d));
  3320. }
  3321. // Tests that Property(&Foo::property, m) works when property()'s type
  3322. // and m's argument type are compatible but different.
  3323. TEST(PropertyTest, WorksForCompatibleMatcherType) {
  3324. // n() returns an int but the inner matcher expects a signed char.
  3325. Matcher<const AClass&> m = Property(&AClass::n,
  3326. Matcher<signed char>(Ge(0)));
  3327. Matcher<const AClass&> m_with_name =
  3328. Property("n", &AClass::n, Matcher<signed char>(Ge(0)));
  3329. AClass a;
  3330. EXPECT_TRUE(m.Matches(a));
  3331. EXPECT_TRUE(m_with_name.Matches(a));
  3332. a.set_n(-1);
  3333. EXPECT_FALSE(m.Matches(a));
  3334. EXPECT_FALSE(m_with_name.Matches(a));
  3335. }
  3336. // Tests that Property() can describe itself.
  3337. TEST(PropertyTest, CanDescribeSelf) {
  3338. Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
  3339. EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
  3340. EXPECT_EQ("is an object whose given property isn't >= 0",
  3341. DescribeNegation(m));
  3342. }
  3343. TEST(PropertyTest, CanDescribeSelfWithPropertyName) {
  3344. Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
  3345. EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
  3346. EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
  3347. DescribeNegation(m));
  3348. }
  3349. // Tests that Property() can explain the match result.
  3350. TEST(PropertyTest, CanExplainMatchResult) {
  3351. Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
  3352. AClass a;
  3353. a.set_n(1);
  3354. EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
  3355. m = Property(&AClass::n, GreaterThan(0));
  3356. EXPECT_EQ(
  3357. "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
  3358. Explain(m, a));
  3359. }
  3360. TEST(PropertyTest, CanExplainMatchResultWithPropertyName) {
  3361. Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
  3362. AClass a;
  3363. a.set_n(1);
  3364. EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a));
  3365. m = Property("fancy_name", &AClass::n, GreaterThan(0));
  3366. EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") +
  3367. ", which is 1 more than 0",
  3368. Explain(m, a));
  3369. }
  3370. // Tests that Property() works when the argument is a pointer to const.
  3371. TEST(PropertyForPointerTest, WorksForPointerToConst) {
  3372. Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
  3373. AClass a;
  3374. a.set_n(1);
  3375. EXPECT_TRUE(m.Matches(&a));
  3376. a.set_n(-1);
  3377. EXPECT_FALSE(m.Matches(&a));
  3378. }
  3379. // Tests that Property() works when the argument is a pointer to non-const.
  3380. TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
  3381. Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
  3382. AClass a;
  3383. a.set_s("hill");
  3384. EXPECT_TRUE(m.Matches(&a));
  3385. a.set_s("hole");
  3386. EXPECT_FALSE(m.Matches(&a));
  3387. }
  3388. // Tests that Property() works when the argument is a reference to a
  3389. // const pointer.
  3390. TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
  3391. Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
  3392. AClass a;
  3393. a.set_s("hill");
  3394. EXPECT_TRUE(m.Matches(&a));
  3395. a.set_s("hole");
  3396. EXPECT_FALSE(m.Matches(&a));
  3397. }
  3398. // Tests that Property() does not match the NULL pointer.
  3399. TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
  3400. Matcher<const AClass*> m = Property(&AClass::x, _);
  3401. EXPECT_FALSE(m.Matches(nullptr));
  3402. }
  3403. // Tests that Property(&Foo::property, ...) works when the argument's
  3404. // type is a sub-type of const Foo*.
  3405. TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
  3406. // The matcher expects a DerivedClass, but inside the Property() we
  3407. // say AClass.
  3408. Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
  3409. DerivedClass d;
  3410. d.set_n(1);
  3411. EXPECT_TRUE(m.Matches(&d));
  3412. d.set_n(-1);
  3413. EXPECT_FALSE(m.Matches(&d));
  3414. }
  3415. // Tests that Property() can describe itself when used to match a pointer.
  3416. TEST(PropertyForPointerTest, CanDescribeSelf) {
  3417. Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
  3418. EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
  3419. EXPECT_EQ("is an object whose given property isn't >= 0",
  3420. DescribeNegation(m));
  3421. }
  3422. TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) {
  3423. Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
  3424. EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
  3425. EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
  3426. DescribeNegation(m));
  3427. }
  3428. // Tests that Property() can explain the result of matching a pointer.
  3429. TEST(PropertyForPointerTest, CanExplainMatchResult) {
  3430. Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
  3431. AClass a;
  3432. a.set_n(1);
  3433. EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
  3434. EXPECT_EQ(
  3435. "which points to an object whose given property is 1" + OfType("int"),
  3436. Explain(m, &a));
  3437. m = Property(&AClass::n, GreaterThan(0));
  3438. EXPECT_EQ("which points to an object whose given property is 1" +
  3439. OfType("int") + ", which is 1 more than 0",
  3440. Explain(m, &a));
  3441. }
  3442. TEST(PropertyForPointerTest, CanExplainMatchResultWithPropertyName) {
  3443. Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
  3444. AClass a;
  3445. a.set_n(1);
  3446. EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
  3447. EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
  3448. OfType("int"),
  3449. Explain(m, &a));
  3450. m = Property("fancy_name", &AClass::n, GreaterThan(0));
  3451. EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
  3452. OfType("int") + ", which is 1 more than 0",
  3453. Explain(m, &a));
  3454. }
  3455. // Tests ResultOf.
  3456. // Tests that ResultOf(f, ...) compiles and works as expected when f is a
  3457. // function pointer.
  3458. std::string IntToStringFunction(int input) {
  3459. return input == 1 ? "foo" : "bar";
  3460. }
  3461. TEST(ResultOfTest, WorksForFunctionPointers) {
  3462. Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));
  3463. EXPECT_TRUE(matcher.Matches(1));
  3464. EXPECT_FALSE(matcher.Matches(2));
  3465. }
  3466. // Tests that ResultOf() can describe itself.
  3467. TEST(ResultOfTest, CanDescribeItself) {
  3468. Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
  3469. EXPECT_EQ("is mapped by the given callable to a value that "
  3470. "is equal to \"foo\"", Describe(matcher));
  3471. EXPECT_EQ("is mapped by the given callable to a value that "
  3472. "isn't equal to \"foo\"", DescribeNegation(matcher));
  3473. }
  3474. // Tests that ResultOf() can explain the match result.
  3475. int IntFunction(int input) { return input == 42 ? 80 : 90; }
  3476. TEST(ResultOfTest, CanExplainMatchResult) {
  3477. Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
  3478. EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
  3479. Explain(matcher, 36));
  3480. matcher = ResultOf(&IntFunction, GreaterThan(85));
  3481. EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
  3482. ", which is 5 more than 85", Explain(matcher, 36));
  3483. }
  3484. // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
  3485. // returns a non-reference.
  3486. TEST(ResultOfTest, WorksForNonReferenceResults) {
  3487. Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
  3488. EXPECT_TRUE(matcher.Matches(42));
  3489. EXPECT_FALSE(matcher.Matches(36));
  3490. }
  3491. // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
  3492. // returns a reference to non-const.
  3493. double& DoubleFunction(double& input) { return input; } // NOLINT
  3494. Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
  3495. return obj;
  3496. }
  3497. TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
  3498. double x = 3.14;
  3499. double x2 = x;
  3500. Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
  3501. EXPECT_TRUE(matcher.Matches(x));
  3502. EXPECT_FALSE(matcher.Matches(x2));
  3503. // Test that ResultOf works with uncopyable objects
  3504. Uncopyable obj(0);
  3505. Uncopyable obj2(0);
  3506. Matcher<Uncopyable&> matcher2 =
  3507. ResultOf(&RefUncopyableFunction, Ref(obj));
  3508. EXPECT_TRUE(matcher2.Matches(obj));
  3509. EXPECT_FALSE(matcher2.Matches(obj2));
  3510. }
  3511. // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
  3512. // returns a reference to const.
  3513. const std::string& StringFunction(const std::string& input) { return input; }
  3514. TEST(ResultOfTest, WorksForReferenceToConstResults) {
  3515. std::string s = "foo";
  3516. std::string s2 = s;
  3517. Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));
  3518. EXPECT_TRUE(matcher.Matches(s));
  3519. EXPECT_FALSE(matcher.Matches(s2));
  3520. }
  3521. // Tests that ResultOf(f, m) works when f(x) and m's
  3522. // argument types are compatible but different.
  3523. TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
  3524. // IntFunction() returns int but the inner matcher expects a signed char.
  3525. Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
  3526. EXPECT_TRUE(matcher.Matches(36));
  3527. EXPECT_FALSE(matcher.Matches(42));
  3528. }
  3529. // Tests that the program aborts when ResultOf is passed
  3530. // a NULL function pointer.
  3531. TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
  3532. EXPECT_DEATH_IF_SUPPORTED(
  3533. ResultOf(static_cast<std::string (*)(int dummy)>(nullptr),
  3534. Eq(std::string("foo"))),
  3535. "NULL function pointer is passed into ResultOf\\(\\)\\.");
  3536. }
  3537. // Tests that ResultOf(f, ...) compiles and works as expected when f is a
  3538. // function reference.
  3539. TEST(ResultOfTest, WorksForFunctionReferences) {
  3540. Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
  3541. EXPECT_TRUE(matcher.Matches(1));
  3542. EXPECT_FALSE(matcher.Matches(2));
  3543. }
  3544. // Tests that ResultOf(f, ...) compiles and works as expected when f is a
  3545. // function object.
  3546. struct Functor {
  3547. std::string operator()(int input) const {
  3548. return IntToStringFunction(input);
  3549. }
  3550. };
  3551. TEST(ResultOfTest, WorksForFunctors) {
  3552. Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));
  3553. EXPECT_TRUE(matcher.Matches(1));
  3554. EXPECT_FALSE(matcher.Matches(2));
  3555. }
  3556. // Tests that ResultOf(f, ...) compiles and works as expected when f is a
  3557. // functor with more than one operator() defined. ResultOf() must work
  3558. // for each defined operator().
  3559. struct PolymorphicFunctor {
  3560. typedef int result_type;
  3561. int operator()(int n) { return n; }
  3562. int operator()(const char* s) { return static_cast<int>(strlen(s)); }
  3563. std::string operator()(int *p) { return p ? "good ptr" : "null"; }
  3564. };
  3565. TEST(ResultOfTest, WorksForPolymorphicFunctors) {
  3566. Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
  3567. EXPECT_TRUE(matcher_int.Matches(10));
  3568. EXPECT_FALSE(matcher_int.Matches(2));
  3569. Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
  3570. EXPECT_TRUE(matcher_string.Matches("long string"));
  3571. EXPECT_FALSE(matcher_string.Matches("shrt"));
  3572. }
  3573. TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) {
  3574. Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr");
  3575. int n = 0;
  3576. EXPECT_TRUE(matcher.Matches(&n));
  3577. EXPECT_FALSE(matcher.Matches(nullptr));
  3578. }
  3579. TEST(ResultOfTest, WorksForLambdas) {
  3580. Matcher<int> matcher = ResultOf(
  3581. [](int str_len) {
  3582. return std::string(static_cast<size_t>(str_len), 'x');
  3583. },
  3584. "xxx");
  3585. EXPECT_TRUE(matcher.Matches(3));
  3586. EXPECT_FALSE(matcher.Matches(1));
  3587. }
  3588. TEST(ResultOfTest, WorksForNonCopyableArguments) {
  3589. Matcher<std::unique_ptr<int>> matcher = ResultOf(
  3590. [](const std::unique_ptr<int>& str_len) {
  3591. return std::string(static_cast<size_t>(*str_len), 'x');
  3592. },
  3593. "xxx");
  3594. EXPECT_TRUE(matcher.Matches(std::unique_ptr<int>(new int(3))));
  3595. EXPECT_FALSE(matcher.Matches(std::unique_ptr<int>(new int(1))));
  3596. }
  3597. const int* ReferencingFunction(const int& n) { return &n; }
  3598. struct ReferencingFunctor {
  3599. typedef const int* result_type;
  3600. result_type operator()(const int& n) { return &n; }
  3601. };
  3602. TEST(ResultOfTest, WorksForReferencingCallables) {
  3603. const int n = 1;
  3604. const int n2 = 1;
  3605. Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
  3606. EXPECT_TRUE(matcher2.Matches(n));
  3607. EXPECT_FALSE(matcher2.Matches(n2));
  3608. Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
  3609. EXPECT_TRUE(matcher3.Matches(n));
  3610. EXPECT_FALSE(matcher3.Matches(n2));
  3611. }
  3612. class DivisibleByImpl {
  3613. public:
  3614. explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
  3615. // For testing using ExplainMatchResultTo() with polymorphic matchers.
  3616. template <typename T>
  3617. bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
  3618. *listener << "which is " << (n % divider_) << " modulo "
  3619. << divider_;
  3620. return (n % divider_) == 0;
  3621. }
  3622. void DescribeTo(ostream* os) const {
  3623. *os << "is divisible by " << divider_;
  3624. }
  3625. void DescribeNegationTo(ostream* os) const {
  3626. *os << "is not divisible by " << divider_;
  3627. }
  3628. void set_divider(int a_divider) { divider_ = a_divider; }
  3629. int divider() const { return divider_; }
  3630. private:
  3631. int divider_;
  3632. };
  3633. PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
  3634. return MakePolymorphicMatcher(DivisibleByImpl(n));
  3635. }
  3636. // Tests that when AllOf() fails, only the first failing matcher is
  3637. // asked to explain why.
  3638. TEST(ExplainMatchResultTest, AllOf_False_False) {
  3639. const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
  3640. EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
  3641. }
  3642. // Tests that when AllOf() fails, only the first failing matcher is
  3643. // asked to explain why.
  3644. TEST(ExplainMatchResultTest, AllOf_False_True) {
  3645. const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
  3646. EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
  3647. }
  3648. // Tests that when AllOf() fails, only the first failing matcher is
  3649. // asked to explain why.
  3650. TEST(ExplainMatchResultTest, AllOf_True_False) {
  3651. const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
  3652. EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
  3653. }
  3654. // Tests that when AllOf() succeeds, all matchers are asked to explain
  3655. // why.
  3656. TEST(ExplainMatchResultTest, AllOf_True_True) {
  3657. const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
  3658. EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
  3659. }
  3660. TEST(ExplainMatchResultTest, AllOf_True_True_2) {
  3661. const Matcher<int> m = AllOf(Ge(2), Le(3));
  3662. EXPECT_EQ("", Explain(m, 2));
  3663. }
  3664. TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
  3665. const Matcher<int> m = GreaterThan(5);
  3666. EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
  3667. }
  3668. // The following two tests verify that values without a public copy
  3669. // ctor can be used as arguments to matchers like Eq(), Ge(), and etc
  3670. // with the help of ByRef().
  3671. class NotCopyable {
  3672. public:
  3673. explicit NotCopyable(int a_value) : value_(a_value) {}
  3674. int value() const { return value_; }
  3675. bool operator==(const NotCopyable& rhs) const {
  3676. return value() == rhs.value();
  3677. }
  3678. bool operator>=(const NotCopyable& rhs) const {
  3679. return value() >= rhs.value();
  3680. }
  3681. private:
  3682. int value_;
  3683. GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
  3684. };
  3685. TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
  3686. const NotCopyable const_value1(1);
  3687. const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
  3688. const NotCopyable n1(1), n2(2);
  3689. EXPECT_TRUE(m.Matches(n1));
  3690. EXPECT_FALSE(m.Matches(n2));
  3691. }
  3692. TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
  3693. NotCopyable value2(2);
  3694. const Matcher<NotCopyable&> m = Ge(ByRef(value2));
  3695. NotCopyable n1(1), n2(2);
  3696. EXPECT_FALSE(m.Matches(n1));
  3697. EXPECT_TRUE(m.Matches(n2));
  3698. }
  3699. TEST(IsEmptyTest, ImplementsIsEmpty) {
  3700. vector<int> container;
  3701. EXPECT_THAT(container, IsEmpty());
  3702. container.push_back(0);
  3703. EXPECT_THAT(container, Not(IsEmpty()));
  3704. container.push_back(1);
  3705. EXPECT_THAT(container, Not(IsEmpty()));
  3706. }
  3707. TEST(IsEmptyTest, WorksWithString) {
  3708. std::string text;
  3709. EXPECT_THAT(text, IsEmpty());
  3710. text = "foo";
  3711. EXPECT_THAT(text, Not(IsEmpty()));
  3712. text = std::string("\0", 1);
  3713. EXPECT_THAT(text, Not(IsEmpty()));
  3714. }
  3715. TEST(IsEmptyTest, CanDescribeSelf) {
  3716. Matcher<vector<int> > m = IsEmpty();
  3717. EXPECT_EQ("is empty", Describe(m));
  3718. EXPECT_EQ("isn't empty", DescribeNegation(m));
  3719. }
  3720. TEST(IsEmptyTest, ExplainsResult) {
  3721. Matcher<vector<int> > m = IsEmpty();
  3722. vector<int> container;
  3723. EXPECT_EQ("", Explain(m, container));
  3724. container.push_back(0);
  3725. EXPECT_EQ("whose size is 1", Explain(m, container));
  3726. }
  3727. TEST(IsEmptyTest, WorksWithMoveOnly) {
  3728. ContainerHelper helper;
  3729. EXPECT_CALL(helper, Call(IsEmpty()));
  3730. helper.Call({});
  3731. }
  3732. TEST(IsTrueTest, IsTrueIsFalse) {
  3733. EXPECT_THAT(true, IsTrue());
  3734. EXPECT_THAT(false, IsFalse());
  3735. EXPECT_THAT(true, Not(IsFalse()));
  3736. EXPECT_THAT(false, Not(IsTrue()));
  3737. EXPECT_THAT(0, Not(IsTrue()));
  3738. EXPECT_THAT(0, IsFalse());
  3739. EXPECT_THAT(nullptr, Not(IsTrue()));
  3740. EXPECT_THAT(nullptr, IsFalse());
  3741. EXPECT_THAT(-1, IsTrue());
  3742. EXPECT_THAT(-1, Not(IsFalse()));
  3743. EXPECT_THAT(1, IsTrue());
  3744. EXPECT_THAT(1, Not(IsFalse()));
  3745. EXPECT_THAT(2, IsTrue());
  3746. EXPECT_THAT(2, Not(IsFalse()));
  3747. int a = 42;
  3748. EXPECT_THAT(a, IsTrue());
  3749. EXPECT_THAT(a, Not(IsFalse()));
  3750. EXPECT_THAT(&a, IsTrue());
  3751. EXPECT_THAT(&a, Not(IsFalse()));
  3752. EXPECT_THAT(false, Not(IsTrue()));
  3753. EXPECT_THAT(true, Not(IsFalse()));
  3754. EXPECT_THAT(std::true_type(), IsTrue());
  3755. EXPECT_THAT(std::true_type(), Not(IsFalse()));
  3756. EXPECT_THAT(std::false_type(), IsFalse());
  3757. EXPECT_THAT(std::false_type(), Not(IsTrue()));
  3758. EXPECT_THAT(nullptr, Not(IsTrue()));
  3759. EXPECT_THAT(nullptr, IsFalse());
  3760. std::unique_ptr<int> null_unique;
  3761. std::unique_ptr<int> nonnull_unique(new int(0));
  3762. EXPECT_THAT(null_unique, Not(IsTrue()));
  3763. EXPECT_THAT(null_unique, IsFalse());
  3764. EXPECT_THAT(nonnull_unique, IsTrue());
  3765. EXPECT_THAT(nonnull_unique, Not(IsFalse()));
  3766. }
  3767. TEST(SizeIsTest, ImplementsSizeIs) {
  3768. vector<int> container;
  3769. EXPECT_THAT(container, SizeIs(0));
  3770. EXPECT_THAT(container, Not(SizeIs(1)));
  3771. container.push_back(0);
  3772. EXPECT_THAT(container, Not(SizeIs(0)));
  3773. EXPECT_THAT(container, SizeIs(1));
  3774. container.push_back(0);
  3775. EXPECT_THAT(container, Not(SizeIs(0)));
  3776. EXPECT_THAT(container, SizeIs(2));
  3777. }
  3778. TEST(SizeIsTest, WorksWithMap) {
  3779. map<std::string, int> container;
  3780. EXPECT_THAT(container, SizeIs(0));
  3781. EXPECT_THAT(container, Not(SizeIs(1)));
  3782. container.insert(make_pair("foo", 1));
  3783. EXPECT_THAT(container, Not(SizeIs(0)));
  3784. EXPECT_THAT(container, SizeIs(1));
  3785. container.insert(make_pair("bar", 2));
  3786. EXPECT_THAT(container, Not(SizeIs(0)));
  3787. EXPECT_THAT(container, SizeIs(2));
  3788. }
  3789. TEST(SizeIsTest, WorksWithReferences) {
  3790. vector<int> container;
  3791. Matcher<const vector<int>&> m = SizeIs(1);
  3792. EXPECT_THAT(container, Not(m));
  3793. container.push_back(0);
  3794. EXPECT_THAT(container, m);
  3795. }
  3796. TEST(SizeIsTest, WorksWithMoveOnly) {
  3797. ContainerHelper helper;
  3798. EXPECT_CALL(helper, Call(SizeIs(3)));
  3799. helper.Call(MakeUniquePtrs({1, 2, 3}));
  3800. }
  3801. // SizeIs should work for any type that provides a size() member function.
  3802. // For example, a size_type member type should not need to be provided.
  3803. struct MinimalistCustomType {
  3804. int size() const { return 1; }
  3805. };
  3806. TEST(SizeIsTest, WorksWithMinimalistCustomType) {
  3807. MinimalistCustomType container;
  3808. EXPECT_THAT(container, SizeIs(1));
  3809. EXPECT_THAT(container, Not(SizeIs(0)));
  3810. }
  3811. TEST(SizeIsTest, CanDescribeSelf) {
  3812. Matcher<vector<int> > m = SizeIs(2);
  3813. EXPECT_EQ("size is equal to 2", Describe(m));
  3814. EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
  3815. }
  3816. TEST(SizeIsTest, ExplainsResult) {
  3817. Matcher<vector<int> > m1 = SizeIs(2);
  3818. Matcher<vector<int> > m2 = SizeIs(Lt(2u));
  3819. Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
  3820. Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
  3821. vector<int> container;
  3822. EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
  3823. EXPECT_EQ("whose size 0 matches", Explain(m2, container));
  3824. EXPECT_EQ("whose size 0 matches", Explain(m3, container));
  3825. EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
  3826. Explain(m4, container));
  3827. container.push_back(0);
  3828. container.push_back(0);
  3829. EXPECT_EQ("whose size 2 matches", Explain(m1, container));
  3830. EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
  3831. EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
  3832. EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
  3833. Explain(m4, container));
  3834. }
  3835. #if GTEST_HAS_TYPED_TEST
  3836. // Tests ContainerEq with different container types, and
  3837. // different element types.
  3838. template <typename T>
  3839. class ContainerEqTest : public testing::Test {};
  3840. typedef testing::Types<
  3841. set<int>,
  3842. vector<size_t>,
  3843. multiset<size_t>,
  3844. list<int> >
  3845. ContainerEqTestTypes;
  3846. TYPED_TEST_SUITE(ContainerEqTest, ContainerEqTestTypes);
  3847. // Tests that the filled container is equal to itself.
  3848. TYPED_TEST(ContainerEqTest, EqualsSelf) {
  3849. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3850. TypeParam my_set(vals, vals + 6);
  3851. const Matcher<TypeParam> m = ContainerEq(my_set);
  3852. EXPECT_TRUE(m.Matches(my_set));
  3853. EXPECT_EQ("", Explain(m, my_set));
  3854. }
  3855. // Tests that missing values are reported.
  3856. TYPED_TEST(ContainerEqTest, ValueMissing) {
  3857. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3858. static const int test_vals[] = {2, 1, 8, 5};
  3859. TypeParam my_set(vals, vals + 6);
  3860. TypeParam test_set(test_vals, test_vals + 4);
  3861. const Matcher<TypeParam> m = ContainerEq(my_set);
  3862. EXPECT_FALSE(m.Matches(test_set));
  3863. EXPECT_EQ("which doesn't have these expected elements: 3",
  3864. Explain(m, test_set));
  3865. }
  3866. // Tests that added values are reported.
  3867. TYPED_TEST(ContainerEqTest, ValueAdded) {
  3868. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3869. static const int test_vals[] = {1, 2, 3, 5, 8, 46};
  3870. TypeParam my_set(vals, vals + 6);
  3871. TypeParam test_set(test_vals, test_vals + 6);
  3872. const Matcher<const TypeParam&> m = ContainerEq(my_set);
  3873. EXPECT_FALSE(m.Matches(test_set));
  3874. EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
  3875. }
  3876. // Tests that added and missing values are reported together.
  3877. TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
  3878. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3879. static const int test_vals[] = {1, 2, 3, 8, 46};
  3880. TypeParam my_set(vals, vals + 6);
  3881. TypeParam test_set(test_vals, test_vals + 5);
  3882. const Matcher<TypeParam> m = ContainerEq(my_set);
  3883. EXPECT_FALSE(m.Matches(test_set));
  3884. EXPECT_EQ("which has these unexpected elements: 46,\n"
  3885. "and doesn't have these expected elements: 5",
  3886. Explain(m, test_set));
  3887. }
  3888. // Tests duplicated value -- expect no explanation.
  3889. TYPED_TEST(ContainerEqTest, DuplicateDifference) {
  3890. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3891. static const int test_vals[] = {1, 2, 3, 5, 8};
  3892. TypeParam my_set(vals, vals + 6);
  3893. TypeParam test_set(test_vals, test_vals + 5);
  3894. const Matcher<const TypeParam&> m = ContainerEq(my_set);
  3895. // Depending on the container, match may be true or false
  3896. // But in any case there should be no explanation.
  3897. EXPECT_EQ("", Explain(m, test_set));
  3898. }
  3899. #endif // GTEST_HAS_TYPED_TEST
  3900. // Tests that multiple missing values are reported.
  3901. // Using just vector here, so order is predictable.
  3902. TEST(ContainerEqExtraTest, MultipleValuesMissing) {
  3903. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3904. static const int test_vals[] = {2, 1, 5};
  3905. vector<int> my_set(vals, vals + 6);
  3906. vector<int> test_set(test_vals, test_vals + 3);
  3907. const Matcher<vector<int> > m = ContainerEq(my_set);
  3908. EXPECT_FALSE(m.Matches(test_set));
  3909. EXPECT_EQ("which doesn't have these expected elements: 3, 8",
  3910. Explain(m, test_set));
  3911. }
  3912. // Tests that added values are reported.
  3913. // Using just vector here, so order is predictable.
  3914. TEST(ContainerEqExtraTest, MultipleValuesAdded) {
  3915. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3916. static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
  3917. list<size_t> my_set(vals, vals + 6);
  3918. list<size_t> test_set(test_vals, test_vals + 7);
  3919. const Matcher<const list<size_t>&> m = ContainerEq(my_set);
  3920. EXPECT_FALSE(m.Matches(test_set));
  3921. EXPECT_EQ("which has these unexpected elements: 92, 46",
  3922. Explain(m, test_set));
  3923. }
  3924. // Tests that added and missing values are reported together.
  3925. TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
  3926. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3927. static const int test_vals[] = {1, 2, 3, 92, 46};
  3928. list<size_t> my_set(vals, vals + 6);
  3929. list<size_t> test_set(test_vals, test_vals + 5);
  3930. const Matcher<const list<size_t> > m = ContainerEq(my_set);
  3931. EXPECT_FALSE(m.Matches(test_set));
  3932. EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
  3933. "and doesn't have these expected elements: 5, 8",
  3934. Explain(m, test_set));
  3935. }
  3936. // Tests to see that duplicate elements are detected,
  3937. // but (as above) not reported in the explanation.
  3938. TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
  3939. static const int vals[] = {1, 1, 2, 3, 5, 8};
  3940. static const int test_vals[] = {1, 2, 3, 5, 8};
  3941. vector<int> my_set(vals, vals + 6);
  3942. vector<int> test_set(test_vals, test_vals + 5);
  3943. const Matcher<vector<int> > m = ContainerEq(my_set);
  3944. EXPECT_TRUE(m.Matches(my_set));
  3945. EXPECT_FALSE(m.Matches(test_set));
  3946. // There is nothing to report when both sets contain all the same values.
  3947. EXPECT_EQ("", Explain(m, test_set));
  3948. }
  3949. // Tests that ContainerEq works for non-trivial associative containers,
  3950. // like maps.
  3951. TEST(ContainerEqExtraTest, WorksForMaps) {
  3952. map<int, std::string> my_map;
  3953. my_map[0] = "a";
  3954. my_map[1] = "b";
  3955. map<int, std::string> test_map;
  3956. test_map[0] = "aa";
  3957. test_map[1] = "b";
  3958. const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
  3959. EXPECT_TRUE(m.Matches(my_map));
  3960. EXPECT_FALSE(m.Matches(test_map));
  3961. EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
  3962. "and doesn't have these expected elements: (0, \"a\")",
  3963. Explain(m, test_map));
  3964. }
  3965. TEST(ContainerEqExtraTest, WorksForNativeArray) {
  3966. int a1[] = {1, 2, 3};
  3967. int a2[] = {1, 2, 3};
  3968. int b[] = {1, 2, 4};
  3969. EXPECT_THAT(a1, ContainerEq(a2));
  3970. EXPECT_THAT(a1, Not(ContainerEq(b)));
  3971. }
  3972. TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
  3973. const char a1[][3] = {"hi", "lo"};
  3974. const char a2[][3] = {"hi", "lo"};
  3975. const char b[][3] = {"lo", "hi"};
  3976. // Tests using ContainerEq() in the first dimension.
  3977. EXPECT_THAT(a1, ContainerEq(a2));
  3978. EXPECT_THAT(a1, Not(ContainerEq(b)));
  3979. // Tests using ContainerEq() in the second dimension.
  3980. EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
  3981. EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
  3982. }
  3983. TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
  3984. const int a1[] = {1, 2, 3};
  3985. const int a2[] = {1, 2, 3};
  3986. const int b[] = {1, 2, 3, 4};
  3987. const int* const p1 = a1;
  3988. EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2));
  3989. EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b)));
  3990. const int c[] = {1, 3, 2};
  3991. EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c)));
  3992. }
  3993. TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
  3994. std::string a1[][3] = {
  3995. {"hi", "hello", "ciao"},
  3996. {"bye", "see you", "ciao"}
  3997. };
  3998. std::string a2[][3] = {
  3999. {"hi", "hello", "ciao"},
  4000. {"bye", "see you", "ciao"}
  4001. };
  4002. const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
  4003. EXPECT_THAT(a1, m);
  4004. a2[0][0] = "ha";
  4005. EXPECT_THAT(a1, m);
  4006. }
  4007. TEST(WhenSortedByTest, WorksForEmptyContainer) {
  4008. const vector<int> numbers;
  4009. EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
  4010. EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
  4011. }
  4012. TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
  4013. vector<unsigned> numbers;
  4014. numbers.push_back(3);
  4015. numbers.push_back(1);
  4016. numbers.push_back(2);
  4017. numbers.push_back(2);
  4018. EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
  4019. ElementsAre(3, 2, 2, 1)));
  4020. EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
  4021. ElementsAre(1, 2, 2, 3))));
  4022. }
  4023. TEST(WhenSortedByTest, WorksForNonVectorContainer) {
  4024. list<std::string> words;
  4025. words.push_back("say");
  4026. words.push_back("hello");
  4027. words.push_back("world");
  4028. EXPECT_THAT(words, WhenSortedBy(less<std::string>(),
  4029. ElementsAre("hello", "say", "world")));
  4030. EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),
  4031. ElementsAre("say", "hello", "world"))));
  4032. }
  4033. TEST(WhenSortedByTest, WorksForNativeArray) {
  4034. const int numbers[] = {1, 3, 2, 4};
  4035. const int sorted_numbers[] = {1, 2, 3, 4};
  4036. EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
  4037. EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
  4038. ElementsAreArray(sorted_numbers)));
  4039. EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
  4040. }
  4041. TEST(WhenSortedByTest, CanDescribeSelf) {
  4042. const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
  4043. EXPECT_EQ("(when sorted) has 2 elements where\n"
  4044. "element #0 is equal to 1,\n"
  4045. "element #1 is equal to 2",
  4046. Describe(m));
  4047. EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
  4048. "element #0 isn't equal to 1, or\n"
  4049. "element #1 isn't equal to 2",
  4050. DescribeNegation(m));
  4051. }
  4052. TEST(WhenSortedByTest, ExplainsMatchResult) {
  4053. const int a[] = {2, 1};
  4054. EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
  4055. Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
  4056. EXPECT_EQ("which is { 1, 2 } when sorted",
  4057. Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
  4058. }
  4059. // WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
  4060. // need to test it as exhaustively as we test the latter.
  4061. TEST(WhenSortedTest, WorksForEmptyContainer) {
  4062. const vector<int> numbers;
  4063. EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
  4064. EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
  4065. }
  4066. TEST(WhenSortedTest, WorksForNonEmptyContainer) {
  4067. list<std::string> words;
  4068. words.push_back("3");
  4069. words.push_back("1");
  4070. words.push_back("2");
  4071. words.push_back("2");
  4072. EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
  4073. EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
  4074. }
  4075. TEST(WhenSortedTest, WorksForMapTypes) {
  4076. map<std::string, int> word_counts;
  4077. word_counts["and"] = 1;
  4078. word_counts["the"] = 1;
  4079. word_counts["buffalo"] = 2;
  4080. EXPECT_THAT(word_counts,
  4081. WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),
  4082. Pair("the", 1))));
  4083. EXPECT_THAT(word_counts,
  4084. Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
  4085. Pair("buffalo", 2)))));
  4086. }
  4087. TEST(WhenSortedTest, WorksForMultiMapTypes) {
  4088. multimap<int, int> ifib;
  4089. ifib.insert(make_pair(8, 6));
  4090. ifib.insert(make_pair(2, 3));
  4091. ifib.insert(make_pair(1, 1));
  4092. ifib.insert(make_pair(3, 4));
  4093. ifib.insert(make_pair(1, 2));
  4094. ifib.insert(make_pair(5, 5));
  4095. EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
  4096. Pair(1, 2),
  4097. Pair(2, 3),
  4098. Pair(3, 4),
  4099. Pair(5, 5),
  4100. Pair(8, 6))));
  4101. EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
  4102. Pair(2, 3),
  4103. Pair(1, 1),
  4104. Pair(3, 4),
  4105. Pair(1, 2),
  4106. Pair(5, 5)))));
  4107. }
  4108. TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
  4109. std::deque<int> d;
  4110. d.push_back(2);
  4111. d.push_back(1);
  4112. EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
  4113. EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
  4114. }
  4115. TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
  4116. std::deque<int> d;
  4117. d.push_back(2);
  4118. d.push_back(1);
  4119. Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
  4120. EXPECT_THAT(d, WhenSorted(vector_match));
  4121. Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
  4122. EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
  4123. }
  4124. // Deliberately bare pseudo-container.
  4125. // Offers only begin() and end() accessors, yielding InputIterator.
  4126. template <typename T>
  4127. class Streamlike {
  4128. private:
  4129. class ConstIter;
  4130. public:
  4131. typedef ConstIter const_iterator;
  4132. typedef T value_type;
  4133. template <typename InIter>
  4134. Streamlike(InIter first, InIter last) : remainder_(first, last) {}
  4135. const_iterator begin() const {
  4136. return const_iterator(this, remainder_.begin());
  4137. }
  4138. const_iterator end() const {
  4139. return const_iterator(this, remainder_.end());
  4140. }
  4141. private:
  4142. class ConstIter : public std::iterator<std::input_iterator_tag,
  4143. value_type,
  4144. ptrdiff_t,
  4145. const value_type*,
  4146. const value_type&> {
  4147. public:
  4148. ConstIter(const Streamlike* s,
  4149. typename std::list<value_type>::iterator pos)
  4150. : s_(s), pos_(pos) {}
  4151. const value_type& operator*() const { return *pos_; }
  4152. const value_type* operator->() const { return &*pos_; }
  4153. ConstIter& operator++() {
  4154. s_->remainder_.erase(pos_++);
  4155. return *this;
  4156. }
  4157. // *iter++ is required to work (see std::istreambuf_iterator).
  4158. // (void)iter++ is also required to work.
  4159. class PostIncrProxy {
  4160. public:
  4161. explicit PostIncrProxy(const value_type& value) : value_(value) {}
  4162. value_type operator*() const { return value_; }
  4163. private:
  4164. value_type value_;
  4165. };
  4166. PostIncrProxy operator++(int) {
  4167. PostIncrProxy proxy(**this);
  4168. ++(*this);
  4169. return proxy;
  4170. }
  4171. friend bool operator==(const ConstIter& a, const ConstIter& b) {
  4172. return a.s_ == b.s_ && a.pos_ == b.pos_;
  4173. }
  4174. friend bool operator!=(const ConstIter& a, const ConstIter& b) {
  4175. return !(a == b);
  4176. }
  4177. private:
  4178. const Streamlike* s_;
  4179. typename std::list<value_type>::iterator pos_;
  4180. };
  4181. friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
  4182. os << "[";
  4183. typedef typename std::list<value_type>::const_iterator Iter;
  4184. const char* sep = "";
  4185. for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
  4186. os << sep << *it;
  4187. sep = ",";
  4188. }
  4189. os << "]";
  4190. return os;
  4191. }
  4192. mutable std::list<value_type> remainder_; // modified by iteration
  4193. };
  4194. TEST(StreamlikeTest, Iteration) {
  4195. const int a[5] = {2, 1, 4, 5, 3};
  4196. Streamlike<int> s(a, a + 5);
  4197. Streamlike<int>::const_iterator it = s.begin();
  4198. const int* ip = a;
  4199. while (it != s.end()) {
  4200. SCOPED_TRACE(ip - a);
  4201. EXPECT_EQ(*ip++, *it++);
  4202. }
  4203. }
  4204. TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
  4205. std::forward_list<int> container;
  4206. EXPECT_THAT(container, BeginEndDistanceIs(0));
  4207. EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
  4208. container.push_front(0);
  4209. EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
  4210. EXPECT_THAT(container, BeginEndDistanceIs(1));
  4211. container.push_front(0);
  4212. EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
  4213. EXPECT_THAT(container, BeginEndDistanceIs(2));
  4214. }
  4215. TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
  4216. const int a[5] = {1, 2, 3, 4, 5};
  4217. Streamlike<int> s(a, a + 5);
  4218. EXPECT_THAT(s, BeginEndDistanceIs(5));
  4219. }
  4220. TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
  4221. Matcher<vector<int> > m = BeginEndDistanceIs(2);
  4222. EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
  4223. EXPECT_EQ("distance between begin() and end() isn't equal to 2",
  4224. DescribeNegation(m));
  4225. }
  4226. TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) {
  4227. ContainerHelper helper;
  4228. EXPECT_CALL(helper, Call(BeginEndDistanceIs(2)));
  4229. helper.Call(MakeUniquePtrs({1, 2}));
  4230. }
  4231. TEST(BeginEndDistanceIsTest, ExplainsResult) {
  4232. Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
  4233. Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
  4234. Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
  4235. Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
  4236. vector<int> container;
  4237. EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
  4238. Explain(m1, container));
  4239. EXPECT_EQ("whose distance between begin() and end() 0 matches",
  4240. Explain(m2, container));
  4241. EXPECT_EQ("whose distance between begin() and end() 0 matches",
  4242. Explain(m3, container));
  4243. EXPECT_EQ(
  4244. "whose distance between begin() and end() 0 doesn't match, which is 1 "
  4245. "less than 1",
  4246. Explain(m4, container));
  4247. container.push_back(0);
  4248. container.push_back(0);
  4249. EXPECT_EQ("whose distance between begin() and end() 2 matches",
  4250. Explain(m1, container));
  4251. EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
  4252. Explain(m2, container));
  4253. EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
  4254. Explain(m3, container));
  4255. EXPECT_EQ(
  4256. "whose distance between begin() and end() 2 matches, which is 1 more "
  4257. "than 1",
  4258. Explain(m4, container));
  4259. }
  4260. TEST(WhenSortedTest, WorksForStreamlike) {
  4261. // Streamlike 'container' provides only minimal iterator support.
  4262. // Its iterators are tagged with input_iterator_tag.
  4263. const int a[5] = {2, 1, 4, 5, 3};
  4264. Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
  4265. EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
  4266. EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
  4267. }
  4268. TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
  4269. const int a[] = {2, 1, 4, 5, 3};
  4270. Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
  4271. Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
  4272. EXPECT_THAT(s, WhenSorted(vector_match));
  4273. EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
  4274. }
  4275. TEST(IsSupersetOfTest, WorksForNativeArray) {
  4276. const int subset[] = {1, 4};
  4277. const int superset[] = {1, 2, 4};
  4278. const int disjoint[] = {1, 0, 3};
  4279. EXPECT_THAT(subset, IsSupersetOf(subset));
  4280. EXPECT_THAT(subset, Not(IsSupersetOf(superset)));
  4281. EXPECT_THAT(superset, IsSupersetOf(subset));
  4282. EXPECT_THAT(subset, Not(IsSupersetOf(disjoint)));
  4283. EXPECT_THAT(disjoint, Not(IsSupersetOf(subset)));
  4284. }
  4285. TEST(IsSupersetOfTest, WorksWithDuplicates) {
  4286. const int not_enough[] = {1, 2};
  4287. const int enough[] = {1, 1, 2};
  4288. const int expected[] = {1, 1};
  4289. EXPECT_THAT(not_enough, Not(IsSupersetOf(expected)));
  4290. EXPECT_THAT(enough, IsSupersetOf(expected));
  4291. }
  4292. TEST(IsSupersetOfTest, WorksForEmpty) {
  4293. vector<int> numbers;
  4294. vector<int> expected;
  4295. EXPECT_THAT(numbers, IsSupersetOf(expected));
  4296. expected.push_back(1);
  4297. EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
  4298. expected.clear();
  4299. numbers.push_back(1);
  4300. numbers.push_back(2);
  4301. EXPECT_THAT(numbers, IsSupersetOf(expected));
  4302. expected.push_back(1);
  4303. EXPECT_THAT(numbers, IsSupersetOf(expected));
  4304. expected.push_back(2);
  4305. EXPECT_THAT(numbers, IsSupersetOf(expected));
  4306. expected.push_back(3);
  4307. EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
  4308. }
  4309. TEST(IsSupersetOfTest, WorksForStreamlike) {
  4310. const int a[5] = {1, 2, 3, 4, 5};
  4311. Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
  4312. vector<int> expected;
  4313. expected.push_back(1);
  4314. expected.push_back(2);
  4315. expected.push_back(5);
  4316. EXPECT_THAT(s, IsSupersetOf(expected));
  4317. expected.push_back(0);
  4318. EXPECT_THAT(s, Not(IsSupersetOf(expected)));
  4319. }
  4320. TEST(IsSupersetOfTest, TakesStlContainer) {
  4321. const int actual[] = {3, 1, 2};
  4322. ::std::list<int> expected;
  4323. expected.push_back(1);
  4324. expected.push_back(3);
  4325. EXPECT_THAT(actual, IsSupersetOf(expected));
  4326. expected.push_back(4);
  4327. EXPECT_THAT(actual, Not(IsSupersetOf(expected)));
  4328. }
  4329. TEST(IsSupersetOfTest, Describe) {
  4330. typedef std::vector<int> IntVec;
  4331. IntVec expected;
  4332. expected.push_back(111);
  4333. expected.push_back(222);
  4334. expected.push_back(333);
  4335. EXPECT_THAT(
  4336. Describe<IntVec>(IsSupersetOf(expected)),
  4337. Eq("a surjection from elements to requirements exists such that:\n"
  4338. " - an element is equal to 111\n"
  4339. " - an element is equal to 222\n"
  4340. " - an element is equal to 333"));
  4341. }
  4342. TEST(IsSupersetOfTest, DescribeNegation) {
  4343. typedef std::vector<int> IntVec;
  4344. IntVec expected;
  4345. expected.push_back(111);
  4346. expected.push_back(222);
  4347. expected.push_back(333);
  4348. EXPECT_THAT(
  4349. DescribeNegation<IntVec>(IsSupersetOf(expected)),
  4350. Eq("no surjection from elements to requirements exists such that:\n"
  4351. " - an element is equal to 111\n"
  4352. " - an element is equal to 222\n"
  4353. " - an element is equal to 333"));
  4354. }
  4355. TEST(IsSupersetOfTest, MatchAndExplain) {
  4356. std::vector<int> v;
  4357. v.push_back(2);
  4358. v.push_back(3);
  4359. std::vector<int> expected;
  4360. expected.push_back(1);
  4361. expected.push_back(2);
  4362. StringMatchResultListener listener;
  4363. ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
  4364. << listener.str();
  4365. EXPECT_THAT(listener.str(),
  4366. Eq("where the following matchers don't match any elements:\n"
  4367. "matcher #0: is equal to 1"));
  4368. v.push_back(1);
  4369. listener.Clear();
  4370. ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
  4371. << listener.str();
  4372. EXPECT_THAT(listener.str(), Eq("where:\n"
  4373. " - element #0 is matched by matcher #1,\n"
  4374. " - element #2 is matched by matcher #0"));
  4375. }
  4376. TEST(IsSupersetOfTest, WorksForRhsInitializerList) {
  4377. const int numbers[] = {1, 3, 6, 2, 4, 5};
  4378. EXPECT_THAT(numbers, IsSupersetOf({1, 2}));
  4379. EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0})));
  4380. }
  4381. TEST(IsSupersetOfTest, WorksWithMoveOnly) {
  4382. ContainerHelper helper;
  4383. EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)})));
  4384. helper.Call(MakeUniquePtrs({1, 2}));
  4385. EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)}))));
  4386. helper.Call(MakeUniquePtrs({2}));
  4387. }
  4388. TEST(IsSubsetOfTest, WorksForNativeArray) {
  4389. const int subset[] = {1, 4};
  4390. const int superset[] = {1, 2, 4};
  4391. const int disjoint[] = {1, 0, 3};
  4392. EXPECT_THAT(subset, IsSubsetOf(subset));
  4393. EXPECT_THAT(subset, IsSubsetOf(superset));
  4394. EXPECT_THAT(superset, Not(IsSubsetOf(subset)));
  4395. EXPECT_THAT(subset, Not(IsSubsetOf(disjoint)));
  4396. EXPECT_THAT(disjoint, Not(IsSubsetOf(subset)));
  4397. }
  4398. TEST(IsSubsetOfTest, WorksWithDuplicates) {
  4399. const int not_enough[] = {1, 2};
  4400. const int enough[] = {1, 1, 2};
  4401. const int actual[] = {1, 1};
  4402. EXPECT_THAT(actual, Not(IsSubsetOf(not_enough)));
  4403. EXPECT_THAT(actual, IsSubsetOf(enough));
  4404. }
  4405. TEST(IsSubsetOfTest, WorksForEmpty) {
  4406. vector<int> numbers;
  4407. vector<int> expected;
  4408. EXPECT_THAT(numbers, IsSubsetOf(expected));
  4409. expected.push_back(1);
  4410. EXPECT_THAT(numbers, IsSubsetOf(expected));
  4411. expected.clear();
  4412. numbers.push_back(1);
  4413. numbers.push_back(2);
  4414. EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
  4415. expected.push_back(1);
  4416. EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
  4417. expected.push_back(2);
  4418. EXPECT_THAT(numbers, IsSubsetOf(expected));
  4419. expected.push_back(3);
  4420. EXPECT_THAT(numbers, IsSubsetOf(expected));
  4421. }
  4422. TEST(IsSubsetOfTest, WorksForStreamlike) {
  4423. const int a[5] = {1, 2};
  4424. Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
  4425. vector<int> expected;
  4426. expected.push_back(1);
  4427. EXPECT_THAT(s, Not(IsSubsetOf(expected)));
  4428. expected.push_back(2);
  4429. expected.push_back(5);
  4430. EXPECT_THAT(s, IsSubsetOf(expected));
  4431. }
  4432. TEST(IsSubsetOfTest, TakesStlContainer) {
  4433. const int actual[] = {3, 1, 2};
  4434. ::std::list<int> expected;
  4435. expected.push_back(1);
  4436. expected.push_back(3);
  4437. EXPECT_THAT(actual, Not(IsSubsetOf(expected)));
  4438. expected.push_back(2);
  4439. expected.push_back(4);
  4440. EXPECT_THAT(actual, IsSubsetOf(expected));
  4441. }
  4442. TEST(IsSubsetOfTest, Describe) {
  4443. typedef std::vector<int> IntVec;
  4444. IntVec expected;
  4445. expected.push_back(111);
  4446. expected.push_back(222);
  4447. expected.push_back(333);
  4448. EXPECT_THAT(
  4449. Describe<IntVec>(IsSubsetOf(expected)),
  4450. Eq("an injection from elements to requirements exists such that:\n"
  4451. " - an element is equal to 111\n"
  4452. " - an element is equal to 222\n"
  4453. " - an element is equal to 333"));
  4454. }
  4455. TEST(IsSubsetOfTest, DescribeNegation) {
  4456. typedef std::vector<int> IntVec;
  4457. IntVec expected;
  4458. expected.push_back(111);
  4459. expected.push_back(222);
  4460. expected.push_back(333);
  4461. EXPECT_THAT(
  4462. DescribeNegation<IntVec>(IsSubsetOf(expected)),
  4463. Eq("no injection from elements to requirements exists such that:\n"
  4464. " - an element is equal to 111\n"
  4465. " - an element is equal to 222\n"
  4466. " - an element is equal to 333"));
  4467. }
  4468. TEST(IsSubsetOfTest, MatchAndExplain) {
  4469. std::vector<int> v;
  4470. v.push_back(2);
  4471. v.push_back(3);
  4472. std::vector<int> expected;
  4473. expected.push_back(1);
  4474. expected.push_back(2);
  4475. StringMatchResultListener listener;
  4476. ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
  4477. << listener.str();
  4478. EXPECT_THAT(listener.str(),
  4479. Eq("where the following elements don't match any matchers:\n"
  4480. "element #1: 3"));
  4481. expected.push_back(3);
  4482. listener.Clear();
  4483. ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
  4484. << listener.str();
  4485. EXPECT_THAT(listener.str(), Eq("where:\n"
  4486. " - element #0 is matched by matcher #1,\n"
  4487. " - element #1 is matched by matcher #2"));
  4488. }
  4489. TEST(IsSubsetOfTest, WorksForRhsInitializerList) {
  4490. const int numbers[] = {1, 2, 3};
  4491. EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4}));
  4492. EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2})));
  4493. }
  4494. TEST(IsSubsetOfTest, WorksWithMoveOnly) {
  4495. ContainerHelper helper;
  4496. EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)})));
  4497. helper.Call(MakeUniquePtrs({1}));
  4498. EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)}))));
  4499. helper.Call(MakeUniquePtrs({2}));
  4500. }
  4501. // Tests using ElementsAre() and ElementsAreArray() with stream-like
  4502. // "containers".
  4503. TEST(ElemensAreStreamTest, WorksForStreamlike) {
  4504. const int a[5] = {1, 2, 3, 4, 5};
  4505. Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
  4506. EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
  4507. EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
  4508. }
  4509. TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
  4510. const int a[5] = {1, 2, 3, 4, 5};
  4511. Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
  4512. vector<int> expected;
  4513. expected.push_back(1);
  4514. expected.push_back(2);
  4515. expected.push_back(3);
  4516. expected.push_back(4);
  4517. expected.push_back(5);
  4518. EXPECT_THAT(s, ElementsAreArray(expected));
  4519. expected[3] = 0;
  4520. EXPECT_THAT(s, Not(ElementsAreArray(expected)));
  4521. }
  4522. TEST(ElementsAreTest, WorksWithUncopyable) {
  4523. Uncopyable objs[2];
  4524. objs[0].set_value(-3);
  4525. objs[1].set_value(1);
  4526. EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
  4527. }
  4528. TEST(ElementsAreTest, WorksWithMoveOnly) {
  4529. ContainerHelper helper;
  4530. EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2))));
  4531. helper.Call(MakeUniquePtrs({1, 2}));
  4532. EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)})));
  4533. helper.Call(MakeUniquePtrs({3, 4}));
  4534. }
  4535. TEST(ElementsAreTest, TakesStlContainer) {
  4536. const int actual[] = {3, 1, 2};
  4537. ::std::list<int> expected;
  4538. expected.push_back(3);
  4539. expected.push_back(1);
  4540. expected.push_back(2);
  4541. EXPECT_THAT(actual, ElementsAreArray(expected));
  4542. expected.push_back(4);
  4543. EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
  4544. }
  4545. // Tests for UnorderedElementsAreArray()
  4546. TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
  4547. const int a[] = {0, 1, 2, 3, 4};
  4548. std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
  4549. do {
  4550. StringMatchResultListener listener;
  4551. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
  4552. s, &listener)) << listener.str();
  4553. } while (std::next_permutation(s.begin(), s.end()));
  4554. }
  4555. TEST(UnorderedElementsAreArrayTest, VectorBool) {
  4556. const bool a[] = {0, 1, 0, 1, 1};
  4557. const bool b[] = {1, 0, 1, 1, 0};
  4558. std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a));
  4559. std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b));
  4560. StringMatchResultListener listener;
  4561. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
  4562. actual, &listener)) << listener.str();
  4563. }
  4564. TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
  4565. // Streamlike 'container' provides only minimal iterator support.
  4566. // Its iterators are tagged with input_iterator_tag, and it has no
  4567. // size() or empty() methods.
  4568. const int a[5] = {2, 1, 4, 5, 3};
  4569. Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
  4570. ::std::vector<int> expected;
  4571. expected.push_back(1);
  4572. expected.push_back(2);
  4573. expected.push_back(3);
  4574. expected.push_back(4);
  4575. expected.push_back(5);
  4576. EXPECT_THAT(s, UnorderedElementsAreArray(expected));
  4577. expected.push_back(6);
  4578. EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
  4579. }
  4580. TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
  4581. const int actual[] = {3, 1, 2};
  4582. ::std::list<int> expected;
  4583. expected.push_back(1);
  4584. expected.push_back(2);
  4585. expected.push_back(3);
  4586. EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
  4587. expected.push_back(4);
  4588. EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
  4589. }
  4590. TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
  4591. const int a[5] = {2, 1, 4, 5, 3};
  4592. EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
  4593. EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
  4594. }
  4595. TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
  4596. const std::string a[5] = {"a", "b", "c", "d", "e"};
  4597. EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
  4598. EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
  4599. }
  4600. TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
  4601. const int a[5] = {2, 1, 4, 5, 3};
  4602. EXPECT_THAT(a, UnorderedElementsAreArray(
  4603. {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
  4604. EXPECT_THAT(a, Not(UnorderedElementsAreArray(
  4605. {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
  4606. }
  4607. TEST(UnorderedElementsAreArrayTest,
  4608. TakesInitializerListOfDifferentTypedMatchers) {
  4609. const int a[5] = {2, 1, 4, 5, 3};
  4610. // The compiler cannot infer the type of the initializer list if its
  4611. // elements have different types. We must explicitly specify the
  4612. // unified element type in this case.
  4613. EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
  4614. {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
  4615. EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
  4616. {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
  4617. }
  4618. TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) {
  4619. ContainerHelper helper;
  4620. EXPECT_CALL(helper,
  4621. Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)})));
  4622. helper.Call(MakeUniquePtrs({2, 1}));
  4623. }
  4624. class UnorderedElementsAreTest : public testing::Test {
  4625. protected:
  4626. typedef std::vector<int> IntVec;
  4627. };
  4628. TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
  4629. Uncopyable objs[2];
  4630. objs[0].set_value(-3);
  4631. objs[1].set_value(1);
  4632. EXPECT_THAT(objs,
  4633. UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
  4634. }
  4635. TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
  4636. const int a[] = {1, 2, 3};
  4637. std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
  4638. do {
  4639. StringMatchResultListener listener;
  4640. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
  4641. s, &listener)) << listener.str();
  4642. } while (std::next_permutation(s.begin(), s.end()));
  4643. }
  4644. TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
  4645. const int a[] = {1, 2, 3};
  4646. std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
  4647. std::vector<Matcher<int> > mv;
  4648. mv.push_back(1);
  4649. mv.push_back(2);
  4650. mv.push_back(2);
  4651. // The element with value '3' matches nothing: fail fast.
  4652. StringMatchResultListener listener;
  4653. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
  4654. s, &listener)) << listener.str();
  4655. }
  4656. TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
  4657. // Streamlike 'container' provides only minimal iterator support.
  4658. // Its iterators are tagged with input_iterator_tag, and it has no
  4659. // size() or empty() methods.
  4660. const int a[5] = {2, 1, 4, 5, 3};
  4661. Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
  4662. EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
  4663. EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
  4664. }
  4665. TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) {
  4666. ContainerHelper helper;
  4667. EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2))));
  4668. helper.Call(MakeUniquePtrs({2, 1}));
  4669. }
  4670. // One naive implementation of the matcher runs in O(N!) time, which is too
  4671. // slow for many real-world inputs. This test shows that our matcher can match
  4672. // 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
  4673. // iterations and obviously effectively incomputable.
  4674. // [ RUN ] UnorderedElementsAreTest.Performance
  4675. // [ OK ] UnorderedElementsAreTest.Performance (4 ms)
  4676. TEST_F(UnorderedElementsAreTest, Performance) {
  4677. std::vector<int> s;
  4678. std::vector<Matcher<int> > mv;
  4679. for (int i = 0; i < 100; ++i) {
  4680. s.push_back(i);
  4681. mv.push_back(_);
  4682. }
  4683. mv[50] = Eq(0);
  4684. StringMatchResultListener listener;
  4685. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
  4686. s, &listener)) << listener.str();
  4687. }
  4688. // Another variant of 'Performance' with similar expectations.
  4689. // [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
  4690. // [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
  4691. TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
  4692. std::vector<int> s;
  4693. std::vector<Matcher<int> > mv;
  4694. for (int i = 0; i < 100; ++i) {
  4695. s.push_back(i);
  4696. if (i & 1) {
  4697. mv.push_back(_);
  4698. } else {
  4699. mv.push_back(i);
  4700. }
  4701. }
  4702. StringMatchResultListener listener;
  4703. EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
  4704. s, &listener)) << listener.str();
  4705. }
  4706. TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
  4707. std::vector<int> v;
  4708. v.push_back(4);
  4709. StringMatchResultListener listener;
  4710. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
  4711. v, &listener)) << listener.str();
  4712. EXPECT_THAT(listener.str(), Eq("which has 1 element"));
  4713. }
  4714. TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
  4715. std::vector<int> v;
  4716. StringMatchResultListener listener;
  4717. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
  4718. v, &listener)) << listener.str();
  4719. EXPECT_THAT(listener.str(), Eq(""));
  4720. }
  4721. TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
  4722. std::vector<int> v;
  4723. v.push_back(1);
  4724. v.push_back(1);
  4725. StringMatchResultListener listener;
  4726. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
  4727. v, &listener)) << listener.str();
  4728. EXPECT_THAT(
  4729. listener.str(),
  4730. Eq("where the following matchers don't match any elements:\n"
  4731. "matcher #1: is equal to 2"));
  4732. }
  4733. TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
  4734. std::vector<int> v;
  4735. v.push_back(1);
  4736. v.push_back(2);
  4737. StringMatchResultListener listener;
  4738. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
  4739. v, &listener)) << listener.str();
  4740. EXPECT_THAT(
  4741. listener.str(),
  4742. Eq("where the following elements don't match any matchers:\n"
  4743. "element #1: 2"));
  4744. }
  4745. TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
  4746. std::vector<int> v;
  4747. v.push_back(2);
  4748. v.push_back(3);
  4749. StringMatchResultListener listener;
  4750. EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
  4751. v, &listener)) << listener.str();
  4752. EXPECT_THAT(
  4753. listener.str(),
  4754. Eq("where"
  4755. " the following matchers don't match any elements:\n"
  4756. "matcher #0: is equal to 1\n"
  4757. "and"
  4758. " where"
  4759. " the following elements don't match any matchers:\n"
  4760. "element #1: 3"));
  4761. }
  4762. // Test helper for formatting element, matcher index pairs in expectations.
  4763. static std::string EMString(int element, int matcher) {
  4764. stringstream ss;
  4765. ss << "(element #" << element << ", matcher #" << matcher << ")";
  4766. return ss.str();
  4767. }
  4768. TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
  4769. // A situation where all elements and matchers have a match
  4770. // associated with them, but the max matching is not perfect.
  4771. std::vector<std::string> v;
  4772. v.push_back("a");
  4773. v.push_back("b");
  4774. v.push_back("c");
  4775. StringMatchResultListener listener;
  4776. EXPECT_FALSE(ExplainMatchResult(
  4777. UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
  4778. << listener.str();
  4779. std::string prefix =
  4780. "where no permutation of the elements can satisfy all matchers, "
  4781. "and the closest match is 2 of 3 matchers with the "
  4782. "pairings:\n";
  4783. // We have to be a bit loose here, because there are 4 valid max matches.
  4784. EXPECT_THAT(
  4785. listener.str(),
  4786. AnyOf(prefix + "{\n " + EMString(0, 0) +
  4787. ",\n " + EMString(1, 2) + "\n}",
  4788. prefix + "{\n " + EMString(0, 1) +
  4789. ",\n " + EMString(1, 2) + "\n}",
  4790. prefix + "{\n " + EMString(0, 0) +
  4791. ",\n " + EMString(2, 2) + "\n}",
  4792. prefix + "{\n " + EMString(0, 1) +
  4793. ",\n " + EMString(2, 2) + "\n}"));
  4794. }
  4795. TEST_F(UnorderedElementsAreTest, Describe) {
  4796. EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
  4797. Eq("is empty"));
  4798. EXPECT_THAT(
  4799. Describe<IntVec>(UnorderedElementsAre(345)),
  4800. Eq("has 1 element and that element is equal to 345"));
  4801. EXPECT_THAT(
  4802. Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
  4803. Eq("has 3 elements and there exists some permutation "
  4804. "of elements such that:\n"
  4805. " - element #0 is equal to 111, and\n"
  4806. " - element #1 is equal to 222, and\n"
  4807. " - element #2 is equal to 333"));
  4808. }
  4809. TEST_F(UnorderedElementsAreTest, DescribeNegation) {
  4810. EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
  4811. Eq("isn't empty"));
  4812. EXPECT_THAT(
  4813. DescribeNegation<IntVec>(UnorderedElementsAre(345)),
  4814. Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
  4815. EXPECT_THAT(
  4816. DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
  4817. Eq("doesn't have 3 elements, or there exists no permutation "
  4818. "of elements such that:\n"
  4819. " - element #0 is equal to 123, and\n"
  4820. " - element #1 is equal to 234, and\n"
  4821. " - element #2 is equal to 345"));
  4822. }
  4823. namespace {
  4824. // Used as a check on the more complex max flow method used in the
  4825. // real testing::internal::FindMaxBipartiteMatching. This method is
  4826. // compatible but runs in worst-case factorial time, so we only
  4827. // use it in testing for small problem sizes.
  4828. template <typename Graph>
  4829. class BacktrackingMaxBPMState {
  4830. public:
  4831. // Does not take ownership of 'g'.
  4832. explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
  4833. ElementMatcherPairs Compute() {
  4834. if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
  4835. return best_so_far_;
  4836. }
  4837. lhs_used_.assign(graph_->LhsSize(), kUnused);
  4838. rhs_used_.assign(graph_->RhsSize(), kUnused);
  4839. for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
  4840. matches_.clear();
  4841. RecurseInto(irhs);
  4842. if (best_so_far_.size() == graph_->RhsSize())
  4843. break;
  4844. }
  4845. return best_so_far_;
  4846. }
  4847. private:
  4848. static const size_t kUnused = static_cast<size_t>(-1);
  4849. void PushMatch(size_t lhs, size_t rhs) {
  4850. matches_.push_back(ElementMatcherPair(lhs, rhs));
  4851. lhs_used_[lhs] = rhs;
  4852. rhs_used_[rhs] = lhs;
  4853. if (matches_.size() > best_so_far_.size()) {
  4854. best_so_far_ = matches_;
  4855. }
  4856. }
  4857. void PopMatch() {
  4858. const ElementMatcherPair& back = matches_.back();
  4859. lhs_used_[back.first] = kUnused;
  4860. rhs_used_[back.second] = kUnused;
  4861. matches_.pop_back();
  4862. }
  4863. bool RecurseInto(size_t irhs) {
  4864. if (rhs_used_[irhs] != kUnused) {
  4865. return true;
  4866. }
  4867. for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
  4868. if (lhs_used_[ilhs] != kUnused) {
  4869. continue;
  4870. }
  4871. if (!graph_->HasEdge(ilhs, irhs)) {
  4872. continue;
  4873. }
  4874. PushMatch(ilhs, irhs);
  4875. if (best_so_far_.size() == graph_->RhsSize()) {
  4876. return false;
  4877. }
  4878. for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
  4879. if (!RecurseInto(mi)) return false;
  4880. }
  4881. PopMatch();
  4882. }
  4883. return true;
  4884. }
  4885. const Graph* graph_; // not owned
  4886. std::vector<size_t> lhs_used_;
  4887. std::vector<size_t> rhs_used_;
  4888. ElementMatcherPairs matches_;
  4889. ElementMatcherPairs best_so_far_;
  4890. };
  4891. template <typename Graph>
  4892. const size_t BacktrackingMaxBPMState<Graph>::kUnused;
  4893. } // namespace
  4894. // Implement a simple backtracking algorithm to determine if it is possible
  4895. // to find one element per matcher, without reusing elements.
  4896. template <typename Graph>
  4897. ElementMatcherPairs
  4898. FindBacktrackingMaxBPM(const Graph& g) {
  4899. return BacktrackingMaxBPMState<Graph>(&g).Compute();
  4900. }
  4901. class BacktrackingBPMTest : public ::testing::Test { };
  4902. // Tests the MaxBipartiteMatching algorithm with square matrices.
  4903. // The single int param is the # of nodes on each of the left and right sides.
  4904. class BipartiteTest : public ::testing::TestWithParam<size_t> {};
  4905. // Verify all match graphs up to some moderate number of edges.
  4906. TEST_P(BipartiteTest, Exhaustive) {
  4907. size_t nodes = GetParam();
  4908. MatchMatrix graph(nodes, nodes);
  4909. do {
  4910. ElementMatcherPairs matches =
  4911. internal::FindMaxBipartiteMatching(graph);
  4912. EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
  4913. << "graph: " << graph.DebugString();
  4914. // Check that all elements of matches are in the graph.
  4915. // Check that elements of first and second are unique.
  4916. std::vector<bool> seen_element(graph.LhsSize());
  4917. std::vector<bool> seen_matcher(graph.RhsSize());
  4918. SCOPED_TRACE(PrintToString(matches));
  4919. for (size_t i = 0; i < matches.size(); ++i) {
  4920. size_t ilhs = matches[i].first;
  4921. size_t irhs = matches[i].second;
  4922. EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
  4923. EXPECT_FALSE(seen_element[ilhs]);
  4924. EXPECT_FALSE(seen_matcher[irhs]);
  4925. seen_element[ilhs] = true;
  4926. seen_matcher[irhs] = true;
  4927. }
  4928. } while (graph.NextGraph());
  4929. }
  4930. INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteTest,
  4931. ::testing::Range(size_t{0}, size_t{5}));
  4932. // Parameterized by a pair interpreted as (LhsSize, RhsSize).
  4933. class BipartiteNonSquareTest
  4934. : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
  4935. };
  4936. TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
  4937. // .......
  4938. // 0:-----\ :
  4939. // 1:---\ | :
  4940. // 2:---\ | :
  4941. // 3:-\ | | :
  4942. // :.......:
  4943. // 0 1 2
  4944. MatchMatrix g(4, 3);
  4945. static const size_t kEdges[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}};
  4946. for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) {
  4947. g.SetEdge(kEdges[i][0], kEdges[i][1], true);
  4948. }
  4949. EXPECT_THAT(FindBacktrackingMaxBPM(g),
  4950. ElementsAre(Pair(3, 0),
  4951. Pair(AnyOf(1, 2), 1),
  4952. Pair(0, 2))) << g.DebugString();
  4953. }
  4954. // Verify a few nonsquare matrices.
  4955. TEST_P(BipartiteNonSquareTest, Exhaustive) {
  4956. size_t nlhs = GetParam().first;
  4957. size_t nrhs = GetParam().second;
  4958. MatchMatrix graph(nlhs, nrhs);
  4959. do {
  4960. EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
  4961. internal::FindMaxBipartiteMatching(graph).size())
  4962. << "graph: " << graph.DebugString()
  4963. << "\nbacktracking: "
  4964. << PrintToString(FindBacktrackingMaxBPM(graph))
  4965. << "\nmax flow: "
  4966. << PrintToString(internal::FindMaxBipartiteMatching(graph));
  4967. } while (graph.NextGraph());
  4968. }
  4969. INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteNonSquareTest,
  4970. testing::Values(
  4971. std::make_pair(1, 2),
  4972. std::make_pair(2, 1),
  4973. std::make_pair(3, 2),
  4974. std::make_pair(2, 3),
  4975. std::make_pair(4, 1),
  4976. std::make_pair(1, 4),
  4977. std::make_pair(4, 3),
  4978. std::make_pair(3, 4)));
  4979. class BipartiteRandomTest
  4980. : public ::testing::TestWithParam<std::pair<int, int> > {
  4981. };
  4982. // Verifies a large sample of larger graphs.
  4983. TEST_P(BipartiteRandomTest, LargerNets) {
  4984. int nodes = GetParam().first;
  4985. int iters = GetParam().second;
  4986. MatchMatrix graph(static_cast<size_t>(nodes), static_cast<size_t>(nodes));
  4987. auto seed = static_cast<testing::internal::UInt32>(GTEST_FLAG(random_seed));
  4988. if (seed == 0) {
  4989. seed = static_cast<testing::internal::UInt32>(time(nullptr));
  4990. }
  4991. for (; iters > 0; --iters, ++seed) {
  4992. srand(static_cast<unsigned int>(seed));
  4993. graph.Randomize();
  4994. EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
  4995. internal::FindMaxBipartiteMatching(graph).size())
  4996. << " graph: " << graph.DebugString()
  4997. << "\nTo reproduce the failure, rerun the test with the flag"
  4998. " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
  4999. }
  5000. }
  5001. // Test argument is a std::pair<int, int> representing (nodes, iters).
  5002. INSTANTIATE_TEST_SUITE_P(Samples, BipartiteRandomTest,
  5003. testing::Values(
  5004. std::make_pair(5, 10000),
  5005. std::make_pair(6, 5000),
  5006. std::make_pair(7, 2000),
  5007. std::make_pair(8, 500),
  5008. std::make_pair(9, 100)));
  5009. // Tests IsReadableTypeName().
  5010. TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
  5011. EXPECT_TRUE(IsReadableTypeName("int"));
  5012. EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
  5013. EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
  5014. EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
  5015. }
  5016. TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
  5017. EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
  5018. EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
  5019. EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
  5020. }
  5021. TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
  5022. EXPECT_FALSE(
  5023. IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
  5024. EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
  5025. }
  5026. TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
  5027. EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
  5028. }
  5029. // Tests FormatMatcherDescription().
  5030. TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
  5031. EXPECT_EQ("is even",
  5032. FormatMatcherDescription(false, "IsEven", Strings()));
  5033. EXPECT_EQ("not (is even)",
  5034. FormatMatcherDescription(true, "IsEven", Strings()));
  5035. const char* params[] = {"5"};
  5036. EXPECT_EQ("equals 5",
  5037. FormatMatcherDescription(false, "Equals",
  5038. Strings(params, params + 1)));
  5039. const char* params2[] = {"5", "8"};
  5040. EXPECT_EQ("is in range (5, 8)",
  5041. FormatMatcherDescription(false, "IsInRange",
  5042. Strings(params2, params2 + 2)));
  5043. }
  5044. // Tests PolymorphicMatcher::mutable_impl().
  5045. TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
  5046. PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
  5047. DivisibleByImpl& impl = m.mutable_impl();
  5048. EXPECT_EQ(42, impl.divider());
  5049. impl.set_divider(0);
  5050. EXPECT_EQ(0, m.mutable_impl().divider());
  5051. }
  5052. // Tests PolymorphicMatcher::impl().
  5053. TEST(PolymorphicMatcherTest, CanAccessImpl) {
  5054. const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
  5055. const DivisibleByImpl& impl = m.impl();
  5056. EXPECT_EQ(42, impl.divider());
  5057. }
  5058. TEST(MatcherTupleTest, ExplainsMatchFailure) {
  5059. stringstream ss1;
  5060. ExplainMatchFailureTupleTo(
  5061. std::make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
  5062. std::make_tuple('a', 10), &ss1);
  5063. EXPECT_EQ("", ss1.str()); // Successful match.
  5064. stringstream ss2;
  5065. ExplainMatchFailureTupleTo(
  5066. std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
  5067. std::make_tuple(2, 'b'), &ss2);
  5068. EXPECT_EQ(" Expected arg #0: is > 5\n"
  5069. " Actual: 2, which is 3 less than 5\n"
  5070. " Expected arg #1: is equal to 'a' (97, 0x61)\n"
  5071. " Actual: 'b' (98, 0x62)\n",
  5072. ss2.str()); // Failed match where both arguments need explanation.
  5073. stringstream ss3;
  5074. ExplainMatchFailureTupleTo(
  5075. std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
  5076. std::make_tuple(2, 'a'), &ss3);
  5077. EXPECT_EQ(" Expected arg #0: is > 5\n"
  5078. " Actual: 2, which is 3 less than 5\n",
  5079. ss3.str()); // Failed match where only one argument needs
  5080. // explanation.
  5081. }
  5082. // Tests Each().
  5083. TEST(EachTest, ExplainsMatchResultCorrectly) {
  5084. set<int> a; // empty
  5085. Matcher<set<int> > m = Each(2);
  5086. EXPECT_EQ("", Explain(m, a));
  5087. Matcher<const int(&)[1]> n = Each(1); // NOLINT
  5088. const int b[1] = {1};
  5089. EXPECT_EQ("", Explain(n, b));
  5090. n = Each(3);
  5091. EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
  5092. a.insert(1);
  5093. a.insert(2);
  5094. a.insert(3);
  5095. m = Each(GreaterThan(0));
  5096. EXPECT_EQ("", Explain(m, a));
  5097. m = Each(GreaterThan(10));
  5098. EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
  5099. Explain(m, a));
  5100. }
  5101. TEST(EachTest, DescribesItselfCorrectly) {
  5102. Matcher<vector<int> > m = Each(1);
  5103. EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
  5104. Matcher<vector<int> > m2 = Not(m);
  5105. EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
  5106. }
  5107. TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
  5108. vector<int> some_vector;
  5109. EXPECT_THAT(some_vector, Each(1));
  5110. some_vector.push_back(3);
  5111. EXPECT_THAT(some_vector, Not(Each(1)));
  5112. EXPECT_THAT(some_vector, Each(3));
  5113. some_vector.push_back(1);
  5114. some_vector.push_back(2);
  5115. EXPECT_THAT(some_vector, Not(Each(3)));
  5116. EXPECT_THAT(some_vector, Each(Lt(3.5)));
  5117. vector<std::string> another_vector;
  5118. another_vector.push_back("fee");
  5119. EXPECT_THAT(another_vector, Each(std::string("fee")));
  5120. another_vector.push_back("fie");
  5121. another_vector.push_back("foe");
  5122. another_vector.push_back("fum");
  5123. EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));
  5124. }
  5125. TEST(EachTest, MatchesMapWhenAllElementsMatch) {
  5126. map<const char*, int> my_map;
  5127. const char* bar = "a string";
  5128. my_map[bar] = 2;
  5129. EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
  5130. map<std::string, int> another_map;
  5131. EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
  5132. another_map["fee"] = 1;
  5133. EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
  5134. another_map["fie"] = 2;
  5135. another_map["foe"] = 3;
  5136. another_map["fum"] = 4;
  5137. EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));
  5138. EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));
  5139. EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
  5140. }
  5141. TEST(EachTest, AcceptsMatcher) {
  5142. const int a[] = {1, 2, 3};
  5143. EXPECT_THAT(a, Each(Gt(0)));
  5144. EXPECT_THAT(a, Not(Each(Gt(1))));
  5145. }
  5146. TEST(EachTest, WorksForNativeArrayAsTuple) {
  5147. const int a[] = {1, 2};
  5148. const int* const pointer = a;
  5149. EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0)));
  5150. EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1))));
  5151. }
  5152. TEST(EachTest, WorksWithMoveOnly) {
  5153. ContainerHelper helper;
  5154. EXPECT_CALL(helper, Call(Each(Pointee(Gt(0)))));
  5155. helper.Call(MakeUniquePtrs({1, 2}));
  5156. }
  5157. // For testing Pointwise().
  5158. class IsHalfOfMatcher {
  5159. public:
  5160. template <typename T1, typename T2>
  5161. bool MatchAndExplain(const std::tuple<T1, T2>& a_pair,
  5162. MatchResultListener* listener) const {
  5163. if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) {
  5164. *listener << "where the second is " << std::get<1>(a_pair);
  5165. return true;
  5166. } else {
  5167. *listener << "where the second/2 is " << std::get<1>(a_pair) / 2;
  5168. return false;
  5169. }
  5170. }
  5171. void DescribeTo(ostream* os) const {
  5172. *os << "are a pair where the first is half of the second";
  5173. }
  5174. void DescribeNegationTo(ostream* os) const {
  5175. *os << "are a pair where the first isn't half of the second";
  5176. }
  5177. };
  5178. PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
  5179. return MakePolymorphicMatcher(IsHalfOfMatcher());
  5180. }
  5181. TEST(PointwiseTest, DescribesSelf) {
  5182. vector<int> rhs;
  5183. rhs.push_back(1);
  5184. rhs.push_back(2);
  5185. rhs.push_back(3);
  5186. const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
  5187. EXPECT_EQ("contains 3 values, where each value and its corresponding value "
  5188. "in { 1, 2, 3 } are a pair where the first is half of the second",
  5189. Describe(m));
  5190. EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
  5191. "index i where x and the i-th value of { 1, 2, 3 } are a pair "
  5192. "where the first isn't half of the second",
  5193. DescribeNegation(m));
  5194. }
  5195. TEST(PointwiseTest, MakesCopyOfRhs) {
  5196. list<signed char> rhs;
  5197. rhs.push_back(2);
  5198. rhs.push_back(4);
  5199. int lhs[] = {1, 2};
  5200. const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
  5201. EXPECT_THAT(lhs, m);
  5202. // Changing rhs now shouldn't affect m, which made a copy of rhs.
  5203. rhs.push_back(6);
  5204. EXPECT_THAT(lhs, m);
  5205. }
  5206. TEST(PointwiseTest, WorksForLhsNativeArray) {
  5207. const int lhs[] = {1, 2, 3};
  5208. vector<int> rhs;
  5209. rhs.push_back(2);
  5210. rhs.push_back(4);
  5211. rhs.push_back(6);
  5212. EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
  5213. EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
  5214. }
  5215. TEST(PointwiseTest, WorksForRhsNativeArray) {
  5216. const int rhs[] = {1, 2, 3};
  5217. vector<int> lhs;
  5218. lhs.push_back(2);
  5219. lhs.push_back(4);
  5220. lhs.push_back(6);
  5221. EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
  5222. EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
  5223. }
  5224. // Test is effective only with sanitizers.
  5225. TEST(PointwiseTest, WorksForVectorOfBool) {
  5226. vector<bool> rhs(3, false);
  5227. rhs[1] = true;
  5228. vector<bool> lhs = rhs;
  5229. EXPECT_THAT(lhs, Pointwise(Eq(), rhs));
  5230. rhs[0] = true;
  5231. EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs)));
  5232. }
  5233. TEST(PointwiseTest, WorksForRhsInitializerList) {
  5234. const vector<int> lhs{2, 4, 6};
  5235. EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
  5236. EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
  5237. }
  5238. TEST(PointwiseTest, RejectsWrongSize) {
  5239. const double lhs[2] = {1, 2};
  5240. const int rhs[1] = {0};
  5241. EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
  5242. EXPECT_EQ("which contains 2 values",
  5243. Explain(Pointwise(Gt(), rhs), lhs));
  5244. const int rhs2[3] = {0, 1, 2};
  5245. EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
  5246. }
  5247. TEST(PointwiseTest, RejectsWrongContent) {
  5248. const double lhs[3] = {1, 2, 3};
  5249. const int rhs[3] = {2, 6, 4};
  5250. EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
  5251. EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
  5252. "where the second/2 is 3",
  5253. Explain(Pointwise(IsHalfOf(), rhs), lhs));
  5254. }
  5255. TEST(PointwiseTest, AcceptsCorrectContent) {
  5256. const double lhs[3] = {1, 2, 3};
  5257. const int rhs[3] = {2, 4, 6};
  5258. EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
  5259. EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
  5260. }
  5261. TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
  5262. const double lhs[3] = {1, 2, 3};
  5263. const int rhs[3] = {2, 4, 6};
  5264. const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
  5265. EXPECT_THAT(lhs, Pointwise(m1, rhs));
  5266. EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
  5267. // This type works as a std::tuple<const double&, const int&> can be
  5268. // implicitly cast to std::tuple<double, int>.
  5269. const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
  5270. EXPECT_THAT(lhs, Pointwise(m2, rhs));
  5271. EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
  5272. }
  5273. MATCHER(PointeeEquals, "Points to an equal value") {
  5274. return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)),
  5275. ::testing::get<0>(arg), result_listener);
  5276. }
  5277. TEST(PointwiseTest, WorksWithMoveOnly) {
  5278. ContainerHelper helper;
  5279. EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2})));
  5280. helper.Call(MakeUniquePtrs({1, 2}));
  5281. }
  5282. TEST(UnorderedPointwiseTest, DescribesSelf) {
  5283. vector<int> rhs;
  5284. rhs.push_back(1);
  5285. rhs.push_back(2);
  5286. rhs.push_back(3);
  5287. const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
  5288. EXPECT_EQ(
  5289. "has 3 elements and there exists some permutation of elements such "
  5290. "that:\n"
  5291. " - element #0 and 1 are a pair where the first is half of the second, "
  5292. "and\n"
  5293. " - element #1 and 2 are a pair where the first is half of the second, "
  5294. "and\n"
  5295. " - element #2 and 3 are a pair where the first is half of the second",
  5296. Describe(m));
  5297. EXPECT_EQ(
  5298. "doesn't have 3 elements, or there exists no permutation of elements "
  5299. "such that:\n"
  5300. " - element #0 and 1 are a pair where the first is half of the second, "
  5301. "and\n"
  5302. " - element #1 and 2 are a pair where the first is half of the second, "
  5303. "and\n"
  5304. " - element #2 and 3 are a pair where the first is half of the second",
  5305. DescribeNegation(m));
  5306. }
  5307. TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
  5308. list<signed char> rhs;
  5309. rhs.push_back(2);
  5310. rhs.push_back(4);
  5311. int lhs[] = {2, 1};
  5312. const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
  5313. EXPECT_THAT(lhs, m);
  5314. // Changing rhs now shouldn't affect m, which made a copy of rhs.
  5315. rhs.push_back(6);
  5316. EXPECT_THAT(lhs, m);
  5317. }
  5318. TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
  5319. const int lhs[] = {1, 2, 3};
  5320. vector<int> rhs;
  5321. rhs.push_back(4);
  5322. rhs.push_back(6);
  5323. rhs.push_back(2);
  5324. EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
  5325. EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
  5326. }
  5327. TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
  5328. const int rhs[] = {1, 2, 3};
  5329. vector<int> lhs;
  5330. lhs.push_back(4);
  5331. lhs.push_back(2);
  5332. lhs.push_back(6);
  5333. EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
  5334. EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
  5335. }
  5336. TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
  5337. const vector<int> lhs{2, 4, 6};
  5338. EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
  5339. EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
  5340. }
  5341. TEST(UnorderedPointwiseTest, RejectsWrongSize) {
  5342. const double lhs[2] = {1, 2};
  5343. const int rhs[1] = {0};
  5344. EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
  5345. EXPECT_EQ("which has 2 elements",
  5346. Explain(UnorderedPointwise(Gt(), rhs), lhs));
  5347. const int rhs2[3] = {0, 1, 2};
  5348. EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
  5349. }
  5350. TEST(UnorderedPointwiseTest, RejectsWrongContent) {
  5351. const double lhs[3] = {1, 2, 3};
  5352. const int rhs[3] = {2, 6, 6};
  5353. EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
  5354. EXPECT_EQ("where the following elements don't match any matchers:\n"
  5355. "element #1: 2",
  5356. Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
  5357. }
  5358. TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
  5359. const double lhs[3] = {1, 2, 3};
  5360. const int rhs[3] = {2, 4, 6};
  5361. EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
  5362. }
  5363. TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
  5364. const double lhs[3] = {1, 2, 3};
  5365. const int rhs[3] = {6, 4, 2};
  5366. EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
  5367. }
  5368. TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
  5369. const double lhs[3] = {1, 2, 3};
  5370. const int rhs[3] = {4, 6, 2};
  5371. const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
  5372. EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
  5373. // This type works as a std::tuple<const double&, const int&> can be
  5374. // implicitly cast to std::tuple<double, int>.
  5375. const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
  5376. EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
  5377. }
  5378. TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {
  5379. ContainerHelper helper;
  5380. EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(),
  5381. std::vector<int>{1, 2})));
  5382. helper.Call(MakeUniquePtrs({2, 1}));
  5383. }
  5384. // Sample optional type implementation with minimal requirements for use with
  5385. // Optional matcher.
  5386. template <typename T>
  5387. class SampleOptional {
  5388. public:
  5389. using value_type = T;
  5390. explicit SampleOptional(T value)
  5391. : value_(std::move(value)), has_value_(true) {}
  5392. SampleOptional() : value_(), has_value_(false) {}
  5393. operator bool() const { return has_value_; }
  5394. const T& operator*() const { return value_; }
  5395. private:
  5396. T value_;
  5397. bool has_value_;
  5398. };
  5399. TEST(OptionalTest, DescribesSelf) {
  5400. const Matcher<SampleOptional<int>> m = Optional(Eq(1));
  5401. EXPECT_EQ("value is equal to 1", Describe(m));
  5402. }
  5403. TEST(OptionalTest, ExplainsSelf) {
  5404. const Matcher<SampleOptional<int>> m = Optional(Eq(1));
  5405. EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptional<int>(1)));
  5406. EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptional<int>(2)));
  5407. }
  5408. TEST(OptionalTest, MatchesNonEmptyOptional) {
  5409. const Matcher<SampleOptional<int>> m1 = Optional(1);
  5410. const Matcher<SampleOptional<int>> m2 = Optional(Eq(2));
  5411. const Matcher<SampleOptional<int>> m3 = Optional(Lt(3));
  5412. SampleOptional<int> opt(1);
  5413. EXPECT_TRUE(m1.Matches(opt));
  5414. EXPECT_FALSE(m2.Matches(opt));
  5415. EXPECT_TRUE(m3.Matches(opt));
  5416. }
  5417. TEST(OptionalTest, DoesNotMatchNullopt) {
  5418. const Matcher<SampleOptional<int>> m = Optional(1);
  5419. SampleOptional<int> empty;
  5420. EXPECT_FALSE(m.Matches(empty));
  5421. }
  5422. TEST(OptionalTest, WorksWithMoveOnly) {
  5423. Matcher<SampleOptional<std::unique_ptr<int>>> m = Optional(Eq(nullptr));
  5424. EXPECT_TRUE(m.Matches(SampleOptional<std::unique_ptr<int>>(nullptr)));
  5425. }
  5426. class SampleVariantIntString {
  5427. public:
  5428. SampleVariantIntString(int i) : i_(i), has_int_(true) {}
  5429. SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {}
  5430. template <typename T>
  5431. friend bool holds_alternative(const SampleVariantIntString& value) {
  5432. return value.has_int_ == std::is_same<T, int>::value;
  5433. }
  5434. template <typename T>
  5435. friend const T& get(const SampleVariantIntString& value) {
  5436. return value.get_impl(static_cast<T*>(nullptr));
  5437. }
  5438. private:
  5439. const int& get_impl(int*) const { return i_; }
  5440. const std::string& get_impl(std::string*) const { return s_; }
  5441. int i_;
  5442. std::string s_;
  5443. bool has_int_;
  5444. };
  5445. TEST(VariantTest, DescribesSelf) {
  5446. const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
  5447. EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type "
  5448. "'.*' and the value is equal to 1"));
  5449. }
  5450. TEST(VariantTest, ExplainsSelf) {
  5451. const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
  5452. EXPECT_THAT(Explain(m, SampleVariantIntString(1)),
  5453. ContainsRegex("whose value 1"));
  5454. EXPECT_THAT(Explain(m, SampleVariantIntString("A")),
  5455. HasSubstr("whose value is not of type '"));
  5456. EXPECT_THAT(Explain(m, SampleVariantIntString(2)),
  5457. "whose value 2 doesn't match");
  5458. }
  5459. TEST(VariantTest, FullMatch) {
  5460. Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
  5461. EXPECT_TRUE(m.Matches(SampleVariantIntString(1)));
  5462. m = VariantWith<std::string>(Eq("1"));
  5463. EXPECT_TRUE(m.Matches(SampleVariantIntString("1")));
  5464. }
  5465. TEST(VariantTest, TypeDoesNotMatch) {
  5466. Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
  5467. EXPECT_FALSE(m.Matches(SampleVariantIntString("1")));
  5468. m = VariantWith<std::string>(Eq("1"));
  5469. EXPECT_FALSE(m.Matches(SampleVariantIntString(1)));
  5470. }
  5471. TEST(VariantTest, InnerDoesNotMatch) {
  5472. Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
  5473. EXPECT_FALSE(m.Matches(SampleVariantIntString(2)));
  5474. m = VariantWith<std::string>(Eq("1"));
  5475. EXPECT_FALSE(m.Matches(SampleVariantIntString("2")));
  5476. }
  5477. class SampleAnyType {
  5478. public:
  5479. explicit SampleAnyType(int i) : index_(0), i_(i) {}
  5480. explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {}
  5481. template <typename T>
  5482. friend const T* any_cast(const SampleAnyType* any) {
  5483. return any->get_impl(static_cast<T*>(nullptr));
  5484. }
  5485. private:
  5486. int index_;
  5487. int i_;
  5488. std::string s_;
  5489. const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; }
  5490. const std::string* get_impl(std::string*) const {
  5491. return index_ == 1 ? &s_ : nullptr;
  5492. }
  5493. };
  5494. TEST(AnyWithTest, FullMatch) {
  5495. Matcher<SampleAnyType> m = AnyWith<int>(Eq(1));
  5496. EXPECT_TRUE(m.Matches(SampleAnyType(1)));
  5497. }
  5498. TEST(AnyWithTest, TestBadCastType) {
  5499. Matcher<SampleAnyType> m = AnyWith<std::string>(Eq("fail"));
  5500. EXPECT_FALSE(m.Matches(SampleAnyType(1)));
  5501. }
  5502. TEST(AnyWithTest, TestUseInContainers) {
  5503. std::vector<SampleAnyType> a;
  5504. a.emplace_back(1);
  5505. a.emplace_back(2);
  5506. a.emplace_back(3);
  5507. EXPECT_THAT(
  5508. a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)}));
  5509. std::vector<SampleAnyType> b;
  5510. b.emplace_back("hello");
  5511. b.emplace_back("merhaba");
  5512. b.emplace_back("salut");
  5513. EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>("hello"),
  5514. AnyWith<std::string>("merhaba"),
  5515. AnyWith<std::string>("salut")}));
  5516. }
  5517. TEST(AnyWithTest, TestCompare) {
  5518. EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0)));
  5519. }
  5520. TEST(AnyWithTest, DescribesSelf) {
  5521. const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
  5522. EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type "
  5523. "'.*' and the value is equal to 1"));
  5524. }
  5525. TEST(AnyWithTest, ExplainsSelf) {
  5526. const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
  5527. EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1"));
  5528. EXPECT_THAT(Explain(m, SampleAnyType("A")),
  5529. HasSubstr("whose value is not of type '"));
  5530. EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match");
  5531. }
  5532. TEST(PointeeTest, WorksOnMoveOnlyType) {
  5533. std::unique_ptr<int> p(new int(3));
  5534. EXPECT_THAT(p, Pointee(Eq(3)));
  5535. EXPECT_THAT(p, Not(Pointee(Eq(2))));
  5536. }
  5537. TEST(NotTest, WorksOnMoveOnlyType) {
  5538. std::unique_ptr<int> p(new int(3));
  5539. EXPECT_THAT(p, Pointee(Eq(3)));
  5540. EXPECT_THAT(p, Not(Pointee(Eq(2))));
  5541. }
  5542. // Tests Args<k0, ..., kn>(m).
  5543. TEST(ArgsTest, AcceptsZeroTemplateArg) {
  5544. const std::tuple<int, bool> t(5, true);
  5545. EXPECT_THAT(t, Args<>(Eq(std::tuple<>())));
  5546. EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>()))));
  5547. }
  5548. TEST(ArgsTest, AcceptsOneTemplateArg) {
  5549. const std::tuple<int, bool> t(5, true);
  5550. EXPECT_THAT(t, Args<0>(Eq(std::make_tuple(5))));
  5551. EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(true))));
  5552. EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(false)))));
  5553. }
  5554. TEST(ArgsTest, AcceptsTwoTemplateArgs) {
  5555. const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
  5556. EXPECT_THAT(t, (Args<0, 1>(Lt())));
  5557. EXPECT_THAT(t, (Args<1, 2>(Lt())));
  5558. EXPECT_THAT(t, Not(Args<0, 2>(Gt())));
  5559. }
  5560. TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
  5561. const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
  5562. EXPECT_THAT(t, (Args<0, 0>(Eq())));
  5563. EXPECT_THAT(t, Not(Args<1, 1>(Ne())));
  5564. }
  5565. TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {
  5566. const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
  5567. EXPECT_THAT(t, (Args<2, 0>(Gt())));
  5568. EXPECT_THAT(t, Not(Args<2, 1>(Lt())));
  5569. }
  5570. MATCHER(SumIsZero, "") {
  5571. return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0;
  5572. }
  5573. TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {
  5574. EXPECT_THAT(std::make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero())));
  5575. EXPECT_THAT(std::make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero())));
  5576. }
  5577. TEST(ArgsTest, CanBeNested) {
  5578. const std::tuple<short, int, long, int> t(4, 5, 6L, 6); // NOLINT
  5579. EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));
  5580. EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));
  5581. }
  5582. TEST(ArgsTest, CanMatchTupleByValue) {
  5583. typedef std::tuple<char, int, int> Tuple3;
  5584. const Matcher<Tuple3> m = Args<1, 2>(Lt());
  5585. EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2)));
  5586. EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2)));
  5587. }
  5588. TEST(ArgsTest, CanMatchTupleByReference) {
  5589. typedef std::tuple<char, char, int> Tuple3;
  5590. const Matcher<const Tuple3&> m = Args<0, 1>(Lt());
  5591. EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2)));
  5592. EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2)));
  5593. }
  5594. // Validates that arg is printed as str.
  5595. MATCHER_P(PrintsAs, str, "") {
  5596. return testing::PrintToString(arg) == str;
  5597. }
  5598. TEST(ArgsTest, AcceptsTenTemplateArgs) {
  5599. EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
  5600. (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
  5601. PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
  5602. EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
  5603. Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
  5604. PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
  5605. }
  5606. TEST(ArgsTest, DescirbesSelfCorrectly) {
  5607. const Matcher<std::tuple<int, bool, char> > m = Args<2, 0>(Lt());
  5608. EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where "
  5609. "the first < the second",
  5610. Describe(m));
  5611. }
  5612. TEST(ArgsTest, DescirbesNestedArgsCorrectly) {
  5613. const Matcher<const std::tuple<int, bool, char, int>&> m =
  5614. Args<0, 2, 3>(Args<2, 0>(Lt()));
  5615. EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple "
  5616. "whose fields (#2, #0) are a pair where the first < the second",
  5617. Describe(m));
  5618. }
  5619. TEST(ArgsTest, DescribesNegationCorrectly) {
  5620. const Matcher<std::tuple<int, char> > m = Args<1, 0>(Gt());
  5621. EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair "
  5622. "where the first > the second",
  5623. DescribeNegation(m));
  5624. }
  5625. TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) {
  5626. const Matcher<std::tuple<bool, int, int> > m = Args<1, 2>(Eq());
  5627. EXPECT_EQ("whose fields (#1, #2) are (42, 42)",
  5628. Explain(m, std::make_tuple(false, 42, 42)));
  5629. EXPECT_EQ("whose fields (#1, #2) are (42, 43)",
  5630. Explain(m, std::make_tuple(false, 42, 43)));
  5631. }
  5632. // For testing Args<>'s explanation.
  5633. class LessThanMatcher : public MatcherInterface<std::tuple<char, int> > {
  5634. public:
  5635. void DescribeTo(::std::ostream* /*os*/) const override {}
  5636. bool MatchAndExplain(std::tuple<char, int> value,
  5637. MatchResultListener* listener) const override {
  5638. const int diff = std::get<0>(value) - std::get<1>(value);
  5639. if (diff > 0) {
  5640. *listener << "where the first value is " << diff
  5641. << " more than the second";
  5642. }
  5643. return diff < 0;
  5644. }
  5645. };
  5646. Matcher<std::tuple<char, int> > LessThan() {
  5647. return MakeMatcher(new LessThanMatcher);
  5648. }
  5649. TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) {
  5650. const Matcher<std::tuple<char, int, int> > m = Args<0, 2>(LessThan());
  5651. EXPECT_EQ(
  5652. "whose fields (#0, #2) are ('a' (97, 0x61), 42), "
  5653. "where the first value is 55 more than the second",
  5654. Explain(m, std::make_tuple('a', 42, 42)));
  5655. EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)",
  5656. Explain(m, std::make_tuple('\0', 42, 43)));
  5657. }
  5658. class PredicateFormatterFromMatcherTest : public ::testing::Test {
  5659. protected:
  5660. enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky };
  5661. // A matcher that can return different results when used multiple times on the
  5662. // same input. No real matcher should do this; but this lets us test that we
  5663. // detect such behavior and fail appropriately.
  5664. class MockMatcher : public MatcherInterface<Behavior> {
  5665. public:
  5666. bool MatchAndExplain(Behavior behavior,
  5667. MatchResultListener* listener) const override {
  5668. *listener << "[MatchAndExplain]";
  5669. switch (behavior) {
  5670. case kInitialSuccess:
  5671. // The first call to MatchAndExplain should use a "not interested"
  5672. // listener; so this is expected to return |true|. There should be no
  5673. // subsequent calls.
  5674. return !listener->IsInterested();
  5675. case kAlwaysFail:
  5676. return false;
  5677. case kFlaky:
  5678. // The first call to MatchAndExplain should use a "not interested"
  5679. // listener; so this will return |false|. Subsequent calls should have
  5680. // an "interested" listener; so this will return |true|, thus
  5681. // simulating a flaky matcher.
  5682. return listener->IsInterested();
  5683. }
  5684. GTEST_LOG_(FATAL) << "This should never be reached";
  5685. return false;
  5686. }
  5687. void DescribeTo(ostream* os) const override { *os << "[DescribeTo]"; }
  5688. void DescribeNegationTo(ostream* os) const override {
  5689. *os << "[DescribeNegationTo]";
  5690. }
  5691. };
  5692. AssertionResult RunPredicateFormatter(Behavior behavior) {
  5693. auto matcher = MakeMatcher(new MockMatcher);
  5694. PredicateFormatterFromMatcher<Matcher<Behavior>> predicate_formatter(
  5695. matcher);
  5696. return predicate_formatter("dummy-name", behavior);
  5697. }
  5698. };
  5699. TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) {
  5700. AssertionResult result = RunPredicateFormatter(kInitialSuccess);
  5701. EXPECT_TRUE(result); // Implicit cast to bool.
  5702. std::string expect;
  5703. EXPECT_EQ(expect, result.message());
  5704. }
  5705. TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
  5706. AssertionResult result = RunPredicateFormatter(kAlwaysFail);
  5707. EXPECT_FALSE(result); // Implicit cast to bool.
  5708. std::string expect =
  5709. "Value of: dummy-name\nExpected: [DescribeTo]\n"
  5710. " Actual: 1, [MatchAndExplain]";
  5711. EXPECT_EQ(expect, result.message());
  5712. }
  5713. TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
  5714. AssertionResult result = RunPredicateFormatter(kFlaky);
  5715. EXPECT_FALSE(result); // Implicit cast to bool.
  5716. std::string expect =
  5717. "Value of: dummy-name\nExpected: [DescribeTo]\n"
  5718. " The matcher failed on the initial attempt; but passed when rerun to "
  5719. "generate the explanation.\n"
  5720. " Actual: 2, [MatchAndExplain]";
  5721. EXPECT_EQ(expect, result.message());
  5722. }
  5723. } // namespace
  5724. } // namespace gmock_matchers_test
  5725. } // namespace testing
  5726. #ifdef _MSC_VER
  5727. # pragma warning(pop)
  5728. #endif