blob: 74e9294fd907e354b524bbf9bc6c8c5d152e436c [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// 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.
Gennadiy Civila3c0dd02018-08-14 14:04:07 -040029
shiqiane35fdd92008-12-10 05:08:54 +000030
31// Google Mock - a framework for writing C++ mock classes.
32//
33// This file tests some commonly used argument matchers.
34
Abseil Teama42cdf22018-12-03 10:48:03 -050035// Silence warning C4244: 'initializing': conversion from 'int' to 'short',
36// possible loss of data and C4100, unreferenced local parameter
37#ifdef _MSC_VER
38# pragma warning(push)
39# pragma warning(disable:4244)
40# pragma warning(disable:4100)
41#endif
42
zhanyong.wan53e08c42010-09-14 05:38:21 +000043#include "gmock/gmock-matchers.h"
zhanyong.wan320814a2013-03-01 00:20:30 +000044#include "gmock/gmock-more-matchers.h"
shiqiane35fdd92008-12-10 05:08:54 +000045
46#include <string.h>
zhanyong.wanfb25d532013-07-28 08:24:00 +000047#include <time.h>
zhanyong.wana9a59e02013-03-27 16:14:55 +000048#include <deque>
Abseil Teame26a3fa2018-12-17 18:59:00 -050049#include <forward_list>
shiqiane35fdd92008-12-10 05:08:54 +000050#include <functional>
zhanyong.wana862f1d2010-03-15 21:23:04 +000051#include <iostream>
zhanyong.wana9a59e02013-03-27 16:14:55 +000052#include <iterator>
zhanyong.wan616180e2013-06-18 18:49:51 +000053#include <limits>
zhanyong.wan6a896b52009-01-16 01:13:50 +000054#include <list>
55#include <map>
Gennadiy Civile55089e2018-04-04 14:05:00 -040056#include <memory>
zhanyong.wan6a896b52009-01-16 01:13:50 +000057#include <set>
shiqiane35fdd92008-12-10 05:08:54 +000058#include <sstream>
zhanyong.wan6a896b52009-01-16 01:13:50 +000059#include <string>
Abseil Teame26a3fa2018-12-17 18:59:00 -050060#include <type_traits>
zhanyong.wanf5e1ce52009-09-16 07:02:02 +000061#include <utility>
zhanyong.wan6a896b52009-01-16 01:13:50 +000062#include <vector>
zhanyong.wan53e08c42010-09-14 05:38:21 +000063#include "gmock/gmock.h"
64#include "gtest/gtest.h"
65#include "gtest/gtest-spi.h"
shiqiane35fdd92008-12-10 05:08:54 +000066
67namespace testing {
68namespace gmock_matchers_test {
Abseil Team1ec20f82018-12-15 08:11:02 -050069namespace {
shiqiane35fdd92008-12-10 05:08:54 +000070
zhanyong.wan898725c2011-09-16 16:45:39 +000071using std::greater;
72using std::less;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000073using std::list;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000074using std::make_pair;
zhanyong.wanb5937da2009-07-16 20:26:41 +000075using std::map;
76using std::multimap;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000077using std::multiset;
78using std::ostream;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000079using std::pair;
zhanyong.wan33605ba2010-04-22 23:37:47 +000080using std::set;
shiqiane35fdd92008-12-10 05:08:54 +000081using std::stringstream;
zhanyong.wan33605ba2010-04-22 23:37:47 +000082using std::vector;
zhanyong.wana862f1d2010-03-15 21:23:04 +000083using testing::internal::DummyMatchResultListener;
zhanyong.wanfb25d532013-07-28 08:24:00 +000084using testing::internal::ElementMatcherPair;
85using testing::internal::ElementMatcherPairs;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000086using testing::internal::ExplainMatchFailureTupleTo;
shiqiane35fdd92008-12-10 05:08:54 +000087using testing::internal::FloatingEqMatcher;
zhanyong.wanb4140802010-06-08 22:53:57 +000088using testing::internal::FormatMatcherDescription;
zhanyong.wan736baa82010-09-27 17:44:16 +000089using testing::internal::IsReadableTypeName;
zhanyong.wanfb25d532013-07-28 08:24:00 +000090using testing::internal::MatchMatrix;
Abseil Team6ef59132018-12-11 14:10:54 -050091using testing::internal::PredicateFormatterFromMatcher;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000092using testing::internal::RE;
zhanyong.wana862f1d2010-03-15 21:23:04 +000093using testing::internal::StreamMatchResultListener;
Abseil Team6ef59132018-12-11 14:10:54 -050094using testing::internal::Strings;
shiqiane35fdd92008-12-10 05:08:54 +000095
Abseil Team1ec20f82018-12-15 08:11:02 -050096// Helper for testing container-valued matchers in mock method context. It is
97// important to test matchers in this context, since it requires additional type
98// deduction beyond what EXPECT_THAT does, thus making it more restrictive.
99struct ContainerHelper {
100 MOCK_METHOD1(Call, void(std::vector<std::unique_ptr<int>>));
101};
102
103std::vector<std::unique_ptr<int>> MakeUniquePtrs(const std::vector<int>& ints) {
104 std::vector<std::unique_ptr<int>> pointers;
105 for (int i : ints) pointers.emplace_back(new int(i));
106 return pointers;
107}
108
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000109// For testing ExplainMatchResultTo().
110class GreaterThanMatcher : public MatcherInterface<int> {
111 public:
112 explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
113
Abseil Team26743362018-12-03 11:30:02 -0500114 void DescribeTo(ostream* os) const override { *os << "is > " << rhs_; }
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000115
Abseil Team26743362018-12-03 11:30:02 -0500116 bool MatchAndExplain(int lhs, MatchResultListener* listener) const override {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000117 const int diff = lhs - rhs_;
118 if (diff > 0) {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000119 *listener << "which is " << diff << " more than " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000120 } else if (diff == 0) {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000121 *listener << "which is the same as " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000122 } else {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000123 *listener << "which is " << -diff << " less than " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000124 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000125
126 return lhs > rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000127 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000128
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000129 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000130 int rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000131};
132
133Matcher<int> GreaterThan(int n) {
134 return MakeMatcher(new GreaterThanMatcher(n));
135}
136
Nico Weber09fd5b32017-05-15 17:07:03 -0400137std::string OfType(const std::string& type_name) {
zhanyong.wan736baa82010-09-27 17:44:16 +0000138#if GTEST_HAS_RTTI
139 return " (of type " + type_name + ")";
140#else
141 return "";
142#endif
143}
144
shiqiane35fdd92008-12-10 05:08:54 +0000145// Returns the description of the given matcher.
146template <typename T>
Nico Weber09fd5b32017-05-15 17:07:03 -0400147std::string Describe(const Matcher<T>& m) {
Gennadiy Civile55089e2018-04-04 14:05:00 -0400148 return DescribeMatcher<T>(m);
shiqiane35fdd92008-12-10 05:08:54 +0000149}
150
151// Returns the description of the negation of the given matcher.
152template <typename T>
Nico Weber09fd5b32017-05-15 17:07:03 -0400153std::string DescribeNegation(const Matcher<T>& m) {
Gennadiy Civile55089e2018-04-04 14:05:00 -0400154 return DescribeMatcher<T>(m, true);
shiqiane35fdd92008-12-10 05:08:54 +0000155}
156
157// Returns the reason why x matches, or doesn't match, m.
158template <typename MatcherType, typename Value>
Nico Weber09fd5b32017-05-15 17:07:03 -0400159std::string Explain(const MatcherType& m, const Value& x) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000160 StringMatchResultListener listener;
161 ExplainMatchResult(m, x, &listener);
162 return listener.str();
shiqiane35fdd92008-12-10 05:08:54 +0000163}
164
Gennadiy Civile55089e2018-04-04 14:05:00 -0400165TEST(MonotonicMatcherTest, IsPrintable) {
166 stringstream ss;
167 ss << GreaterThan(5);
168 EXPECT_EQ("is > 5", ss.str());
169}
170
zhanyong.wana862f1d2010-03-15 21:23:04 +0000171TEST(MatchResultListenerTest, StreamingWorks) {
172 StringMatchResultListener listener;
173 listener << "hi" << 5;
174 EXPECT_EQ("hi5", listener.str());
175
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000176 listener.Clear();
177 EXPECT_EQ("", listener.str());
178
179 listener << 42;
180 EXPECT_EQ("42", listener.str());
181
zhanyong.wana862f1d2010-03-15 21:23:04 +0000182 // Streaming shouldn't crash when the underlying ostream is NULL.
183 DummyMatchResultListener dummy;
184 dummy << "hi" << 5;
185}
186
187TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
Abseil Team4bb49ed2018-10-04 18:28:05 -0400188 EXPECT_TRUE(DummyMatchResultListener().stream() == nullptr);
189 EXPECT_TRUE(StreamMatchResultListener(nullptr).stream() == nullptr);
zhanyong.wana862f1d2010-03-15 21:23:04 +0000190
191 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
192}
193
194TEST(MatchResultListenerTest, IsInterestedWorks) {
195 EXPECT_TRUE(StringMatchResultListener().IsInterested());
196 EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
197
198 EXPECT_FALSE(DummyMatchResultListener().IsInterested());
Abseil Team4bb49ed2018-10-04 18:28:05 -0400199 EXPECT_FALSE(StreamMatchResultListener(nullptr).IsInterested());
zhanyong.wana862f1d2010-03-15 21:23:04 +0000200}
201
shiqiane35fdd92008-12-10 05:08:54 +0000202// Makes sure that the MatcherInterface<T> interface doesn't
203// change.
204class EvenMatcherImpl : public MatcherInterface<int> {
205 public:
Abseil Team26743362018-12-03 11:30:02 -0500206 bool MatchAndExplain(int x,
207 MatchResultListener* /* listener */) const override {
zhanyong.wandb22c222010-01-28 21:52:29 +0000208 return x % 2 == 0;
209 }
shiqiane35fdd92008-12-10 05:08:54 +0000210
Abseil Team26743362018-12-03 11:30:02 -0500211 void DescribeTo(ostream* os) const override { *os << "is an even number"; }
shiqiane35fdd92008-12-10 05:08:54 +0000212
213 // We deliberately don't define DescribeNegationTo() and
214 // ExplainMatchResultTo() here, to make sure the definition of these
215 // two methods is optional.
216};
217
zhanyong.wana862f1d2010-03-15 21:23:04 +0000218// Makes sure that the MatcherInterface API doesn't change.
219TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
shiqiane35fdd92008-12-10 05:08:54 +0000220 EvenMatcherImpl m;
221}
222
zhanyong.wan82113312010-01-08 21:55:40 +0000223// Tests implementing a monomorphic matcher using MatchAndExplain().
224
225class NewEvenMatcherImpl : public MatcherInterface<int> {
226 public:
Abseil Team26743362018-12-03 11:30:02 -0500227 bool MatchAndExplain(int x, MatchResultListener* listener) const override {
zhanyong.wan82113312010-01-08 21:55:40 +0000228 const bool match = x % 2 == 0;
229 // Verifies that we can stream to a listener directly.
230 *listener << "value % " << 2;
Abseil Team4bb49ed2018-10-04 18:28:05 -0400231 if (listener->stream() != nullptr) {
zhanyong.wan82113312010-01-08 21:55:40 +0000232 // Verifies that we can stream to a listener's underlying stream
233 // too.
234 *listener->stream() << " == " << (x % 2);
235 }
236 return match;
237 }
238
Abseil Team26743362018-12-03 11:30:02 -0500239 void DescribeTo(ostream* os) const override { *os << "is an even number"; }
zhanyong.wan82113312010-01-08 21:55:40 +0000240};
241
242TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
243 Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
244 EXPECT_TRUE(m.Matches(2));
245 EXPECT_FALSE(m.Matches(3));
246 EXPECT_EQ("value % 2 == 0", Explain(m, 2));
247 EXPECT_EQ("value % 2 == 1", Explain(m, 3));
248}
249
shiqiane35fdd92008-12-10 05:08:54 +0000250// Tests default-constructing a matcher.
251TEST(MatcherTest, CanBeDefaultConstructed) {
252 Matcher<double> m;
253}
254
255// Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
256TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
257 const MatcherInterface<int>* impl = new EvenMatcherImpl;
258 Matcher<int> m(impl);
259 EXPECT_TRUE(m.Matches(4));
260 EXPECT_FALSE(m.Matches(5));
261}
262
263// Tests that value can be used in place of Eq(value).
264TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
265 Matcher<int> m1 = 5;
266 EXPECT_TRUE(m1.Matches(5));
267 EXPECT_FALSE(m1.Matches(6));
268}
269
270// Tests that NULL can be used in place of Eq(NULL).
271TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
Vadim Barkov3feffdd2018-10-28 03:27:51 +0300272 Matcher<int*> m1 = nullptr;
Abseil Team4bb49ed2018-10-04 18:28:05 -0400273 EXPECT_TRUE(m1.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +0000274 int n = 0;
275 EXPECT_FALSE(m1.Matches(&n));
276}
277
Gennadiy Civile55089e2018-04-04 14:05:00 -0400278// Tests that matchers can be constructed from a variable that is not properly
279// defined. This should be illegal, but many users rely on this accidentally.
280struct Undefined {
281 virtual ~Undefined() = 0;
282 static const int kInt = 1;
283};
284
285TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) {
286 Matcher<int> m1 = Undefined::kInt;
287 EXPECT_TRUE(m1.Matches(1));
288 EXPECT_FALSE(m1.Matches(2));
289}
290
291// Test that a matcher parameterized with an abstract class compiles.
292TEST(MatcherTest, CanAcceptAbstractClass) { Matcher<const Undefined&> m = _; }
293
shiqiane35fdd92008-12-10 05:08:54 +0000294// Tests that matchers are copyable.
295TEST(MatcherTest, IsCopyable) {
296 // Tests the copy constructor.
297 Matcher<bool> m1 = Eq(false);
298 EXPECT_TRUE(m1.Matches(false));
299 EXPECT_FALSE(m1.Matches(true));
300
301 // Tests the assignment operator.
302 m1 = Eq(true);
303 EXPECT_TRUE(m1.Matches(true));
304 EXPECT_FALSE(m1.Matches(false));
305}
306
307// Tests that Matcher<T>::DescribeTo() calls
308// MatcherInterface<T>::DescribeTo().
309TEST(MatcherTest, CanDescribeItself) {
310 EXPECT_EQ("is an even number",
311 Describe(Matcher<int>(new EvenMatcherImpl)));
312}
313
zhanyong.wan82113312010-01-08 21:55:40 +0000314// Tests Matcher<T>::MatchAndExplain().
315TEST(MatcherTest, MatchAndExplain) {
316 Matcher<int> m = GreaterThan(0);
zhanyong.wan34b034c2010-03-05 21:23:23 +0000317 StringMatchResultListener listener1;
zhanyong.wan82113312010-01-08 21:55:40 +0000318 EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000319 EXPECT_EQ("which is 42 more than 0", listener1.str());
zhanyong.wan82113312010-01-08 21:55:40 +0000320
zhanyong.wan34b034c2010-03-05 21:23:23 +0000321 StringMatchResultListener listener2;
zhanyong.wan82113312010-01-08 21:55:40 +0000322 EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000323 EXPECT_EQ("which is 9 less than 0", listener2.str());
zhanyong.wan82113312010-01-08 21:55:40 +0000324}
325
shiqiane35fdd92008-12-10 05:08:54 +0000326// Tests that a C-string literal can be implicitly converted to a
Gennadiy Civile55089e2018-04-04 14:05:00 -0400327// Matcher<std::string> or Matcher<const std::string&>.
shiqiane35fdd92008-12-10 05:08:54 +0000328TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
Gennadiy Civile55089e2018-04-04 14:05:00 -0400329 Matcher<std::string> m1 = "hi";
shiqiane35fdd92008-12-10 05:08:54 +0000330 EXPECT_TRUE(m1.Matches("hi"));
331 EXPECT_FALSE(m1.Matches("hello"));
332
Gennadiy Civile55089e2018-04-04 14:05:00 -0400333 Matcher<const std::string&> m2 = "hi";
shiqiane35fdd92008-12-10 05:08:54 +0000334 EXPECT_TRUE(m2.Matches("hi"));
335 EXPECT_FALSE(m2.Matches("hello"));
336}
337
338// Tests that a string object can be implicitly converted to a
Gennadiy Civile55089e2018-04-04 14:05:00 -0400339// Matcher<std::string> or Matcher<const std::string&>.
shiqiane35fdd92008-12-10 05:08:54 +0000340TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
Gennadiy Civile55089e2018-04-04 14:05:00 -0400341 Matcher<std::string> m1 = std::string("hi");
shiqiane35fdd92008-12-10 05:08:54 +0000342 EXPECT_TRUE(m1.Matches("hi"));
343 EXPECT_FALSE(m1.Matches("hello"));
344
Gennadiy Civile55089e2018-04-04 14:05:00 -0400345 Matcher<const std::string&> m2 = std::string("hi");
shiqiane35fdd92008-12-10 05:08:54 +0000346 EXPECT_TRUE(m2.Matches("hi"));
347 EXPECT_FALSE(m2.Matches("hello"));
348}
349
Gennadiy Civile55089e2018-04-04 14:05:00 -0400350#if GTEST_HAS_ABSL
351// Tests that a C-string literal can be implicitly converted to a
352// Matcher<absl::string_view> or Matcher<const absl::string_view&>.
353TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
354 Matcher<absl::string_view> m1 = "cats";
zhanyong.wan1f122a02013-03-25 16:27:03 +0000355 EXPECT_TRUE(m1.Matches("cats"));
356 EXPECT_FALSE(m1.Matches("dogs"));
357
Gennadiy Civile55089e2018-04-04 14:05:00 -0400358 Matcher<const absl::string_view&> m2 = "cats";
zhanyong.wan1f122a02013-03-25 16:27:03 +0000359 EXPECT_TRUE(m2.Matches("cats"));
360 EXPECT_FALSE(m2.Matches("dogs"));
361}
362
Gennadiy Civile55089e2018-04-04 14:05:00 -0400363// Tests that a std::string object can be implicitly converted to a
364// Matcher<absl::string_view> or Matcher<const absl::string_view&>.
365TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {
366 Matcher<absl::string_view> m1 = std::string("cats");
zhanyong.wan1f122a02013-03-25 16:27:03 +0000367 EXPECT_TRUE(m1.Matches("cats"));
368 EXPECT_FALSE(m1.Matches("dogs"));
369
Gennadiy Civile55089e2018-04-04 14:05:00 -0400370 Matcher<const absl::string_view&> m2 = std::string("cats");
zhanyong.wan1f122a02013-03-25 16:27:03 +0000371 EXPECT_TRUE(m2.Matches("cats"));
372 EXPECT_FALSE(m2.Matches("dogs"));
373}
374
Gennadiy Civile55089e2018-04-04 14:05:00 -0400375// Tests that a absl::string_view object can be implicitly converted to a
376// Matcher<absl::string_view> or Matcher<const absl::string_view&>.
377TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {
378 Matcher<absl::string_view> m1 = absl::string_view("cats");
379 EXPECT_TRUE(m1.Matches("cats"));
380 EXPECT_FALSE(m1.Matches("dogs"));
381
382 Matcher<const absl::string_view&> m2 = absl::string_view("cats");
383 EXPECT_TRUE(m2.Matches("cats"));
384 EXPECT_FALSE(m2.Matches("dogs"));
385}
386#endif // GTEST_HAS_ABSL
zhanyong.wan1f122a02013-03-25 16:27:03 +0000387
Abseil Team28a96d12019-02-05 12:18:47 -0500388// Tests that a std::reference_wrapper<std::string> object can be implicitly
389// converted to a Matcher<std::string> or Matcher<const std::string&> via Eq().
390TEST(StringMatcherTest,
391 CanBeImplicitlyConstructedFromEqReferenceWrapperString) {
392 std::string value = "cats";
393 Matcher<std::string> m1 = Eq(std::ref(value));
394 EXPECT_TRUE(m1.Matches("cats"));
395 EXPECT_FALSE(m1.Matches("dogs"));
396
397 Matcher<const std::string&> m2 = Eq(std::ref(value));
398 EXPECT_TRUE(m2.Matches("cats"));
399 EXPECT_FALSE(m2.Matches("dogs"));
400}
401
shiqiane35fdd92008-12-10 05:08:54 +0000402// Tests that MakeMatcher() constructs a Matcher<T> from a
403// MatcherInterface* without requiring the user to explicitly
404// write the type.
405TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
Abseil Team4bb49ed2018-10-04 18:28:05 -0400406 const MatcherInterface<int>* dummy_impl = nullptr;
shiqiane35fdd92008-12-10 05:08:54 +0000407 Matcher<int> m = MakeMatcher(dummy_impl);
408}
409
zhanyong.wan82113312010-01-08 21:55:40 +0000410// Tests that MakePolymorphicMatcher() can construct a polymorphic
411// matcher from its implementation using the old API.
zhanyong.wan33605ba2010-04-22 23:37:47 +0000412const int g_bar = 1;
shiqiane35fdd92008-12-10 05:08:54 +0000413class ReferencesBarOrIsZeroImpl {
414 public:
415 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +0000416 bool MatchAndExplain(const T& x,
417 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000418 const void* p = &x;
zhanyong.wan33605ba2010-04-22 23:37:47 +0000419 return p == &g_bar || x == 0;
shiqiane35fdd92008-12-10 05:08:54 +0000420 }
421
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000422 void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
shiqiane35fdd92008-12-10 05:08:54 +0000423
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000424 void DescribeNegationTo(ostream* os) const {
zhanyong.wan33605ba2010-04-22 23:37:47 +0000425 *os << "doesn't reference g_bar and is not zero";
shiqiane35fdd92008-12-10 05:08:54 +0000426 }
427};
428
429// This function verifies that MakePolymorphicMatcher() returns a
430// PolymorphicMatcher<T> where T is the argument's type.
431PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
432 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
433}
434
zhanyong.wan82113312010-01-08 21:55:40 +0000435TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
shiqiane35fdd92008-12-10 05:08:54 +0000436 // Using a polymorphic matcher to match a reference type.
437 Matcher<const int&> m1 = ReferencesBarOrIsZero();
438 EXPECT_TRUE(m1.Matches(0));
439 // Verifies that the identity of a by-reference argument is preserved.
zhanyong.wan33605ba2010-04-22 23:37:47 +0000440 EXPECT_TRUE(m1.Matches(g_bar));
shiqiane35fdd92008-12-10 05:08:54 +0000441 EXPECT_FALSE(m1.Matches(1));
zhanyong.wan33605ba2010-04-22 23:37:47 +0000442 EXPECT_EQ("g_bar or zero", Describe(m1));
shiqiane35fdd92008-12-10 05:08:54 +0000443
444 // Using a polymorphic matcher to match a value type.
445 Matcher<double> m2 = ReferencesBarOrIsZero();
446 EXPECT_TRUE(m2.Matches(0.0));
447 EXPECT_FALSE(m2.Matches(0.1));
zhanyong.wan33605ba2010-04-22 23:37:47 +0000448 EXPECT_EQ("g_bar or zero", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +0000449}
450
zhanyong.wan82113312010-01-08 21:55:40 +0000451// Tests implementing a polymorphic matcher using MatchAndExplain().
452
453class PolymorphicIsEvenImpl {
454 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000455 void DescribeTo(ostream* os) const { *os << "is even"; }
zhanyong.wan82113312010-01-08 21:55:40 +0000456
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000457 void DescribeNegationTo(ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000458 *os << "is odd";
459 }
zhanyong.wan82113312010-01-08 21:55:40 +0000460
zhanyong.wandb22c222010-01-28 21:52:29 +0000461 template <typename T>
462 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
463 // Verifies that we can stream to the listener directly.
464 *listener << "% " << 2;
Abseil Team4bb49ed2018-10-04 18:28:05 -0400465 if (listener->stream() != nullptr) {
zhanyong.wandb22c222010-01-28 21:52:29 +0000466 // Verifies that we can stream to the listener's underlying stream
467 // too.
468 *listener->stream() << " == " << (x % 2);
469 }
470 return (x % 2) == 0;
zhanyong.wan82113312010-01-08 21:55:40 +0000471 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000472};
zhanyong.wan82113312010-01-08 21:55:40 +0000473
474PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
475 return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
476}
477
478TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
479 // Using PolymorphicIsEven() as a Matcher<int>.
480 const Matcher<int> m1 = PolymorphicIsEven();
481 EXPECT_TRUE(m1.Matches(42));
482 EXPECT_FALSE(m1.Matches(43));
483 EXPECT_EQ("is even", Describe(m1));
484
485 const Matcher<int> not_m1 = Not(m1);
486 EXPECT_EQ("is odd", Describe(not_m1));
487
488 EXPECT_EQ("% 2 == 0", Explain(m1, 42));
489
490 // Using PolymorphicIsEven() as a Matcher<char>.
491 const Matcher<char> m2 = PolymorphicIsEven();
492 EXPECT_TRUE(m2.Matches('\x42'));
493 EXPECT_FALSE(m2.Matches('\x43'));
494 EXPECT_EQ("is even", Describe(m2));
495
496 const Matcher<char> not_m2 = Not(m2);
497 EXPECT_EQ("is odd", Describe(not_m2));
498
499 EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
500}
501
shiqiane35fdd92008-12-10 05:08:54 +0000502// Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
503TEST(MatcherCastTest, FromPolymorphicMatcher) {
504 Matcher<int> m = MatcherCast<int>(Eq(5));
505 EXPECT_TRUE(m.Matches(5));
506 EXPECT_FALSE(m.Matches(6));
507}
508
509// For testing casting matchers between compatible types.
510class IntValue {
511 public:
512 // An int can be statically (although not implicitly) cast to a
513 // IntValue.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000514 explicit IntValue(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +0000515
516 int value() const { return value_; }
517 private:
518 int value_;
519};
520
521// For testing casting matchers between compatible types.
522bool IsPositiveIntValue(const IntValue& foo) {
523 return foo.value() > 0;
524}
525
526// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
527// can be statically converted to U.
528TEST(MatcherCastTest, FromCompatibleType) {
529 Matcher<double> m1 = Eq(2.0);
530 Matcher<int> m2 = MatcherCast<int>(m1);
531 EXPECT_TRUE(m2.Matches(2));
532 EXPECT_FALSE(m2.Matches(3));
533
534 Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
535 Matcher<int> m4 = MatcherCast<int>(m3);
536 // In the following, the arguments 1 and 0 are statically converted
537 // to IntValue objects, and then tested by the IsPositiveIntValue()
538 // predicate.
539 EXPECT_TRUE(m4.Matches(1));
540 EXPECT_FALSE(m4.Matches(0));
541}
542
543// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
544TEST(MatcherCastTest, FromConstReferenceToNonReference) {
545 Matcher<const int&> m1 = Eq(0);
546 Matcher<int> m2 = MatcherCast<int>(m1);
547 EXPECT_TRUE(m2.Matches(0));
548 EXPECT_FALSE(m2.Matches(1));
549}
550
551// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
552TEST(MatcherCastTest, FromReferenceToNonReference) {
553 Matcher<int&> m1 = Eq(0);
554 Matcher<int> m2 = MatcherCast<int>(m1);
555 EXPECT_TRUE(m2.Matches(0));
556 EXPECT_FALSE(m2.Matches(1));
557}
558
559// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
560TEST(MatcherCastTest, FromNonReferenceToConstReference) {
561 Matcher<int> m1 = Eq(0);
562 Matcher<const int&> m2 = MatcherCast<const int&>(m1);
563 EXPECT_TRUE(m2.Matches(0));
564 EXPECT_FALSE(m2.Matches(1));
565}
566
567// Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
568TEST(MatcherCastTest, FromNonReferenceToReference) {
569 Matcher<int> m1 = Eq(0);
570 Matcher<int&> m2 = MatcherCast<int&>(m1);
571 int n = 0;
572 EXPECT_TRUE(m2.Matches(n));
573 n = 1;
574 EXPECT_FALSE(m2.Matches(n));
575}
576
577// Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
578TEST(MatcherCastTest, FromSameType) {
579 Matcher<int> m1 = Eq(0);
580 Matcher<int> m2 = MatcherCast<int>(m1);
581 EXPECT_TRUE(m2.Matches(0));
582 EXPECT_FALSE(m2.Matches(1));
583}
584
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -0400585// Tests that MatcherCast<T>(m) works when m is a value of the same type as the
586// value type of the Matcher.
587TEST(MatcherCastTest, FromAValue) {
588 Matcher<int> m = MatcherCast<int>(42);
589 EXPECT_TRUE(m.Matches(42));
590 EXPECT_FALSE(m.Matches(239));
591}
592
593// Tests that MatcherCast<T>(m) works when m is a value of the type implicitly
594// convertible to the value type of the Matcher.
595TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) {
596 const int kExpected = 'c';
597 Matcher<int> m = MatcherCast<int>('c');
598 EXPECT_TRUE(m.Matches(kExpected));
599 EXPECT_FALSE(m.Matches(kExpected + 1));
600}
601
602struct NonImplicitlyConstructibleTypeWithOperatorEq {
603 friend bool operator==(
604 const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */,
605 int rhs) {
606 return 42 == rhs;
607 }
608 friend bool operator==(
609 int lhs,
610 const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) {
611 return lhs == 42;
612 }
613};
614
615// Tests that MatcherCast<T>(m) works when m is a neither a matcher nor
616// implicitly convertible to the value type of the Matcher, but the value type
617// of the matcher has operator==() overload accepting m.
618TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) {
619 Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m1 =
620 MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(42);
621 EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
622
623 Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m2 =
624 MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(239);
625 EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
626
627 // When updating the following lines please also change the comment to
628 // namespace convertible_from_any.
629 Matcher<int> m3 =
630 MatcherCast<int>(NonImplicitlyConstructibleTypeWithOperatorEq());
631 EXPECT_TRUE(m3.Matches(42));
632 EXPECT_FALSE(m3.Matches(239));
633}
634
Gennadiy Civilb5391672018-04-25 13:10:41 -0400635// ConvertibleFromAny does not work with MSVC. resulting in
636// error C2440: 'initializing': cannot convert from 'Eq' to 'M'
637// No constructor could take the source type, or constructor overload
638// resolution was ambiguous
639
640#if !defined _MSC_VER
641
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -0400642// The below ConvertibleFromAny struct is implicitly constructible from anything
643// and when in the same namespace can interact with other tests. In particular,
644// if it is in the same namespace as other tests and one removes
645// NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...);
646// then the corresponding test still compiles (and it should not!) by implicitly
647// converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny
648// in m3.Matcher().
649namespace convertible_from_any {
kosak506340a2014-11-17 01:47:54 +0000650// Implicitly convertible from any type.
jgm79a367e2012-04-10 16:02:11 +0000651struct ConvertibleFromAny {
Gennadiy Civil70451382018-04-05 11:59:59 -0400652 ConvertibleFromAny(int a_value) : value(a_value) {}
jgm79a367e2012-04-10 16:02:11 +0000653 template <typename T>
Gennadiy Civilb5391672018-04-25 13:10:41 -0400654 ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
jgm79a367e2012-04-10 16:02:11 +0000655 ADD_FAILURE() << "Conversion constructor called";
656 }
657 int value;
658};
659
660bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
661 return a.value == b.value;
662}
663
664ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
665 return os << a.value;
666}
667
668TEST(MatcherCastTest, ConversionConstructorIsUsed) {
669 Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
670 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
671 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
672}
673
674TEST(MatcherCastTest, FromConvertibleFromAny) {
675 Matcher<ConvertibleFromAny> m =
676 MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
677 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
678 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
679}
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -0400680} // namespace convertible_from_any
jgm79a367e2012-04-10 16:02:11 +0000681
Gennadiy Civilb5391672018-04-25 13:10:41 -0400682#endif // !defined _MSC_VER
683
kosak5f2a6ca2013-12-03 01:43:07 +0000684struct IntReferenceWrapper {
685 IntReferenceWrapper(const int& a_value) : value(&a_value) {}
686 const int* value;
687};
688
689bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
690 return a.value == b.value;
691}
692
693TEST(MatcherCastTest, ValueIsNotCopied) {
694 int n = 42;
695 Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
696 // Verify that the matcher holds a reference to n, not to its temporary copy.
697 EXPECT_TRUE(m.Matches(n));
698}
699
billydonahue1f5fdea2014-05-19 17:54:51 +0000700class Base {
701 public:
702 virtual ~Base() {}
703 Base() {}
704 private:
705 GTEST_DISALLOW_COPY_AND_ASSIGN_(Base);
706};
707
708class Derived : public Base {
709 public:
710 Derived() : Base() {}
711 int i;
712};
713
714class OtherDerived : public Base {};
zhanyong.wan18490652009-05-11 18:54:08 +0000715
716// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
717TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
718 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
719 EXPECT_TRUE(m2.Matches(' '));
720 EXPECT_FALSE(m2.Matches('\n'));
721}
722
zhanyong.wan16cf4732009-05-14 20:55:30 +0000723// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
724// T and U are arithmetic types and T can be losslessly converted to
725// U.
726TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
zhanyong.wan18490652009-05-11 18:54:08 +0000727 Matcher<double> m1 = DoubleEq(1.0);
zhanyong.wan16cf4732009-05-14 20:55:30 +0000728 Matcher<float> m2 = SafeMatcherCast<float>(m1);
729 EXPECT_TRUE(m2.Matches(1.0f));
730 EXPECT_FALSE(m2.Matches(2.0f));
731
732 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
733 EXPECT_TRUE(m3.Matches('a'));
734 EXPECT_FALSE(m3.Matches('b'));
zhanyong.wan18490652009-05-11 18:54:08 +0000735}
736
737// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
738// are pointers or references to a derived and a base class, correspondingly.
739TEST(SafeMatcherCastTest, FromBaseClass) {
740 Derived d, d2;
741 Matcher<Base*> m1 = Eq(&d);
742 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
743 EXPECT_TRUE(m2.Matches(&d));
744 EXPECT_FALSE(m2.Matches(&d2));
745
746 Matcher<Base&> m3 = Ref(d);
747 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
748 EXPECT_TRUE(m4.Matches(d));
749 EXPECT_FALSE(m4.Matches(d2));
750}
751
752// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
753TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
754 int n = 0;
755 Matcher<const int&> m1 = Ref(n);
756 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
757 int n1 = 0;
758 EXPECT_TRUE(m2.Matches(n));
759 EXPECT_FALSE(m2.Matches(n1));
760}
761
762// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
763TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
764 Matcher<int> m1 = Eq(0);
765 Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
766 EXPECT_TRUE(m2.Matches(0));
767 EXPECT_FALSE(m2.Matches(1));
768}
769
770// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
771TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
772 Matcher<int> m1 = Eq(0);
773 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
774 int n = 0;
775 EXPECT_TRUE(m2.Matches(n));
776 n = 1;
777 EXPECT_FALSE(m2.Matches(n));
778}
779
780// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
781TEST(SafeMatcherCastTest, FromSameType) {
782 Matcher<int> m1 = Eq(0);
783 Matcher<int> m2 = SafeMatcherCast<int>(m1);
784 EXPECT_TRUE(m2.Matches(0));
785 EXPECT_FALSE(m2.Matches(1));
786}
787
Gennadiy Civilb5391672018-04-25 13:10:41 -0400788#if !defined _MSC_VER
789
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -0400790namespace convertible_from_any {
jgm79a367e2012-04-10 16:02:11 +0000791TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
792 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
793 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
794 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
795}
796
797TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
798 Matcher<ConvertibleFromAny> m =
799 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
800 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
801 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
802}
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -0400803} // namespace convertible_from_any
jgm79a367e2012-04-10 16:02:11 +0000804
Gennadiy Civilb5391672018-04-25 13:10:41 -0400805#endif // !defined _MSC_VER
806
kosak5f2a6ca2013-12-03 01:43:07 +0000807TEST(SafeMatcherCastTest, ValueIsNotCopied) {
808 int n = 42;
809 Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
810 // Verify that the matcher holds a reference to n, not to its temporary copy.
811 EXPECT_TRUE(m.Matches(n));
812}
813
kosak9b1a9442015-04-28 23:06:58 +0000814TEST(ExpectThat, TakesLiterals) {
815 EXPECT_THAT(1, 1);
816 EXPECT_THAT(1.0, 1.0);
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -0400817 EXPECT_THAT(std::string(), "");
kosak9b1a9442015-04-28 23:06:58 +0000818}
819
820TEST(ExpectThat, TakesFunctions) {
821 struct Helper {
822 static void Func() {}
823 };
824 void (*func)() = Helper::Func;
825 EXPECT_THAT(func, Helper::Func);
826 EXPECT_THAT(func, &Helper::Func);
827}
828
shiqiane35fdd92008-12-10 05:08:54 +0000829// Tests that A<T>() matches any value of type T.
830TEST(ATest, MatchesAnyValue) {
831 // Tests a matcher for a value type.
832 Matcher<double> m1 = A<double>();
833 EXPECT_TRUE(m1.Matches(91.43));
834 EXPECT_TRUE(m1.Matches(-15.32));
835
836 // Tests a matcher for a reference type.
837 int a = 2;
838 int b = -6;
839 Matcher<int&> m2 = A<int&>();
840 EXPECT_TRUE(m2.Matches(a));
841 EXPECT_TRUE(m2.Matches(b));
842}
843
zhanyong.wanf4274522013-04-24 02:49:43 +0000844TEST(ATest, WorksForDerivedClass) {
845 Base base;
846 Derived derived;
847 EXPECT_THAT(&base, A<Base*>());
848 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
849 EXPECT_THAT(&derived, A<Base*>());
850 EXPECT_THAT(&derived, A<Derived*>());
851}
852
shiqiane35fdd92008-12-10 05:08:54 +0000853// Tests that A<T>() describes itself properly.
854TEST(ATest, CanDescribeSelf) {
855 EXPECT_EQ("is anything", Describe(A<bool>()));
856}
857
858// Tests that An<T>() matches any value of type T.
859TEST(AnTest, MatchesAnyValue) {
860 // Tests a matcher for a value type.
861 Matcher<int> m1 = An<int>();
862 EXPECT_TRUE(m1.Matches(9143));
863 EXPECT_TRUE(m1.Matches(-1532));
864
865 // Tests a matcher for a reference type.
866 int a = 2;
867 int b = -6;
868 Matcher<int&> m2 = An<int&>();
869 EXPECT_TRUE(m2.Matches(a));
870 EXPECT_TRUE(m2.Matches(b));
871}
872
873// Tests that An<T>() describes itself properly.
874TEST(AnTest, CanDescribeSelf) {
875 EXPECT_EQ("is anything", Describe(An<int>()));
876}
877
878// Tests that _ can be used as a matcher for any type and matches any
879// value of that type.
880TEST(UnderscoreTest, MatchesAnyValue) {
881 // Uses _ as a matcher for a value type.
882 Matcher<int> m1 = _;
883 EXPECT_TRUE(m1.Matches(123));
884 EXPECT_TRUE(m1.Matches(-242));
885
886 // Uses _ as a matcher for a reference type.
887 bool a = false;
888 const bool b = true;
889 Matcher<const bool&> m2 = _;
890 EXPECT_TRUE(m2.Matches(a));
891 EXPECT_TRUE(m2.Matches(b));
892}
893
894// Tests that _ describes itself properly.
895TEST(UnderscoreTest, CanDescribeSelf) {
896 Matcher<int> m = _;
897 EXPECT_EQ("is anything", Describe(m));
898}
899
900// Tests that Eq(x) matches any value equal to x.
901TEST(EqTest, MatchesEqualValue) {
902 // 2 C-strings with same content but different addresses.
903 const char a1[] = "hi";
904 const char a2[] = "hi";
905
906 Matcher<const char*> m1 = Eq(a1);
907 EXPECT_TRUE(m1.Matches(a1));
908 EXPECT_FALSE(m1.Matches(a2));
909}
910
911// Tests that Eq(v) describes itself properly.
912
913class Unprintable {
914 public:
915 Unprintable() : c_('a') {}
916
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -0400917 bool operator==(const Unprintable& /* rhs */) const { return true; }
Enji Coopered2fe122019-02-12 16:35:38 -0800918 // -Wunused-private-field: dummy accessor for `c_`.
919 char dummy_c() { return c_; }
shiqiane35fdd92008-12-10 05:08:54 +0000920 private:
921 char c_;
922};
923
924TEST(EqTest, CanDescribeSelf) {
925 Matcher<Unprintable> m = Eq(Unprintable());
926 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
927}
928
929// Tests that Eq(v) can be used to match any type that supports
930// comparing with type T, where T is v's type.
931TEST(EqTest, IsPolymorphic) {
932 Matcher<int> m1 = Eq(1);
933 EXPECT_TRUE(m1.Matches(1));
934 EXPECT_FALSE(m1.Matches(2));
935
936 Matcher<char> m2 = Eq(1);
937 EXPECT_TRUE(m2.Matches('\1'));
938 EXPECT_FALSE(m2.Matches('a'));
939}
940
941// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
942TEST(TypedEqTest, ChecksEqualityForGivenType) {
943 Matcher<char> m1 = TypedEq<char>('a');
944 EXPECT_TRUE(m1.Matches('a'));
945 EXPECT_FALSE(m1.Matches('b'));
946
947 Matcher<int> m2 = TypedEq<int>(6);
948 EXPECT_TRUE(m2.Matches(6));
949 EXPECT_FALSE(m2.Matches(7));
950}
951
952// Tests that TypedEq(v) describes itself properly.
953TEST(TypedEqTest, CanDescribeSelf) {
954 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
955}
956
957// Tests that TypedEq<T>(v) has type Matcher<T>.
958
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +0200959// Type<T>::IsTypeOf(v) compiles if the type of value v is T, where T
shiqiane35fdd92008-12-10 05:08:54 +0000960// is a "bare" type (i.e. not in the form of const U or U&). If v's
961// type is not T, the compiler will generate a message about
Troy Holsapplec8510502018-02-07 22:06:00 -0800962// "undefined reference".
shiqiane35fdd92008-12-10 05:08:54 +0000963template <typename T>
964struct Type {
zhanyong.wan32de5f52009-12-23 00:13:23 +0000965 static bool IsTypeOf(const T& /* v */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000966
967 template <typename T2>
968 static void IsTypeOf(T2 v);
969};
970
971TEST(TypedEqTest, HasSpecifiedType) {
972 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
973 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
974 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
975}
976
977// Tests that Ge(v) matches anything >= v.
978TEST(GeTest, ImplementsGreaterThanOrEqual) {
979 Matcher<int> m1 = Ge(0);
980 EXPECT_TRUE(m1.Matches(1));
981 EXPECT_TRUE(m1.Matches(0));
982 EXPECT_FALSE(m1.Matches(-1));
983}
984
985// Tests that Ge(v) describes itself properly.
986TEST(GeTest, CanDescribeSelf) {
987 Matcher<int> m = Ge(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000988 EXPECT_EQ("is >= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000989}
990
991// Tests that Gt(v) matches anything > v.
992TEST(GtTest, ImplementsGreaterThan) {
993 Matcher<double> m1 = Gt(0);
994 EXPECT_TRUE(m1.Matches(1.0));
995 EXPECT_FALSE(m1.Matches(0.0));
996 EXPECT_FALSE(m1.Matches(-1.0));
997}
998
999// Tests that Gt(v) describes itself properly.
1000TEST(GtTest, CanDescribeSelf) {
1001 Matcher<int> m = Gt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001002 EXPECT_EQ("is > 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001003}
1004
1005// Tests that Le(v) matches anything <= v.
1006TEST(LeTest, ImplementsLessThanOrEqual) {
1007 Matcher<char> m1 = Le('b');
1008 EXPECT_TRUE(m1.Matches('a'));
1009 EXPECT_TRUE(m1.Matches('b'));
1010 EXPECT_FALSE(m1.Matches('c'));
1011}
1012
1013// Tests that Le(v) describes itself properly.
1014TEST(LeTest, CanDescribeSelf) {
1015 Matcher<int> m = Le(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001016 EXPECT_EQ("is <= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001017}
1018
1019// Tests that Lt(v) matches anything < v.
1020TEST(LtTest, ImplementsLessThan) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001021 Matcher<const std::string&> m1 = Lt("Hello");
shiqiane35fdd92008-12-10 05:08:54 +00001022 EXPECT_TRUE(m1.Matches("Abc"));
1023 EXPECT_FALSE(m1.Matches("Hello"));
1024 EXPECT_FALSE(m1.Matches("Hello, world!"));
1025}
1026
1027// Tests that Lt(v) describes itself properly.
1028TEST(LtTest, CanDescribeSelf) {
1029 Matcher<int> m = Lt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001030 EXPECT_EQ("is < 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001031}
1032
1033// Tests that Ne(v) matches anything != v.
1034TEST(NeTest, ImplementsNotEqual) {
1035 Matcher<int> m1 = Ne(0);
1036 EXPECT_TRUE(m1.Matches(1));
1037 EXPECT_TRUE(m1.Matches(-1));
1038 EXPECT_FALSE(m1.Matches(0));
1039}
1040
1041// Tests that Ne(v) describes itself properly.
1042TEST(NeTest, CanDescribeSelf) {
1043 Matcher<int> m = Ne(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001044 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001045}
1046
Abseil Team9acd0652019-01-12 15:41:51 -05001047class MoveOnly {
1048 public:
1049 explicit MoveOnly(int i) : i_(i) {}
1050 MoveOnly(const MoveOnly&) = delete;
1051 MoveOnly(MoveOnly&&) = default;
1052 MoveOnly& operator=(const MoveOnly&) = delete;
1053 MoveOnly& operator=(MoveOnly&&) = default;
1054
1055 bool operator==(const MoveOnly& other) const { return i_ == other.i_; }
1056 bool operator!=(const MoveOnly& other) const { return i_ != other.i_; }
1057 bool operator<(const MoveOnly& other) const { return i_ < other.i_; }
1058 bool operator<=(const MoveOnly& other) const { return i_ <= other.i_; }
1059 bool operator>(const MoveOnly& other) const { return i_ > other.i_; }
1060 bool operator>=(const MoveOnly& other) const { return i_ >= other.i_; }
1061
1062 private:
1063 int i_;
1064};
1065
1066struct MoveHelper {
1067 MOCK_METHOD1(Call, void(MoveOnly));
1068};
1069
1070TEST(ComparisonBaseTest, WorksWithMoveOnly) {
1071 MoveOnly m{0};
1072 MoveHelper helper;
1073
1074 EXPECT_CALL(helper, Call(Eq(ByRef(m))));
1075 helper.Call(MoveOnly(0));
1076 EXPECT_CALL(helper, Call(Ne(ByRef(m))));
1077 helper.Call(MoveOnly(1));
1078 EXPECT_CALL(helper, Call(Le(ByRef(m))));
1079 helper.Call(MoveOnly(0));
1080 EXPECT_CALL(helper, Call(Lt(ByRef(m))));
1081 helper.Call(MoveOnly(-1));
1082 EXPECT_CALL(helper, Call(Ge(ByRef(m))));
1083 helper.Call(MoveOnly(0));
1084 EXPECT_CALL(helper, Call(Gt(ByRef(m))));
1085 helper.Call(MoveOnly(1));
1086}
1087
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001088// Tests that IsNull() matches any NULL pointer of any type.
1089TEST(IsNullTest, MatchesNullPointer) {
1090 Matcher<int*> m1 = IsNull();
Abseil Team4bb49ed2018-10-04 18:28:05 -04001091 int* p1 = nullptr;
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001092 int n = 0;
1093 EXPECT_TRUE(m1.Matches(p1));
1094 EXPECT_FALSE(m1.Matches(&n));
1095
1096 Matcher<const char*> m2 = IsNull();
Abseil Team4bb49ed2018-10-04 18:28:05 -04001097 const char* p2 = nullptr;
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001098 EXPECT_TRUE(m2.Matches(p2));
1099 EXPECT_FALSE(m2.Matches("hi"));
1100
1101 Matcher<void*> m3 = IsNull();
Abseil Team4bb49ed2018-10-04 18:28:05 -04001102 void* p3 = nullptr;
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001103 EXPECT_TRUE(m3.Matches(p3));
1104 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
1105}
1106
kosak6305ff52015-04-28 22:36:31 +00001107TEST(IsNullTest, StdFunction) {
1108 const Matcher<std::function<void()>> m = IsNull();
1109
1110 EXPECT_TRUE(m.Matches(std::function<void()>()));
1111 EXPECT_FALSE(m.Matches([]{}));
1112}
kosak6305ff52015-04-28 22:36:31 +00001113
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001114// Tests that IsNull() describes itself properly.
1115TEST(IsNullTest, CanDescribeSelf) {
1116 Matcher<int*> m = IsNull();
1117 EXPECT_EQ("is NULL", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001118 EXPECT_EQ("isn't NULL", DescribeNegation(m));
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001119}
1120
shiqiane35fdd92008-12-10 05:08:54 +00001121// Tests that NotNull() matches any non-NULL pointer of any type.
1122TEST(NotNullTest, MatchesNonNullPointer) {
1123 Matcher<int*> m1 = NotNull();
Abseil Team4bb49ed2018-10-04 18:28:05 -04001124 int* p1 = nullptr;
shiqiane35fdd92008-12-10 05:08:54 +00001125 int n = 0;
1126 EXPECT_FALSE(m1.Matches(p1));
1127 EXPECT_TRUE(m1.Matches(&n));
1128
1129 Matcher<const char*> m2 = NotNull();
Abseil Team4bb49ed2018-10-04 18:28:05 -04001130 const char* p2 = nullptr;
shiqiane35fdd92008-12-10 05:08:54 +00001131 EXPECT_FALSE(m2.Matches(p2));
1132 EXPECT_TRUE(m2.Matches("hi"));
1133}
1134
vladlosev79b83502009-11-18 00:43:37 +00001135TEST(NotNullTest, LinkedPtr) {
misterg80b43d92018-10-29 11:09:33 -04001136 const Matcher<std::shared_ptr<int>> m = NotNull();
1137 const std::shared_ptr<int> null_p;
1138 const std::shared_ptr<int> non_null_p(new int);
vladlosev79b83502009-11-18 00:43:37 +00001139
1140 EXPECT_FALSE(m.Matches(null_p));
1141 EXPECT_TRUE(m.Matches(non_null_p));
1142}
1143
1144TEST(NotNullTest, ReferenceToConstLinkedPtr) {
misterg80b43d92018-10-29 11:09:33 -04001145 const Matcher<const std::shared_ptr<double>&> m = NotNull();
1146 const std::shared_ptr<double> null_p;
1147 const std::shared_ptr<double> non_null_p(new double);
vladlosev79b83502009-11-18 00:43:37 +00001148
1149 EXPECT_FALSE(m.Matches(null_p));
1150 EXPECT_TRUE(m.Matches(non_null_p));
1151}
1152
kosak6305ff52015-04-28 22:36:31 +00001153TEST(NotNullTest, StdFunction) {
1154 const Matcher<std::function<void()>> m = NotNull();
1155
1156 EXPECT_TRUE(m.Matches([]{}));
1157 EXPECT_FALSE(m.Matches(std::function<void()>()));
1158}
kosak6305ff52015-04-28 22:36:31 +00001159
shiqiane35fdd92008-12-10 05:08:54 +00001160// Tests that NotNull() describes itself properly.
1161TEST(NotNullTest, CanDescribeSelf) {
1162 Matcher<int*> m = NotNull();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001163 EXPECT_EQ("isn't NULL", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001164}
1165
1166// Tests that Ref(variable) matches an argument that references
1167// 'variable'.
1168TEST(RefTest, MatchesSameVariable) {
1169 int a = 0;
1170 int b = 0;
1171 Matcher<int&> m = Ref(a);
1172 EXPECT_TRUE(m.Matches(a));
1173 EXPECT_FALSE(m.Matches(b));
1174}
1175
1176// Tests that Ref(variable) describes itself properly.
1177TEST(RefTest, CanDescribeSelf) {
1178 int n = 5;
1179 Matcher<int&> m = Ref(n);
1180 stringstream ss;
1181 ss << "references the variable @" << &n << " 5";
Nico Weber09fd5b32017-05-15 17:07:03 -04001182 EXPECT_EQ(ss.str(), Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001183}
1184
1185// Test that Ref(non_const_varialbe) can be used as a matcher for a
1186// const reference.
1187TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1188 int a = 0;
1189 int b = 0;
1190 Matcher<const int&> m = Ref(a);
1191 EXPECT_TRUE(m.Matches(a));
1192 EXPECT_FALSE(m.Matches(b));
1193}
1194
1195// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1196// used wherever Ref(base) can be used (Ref(derived) is a sub-type
1197// of Ref(base), but not vice versa.
1198
shiqiane35fdd92008-12-10 05:08:54 +00001199TEST(RefTest, IsCovariant) {
1200 Base base, base2;
1201 Derived derived;
1202 Matcher<const Base&> m1 = Ref(base);
1203 EXPECT_TRUE(m1.Matches(base));
1204 EXPECT_FALSE(m1.Matches(base2));
1205 EXPECT_FALSE(m1.Matches(derived));
1206
1207 m1 = Ref(derived);
1208 EXPECT_TRUE(m1.Matches(derived));
1209 EXPECT_FALSE(m1.Matches(base));
1210 EXPECT_FALSE(m1.Matches(base2));
1211}
1212
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001213TEST(RefTest, ExplainsResult) {
1214 int n = 0;
1215 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1216 StartsWith("which is located @"));
1217
1218 int m = 0;
1219 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1220 StartsWith("which is located @"));
1221}
1222
shiqiane35fdd92008-12-10 05:08:54 +00001223// Tests string comparison matchers.
1224
1225TEST(StrEqTest, MatchesEqualString) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001226 Matcher<const char*> m = StrEq(std::string("Hello"));
shiqiane35fdd92008-12-10 05:08:54 +00001227 EXPECT_TRUE(m.Matches("Hello"));
1228 EXPECT_FALSE(m.Matches("hello"));
Abseil Team4bb49ed2018-10-04 18:28:05 -04001229 EXPECT_FALSE(m.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00001230
Nico Weber09fd5b32017-05-15 17:07:03 -04001231 Matcher<const std::string&> m2 = StrEq("Hello");
shiqiane35fdd92008-12-10 05:08:54 +00001232 EXPECT_TRUE(m2.Matches("Hello"));
1233 EXPECT_FALSE(m2.Matches("Hi"));
Gennadiy Civile55089e2018-04-04 14:05:00 -04001234
1235#if GTEST_HAS_ABSL
1236 Matcher<const absl::string_view&> m3 = StrEq("Hello");
1237 EXPECT_TRUE(m3.Matches(absl::string_view("Hello")));
1238 EXPECT_FALSE(m3.Matches(absl::string_view("hello")));
1239 EXPECT_FALSE(m3.Matches(absl::string_view()));
Abseil Teamffc9bae2018-09-13 11:27:56 -04001240
1241 Matcher<const absl::string_view&> m_empty = StrEq("");
1242 EXPECT_TRUE(m_empty.Matches(absl::string_view("")));
1243 EXPECT_TRUE(m_empty.Matches(absl::string_view()));
1244 EXPECT_FALSE(m_empty.Matches(absl::string_view("hello")));
Gennadiy Civile55089e2018-04-04 14:05:00 -04001245#endif // GTEST_HAS_ABSL
shiqiane35fdd92008-12-10 05:08:54 +00001246}
1247
1248TEST(StrEqTest, CanDescribeSelf) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001249 Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
vladlosevaa432202011-04-01 21:58:42 +00001250 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
shiqiane35fdd92008-12-10 05:08:54 +00001251 Describe(m));
1252
Nico Weber09fd5b32017-05-15 17:07:03 -04001253 std::string str("01204500800");
shiqiane35fdd92008-12-10 05:08:54 +00001254 str[3] = '\0';
Nico Weber09fd5b32017-05-15 17:07:03 -04001255 Matcher<std::string> m2 = StrEq(str);
shiqiane35fdd92008-12-10 05:08:54 +00001256 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1257 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
Nico Weber09fd5b32017-05-15 17:07:03 -04001258 Matcher<std::string> m3 = StrEq(str);
shiqiane35fdd92008-12-10 05:08:54 +00001259 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1260}
1261
1262TEST(StrNeTest, MatchesUnequalString) {
1263 Matcher<const char*> m = StrNe("Hello");
1264 EXPECT_TRUE(m.Matches(""));
Abseil Team4bb49ed2018-10-04 18:28:05 -04001265 EXPECT_TRUE(m.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00001266 EXPECT_FALSE(m.Matches("Hello"));
1267
Nico Weber09fd5b32017-05-15 17:07:03 -04001268 Matcher<std::string> m2 = StrNe(std::string("Hello"));
shiqiane35fdd92008-12-10 05:08:54 +00001269 EXPECT_TRUE(m2.Matches("hello"));
1270 EXPECT_FALSE(m2.Matches("Hello"));
Gennadiy Civile55089e2018-04-04 14:05:00 -04001271
1272#if GTEST_HAS_ABSL
1273 Matcher<const absl::string_view> m3 = StrNe("Hello");
1274 EXPECT_TRUE(m3.Matches(absl::string_view("")));
1275 EXPECT_TRUE(m3.Matches(absl::string_view()));
1276 EXPECT_FALSE(m3.Matches(absl::string_view("Hello")));
1277#endif // GTEST_HAS_ABSL
shiqiane35fdd92008-12-10 05:08:54 +00001278}
1279
1280TEST(StrNeTest, CanDescribeSelf) {
1281 Matcher<const char*> m = StrNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001282 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001283}
1284
1285TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
Gennadiy Civile55089e2018-04-04 14:05:00 -04001286 Matcher<const char*> m = StrCaseEq(std::string("Hello"));
shiqiane35fdd92008-12-10 05:08:54 +00001287 EXPECT_TRUE(m.Matches("Hello"));
1288 EXPECT_TRUE(m.Matches("hello"));
1289 EXPECT_FALSE(m.Matches("Hi"));
Abseil Team4bb49ed2018-10-04 18:28:05 -04001290 EXPECT_FALSE(m.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00001291
Gennadiy Civile55089e2018-04-04 14:05:00 -04001292 Matcher<const std::string&> m2 = StrCaseEq("Hello");
shiqiane35fdd92008-12-10 05:08:54 +00001293 EXPECT_TRUE(m2.Matches("hello"));
1294 EXPECT_FALSE(m2.Matches("Hi"));
Gennadiy Civile55089e2018-04-04 14:05:00 -04001295
1296#if GTEST_HAS_ABSL
1297 Matcher<const absl::string_view&> m3 = StrCaseEq(std::string("Hello"));
1298 EXPECT_TRUE(m3.Matches(absl::string_view("Hello")));
1299 EXPECT_TRUE(m3.Matches(absl::string_view("hello")));
1300 EXPECT_FALSE(m3.Matches(absl::string_view("Hi")));
1301 EXPECT_FALSE(m3.Matches(absl::string_view()));
1302#endif // GTEST_HAS_ABSL
shiqiane35fdd92008-12-10 05:08:54 +00001303}
1304
1305TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001306 std::string str1("oabocdooeoo");
1307 std::string str2("OABOCDOOEOO");
1308 Matcher<const std::string&> m0 = StrCaseEq(str1);
1309 EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0')));
shiqiane35fdd92008-12-10 05:08:54 +00001310
1311 str1[3] = str2[3] = '\0';
Nico Weber09fd5b32017-05-15 17:07:03 -04001312 Matcher<const std::string&> m1 = StrCaseEq(str1);
shiqiane35fdd92008-12-10 05:08:54 +00001313 EXPECT_TRUE(m1.Matches(str2));
1314
1315 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1316 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
Nico Weber09fd5b32017-05-15 17:07:03 -04001317 Matcher<const std::string&> m2 = StrCaseEq(str1);
shiqiane35fdd92008-12-10 05:08:54 +00001318 str1[9] = str2[9] = '\0';
1319 EXPECT_FALSE(m2.Matches(str2));
1320
Nico Weber09fd5b32017-05-15 17:07:03 -04001321 Matcher<const std::string&> m3 = StrCaseEq(str1);
shiqiane35fdd92008-12-10 05:08:54 +00001322 EXPECT_TRUE(m3.Matches(str2));
1323
1324 EXPECT_FALSE(m3.Matches(str2 + "x"));
1325 str2.append(1, '\0');
1326 EXPECT_FALSE(m3.Matches(str2));
Nico Weber09fd5b32017-05-15 17:07:03 -04001327 EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9)));
shiqiane35fdd92008-12-10 05:08:54 +00001328}
1329
1330TEST(StrCaseEqTest, CanDescribeSelf) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001331 Matcher<std::string> m = StrCaseEq("Hi");
shiqiane35fdd92008-12-10 05:08:54 +00001332 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1333}
1334
1335TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1336 Matcher<const char*> m = StrCaseNe("Hello");
1337 EXPECT_TRUE(m.Matches("Hi"));
Abseil Team4bb49ed2018-10-04 18:28:05 -04001338 EXPECT_TRUE(m.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00001339 EXPECT_FALSE(m.Matches("Hello"));
1340 EXPECT_FALSE(m.Matches("hello"));
1341
Nico Weber09fd5b32017-05-15 17:07:03 -04001342 Matcher<std::string> m2 = StrCaseNe(std::string("Hello"));
shiqiane35fdd92008-12-10 05:08:54 +00001343 EXPECT_TRUE(m2.Matches(""));
1344 EXPECT_FALSE(m2.Matches("Hello"));
Gennadiy Civile55089e2018-04-04 14:05:00 -04001345
1346#if GTEST_HAS_ABSL
1347 Matcher<const absl::string_view> m3 = StrCaseNe("Hello");
1348 EXPECT_TRUE(m3.Matches(absl::string_view("Hi")));
1349 EXPECT_TRUE(m3.Matches(absl::string_view()));
1350 EXPECT_FALSE(m3.Matches(absl::string_view("Hello")));
1351 EXPECT_FALSE(m3.Matches(absl::string_view("hello")));
1352#endif // GTEST_HAS_ABSL
shiqiane35fdd92008-12-10 05:08:54 +00001353}
1354
1355TEST(StrCaseNeTest, CanDescribeSelf) {
1356 Matcher<const char*> m = StrCaseNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001357 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001358}
1359
1360// Tests that HasSubstr() works for matching string-typed values.
1361TEST(HasSubstrTest, WorksForStringClasses) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001362 const Matcher<std::string> m1 = HasSubstr("foo");
1363 EXPECT_TRUE(m1.Matches(std::string("I love food.")));
1364 EXPECT_FALSE(m1.Matches(std::string("tofo")));
shiqiane35fdd92008-12-10 05:08:54 +00001365
1366 const Matcher<const std::string&> m2 = HasSubstr("foo");
1367 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1368 EXPECT_FALSE(m2.Matches(std::string("tofo")));
Abseil Teamffc9bae2018-09-13 11:27:56 -04001369
1370 const Matcher<std::string> m_empty = HasSubstr("");
1371 EXPECT_TRUE(m_empty.Matches(std::string()));
1372 EXPECT_TRUE(m_empty.Matches(std::string("not empty")));
shiqiane35fdd92008-12-10 05:08:54 +00001373}
1374
1375// Tests that HasSubstr() works for matching C-string-typed values.
1376TEST(HasSubstrTest, WorksForCStrings) {
1377 const Matcher<char*> m1 = HasSubstr("foo");
1378 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1379 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
Abseil Team4bb49ed2018-10-04 18:28:05 -04001380 EXPECT_FALSE(m1.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00001381
1382 const Matcher<const char*> m2 = HasSubstr("foo");
1383 EXPECT_TRUE(m2.Matches("I love food."));
1384 EXPECT_FALSE(m2.Matches("tofo"));
Abseil Team4bb49ed2018-10-04 18:28:05 -04001385 EXPECT_FALSE(m2.Matches(nullptr));
Abseil Teamffc9bae2018-09-13 11:27:56 -04001386
1387 const Matcher<const char*> m_empty = HasSubstr("");
1388 EXPECT_TRUE(m_empty.Matches("not empty"));
1389 EXPECT_TRUE(m_empty.Matches(""));
Abseil Team4bb49ed2018-10-04 18:28:05 -04001390 EXPECT_FALSE(m_empty.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00001391}
1392
Gennadiy Civile55089e2018-04-04 14:05:00 -04001393#if GTEST_HAS_ABSL
1394// Tests that HasSubstr() works for matching absl::string_view-typed values.
1395TEST(HasSubstrTest, WorksForStringViewClasses) {
1396 const Matcher<absl::string_view> m1 = HasSubstr("foo");
1397 EXPECT_TRUE(m1.Matches(absl::string_view("I love food.")));
1398 EXPECT_FALSE(m1.Matches(absl::string_view("tofo")));
1399 EXPECT_FALSE(m1.Matches(absl::string_view()));
1400
1401 const Matcher<const absl::string_view&> m2 = HasSubstr("foo");
1402 EXPECT_TRUE(m2.Matches(absl::string_view("I love food.")));
1403 EXPECT_FALSE(m2.Matches(absl::string_view("tofo")));
1404 EXPECT_FALSE(m2.Matches(absl::string_view()));
1405
1406 const Matcher<const absl::string_view&> m3 = HasSubstr("");
1407 EXPECT_TRUE(m3.Matches(absl::string_view("foo")));
Abseil Teamffc9bae2018-09-13 11:27:56 -04001408 EXPECT_TRUE(m3.Matches(absl::string_view("")));
1409 EXPECT_TRUE(m3.Matches(absl::string_view()));
Gennadiy Civile55089e2018-04-04 14:05:00 -04001410}
1411#endif // GTEST_HAS_ABSL
1412
shiqiane35fdd92008-12-10 05:08:54 +00001413// Tests that HasSubstr(s) describes itself properly.
1414TEST(HasSubstrTest, CanDescribeSelf) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001415 Matcher<std::string> m = HasSubstr("foo\n\"");
shiqiane35fdd92008-12-10 05:08:54 +00001416 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1417}
1418
zhanyong.wanb5937da2009-07-16 20:26:41 +00001419TEST(KeyTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001420 Matcher<const pair<std::string, int>&> m = Key("foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001421 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001422 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1423}
1424
1425TEST(KeyTest, ExplainsResult) {
1426 Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1427 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1428 Explain(m, make_pair(5, true)));
1429 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1430 Explain(m, make_pair(15, true)));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001431}
1432
1433TEST(KeyTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001434 pair<int, std::string> p(25, "foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001435 EXPECT_THAT(p, Key(25));
1436 EXPECT_THAT(p, Not(Key(42)));
1437 EXPECT_THAT(p, Key(Ge(20)));
1438 EXPECT_THAT(p, Not(Key(Lt(25))));
1439}
1440
Abseil Team9acd0652019-01-12 15:41:51 -05001441TEST(KeyTest, WorksWithMoveOnly) {
1442 pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
1443 EXPECT_THAT(p, Key(Eq(nullptr)));
1444}
1445
Gennadiy Civile55089e2018-04-04 14:05:00 -04001446template <size_t I>
1447struct Tag {};
1448
1449struct PairWithGet {
1450 int member_1;
Abseil Teamd9825432019-04-01 12:06:49 -04001451 std::string member_2;
Gennadiy Civile55089e2018-04-04 14:05:00 -04001452 using first_type = int;
Abseil Teamd9825432019-04-01 12:06:49 -04001453 using second_type = std::string;
Gennadiy Civile55089e2018-04-04 14:05:00 -04001454
1455 const int& GetImpl(Tag<0>) const { return member_1; }
Abseil Teamd9825432019-04-01 12:06:49 -04001456 const std::string& GetImpl(Tag<1>) const { return member_2; }
Gennadiy Civile55089e2018-04-04 14:05:00 -04001457};
1458template <size_t I>
1459auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag<I>())) {
1460 return value.GetImpl(Tag<I>());
1461}
1462TEST(PairTest, MatchesPairWithGetCorrectly) {
1463 PairWithGet p{25, "foo"};
1464 EXPECT_THAT(p, Key(25));
1465 EXPECT_THAT(p, Not(Key(42)));
1466 EXPECT_THAT(p, Key(Ge(20)));
1467 EXPECT_THAT(p, Not(Key(Lt(25))));
1468
1469 std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
1470 EXPECT_THAT(v, Contains(Key(29)));
1471}
Gennadiy Civile55089e2018-04-04 14:05:00 -04001472
zhanyong.wanb5937da2009-07-16 20:26:41 +00001473TEST(KeyTest, SafelyCastsInnerMatcher) {
1474 Matcher<int> is_positive = Gt(0);
1475 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001476 pair<char, bool> p('a', true);
zhanyong.wanb5937da2009-07-16 20:26:41 +00001477 EXPECT_THAT(p, Key(is_positive));
1478 EXPECT_THAT(p, Not(Key(is_negative)));
1479}
1480
1481TEST(KeyTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001482 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001483 container.insert(make_pair(1, 'a'));
1484 container.insert(make_pair(2, 'b'));
1485 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001486 EXPECT_THAT(container, Contains(Key(1)));
1487 EXPECT_THAT(container, Not(Contains(Key(3))));
1488}
1489
1490TEST(KeyTest, InsideContainsUsingMultimap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001491 multimap<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001492 container.insert(make_pair(1, 'a'));
1493 container.insert(make_pair(2, 'b'));
1494 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001495
1496 EXPECT_THAT(container, Not(Contains(Key(25))));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001497 container.insert(make_pair(25, 'd'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001498 EXPECT_THAT(container, Contains(Key(25)));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001499 container.insert(make_pair(25, 'e'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001500 EXPECT_THAT(container, Contains(Key(25)));
1501
1502 EXPECT_THAT(container, Contains(Key(1)));
1503 EXPECT_THAT(container, Not(Contains(Key(3))));
1504}
1505
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001506TEST(PairTest, Typing) {
1507 // Test verifies the following type conversions can be compiled.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001508 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1509 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1510 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001511
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001512 Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1513 Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001514}
1515
1516TEST(PairTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001517 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001518 EXPECT_EQ("has a first field that is equal to \"foo\""
1519 ", and has a second field that is equal to 42",
1520 Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001521 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1522 ", or has a second field that isn't equal to 42",
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001523 DescribeNegation(m1));
1524 // Double and triple negation (1 or 2 times not and description of negation).
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001525 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1526 EXPECT_EQ("has a first field that isn't equal to 13"
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001527 ", and has a second field that is equal to 42",
1528 DescribeNegation(m2));
1529}
1530
1531TEST(PairTest, CanExplainMatchResultTo) {
zhanyong.wan82113312010-01-08 21:55:40 +00001532 // If neither field matches, Pair() should explain about the first
1533 // field.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001534 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001535 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001536 Explain(m, make_pair(-1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001537
zhanyong.wan82113312010-01-08 21:55:40 +00001538 // If the first field matches but the second doesn't, Pair() should
1539 // explain about the second field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001540 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001541 Explain(m, make_pair(1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001542
zhanyong.wan82113312010-01-08 21:55:40 +00001543 // If the first field doesn't match but the second does, Pair()
1544 // should explain about the first field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001545 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001546 Explain(m, make_pair(-1, 2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001547
zhanyong.wan82113312010-01-08 21:55:40 +00001548 // If both fields match, Pair() should explain about them both.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001549 EXPECT_EQ("whose both fields match, where the first field is a value "
1550 "which is 1 more than 0, and the second field is a value "
1551 "which is 2 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001552 Explain(m, make_pair(1, 2)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001553
1554 // If only the first match has an explanation, only this explanation should
1555 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001556 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001557 EXPECT_EQ("whose both fields match, where the first field is a value "
1558 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001559 Explain(explain_first, make_pair(1, 0)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001560
1561 // If only the second match has an explanation, only this explanation should
1562 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001563 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001564 EXPECT_EQ("whose both fields match, where the second field is a value "
1565 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001566 Explain(explain_second, make_pair(0, 1)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001567}
1568
1569TEST(PairTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001570 pair<int, std::string> p(25, "foo");
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001571
1572 // Both fields match.
1573 EXPECT_THAT(p, Pair(25, "foo"));
1574 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1575
Gennadiy Civile55089e2018-04-04 14:05:00 -04001576 // 'first' doesnt' match, but 'second' matches.
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001577 EXPECT_THAT(p, Not(Pair(42, "foo")));
1578 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1579
1580 // 'first' matches, but 'second' doesn't match.
1581 EXPECT_THAT(p, Not(Pair(25, "bar")));
1582 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1583
1584 // Neither field matches.
1585 EXPECT_THAT(p, Not(Pair(13, "bar")));
1586 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1587}
1588
Abseil Team9acd0652019-01-12 15:41:51 -05001589TEST(PairTest, WorksWithMoveOnly) {
1590 pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
1591 p.second.reset(new int(7));
1592 EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr)));
1593}
1594
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001595TEST(PairTest, SafelyCastsInnerMatchers) {
1596 Matcher<int> is_positive = Gt(0);
1597 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001598 pair<char, bool> p('a', true);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001599 EXPECT_THAT(p, Pair(is_positive, _));
1600 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1601 EXPECT_THAT(p, Pair(_, is_positive));
1602 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1603}
1604
1605TEST(PairTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001606 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001607 container.insert(make_pair(1, 'a'));
1608 container.insert(make_pair(2, 'b'));
1609 container.insert(make_pair(4, 'c'));
zhanyong.wan95b12332009-09-25 18:55:50 +00001610 EXPECT_THAT(container, Contains(Pair(1, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001611 EXPECT_THAT(container, Contains(Pair(1, _)));
zhanyong.wan95b12332009-09-25 18:55:50 +00001612 EXPECT_THAT(container, Contains(Pair(_, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001613 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1614}
1615
Abseil Team1ec20f82018-12-15 08:11:02 -05001616TEST(ContainsTest, WorksWithMoveOnly) {
1617 ContainerHelper helper;
1618 EXPECT_CALL(helper, Call(Contains(Pointee(2))));
1619 helper.Call(MakeUniquePtrs({1, 2}));
1620}
1621
Gennadiy Civile55089e2018-04-04 14:05:00 -04001622TEST(PairTest, UseGetInsteadOfMembers) {
1623 PairWithGet pair{7, "ABC"};
1624 EXPECT_THAT(pair, Pair(7, "ABC"));
1625 EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB")));
1626 EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC")));
1627
1628 std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
Abseil Teamd9825432019-04-01 12:06:49 -04001629 EXPECT_THAT(v,
1630 ElementsAre(Pair(11, std::string("Foo")), Pair(Ge(10), Not(""))));
Gennadiy Civile55089e2018-04-04 14:05:00 -04001631}
Gennadiy Civile55089e2018-04-04 14:05:00 -04001632
shiqiane35fdd92008-12-10 05:08:54 +00001633// Tests StartsWith(s).
1634
1635TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001636 const Matcher<const char*> m1 = StartsWith(std::string(""));
shiqiane35fdd92008-12-10 05:08:54 +00001637 EXPECT_TRUE(m1.Matches("Hi"));
1638 EXPECT_TRUE(m1.Matches(""));
Abseil Team4bb49ed2018-10-04 18:28:05 -04001639 EXPECT_FALSE(m1.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00001640
Nico Weber09fd5b32017-05-15 17:07:03 -04001641 const Matcher<const std::string&> m2 = StartsWith("Hi");
shiqiane35fdd92008-12-10 05:08:54 +00001642 EXPECT_TRUE(m2.Matches("Hi"));
1643 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1644 EXPECT_TRUE(m2.Matches("High"));
1645 EXPECT_FALSE(m2.Matches("H"));
1646 EXPECT_FALSE(m2.Matches(" Hi"));
Abseil Teamffc9bae2018-09-13 11:27:56 -04001647
1648#if GTEST_HAS_ABSL
1649 const Matcher<absl::string_view> m_empty = StartsWith("");
1650 EXPECT_TRUE(m_empty.Matches(absl::string_view()));
1651 EXPECT_TRUE(m_empty.Matches(absl::string_view("")));
1652 EXPECT_TRUE(m_empty.Matches(absl::string_view("not empty")));
1653#endif // GTEST_HAS_ABSL
shiqiane35fdd92008-12-10 05:08:54 +00001654}
1655
1656TEST(StartsWithTest, CanDescribeSelf) {
1657 Matcher<const std::string> m = StartsWith("Hi");
1658 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1659}
1660
1661// Tests EndsWith(s).
1662
1663TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1664 const Matcher<const char*> m1 = EndsWith("");
1665 EXPECT_TRUE(m1.Matches("Hi"));
1666 EXPECT_TRUE(m1.Matches(""));
Abseil Team4bb49ed2018-10-04 18:28:05 -04001667 EXPECT_FALSE(m1.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00001668
Gennadiy Civile55089e2018-04-04 14:05:00 -04001669 const Matcher<const std::string&> m2 = EndsWith(std::string("Hi"));
shiqiane35fdd92008-12-10 05:08:54 +00001670 EXPECT_TRUE(m2.Matches("Hi"));
1671 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1672 EXPECT_TRUE(m2.Matches("Super Hi"));
1673 EXPECT_FALSE(m2.Matches("i"));
1674 EXPECT_FALSE(m2.Matches("Hi "));
Gennadiy Civile55089e2018-04-04 14:05:00 -04001675
Gennadiy Civile55089e2018-04-04 14:05:00 -04001676#if GTEST_HAS_ABSL
1677 const Matcher<const absl::string_view&> m4 = EndsWith("");
1678 EXPECT_TRUE(m4.Matches("Hi"));
1679 EXPECT_TRUE(m4.Matches(""));
Abseil Teamffc9bae2018-09-13 11:27:56 -04001680 EXPECT_TRUE(m4.Matches(absl::string_view()));
1681 EXPECT_TRUE(m4.Matches(absl::string_view("")));
Gennadiy Civile55089e2018-04-04 14:05:00 -04001682#endif // GTEST_HAS_ABSL
shiqiane35fdd92008-12-10 05:08:54 +00001683}
1684
1685TEST(EndsWithTest, CanDescribeSelf) {
1686 Matcher<const std::string> m = EndsWith("Hi");
1687 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1688}
1689
shiqiane35fdd92008-12-10 05:08:54 +00001690// Tests MatchesRegex().
1691
1692TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1693 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1694 EXPECT_TRUE(m1.Matches("az"));
1695 EXPECT_TRUE(m1.Matches("abcz"));
Abseil Team4bb49ed2018-10-04 18:28:05 -04001696 EXPECT_FALSE(m1.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00001697
Nico Weber09fd5b32017-05-15 17:07:03 -04001698 const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z"));
shiqiane35fdd92008-12-10 05:08:54 +00001699 EXPECT_TRUE(m2.Matches("azbz"));
1700 EXPECT_FALSE(m2.Matches("az1"));
1701 EXPECT_FALSE(m2.Matches("1az"));
Gennadiy Civile55089e2018-04-04 14:05:00 -04001702
1703#if GTEST_HAS_ABSL
1704 const Matcher<const absl::string_view&> m3 = MatchesRegex("a.*z");
1705 EXPECT_TRUE(m3.Matches(absl::string_view("az")));
1706 EXPECT_TRUE(m3.Matches(absl::string_view("abcz")));
1707 EXPECT_FALSE(m3.Matches(absl::string_view("1az")));
Gennadiy Civile55089e2018-04-04 14:05:00 -04001708 EXPECT_FALSE(m3.Matches(absl::string_view()));
1709 const Matcher<const absl::string_view&> m4 = MatchesRegex("");
Abseil Teamffc9bae2018-09-13 11:27:56 -04001710 EXPECT_TRUE(m4.Matches(absl::string_view("")));
1711 EXPECT_TRUE(m4.Matches(absl::string_view()));
Gennadiy Civile55089e2018-04-04 14:05:00 -04001712#endif // GTEST_HAS_ABSL
shiqiane35fdd92008-12-10 05:08:54 +00001713}
1714
1715TEST(MatchesRegexTest, CanDescribeSelf) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001716 Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*"));
shiqiane35fdd92008-12-10 05:08:54 +00001717 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1718
zhanyong.wand14aaed2010-01-14 05:36:32 +00001719 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1720 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
Gennadiy Civile55089e2018-04-04 14:05:00 -04001721
1722#if GTEST_HAS_ABSL
1723 Matcher<const absl::string_view> m3 = MatchesRegex(new RE("0.*"));
1724 EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3));
1725#endif // GTEST_HAS_ABSL
shiqiane35fdd92008-12-10 05:08:54 +00001726}
1727
1728// Tests ContainsRegex().
1729
1730TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001731 const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z"));
shiqiane35fdd92008-12-10 05:08:54 +00001732 EXPECT_TRUE(m1.Matches("az"));
1733 EXPECT_TRUE(m1.Matches("0abcz1"));
Abseil Team4bb49ed2018-10-04 18:28:05 -04001734 EXPECT_FALSE(m1.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00001735
Nico Weber09fd5b32017-05-15 17:07:03 -04001736 const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z"));
shiqiane35fdd92008-12-10 05:08:54 +00001737 EXPECT_TRUE(m2.Matches("azbz"));
1738 EXPECT_TRUE(m2.Matches("az1"));
1739 EXPECT_FALSE(m2.Matches("1a"));
Gennadiy Civile55089e2018-04-04 14:05:00 -04001740
1741#if GTEST_HAS_ABSL
1742 const Matcher<const absl::string_view&> m3 = ContainsRegex(new RE("a.*z"));
1743 EXPECT_TRUE(m3.Matches(absl::string_view("azbz")));
1744 EXPECT_TRUE(m3.Matches(absl::string_view("az1")));
1745 EXPECT_FALSE(m3.Matches(absl::string_view("1a")));
Gennadiy Civile55089e2018-04-04 14:05:00 -04001746 EXPECT_FALSE(m3.Matches(absl::string_view()));
1747 const Matcher<const absl::string_view&> m4 = ContainsRegex("");
Abseil Teamffc9bae2018-09-13 11:27:56 -04001748 EXPECT_TRUE(m4.Matches(absl::string_view("")));
1749 EXPECT_TRUE(m4.Matches(absl::string_view()));
Gennadiy Civile55089e2018-04-04 14:05:00 -04001750#endif // GTEST_HAS_ABSL
shiqiane35fdd92008-12-10 05:08:54 +00001751}
1752
1753TEST(ContainsRegexTest, CanDescribeSelf) {
1754 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1755 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1756
zhanyong.wand14aaed2010-01-14 05:36:32 +00001757 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1758 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
Gennadiy Civile55089e2018-04-04 14:05:00 -04001759
1760#if GTEST_HAS_ABSL
1761 Matcher<const absl::string_view> m3 = ContainsRegex(new RE("0.*"));
1762 EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3));
1763#endif // GTEST_HAS_ABSL
shiqiane35fdd92008-12-10 05:08:54 +00001764}
shiqiane35fdd92008-12-10 05:08:54 +00001765
1766// Tests for wide strings.
1767#if GTEST_HAS_STD_WSTRING
1768TEST(StdWideStrEqTest, MatchesEqual) {
1769 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1770 EXPECT_TRUE(m.Matches(L"Hello"));
1771 EXPECT_FALSE(m.Matches(L"hello"));
Abseil Team4bb49ed2018-10-04 18:28:05 -04001772 EXPECT_FALSE(m.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00001773
1774 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1775 EXPECT_TRUE(m2.Matches(L"Hello"));
1776 EXPECT_FALSE(m2.Matches(L"Hi"));
1777
1778 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1779 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1780 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1781
1782 ::std::wstring str(L"01204500800");
1783 str[3] = L'\0';
1784 Matcher<const ::std::wstring&> m4 = StrEq(str);
1785 EXPECT_TRUE(m4.Matches(str));
1786 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1787 Matcher<const ::std::wstring&> m5 = StrEq(str);
1788 EXPECT_TRUE(m5.Matches(str));
1789}
1790
1791TEST(StdWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001792 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1793 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001794 Describe(m));
1795
1796 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1797 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1798 Describe(m2));
1799
1800 ::std::wstring str(L"01204500800");
1801 str[3] = L'\0';
1802 Matcher<const ::std::wstring&> m4 = StrEq(str);
1803 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1804 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1805 Matcher<const ::std::wstring&> m5 = StrEq(str);
1806 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1807}
1808
1809TEST(StdWideStrNeTest, MatchesUnequalString) {
1810 Matcher<const wchar_t*> m = StrNe(L"Hello");
1811 EXPECT_TRUE(m.Matches(L""));
Abseil Team4bb49ed2018-10-04 18:28:05 -04001812 EXPECT_TRUE(m.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00001813 EXPECT_FALSE(m.Matches(L"Hello"));
1814
1815 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1816 EXPECT_TRUE(m2.Matches(L"hello"));
1817 EXPECT_FALSE(m2.Matches(L"Hello"));
1818}
1819
1820TEST(StdWideStrNeTest, CanDescribeSelf) {
1821 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001822 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001823}
1824
1825TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1826 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1827 EXPECT_TRUE(m.Matches(L"Hello"));
1828 EXPECT_TRUE(m.Matches(L"hello"));
1829 EXPECT_FALSE(m.Matches(L"Hi"));
Abseil Team4bb49ed2018-10-04 18:28:05 -04001830 EXPECT_FALSE(m.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00001831
1832 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1833 EXPECT_TRUE(m2.Matches(L"hello"));
1834 EXPECT_FALSE(m2.Matches(L"Hi"));
1835}
1836
1837TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1838 ::std::wstring str1(L"oabocdooeoo");
1839 ::std::wstring str2(L"OABOCDOOEOO");
1840 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1841 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1842
1843 str1[3] = str2[3] = L'\0';
1844 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1845 EXPECT_TRUE(m1.Matches(str2));
1846
1847 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1848 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1849 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1850 str1[9] = str2[9] = L'\0';
1851 EXPECT_FALSE(m2.Matches(str2));
1852
1853 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1854 EXPECT_TRUE(m3.Matches(str2));
1855
1856 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1857 str2.append(1, L'\0');
1858 EXPECT_FALSE(m3.Matches(str2));
1859 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1860}
1861
1862TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1863 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1864 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1865}
1866
1867TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1868 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1869 EXPECT_TRUE(m.Matches(L"Hi"));
Abseil Team4bb49ed2018-10-04 18:28:05 -04001870 EXPECT_TRUE(m.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00001871 EXPECT_FALSE(m.Matches(L"Hello"));
1872 EXPECT_FALSE(m.Matches(L"hello"));
1873
1874 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1875 EXPECT_TRUE(m2.Matches(L""));
1876 EXPECT_FALSE(m2.Matches(L"Hello"));
1877}
1878
1879TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1880 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001881 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001882}
1883
1884// Tests that HasSubstr() works for matching wstring-typed values.
1885TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1886 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1887 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1888 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1889
1890 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1891 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1892 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1893}
1894
1895// Tests that HasSubstr() works for matching C-wide-string-typed values.
1896TEST(StdWideHasSubstrTest, WorksForCStrings) {
1897 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1898 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1899 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
Abseil Team4bb49ed2018-10-04 18:28:05 -04001900 EXPECT_FALSE(m1.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00001901
1902 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1903 EXPECT_TRUE(m2.Matches(L"I love food."));
1904 EXPECT_FALSE(m2.Matches(L"tofo"));
Abseil Team4bb49ed2018-10-04 18:28:05 -04001905 EXPECT_FALSE(m2.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00001906}
1907
1908// Tests that HasSubstr(s) describes itself properly.
1909TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1910 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1911 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1912}
1913
1914// Tests StartsWith(s).
1915
1916TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1917 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1918 EXPECT_TRUE(m1.Matches(L"Hi"));
1919 EXPECT_TRUE(m1.Matches(L""));
Abseil Team4bb49ed2018-10-04 18:28:05 -04001920 EXPECT_FALSE(m1.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00001921
1922 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1923 EXPECT_TRUE(m2.Matches(L"Hi"));
1924 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1925 EXPECT_TRUE(m2.Matches(L"High"));
1926 EXPECT_FALSE(m2.Matches(L"H"));
1927 EXPECT_FALSE(m2.Matches(L" Hi"));
1928}
1929
1930TEST(StdWideStartsWithTest, CanDescribeSelf) {
1931 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
1932 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1933}
1934
1935// Tests EndsWith(s).
1936
1937TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
1938 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1939 EXPECT_TRUE(m1.Matches(L"Hi"));
1940 EXPECT_TRUE(m1.Matches(L""));
Abseil Team4bb49ed2018-10-04 18:28:05 -04001941 EXPECT_FALSE(m1.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00001942
1943 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
1944 EXPECT_TRUE(m2.Matches(L"Hi"));
1945 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1946 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1947 EXPECT_FALSE(m2.Matches(L"i"));
1948 EXPECT_FALSE(m2.Matches(L"Hi "));
1949}
1950
1951TEST(StdWideEndsWithTest, CanDescribeSelf) {
1952 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
1953 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1954}
1955
1956#endif // GTEST_HAS_STD_WSTRING
1957
Abseil Team7d3b73c2018-10-09 14:50:26 -04001958typedef ::std::tuple<long, int> Tuple2; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00001959
1960// Tests that Eq() matches a 2-tuple where the first field == the
1961// second field.
1962TEST(Eq2Test, MatchesEqualArguments) {
1963 Matcher<const Tuple2&> m = Eq();
1964 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1965 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1966}
1967
1968// Tests that Eq() describes itself properly.
1969TEST(Eq2Test, CanDescribeSelf) {
1970 Matcher<const Tuple2&> m = Eq();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001971 EXPECT_EQ("are an equal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001972}
1973
1974// Tests that Ge() matches a 2-tuple where the first field >= the
1975// second field.
1976TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
1977 Matcher<const Tuple2&> m = Ge();
1978 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1979 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1980 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1981}
1982
1983// Tests that Ge() describes itself properly.
1984TEST(Ge2Test, CanDescribeSelf) {
1985 Matcher<const Tuple2&> m = Ge();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001986 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001987}
1988
1989// Tests that Gt() matches a 2-tuple where the first field > the
1990// second field.
1991TEST(Gt2Test, MatchesGreaterThanArguments) {
1992 Matcher<const Tuple2&> m = Gt();
1993 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1994 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1995 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1996}
1997
1998// Tests that Gt() describes itself properly.
1999TEST(Gt2Test, CanDescribeSelf) {
2000 Matcher<const Tuple2&> m = Gt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002001 EXPECT_EQ("are a pair where the first > the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002002}
2003
2004// Tests that Le() matches a 2-tuple where the first field <= the
2005// second field.
2006TEST(Le2Test, MatchesLessThanOrEqualArguments) {
2007 Matcher<const Tuple2&> m = Le();
2008 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2009 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2010 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
2011}
2012
2013// Tests that Le() describes itself properly.
2014TEST(Le2Test, CanDescribeSelf) {
2015 Matcher<const Tuple2&> m = Le();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002016 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002017}
2018
2019// Tests that Lt() matches a 2-tuple where the first field < the
2020// second field.
2021TEST(Lt2Test, MatchesLessThanArguments) {
2022 Matcher<const Tuple2&> m = Lt();
2023 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2024 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2025 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
2026}
2027
2028// Tests that Lt() describes itself properly.
2029TEST(Lt2Test, CanDescribeSelf) {
2030 Matcher<const Tuple2&> m = Lt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002031 EXPECT_EQ("are a pair where the first < the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002032}
2033
2034// Tests that Ne() matches a 2-tuple where the first field != the
2035// second field.
2036TEST(Ne2Test, MatchesUnequalArguments) {
2037 Matcher<const Tuple2&> m = Ne();
2038 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2039 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2040 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2041}
2042
2043// Tests that Ne() describes itself properly.
2044TEST(Ne2Test, CanDescribeSelf) {
2045 Matcher<const Tuple2&> m = Ne();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002046 EXPECT_EQ("are an unequal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002047}
2048
Abseil Team9acd0652019-01-12 15:41:51 -05002049TEST(PairMatchBaseTest, WorksWithMoveOnly) {
2050 using Pointers = std::tuple<std::unique_ptr<int>, std::unique_ptr<int>>;
2051 Matcher<Pointers> matcher = Eq();
2052 Pointers pointers;
2053 // Tested values don't matter; the point is that matcher does not copy the
2054 // matched values.
2055 EXPECT_TRUE(matcher.Matches(pointers));
2056}
2057
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002058// Tests that FloatEq() matches a 2-tuple where
2059// FloatEq(first field) matches the second field.
2060TEST(FloatEq2Test, MatchesEqualArguments) {
Abseil Team7d3b73c2018-10-09 14:50:26 -04002061 typedef ::std::tuple<float, float> Tpl;
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002062 Matcher<const Tpl&> m = FloatEq();
2063 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2064 EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f)));
2065 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2066}
2067
2068// Tests that FloatEq() describes itself properly.
2069TEST(FloatEq2Test, CanDescribeSelf) {
Abseil Team7d3b73c2018-10-09 14:50:26 -04002070 Matcher<const ::std::tuple<float, float>&> m = FloatEq();
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002071 EXPECT_EQ("are an almost-equal pair", Describe(m));
2072}
2073
2074// Tests that NanSensitiveFloatEq() matches a 2-tuple where
2075// NanSensitiveFloatEq(first field) matches the second field.
2076TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) {
Abseil Team7d3b73c2018-10-09 14:50:26 -04002077 typedef ::std::tuple<float, float> Tpl;
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002078 Matcher<const Tpl&> m = NanSensitiveFloatEq();
2079 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2080 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
2081 std::numeric_limits<float>::quiet_NaN())));
2082 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2083 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
2084 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
2085}
2086
2087// Tests that NanSensitiveFloatEq() describes itself properly.
2088TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) {
Abseil Team7d3b73c2018-10-09 14:50:26 -04002089 Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatEq();
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002090 EXPECT_EQ("are an almost-equal pair", Describe(m));
2091}
2092
2093// Tests that DoubleEq() matches a 2-tuple where
2094// DoubleEq(first field) matches the second field.
2095TEST(DoubleEq2Test, MatchesEqualArguments) {
Abseil Team7d3b73c2018-10-09 14:50:26 -04002096 typedef ::std::tuple<double, double> Tpl;
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002097 Matcher<const Tpl&> m = DoubleEq();
2098 EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
2099 EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1)));
2100 EXPECT_FALSE(m.Matches(Tpl(1.1, 1.0)));
2101}
2102
2103// Tests that DoubleEq() describes itself properly.
2104TEST(DoubleEq2Test, CanDescribeSelf) {
Abseil Team7d3b73c2018-10-09 14:50:26 -04002105 Matcher<const ::std::tuple<double, double>&> m = DoubleEq();
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002106 EXPECT_EQ("are an almost-equal pair", Describe(m));
2107}
2108
2109// Tests that NanSensitiveDoubleEq() matches a 2-tuple where
2110// NanSensitiveDoubleEq(first field) matches the second field.
2111TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) {
Abseil Team7d3b73c2018-10-09 14:50:26 -04002112 typedef ::std::tuple<double, double> Tpl;
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002113 Matcher<const Tpl&> m = NanSensitiveDoubleEq();
2114 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2115 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
2116 std::numeric_limits<double>::quiet_NaN())));
2117 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2118 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
2119 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
2120}
2121
2122// Tests that DoubleEq() describes itself properly.
2123TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) {
Abseil Team7d3b73c2018-10-09 14:50:26 -04002124 Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleEq();
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002125 EXPECT_EQ("are an almost-equal pair", Describe(m));
2126}
2127
2128// Tests that FloatEq() matches a 2-tuple where
2129// FloatNear(first field, max_abs_error) matches the second field.
2130TEST(FloatNear2Test, MatchesEqualArguments) {
Abseil Team7d3b73c2018-10-09 14:50:26 -04002131 typedef ::std::tuple<float, float> Tpl;
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002132 Matcher<const Tpl&> m = FloatNear(0.5f);
2133 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2134 EXPECT_TRUE(m.Matches(Tpl(1.3f, 1.0f)));
2135 EXPECT_FALSE(m.Matches(Tpl(1.8f, 1.0f)));
2136}
2137
2138// Tests that FloatNear() describes itself properly.
2139TEST(FloatNear2Test, CanDescribeSelf) {
Abseil Team7d3b73c2018-10-09 14:50:26 -04002140 Matcher<const ::std::tuple<float, float>&> m = FloatNear(0.5f);
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002141 EXPECT_EQ("are an almost-equal pair", Describe(m));
2142}
2143
2144// Tests that NanSensitiveFloatNear() matches a 2-tuple where
2145// NanSensitiveFloatNear(first field) matches the second field.
2146TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) {
Abseil Team7d3b73c2018-10-09 14:50:26 -04002147 typedef ::std::tuple<float, float> Tpl;
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002148 Matcher<const Tpl&> m = NanSensitiveFloatNear(0.5f);
2149 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2150 EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
2151 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
2152 std::numeric_limits<float>::quiet_NaN())));
2153 EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
2154 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
2155 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
2156}
2157
2158// Tests that NanSensitiveFloatNear() describes itself properly.
2159TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) {
Abseil Team7d3b73c2018-10-09 14:50:26 -04002160 Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatNear(0.5f);
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002161 EXPECT_EQ("are an almost-equal pair", Describe(m));
2162}
2163
2164// Tests that FloatEq() matches a 2-tuple where
2165// DoubleNear(first field, max_abs_error) matches the second field.
2166TEST(DoubleNear2Test, MatchesEqualArguments) {
Abseil Team7d3b73c2018-10-09 14:50:26 -04002167 typedef ::std::tuple<double, double> Tpl;
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002168 Matcher<const Tpl&> m = DoubleNear(0.5);
2169 EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
2170 EXPECT_TRUE(m.Matches(Tpl(1.3, 1.0)));
2171 EXPECT_FALSE(m.Matches(Tpl(1.8, 1.0)));
2172}
2173
2174// Tests that DoubleNear() describes itself properly.
2175TEST(DoubleNear2Test, CanDescribeSelf) {
Abseil Team7d3b73c2018-10-09 14:50:26 -04002176 Matcher<const ::std::tuple<double, double>&> m = DoubleNear(0.5);
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002177 EXPECT_EQ("are an almost-equal pair", Describe(m));
2178}
2179
2180// Tests that NanSensitiveDoubleNear() matches a 2-tuple where
2181// NanSensitiveDoubleNear(first field) matches the second field.
2182TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) {
Abseil Team7d3b73c2018-10-09 14:50:26 -04002183 typedef ::std::tuple<double, double> Tpl;
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002184 Matcher<const Tpl&> m = NanSensitiveDoubleNear(0.5f);
2185 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2186 EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
2187 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
2188 std::numeric_limits<double>::quiet_NaN())));
2189 EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
2190 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
2191 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
2192}
2193
2194// Tests that NanSensitiveDoubleNear() describes itself properly.
2195TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) {
Abseil Team7d3b73c2018-10-09 14:50:26 -04002196 Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleNear(0.5f);
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002197 EXPECT_EQ("are an almost-equal pair", Describe(m));
2198}
2199
shiqiane35fdd92008-12-10 05:08:54 +00002200// Tests that Not(m) matches any value that doesn't match m.
2201TEST(NotTest, NegatesMatcher) {
2202 Matcher<int> m;
2203 m = Not(Eq(2));
2204 EXPECT_TRUE(m.Matches(3));
2205 EXPECT_FALSE(m.Matches(2));
2206}
2207
2208// Tests that Not(m) describes itself properly.
2209TEST(NotTest, CanDescribeSelf) {
2210 Matcher<int> m = Not(Eq(5));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002211 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002212}
2213
zhanyong.wan18490652009-05-11 18:54:08 +00002214// Tests that monomorphic matchers are safely cast by the Not matcher.
2215TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2216 // greater_than_5 is a monomorphic matcher.
2217 Matcher<int> greater_than_5 = Gt(5);
2218
2219 Matcher<const int&> m = Not(greater_than_5);
2220 Matcher<int&> m2 = Not(greater_than_5);
2221 Matcher<int&> m3 = Not(m);
2222}
2223
zhanyong.wan02c15052010-06-09 19:21:30 +00002224// Helper to allow easy testing of AllOf matchers with num parameters.
2225void AllOfMatches(int num, const Matcher<int>& m) {
2226 SCOPED_TRACE(Describe(m));
2227 EXPECT_TRUE(m.Matches(0));
2228 for (int i = 1; i <= num; ++i) {
2229 EXPECT_FALSE(m.Matches(i));
2230 }
2231 EXPECT_TRUE(m.Matches(num + 1));
2232}
2233
shiqiane35fdd92008-12-10 05:08:54 +00002234// Tests that AllOf(m1, ..., mn) matches any value that matches all of
2235// the given matchers.
2236TEST(AllOfTest, MatchesWhenAllMatch) {
2237 Matcher<int> m;
2238 m = AllOf(Le(2), Ge(1));
2239 EXPECT_TRUE(m.Matches(1));
2240 EXPECT_TRUE(m.Matches(2));
2241 EXPECT_FALSE(m.Matches(0));
2242 EXPECT_FALSE(m.Matches(3));
2243
2244 m = AllOf(Gt(0), Ne(1), Ne(2));
2245 EXPECT_TRUE(m.Matches(3));
2246 EXPECT_FALSE(m.Matches(2));
2247 EXPECT_FALSE(m.Matches(1));
2248 EXPECT_FALSE(m.Matches(0));
2249
2250 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2251 EXPECT_TRUE(m.Matches(4));
2252 EXPECT_FALSE(m.Matches(3));
2253 EXPECT_FALSE(m.Matches(2));
2254 EXPECT_FALSE(m.Matches(1));
2255 EXPECT_FALSE(m.Matches(0));
2256
2257 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2258 EXPECT_TRUE(m.Matches(0));
2259 EXPECT_TRUE(m.Matches(1));
2260 EXPECT_FALSE(m.Matches(3));
zhanyong.wan02c15052010-06-09 19:21:30 +00002261
2262 // The following tests for varying number of sub-matchers. Due to the way
2263 // the sub-matchers are handled it is enough to test every sub-matcher once
2264 // with sub-matchers using the same matcher type. Varying matcher types are
2265 // checked for above.
2266 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2267 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2268 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2269 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2270 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2271 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2272 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2273 Ne(8)));
2274 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2275 Ne(8), Ne(9)));
2276 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2277 Ne(9), Ne(10)));
misterg4ac07de2018-10-08 11:56:57 -04002278 AllOfMatches(
2279 50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
2280 Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), Ne(16), Ne(17),
2281 Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), Ne(23), Ne(24), Ne(25),
2282 Ne(26), Ne(27), Ne(28), Ne(29), Ne(30), Ne(31), Ne(32), Ne(33),
2283 Ne(34), Ne(35), Ne(36), Ne(37), Ne(38), Ne(39), Ne(40), Ne(41),
2284 Ne(42), Ne(43), Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2285 Ne(50)));
shiqiane35fdd92008-12-10 05:08:54 +00002286}
2287
zhanyong.wan616180e2013-06-18 18:49:51 +00002288
shiqiane35fdd92008-12-10 05:08:54 +00002289// Tests that AllOf(m1, ..., mn) describes itself properly.
2290TEST(AllOfTest, CanDescribeSelf) {
2291 Matcher<int> m;
2292 m = AllOf(Le(2), Ge(1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002293 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002294
2295 m = AllOf(Gt(0), Ne(1), Ne(2));
mistergfab35922018-10-08 10:30:02 -04002296 std::string expected_descr1 =
2297 "(is > 0) and (isn't equal to 1) and (isn't equal to 2)";
2298 EXPECT_EQ(expected_descr1, Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002299
2300 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
mistergfab35922018-10-08 10:30:02 -04002301 std::string expected_descr2 =
2302 "(is > 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't equal "
2303 "to 3)";
2304 EXPECT_EQ(expected_descr2, Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002305
2306 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
mistergfab35922018-10-08 10:30:02 -04002307 std::string expected_descr3 =
2308 "(is >= 0) and (is < 10) and (isn't equal to 3) and (isn't equal to 5) "
2309 "and (isn't equal to 7)";
2310 EXPECT_EQ(expected_descr3, Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002311}
2312
2313// Tests that AllOf(m1, ..., mn) describes its negation properly.
2314TEST(AllOfTest, CanDescribeNegation) {
2315 Matcher<int> m;
2316 m = AllOf(Le(2), Ge(1));
mistergfab35922018-10-08 10:30:02 -04002317 std::string expected_descr4 = "(isn't <= 2) or (isn't >= 1)";
2318 EXPECT_EQ(expected_descr4, DescribeNegation(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002319
2320 m = AllOf(Gt(0), Ne(1), Ne(2));
mistergfab35922018-10-08 10:30:02 -04002321 std::string expected_descr5 =
2322 "(isn't > 0) or (is equal to 1) or (is equal to 2)";
2323 EXPECT_EQ(expected_descr5, DescribeNegation(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002324
2325 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
mistergfab35922018-10-08 10:30:02 -04002326 std::string expected_descr6 =
2327 "(isn't > 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)";
2328 EXPECT_EQ(expected_descr6, DescribeNegation(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002329
2330 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
mistergfab35922018-10-08 10:30:02 -04002331 std::string expected_desr7 =
2332 "(isn't >= 0) or (isn't < 10) or (is equal to 3) or (is equal to 5) or "
2333 "(is equal to 7)";
2334 EXPECT_EQ(expected_desr7, DescribeNegation(m));
2335
2336 m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
2337 Ne(10), Ne(11));
2338 AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2339 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)"));
2340 AllOfMatches(11, m);
shiqiane35fdd92008-12-10 05:08:54 +00002341}
2342
zhanyong.wan18490652009-05-11 18:54:08 +00002343// Tests that monomorphic matchers are safely cast by the AllOf matcher.
2344TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2345 // greater_than_5 and less_than_10 are monomorphic matchers.
2346 Matcher<int> greater_than_5 = Gt(5);
2347 Matcher<int> less_than_10 = Lt(10);
2348
2349 Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2350 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2351 Matcher<int&> m3 = AllOf(greater_than_5, m2);
2352
2353 // Tests that BothOf works when composing itself.
2354 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2355 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2356}
2357
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002358TEST(AllOfTest, ExplainsResult) {
2359 Matcher<int> m;
2360
2361 // Successful match. Both matchers need to explain. The second
2362 // matcher doesn't give an explanation, so only the first matcher's
2363 // explanation is printed.
2364 m = AllOf(GreaterThan(10), Lt(30));
2365 EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2366
2367 // Successful match. Both matchers need to explain.
2368 m = AllOf(GreaterThan(10), GreaterThan(20));
2369 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2370 Explain(m, 30));
2371
2372 // Successful match. All matchers need to explain. The second
2373 // matcher doesn't given an explanation.
2374 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2375 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2376 Explain(m, 25));
2377
2378 // Successful match. All matchers need to explain.
2379 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2380 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2381 "and which is 10 more than 30",
2382 Explain(m, 40));
2383
2384 // Failed match. The first matcher, which failed, needs to
2385 // explain.
2386 m = AllOf(GreaterThan(10), GreaterThan(20));
2387 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2388
2389 // Failed match. The second matcher, which failed, needs to
2390 // explain. Since it doesn't given an explanation, nothing is
2391 // printed.
2392 m = AllOf(GreaterThan(10), Lt(30));
2393 EXPECT_EQ("", Explain(m, 40));
2394
2395 // Failed match. The second matcher, which failed, needs to
2396 // explain.
2397 m = AllOf(GreaterThan(10), GreaterThan(20));
2398 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2399}
2400
zhanyong.wan02c15052010-06-09 19:21:30 +00002401// Helper to allow easy testing of AnyOf matchers with num parameters.
Gennadiy Civil3530ab92018-07-18 11:51:14 -04002402static void AnyOfMatches(int num, const Matcher<int>& m) {
zhanyong.wan02c15052010-06-09 19:21:30 +00002403 SCOPED_TRACE(Describe(m));
2404 EXPECT_FALSE(m.Matches(0));
2405 for (int i = 1; i <= num; ++i) {
2406 EXPECT_TRUE(m.Matches(i));
2407 }
2408 EXPECT_FALSE(m.Matches(num + 1));
2409}
2410
Gennadiy Civil3530ab92018-07-18 11:51:14 -04002411static void AnyOfStringMatches(int num, const Matcher<std::string>& m) {
2412 SCOPED_TRACE(Describe(m));
2413 EXPECT_FALSE(m.Matches(std::to_string(0)));
2414
2415 for (int i = 1; i <= num; ++i) {
2416 EXPECT_TRUE(m.Matches(std::to_string(i)));
2417 }
2418 EXPECT_FALSE(m.Matches(std::to_string(num + 1)));
2419}
Gennadiy Civil3530ab92018-07-18 11:51:14 -04002420
shiqiane35fdd92008-12-10 05:08:54 +00002421// Tests that AnyOf(m1, ..., mn) matches any value that matches at
2422// least one of the given matchers.
2423TEST(AnyOfTest, MatchesWhenAnyMatches) {
2424 Matcher<int> m;
2425 m = AnyOf(Le(1), Ge(3));
2426 EXPECT_TRUE(m.Matches(1));
2427 EXPECT_TRUE(m.Matches(4));
2428 EXPECT_FALSE(m.Matches(2));
2429
2430 m = AnyOf(Lt(0), Eq(1), Eq(2));
2431 EXPECT_TRUE(m.Matches(-1));
2432 EXPECT_TRUE(m.Matches(1));
2433 EXPECT_TRUE(m.Matches(2));
2434 EXPECT_FALSE(m.Matches(0));
2435
2436 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2437 EXPECT_TRUE(m.Matches(-1));
2438 EXPECT_TRUE(m.Matches(1));
2439 EXPECT_TRUE(m.Matches(2));
2440 EXPECT_TRUE(m.Matches(3));
2441 EXPECT_FALSE(m.Matches(0));
2442
2443 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2444 EXPECT_TRUE(m.Matches(0));
2445 EXPECT_TRUE(m.Matches(11));
2446 EXPECT_TRUE(m.Matches(3));
2447 EXPECT_FALSE(m.Matches(2));
zhanyong.wan02c15052010-06-09 19:21:30 +00002448
2449 // The following tests for varying number of sub-matchers. Due to the way
2450 // the sub-matchers are handled it is enough to test every sub-matcher once
2451 // with sub-matchers using the same matcher type. Varying matcher types are
2452 // checked for above.
2453 AnyOfMatches(2, AnyOf(1, 2));
2454 AnyOfMatches(3, AnyOf(1, 2, 3));
2455 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2456 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2457 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2458 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2459 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2460 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2461 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
shiqiane35fdd92008-12-10 05:08:54 +00002462}
2463
zhanyong.wan616180e2013-06-18 18:49:51 +00002464// Tests the variadic version of the AnyOfMatcher.
2465TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2466 // Also make sure AnyOf is defined in the right namespace and does not depend
2467 // on ADL.
2468 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2469
Gennadiy Civilb5391672018-04-25 13:10:41 -04002470 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)"));
zhanyong.wan616180e2013-06-18 18:49:51 +00002471 AnyOfMatches(11, m);
2472 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2473 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2474 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2475 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2476 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
Gennadiy Civil3530ab92018-07-18 11:51:14 -04002477 AnyOfStringMatches(
2478 50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
2479 "13", "14", "15", "16", "17", "18", "19", "20", "21", "22",
2480 "23", "24", "25", "26", "27", "28", "29", "30", "31", "32",
2481 "33", "34", "35", "36", "37", "38", "39", "40", "41", "42",
2482 "43", "44", "45", "46", "47", "48", "49", "50"));
zhanyong.wan616180e2013-06-18 18:49:51 +00002483}
2484
Gennadiy Civildff32af2018-04-17 16:12:04 -04002485// Tests the variadic version of the ElementsAreMatcher
2486TEST(ElementsAreTest, HugeMatcher) {
Gennadiy Civil5dccf6b2018-04-17 16:22:35 -04002487 vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
Gennadiy Civildff32af2018-04-17 16:12:04 -04002488
2489 EXPECT_THAT(test_vector,
2490 ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7),
Gennadiy Civil5dccf6b2018-04-17 16:22:35 -04002491 Eq(8), Eq(9), Eq(10), Gt(1), Eq(12)));
Gennadiy Civildff32af2018-04-17 16:12:04 -04002492}
2493
2494// Tests the variadic version of the UnorderedElementsAreMatcher
Gennadiy Civil4707c0f2018-04-18 10:36:12 -04002495TEST(ElementsAreTest, HugeMatcherStr) {
Abseil Teamd9825432019-04-01 12:06:49 -04002496 vector<std::string> test_vector{
Gennadiy Civil4707c0f2018-04-18 10:36:12 -04002497 "literal_string", "", "", "", "", "", "", "", "", "", "", ""};
2498
2499 EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _,
2500 _, _, _, _, _, _));
2501}
2502
2503// Tests the variadic version of the UnorderedElementsAreMatcher
Gennadiy Civildff32af2018-04-17 16:12:04 -04002504TEST(ElementsAreTest, HugeMatcherUnordered) {
Gennadiy Civil80d6e262018-04-17 19:32:15 -04002505 vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};
Gennadiy Civildff32af2018-04-17 16:12:04 -04002506
Gennadiy Civil5dccf6b2018-04-17 16:22:35 -04002507 EXPECT_THAT(test_vector, UnorderedElementsAre(
Gennadiy Civil80d6e262018-04-17 19:32:15 -04002508 Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7),
2509 Eq(3), Eq(9), Eq(12), Eq(11), Ne(122)));
Gennadiy Civildff32af2018-04-17 16:12:04 -04002510}
2511
zhanyong.wan616180e2013-06-18 18:49:51 +00002512
shiqiane35fdd92008-12-10 05:08:54 +00002513// Tests that AnyOf(m1, ..., mn) describes itself properly.
2514TEST(AnyOfTest, CanDescribeSelf) {
2515 Matcher<int> m;
2516 m = AnyOf(Le(1), Ge(3));
misterg78761b52018-10-09 16:26:28 -04002517
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002518 EXPECT_EQ("(is <= 1) or (is >= 3)",
shiqiane35fdd92008-12-10 05:08:54 +00002519 Describe(m));
2520
2521 m = AnyOf(Lt(0), Eq(1), Eq(2));
misterg78761b52018-10-09 16:26:28 -04002522 EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2)", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002523
2524 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
misterg78761b52018-10-09 16:26:28 -04002525 EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)",
shiqiane35fdd92008-12-10 05:08:54 +00002526 Describe(m));
2527
2528 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
misterg78761b52018-10-09 16:26:28 -04002529 EXPECT_EQ(
2530 "(is <= 0) or (is > 10) or (is equal to 3) or (is equal to 5) or (is "
2531 "equal to 7)",
2532 Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002533}
2534
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002535// Tests that AnyOf(m1, ..., mn) describes its negation properly.
2536TEST(AnyOfTest, CanDescribeNegation) {
2537 Matcher<int> m;
2538 m = AnyOf(Le(1), Ge(3));
2539 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2540 DescribeNegation(m));
2541
2542 m = AnyOf(Lt(0), Eq(1), Eq(2));
misterg78761b52018-10-09 16:26:28 -04002543 EXPECT_EQ("(isn't < 0) and (isn't equal to 1) and (isn't equal to 2)",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002544 DescribeNegation(m));
2545
2546 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
misterg78761b52018-10-09 16:26:28 -04002547 EXPECT_EQ(
2548 "(isn't < 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't "
2549 "equal to 3)",
2550 DescribeNegation(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002551
2552 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
misterg78761b52018-10-09 16:26:28 -04002553 EXPECT_EQ(
2554 "(isn't <= 0) and (isn't > 10) and (isn't equal to 3) and (isn't equal "
2555 "to 5) and (isn't equal to 7)",
2556 DescribeNegation(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002557}
2558
zhanyong.wan18490652009-05-11 18:54:08 +00002559// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2560TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2561 // greater_than_5 and less_than_10 are monomorphic matchers.
2562 Matcher<int> greater_than_5 = Gt(5);
2563 Matcher<int> less_than_10 = Lt(10);
2564
2565 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2566 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2567 Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2568
2569 // Tests that EitherOf works when composing itself.
2570 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2571 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2572}
2573
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002574TEST(AnyOfTest, ExplainsResult) {
2575 Matcher<int> m;
2576
2577 // Failed match. Both matchers need to explain. The second
2578 // matcher doesn't give an explanation, so only the first matcher's
2579 // explanation is printed.
2580 m = AnyOf(GreaterThan(10), Lt(0));
2581 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2582
2583 // Failed match. Both matchers need to explain.
2584 m = AnyOf(GreaterThan(10), GreaterThan(20));
2585 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2586 Explain(m, 5));
2587
2588 // Failed match. All matchers need to explain. The second
2589 // matcher doesn't given an explanation.
2590 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2591 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2592 Explain(m, 5));
2593
2594 // Failed match. All matchers need to explain.
2595 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2596 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2597 "and which is 25 less than 30",
2598 Explain(m, 5));
2599
2600 // Successful match. The first matcher, which succeeded, needs to
2601 // explain.
2602 m = AnyOf(GreaterThan(10), GreaterThan(20));
2603 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2604
2605 // Successful match. The second matcher, which succeeded, needs to
2606 // explain. Since it doesn't given an explanation, nothing is
2607 // printed.
2608 m = AnyOf(GreaterThan(10), Lt(30));
2609 EXPECT_EQ("", Explain(m, 0));
2610
2611 // Successful match. The second matcher, which succeeded, needs to
2612 // explain.
2613 m = AnyOf(GreaterThan(30), GreaterThan(20));
2614 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2615}
2616
shiqiane35fdd92008-12-10 05:08:54 +00002617// The following predicate function and predicate functor are for
2618// testing the Truly(predicate) matcher.
2619
2620// Returns non-zero if the input is positive. Note that the return
2621// type of this function is not bool. It's OK as Truly() accepts any
2622// unary function or functor whose return type can be implicitly
2623// converted to bool.
2624int IsPositive(double x) {
2625 return x > 0 ? 1 : 0;
2626}
2627
2628// This functor returns true if the input is greater than the given
2629// number.
2630class IsGreaterThan {
2631 public:
2632 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2633
2634 bool operator()(int n) const { return n > threshold_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002635
shiqiane35fdd92008-12-10 05:08:54 +00002636 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002637 int threshold_;
shiqiane35fdd92008-12-10 05:08:54 +00002638};
2639
2640// For testing Truly().
2641const int foo = 0;
2642
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +02002643// This predicate returns true if the argument references foo and has
shiqiane35fdd92008-12-10 05:08:54 +00002644// a zero value.
2645bool ReferencesFooAndIsZero(const int& n) {
2646 return (&n == &foo) && (n == 0);
2647}
2648
2649// Tests that Truly(predicate) matches what satisfies the given
2650// predicate.
2651TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2652 Matcher<double> m = Truly(IsPositive);
2653 EXPECT_TRUE(m.Matches(2.0));
2654 EXPECT_FALSE(m.Matches(-1.5));
2655}
2656
2657// Tests that Truly(predicate_functor) works too.
2658TEST(TrulyTest, CanBeUsedWithFunctor) {
2659 Matcher<int> m = Truly(IsGreaterThan(5));
2660 EXPECT_TRUE(m.Matches(6));
2661 EXPECT_FALSE(m.Matches(4));
2662}
2663
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00002664// A class that can be implicitly converted to bool.
2665class ConvertibleToBool {
2666 public:
2667 explicit ConvertibleToBool(int number) : number_(number) {}
2668 operator bool() const { return number_ != 0; }
2669
2670 private:
2671 int number_;
2672};
2673
2674ConvertibleToBool IsNotZero(int number) {
2675 return ConvertibleToBool(number);
2676}
2677
2678// Tests that the predicate used in Truly() may return a class that's
2679// implicitly convertible to bool, even when the class has no
2680// operator!().
2681TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2682 Matcher<int> m = Truly(IsNotZero);
2683 EXPECT_TRUE(m.Matches(1));
2684 EXPECT_FALSE(m.Matches(0));
2685}
2686
shiqiane35fdd92008-12-10 05:08:54 +00002687// Tests that Truly(predicate) can describe itself properly.
2688TEST(TrulyTest, CanDescribeSelf) {
2689 Matcher<double> m = Truly(IsPositive);
2690 EXPECT_EQ("satisfies the given predicate",
2691 Describe(m));
2692}
2693
2694// Tests that Truly(predicate) works when the matcher takes its
2695// argument by reference.
2696TEST(TrulyTest, WorksForByRefArguments) {
2697 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2698 EXPECT_TRUE(m.Matches(foo));
2699 int n = 0;
2700 EXPECT_FALSE(m.Matches(n));
2701}
2702
2703// Tests that Matches(m) is a predicate satisfied by whatever that
2704// matches matcher m.
2705TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2706 EXPECT_TRUE(Matches(Ge(0))(1));
2707 EXPECT_FALSE(Matches(Eq('a'))('b'));
2708}
2709
2710// Tests that Matches(m) works when the matcher takes its argument by
2711// reference.
2712TEST(MatchesTest, WorksOnByRefArguments) {
2713 int m = 0, n = 0;
2714 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2715 EXPECT_FALSE(Matches(Ref(m))(n));
2716}
2717
2718// Tests that a Matcher on non-reference type can be used in
2719// Matches().
2720TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
2721 Matcher<int> eq5 = Eq(5);
2722 EXPECT_TRUE(Matches(eq5)(5));
2723 EXPECT_FALSE(Matches(eq5)(2));
2724}
2725
zhanyong.wanb8243162009-06-04 05:48:20 +00002726// Tests Value(value, matcher). Since Value() is a simple wrapper for
2727// Matches(), which has been tested already, we don't spend a lot of
2728// effort on testing Value().
2729TEST(ValueTest, WorksWithPolymorphicMatcher) {
2730 EXPECT_TRUE(Value("hi", StartsWith("h")));
2731 EXPECT_FALSE(Value(5, Gt(10)));
2732}
2733
2734TEST(ValueTest, WorksWithMonomorphicMatcher) {
2735 const Matcher<int> is_zero = Eq(0);
2736 EXPECT_TRUE(Value(0, is_zero));
2737 EXPECT_FALSE(Value('a', is_zero));
2738
2739 int n = 0;
2740 const Matcher<const int&> ref_n = Ref(n);
2741 EXPECT_TRUE(Value(n, ref_n));
2742 EXPECT_FALSE(Value(1, ref_n));
2743}
2744
zhanyong.wana862f1d2010-03-15 21:23:04 +00002745TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002746 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002747 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002748 EXPECT_EQ("% 2 == 0", listener1.str());
2749
2750 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002751 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002752 EXPECT_EQ("", listener2.str());
2753}
2754
zhanyong.wana862f1d2010-03-15 21:23:04 +00002755TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002756 const Matcher<int> is_even = PolymorphicIsEven();
2757 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002758 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002759 EXPECT_EQ("% 2 == 0", listener1.str());
2760
2761 const Matcher<const double&> is_zero = Eq(0);
2762 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002763 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002764 EXPECT_EQ("", listener2.str());
2765}
2766
zhanyong.wana862f1d2010-03-15 21:23:04 +00002767MATCHER_P(Really, inner_matcher, "") {
2768 return ExplainMatchResult(inner_matcher, arg, result_listener);
2769}
2770
2771TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
2772 EXPECT_THAT(0, Really(Eq(0)));
2773}
2774
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002775TEST(DescribeMatcherTest, WorksWithValue) {
2776 EXPECT_EQ("is equal to 42", DescribeMatcher<int>(42));
2777 EXPECT_EQ("isn't equal to 42", DescribeMatcher<int>(42, true));
2778}
2779
2780TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) {
2781 const Matcher<int> monomorphic = Le(0);
2782 EXPECT_EQ("is <= 0", DescribeMatcher<int>(monomorphic));
2783 EXPECT_EQ("isn't <= 0", DescribeMatcher<int>(monomorphic, true));
2784}
2785
2786TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) {
2787 EXPECT_EQ("is even", DescribeMatcher<int>(PolymorphicIsEven()));
2788 EXPECT_EQ("is odd", DescribeMatcher<int>(PolymorphicIsEven(), true));
2789}
2790
zhanyong.wanbf550852009-06-09 06:09:53 +00002791TEST(AllArgsTest, WorksForTuple) {
Abseil Team7d3b73c2018-10-09 14:50:26 -04002792 EXPECT_THAT(std::make_tuple(1, 2L), AllArgs(Lt()));
2793 EXPECT_THAT(std::make_tuple(2L, 1), Not(AllArgs(Lt())));
zhanyong.wanbf550852009-06-09 06:09:53 +00002794}
2795
2796TEST(AllArgsTest, WorksForNonTuple) {
2797 EXPECT_THAT(42, AllArgs(Gt(0)));
2798 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
2799}
2800
2801class AllArgsHelper {
2802 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002803 AllArgsHelper() {}
2804
zhanyong.wanbf550852009-06-09 06:09:53 +00002805 MOCK_METHOD2(Helper, int(char x, int y));
zhanyong.wan32de5f52009-12-23 00:13:23 +00002806
2807 private:
2808 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
zhanyong.wanbf550852009-06-09 06:09:53 +00002809};
2810
2811TEST(AllArgsTest, WorksInWithClause) {
2812 AllArgsHelper helper;
2813 ON_CALL(helper, Helper(_, _))
2814 .With(AllArgs(Lt()))
2815 .WillByDefault(Return(1));
2816 EXPECT_CALL(helper, Helper(_, _));
2817 EXPECT_CALL(helper, Helper(_, _))
2818 .With(AllArgs(Gt()))
2819 .WillOnce(Return(2));
2820
2821 EXPECT_EQ(1, helper.Helper('\1', 2));
2822 EXPECT_EQ(2, helper.Helper('a', 1));
2823}
2824
Gennadiy Civilb5391672018-04-25 13:10:41 -04002825class OptionalMatchersHelper {
2826 public:
2827 OptionalMatchersHelper() {}
2828
2829 MOCK_METHOD0(NoArgs, int());
2830
2831 MOCK_METHOD1(OneArg, int(int y));
2832
2833 MOCK_METHOD2(TwoArgs, int(char x, int y));
2834
2835 MOCK_METHOD1(Overloaded, int(char x));
2836 MOCK_METHOD2(Overloaded, int(char x, int y));
2837
2838 private:
2839 GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper);
2840};
2841
2842TEST(AllArgsTest, WorksWithoutMatchers) {
2843 OptionalMatchersHelper helper;
2844
2845 ON_CALL(helper, NoArgs).WillByDefault(Return(10));
2846 ON_CALL(helper, OneArg).WillByDefault(Return(20));
2847 ON_CALL(helper, TwoArgs).WillByDefault(Return(30));
2848
2849 EXPECT_EQ(10, helper.NoArgs());
2850 EXPECT_EQ(20, helper.OneArg(1));
2851 EXPECT_EQ(30, helper.TwoArgs('\1', 2));
2852
2853 EXPECT_CALL(helper, NoArgs).Times(1);
2854 EXPECT_CALL(helper, OneArg).WillOnce(Return(100));
2855 EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200));
2856 EXPECT_CALL(helper, TwoArgs).Times(0);
2857
2858 EXPECT_EQ(10, helper.NoArgs());
2859 EXPECT_EQ(100, helper.OneArg(1));
2860 EXPECT_EQ(200, helper.OneArg(17));
2861}
2862
shiqiane35fdd92008-12-10 05:08:54 +00002863// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2864// matches the matcher.
2865TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
2866 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
2867 ASSERT_THAT("Foo", EndsWith("oo"));
2868 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
2869 EXPECT_THAT("Hello", StartsWith("Hell"));
2870}
2871
2872// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2873// doesn't match the matcher.
2874TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
2875 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
2876 // which cannot reference auto variables.
zhanyong.wan736baa82010-09-27 17:44:16 +00002877 static unsigned short n; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00002878 n = 5;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002879
2880 // VC++ prior to version 8.0 SP1 has a bug where it will not see any
2881 // functions declared in the namespace scope from within nested classes.
2882 // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
2883 // namespace-level functions invoked inside them need to be explicitly
2884 // resolved.
2885 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
shiqiane35fdd92008-12-10 05:08:54 +00002886 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002887 "Expected: is > 10\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002888 " Actual: 5" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002889 n = 0;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002890 EXPECT_NONFATAL_FAILURE(
2891 EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
2892 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002893 "Expected: (is <= 7) and (is >= 5)\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002894 " Actual: 0" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002895}
2896
2897// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
2898// has a reference type.
2899TEST(MatcherAssertionTest, WorksForByRefArguments) {
2900 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
2901 // reference auto variables.
2902 static int n;
2903 n = 0;
2904 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002905 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
shiqiane35fdd92008-12-10 05:08:54 +00002906 "Value of: n\n"
2907 "Expected: does not reference the variable @");
2908 // Tests the "Actual" part.
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002909 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
zhanyong.wan736baa82010-09-27 17:44:16 +00002910 "Actual: 0" + OfType("int") + ", which is located @");
shiqiane35fdd92008-12-10 05:08:54 +00002911}
2912
2913// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
2914// monomorphic.
2915TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
2916 Matcher<const char*> starts_with_he = StartsWith("he");
2917 ASSERT_THAT("hello", starts_with_he);
2918
Nico Weber09fd5b32017-05-15 17:07:03 -04002919 Matcher<const std::string&> ends_with_ok = EndsWith("ok");
shiqiane35fdd92008-12-10 05:08:54 +00002920 ASSERT_THAT("book", ends_with_ok);
Nico Weber09fd5b32017-05-15 17:07:03 -04002921 const std::string bad = "bad";
zhanyong.wan736baa82010-09-27 17:44:16 +00002922 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
2923 "Value of: bad\n"
2924 "Expected: ends with \"ok\"\n"
2925 " Actual: \"bad\"");
shiqiane35fdd92008-12-10 05:08:54 +00002926 Matcher<int> is_greater_than_5 = Gt(5);
2927 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
2928 "Value of: 5\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002929 "Expected: is > 5\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002930 " Actual: 5" + OfType("int"));
shiqiane35fdd92008-12-10 05:08:54 +00002931}
2932
2933// Tests floating-point matchers.
2934template <typename RawType>
2935class FloatingPointTest : public testing::Test {
2936 protected:
zhanyong.wan35877b72013-09-18 17:51:08 +00002937 typedef testing::internal::FloatingPoint<RawType> Floating;
shiqiane35fdd92008-12-10 05:08:54 +00002938 typedef typename Floating::Bits Bits;
2939
zhanyong.wan35877b72013-09-18 17:51:08 +00002940 FloatingPointTest()
2941 : max_ulps_(Floating::kMaxUlps),
2942 zero_bits_(Floating(0).bits()),
2943 one_bits_(Floating(1).bits()),
2944 infinity_bits_(Floating(Floating::Infinity()).bits()),
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002945 close_to_positive_zero_(
2946 Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
2947 close_to_negative_zero_(
2948 -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
2949 further_from_negative_zero_(-Floating::ReinterpretBits(
Mark Mentovaicfe466a2015-11-11 18:26:35 -05002950 zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002951 close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
2952 further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
zhanyong.wan35877b72013-09-18 17:51:08 +00002953 infinity_(Floating::Infinity()),
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002954 close_to_infinity_(
2955 Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
2956 further_from_infinity_(
2957 Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
zhanyong.wan35877b72013-09-18 17:51:08 +00002958 max_(Floating::Max()),
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04002959 nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
2960 nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
shiqiane35fdd92008-12-10 05:08:54 +00002961 }
2962
2963 void TestSize() {
2964 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2965 }
2966
2967 // A battery of tests for FloatingEqMatcher::Matches.
2968 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2969 void TestMatches(
2970 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
2971 Matcher<RawType> m1 = matcher_maker(0.0);
2972 EXPECT_TRUE(m1.Matches(-0.0));
2973 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
2974 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
2975 EXPECT_FALSE(m1.Matches(1.0));
2976
2977 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
2978 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
2979
2980 Matcher<RawType> m3 = matcher_maker(1.0);
2981 EXPECT_TRUE(m3.Matches(close_to_one_));
2982 EXPECT_FALSE(m3.Matches(further_from_one_));
2983
2984 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
2985 EXPECT_FALSE(m3.Matches(0.0));
2986
2987 Matcher<RawType> m4 = matcher_maker(-infinity_);
2988 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
2989
2990 Matcher<RawType> m5 = matcher_maker(infinity_);
2991 EXPECT_TRUE(m5.Matches(close_to_infinity_));
2992
2993 // This is interesting as the representations of infinity_ and nan1_
2994 // are only 1 DLP apart.
2995 EXPECT_FALSE(m5.Matches(nan1_));
2996
2997 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2998 // some cases.
2999 Matcher<const RawType&> m6 = matcher_maker(0.0);
3000 EXPECT_TRUE(m6.Matches(-0.0));
3001 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
3002 EXPECT_FALSE(m6.Matches(1.0));
3003
3004 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
3005 // cases.
3006 Matcher<RawType&> m7 = matcher_maker(0.0);
3007 RawType x = 0.0;
3008 EXPECT_TRUE(m7.Matches(x));
3009 x = 0.01f;
3010 EXPECT_FALSE(m7.Matches(x));
3011 }
3012
3013 // Pre-calculated numbers to be used by the tests.
3014
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003015 const Bits max_ulps_;
shiqiane35fdd92008-12-10 05:08:54 +00003016
zhanyong.wan35877b72013-09-18 17:51:08 +00003017 const Bits zero_bits_; // The bits that represent 0.0.
3018 const Bits one_bits_; // The bits that represent 1.0.
3019 const Bits infinity_bits_; // The bits that represent +infinity.
shiqiane35fdd92008-12-10 05:08:54 +00003020
zhanyong.wan35877b72013-09-18 17:51:08 +00003021 // Some numbers close to 0.0.
3022 const RawType close_to_positive_zero_;
3023 const RawType close_to_negative_zero_;
3024 const RawType further_from_negative_zero_;
shiqiane35fdd92008-12-10 05:08:54 +00003025
zhanyong.wan35877b72013-09-18 17:51:08 +00003026 // Some numbers close to 1.0.
3027 const RawType close_to_one_;
3028 const RawType further_from_one_;
3029
3030 // Some numbers close to +infinity.
3031 const RawType infinity_;
3032 const RawType close_to_infinity_;
3033 const RawType further_from_infinity_;
3034
3035 // Maximum representable value that's not infinity.
3036 const RawType max_;
3037
3038 // Some NaNs.
3039 const RawType nan1_;
3040 const RawType nan2_;
shiqiane35fdd92008-12-10 05:08:54 +00003041};
3042
zhanyong.wan616180e2013-06-18 18:49:51 +00003043// Tests floating-point matchers with fixed epsilons.
3044template <typename RawType>
3045class FloatingPointNearTest : public FloatingPointTest<RawType> {
3046 protected:
3047 typedef FloatingPointTest<RawType> ParentType;
3048
3049 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
3050 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
3051 void TestNearMatches(
3052 testing::internal::FloatingEqMatcher<RawType>
3053 (*matcher_maker)(RawType, RawType)) {
3054 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
3055 EXPECT_TRUE(m1.Matches(0.0));
3056 EXPECT_TRUE(m1.Matches(-0.0));
3057 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
3058 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
3059 EXPECT_FALSE(m1.Matches(1.0));
3060
3061 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
3062 EXPECT_TRUE(m2.Matches(0.0));
3063 EXPECT_TRUE(m2.Matches(-0.0));
3064 EXPECT_TRUE(m2.Matches(1.0));
3065 EXPECT_TRUE(m2.Matches(-1.0));
3066 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
3067 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
3068
3069 // Check that inf matches inf, regardless of the of the specified max
3070 // absolute error.
3071 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
3072 EXPECT_TRUE(m3.Matches(ParentType::infinity_));
3073 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
3074 EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
3075
3076 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
3077 EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
3078 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
3079 EXPECT_FALSE(m4.Matches(ParentType::infinity_));
3080
3081 // Test various overflow scenarios.
zhanyong.wan35877b72013-09-18 17:51:08 +00003082 Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
3083 EXPECT_TRUE(m5.Matches(ParentType::max_));
3084 EXPECT_FALSE(m5.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00003085
zhanyong.wan35877b72013-09-18 17:51:08 +00003086 Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
3087 EXPECT_FALSE(m6.Matches(ParentType::max_));
3088 EXPECT_TRUE(m6.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00003089
zhanyong.wan35877b72013-09-18 17:51:08 +00003090 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
3091 EXPECT_TRUE(m7.Matches(ParentType::max_));
3092 EXPECT_FALSE(m7.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00003093
zhanyong.wan35877b72013-09-18 17:51:08 +00003094 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
3095 EXPECT_FALSE(m8.Matches(ParentType::max_));
3096 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00003097
3098 // The difference between max() and -max() normally overflows to infinity,
3099 // but it should still match if the max_abs_error is also infinity.
3100 Matcher<RawType> m9 = matcher_maker(
zhanyong.wan35877b72013-09-18 17:51:08 +00003101 ParentType::max_, ParentType::infinity_);
3102 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00003103
3104 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
3105 // some cases.
3106 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
3107 EXPECT_TRUE(m10.Matches(-0.0));
3108 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
3109 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
3110
3111 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
3112 // cases.
3113 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
3114 RawType x = 0.0;
3115 EXPECT_TRUE(m11.Matches(x));
3116 x = 1.0f;
3117 EXPECT_TRUE(m11.Matches(x));
3118 x = -1.0f;
3119 EXPECT_TRUE(m11.Matches(x));
3120 x = 1.1f;
3121 EXPECT_FALSE(m11.Matches(x));
3122 x = -1.1f;
3123 EXPECT_FALSE(m11.Matches(x));
3124 }
3125};
3126
shiqiane35fdd92008-12-10 05:08:54 +00003127// Instantiate FloatingPointTest for testing floats.
3128typedef FloatingPointTest<float> FloatTest;
3129
3130TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
3131 TestMatches(&FloatEq);
3132}
3133
3134TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
3135 TestMatches(&NanSensitiveFloatEq);
3136}
3137
3138TEST_F(FloatTest, FloatEqCannotMatchNaN) {
3139 // FloatEq never matches NaN.
3140 Matcher<float> m = FloatEq(nan1_);
3141 EXPECT_FALSE(m.Matches(nan1_));
3142 EXPECT_FALSE(m.Matches(nan2_));
3143 EXPECT_FALSE(m.Matches(1.0));
3144}
3145
3146TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
3147 // NanSensitiveFloatEq will match NaN.
3148 Matcher<float> m = NanSensitiveFloatEq(nan1_);
3149 EXPECT_TRUE(m.Matches(nan1_));
3150 EXPECT_TRUE(m.Matches(nan2_));
3151 EXPECT_FALSE(m.Matches(1.0));
3152}
3153
3154TEST_F(FloatTest, FloatEqCanDescribeSelf) {
3155 Matcher<float> m1 = FloatEq(2.0f);
3156 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003157 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003158
3159 Matcher<float> m2 = FloatEq(0.5f);
3160 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003161 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003162
3163 Matcher<float> m3 = FloatEq(nan1_);
3164 EXPECT_EQ("never matches", Describe(m3));
3165 EXPECT_EQ("is anything", DescribeNegation(m3));
3166}
3167
3168TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
3169 Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
3170 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003171 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003172
3173 Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
3174 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003175 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003176
3177 Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
3178 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003179 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00003180}
3181
zhanyong.wan616180e2013-06-18 18:49:51 +00003182// Instantiate FloatingPointTest for testing floats with a user-specified
3183// max absolute error.
3184typedef FloatingPointNearTest<float> FloatNearTest;
3185
3186TEST_F(FloatNearTest, FloatNearMatches) {
3187 TestNearMatches(&FloatNear);
3188}
3189
3190TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
3191 TestNearMatches(&NanSensitiveFloatNear);
3192}
3193
3194TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
3195 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
3196 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3197 EXPECT_EQ(
3198 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3199
3200 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
3201 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3202 EXPECT_EQ(
3203 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3204
3205 Matcher<float> m3 = FloatNear(nan1_, 0.0);
3206 EXPECT_EQ("never matches", Describe(m3));
3207 EXPECT_EQ("is anything", DescribeNegation(m3));
3208}
3209
3210TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
3211 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
3212 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3213 EXPECT_EQ(
3214 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3215
3216 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
3217 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3218 EXPECT_EQ(
3219 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3220
3221 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
3222 EXPECT_EQ("is NaN", Describe(m3));
3223 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3224}
3225
3226TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
3227 // FloatNear never matches NaN.
3228 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
3229 EXPECT_FALSE(m.Matches(nan1_));
3230 EXPECT_FALSE(m.Matches(nan2_));
3231 EXPECT_FALSE(m.Matches(1.0));
3232}
3233
3234TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
3235 // NanSensitiveFloatNear will match NaN.
3236 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
3237 EXPECT_TRUE(m.Matches(nan1_));
3238 EXPECT_TRUE(m.Matches(nan2_));
3239 EXPECT_FALSE(m.Matches(1.0));
3240}
3241
shiqiane35fdd92008-12-10 05:08:54 +00003242// Instantiate FloatingPointTest for testing doubles.
3243typedef FloatingPointTest<double> DoubleTest;
3244
3245TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
3246 TestMatches(&DoubleEq);
3247}
3248
3249TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
3250 TestMatches(&NanSensitiveDoubleEq);
3251}
3252
3253TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
3254 // DoubleEq never matches NaN.
3255 Matcher<double> m = DoubleEq(nan1_);
3256 EXPECT_FALSE(m.Matches(nan1_));
3257 EXPECT_FALSE(m.Matches(nan2_));
3258 EXPECT_FALSE(m.Matches(1.0));
3259}
3260
3261TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3262 // NanSensitiveDoubleEq will match NaN.
3263 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
3264 EXPECT_TRUE(m.Matches(nan1_));
3265 EXPECT_TRUE(m.Matches(nan2_));
3266 EXPECT_FALSE(m.Matches(1.0));
3267}
3268
3269TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3270 Matcher<double> m1 = DoubleEq(2.0);
3271 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003272 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003273
3274 Matcher<double> m2 = DoubleEq(0.5);
3275 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003276 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003277
3278 Matcher<double> m3 = DoubleEq(nan1_);
3279 EXPECT_EQ("never matches", Describe(m3));
3280 EXPECT_EQ("is anything", DescribeNegation(m3));
3281}
3282
3283TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3284 Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3285 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003286 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003287
3288 Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3289 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003290 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003291
3292 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3293 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003294 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00003295}
3296
zhanyong.wan616180e2013-06-18 18:49:51 +00003297// Instantiate FloatingPointTest for testing floats with a user-specified
3298// max absolute error.
3299typedef FloatingPointNearTest<double> DoubleNearTest;
3300
3301TEST_F(DoubleNearTest, DoubleNearMatches) {
3302 TestNearMatches(&DoubleNear);
3303}
3304
3305TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3306 TestNearMatches(&NanSensitiveDoubleNear);
3307}
3308
3309TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3310 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3311 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3312 EXPECT_EQ(
3313 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3314
3315 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3316 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3317 EXPECT_EQ(
3318 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3319
3320 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3321 EXPECT_EQ("never matches", Describe(m3));
3322 EXPECT_EQ("is anything", DescribeNegation(m3));
3323}
3324
kosak6b817802015-01-08 02:38:14 +00003325TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
3326 EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
3327 EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
3328 EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
3329
Nico Weber09fd5b32017-05-15 17:07:03 -04003330 const std::string explanation =
3331 Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
kosak6b817802015-01-08 02:38:14 +00003332 // Different C++ implementations may print floating-point numbers
3333 // slightly differently.
3334 EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC
3335 explanation == "which is 1.2e-010 from 2.1") // MSVC
3336 << " where explanation is \"" << explanation << "\".";
3337}
3338
zhanyong.wan616180e2013-06-18 18:49:51 +00003339TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3340 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3341 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3342 EXPECT_EQ(
3343 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3344
3345 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3346 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3347 EXPECT_EQ(
3348 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3349
3350 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3351 EXPECT_EQ("is NaN", Describe(m3));
3352 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3353}
3354
3355TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3356 // DoubleNear never matches NaN.
3357 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3358 EXPECT_FALSE(m.Matches(nan1_));
3359 EXPECT_FALSE(m.Matches(nan2_));
3360 EXPECT_FALSE(m.Matches(1.0));
3361}
3362
3363TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3364 // NanSensitiveDoubleNear will match NaN.
3365 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3366 EXPECT_TRUE(m.Matches(nan1_));
3367 EXPECT_TRUE(m.Matches(nan2_));
3368 EXPECT_FALSE(m.Matches(1.0));
3369}
3370
shiqiane35fdd92008-12-10 05:08:54 +00003371TEST(PointeeTest, RawPointer) {
3372 const Matcher<int*> m = Pointee(Ge(0));
3373
3374 int n = 1;
3375 EXPECT_TRUE(m.Matches(&n));
3376 n = -1;
3377 EXPECT_FALSE(m.Matches(&n));
Abseil Team4bb49ed2018-10-04 18:28:05 -04003378 EXPECT_FALSE(m.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00003379}
3380
3381TEST(PointeeTest, RawPointerToConst) {
3382 const Matcher<const double*> m = Pointee(Ge(0));
3383
3384 double x = 1;
3385 EXPECT_TRUE(m.Matches(&x));
3386 x = -1;
3387 EXPECT_FALSE(m.Matches(&x));
Abseil Team4bb49ed2018-10-04 18:28:05 -04003388 EXPECT_FALSE(m.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00003389}
3390
3391TEST(PointeeTest, ReferenceToConstRawPointer) {
3392 const Matcher<int* const &> m = Pointee(Ge(0));
3393
3394 int n = 1;
3395 EXPECT_TRUE(m.Matches(&n));
3396 n = -1;
3397 EXPECT_FALSE(m.Matches(&n));
Abseil Team4bb49ed2018-10-04 18:28:05 -04003398 EXPECT_FALSE(m.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00003399}
3400
3401TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3402 const Matcher<double* &> m = Pointee(Ge(0));
3403
3404 double x = 1.0;
3405 double* p = &x;
3406 EXPECT_TRUE(m.Matches(p));
3407 x = -1;
3408 EXPECT_FALSE(m.Matches(p));
Abseil Team4bb49ed2018-10-04 18:28:05 -04003409 p = nullptr;
shiqiane35fdd92008-12-10 05:08:54 +00003410 EXPECT_FALSE(m.Matches(p));
3411}
3412
billydonahue1f5fdea2014-05-19 17:54:51 +00003413MATCHER_P(FieldIIs, inner_matcher, "") {
3414 return ExplainMatchResult(inner_matcher, arg.i, result_listener);
3415}
3416
Scott Grahama9653c42018-05-02 11:14:39 -07003417#if GTEST_HAS_RTTI
billydonahue1f5fdea2014-05-19 17:54:51 +00003418TEST(WhenDynamicCastToTest, SameType) {
3419 Derived derived;
3420 derived.i = 4;
3421
3422 // Right type. A pointer is passed down.
3423 Base* as_base_ptr = &derived;
3424 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
3425 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
3426 EXPECT_THAT(as_base_ptr,
3427 Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
3428}
3429
3430TEST(WhenDynamicCastToTest, WrongTypes) {
3431 Base base;
3432 Derived derived;
3433 OtherDerived other_derived;
3434
3435 // Wrong types. NULL is passed.
3436 EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3437 EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
3438 Base* as_base_ptr = &derived;
3439 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
3440 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
3441 as_base_ptr = &other_derived;
3442 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3443 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3444}
3445
3446TEST(WhenDynamicCastToTest, AlreadyNull) {
3447 // Already NULL.
Abseil Team4bb49ed2018-10-04 18:28:05 -04003448 Base* as_base_ptr = nullptr;
billydonahue1f5fdea2014-05-19 17:54:51 +00003449 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3450}
3451
3452struct AmbiguousCastTypes {
3453 class VirtualDerived : public virtual Base {};
3454 class DerivedSub1 : public VirtualDerived {};
3455 class DerivedSub2 : public VirtualDerived {};
3456 class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
3457};
3458
3459TEST(WhenDynamicCastToTest, AmbiguousCast) {
3460 AmbiguousCastTypes::DerivedSub1 sub1;
3461 AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
3462 // Multiply derived from Base. dynamic_cast<> returns NULL.
3463 Base* as_base_ptr =
3464 static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
3465 EXPECT_THAT(as_base_ptr,
3466 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
3467 as_base_ptr = &sub1;
3468 EXPECT_THAT(
3469 as_base_ptr,
3470 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
3471}
3472
3473TEST(WhenDynamicCastToTest, Describe) {
3474 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003475 const std::string prefix =
billydonahue1f5fdea2014-05-19 17:54:51 +00003476 "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
billydonahue1f5fdea2014-05-19 17:54:51 +00003477 EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
3478 EXPECT_EQ(prefix + "does not point to a value that is anything",
3479 DescribeNegation(matcher));
3480}
3481
3482TEST(WhenDynamicCastToTest, Explain) {
3483 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
Abseil Team4bb49ed2018-10-04 18:28:05 -04003484 Base* null = nullptr;
billydonahue1f5fdea2014-05-19 17:54:51 +00003485 EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
3486 Derived derived;
3487 EXPECT_TRUE(matcher.Matches(&derived));
3488 EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
3489
3490 // With references, the matcher itself can fail. Test for that one.
3491 Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
3492 EXPECT_THAT(Explain(ref_matcher, derived),
3493 HasSubstr("which cannot be dynamic_cast"));
3494}
3495
3496TEST(WhenDynamicCastToTest, GoodReference) {
3497 Derived derived;
3498 derived.i = 4;
3499 Base& as_base_ref = derived;
3500 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
3501 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
3502}
3503
3504TEST(WhenDynamicCastToTest, BadReference) {
3505 Derived derived;
3506 Base& as_base_ref = derived;
3507 EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
3508}
Scott Grahama9653c42018-05-02 11:14:39 -07003509#endif // GTEST_HAS_RTTI
billydonahue1f5fdea2014-05-19 17:54:51 +00003510
vladlosevada23472012-08-14 15:38:49 +00003511// Minimal const-propagating pointer.
3512template <typename T>
3513class ConstPropagatingPtr {
3514 public:
3515 typedef T element_type;
3516
3517 ConstPropagatingPtr() : val_() {}
3518 explicit ConstPropagatingPtr(T* t) : val_(t) {}
3519 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3520
3521 T* get() { return val_; }
3522 T& operator*() { return *val_; }
3523 // Most smart pointers return non-const T* and T& from the next methods.
3524 const T* get() const { return val_; }
3525 const T& operator*() const { return *val_; }
3526
3527 private:
3528 T* val_;
3529};
3530
3531TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3532 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3533 int three = 3;
3534 const ConstPropagatingPtr<int> co(&three);
3535 ConstPropagatingPtr<int> o(&three);
3536 EXPECT_TRUE(m.Matches(o));
3537 EXPECT_TRUE(m.Matches(co));
3538 *o = 6;
3539 EXPECT_FALSE(m.Matches(o));
3540 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3541}
3542
shiqiane35fdd92008-12-10 05:08:54 +00003543TEST(PointeeTest, NeverMatchesNull) {
3544 const Matcher<const char*> m = Pointee(_);
Abseil Team4bb49ed2018-10-04 18:28:05 -04003545 EXPECT_FALSE(m.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00003546}
3547
3548// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3549TEST(PointeeTest, MatchesAgainstAValue) {
3550 const Matcher<int*> m = Pointee(5);
3551
3552 int n = 5;
3553 EXPECT_TRUE(m.Matches(&n));
3554 n = -1;
3555 EXPECT_FALSE(m.Matches(&n));
Abseil Team4bb49ed2018-10-04 18:28:05 -04003556 EXPECT_FALSE(m.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00003557}
3558
3559TEST(PointeeTest, CanDescribeSelf) {
3560 const Matcher<int*> m = Pointee(Gt(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003561 EXPECT_EQ("points to a value that is > 3", Describe(m));
3562 EXPECT_EQ("does not point to a value that is > 3",
shiqiane35fdd92008-12-10 05:08:54 +00003563 DescribeNegation(m));
3564}
3565
shiqiane35fdd92008-12-10 05:08:54 +00003566TEST(PointeeTest, CanExplainMatchResult) {
Nico Weber09fd5b32017-05-15 17:07:03 -04003567 const Matcher<const std::string*> m = Pointee(StartsWith("Hi"));
shiqiane35fdd92008-12-10 05:08:54 +00003568
Abseil Team4bb49ed2018-10-04 18:28:05 -04003569 EXPECT_EQ("", Explain(m, static_cast<const std::string*>(nullptr)));
shiqiane35fdd92008-12-10 05:08:54 +00003570
zhanyong.wan736baa82010-09-27 17:44:16 +00003571 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
3572 long n = 3; // NOLINT
3573 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003574 Explain(m2, &n));
3575}
3576
3577TEST(PointeeTest, AlwaysExplainsPointee) {
3578 const Matcher<int*> m = Pointee(0);
3579 int n = 42;
zhanyong.wan736baa82010-09-27 17:44:16 +00003580 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
shiqiane35fdd92008-12-10 05:08:54 +00003581}
3582
3583// An uncopyable class.
3584class Uncopyable {
3585 public:
billydonahue1f5fdea2014-05-19 17:54:51 +00003586 Uncopyable() : value_(-1) {}
zhanyong.wan32de5f52009-12-23 00:13:23 +00003587 explicit Uncopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003588
3589 int value() const { return value_; }
billydonahue1f5fdea2014-05-19 17:54:51 +00003590 void set_value(int i) { value_ = i; }
3591
shiqiane35fdd92008-12-10 05:08:54 +00003592 private:
billydonahue1f5fdea2014-05-19 17:54:51 +00003593 int value_;
shiqiane35fdd92008-12-10 05:08:54 +00003594 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3595};
3596
Krystian Kuzniarekbf6df7e2019-07-26 11:48:08 +02003597// Returns true if x.value() is positive.
shiqiane35fdd92008-12-10 05:08:54 +00003598bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3599
billydonahue1f5fdea2014-05-19 17:54:51 +00003600MATCHER_P(UncopyableIs, inner_matcher, "") {
3601 return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
3602}
3603
shiqiane35fdd92008-12-10 05:08:54 +00003604// A user-defined struct for testing Field().
3605struct AStruct {
Abseil Team4bb49ed2018-10-04 18:28:05 -04003606 AStruct() : x(0), y(1.0), z(5), p(nullptr) {}
shiqiane35fdd92008-12-10 05:08:54 +00003607 AStruct(const AStruct& rhs)
3608 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3609
3610 int x; // A non-const field.
3611 const double y; // A const field.
3612 Uncopyable z; // An uncopyable field.
3613 const char* p; // A pointer field.
zhanyong.wan32de5f52009-12-23 00:13:23 +00003614
3615 private:
3616 GTEST_DISALLOW_ASSIGN_(AStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003617};
3618
3619// A derived struct for testing Field().
3620struct DerivedStruct : public AStruct {
3621 char ch;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003622
3623 private:
3624 GTEST_DISALLOW_ASSIGN_(DerivedStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003625};
3626
3627// Tests that Field(&Foo::field, ...) works when field is non-const.
3628TEST(FieldTest, WorksForNonConstField) {
3629 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003630 Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0));
shiqiane35fdd92008-12-10 05:08:54 +00003631
3632 AStruct a;
3633 EXPECT_TRUE(m.Matches(a));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003634 EXPECT_TRUE(m_with_name.Matches(a));
shiqiane35fdd92008-12-10 05:08:54 +00003635 a.x = -1;
3636 EXPECT_FALSE(m.Matches(a));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003637 EXPECT_FALSE(m_with_name.Matches(a));
shiqiane35fdd92008-12-10 05:08:54 +00003638}
3639
3640// Tests that Field(&Foo::field, ...) works when field is const.
3641TEST(FieldTest, WorksForConstField) {
3642 AStruct a;
3643
3644 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003645 Matcher<AStruct> m_with_name = Field("y", &AStruct::y, Ge(0.0));
shiqiane35fdd92008-12-10 05:08:54 +00003646 EXPECT_TRUE(m.Matches(a));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003647 EXPECT_TRUE(m_with_name.Matches(a));
shiqiane35fdd92008-12-10 05:08:54 +00003648 m = Field(&AStruct::y, Le(0.0));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003649 m_with_name = Field("y", &AStruct::y, Le(0.0));
shiqiane35fdd92008-12-10 05:08:54 +00003650 EXPECT_FALSE(m.Matches(a));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003651 EXPECT_FALSE(m_with_name.Matches(a));
shiqiane35fdd92008-12-10 05:08:54 +00003652}
3653
3654// Tests that Field(&Foo::field, ...) works when field is not copyable.
3655TEST(FieldTest, WorksForUncopyableField) {
3656 AStruct a;
3657
3658 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3659 EXPECT_TRUE(m.Matches(a));
3660 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3661 EXPECT_FALSE(m.Matches(a));
3662}
3663
3664// Tests that Field(&Foo::field, ...) works when field is a pointer.
3665TEST(FieldTest, WorksForPointerField) {
3666 // Matching against NULL.
Abseil Team4bb49ed2018-10-04 18:28:05 -04003667 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00003668 AStruct a;
3669 EXPECT_TRUE(m.Matches(a));
3670 a.p = "hi";
3671 EXPECT_FALSE(m.Matches(a));
3672
3673 // Matching a pointer that is not NULL.
3674 m = Field(&AStruct::p, StartsWith("hi"));
3675 a.p = "hill";
3676 EXPECT_TRUE(m.Matches(a));
3677 a.p = "hole";
3678 EXPECT_FALSE(m.Matches(a));
3679}
3680
3681// Tests that Field() works when the object is passed by reference.
3682TEST(FieldTest, WorksForByRefArgument) {
3683 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3684
3685 AStruct a;
3686 EXPECT_TRUE(m.Matches(a));
3687 a.x = -1;
3688 EXPECT_FALSE(m.Matches(a));
3689}
3690
3691// Tests that Field(&Foo::field, ...) works when the argument's type
3692// is a sub-type of Foo.
3693TEST(FieldTest, WorksForArgumentOfSubType) {
3694 // Note that the matcher expects DerivedStruct but we say AStruct
3695 // inside Field().
3696 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
3697
3698 DerivedStruct d;
3699 EXPECT_TRUE(m.Matches(d));
3700 d.x = -1;
3701 EXPECT_FALSE(m.Matches(d));
3702}
3703
3704// Tests that Field(&Foo::field, m) works when field's type and m's
3705// argument type are compatible but not the same.
3706TEST(FieldTest, WorksForCompatibleMatcherType) {
3707 // The field is an int, but the inner matcher expects a signed char.
3708 Matcher<const AStruct&> m = Field(&AStruct::x,
3709 Matcher<signed char>(Ge(0)));
3710
3711 AStruct a;
3712 EXPECT_TRUE(m.Matches(a));
3713 a.x = -1;
3714 EXPECT_FALSE(m.Matches(a));
3715}
3716
3717// Tests that Field() can describe itself.
3718TEST(FieldTest, CanDescribeSelf) {
3719 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3720
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003721 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3722 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003723}
3724
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003725TEST(FieldTest, CanDescribeSelfWithFieldName) {
3726 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
3727
3728 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
3729 EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
3730 DescribeNegation(m));
3731}
3732
shiqiane35fdd92008-12-10 05:08:54 +00003733// Tests that Field() can explain the match result.
3734TEST(FieldTest, CanExplainMatchResult) {
3735 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3736
3737 AStruct a;
3738 a.x = 1;
zhanyong.wan736baa82010-09-27 17:44:16 +00003739 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003740
3741 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003742 EXPECT_EQ(
3743 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
3744 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003745}
3746
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003747TEST(FieldTest, CanExplainMatchResultWithFieldName) {
3748 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
3749
3750 AStruct a;
3751 a.x = 1;
3752 EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a));
3753
3754 m = Field("field_name", &AStruct::x, GreaterThan(0));
3755 EXPECT_EQ("whose field `field_name` is 1" + OfType("int") +
3756 ", which is 1 more than 0",
3757 Explain(m, a));
3758}
3759
shiqiane35fdd92008-12-10 05:08:54 +00003760// Tests that Field() works when the argument is a pointer to const.
3761TEST(FieldForPointerTest, WorksForPointerToConst) {
3762 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3763
3764 AStruct a;
3765 EXPECT_TRUE(m.Matches(&a));
3766 a.x = -1;
3767 EXPECT_FALSE(m.Matches(&a));
3768}
3769
3770// Tests that Field() works when the argument is a pointer to non-const.
3771TEST(FieldForPointerTest, WorksForPointerToNonConst) {
3772 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
3773
3774 AStruct a;
3775 EXPECT_TRUE(m.Matches(&a));
3776 a.x = -1;
3777 EXPECT_FALSE(m.Matches(&a));
3778}
3779
zhanyong.wan6953a722010-01-13 05:15:07 +00003780// Tests that Field() works when the argument is a reference to a const pointer.
3781TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
3782 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
3783
3784 AStruct a;
3785 EXPECT_TRUE(m.Matches(&a));
3786 a.x = -1;
3787 EXPECT_FALSE(m.Matches(&a));
3788}
3789
shiqiane35fdd92008-12-10 05:08:54 +00003790// Tests that Field() does not match the NULL pointer.
3791TEST(FieldForPointerTest, DoesNotMatchNull) {
3792 Matcher<const AStruct*> m = Field(&AStruct::x, _);
Abseil Team4bb49ed2018-10-04 18:28:05 -04003793 EXPECT_FALSE(m.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00003794}
3795
3796// Tests that Field(&Foo::field, ...) works when the argument's type
3797// is a sub-type of const Foo*.
3798TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
3799 // Note that the matcher expects DerivedStruct but we say AStruct
3800 // inside Field().
3801 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
3802
3803 DerivedStruct d;
3804 EXPECT_TRUE(m.Matches(&d));
3805 d.x = -1;
3806 EXPECT_FALSE(m.Matches(&d));
3807}
3808
3809// Tests that Field() can describe itself when used to match a pointer.
3810TEST(FieldForPointerTest, CanDescribeSelf) {
3811 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3812
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003813 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3814 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003815}
3816
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003817TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) {
3818 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
3819
3820 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
3821 EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
3822 DescribeNegation(m));
3823}
3824
shiqiane35fdd92008-12-10 05:08:54 +00003825// Tests that Field() can explain the result of matching a pointer.
3826TEST(FieldForPointerTest, CanExplainMatchResult) {
3827 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3828
3829 AStruct a;
3830 a.x = 1;
Abseil Team4bb49ed2018-10-04 18:28:05 -04003831 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003832 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
3833 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003834
3835 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003836 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
3837 ", which is 1 more than 0", Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003838}
3839
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003840TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) {
3841 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
3842
3843 AStruct a;
3844 a.x = 1;
Abseil Team4bb49ed2018-10-04 18:28:05 -04003845 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003846 EXPECT_EQ(
3847 "which points to an object whose field `field_name` is 1" + OfType("int"),
3848 Explain(m, &a));
3849
3850 m = Field("field_name", &AStruct::x, GreaterThan(0));
3851 EXPECT_EQ("which points to an object whose field `field_name` is 1" +
3852 OfType("int") + ", which is 1 more than 0",
3853 Explain(m, &a));
3854}
3855
shiqiane35fdd92008-12-10 05:08:54 +00003856// A user-defined class for testing Property().
3857class AClass {
3858 public:
3859 AClass() : n_(0) {}
3860
3861 // A getter that returns a non-reference.
3862 int n() const { return n_; }
3863
3864 void set_n(int new_n) { n_ = new_n; }
3865
3866 // A getter that returns a reference to const.
Nico Weber09fd5b32017-05-15 17:07:03 -04003867 const std::string& s() const { return s_; }
shiqiane35fdd92008-12-10 05:08:54 +00003868
Roman Perepelitsa966b5492017-08-22 16:06:26 +02003869 const std::string& s_ref() const & { return s_; }
Roman Perepelitsa966b5492017-08-22 16:06:26 +02003870
Nico Weber09fd5b32017-05-15 17:07:03 -04003871 void set_s(const std::string& new_s) { s_ = new_s; }
shiqiane35fdd92008-12-10 05:08:54 +00003872
3873 // A getter that returns a reference to non-const.
3874 double& x() const { return x_; }
Roman Perepelitsa966b5492017-08-22 16:06:26 +02003875
shiqiane35fdd92008-12-10 05:08:54 +00003876 private:
3877 int n_;
Nico Weber09fd5b32017-05-15 17:07:03 -04003878 std::string s_;
shiqiane35fdd92008-12-10 05:08:54 +00003879
3880 static double x_;
3881};
3882
3883double AClass::x_ = 0.0;
3884
3885// A derived class for testing Property().
3886class DerivedClass : public AClass {
kosak6414d802013-12-03 23:19:36 +00003887 public:
3888 int k() const { return k_; }
shiqiane35fdd92008-12-10 05:08:54 +00003889 private:
3890 int k_;
3891};
3892
3893// Tests that Property(&Foo::property, ...) works when property()
3894// returns a non-reference.
3895TEST(PropertyTest, WorksForNonReferenceProperty) {
3896 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003897 Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0));
shiqiane35fdd92008-12-10 05:08:54 +00003898
3899 AClass a;
3900 a.set_n(1);
3901 EXPECT_TRUE(m.Matches(a));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003902 EXPECT_TRUE(m_with_name.Matches(a));
shiqiane35fdd92008-12-10 05:08:54 +00003903
3904 a.set_n(-1);
3905 EXPECT_FALSE(m.Matches(a));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003906 EXPECT_FALSE(m_with_name.Matches(a));
shiqiane35fdd92008-12-10 05:08:54 +00003907}
3908
3909// Tests that Property(&Foo::property, ...) works when property()
3910// returns a reference to const.
3911TEST(PropertyTest, WorksForReferenceToConstProperty) {
3912 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003913 Matcher<const AClass&> m_with_name =
3914 Property("s", &AClass::s, StartsWith("hi"));
shiqiane35fdd92008-12-10 05:08:54 +00003915
3916 AClass a;
3917 a.set_s("hill");
3918 EXPECT_TRUE(m.Matches(a));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003919 EXPECT_TRUE(m_with_name.Matches(a));
shiqiane35fdd92008-12-10 05:08:54 +00003920
3921 a.set_s("hole");
3922 EXPECT_FALSE(m.Matches(a));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003923 EXPECT_FALSE(m_with_name.Matches(a));
shiqiane35fdd92008-12-10 05:08:54 +00003924}
3925
Roman Perepelitsa966b5492017-08-22 16:06:26 +02003926// Tests that Property(&Foo::property, ...) works when property() is
3927// ref-qualified.
3928TEST(PropertyTest, WorksForRefQualifiedProperty) {
3929 Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi"));
Gennadiy Civila02af2f2018-07-20 11:28:58 -04003930 Matcher<const AClass&> m_with_name =
3931 Property("s", &AClass::s_ref, StartsWith("hi"));
Roman Perepelitsa966b5492017-08-22 16:06:26 +02003932
3933 AClass a;
3934 a.set_s("hill");
3935 EXPECT_TRUE(m.Matches(a));
Gennadiy Civila02af2f2018-07-20 11:28:58 -04003936 EXPECT_TRUE(m_with_name.Matches(a));
Roman Perepelitsa966b5492017-08-22 16:06:26 +02003937
3938 a.set_s("hole");
3939 EXPECT_FALSE(m.Matches(a));
Gennadiy Civila02af2f2018-07-20 11:28:58 -04003940 EXPECT_FALSE(m_with_name.Matches(a));
Roman Perepelitsa966b5492017-08-22 16:06:26 +02003941}
Roman Perepelitsa966b5492017-08-22 16:06:26 +02003942
shiqiane35fdd92008-12-10 05:08:54 +00003943// Tests that Property(&Foo::property, ...) works when property()
3944// returns a reference to non-const.
3945TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
3946 double x = 0.0;
3947 AClass a;
3948
3949 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
3950 EXPECT_FALSE(m.Matches(a));
3951
3952 m = Property(&AClass::x, Not(Ref(x)));
3953 EXPECT_TRUE(m.Matches(a));
3954}
3955
3956// Tests that Property(&Foo::property, ...) works when the argument is
3957// passed by value.
3958TEST(PropertyTest, WorksForByValueArgument) {
3959 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
3960
3961 AClass a;
3962 a.set_s("hill");
3963 EXPECT_TRUE(m.Matches(a));
3964
3965 a.set_s("hole");
3966 EXPECT_FALSE(m.Matches(a));
3967}
3968
3969// Tests that Property(&Foo::property, ...) works when the argument's
3970// type is a sub-type of Foo.
3971TEST(PropertyTest, WorksForArgumentOfSubType) {
3972 // The matcher expects a DerivedClass, but inside the Property() we
3973 // say AClass.
3974 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
3975
3976 DerivedClass d;
3977 d.set_n(1);
3978 EXPECT_TRUE(m.Matches(d));
3979
3980 d.set_n(-1);
3981 EXPECT_FALSE(m.Matches(d));
3982}
3983
3984// Tests that Property(&Foo::property, m) works when property()'s type
3985// and m's argument type are compatible but different.
3986TEST(PropertyTest, WorksForCompatibleMatcherType) {
3987 // n() returns an int but the inner matcher expects a signed char.
3988 Matcher<const AClass&> m = Property(&AClass::n,
3989 Matcher<signed char>(Ge(0)));
3990
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003991 Matcher<const AClass&> m_with_name =
3992 Property("n", &AClass::n, Matcher<signed char>(Ge(0)));
3993
shiqiane35fdd92008-12-10 05:08:54 +00003994 AClass a;
3995 EXPECT_TRUE(m.Matches(a));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003996 EXPECT_TRUE(m_with_name.Matches(a));
shiqiane35fdd92008-12-10 05:08:54 +00003997 a.set_n(-1);
3998 EXPECT_FALSE(m.Matches(a));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04003999 EXPECT_FALSE(m_with_name.Matches(a));
shiqiane35fdd92008-12-10 05:08:54 +00004000}
4001
4002// Tests that Property() can describe itself.
4003TEST(PropertyTest, CanDescribeSelf) {
4004 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4005
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004006 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
4007 EXPECT_EQ("is an object whose given property isn't >= 0",
4008 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00004009}
4010
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04004011TEST(PropertyTest, CanDescribeSelfWithPropertyName) {
4012 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
4013
4014 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
4015 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
4016 DescribeNegation(m));
4017}
4018
shiqiane35fdd92008-12-10 05:08:54 +00004019// Tests that Property() can explain the match result.
4020TEST(PropertyTest, CanExplainMatchResult) {
4021 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4022
4023 AClass a;
4024 a.set_n(1);
zhanyong.wan736baa82010-09-27 17:44:16 +00004025 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00004026
4027 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00004028 EXPECT_EQ(
4029 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
4030 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00004031}
4032
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04004033TEST(PropertyTest, CanExplainMatchResultWithPropertyName) {
4034 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
4035
4036 AClass a;
4037 a.set_n(1);
4038 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a));
4039
4040 m = Property("fancy_name", &AClass::n, GreaterThan(0));
4041 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") +
4042 ", which is 1 more than 0",
4043 Explain(m, a));
4044}
4045
shiqiane35fdd92008-12-10 05:08:54 +00004046// Tests that Property() works when the argument is a pointer to const.
4047TEST(PropertyForPointerTest, WorksForPointerToConst) {
4048 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4049
4050 AClass a;
4051 a.set_n(1);
4052 EXPECT_TRUE(m.Matches(&a));
4053
4054 a.set_n(-1);
4055 EXPECT_FALSE(m.Matches(&a));
4056}
4057
4058// Tests that Property() works when the argument is a pointer to non-const.
4059TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
4060 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
4061
4062 AClass a;
4063 a.set_s("hill");
4064 EXPECT_TRUE(m.Matches(&a));
4065
4066 a.set_s("hole");
4067 EXPECT_FALSE(m.Matches(&a));
4068}
4069
zhanyong.wan6953a722010-01-13 05:15:07 +00004070// Tests that Property() works when the argument is a reference to a
4071// const pointer.
4072TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
4073 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
4074
4075 AClass a;
4076 a.set_s("hill");
4077 EXPECT_TRUE(m.Matches(&a));
4078
4079 a.set_s("hole");
4080 EXPECT_FALSE(m.Matches(&a));
4081}
4082
shiqiane35fdd92008-12-10 05:08:54 +00004083// Tests that Property() does not match the NULL pointer.
4084TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
4085 Matcher<const AClass*> m = Property(&AClass::x, _);
Abseil Team4bb49ed2018-10-04 18:28:05 -04004086 EXPECT_FALSE(m.Matches(nullptr));
shiqiane35fdd92008-12-10 05:08:54 +00004087}
4088
4089// Tests that Property(&Foo::property, ...) works when the argument's
4090// type is a sub-type of const Foo*.
4091TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
4092 // The matcher expects a DerivedClass, but inside the Property() we
4093 // say AClass.
4094 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
4095
4096 DerivedClass d;
4097 d.set_n(1);
4098 EXPECT_TRUE(m.Matches(&d));
4099
4100 d.set_n(-1);
4101 EXPECT_FALSE(m.Matches(&d));
4102}
4103
4104// Tests that Property() can describe itself when used to match a pointer.
4105TEST(PropertyForPointerTest, CanDescribeSelf) {
4106 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4107
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004108 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
4109 EXPECT_EQ("is an object whose given property isn't >= 0",
4110 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00004111}
4112
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04004113TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) {
4114 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
4115
4116 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
4117 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
4118 DescribeNegation(m));
4119}
4120
shiqiane35fdd92008-12-10 05:08:54 +00004121// Tests that Property() can explain the result of matching a pointer.
4122TEST(PropertyForPointerTest, CanExplainMatchResult) {
4123 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4124
4125 AClass a;
4126 a.set_n(1);
Abseil Team4bb49ed2018-10-04 18:28:05 -04004127 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
zhanyong.wan736baa82010-09-27 17:44:16 +00004128 EXPECT_EQ(
4129 "which points to an object whose given property is 1" + OfType("int"),
4130 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00004131
4132 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00004133 EXPECT_EQ("which points to an object whose given property is 1" +
4134 OfType("int") + ", which is 1 more than 0",
4135 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00004136}
4137
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04004138TEST(PropertyForPointerTest, CanExplainMatchResultWithPropertyName) {
4139 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
4140
4141 AClass a;
4142 a.set_n(1);
Abseil Team4bb49ed2018-10-04 18:28:05 -04004143 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04004144 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
4145 OfType("int"),
4146 Explain(m, &a));
4147
4148 m = Property("fancy_name", &AClass::n, GreaterThan(0));
4149 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
4150 OfType("int") + ", which is 1 more than 0",
4151 Explain(m, &a));
4152}
4153
shiqiane35fdd92008-12-10 05:08:54 +00004154// Tests ResultOf.
4155
4156// Tests that ResultOf(f, ...) compiles and works as expected when f is a
4157// function pointer.
Nico Weber09fd5b32017-05-15 17:07:03 -04004158std::string IntToStringFunction(int input) {
4159 return input == 1 ? "foo" : "bar";
4160}
shiqiane35fdd92008-12-10 05:08:54 +00004161
4162TEST(ResultOfTest, WorksForFunctionPointers) {
Nico Weber09fd5b32017-05-15 17:07:03 -04004163 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));
shiqiane35fdd92008-12-10 05:08:54 +00004164
4165 EXPECT_TRUE(matcher.Matches(1));
4166 EXPECT_FALSE(matcher.Matches(2));
4167}
4168
4169// Tests that ResultOf() can describe itself.
4170TEST(ResultOfTest, CanDescribeItself) {
4171 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
4172
zhanyong.wan676e8cc2010-03-16 20:01:51 +00004173 EXPECT_EQ("is mapped by the given callable to a value that "
4174 "is equal to \"foo\"", Describe(matcher));
4175 EXPECT_EQ("is mapped by the given callable to a value that "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004176 "isn't equal to \"foo\"", DescribeNegation(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00004177}
4178
4179// Tests that ResultOf() can explain the match result.
4180int IntFunction(int input) { return input == 42 ? 80 : 90; }
4181
4182TEST(ResultOfTest, CanExplainMatchResult) {
4183 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00004184 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00004185 Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00004186
4187 matcher = ResultOf(&IntFunction, GreaterThan(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00004188 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
4189 ", which is 5 more than 85", Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00004190}
4191
4192// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4193// returns a non-reference.
4194TEST(ResultOfTest, WorksForNonReferenceResults) {
4195 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
4196
4197 EXPECT_TRUE(matcher.Matches(42));
4198 EXPECT_FALSE(matcher.Matches(36));
4199}
4200
4201// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4202// returns a reference to non-const.
zhanyong.wan736baa82010-09-27 17:44:16 +00004203double& DoubleFunction(double& input) { return input; } // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00004204
zhanyong.wan736baa82010-09-27 17:44:16 +00004205Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00004206 return obj;
4207}
4208
4209TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
4210 double x = 3.14;
4211 double x2 = x;
4212 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
4213
4214 EXPECT_TRUE(matcher.Matches(x));
4215 EXPECT_FALSE(matcher.Matches(x2));
4216
4217 // Test that ResultOf works with uncopyable objects
4218 Uncopyable obj(0);
4219 Uncopyable obj2(0);
4220 Matcher<Uncopyable&> matcher2 =
4221 ResultOf(&RefUncopyableFunction, Ref(obj));
4222
4223 EXPECT_TRUE(matcher2.Matches(obj));
4224 EXPECT_FALSE(matcher2.Matches(obj2));
4225}
4226
4227// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4228// returns a reference to const.
Nico Weber09fd5b32017-05-15 17:07:03 -04004229const std::string& StringFunction(const std::string& input) { return input; }
shiqiane35fdd92008-12-10 05:08:54 +00004230
4231TEST(ResultOfTest, WorksForReferenceToConstResults) {
Nico Weber09fd5b32017-05-15 17:07:03 -04004232 std::string s = "foo";
4233 std::string s2 = s;
4234 Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));
shiqiane35fdd92008-12-10 05:08:54 +00004235
4236 EXPECT_TRUE(matcher.Matches(s));
4237 EXPECT_FALSE(matcher.Matches(s2));
4238}
4239
4240// Tests that ResultOf(f, m) works when f(x) and m's
4241// argument types are compatible but different.
4242TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
4243 // IntFunction() returns int but the inner matcher expects a signed char.
4244 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
4245
4246 EXPECT_TRUE(matcher.Matches(36));
4247 EXPECT_FALSE(matcher.Matches(42));
4248}
4249
shiqiane35fdd92008-12-10 05:08:54 +00004250// Tests that the program aborts when ResultOf is passed
4251// a NULL function pointer.
4252TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
zhanyong.wan04d6ed82009-09-11 07:01:08 +00004253 EXPECT_DEATH_IF_SUPPORTED(
Abseil Team4bb49ed2018-10-04 18:28:05 -04004254 ResultOf(static_cast<std::string (*)(int dummy)>(nullptr),
Nico Weber09fd5b32017-05-15 17:07:03 -04004255 Eq(std::string("foo"))),
4256 "NULL function pointer is passed into ResultOf\\(\\)\\.");
shiqiane35fdd92008-12-10 05:08:54 +00004257}
shiqiane35fdd92008-12-10 05:08:54 +00004258
4259// Tests that ResultOf(f, ...) compiles and works as expected when f is a
4260// function reference.
4261TEST(ResultOfTest, WorksForFunctionReferences) {
4262 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
4263 EXPECT_TRUE(matcher.Matches(1));
4264 EXPECT_FALSE(matcher.Matches(2));
4265}
4266
4267// Tests that ResultOf(f, ...) compiles and works as expected when f is a
4268// function object.
Tom Lacheckid5151582019-06-13 17:37:33 +01004269struct Functor {
4270 std::string operator()(int input) const {
shiqiane35fdd92008-12-10 05:08:54 +00004271 return IntToStringFunction(input);
4272 }
4273};
4274
4275TEST(ResultOfTest, WorksForFunctors) {
Nico Weber09fd5b32017-05-15 17:07:03 -04004276 Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));
shiqiane35fdd92008-12-10 05:08:54 +00004277
4278 EXPECT_TRUE(matcher.Matches(1));
4279 EXPECT_FALSE(matcher.Matches(2));
4280}
4281
4282// Tests that ResultOf(f, ...) compiles and works as expected when f is a
Gennadiy Civil3530ab92018-07-18 11:51:14 -04004283// functor with more than one operator() defined. ResultOf() must work
shiqiane35fdd92008-12-10 05:08:54 +00004284// for each defined operator().
4285struct PolymorphicFunctor {
4286 typedef int result_type;
4287 int operator()(int n) { return n; }
4288 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
Abseil Teama0e62d92018-08-24 13:30:17 -04004289 std::string operator()(int *p) { return p ? "good ptr" : "null"; }
shiqiane35fdd92008-12-10 05:08:54 +00004290};
4291
4292TEST(ResultOfTest, WorksForPolymorphicFunctors) {
4293 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
4294
4295 EXPECT_TRUE(matcher_int.Matches(10));
4296 EXPECT_FALSE(matcher_int.Matches(2));
4297
4298 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
4299
4300 EXPECT_TRUE(matcher_string.Matches("long string"));
4301 EXPECT_FALSE(matcher_string.Matches("shrt"));
4302}
4303
Abseil Teama0e62d92018-08-24 13:30:17 -04004304TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) {
4305 Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr");
4306
4307 int n = 0;
4308 EXPECT_TRUE(matcher.Matches(&n));
4309 EXPECT_FALSE(matcher.Matches(nullptr));
4310}
4311
4312TEST(ResultOfTest, WorksForLambdas) {
Gennadiy Civila0d60be2019-04-18 09:44:23 -04004313 Matcher<int> matcher = ResultOf(
4314 [](int str_len) {
4315 return std::string(static_cast<size_t>(str_len), 'x');
4316 },
4317 "xxx");
Abseil Teama0e62d92018-08-24 13:30:17 -04004318 EXPECT_TRUE(matcher.Matches(3));
4319 EXPECT_FALSE(matcher.Matches(1));
4320}
Abseil Teama0e62d92018-08-24 13:30:17 -04004321
shiqiane35fdd92008-12-10 05:08:54 +00004322const int* ReferencingFunction(const int& n) { return &n; }
4323
4324struct ReferencingFunctor {
4325 typedef const int* result_type;
4326 result_type operator()(const int& n) { return &n; }
4327};
4328
4329TEST(ResultOfTest, WorksForReferencingCallables) {
4330 const int n = 1;
4331 const int n2 = 1;
4332 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
4333 EXPECT_TRUE(matcher2.Matches(n));
4334 EXPECT_FALSE(matcher2.Matches(n2));
4335
4336 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
4337 EXPECT_TRUE(matcher3.Matches(n));
4338 EXPECT_FALSE(matcher3.Matches(n2));
4339}
4340
shiqiane35fdd92008-12-10 05:08:54 +00004341class DivisibleByImpl {
4342 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00004343 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
shiqiane35fdd92008-12-10 05:08:54 +00004344
zhanyong.wandb22c222010-01-28 21:52:29 +00004345 // For testing using ExplainMatchResultTo() with polymorphic matchers.
shiqiane35fdd92008-12-10 05:08:54 +00004346 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00004347 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004348 *listener << "which is " << (n % divider_) << " modulo "
zhanyong.wandb22c222010-01-28 21:52:29 +00004349 << divider_;
shiqiane35fdd92008-12-10 05:08:54 +00004350 return (n % divider_) == 0;
4351 }
4352
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004353 void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00004354 *os << "is divisible by " << divider_;
4355 }
4356
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004357 void DescribeNegationTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00004358 *os << "is not divisible by " << divider_;
4359 }
4360
zhanyong.wan32de5f52009-12-23 00:13:23 +00004361 void set_divider(int a_divider) { divider_ = a_divider; }
shiqiane35fdd92008-12-10 05:08:54 +00004362 int divider() const { return divider_; }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004363
shiqiane35fdd92008-12-10 05:08:54 +00004364 private:
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004365 int divider_;
shiqiane35fdd92008-12-10 05:08:54 +00004366};
4367
shiqiane35fdd92008-12-10 05:08:54 +00004368PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
4369 return MakePolymorphicMatcher(DivisibleByImpl(n));
4370}
4371
4372// Tests that when AllOf() fails, only the first failing matcher is
4373// asked to explain why.
4374TEST(ExplainMatchResultTest, AllOf_False_False) {
4375 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004376 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00004377}
4378
4379// Tests that when AllOf() fails, only the first failing matcher is
4380// asked to explain why.
4381TEST(ExplainMatchResultTest, AllOf_False_True) {
4382 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004383 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00004384}
4385
4386// Tests that when AllOf() fails, only the first failing matcher is
4387// asked to explain why.
4388TEST(ExplainMatchResultTest, AllOf_True_False) {
4389 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004390 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00004391}
4392
4393// Tests that when AllOf() succeeds, all matchers are asked to explain
4394// why.
4395TEST(ExplainMatchResultTest, AllOf_True_True) {
4396 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004397 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00004398}
4399
4400TEST(ExplainMatchResultTest, AllOf_True_True_2) {
4401 const Matcher<int> m = AllOf(Ge(2), Le(3));
4402 EXPECT_EQ("", Explain(m, 2));
4403}
4404
4405TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
4406 const Matcher<int> m = GreaterThan(5);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00004407 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00004408}
4409
4410// The following two tests verify that values without a public copy
4411// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
4412// with the help of ByRef().
4413
4414class NotCopyable {
4415 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00004416 explicit NotCopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00004417
4418 int value() const { return value_; }
4419
4420 bool operator==(const NotCopyable& rhs) const {
4421 return value() == rhs.value();
4422 }
4423
4424 bool operator>=(const NotCopyable& rhs) const {
4425 return value() >= rhs.value();
4426 }
4427 private:
4428 int value_;
4429
4430 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
4431};
4432
4433TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
4434 const NotCopyable const_value1(1);
4435 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
4436
4437 const NotCopyable n1(1), n2(2);
4438 EXPECT_TRUE(m.Matches(n1));
4439 EXPECT_FALSE(m.Matches(n2));
4440}
4441
4442TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
4443 NotCopyable value2(2);
4444 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
4445
4446 NotCopyable n1(1), n2(2);
4447 EXPECT_FALSE(m.Matches(n1));
4448 EXPECT_TRUE(m.Matches(n2));
4449}
4450
zhanyong.wan320814a2013-03-01 00:20:30 +00004451TEST(IsEmptyTest, ImplementsIsEmpty) {
4452 vector<int> container;
4453 EXPECT_THAT(container, IsEmpty());
4454 container.push_back(0);
4455 EXPECT_THAT(container, Not(IsEmpty()));
4456 container.push_back(1);
4457 EXPECT_THAT(container, Not(IsEmpty()));
4458}
4459
4460TEST(IsEmptyTest, WorksWithString) {
Nico Weber09fd5b32017-05-15 17:07:03 -04004461 std::string text;
zhanyong.wan320814a2013-03-01 00:20:30 +00004462 EXPECT_THAT(text, IsEmpty());
4463 text = "foo";
4464 EXPECT_THAT(text, Not(IsEmpty()));
Nico Weber09fd5b32017-05-15 17:07:03 -04004465 text = std::string("\0", 1);
zhanyong.wan320814a2013-03-01 00:20:30 +00004466 EXPECT_THAT(text, Not(IsEmpty()));
4467}
4468
4469TEST(IsEmptyTest, CanDescribeSelf) {
4470 Matcher<vector<int> > m = IsEmpty();
4471 EXPECT_EQ("is empty", Describe(m));
4472 EXPECT_EQ("isn't empty", DescribeNegation(m));
4473}
4474
4475TEST(IsEmptyTest, ExplainsResult) {
4476 Matcher<vector<int> > m = IsEmpty();
4477 vector<int> container;
4478 EXPECT_EQ("", Explain(m, container));
4479 container.push_back(0);
4480 EXPECT_EQ("whose size is 1", Explain(m, container));
4481}
4482
Abseil Team1ec20f82018-12-15 08:11:02 -05004483TEST(IsEmptyTest, WorksWithMoveOnly) {
4484 ContainerHelper helper;
4485 EXPECT_CALL(helper, Call(IsEmpty()));
4486 helper.Call({});
4487}
4488
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04004489TEST(IsTrueTest, IsTrueIsFalse) {
4490 EXPECT_THAT(true, IsTrue());
4491 EXPECT_THAT(false, IsFalse());
4492 EXPECT_THAT(true, Not(IsFalse()));
4493 EXPECT_THAT(false, Not(IsTrue()));
4494 EXPECT_THAT(0, Not(IsTrue()));
4495 EXPECT_THAT(0, IsFalse());
Vadim Barkov3feffdd2018-10-28 03:27:51 +03004496 EXPECT_THAT(nullptr, Not(IsTrue()));
4497 EXPECT_THAT(nullptr, IsFalse());
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04004498 EXPECT_THAT(-1, IsTrue());
4499 EXPECT_THAT(-1, Not(IsFalse()));
4500 EXPECT_THAT(1, IsTrue());
4501 EXPECT_THAT(1, Not(IsFalse()));
4502 EXPECT_THAT(2, IsTrue());
4503 EXPECT_THAT(2, Not(IsFalse()));
4504 int a = 42;
4505 EXPECT_THAT(a, IsTrue());
4506 EXPECT_THAT(a, Not(IsFalse()));
4507 EXPECT_THAT(&a, IsTrue());
4508 EXPECT_THAT(&a, Not(IsFalse()));
4509 EXPECT_THAT(false, Not(IsTrue()));
4510 EXPECT_THAT(true, Not(IsFalse()));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04004511 EXPECT_THAT(std::true_type(), IsTrue());
4512 EXPECT_THAT(std::true_type(), Not(IsFalse()));
4513 EXPECT_THAT(std::false_type(), IsFalse());
4514 EXPECT_THAT(std::false_type(), Not(IsTrue()));
4515 EXPECT_THAT(nullptr, Not(IsTrue()));
4516 EXPECT_THAT(nullptr, IsFalse());
4517 std::unique_ptr<int> null_unique;
4518 std::unique_ptr<int> nonnull_unique(new int(0));
4519 EXPECT_THAT(null_unique, Not(IsTrue()));
4520 EXPECT_THAT(null_unique, IsFalse());
4521 EXPECT_THAT(nonnull_unique, IsTrue());
4522 EXPECT_THAT(nonnull_unique, Not(IsFalse()));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04004523}
4524
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004525TEST(SizeIsTest, ImplementsSizeIs) {
4526 vector<int> container;
4527 EXPECT_THAT(container, SizeIs(0));
4528 EXPECT_THAT(container, Not(SizeIs(1)));
4529 container.push_back(0);
4530 EXPECT_THAT(container, Not(SizeIs(0)));
4531 EXPECT_THAT(container, SizeIs(1));
4532 container.push_back(0);
4533 EXPECT_THAT(container, Not(SizeIs(0)));
4534 EXPECT_THAT(container, SizeIs(2));
4535}
4536
4537TEST(SizeIsTest, WorksWithMap) {
Nico Weber09fd5b32017-05-15 17:07:03 -04004538 map<std::string, int> container;
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004539 EXPECT_THAT(container, SizeIs(0));
4540 EXPECT_THAT(container, Not(SizeIs(1)));
4541 container.insert(make_pair("foo", 1));
4542 EXPECT_THAT(container, Not(SizeIs(0)));
4543 EXPECT_THAT(container, SizeIs(1));
4544 container.insert(make_pair("bar", 2));
4545 EXPECT_THAT(container, Not(SizeIs(0)));
4546 EXPECT_THAT(container, SizeIs(2));
4547}
4548
4549TEST(SizeIsTest, WorksWithReferences) {
4550 vector<int> container;
4551 Matcher<const vector<int>&> m = SizeIs(1);
4552 EXPECT_THAT(container, Not(m));
4553 container.push_back(0);
4554 EXPECT_THAT(container, m);
4555}
4556
Abseil Team1ec20f82018-12-15 08:11:02 -05004557TEST(SizeIsTest, WorksWithMoveOnly) {
4558 ContainerHelper helper;
4559 EXPECT_CALL(helper, Call(SizeIs(3)));
4560 helper.Call(MakeUniquePtrs({1, 2, 3}));
4561}
4562
Abseil Team3d71ab42018-12-03 14:55:34 -05004563// SizeIs should work for any type that provides a size() member function.
4564// For example, a size_type member type should not need to be provided.
4565struct MinimalistCustomType {
4566 int size() const { return 1; }
4567};
4568TEST(SizeIsTest, WorksWithMinimalistCustomType) {
4569 MinimalistCustomType container;
4570 EXPECT_THAT(container, SizeIs(1));
4571 EXPECT_THAT(container, Not(SizeIs(0)));
4572}
4573
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004574TEST(SizeIsTest, CanDescribeSelf) {
4575 Matcher<vector<int> > m = SizeIs(2);
4576 EXPECT_EQ("size is equal to 2", Describe(m));
4577 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
4578}
4579
4580TEST(SizeIsTest, ExplainsResult) {
4581 Matcher<vector<int> > m1 = SizeIs(2);
4582 Matcher<vector<int> > m2 = SizeIs(Lt(2u));
4583 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
4584 Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
4585 vector<int> container;
4586 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
4587 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
4588 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
4589 EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
4590 Explain(m4, container));
4591 container.push_back(0);
4592 container.push_back(0);
4593 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
4594 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
4595 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
4596 EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
4597 Explain(m4, container));
4598}
4599
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004600#if GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004601// Tests ContainerEq with different container types, and
4602// different element types.
4603
4604template <typename T>
zhanyong.wanb8243162009-06-04 05:48:20 +00004605class ContainerEqTest : public testing::Test {};
zhanyong.wan6a896b52009-01-16 01:13:50 +00004606
4607typedef testing::Types<
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004608 set<int>,
4609 vector<size_t>,
4610 multiset<size_t>,
4611 list<int> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004612 ContainerEqTestTypes;
4613
misterg52ea4f72019-02-04 11:40:09 -05004614TYPED_TEST_SUITE(ContainerEqTest, ContainerEqTestTypes);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004615
4616// Tests that the filled container is equal to itself.
4617TYPED_TEST(ContainerEqTest, EqualsSelf) {
4618 static const int vals[] = {1, 1, 2, 3, 5, 8};
4619 TypeParam my_set(vals, vals + 6);
4620 const Matcher<TypeParam> m = ContainerEq(my_set);
4621 EXPECT_TRUE(m.Matches(my_set));
4622 EXPECT_EQ("", Explain(m, my_set));
4623}
4624
4625// Tests that missing values are reported.
4626TYPED_TEST(ContainerEqTest, ValueMissing) {
4627 static const int vals[] = {1, 1, 2, 3, 5, 8};
4628 static const int test_vals[] = {2, 1, 8, 5};
4629 TypeParam my_set(vals, vals + 6);
4630 TypeParam test_set(test_vals, test_vals + 4);
4631 const Matcher<TypeParam> m = ContainerEq(my_set);
4632 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004633 EXPECT_EQ("which doesn't have these expected elements: 3",
4634 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004635}
4636
4637// Tests that added values are reported.
4638TYPED_TEST(ContainerEqTest, ValueAdded) {
4639 static const int vals[] = {1, 1, 2, 3, 5, 8};
4640 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4641 TypeParam my_set(vals, vals + 6);
4642 TypeParam test_set(test_vals, test_vals + 6);
4643 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4644 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004645 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004646}
4647
4648// Tests that added and missing values are reported together.
4649TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4650 static const int vals[] = {1, 1, 2, 3, 5, 8};
4651 static const int test_vals[] = {1, 2, 3, 8, 46};
4652 TypeParam my_set(vals, vals + 6);
4653 TypeParam test_set(test_vals, test_vals + 5);
4654 const Matcher<TypeParam> m = ContainerEq(my_set);
4655 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004656 EXPECT_EQ("which has these unexpected elements: 46,\n"
4657 "and doesn't have these expected elements: 5",
4658 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004659}
4660
4661// Tests duplicated value -- expect no explanation.
4662TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4663 static const int vals[] = {1, 1, 2, 3, 5, 8};
4664 static const int test_vals[] = {1, 2, 3, 5, 8};
4665 TypeParam my_set(vals, vals + 6);
4666 TypeParam test_set(test_vals, test_vals + 5);
4667 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4668 // Depending on the container, match may be true or false
4669 // But in any case there should be no explanation.
4670 EXPECT_EQ("", Explain(m, test_set));
4671}
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004672#endif // GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004673
Abseil Team6ef59132018-12-11 14:10:54 -05004674// Tests that multiple missing values are reported.
Troy Holsapplec8510502018-02-07 22:06:00 -08004675// Using just vector here, so order is predictable.
zhanyong.wan6a896b52009-01-16 01:13:50 +00004676TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4677 static const int vals[] = {1, 1, 2, 3, 5, 8};
4678 static const int test_vals[] = {2, 1, 5};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004679 vector<int> my_set(vals, vals + 6);
4680 vector<int> test_set(test_vals, test_vals + 3);
4681 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004682 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004683 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4684 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004685}
4686
4687// Tests that added values are reported.
Troy Holsapplec8510502018-02-07 22:06:00 -08004688// Using just vector here, so order is predictable.
zhanyong.wan6a896b52009-01-16 01:13:50 +00004689TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4690 static const int vals[] = {1, 1, 2, 3, 5, 8};
4691 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004692 list<size_t> my_set(vals, vals + 6);
4693 list<size_t> test_set(test_vals, test_vals + 7);
4694 const Matcher<const list<size_t>&> m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004695 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004696 EXPECT_EQ("which has these unexpected elements: 92, 46",
4697 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004698}
4699
4700// Tests that added and missing values are reported together.
4701TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
4702 static const int vals[] = {1, 1, 2, 3, 5, 8};
4703 static const int test_vals[] = {1, 2, 3, 92, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004704 list<size_t> my_set(vals, vals + 6);
4705 list<size_t> test_set(test_vals, test_vals + 5);
4706 const Matcher<const list<size_t> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004707 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004708 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4709 "and doesn't have these expected elements: 5, 8",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004710 Explain(m, test_set));
4711}
4712
4713// Tests to see that duplicate elements are detected,
4714// but (as above) not reported in the explanation.
4715TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
4716 static const int vals[] = {1, 1, 2, 3, 5, 8};
4717 static const int test_vals[] = {1, 2, 3, 5, 8};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004718 vector<int> my_set(vals, vals + 6);
4719 vector<int> test_set(test_vals, test_vals + 5);
4720 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004721 EXPECT_TRUE(m.Matches(my_set));
4722 EXPECT_FALSE(m.Matches(test_set));
4723 // There is nothing to report when both sets contain all the same values.
4724 EXPECT_EQ("", Explain(m, test_set));
4725}
4726
4727// Tests that ContainerEq works for non-trivial associative containers,
4728// like maps.
4729TEST(ContainerEqExtraTest, WorksForMaps) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004730 map<int, std::string> my_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004731 my_map[0] = "a";
4732 my_map[1] = "b";
4733
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004734 map<int, std::string> test_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004735 test_map[0] = "aa";
4736 test_map[1] = "b";
4737
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004738 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004739 EXPECT_TRUE(m.Matches(my_map));
4740 EXPECT_FALSE(m.Matches(test_map));
4741
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004742 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
4743 "and doesn't have these expected elements: (0, \"a\")",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004744 Explain(m, test_map));
4745}
4746
zhanyong.wanb8243162009-06-04 05:48:20 +00004747TEST(ContainerEqExtraTest, WorksForNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00004748 int a1[] = {1, 2, 3};
4749 int a2[] = {1, 2, 3};
4750 int b[] = {1, 2, 4};
zhanyong.wanb8243162009-06-04 05:48:20 +00004751
4752 EXPECT_THAT(a1, ContainerEq(a2));
4753 EXPECT_THAT(a1, Not(ContainerEq(b)));
4754}
4755
4756TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00004757 const char a1[][3] = {"hi", "lo"};
4758 const char a2[][3] = {"hi", "lo"};
4759 const char b[][3] = {"lo", "hi"};
zhanyong.wanb8243162009-06-04 05:48:20 +00004760
4761 // Tests using ContainerEq() in the first dimension.
4762 EXPECT_THAT(a1, ContainerEq(a2));
4763 EXPECT_THAT(a1, Not(ContainerEq(b)));
4764
4765 // Tests using ContainerEq() in the second dimension.
4766 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
4767 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
4768}
4769
4770TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
kosak2336e9c2014-07-28 22:57:30 +00004771 const int a1[] = {1, 2, 3};
4772 const int a2[] = {1, 2, 3};
4773 const int b[] = {1, 2, 3, 4};
zhanyong.wanb8243162009-06-04 05:48:20 +00004774
zhanyong.wan2661c682009-06-09 05:42:12 +00004775 const int* const p1 = a1;
Abseil Team7d3b73c2018-10-09 14:50:26 -04004776 EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2));
4777 EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004778
kosak2336e9c2014-07-28 22:57:30 +00004779 const int c[] = {1, 3, 2};
Abseil Team7d3b73c2018-10-09 14:50:26 -04004780 EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004781}
4782
4783TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
4784 std::string a1[][3] = {
kosak2336e9c2014-07-28 22:57:30 +00004785 {"hi", "hello", "ciao"},
4786 {"bye", "see you", "ciao"}
zhanyong.wanb8243162009-06-04 05:48:20 +00004787 };
4788
4789 std::string a2[][3] = {
kosak2336e9c2014-07-28 22:57:30 +00004790 {"hi", "hello", "ciao"},
4791 {"bye", "see you", "ciao"}
zhanyong.wanb8243162009-06-04 05:48:20 +00004792 };
4793
4794 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
4795 EXPECT_THAT(a1, m);
4796
4797 a2[0][0] = "ha";
4798 EXPECT_THAT(a1, m);
4799}
4800
zhanyong.wan898725c2011-09-16 16:45:39 +00004801TEST(WhenSortedByTest, WorksForEmptyContainer) {
4802 const vector<int> numbers;
4803 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
4804 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
4805}
4806
4807TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
4808 vector<unsigned> numbers;
4809 numbers.push_back(3);
4810 numbers.push_back(1);
4811 numbers.push_back(2);
4812 numbers.push_back(2);
4813 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
4814 ElementsAre(3, 2, 2, 1)));
4815 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
4816 ElementsAre(1, 2, 2, 3))));
4817}
4818
4819TEST(WhenSortedByTest, WorksForNonVectorContainer) {
Nico Weber09fd5b32017-05-15 17:07:03 -04004820 list<std::string> words;
zhanyong.wan898725c2011-09-16 16:45:39 +00004821 words.push_back("say");
4822 words.push_back("hello");
4823 words.push_back("world");
Nico Weber09fd5b32017-05-15 17:07:03 -04004824 EXPECT_THAT(words, WhenSortedBy(less<std::string>(),
zhanyong.wan898725c2011-09-16 16:45:39 +00004825 ElementsAre("hello", "say", "world")));
Nico Weber09fd5b32017-05-15 17:07:03 -04004826 EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),
zhanyong.wan898725c2011-09-16 16:45:39 +00004827 ElementsAre("say", "hello", "world"))));
4828}
4829
4830TEST(WhenSortedByTest, WorksForNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00004831 const int numbers[] = {1, 3, 2, 4};
4832 const int sorted_numbers[] = {1, 2, 3, 4};
zhanyong.wan898725c2011-09-16 16:45:39 +00004833 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
4834 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
4835 ElementsAreArray(sorted_numbers)));
4836 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
4837}
4838
4839TEST(WhenSortedByTest, CanDescribeSelf) {
4840 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
4841 EXPECT_EQ("(when sorted) has 2 elements where\n"
4842 "element #0 is equal to 1,\n"
4843 "element #1 is equal to 2",
4844 Describe(m));
4845 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
4846 "element #0 isn't equal to 1, or\n"
4847 "element #1 isn't equal to 2",
4848 DescribeNegation(m));
4849}
4850
4851TEST(WhenSortedByTest, ExplainsMatchResult) {
kosak2336e9c2014-07-28 22:57:30 +00004852 const int a[] = {2, 1};
zhanyong.wan898725c2011-09-16 16:45:39 +00004853 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
4854 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
4855 EXPECT_EQ("which is { 1, 2 } when sorted",
4856 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
4857}
4858
4859// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
4860// need to test it as exhaustively as we test the latter.
4861
4862TEST(WhenSortedTest, WorksForEmptyContainer) {
4863 const vector<int> numbers;
4864 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
4865 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
4866}
4867
4868TEST(WhenSortedTest, WorksForNonEmptyContainer) {
Nico Weber09fd5b32017-05-15 17:07:03 -04004869 list<std::string> words;
zhanyong.wan898725c2011-09-16 16:45:39 +00004870 words.push_back("3");
4871 words.push_back("1");
4872 words.push_back("2");
4873 words.push_back("2");
4874 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
4875 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
4876}
4877
zhanyong.wana9a59e02013-03-27 16:14:55 +00004878TEST(WhenSortedTest, WorksForMapTypes) {
Nico Weber09fd5b32017-05-15 17:07:03 -04004879 map<std::string, int> word_counts;
4880 word_counts["and"] = 1;
4881 word_counts["the"] = 1;
4882 word_counts["buffalo"] = 2;
4883 EXPECT_THAT(word_counts,
4884 WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),
4885 Pair("the", 1))));
4886 EXPECT_THAT(word_counts,
4887 Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
4888 Pair("buffalo", 2)))));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004889}
4890
4891TEST(WhenSortedTest, WorksForMultiMapTypes) {
4892 multimap<int, int> ifib;
4893 ifib.insert(make_pair(8, 6));
4894 ifib.insert(make_pair(2, 3));
4895 ifib.insert(make_pair(1, 1));
4896 ifib.insert(make_pair(3, 4));
4897 ifib.insert(make_pair(1, 2));
4898 ifib.insert(make_pair(5, 5));
4899 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
4900 Pair(1, 2),
4901 Pair(2, 3),
4902 Pair(3, 4),
4903 Pair(5, 5),
4904 Pair(8, 6))));
4905 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
4906 Pair(2, 3),
4907 Pair(1, 1),
4908 Pair(3, 4),
4909 Pair(1, 2),
4910 Pair(5, 5)))));
4911}
4912
4913TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
4914 std::deque<int> d;
4915 d.push_back(2);
4916 d.push_back(1);
4917 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
4918 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
4919}
4920
4921TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
4922 std::deque<int> d;
4923 d.push_back(2);
4924 d.push_back(1);
4925 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
4926 EXPECT_THAT(d, WhenSorted(vector_match));
4927 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
4928 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
4929}
4930
4931// Deliberately bare pseudo-container.
4932// Offers only begin() and end() accessors, yielding InputIterator.
4933template <typename T>
4934class Streamlike {
4935 private:
4936 class ConstIter;
4937 public:
4938 typedef ConstIter const_iterator;
4939 typedef T value_type;
4940
4941 template <typename InIter>
4942 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
4943
4944 const_iterator begin() const {
4945 return const_iterator(this, remainder_.begin());
4946 }
4947 const_iterator end() const {
4948 return const_iterator(this, remainder_.end());
4949 }
4950
4951 private:
4952 class ConstIter : public std::iterator<std::input_iterator_tag,
4953 value_type,
4954 ptrdiff_t,
kosakcd99eb02014-11-17 02:18:28 +00004955 const value_type*,
4956 const value_type&> {
zhanyong.wana9a59e02013-03-27 16:14:55 +00004957 public:
4958 ConstIter(const Streamlike* s,
4959 typename std::list<value_type>::iterator pos)
4960 : s_(s), pos_(pos) {}
4961
4962 const value_type& operator*() const { return *pos_; }
4963 const value_type* operator->() const { return &*pos_; }
4964 ConstIter& operator++() {
4965 s_->remainder_.erase(pos_++);
4966 return *this;
4967 }
4968
4969 // *iter++ is required to work (see std::istreambuf_iterator).
4970 // (void)iter++ is also required to work.
4971 class PostIncrProxy {
4972 public:
4973 explicit PostIncrProxy(const value_type& value) : value_(value) {}
4974 value_type operator*() const { return value_; }
4975 private:
4976 value_type value_;
4977 };
4978 PostIncrProxy operator++(int) {
4979 PostIncrProxy proxy(**this);
4980 ++(*this);
4981 return proxy;
4982 }
4983
4984 friend bool operator==(const ConstIter& a, const ConstIter& b) {
4985 return a.s_ == b.s_ && a.pos_ == b.pos_;
4986 }
4987 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
4988 return !(a == b);
4989 }
4990
4991 private:
4992 const Streamlike* s_;
4993 typename std::list<value_type>::iterator pos_;
4994 };
4995
4996 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
4997 os << "[";
4998 typedef typename std::list<value_type>::const_iterator Iter;
4999 const char* sep = "";
5000 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
5001 os << sep << *it;
5002 sep = ",";
5003 }
5004 os << "]";
5005 return os;
5006 }
5007
5008 mutable std::list<value_type> remainder_; // modified by iteration
5009};
5010
5011TEST(StreamlikeTest, Iteration) {
kosak2336e9c2014-07-28 22:57:30 +00005012 const int a[5] = {2, 1, 4, 5, 3};
zhanyong.wana9a59e02013-03-27 16:14:55 +00005013 Streamlike<int> s(a, a + 5);
5014 Streamlike<int>::const_iterator it = s.begin();
5015 const int* ip = a;
5016 while (it != s.end()) {
5017 SCOPED_TRACE(ip - a);
5018 EXPECT_EQ(*ip++, *it++);
5019 }
5020}
5021
kosakb6a34882014-03-12 21:06:46 +00005022TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
5023 std::forward_list<int> container;
5024 EXPECT_THAT(container, BeginEndDistanceIs(0));
5025 EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
5026 container.push_front(0);
5027 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
5028 EXPECT_THAT(container, BeginEndDistanceIs(1));
5029 container.push_front(0);
5030 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
5031 EXPECT_THAT(container, BeginEndDistanceIs(2));
5032}
kosakb6a34882014-03-12 21:06:46 +00005033
5034TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
kosak2336e9c2014-07-28 22:57:30 +00005035 const int a[5] = {1, 2, 3, 4, 5};
kosakb6a34882014-03-12 21:06:46 +00005036 Streamlike<int> s(a, a + 5);
5037 EXPECT_THAT(s, BeginEndDistanceIs(5));
5038}
5039
5040TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
5041 Matcher<vector<int> > m = BeginEndDistanceIs(2);
5042 EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
5043 EXPECT_EQ("distance between begin() and end() isn't equal to 2",
5044 DescribeNegation(m));
5045}
5046
Abseil Team1ec20f82018-12-15 08:11:02 -05005047TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) {
5048 ContainerHelper helper;
5049 EXPECT_CALL(helper, Call(BeginEndDistanceIs(2)));
5050 helper.Call(MakeUniquePtrs({1, 2}));
5051}
5052
kosakb6a34882014-03-12 21:06:46 +00005053TEST(BeginEndDistanceIsTest, ExplainsResult) {
5054 Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
5055 Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
5056 Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
5057 Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
5058 vector<int> container;
5059 EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
5060 Explain(m1, container));
5061 EXPECT_EQ("whose distance between begin() and end() 0 matches",
5062 Explain(m2, container));
5063 EXPECT_EQ("whose distance between begin() and end() 0 matches",
5064 Explain(m3, container));
5065 EXPECT_EQ(
5066 "whose distance between begin() and end() 0 doesn't match, which is 1 "
5067 "less than 1",
5068 Explain(m4, container));
5069 container.push_back(0);
5070 container.push_back(0);
5071 EXPECT_EQ("whose distance between begin() and end() 2 matches",
5072 Explain(m1, container));
5073 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
5074 Explain(m2, container));
5075 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
5076 Explain(m3, container));
5077 EXPECT_EQ(
5078 "whose distance between begin() and end() 2 matches, which is 1 more "
5079 "than 1",
5080 Explain(m4, container));
5081}
5082
zhanyong.wana9a59e02013-03-27 16:14:55 +00005083TEST(WhenSortedTest, WorksForStreamlike) {
5084 // Streamlike 'container' provides only minimal iterator support.
5085 // Its iterators are tagged with input_iterator_tag.
kosak2336e9c2014-07-28 22:57:30 +00005086 const int a[5] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00005087 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00005088 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
5089 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
5090}
5091
5092TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
kosak2336e9c2014-07-28 22:57:30 +00005093 const int a[] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00005094 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00005095 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
5096 EXPECT_THAT(s, WhenSorted(vector_match));
5097 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
5098}
5099
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04005100TEST(IsSupersetOfTest, WorksForNativeArray) {
5101 const int subset[] = {1, 4};
5102 const int superset[] = {1, 2, 4};
5103 const int disjoint[] = {1, 0, 3};
5104 EXPECT_THAT(subset, IsSupersetOf(subset));
5105 EXPECT_THAT(subset, Not(IsSupersetOf(superset)));
5106 EXPECT_THAT(superset, IsSupersetOf(subset));
5107 EXPECT_THAT(subset, Not(IsSupersetOf(disjoint)));
5108 EXPECT_THAT(disjoint, Not(IsSupersetOf(subset)));
5109}
5110
5111TEST(IsSupersetOfTest, WorksWithDuplicates) {
5112 const int not_enough[] = {1, 2};
5113 const int enough[] = {1, 1, 2};
5114 const int expected[] = {1, 1};
5115 EXPECT_THAT(not_enough, Not(IsSupersetOf(expected)));
5116 EXPECT_THAT(enough, IsSupersetOf(expected));
5117}
5118
5119TEST(IsSupersetOfTest, WorksForEmpty) {
5120 vector<int> numbers;
5121 vector<int> expected;
5122 EXPECT_THAT(numbers, IsSupersetOf(expected));
5123 expected.push_back(1);
5124 EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
5125 expected.clear();
5126 numbers.push_back(1);
5127 numbers.push_back(2);
5128 EXPECT_THAT(numbers, IsSupersetOf(expected));
5129 expected.push_back(1);
5130 EXPECT_THAT(numbers, IsSupersetOf(expected));
5131 expected.push_back(2);
5132 EXPECT_THAT(numbers, IsSupersetOf(expected));
5133 expected.push_back(3);
5134 EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
5135}
5136
5137TEST(IsSupersetOfTest, WorksForStreamlike) {
5138 const int a[5] = {1, 2, 3, 4, 5};
5139 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5140
5141 vector<int> expected;
5142 expected.push_back(1);
5143 expected.push_back(2);
5144 expected.push_back(5);
5145 EXPECT_THAT(s, IsSupersetOf(expected));
5146
5147 expected.push_back(0);
5148 EXPECT_THAT(s, Not(IsSupersetOf(expected)));
5149}
5150
5151TEST(IsSupersetOfTest, TakesStlContainer) {
5152 const int actual[] = {3, 1, 2};
5153
5154 ::std::list<int> expected;
5155 expected.push_back(1);
5156 expected.push_back(3);
5157 EXPECT_THAT(actual, IsSupersetOf(expected));
5158
5159 expected.push_back(4);
5160 EXPECT_THAT(actual, Not(IsSupersetOf(expected)));
5161}
5162
5163TEST(IsSupersetOfTest, Describe) {
5164 typedef std::vector<int> IntVec;
5165 IntVec expected;
5166 expected.push_back(111);
5167 expected.push_back(222);
5168 expected.push_back(333);
5169 EXPECT_THAT(
5170 Describe<IntVec>(IsSupersetOf(expected)),
5171 Eq("a surjection from elements to requirements exists such that:\n"
5172 " - an element is equal to 111\n"
5173 " - an element is equal to 222\n"
5174 " - an element is equal to 333"));
5175}
5176
5177TEST(IsSupersetOfTest, DescribeNegation) {
5178 typedef std::vector<int> IntVec;
5179 IntVec expected;
5180 expected.push_back(111);
5181 expected.push_back(222);
5182 expected.push_back(333);
5183 EXPECT_THAT(
5184 DescribeNegation<IntVec>(IsSupersetOf(expected)),
5185 Eq("no surjection from elements to requirements exists such that:\n"
5186 " - an element is equal to 111\n"
5187 " - an element is equal to 222\n"
5188 " - an element is equal to 333"));
5189}
5190
5191TEST(IsSupersetOfTest, MatchAndExplain) {
5192 std::vector<int> v;
5193 v.push_back(2);
5194 v.push_back(3);
5195 std::vector<int> expected;
5196 expected.push_back(1);
5197 expected.push_back(2);
5198 StringMatchResultListener listener;
5199 ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
5200 << listener.str();
5201 EXPECT_THAT(listener.str(),
5202 Eq("where the following matchers don't match any elements:\n"
5203 "matcher #0: is equal to 1"));
5204
5205 v.push_back(1);
5206 listener.Clear();
5207 ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
5208 << listener.str();
5209 EXPECT_THAT(listener.str(), Eq("where:\n"
5210 " - element #0 is matched by matcher #1,\n"
5211 " - element #2 is matched by matcher #0"));
5212}
5213
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04005214TEST(IsSupersetOfTest, WorksForRhsInitializerList) {
5215 const int numbers[] = {1, 3, 6, 2, 4, 5};
5216 EXPECT_THAT(numbers, IsSupersetOf({1, 2}));
5217 EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0})));
5218}
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04005219
Abseil Team1ec20f82018-12-15 08:11:02 -05005220TEST(IsSupersetOfTest, WorksWithMoveOnly) {
5221 ContainerHelper helper;
5222 EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)})));
5223 helper.Call(MakeUniquePtrs({1, 2}));
5224 EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)}))));
5225 helper.Call(MakeUniquePtrs({2}));
5226}
5227
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04005228TEST(IsSubsetOfTest, WorksForNativeArray) {
5229 const int subset[] = {1, 4};
5230 const int superset[] = {1, 2, 4};
5231 const int disjoint[] = {1, 0, 3};
5232 EXPECT_THAT(subset, IsSubsetOf(subset));
5233 EXPECT_THAT(subset, IsSubsetOf(superset));
5234 EXPECT_THAT(superset, Not(IsSubsetOf(subset)));
5235 EXPECT_THAT(subset, Not(IsSubsetOf(disjoint)));
5236 EXPECT_THAT(disjoint, Not(IsSubsetOf(subset)));
5237}
5238
5239TEST(IsSubsetOfTest, WorksWithDuplicates) {
5240 const int not_enough[] = {1, 2};
5241 const int enough[] = {1, 1, 2};
5242 const int actual[] = {1, 1};
5243 EXPECT_THAT(actual, Not(IsSubsetOf(not_enough)));
5244 EXPECT_THAT(actual, IsSubsetOf(enough));
5245}
5246
5247TEST(IsSubsetOfTest, WorksForEmpty) {
5248 vector<int> numbers;
5249 vector<int> expected;
5250 EXPECT_THAT(numbers, IsSubsetOf(expected));
5251 expected.push_back(1);
5252 EXPECT_THAT(numbers, IsSubsetOf(expected));
5253 expected.clear();
5254 numbers.push_back(1);
5255 numbers.push_back(2);
5256 EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
5257 expected.push_back(1);
5258 EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
5259 expected.push_back(2);
5260 EXPECT_THAT(numbers, IsSubsetOf(expected));
5261 expected.push_back(3);
5262 EXPECT_THAT(numbers, IsSubsetOf(expected));
5263}
5264
5265TEST(IsSubsetOfTest, WorksForStreamlike) {
5266 const int a[5] = {1, 2};
5267 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5268
5269 vector<int> expected;
5270 expected.push_back(1);
5271 EXPECT_THAT(s, Not(IsSubsetOf(expected)));
5272 expected.push_back(2);
5273 expected.push_back(5);
5274 EXPECT_THAT(s, IsSubsetOf(expected));
5275}
5276
5277TEST(IsSubsetOfTest, TakesStlContainer) {
5278 const int actual[] = {3, 1, 2};
5279
5280 ::std::list<int> expected;
5281 expected.push_back(1);
5282 expected.push_back(3);
5283 EXPECT_THAT(actual, Not(IsSubsetOf(expected)));
5284
5285 expected.push_back(2);
5286 expected.push_back(4);
5287 EXPECT_THAT(actual, IsSubsetOf(expected));
5288}
5289
5290TEST(IsSubsetOfTest, Describe) {
5291 typedef std::vector<int> IntVec;
5292 IntVec expected;
5293 expected.push_back(111);
5294 expected.push_back(222);
5295 expected.push_back(333);
5296
5297 EXPECT_THAT(
5298 Describe<IntVec>(IsSubsetOf(expected)),
5299 Eq("an injection from elements to requirements exists such that:\n"
5300 " - an element is equal to 111\n"
5301 " - an element is equal to 222\n"
5302 " - an element is equal to 333"));
5303}
5304
5305TEST(IsSubsetOfTest, DescribeNegation) {
5306 typedef std::vector<int> IntVec;
5307 IntVec expected;
5308 expected.push_back(111);
5309 expected.push_back(222);
5310 expected.push_back(333);
5311 EXPECT_THAT(
5312 DescribeNegation<IntVec>(IsSubsetOf(expected)),
5313 Eq("no injection from elements to requirements exists such that:\n"
5314 " - an element is equal to 111\n"
5315 " - an element is equal to 222\n"
5316 " - an element is equal to 333"));
5317}
5318
5319TEST(IsSubsetOfTest, MatchAndExplain) {
5320 std::vector<int> v;
5321 v.push_back(2);
5322 v.push_back(3);
5323 std::vector<int> expected;
5324 expected.push_back(1);
5325 expected.push_back(2);
5326 StringMatchResultListener listener;
5327 ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
5328 << listener.str();
5329 EXPECT_THAT(listener.str(),
5330 Eq("where the following elements don't match any matchers:\n"
5331 "element #1: 3"));
5332
5333 expected.push_back(3);
5334 listener.Clear();
5335 ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
5336 << listener.str();
5337 EXPECT_THAT(listener.str(), Eq("where:\n"
5338 " - element #0 is matched by matcher #1,\n"
5339 " - element #1 is matched by matcher #2"));
5340}
5341
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04005342TEST(IsSubsetOfTest, WorksForRhsInitializerList) {
5343 const int numbers[] = {1, 2, 3};
5344 EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4}));
5345 EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2})));
5346}
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04005347
Abseil Team1ec20f82018-12-15 08:11:02 -05005348TEST(IsSubsetOfTest, WorksWithMoveOnly) {
5349 ContainerHelper helper;
5350 EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)})));
5351 helper.Call(MakeUniquePtrs({1}));
5352 EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)}))));
5353 helper.Call(MakeUniquePtrs({2}));
5354}
5355
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00005356// Tests using ElementsAre() and ElementsAreArray() with stream-like
5357// "containers".
5358
5359TEST(ElemensAreStreamTest, WorksForStreamlike) {
kosak2336e9c2014-07-28 22:57:30 +00005360 const int a[5] = {1, 2, 3, 4, 5};
kosak6414d802013-12-03 23:19:36 +00005361 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00005362 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
5363 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
5364}
5365
5366TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
kosak2336e9c2014-07-28 22:57:30 +00005367 const int a[5] = {1, 2, 3, 4, 5};
kosak6414d802013-12-03 23:19:36 +00005368 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00005369
5370 vector<int> expected;
5371 expected.push_back(1);
5372 expected.push_back(2);
5373 expected.push_back(3);
5374 expected.push_back(4);
5375 expected.push_back(5);
5376 EXPECT_THAT(s, ElementsAreArray(expected));
5377
5378 expected[3] = 0;
5379 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
5380}
5381
billydonahue1f5fdea2014-05-19 17:54:51 +00005382TEST(ElementsAreTest, WorksWithUncopyable) {
5383 Uncopyable objs[2];
5384 objs[0].set_value(-3);
5385 objs[1].set_value(1);
5386 EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
5387}
5388
Abseil Team1ec20f82018-12-15 08:11:02 -05005389TEST(ElementsAreTest, WorksWithMoveOnly) {
5390 ContainerHelper helper;
5391 EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2))));
5392 helper.Call(MakeUniquePtrs({1, 2}));
5393
5394 EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)})));
5395 helper.Call(MakeUniquePtrs({3, 4}));
5396}
5397
kosak06678922014-07-28 20:01:28 +00005398TEST(ElementsAreTest, TakesStlContainer) {
5399 const int actual[] = {3, 1, 2};
5400
5401 ::std::list<int> expected;
5402 expected.push_back(3);
5403 expected.push_back(1);
5404 expected.push_back(2);
5405 EXPECT_THAT(actual, ElementsAreArray(expected));
5406
5407 expected.push_back(4);
5408 EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
5409}
5410
zhanyong.wanfb25d532013-07-28 08:24:00 +00005411// Tests for UnorderedElementsAreArray()
5412
5413TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
kosak2336e9c2014-07-28 22:57:30 +00005414 const int a[] = {0, 1, 2, 3, 4};
kosak6414d802013-12-03 23:19:36 +00005415 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00005416 do {
5417 StringMatchResultListener listener;
5418 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
5419 s, &listener)) << listener.str();
5420 } while (std::next_permutation(s.begin(), s.end()));
5421}
5422
5423TEST(UnorderedElementsAreArrayTest, VectorBool) {
kosak2336e9c2014-07-28 22:57:30 +00005424 const bool a[] = {0, 1, 0, 1, 1};
5425 const bool b[] = {1, 0, 1, 1, 0};
kosak6414d802013-12-03 23:19:36 +00005426 std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a));
5427 std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b));
zhanyong.wanfb25d532013-07-28 08:24:00 +00005428 StringMatchResultListener listener;
5429 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
5430 actual, &listener)) << listener.str();
5431}
5432
zhanyong.wan5579c1a2013-07-30 06:16:21 +00005433TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
5434 // Streamlike 'container' provides only minimal iterator support.
5435 // Its iterators are tagged with input_iterator_tag, and it has no
5436 // size() or empty() methods.
kosak2336e9c2014-07-28 22:57:30 +00005437 const int a[5] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00005438 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan5579c1a2013-07-30 06:16:21 +00005439
5440 ::std::vector<int> expected;
5441 expected.push_back(1);
5442 expected.push_back(2);
5443 expected.push_back(3);
5444 expected.push_back(4);
5445 expected.push_back(5);
5446 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
5447
5448 expected.push_back(6);
5449 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
5450}
5451
kosak06678922014-07-28 20:01:28 +00005452TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
5453 const int actual[] = {3, 1, 2};
5454
5455 ::std::list<int> expected;
5456 expected.push_back(1);
5457 expected.push_back(2);
5458 expected.push_back(3);
5459 EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
5460
5461 expected.push_back(4);
5462 EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
5463}
5464
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00005465
5466TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
kosak2336e9c2014-07-28 22:57:30 +00005467 const int a[5] = {2, 1, 4, 5, 3};
5468 EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
5469 EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00005470}
5471
5472TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
Nico Weber09fd5b32017-05-15 17:07:03 -04005473 const std::string a[5] = {"a", "b", "c", "d", "e"};
kosak2336e9c2014-07-28 22:57:30 +00005474 EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
5475 EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00005476}
5477
5478TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
kosak2336e9c2014-07-28 22:57:30 +00005479 const int a[5] = {2, 1, 4, 5, 3};
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00005480 EXPECT_THAT(a, UnorderedElementsAreArray(
kosak2336e9c2014-07-28 22:57:30 +00005481 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00005482 EXPECT_THAT(a, Not(UnorderedElementsAreArray(
kosak2336e9c2014-07-28 22:57:30 +00005483 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00005484}
5485
5486TEST(UnorderedElementsAreArrayTest,
5487 TakesInitializerListOfDifferentTypedMatchers) {
kosak2336e9c2014-07-28 22:57:30 +00005488 const int a[5] = {2, 1, 4, 5, 3};
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00005489 // The compiler cannot infer the type of the initializer list if its
5490 // elements have different types. We must explicitly specify the
5491 // unified element type in this case.
5492 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
kosak2336e9c2014-07-28 22:57:30 +00005493 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00005494 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
kosak2336e9c2014-07-28 22:57:30 +00005495 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00005496}
5497
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00005498
Abseil Team1ec20f82018-12-15 08:11:02 -05005499TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) {
5500 ContainerHelper helper;
5501 EXPECT_CALL(helper,
5502 Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)})));
5503 helper.Call(MakeUniquePtrs({2, 1}));
5504}
5505
zhanyong.wanfb25d532013-07-28 08:24:00 +00005506class UnorderedElementsAreTest : public testing::Test {
5507 protected:
5508 typedef std::vector<int> IntVec;
5509};
5510
billydonahue1f5fdea2014-05-19 17:54:51 +00005511TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
5512 Uncopyable objs[2];
5513 objs[0].set_value(-3);
5514 objs[1].set_value(1);
5515 EXPECT_THAT(objs,
5516 UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
5517}
5518
zhanyong.wanfb25d532013-07-28 08:24:00 +00005519TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
kosak2336e9c2014-07-28 22:57:30 +00005520 const int a[] = {1, 2, 3};
kosak6414d802013-12-03 23:19:36 +00005521 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00005522 do {
5523 StringMatchResultListener listener;
5524 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5525 s, &listener)) << listener.str();
5526 } while (std::next_permutation(s.begin(), s.end()));
5527}
5528
5529TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
kosak2336e9c2014-07-28 22:57:30 +00005530 const int a[] = {1, 2, 3};
kosak6414d802013-12-03 23:19:36 +00005531 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00005532 std::vector<Matcher<int> > mv;
5533 mv.push_back(1);
5534 mv.push_back(2);
5535 mv.push_back(2);
5536 // The element with value '3' matches nothing: fail fast.
5537 StringMatchResultListener listener;
5538 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
5539 s, &listener)) << listener.str();
5540}
5541
zhanyong.wan5579c1a2013-07-30 06:16:21 +00005542TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
5543 // Streamlike 'container' provides only minimal iterator support.
5544 // Its iterators are tagged with input_iterator_tag, and it has no
5545 // size() or empty() methods.
kosak2336e9c2014-07-28 22:57:30 +00005546 const int a[5] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00005547 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan5579c1a2013-07-30 06:16:21 +00005548
5549 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
5550 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
5551}
5552
Abseil Team1ec20f82018-12-15 08:11:02 -05005553TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) {
5554 ContainerHelper helper;
5555 EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2))));
5556 helper.Call(MakeUniquePtrs({2, 1}));
5557}
5558
zhanyong.wanfb25d532013-07-28 08:24:00 +00005559// One naive implementation of the matcher runs in O(N!) time, which is too
5560// slow for many real-world inputs. This test shows that our matcher can match
5561// 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
5562// iterations and obviously effectively incomputable.
5563// [ RUN ] UnorderedElementsAreTest.Performance
5564// [ OK ] UnorderedElementsAreTest.Performance (4 ms)
5565TEST_F(UnorderedElementsAreTest, Performance) {
5566 std::vector<int> s;
5567 std::vector<Matcher<int> > mv;
5568 for (int i = 0; i < 100; ++i) {
5569 s.push_back(i);
5570 mv.push_back(_);
5571 }
5572 mv[50] = Eq(0);
5573 StringMatchResultListener listener;
5574 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
5575 s, &listener)) << listener.str();
5576}
5577
5578// Another variant of 'Performance' with similar expectations.
5579// [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
5580// [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
5581TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
5582 std::vector<int> s;
5583 std::vector<Matcher<int> > mv;
5584 for (int i = 0; i < 100; ++i) {
5585 s.push_back(i);
5586 if (i & 1) {
5587 mv.push_back(_);
5588 } else {
5589 mv.push_back(i);
5590 }
5591 }
5592 StringMatchResultListener listener;
5593 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
5594 s, &listener)) << listener.str();
5595}
5596
5597TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
5598 std::vector<int> v;
5599 v.push_back(4);
5600 StringMatchResultListener listener;
5601 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5602 v, &listener)) << listener.str();
5603 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
5604}
5605
5606TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
5607 std::vector<int> v;
5608 StringMatchResultListener listener;
5609 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5610 v, &listener)) << listener.str();
5611 EXPECT_THAT(listener.str(), Eq(""));
5612}
5613
5614TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
5615 std::vector<int> v;
5616 v.push_back(1);
5617 v.push_back(1);
5618 StringMatchResultListener listener;
5619 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
5620 v, &listener)) << listener.str();
5621 EXPECT_THAT(
5622 listener.str(),
5623 Eq("where the following matchers don't match any elements:\n"
5624 "matcher #1: is equal to 2"));
5625}
5626
5627TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
5628 std::vector<int> v;
5629 v.push_back(1);
5630 v.push_back(2);
5631 StringMatchResultListener listener;
5632 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
5633 v, &listener)) << listener.str();
5634 EXPECT_THAT(
5635 listener.str(),
5636 Eq("where the following elements don't match any matchers:\n"
5637 "element #1: 2"));
5638}
5639
5640TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
5641 std::vector<int> v;
5642 v.push_back(2);
5643 v.push_back(3);
5644 StringMatchResultListener listener;
5645 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
5646 v, &listener)) << listener.str();
5647 EXPECT_THAT(
5648 listener.str(),
5649 Eq("where"
5650 " the following matchers don't match any elements:\n"
5651 "matcher #0: is equal to 1\n"
5652 "and"
5653 " where"
5654 " the following elements don't match any matchers:\n"
5655 "element #1: 3"));
5656}
5657
5658// Test helper for formatting element, matcher index pairs in expectations.
Nico Weber09fd5b32017-05-15 17:07:03 -04005659static std::string EMString(int element, int matcher) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00005660 stringstream ss;
5661 ss << "(element #" << element << ", matcher #" << matcher << ")";
5662 return ss.str();
5663}
5664
5665TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
5666 // A situation where all elements and matchers have a match
5667 // associated with them, but the max matching is not perfect.
Nico Weber09fd5b32017-05-15 17:07:03 -04005668 std::vector<std::string> v;
zhanyong.wanfb25d532013-07-28 08:24:00 +00005669 v.push_back("a");
5670 v.push_back("b");
5671 v.push_back("c");
5672 StringMatchResultListener listener;
5673 EXPECT_FALSE(ExplainMatchResult(
5674 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
5675 << listener.str();
5676
Nico Weber09fd5b32017-05-15 17:07:03 -04005677 std::string prefix =
zhanyong.wanfb25d532013-07-28 08:24:00 +00005678 "where no permutation of the elements can satisfy all matchers, "
5679 "and the closest match is 2 of 3 matchers with the "
5680 "pairings:\n";
5681
5682 // We have to be a bit loose here, because there are 4 valid max matches.
5683 EXPECT_THAT(
5684 listener.str(),
5685 AnyOf(prefix + "{\n " + EMString(0, 0) +
5686 ",\n " + EMString(1, 2) + "\n}",
5687 prefix + "{\n " + EMString(0, 1) +
5688 ",\n " + EMString(1, 2) + "\n}",
5689 prefix + "{\n " + EMString(0, 0) +
5690 ",\n " + EMString(2, 2) + "\n}",
5691 prefix + "{\n " + EMString(0, 1) +
5692 ",\n " + EMString(2, 2) + "\n}"));
5693}
5694
5695TEST_F(UnorderedElementsAreTest, Describe) {
5696 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
5697 Eq("is empty"));
5698 EXPECT_THAT(
5699 Describe<IntVec>(UnorderedElementsAre(345)),
5700 Eq("has 1 element and that element is equal to 345"));
5701 EXPECT_THAT(
5702 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
5703 Eq("has 3 elements and there exists some permutation "
5704 "of elements such that:\n"
5705 " - element #0 is equal to 111, and\n"
5706 " - element #1 is equal to 222, and\n"
5707 " - element #2 is equal to 333"));
5708}
5709
5710TEST_F(UnorderedElementsAreTest, DescribeNegation) {
5711 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
5712 Eq("isn't empty"));
5713 EXPECT_THAT(
5714 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
5715 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
5716 EXPECT_THAT(
5717 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
5718 Eq("doesn't have 3 elements, or there exists no permutation "
5719 "of elements such that:\n"
5720 " - element #0 is equal to 123, and\n"
5721 " - element #1 is equal to 234, and\n"
5722 " - element #2 is equal to 345"));
5723}
5724
5725namespace {
5726
5727// Used as a check on the more complex max flow method used in the
5728// real testing::internal::FindMaxBipartiteMatching. This method is
5729// compatible but runs in worst-case factorial time, so we only
5730// use it in testing for small problem sizes.
5731template <typename Graph>
5732class BacktrackingMaxBPMState {
5733 public:
5734 // Does not take ownership of 'g'.
5735 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
5736
5737 ElementMatcherPairs Compute() {
5738 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
5739 return best_so_far_;
5740 }
5741 lhs_used_.assign(graph_->LhsSize(), kUnused);
5742 rhs_used_.assign(graph_->RhsSize(), kUnused);
5743 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
5744 matches_.clear();
5745 RecurseInto(irhs);
5746 if (best_so_far_.size() == graph_->RhsSize())
5747 break;
5748 }
5749 return best_so_far_;
5750 }
5751
5752 private:
5753 static const size_t kUnused = static_cast<size_t>(-1);
5754
5755 void PushMatch(size_t lhs, size_t rhs) {
5756 matches_.push_back(ElementMatcherPair(lhs, rhs));
5757 lhs_used_[lhs] = rhs;
5758 rhs_used_[rhs] = lhs;
5759 if (matches_.size() > best_so_far_.size()) {
5760 best_so_far_ = matches_;
5761 }
5762 }
5763
5764 void PopMatch() {
5765 const ElementMatcherPair& back = matches_.back();
5766 lhs_used_[back.first] = kUnused;
5767 rhs_used_[back.second] = kUnused;
5768 matches_.pop_back();
5769 }
5770
5771 bool RecurseInto(size_t irhs) {
5772 if (rhs_used_[irhs] != kUnused) {
5773 return true;
5774 }
5775 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
5776 if (lhs_used_[ilhs] != kUnused) {
5777 continue;
5778 }
5779 if (!graph_->HasEdge(ilhs, irhs)) {
5780 continue;
5781 }
5782 PushMatch(ilhs, irhs);
5783 if (best_so_far_.size() == graph_->RhsSize()) {
5784 return false;
5785 }
5786 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
5787 if (!RecurseInto(mi)) return false;
5788 }
5789 PopMatch();
5790 }
5791 return true;
5792 }
5793
5794 const Graph* graph_; // not owned
5795 std::vector<size_t> lhs_used_;
5796 std::vector<size_t> rhs_used_;
5797 ElementMatcherPairs matches_;
5798 ElementMatcherPairs best_so_far_;
5799};
5800
5801template <typename Graph>
5802const size_t BacktrackingMaxBPMState<Graph>::kUnused;
5803
5804} // namespace
5805
5806// Implement a simple backtracking algorithm to determine if it is possible
5807// to find one element per matcher, without reusing elements.
5808template <typename Graph>
5809ElementMatcherPairs
5810FindBacktrackingMaxBPM(const Graph& g) {
5811 return BacktrackingMaxBPMState<Graph>(&g).Compute();
5812}
5813
5814class BacktrackingBPMTest : public ::testing::Test { };
5815
5816// Tests the MaxBipartiteMatching algorithm with square matrices.
5817// The single int param is the # of nodes on each of the left and right sides.
Gennadiy Civila0d60be2019-04-18 09:44:23 -04005818class BipartiteTest : public ::testing::TestWithParam<size_t> {};
zhanyong.wanfb25d532013-07-28 08:24:00 +00005819
5820// Verify all match graphs up to some moderate number of edges.
5821TEST_P(BipartiteTest, Exhaustive) {
Enji Cooper3829b842019-03-08 11:09:00 -08005822 size_t nodes = GetParam();
zhanyong.wanfb25d532013-07-28 08:24:00 +00005823 MatchMatrix graph(nodes, nodes);
5824 do {
5825 ElementMatcherPairs matches =
5826 internal::FindMaxBipartiteMatching(graph);
5827 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
5828 << "graph: " << graph.DebugString();
5829 // Check that all elements of matches are in the graph.
5830 // Check that elements of first and second are unique.
5831 std::vector<bool> seen_element(graph.LhsSize());
5832 std::vector<bool> seen_matcher(graph.RhsSize());
5833 SCOPED_TRACE(PrintToString(matches));
5834 for (size_t i = 0; i < matches.size(); ++i) {
5835 size_t ilhs = matches[i].first;
5836 size_t irhs = matches[i].second;
5837 EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
5838 EXPECT_FALSE(seen_element[ilhs]);
5839 EXPECT_FALSE(seen_matcher[irhs]);
5840 seen_element[ilhs] = true;
5841 seen_matcher[irhs] = true;
5842 }
5843 } while (graph.NextGraph());
5844}
5845
misterg52ea4f72019-02-04 11:40:09 -05005846INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteTest,
Gennadiy Civila0d60be2019-04-18 09:44:23 -04005847 ::testing::Range(size_t{0}, size_t{5}));
zhanyong.wanfb25d532013-07-28 08:24:00 +00005848
5849// Parameterized by a pair interpreted as (LhsSize, RhsSize).
5850class BipartiteNonSquareTest
5851 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
5852};
5853
5854TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
5855 // .......
5856 // 0:-----\ :
5857 // 1:---\ | :
5858 // 2:---\ | :
5859 // 3:-\ | | :
5860 // :.......:
5861 // 0 1 2
5862 MatchMatrix g(4, 3);
Enji Cooper3829b842019-03-08 11:09:00 -08005863 static const size_t kEdges[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}};
kosak6414d802013-12-03 23:19:36 +00005864 for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00005865 g.SetEdge(kEdges[i][0], kEdges[i][1], true);
5866 }
5867 EXPECT_THAT(FindBacktrackingMaxBPM(g),
5868 ElementsAre(Pair(3, 0),
5869 Pair(AnyOf(1, 2), 1),
5870 Pair(0, 2))) << g.DebugString();
5871}
5872
5873// Verify a few nonsquare matrices.
5874TEST_P(BipartiteNonSquareTest, Exhaustive) {
5875 size_t nlhs = GetParam().first;
5876 size_t nrhs = GetParam().second;
5877 MatchMatrix graph(nlhs, nrhs);
5878 do {
5879 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5880 internal::FindMaxBipartiteMatching(graph).size())
5881 << "graph: " << graph.DebugString()
5882 << "\nbacktracking: "
5883 << PrintToString(FindBacktrackingMaxBPM(graph))
5884 << "\nmax flow: "
5885 << PrintToString(internal::FindMaxBipartiteMatching(graph));
5886 } while (graph.NextGraph());
5887}
5888
misterg52ea4f72019-02-04 11:40:09 -05005889INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteNonSquareTest,
zhanyong.wanfb25d532013-07-28 08:24:00 +00005890 testing::Values(
5891 std::make_pair(1, 2),
5892 std::make_pair(2, 1),
5893 std::make_pair(3, 2),
5894 std::make_pair(2, 3),
5895 std::make_pair(4, 1),
5896 std::make_pair(1, 4),
5897 std::make_pair(4, 3),
5898 std::make_pair(3, 4)));
5899
5900class BipartiteRandomTest
5901 : public ::testing::TestWithParam<std::pair<int, int> > {
5902};
5903
5904// Verifies a large sample of larger graphs.
5905TEST_P(BipartiteRandomTest, LargerNets) {
5906 int nodes = GetParam().first;
5907 int iters = GetParam().second;
Enji Cooper3829b842019-03-08 11:09:00 -08005908 MatchMatrix graph(static_cast<size_t>(nodes), static_cast<size_t>(nodes));
zhanyong.wanfb25d532013-07-28 08:24:00 +00005909
Enji Cooper3829b842019-03-08 11:09:00 -08005910 auto seed = static_cast<testing::internal::UInt32>(GTEST_FLAG(random_seed));
zhanyong.wanfb25d532013-07-28 08:24:00 +00005911 if (seed == 0) {
Enji Cooper3829b842019-03-08 11:09:00 -08005912 seed = static_cast<testing::internal::UInt32>(time(nullptr));
zhanyong.wanfb25d532013-07-28 08:24:00 +00005913 }
5914
5915 for (; iters > 0; --iters, ++seed) {
Enji Cooper3829b842019-03-08 11:09:00 -08005916 srand(static_cast<unsigned int>(seed));
zhanyong.wanfb25d532013-07-28 08:24:00 +00005917 graph.Randomize();
5918 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5919 internal::FindMaxBipartiteMatching(graph).size())
5920 << " graph: " << graph.DebugString()
5921 << "\nTo reproduce the failure, rerun the test with the flag"
5922 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
5923 }
5924}
5925
5926// Test argument is a std::pair<int, int> representing (nodes, iters).
misterg52ea4f72019-02-04 11:40:09 -05005927INSTANTIATE_TEST_SUITE_P(Samples, BipartiteRandomTest,
zhanyong.wanfb25d532013-07-28 08:24:00 +00005928 testing::Values(
5929 std::make_pair(5, 10000),
5930 std::make_pair(6, 5000),
5931 std::make_pair(7, 2000),
5932 std::make_pair(8, 500),
5933 std::make_pair(9, 100)));
5934
zhanyong.wan736baa82010-09-27 17:44:16 +00005935// Tests IsReadableTypeName().
5936
5937TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
5938 EXPECT_TRUE(IsReadableTypeName("int"));
5939 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
5940 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
5941 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
5942}
5943
5944TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
5945 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
5946 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
5947 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
5948}
5949
5950TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
5951 EXPECT_FALSE(
5952 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
5953 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
5954}
5955
5956TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
5957 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
5958}
5959
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005960// Tests FormatMatcherDescription().
5961
5962TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
5963 EXPECT_EQ("is even",
zhanyong.wanb4140802010-06-08 22:53:57 +00005964 FormatMatcherDescription(false, "IsEven", Strings()));
5965 EXPECT_EQ("not (is even)",
5966 FormatMatcherDescription(true, "IsEven", Strings()));
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005967
kosak2336e9c2014-07-28 22:57:30 +00005968 const char* params[] = {"5"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005969 EXPECT_EQ("equals 5",
zhanyong.wanb4140802010-06-08 22:53:57 +00005970 FormatMatcherDescription(false, "Equals",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005971 Strings(params, params + 1)));
5972
kosak2336e9c2014-07-28 22:57:30 +00005973 const char* params2[] = {"5", "8"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005974 EXPECT_EQ("is in range (5, 8)",
zhanyong.wanb4140802010-06-08 22:53:57 +00005975 FormatMatcherDescription(false, "IsInRange",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005976 Strings(params2, params2 + 2)));
5977}
5978
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00005979// Tests PolymorphicMatcher::mutable_impl().
5980TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
5981 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5982 DivisibleByImpl& impl = m.mutable_impl();
5983 EXPECT_EQ(42, impl.divider());
5984
5985 impl.set_divider(0);
5986 EXPECT_EQ(0, m.mutable_impl().divider());
5987}
5988
5989// Tests PolymorphicMatcher::impl().
5990TEST(PolymorphicMatcherTest, CanAccessImpl) {
5991 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5992 const DivisibleByImpl& impl = m.impl();
5993 EXPECT_EQ(42, impl.divider());
5994}
5995
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005996TEST(MatcherTupleTest, ExplainsMatchFailure) {
5997 stringstream ss1;
Abseil Team7d3b73c2018-10-09 14:50:26 -04005998 ExplainMatchFailureTupleTo(
5999 std::make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
6000 std::make_tuple('a', 10), &ss1);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00006001 EXPECT_EQ("", ss1.str()); // Successful match.
6002
6003 stringstream ss2;
Abseil Team7d3b73c2018-10-09 14:50:26 -04006004 ExplainMatchFailureTupleTo(
6005 std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
6006 std::make_tuple(2, 'b'), &ss2);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00006007 EXPECT_EQ(" Expected arg #0: is > 5\n"
6008 " Actual: 2, which is 3 less than 5\n"
zhanyong.wand60c5f42010-07-21 22:21:07 +00006009 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
6010 " Actual: 'b' (98, 0x62)\n",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00006011 ss2.str()); // Failed match where both arguments need explanation.
6012
6013 stringstream ss3;
Abseil Team7d3b73c2018-10-09 14:50:26 -04006014 ExplainMatchFailureTupleTo(
6015 std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
6016 std::make_tuple(2, 'a'), &ss3);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00006017 EXPECT_EQ(" Expected arg #0: is > 5\n"
6018 " Actual: 2, which is 3 less than 5\n",
6019 ss3.str()); // Failed match where only one argument needs
6020 // explanation.
6021}
6022
zhanyong.wan33605ba2010-04-22 23:37:47 +00006023// Tests Each().
6024
6025TEST(EachTest, ExplainsMatchResultCorrectly) {
6026 set<int> a; // empty
6027
6028 Matcher<set<int> > m = Each(2);
6029 EXPECT_EQ("", Explain(m, a));
6030
zhanyong.wan736baa82010-09-27 17:44:16 +00006031 Matcher<const int(&)[1]> n = Each(1); // NOLINT
zhanyong.wan33605ba2010-04-22 23:37:47 +00006032
kosak2336e9c2014-07-28 22:57:30 +00006033 const int b[1] = {1};
zhanyong.wan33605ba2010-04-22 23:37:47 +00006034 EXPECT_EQ("", Explain(n, b));
6035
6036 n = Each(3);
6037 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
6038
6039 a.insert(1);
6040 a.insert(2);
6041 a.insert(3);
6042 m = Each(GreaterThan(0));
6043 EXPECT_EQ("", Explain(m, a));
6044
6045 m = Each(GreaterThan(10));
6046 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
6047 Explain(m, a));
6048}
6049
6050TEST(EachTest, DescribesItselfCorrectly) {
6051 Matcher<vector<int> > m = Each(1);
6052 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
6053
6054 Matcher<vector<int> > m2 = Not(m);
6055 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
6056}
6057
6058TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
6059 vector<int> some_vector;
6060 EXPECT_THAT(some_vector, Each(1));
6061 some_vector.push_back(3);
6062 EXPECT_THAT(some_vector, Not(Each(1)));
6063 EXPECT_THAT(some_vector, Each(3));
6064 some_vector.push_back(1);
6065 some_vector.push_back(2);
6066 EXPECT_THAT(some_vector, Not(Each(3)));
6067 EXPECT_THAT(some_vector, Each(Lt(3.5)));
6068
Nico Weber09fd5b32017-05-15 17:07:03 -04006069 vector<std::string> another_vector;
zhanyong.wan33605ba2010-04-22 23:37:47 +00006070 another_vector.push_back("fee");
Nico Weber09fd5b32017-05-15 17:07:03 -04006071 EXPECT_THAT(another_vector, Each(std::string("fee")));
zhanyong.wan33605ba2010-04-22 23:37:47 +00006072 another_vector.push_back("fie");
6073 another_vector.push_back("foe");
6074 another_vector.push_back("fum");
Nico Weber09fd5b32017-05-15 17:07:03 -04006075 EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));
zhanyong.wan33605ba2010-04-22 23:37:47 +00006076}
6077
6078TEST(EachTest, MatchesMapWhenAllElementsMatch) {
6079 map<const char*, int> my_map;
6080 const char* bar = "a string";
6081 my_map[bar] = 2;
6082 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
6083
Nico Weber09fd5b32017-05-15 17:07:03 -04006084 map<std::string, int> another_map;
6085 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
zhanyong.wan33605ba2010-04-22 23:37:47 +00006086 another_map["fee"] = 1;
Nico Weber09fd5b32017-05-15 17:07:03 -04006087 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
zhanyong.wan33605ba2010-04-22 23:37:47 +00006088 another_map["fie"] = 2;
6089 another_map["foe"] = 3;
6090 another_map["fum"] = 4;
Nico Weber09fd5b32017-05-15 17:07:03 -04006091 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));
6092 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));
zhanyong.wan33605ba2010-04-22 23:37:47 +00006093 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
6094}
6095
6096TEST(EachTest, AcceptsMatcher) {
kosak2336e9c2014-07-28 22:57:30 +00006097 const int a[] = {1, 2, 3};
zhanyong.wan33605ba2010-04-22 23:37:47 +00006098 EXPECT_THAT(a, Each(Gt(0)));
6099 EXPECT_THAT(a, Not(Each(Gt(1))));
6100}
6101
6102TEST(EachTest, WorksForNativeArrayAsTuple) {
kosak2336e9c2014-07-28 22:57:30 +00006103 const int a[] = {1, 2};
zhanyong.wan33605ba2010-04-22 23:37:47 +00006104 const int* const pointer = a;
Abseil Team7d3b73c2018-10-09 14:50:26 -04006105 EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0)));
6106 EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1))));
zhanyong.wan33605ba2010-04-22 23:37:47 +00006107}
6108
Abseil Team1ec20f82018-12-15 08:11:02 -05006109TEST(EachTest, WorksWithMoveOnly) {
6110 ContainerHelper helper;
6111 EXPECT_CALL(helper, Call(Each(Pointee(Gt(0)))));
6112 helper.Call(MakeUniquePtrs({1, 2}));
6113}
6114
zhanyong.wanab5b77c2010-05-17 19:32:48 +00006115// For testing Pointwise().
6116class IsHalfOfMatcher {
6117 public:
6118 template <typename T1, typename T2>
Abseil Team7d3b73c2018-10-09 14:50:26 -04006119 bool MatchAndExplain(const std::tuple<T1, T2>& a_pair,
zhanyong.wanab5b77c2010-05-17 19:32:48 +00006120 MatchResultListener* listener) const {
Abseil Team7d3b73c2018-10-09 14:50:26 -04006121 if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) {
6122 *listener << "where the second is " << std::get<1>(a_pair);
zhanyong.wanab5b77c2010-05-17 19:32:48 +00006123 return true;
6124 } else {
Abseil Team7d3b73c2018-10-09 14:50:26 -04006125 *listener << "where the second/2 is " << std::get<1>(a_pair) / 2;
zhanyong.wanab5b77c2010-05-17 19:32:48 +00006126 return false;
6127 }
6128 }
6129
6130 void DescribeTo(ostream* os) const {
6131 *os << "are a pair where the first is half of the second";
6132 }
6133
6134 void DescribeNegationTo(ostream* os) const {
6135 *os << "are a pair where the first isn't half of the second";
6136 }
6137};
6138
6139PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
6140 return MakePolymorphicMatcher(IsHalfOfMatcher());
6141}
6142
6143TEST(PointwiseTest, DescribesSelf) {
6144 vector<int> rhs;
6145 rhs.push_back(1);
6146 rhs.push_back(2);
6147 rhs.push_back(3);
6148 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
6149 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
6150 "in { 1, 2, 3 } are a pair where the first is half of the second",
6151 Describe(m));
6152 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
6153 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
6154 "where the first isn't half of the second",
6155 DescribeNegation(m));
6156}
6157
6158TEST(PointwiseTest, MakesCopyOfRhs) {
6159 list<signed char> rhs;
6160 rhs.push_back(2);
6161 rhs.push_back(4);
6162
kosak2336e9c2014-07-28 22:57:30 +00006163 int lhs[] = {1, 2};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00006164 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
6165 EXPECT_THAT(lhs, m);
6166
6167 // Changing rhs now shouldn't affect m, which made a copy of rhs.
6168 rhs.push_back(6);
6169 EXPECT_THAT(lhs, m);
6170}
6171
6172TEST(PointwiseTest, WorksForLhsNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00006173 const int lhs[] = {1, 2, 3};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00006174 vector<int> rhs;
6175 rhs.push_back(2);
6176 rhs.push_back(4);
6177 rhs.push_back(6);
6178 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
6179 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
6180}
6181
6182TEST(PointwiseTest, WorksForRhsNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00006183 const int rhs[] = {1, 2, 3};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00006184 vector<int> lhs;
6185 lhs.push_back(2);
6186 lhs.push_back(4);
6187 lhs.push_back(6);
6188 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
6189 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
6190}
6191
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04006192// Test is effective only with sanitizers.
6193TEST(PointwiseTest, WorksForVectorOfBool) {
6194 vector<bool> rhs(3, false);
6195 rhs[1] = true;
6196 vector<bool> lhs = rhs;
6197 EXPECT_THAT(lhs, Pointwise(Eq(), rhs));
6198 rhs[0] = true;
6199 EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs)));
6200}
6201
kosak2336e9c2014-07-28 22:57:30 +00006202
6203TEST(PointwiseTest, WorksForRhsInitializerList) {
6204 const vector<int> lhs{2, 4, 6};
6205 EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
6206 EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
6207}
6208
kosak2336e9c2014-07-28 22:57:30 +00006209
zhanyong.wanab5b77c2010-05-17 19:32:48 +00006210TEST(PointwiseTest, RejectsWrongSize) {
kosak2336e9c2014-07-28 22:57:30 +00006211 const double lhs[2] = {1, 2};
6212 const int rhs[1] = {0};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00006213 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
6214 EXPECT_EQ("which contains 2 values",
6215 Explain(Pointwise(Gt(), rhs), lhs));
6216
kosak2336e9c2014-07-28 22:57:30 +00006217 const int rhs2[3] = {0, 1, 2};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00006218 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
6219}
6220
6221TEST(PointwiseTest, RejectsWrongContent) {
kosak2336e9c2014-07-28 22:57:30 +00006222 const double lhs[3] = {1, 2, 3};
6223 const int rhs[3] = {2, 6, 4};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00006224 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
6225 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
6226 "where the second/2 is 3",
6227 Explain(Pointwise(IsHalfOf(), rhs), lhs));
6228}
6229
6230TEST(PointwiseTest, AcceptsCorrectContent) {
kosak2336e9c2014-07-28 22:57:30 +00006231 const double lhs[3] = {1, 2, 3};
6232 const int rhs[3] = {2, 4, 6};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00006233 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
6234 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
6235}
6236
6237TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
kosak2336e9c2014-07-28 22:57:30 +00006238 const double lhs[3] = {1, 2, 3};
6239 const int rhs[3] = {2, 4, 6};
Abseil Team7d3b73c2018-10-09 14:50:26 -04006240 const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00006241 EXPECT_THAT(lhs, Pointwise(m1, rhs));
6242 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
6243
Abseil Team7d3b73c2018-10-09 14:50:26 -04006244 // This type works as a std::tuple<const double&, const int&> can be
6245 // implicitly cast to std::tuple<double, int>.
6246 const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00006247 EXPECT_THAT(lhs, Pointwise(m2, rhs));
6248 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
6249}
6250
Abseil Team1ec20f82018-12-15 08:11:02 -05006251MATCHER(PointeeEquals, "Points to an equal value") {
6252 return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)),
6253 ::testing::get<0>(arg), result_listener);
6254}
6255
6256TEST(PointwiseTest, WorksWithMoveOnly) {
6257 ContainerHelper helper;
6258 EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2})));
6259 helper.Call(MakeUniquePtrs({1, 2}));
6260}
6261
kosak2336e9c2014-07-28 22:57:30 +00006262TEST(UnorderedPointwiseTest, DescribesSelf) {
6263 vector<int> rhs;
6264 rhs.push_back(1);
6265 rhs.push_back(2);
6266 rhs.push_back(3);
6267 const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
6268 EXPECT_EQ(
6269 "has 3 elements and there exists some permutation of elements such "
6270 "that:\n"
6271 " - element #0 and 1 are a pair where the first is half of the second, "
6272 "and\n"
6273 " - element #1 and 2 are a pair where the first is half of the second, "
6274 "and\n"
6275 " - element #2 and 3 are a pair where the first is half of the second",
6276 Describe(m));
6277 EXPECT_EQ(
6278 "doesn't have 3 elements, or there exists no permutation of elements "
6279 "such that:\n"
6280 " - element #0 and 1 are a pair where the first is half of the second, "
6281 "and\n"
6282 " - element #1 and 2 are a pair where the first is half of the second, "
6283 "and\n"
6284 " - element #2 and 3 are a pair where the first is half of the second",
6285 DescribeNegation(m));
6286}
6287
6288TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
6289 list<signed char> rhs;
6290 rhs.push_back(2);
6291 rhs.push_back(4);
6292
6293 int lhs[] = {2, 1};
6294 const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
6295 EXPECT_THAT(lhs, m);
6296
6297 // Changing rhs now shouldn't affect m, which made a copy of rhs.
6298 rhs.push_back(6);
6299 EXPECT_THAT(lhs, m);
6300}
6301
6302TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
6303 const int lhs[] = {1, 2, 3};
6304 vector<int> rhs;
6305 rhs.push_back(4);
6306 rhs.push_back(6);
6307 rhs.push_back(2);
6308 EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
6309 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
6310}
6311
6312TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
6313 const int rhs[] = {1, 2, 3};
6314 vector<int> lhs;
6315 lhs.push_back(4);
6316 lhs.push_back(2);
6317 lhs.push_back(6);
6318 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
6319 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
6320}
6321
kosak2336e9c2014-07-28 22:57:30 +00006322
6323TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
6324 const vector<int> lhs{2, 4, 6};
6325 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
6326 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
6327}
6328
kosak2336e9c2014-07-28 22:57:30 +00006329
6330TEST(UnorderedPointwiseTest, RejectsWrongSize) {
6331 const double lhs[2] = {1, 2};
6332 const int rhs[1] = {0};
6333 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
6334 EXPECT_EQ("which has 2 elements",
6335 Explain(UnorderedPointwise(Gt(), rhs), lhs));
6336
6337 const int rhs2[3] = {0, 1, 2};
6338 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
6339}
6340
6341TEST(UnorderedPointwiseTest, RejectsWrongContent) {
6342 const double lhs[3] = {1, 2, 3};
6343 const int rhs[3] = {2, 6, 6};
6344 EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
6345 EXPECT_EQ("where the following elements don't match any matchers:\n"
6346 "element #1: 2",
6347 Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
6348}
6349
6350TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
6351 const double lhs[3] = {1, 2, 3};
6352 const int rhs[3] = {2, 4, 6};
6353 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
6354}
6355
6356TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
6357 const double lhs[3] = {1, 2, 3};
6358 const int rhs[3] = {6, 4, 2};
6359 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
6360}
6361
6362TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
6363 const double lhs[3] = {1, 2, 3};
6364 const int rhs[3] = {4, 6, 2};
Abseil Team7d3b73c2018-10-09 14:50:26 -04006365 const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
kosak2336e9c2014-07-28 22:57:30 +00006366 EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
6367
Abseil Team7d3b73c2018-10-09 14:50:26 -04006368 // This type works as a std::tuple<const double&, const int&> can be
6369 // implicitly cast to std::tuple<double, int>.
6370 const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
kosak2336e9c2014-07-28 22:57:30 +00006371 EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
6372}
6373
Abseil Team1ec20f82018-12-15 08:11:02 -05006374TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {
6375 ContainerHelper helper;
6376 EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(),
6377 std::vector<int>{1, 2})));
6378 helper.Call(MakeUniquePtrs({2, 1}));
6379}
6380
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04006381// Sample optional type implementation with minimal requirements for use with
6382// Optional matcher.
Abseil Team9acd0652019-01-12 15:41:51 -05006383template <typename T>
6384class SampleOptional {
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04006385 public:
Abseil Team9acd0652019-01-12 15:41:51 -05006386 using value_type = T;
6387 explicit SampleOptional(T value)
6388 : value_(std::move(value)), has_value_(true) {}
6389 SampleOptional() : value_(), has_value_(false) {}
6390 operator bool() const { return has_value_; }
6391 const T& operator*() const { return value_; }
6392
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04006393 private:
Abseil Team9acd0652019-01-12 15:41:51 -05006394 T value_;
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04006395 bool has_value_;
6396};
6397
6398TEST(OptionalTest, DescribesSelf) {
Abseil Team9acd0652019-01-12 15:41:51 -05006399 const Matcher<SampleOptional<int>> m = Optional(Eq(1));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04006400 EXPECT_EQ("value is equal to 1", Describe(m));
6401}
6402
6403TEST(OptionalTest, ExplainsSelf) {
Abseil Team9acd0652019-01-12 15:41:51 -05006404 const Matcher<SampleOptional<int>> m = Optional(Eq(1));
6405 EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptional<int>(1)));
6406 EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptional<int>(2)));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04006407}
6408
6409TEST(OptionalTest, MatchesNonEmptyOptional) {
Abseil Team9acd0652019-01-12 15:41:51 -05006410 const Matcher<SampleOptional<int>> m1 = Optional(1);
6411 const Matcher<SampleOptional<int>> m2 = Optional(Eq(2));
6412 const Matcher<SampleOptional<int>> m3 = Optional(Lt(3));
6413 SampleOptional<int> opt(1);
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04006414 EXPECT_TRUE(m1.Matches(opt));
6415 EXPECT_FALSE(m2.Matches(opt));
6416 EXPECT_TRUE(m3.Matches(opt));
6417}
6418
6419TEST(OptionalTest, DoesNotMatchNullopt) {
Abseil Team9acd0652019-01-12 15:41:51 -05006420 const Matcher<SampleOptional<int>> m = Optional(1);
6421 SampleOptional<int> empty;
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04006422 EXPECT_FALSE(m.Matches(empty));
6423}
6424
Abseil Team9acd0652019-01-12 15:41:51 -05006425TEST(OptionalTest, WorksWithMoveOnly) {
6426 Matcher<SampleOptional<std::unique_ptr<int>>> m = Optional(Eq(nullptr));
6427 EXPECT_TRUE(m.Matches(SampleOptional<std::unique_ptr<int>>(nullptr)));
6428}
6429
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05006430class SampleVariantIntString {
6431 public:
6432 SampleVariantIntString(int i) : i_(i), has_int_(true) {}
6433 SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {}
6434
6435 template <typename T>
6436 friend bool holds_alternative(const SampleVariantIntString& value) {
6437 return value.has_int_ == internal::IsSame<T, int>::value;
6438 }
6439
6440 template <typename T>
6441 friend const T& get(const SampleVariantIntString& value) {
Abseil Team4bb49ed2018-10-04 18:28:05 -04006442 return value.get_impl(static_cast<T*>(nullptr));
Xiaoyi Zhang190e2cd2018-02-27 11:36:21 -05006443 }
6444
6445 private:
6446 const int& get_impl(int*) const { return i_; }
6447 const std::string& get_impl(std::string*) const { return s_; }
6448
6449 int i_;
6450 std::string s_;
6451 bool has_int_;
6452};
6453
6454TEST(VariantTest, DescribesSelf) {
6455 const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6456 EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type "
6457 "'.*' and the value is equal to 1"));
6458}
6459
6460TEST(VariantTest, ExplainsSelf) {
6461 const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6462 EXPECT_THAT(Explain(m, SampleVariantIntString(1)),
6463 ContainsRegex("whose value 1"));
6464 EXPECT_THAT(Explain(m, SampleVariantIntString("A")),
6465 HasSubstr("whose value is not of type '"));
6466 EXPECT_THAT(Explain(m, SampleVariantIntString(2)),
6467 "whose value 2 doesn't match");
6468}
6469
6470TEST(VariantTest, FullMatch) {
6471 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6472 EXPECT_TRUE(m.Matches(SampleVariantIntString(1)));
6473
6474 m = VariantWith<std::string>(Eq("1"));
6475 EXPECT_TRUE(m.Matches(SampleVariantIntString("1")));
6476}
6477
6478TEST(VariantTest, TypeDoesNotMatch) {
6479 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6480 EXPECT_FALSE(m.Matches(SampleVariantIntString("1")));
6481
6482 m = VariantWith<std::string>(Eq("1"));
6483 EXPECT_FALSE(m.Matches(SampleVariantIntString(1)));
6484}
6485
6486TEST(VariantTest, InnerDoesNotMatch) {
6487 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6488 EXPECT_FALSE(m.Matches(SampleVariantIntString(2)));
6489
6490 m = VariantWith<std::string>(Eq("1"));
6491 EXPECT_FALSE(m.Matches(SampleVariantIntString("2")));
6492}
6493
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04006494class SampleAnyType {
6495 public:
6496 explicit SampleAnyType(int i) : index_(0), i_(i) {}
6497 explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {}
6498
6499 template <typename T>
6500 friend const T* any_cast(const SampleAnyType* any) {
Abseil Team4bb49ed2018-10-04 18:28:05 -04006501 return any->get_impl(static_cast<T*>(nullptr));
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04006502 }
6503
6504 private:
6505 int index_;
6506 int i_;
6507 std::string s_;
6508
Abseil Team4bb49ed2018-10-04 18:28:05 -04006509 const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; }
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04006510 const std::string* get_impl(std::string*) const {
Abseil Team4bb49ed2018-10-04 18:28:05 -04006511 return index_ == 1 ? &s_ : nullptr;
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04006512 }
6513};
6514
6515TEST(AnyWithTest, FullMatch) {
6516 Matcher<SampleAnyType> m = AnyWith<int>(Eq(1));
6517 EXPECT_TRUE(m.Matches(SampleAnyType(1)));
6518}
6519
6520TEST(AnyWithTest, TestBadCastType) {
6521 Matcher<SampleAnyType> m = AnyWith<std::string>(Eq("fail"));
6522 EXPECT_FALSE(m.Matches(SampleAnyType(1)));
6523}
6524
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04006525TEST(AnyWithTest, TestUseInContainers) {
6526 std::vector<SampleAnyType> a;
6527 a.emplace_back(1);
6528 a.emplace_back(2);
6529 a.emplace_back(3);
6530 EXPECT_THAT(
6531 a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)}));
6532
6533 std::vector<SampleAnyType> b;
6534 b.emplace_back("hello");
6535 b.emplace_back("merhaba");
6536 b.emplace_back("salut");
6537 EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>("hello"),
6538 AnyWith<std::string>("merhaba"),
6539 AnyWith<std::string>("salut")}));
6540}
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04006541TEST(AnyWithTest, TestCompare) {
6542 EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0)));
6543}
6544
6545TEST(AnyWithTest, DescribesSelf) {
6546 const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
6547 EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type "
6548 "'.*' and the value is equal to 1"));
6549}
6550
6551TEST(AnyWithTest, ExplainsSelf) {
6552 const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
6553
6554 EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1"));
6555 EXPECT_THAT(Explain(m, SampleAnyType("A")),
6556 HasSubstr("whose value is not of type '"));
6557 EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match");
6558}
6559
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04006560TEST(PointeeTest, WorksOnMoveOnlyType) {
6561 std::unique_ptr<int> p(new int(3));
6562 EXPECT_THAT(p, Pointee(Eq(3)));
6563 EXPECT_THAT(p, Not(Pointee(Eq(2))));
6564}
6565
6566TEST(NotTest, WorksOnMoveOnlyType) {
6567 std::unique_ptr<int> p(new int(3));
6568 EXPECT_THAT(p, Pointee(Eq(3)));
6569 EXPECT_THAT(p, Not(Pointee(Eq(2))));
6570}
6571
Abseil Teama42cdf22018-12-03 10:48:03 -05006572// Tests Args<k0, ..., kn>(m).
6573
6574TEST(ArgsTest, AcceptsZeroTemplateArg) {
6575 const std::tuple<int, bool> t(5, true);
6576 EXPECT_THAT(t, Args<>(Eq(std::tuple<>())));
6577 EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>()))));
6578}
6579
6580TEST(ArgsTest, AcceptsOneTemplateArg) {
6581 const std::tuple<int, bool> t(5, true);
6582 EXPECT_THAT(t, Args<0>(Eq(std::make_tuple(5))));
6583 EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(true))));
6584 EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(false)))));
6585}
6586
6587TEST(ArgsTest, AcceptsTwoTemplateArgs) {
6588 const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
6589
6590 EXPECT_THAT(t, (Args<0, 1>(Lt())));
6591 EXPECT_THAT(t, (Args<1, 2>(Lt())));
6592 EXPECT_THAT(t, Not(Args<0, 2>(Gt())));
6593}
6594
6595TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
6596 const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
6597 EXPECT_THAT(t, (Args<0, 0>(Eq())));
6598 EXPECT_THAT(t, Not(Args<1, 1>(Ne())));
6599}
6600
6601TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {
6602 const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
6603 EXPECT_THAT(t, (Args<2, 0>(Gt())));
6604 EXPECT_THAT(t, Not(Args<2, 1>(Lt())));
6605}
6606
6607MATCHER(SumIsZero, "") {
6608 return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0;
6609}
6610
6611TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {
6612 EXPECT_THAT(std::make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero())));
6613 EXPECT_THAT(std::make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero())));
6614}
6615
6616TEST(ArgsTest, CanBeNested) {
6617 const std::tuple<short, int, long, int> t(4, 5, 6L, 6); // NOLINT
6618 EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));
6619 EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));
6620}
6621
6622TEST(ArgsTest, CanMatchTupleByValue) {
6623 typedef std::tuple<char, int, int> Tuple3;
6624 const Matcher<Tuple3> m = Args<1, 2>(Lt());
6625 EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2)));
6626 EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2)));
6627}
6628
6629TEST(ArgsTest, CanMatchTupleByReference) {
6630 typedef std::tuple<char, char, int> Tuple3;
6631 const Matcher<const Tuple3&> m = Args<0, 1>(Lt());
6632 EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2)));
6633 EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2)));
6634}
6635
6636// Validates that arg is printed as str.
6637MATCHER_P(PrintsAs, str, "") {
6638 return testing::PrintToString(arg) == str;
6639}
6640
6641TEST(ArgsTest, AcceptsTenTemplateArgs) {
6642 EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
6643 (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
6644 PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
6645 EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
6646 Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
6647 PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
6648}
6649
6650TEST(ArgsTest, DescirbesSelfCorrectly) {
6651 const Matcher<std::tuple<int, bool, char> > m = Args<2, 0>(Lt());
6652 EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where "
6653 "the first < the second",
6654 Describe(m));
6655}
6656
6657TEST(ArgsTest, DescirbesNestedArgsCorrectly) {
6658 const Matcher<const std::tuple<int, bool, char, int>&> m =
6659 Args<0, 2, 3>(Args<2, 0>(Lt()));
6660 EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple "
6661 "whose fields (#2, #0) are a pair where the first < the second",
6662 Describe(m));
6663}
6664
6665TEST(ArgsTest, DescribesNegationCorrectly) {
6666 const Matcher<std::tuple<int, char> > m = Args<1, 0>(Gt());
6667 EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair "
6668 "where the first > the second",
6669 DescribeNegation(m));
6670}
6671
6672TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) {
6673 const Matcher<std::tuple<bool, int, int> > m = Args<1, 2>(Eq());
6674 EXPECT_EQ("whose fields (#1, #2) are (42, 42)",
6675 Explain(m, std::make_tuple(false, 42, 42)));
6676 EXPECT_EQ("whose fields (#1, #2) are (42, 43)",
6677 Explain(m, std::make_tuple(false, 42, 43)));
6678}
6679
6680// For testing Args<>'s explanation.
6681class LessThanMatcher : public MatcherInterface<std::tuple<char, int> > {
6682 public:
Enji Cooper1c227972019-02-13 10:31:35 -08006683 void DescribeTo(::std::ostream* /*os*/) const override {}
Abseil Teama42cdf22018-12-03 10:48:03 -05006684
Enji Cooper53884732019-02-13 09:45:53 -08006685 bool MatchAndExplain(std::tuple<char, int> value,
6686 MatchResultListener* listener) const override {
Abseil Teama42cdf22018-12-03 10:48:03 -05006687 const int diff = std::get<0>(value) - std::get<1>(value);
6688 if (diff > 0) {
6689 *listener << "where the first value is " << diff
6690 << " more than the second";
6691 }
6692 return diff < 0;
6693 }
6694};
6695
6696Matcher<std::tuple<char, int> > LessThan() {
6697 return MakeMatcher(new LessThanMatcher);
6698}
6699
6700TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) {
6701 const Matcher<std::tuple<char, int, int> > m = Args<0, 2>(LessThan());
6702 EXPECT_EQ(
6703 "whose fields (#0, #2) are ('a' (97, 0x61), 42), "
6704 "where the first value is 55 more than the second",
6705 Explain(m, std::make_tuple('a', 42, 42)));
6706 EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)",
6707 Explain(m, std::make_tuple('\0', 42, 43)));
6708}
Gennadiy Civil0cd6a4f2018-04-05 11:34:19 -04006709
Abseil Team6ef59132018-12-11 14:10:54 -05006710class PredicateFormatterFromMatcherTest : public ::testing::Test {
6711 protected:
6712 enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky };
6713
6714 // A matcher that can return different results when used multiple times on the
6715 // same input. No real matcher should do this; but this lets us test that we
6716 // detect such behavior and fail appropriately.
6717 class MockMatcher : public MatcherInterface<Behavior> {
6718 public:
6719 bool MatchAndExplain(Behavior behavior,
6720 MatchResultListener* listener) const override {
6721 *listener << "[MatchAndExplain]";
6722 switch (behavior) {
6723 case kInitialSuccess:
6724 // The first call to MatchAndExplain should use a "not interested"
6725 // listener; so this is expected to return |true|. There should be no
6726 // subsequent calls.
6727 return !listener->IsInterested();
6728
6729 case kAlwaysFail:
6730 return false;
6731
6732 case kFlaky:
6733 // The first call to MatchAndExplain should use a "not interested"
6734 // listener; so this will return |false|. Subsequent calls should have
6735 // an "interested" listener; so this will return |true|, thus
6736 // simulating a flaky matcher.
6737 return listener->IsInterested();
6738 }
6739
6740 GTEST_LOG_(FATAL) << "This should never be reached";
6741 return false;
6742 }
6743
6744 void DescribeTo(ostream* os) const override { *os << "[DescribeTo]"; }
6745
6746 void DescribeNegationTo(ostream* os) const override {
6747 *os << "[DescribeNegationTo]";
6748 }
6749 };
6750
6751 AssertionResult RunPredicateFormatter(Behavior behavior) {
6752 auto matcher = MakeMatcher(new MockMatcher);
6753 PredicateFormatterFromMatcher<Matcher<Behavior>> predicate_formatter(
6754 matcher);
6755 return predicate_formatter("dummy-name", behavior);
6756 }
Abseil Team6ef59132018-12-11 14:10:54 -05006757};
6758
6759TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) {
6760 AssertionResult result = RunPredicateFormatter(kInitialSuccess);
6761 EXPECT_TRUE(result); // Implicit cast to bool.
6762 std::string expect;
6763 EXPECT_EQ(expect, result.message());
6764}
6765
6766TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
6767 AssertionResult result = RunPredicateFormatter(kAlwaysFail);
6768 EXPECT_FALSE(result); // Implicit cast to bool.
6769 std::string expect =
6770 "Value of: dummy-name\nExpected: [DescribeTo]\n"
Abseil Team1ec20f82018-12-15 08:11:02 -05006771 " Actual: 1, [MatchAndExplain]";
Abseil Team6ef59132018-12-11 14:10:54 -05006772 EXPECT_EQ(expect, result.message());
6773}
6774
6775TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
6776 AssertionResult result = RunPredicateFormatter(kFlaky);
6777 EXPECT_FALSE(result); // Implicit cast to bool.
6778 std::string expect =
6779 "Value of: dummy-name\nExpected: [DescribeTo]\n"
6780 " The matcher failed on the initial attempt; but passed when rerun to "
6781 "generate the explanation.\n"
Abseil Team1ec20f82018-12-15 08:11:02 -05006782 " Actual: 2, [MatchAndExplain]";
Abseil Team6ef59132018-12-11 14:10:54 -05006783 EXPECT_EQ(expect, result.message());
6784}
6785
Abseil Team1ec20f82018-12-15 08:11:02 -05006786} // namespace
shiqiane35fdd92008-12-10 05:08:54 +00006787} // namespace gmock_matchers_test
6788} // namespace testing
Abseil Teama42cdf22018-12-03 10:48:03 -05006789
6790#ifdef _MSC_VER
6791# pragma warning(pop)
6792#endif