?login_element?

Subversion Repositories NedoOS

Rev

Blame | Last modification | View Log | Download

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