]> git.proxmox.com Git - ceph.git/blame - ceph/src/jaegertracing/opentelemetry-cpp/third_party/googletest/googlemock/test/gmock-matchers_test.cc
update ceph source to reef 18.1.2
[ceph.git] / ceph / src / jaegertracing / opentelemetry-cpp / third_party / googletest / googlemock / test / gmock-matchers_test.cc
CommitLineData
31f18b77
FG
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1e59de90 29
31f18b77
FG
30
31// Google Mock - a framework for writing C++ mock classes.
32//
33// This file tests some commonly used argument matchers.
34
1e59de90
TL
35// 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
31f18b77 43#include "gmock/gmock-matchers.h"
31f18b77
FG
44
45#include <string.h>
46#include <time.h>
1e59de90
TL
47
48#include <array>
49#include <cstdint>
31f18b77 50#include <deque>
1e59de90 51#include <forward_list>
31f18b77
FG
52#include <functional>
53#include <iostream>
54#include <iterator>
55#include <limits>
56#include <list>
57#include <map>
1e59de90 58#include <memory>
31f18b77
FG
59#include <set>
60#include <sstream>
61#include <string>
1e59de90
TL
62#include <type_traits>
63#include <unordered_map>
64#include <unordered_set>
31f18b77
FG
65#include <utility>
66#include <vector>
1e59de90
TL
67
68#include "gmock/gmock-more-matchers.h"
31f18b77 69#include "gmock/gmock.h"
31f18b77 70#include "gtest/gtest-spi.h"
1e59de90 71#include "gtest/gtest.h"
31f18b77
FG
72
73namespace testing {
31f18b77 74namespace gmock_matchers_test {
1e59de90 75namespace {
31f18b77
FG
76
77using std::greater;
78using std::less;
79using std::list;
80using std::make_pair;
81using std::map;
82using std::multimap;
83using std::multiset;
84using std::ostream;
85using std::pair;
86using std::set;
87using std::stringstream;
88using std::vector;
31f18b77
FG
89using testing::internal::DummyMatchResultListener;
90using testing::internal::ElementMatcherPair;
91using testing::internal::ElementMatcherPairs;
1e59de90 92using testing::internal::ElementsAreArrayMatcher;
31f18b77
FG
93using testing::internal::ExplainMatchFailureTupleTo;
94using testing::internal::FloatingEqMatcher;
95using testing::internal::FormatMatcherDescription;
96using testing::internal::IsReadableTypeName;
31f18b77 97using testing::internal::MatchMatrix;
1e59de90 98using testing::internal::PredicateFormatterFromMatcher;
31f18b77 99using testing::internal::RE;
31f18b77
FG
100using testing::internal::StreamMatchResultListener;
101using testing::internal::Strings;
1e59de90
TL
102
103// Helper for testing container-valued matchers in mock method context. It is
104// important to test matchers in this context, since it requires additional type
105// deduction beyond what EXPECT_THAT does, thus making it more restrictive.
106struct ContainerHelper {
107 MOCK_METHOD1(Call, void(std::vector<std::unique_ptr<int>>));
108};
109
110std::vector<std::unique_ptr<int>> MakeUniquePtrs(const std::vector<int>& ints) {
111 std::vector<std::unique_ptr<int>> pointers;
112 for (int i : ints) pointers.emplace_back(new int(i));
113 return pointers;
114}
31f18b77
FG
115
116// For testing ExplainMatchResultTo().
117class GreaterThanMatcher : public MatcherInterface<int> {
118 public:
119 explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
120
1e59de90 121 void DescribeTo(ostream* os) const override { *os << "is > " << rhs_; }
31f18b77 122
1e59de90 123 bool MatchAndExplain(int lhs, MatchResultListener* listener) const override {
31f18b77
FG
124 const int diff = lhs - rhs_;
125 if (diff > 0) {
126 *listener << "which is " << diff << " more than " << rhs_;
127 } else if (diff == 0) {
128 *listener << "which is the same as " << rhs_;
129 } else {
130 *listener << "which is " << -diff << " less than " << rhs_;
131 }
132
133 return lhs > rhs_;
134 }
135
136 private:
137 int rhs_;
138};
139
140Matcher<int> GreaterThan(int n) {
141 return MakeMatcher(new GreaterThanMatcher(n));
142}
143
1e59de90 144std::string OfType(const std::string& type_name) {
31f18b77 145#if GTEST_HAS_RTTI
1e59de90 146 return IsReadableTypeName(type_name) ? " (of type " + type_name + ")" : "";
31f18b77
FG
147#else
148 return "";
149#endif
150}
151
152// Returns the description of the given matcher.
153template <typename T>
1e59de90
TL
154std::string Describe(const Matcher<T>& m) {
155 return DescribeMatcher<T>(m);
31f18b77
FG
156}
157
158// Returns the description of the negation of the given matcher.
159template <typename T>
1e59de90
TL
160std::string DescribeNegation(const Matcher<T>& m) {
161 return DescribeMatcher<T>(m, true);
31f18b77
FG
162}
163
164// Returns the reason why x matches, or doesn't match, m.
165template <typename MatcherType, typename Value>
1e59de90 166std::string Explain(const MatcherType& m, const Value& x) {
31f18b77
FG
167 StringMatchResultListener listener;
168 ExplainMatchResult(m, x, &listener);
169 return listener.str();
170}
171
1e59de90
TL
172TEST(MonotonicMatcherTest, IsPrintable) {
173 stringstream ss;
174 ss << GreaterThan(5);
175 EXPECT_EQ("is > 5", ss.str());
176}
177
31f18b77
FG
178TEST(MatchResultListenerTest, StreamingWorks) {
179 StringMatchResultListener listener;
180 listener << "hi" << 5;
181 EXPECT_EQ("hi5", listener.str());
182
183 listener.Clear();
184 EXPECT_EQ("", listener.str());
185
186 listener << 42;
187 EXPECT_EQ("42", listener.str());
188
189 // Streaming shouldn't crash when the underlying ostream is NULL.
190 DummyMatchResultListener dummy;
191 dummy << "hi" << 5;
192}
193
194TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
1e59de90
TL
195 EXPECT_TRUE(DummyMatchResultListener().stream() == nullptr);
196 EXPECT_TRUE(StreamMatchResultListener(nullptr).stream() == nullptr);
31f18b77
FG
197
198 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
199}
200
201TEST(MatchResultListenerTest, IsInterestedWorks) {
202 EXPECT_TRUE(StringMatchResultListener().IsInterested());
203 EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
204
205 EXPECT_FALSE(DummyMatchResultListener().IsInterested());
1e59de90 206 EXPECT_FALSE(StreamMatchResultListener(nullptr).IsInterested());
31f18b77
FG
207}
208
209// Makes sure that the MatcherInterface<T> interface doesn't
210// change.
211class EvenMatcherImpl : public MatcherInterface<int> {
212 public:
1e59de90
TL
213 bool MatchAndExplain(int x,
214 MatchResultListener* /* listener */) const override {
31f18b77
FG
215 return x % 2 == 0;
216 }
217
1e59de90 218 void DescribeTo(ostream* os) const override { *os << "is an even number"; }
31f18b77
FG
219
220 // We deliberately don't define DescribeNegationTo() and
221 // ExplainMatchResultTo() here, to make sure the definition of these
222 // two methods is optional.
223};
224
225// Makes sure that the MatcherInterface API doesn't change.
226TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
227 EvenMatcherImpl m;
228}
229
230// Tests implementing a monomorphic matcher using MatchAndExplain().
231
232class NewEvenMatcherImpl : public MatcherInterface<int> {
233 public:
1e59de90 234 bool MatchAndExplain(int x, MatchResultListener* listener) const override {
31f18b77
FG
235 const bool match = x % 2 == 0;
236 // Verifies that we can stream to a listener directly.
237 *listener << "value % " << 2;
1e59de90 238 if (listener->stream() != nullptr) {
31f18b77
FG
239 // Verifies that we can stream to a listener's underlying stream
240 // too.
241 *listener->stream() << " == " << (x % 2);
242 }
243 return match;
244 }
245
1e59de90 246 void DescribeTo(ostream* os) const override { *os << "is an even number"; }
31f18b77
FG
247};
248
249TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
250 Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
251 EXPECT_TRUE(m.Matches(2));
252 EXPECT_FALSE(m.Matches(3));
253 EXPECT_EQ("value % 2 == 0", Explain(m, 2));
254 EXPECT_EQ("value % 2 == 1", Explain(m, 3));
255}
256
257// Tests default-constructing a matcher.
258TEST(MatcherTest, CanBeDefaultConstructed) {
259 Matcher<double> m;
260}
261
262// Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
263TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
264 const MatcherInterface<int>* impl = new EvenMatcherImpl;
265 Matcher<int> m(impl);
266 EXPECT_TRUE(m.Matches(4));
267 EXPECT_FALSE(m.Matches(5));
268}
269
270// Tests that value can be used in place of Eq(value).
271TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
272 Matcher<int> m1 = 5;
273 EXPECT_TRUE(m1.Matches(5));
274 EXPECT_FALSE(m1.Matches(6));
275}
276
277// Tests that NULL can be used in place of Eq(NULL).
278TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
1e59de90
TL
279 Matcher<int*> m1 = nullptr;
280 EXPECT_TRUE(m1.Matches(nullptr));
31f18b77
FG
281 int n = 0;
282 EXPECT_FALSE(m1.Matches(&n));
283}
284
1e59de90
TL
285// Tests that matchers can be constructed from a variable that is not properly
286// defined. This should be illegal, but many users rely on this accidentally.
287struct Undefined {
288 virtual ~Undefined() = 0;
289 static const int kInt = 1;
290};
291
292TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) {
293 Matcher<int> m1 = Undefined::kInt;
294 EXPECT_TRUE(m1.Matches(1));
295 EXPECT_FALSE(m1.Matches(2));
296}
297
298// Test that a matcher parameterized with an abstract class compiles.
299TEST(MatcherTest, CanAcceptAbstractClass) { Matcher<const Undefined&> m = _; }
300
31f18b77
FG
301// Tests that matchers are copyable.
302TEST(MatcherTest, IsCopyable) {
303 // Tests the copy constructor.
304 Matcher<bool> m1 = Eq(false);
305 EXPECT_TRUE(m1.Matches(false));
306 EXPECT_FALSE(m1.Matches(true));
307
308 // Tests the assignment operator.
309 m1 = Eq(true);
310 EXPECT_TRUE(m1.Matches(true));
311 EXPECT_FALSE(m1.Matches(false));
312}
313
314// Tests that Matcher<T>::DescribeTo() calls
315// MatcherInterface<T>::DescribeTo().
316TEST(MatcherTest, CanDescribeItself) {
317 EXPECT_EQ("is an even number",
318 Describe(Matcher<int>(new EvenMatcherImpl)));
319}
320
321// Tests Matcher<T>::MatchAndExplain().
322TEST(MatcherTest, MatchAndExplain) {
323 Matcher<int> m = GreaterThan(0);
324 StringMatchResultListener listener1;
325 EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
326 EXPECT_EQ("which is 42 more than 0", listener1.str());
327
328 StringMatchResultListener listener2;
329 EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
330 EXPECT_EQ("which is 9 less than 0", listener2.str());
331}
332
333// Tests that a C-string literal can be implicitly converted to a
1e59de90 334// Matcher<std::string> or Matcher<const std::string&>.
31f18b77 335TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
1e59de90 336 Matcher<std::string> m1 = "hi";
31f18b77
FG
337 EXPECT_TRUE(m1.Matches("hi"));
338 EXPECT_FALSE(m1.Matches("hello"));
339
1e59de90 340 Matcher<const std::string&> m2 = "hi";
31f18b77
FG
341 EXPECT_TRUE(m2.Matches("hi"));
342 EXPECT_FALSE(m2.Matches("hello"));
343}
344
345// Tests that a string object can be implicitly converted to a
1e59de90 346// Matcher<std::string> or Matcher<const std::string&>.
31f18b77 347TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
1e59de90 348 Matcher<std::string> m1 = std::string("hi");
31f18b77
FG
349 EXPECT_TRUE(m1.Matches("hi"));
350 EXPECT_FALSE(m1.Matches("hello"));
351
1e59de90 352 Matcher<const std::string&> m2 = std::string("hi");
31f18b77
FG
353 EXPECT_TRUE(m2.Matches("hi"));
354 EXPECT_FALSE(m2.Matches("hello"));
355}
356
1e59de90 357#if GTEST_INTERNAL_HAS_STRING_VIEW
31f18b77 358// Tests that a C-string literal can be implicitly converted to a
1e59de90
TL
359// Matcher<StringView> or Matcher<const StringView&>.
360TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
361 Matcher<internal::StringView> m1 = "cats";
31f18b77
FG
362 EXPECT_TRUE(m1.Matches("cats"));
363 EXPECT_FALSE(m1.Matches("dogs"));
364
1e59de90 365 Matcher<const internal::StringView&> m2 = "cats";
31f18b77
FG
366 EXPECT_TRUE(m2.Matches("cats"));
367 EXPECT_FALSE(m2.Matches("dogs"));
368}
369
1e59de90
TL
370// Tests that a std::string object can be implicitly converted to a
371// Matcher<StringView> or Matcher<const StringView&>.
372TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {
373 Matcher<internal::StringView> m1 = std::string("cats");
374 EXPECT_TRUE(m1.Matches("cats"));
375 EXPECT_FALSE(m1.Matches("dogs"));
376
377 Matcher<const internal::StringView&> m2 = std::string("cats");
378 EXPECT_TRUE(m2.Matches("cats"));
379 EXPECT_FALSE(m2.Matches("dogs"));
380}
381
382// Tests that a StringView object can be implicitly converted to a
383// Matcher<StringView> or Matcher<const StringView&>.
384TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {
385 Matcher<internal::StringView> m1 = internal::StringView("cats");
31f18b77
FG
386 EXPECT_TRUE(m1.Matches("cats"));
387 EXPECT_FALSE(m1.Matches("dogs"));
388
1e59de90 389 Matcher<const internal::StringView&> m2 = internal::StringView("cats");
31f18b77
FG
390 EXPECT_TRUE(m2.Matches("cats"));
391 EXPECT_FALSE(m2.Matches("dogs"));
392}
1e59de90 393#endif // GTEST_INTERNAL_HAS_STRING_VIEW
31f18b77 394
1e59de90
TL
395// Tests that a std::reference_wrapper<std::string> object can be implicitly
396// converted to a Matcher<std::string> or Matcher<const std::string&> via Eq().
397TEST(StringMatcherTest,
398 CanBeImplicitlyConstructedFromEqReferenceWrapperString) {
399 std::string value = "cats";
400 Matcher<std::string> m1 = Eq(std::ref(value));
31f18b77
FG
401 EXPECT_TRUE(m1.Matches("cats"));
402 EXPECT_FALSE(m1.Matches("dogs"));
403
1e59de90 404 Matcher<const std::string&> m2 = Eq(std::ref(value));
31f18b77
FG
405 EXPECT_TRUE(m2.Matches("cats"));
406 EXPECT_FALSE(m2.Matches("dogs"));
407}
31f18b77
FG
408
409// Tests that MakeMatcher() constructs a Matcher<T> from a
410// MatcherInterface* without requiring the user to explicitly
411// write the type.
412TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
1e59de90 413 const MatcherInterface<int>* dummy_impl = nullptr;
31f18b77
FG
414 Matcher<int> m = MakeMatcher(dummy_impl);
415}
416
417// Tests that MakePolymorphicMatcher() can construct a polymorphic
418// matcher from its implementation using the old API.
419const int g_bar = 1;
420class ReferencesBarOrIsZeroImpl {
421 public:
422 template <typename T>
423 bool MatchAndExplain(const T& x,
424 MatchResultListener* /* listener */) const {
425 const void* p = &x;
426 return p == &g_bar || x == 0;
427 }
428
429 void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
430
431 void DescribeNegationTo(ostream* os) const {
432 *os << "doesn't reference g_bar and is not zero";
433 }
434};
435
436// This function verifies that MakePolymorphicMatcher() returns a
437// PolymorphicMatcher<T> where T is the argument's type.
438PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
439 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
440}
441
442TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
443 // Using a polymorphic matcher to match a reference type.
444 Matcher<const int&> m1 = ReferencesBarOrIsZero();
445 EXPECT_TRUE(m1.Matches(0));
446 // Verifies that the identity of a by-reference argument is preserved.
447 EXPECT_TRUE(m1.Matches(g_bar));
448 EXPECT_FALSE(m1.Matches(1));
449 EXPECT_EQ("g_bar or zero", Describe(m1));
450
451 // Using a polymorphic matcher to match a value type.
452 Matcher<double> m2 = ReferencesBarOrIsZero();
453 EXPECT_TRUE(m2.Matches(0.0));
454 EXPECT_FALSE(m2.Matches(0.1));
455 EXPECT_EQ("g_bar or zero", Describe(m2));
456}
457
458// Tests implementing a polymorphic matcher using MatchAndExplain().
459
460class PolymorphicIsEvenImpl {
461 public:
462 void DescribeTo(ostream* os) const { *os << "is even"; }
463
464 void DescribeNegationTo(ostream* os) const {
465 *os << "is odd";
466 }
467
468 template <typename T>
469 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
470 // Verifies that we can stream to the listener directly.
471 *listener << "% " << 2;
1e59de90 472 if (listener->stream() != nullptr) {
31f18b77
FG
473 // Verifies that we can stream to the listener's underlying stream
474 // too.
475 *listener->stream() << " == " << (x % 2);
476 }
477 return (x % 2) == 0;
478 }
479};
480
481PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
482 return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
483}
484
485TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
486 // Using PolymorphicIsEven() as a Matcher<int>.
487 const Matcher<int> m1 = PolymorphicIsEven();
488 EXPECT_TRUE(m1.Matches(42));
489 EXPECT_FALSE(m1.Matches(43));
490 EXPECT_EQ("is even", Describe(m1));
491
492 const Matcher<int> not_m1 = Not(m1);
493 EXPECT_EQ("is odd", Describe(not_m1));
494
495 EXPECT_EQ("% 2 == 0", Explain(m1, 42));
496
497 // Using PolymorphicIsEven() as a Matcher<char>.
498 const Matcher<char> m2 = PolymorphicIsEven();
499 EXPECT_TRUE(m2.Matches('\x42'));
500 EXPECT_FALSE(m2.Matches('\x43'));
501 EXPECT_EQ("is even", Describe(m2));
502
503 const Matcher<char> not_m2 = Not(m2);
504 EXPECT_EQ("is odd", Describe(not_m2));
505
506 EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
507}
508
509// Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
510TEST(MatcherCastTest, FromPolymorphicMatcher) {
511 Matcher<int> m = MatcherCast<int>(Eq(5));
512 EXPECT_TRUE(m.Matches(5));
513 EXPECT_FALSE(m.Matches(6));
514}
515
516// For testing casting matchers between compatible types.
517class IntValue {
518 public:
519 // An int can be statically (although not implicitly) cast to a
520 // IntValue.
521 explicit IntValue(int a_value) : value_(a_value) {}
522
523 int value() const { return value_; }
524 private:
525 int value_;
526};
527
528// For testing casting matchers between compatible types.
529bool IsPositiveIntValue(const IntValue& foo) {
530 return foo.value() > 0;
531}
532
533// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
534// can be statically converted to U.
535TEST(MatcherCastTest, FromCompatibleType) {
536 Matcher<double> m1 = Eq(2.0);
537 Matcher<int> m2 = MatcherCast<int>(m1);
538 EXPECT_TRUE(m2.Matches(2));
539 EXPECT_FALSE(m2.Matches(3));
540
541 Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
542 Matcher<int> m4 = MatcherCast<int>(m3);
543 // In the following, the arguments 1 and 0 are statically converted
544 // to IntValue objects, and then tested by the IsPositiveIntValue()
545 // predicate.
546 EXPECT_TRUE(m4.Matches(1));
547 EXPECT_FALSE(m4.Matches(0));
548}
549
550// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
551TEST(MatcherCastTest, FromConstReferenceToNonReference) {
552 Matcher<const int&> m1 = Eq(0);
553 Matcher<int> m2 = MatcherCast<int>(m1);
554 EXPECT_TRUE(m2.Matches(0));
555 EXPECT_FALSE(m2.Matches(1));
556}
557
558// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
559TEST(MatcherCastTest, FromReferenceToNonReference) {
560 Matcher<int&> m1 = Eq(0);
561 Matcher<int> m2 = MatcherCast<int>(m1);
562 EXPECT_TRUE(m2.Matches(0));
563 EXPECT_FALSE(m2.Matches(1));
564}
565
566// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
567TEST(MatcherCastTest, FromNonReferenceToConstReference) {
568 Matcher<int> m1 = Eq(0);
569 Matcher<const int&> m2 = MatcherCast<const int&>(m1);
570 EXPECT_TRUE(m2.Matches(0));
571 EXPECT_FALSE(m2.Matches(1));
572}
573
574// Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
575TEST(MatcherCastTest, FromNonReferenceToReference) {
576 Matcher<int> m1 = Eq(0);
577 Matcher<int&> m2 = MatcherCast<int&>(m1);
578 int n = 0;
579 EXPECT_TRUE(m2.Matches(n));
580 n = 1;
581 EXPECT_FALSE(m2.Matches(n));
582}
583
584// Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
585TEST(MatcherCastTest, FromSameType) {
586 Matcher<int> m1 = Eq(0);
587 Matcher<int> m2 = MatcherCast<int>(m1);
588 EXPECT_TRUE(m2.Matches(0));
589 EXPECT_FALSE(m2.Matches(1));
590}
591
1e59de90
TL
592// Tests that MatcherCast<T>(m) works when m is a value of the same type as the
593// value type of the Matcher.
594TEST(MatcherCastTest, FromAValue) {
595 Matcher<int> m = MatcherCast<int>(42);
596 EXPECT_TRUE(m.Matches(42));
597 EXPECT_FALSE(m.Matches(239));
598}
599
600// Tests that MatcherCast<T>(m) works when m is a value of the type implicitly
601// convertible to the value type of the Matcher.
602TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) {
603 const int kExpected = 'c';
604 Matcher<int> m = MatcherCast<int>('c');
605 EXPECT_TRUE(m.Matches(kExpected));
606 EXPECT_FALSE(m.Matches(kExpected + 1));
607}
608
609struct NonImplicitlyConstructibleTypeWithOperatorEq {
610 friend bool operator==(
611 const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */,
612 int rhs) {
613 return 42 == rhs;
614 }
615 friend bool operator==(
616 int lhs,
617 const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) {
618 return lhs == 42;
619 }
620};
621
622// Tests that MatcherCast<T>(m) works when m is a neither a matcher nor
623// implicitly convertible to the value type of the Matcher, but the value type
624// of the matcher has operator==() overload accepting m.
625TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) {
626 Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m1 =
627 MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(42);
628 EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
629
630 Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m2 =
631 MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(239);
632 EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
633
634 // When updating the following lines please also change the comment to
635 // namespace convertible_from_any.
636 Matcher<int> m3 =
637 MatcherCast<int>(NonImplicitlyConstructibleTypeWithOperatorEq());
638 EXPECT_TRUE(m3.Matches(42));
639 EXPECT_FALSE(m3.Matches(239));
640}
641
642// ConvertibleFromAny does not work with MSVC. resulting in
643// error C2440: 'initializing': cannot convert from 'Eq' to 'M'
644// No constructor could take the source type, or constructor overload
645// resolution was ambiguous
646
647#if !defined _MSC_VER
648
649// The below ConvertibleFromAny struct is implicitly constructible from anything
650// and when in the same namespace can interact with other tests. In particular,
651// if it is in the same namespace as other tests and one removes
652// NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...);
653// then the corresponding test still compiles (and it should not!) by implicitly
654// converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny
655// in m3.Matcher().
656namespace convertible_from_any {
31f18b77
FG
657// Implicitly convertible from any type.
658struct ConvertibleFromAny {
659 ConvertibleFromAny(int a_value) : value(a_value) {}
660 template <typename T>
661 ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
662 ADD_FAILURE() << "Conversion constructor called";
663 }
664 int value;
665};
666
667bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
668 return a.value == b.value;
669}
670
671ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
672 return os << a.value;
673}
674
675TEST(MatcherCastTest, ConversionConstructorIsUsed) {
676 Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
677 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
678 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
679}
680
681TEST(MatcherCastTest, FromConvertibleFromAny) {
682 Matcher<ConvertibleFromAny> m =
683 MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
684 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
685 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
686}
1e59de90
TL
687} // namespace convertible_from_any
688
689#endif // !defined _MSC_VER
31f18b77
FG
690
691struct IntReferenceWrapper {
692 IntReferenceWrapper(const int& a_value) : value(&a_value) {}
693 const int* value;
694};
695
696bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
697 return a.value == b.value;
698}
699
700TEST(MatcherCastTest, ValueIsNotCopied) {
701 int n = 42;
702 Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
703 // Verify that the matcher holds a reference to n, not to its temporary copy.
704 EXPECT_TRUE(m.Matches(n));
705}
706
707class Base {
708 public:
709 virtual ~Base() {}
710 Base() {}
711 private:
712 GTEST_DISALLOW_COPY_AND_ASSIGN_(Base);
713};
714
715class Derived : public Base {
716 public:
717 Derived() : Base() {}
718 int i;
719};
720
721class OtherDerived : public Base {};
722
723// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
724TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
725 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
726 EXPECT_TRUE(m2.Matches(' '));
727 EXPECT_FALSE(m2.Matches('\n'));
728}
729
730// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
731// T and U are arithmetic types and T can be losslessly converted to
732// U.
733TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
734 Matcher<double> m1 = DoubleEq(1.0);
735 Matcher<float> m2 = SafeMatcherCast<float>(m1);
736 EXPECT_TRUE(m2.Matches(1.0f));
737 EXPECT_FALSE(m2.Matches(2.0f));
738
739 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
740 EXPECT_TRUE(m3.Matches('a'));
741 EXPECT_FALSE(m3.Matches('b'));
742}
743
744// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
745// are pointers or references to a derived and a base class, correspondingly.
746TEST(SafeMatcherCastTest, FromBaseClass) {
747 Derived d, d2;
748 Matcher<Base*> m1 = Eq(&d);
749 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
750 EXPECT_TRUE(m2.Matches(&d));
751 EXPECT_FALSE(m2.Matches(&d2));
752
753 Matcher<Base&> m3 = Ref(d);
754 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
755 EXPECT_TRUE(m4.Matches(d));
756 EXPECT_FALSE(m4.Matches(d2));
757}
758
759// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
760TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
761 int n = 0;
762 Matcher<const int&> m1 = Ref(n);
763 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
764 int n1 = 0;
765 EXPECT_TRUE(m2.Matches(n));
766 EXPECT_FALSE(m2.Matches(n1));
767}
768
769// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
770TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
1e59de90
TL
771 Matcher<std::unique_ptr<int>> m1 = IsNull();
772 Matcher<const std::unique_ptr<int>&> m2 =
773 SafeMatcherCast<const std::unique_ptr<int>&>(m1);
774 EXPECT_TRUE(m2.Matches(std::unique_ptr<int>()));
775 EXPECT_FALSE(m2.Matches(std::unique_ptr<int>(new int)));
31f18b77
FG
776}
777
778// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
779TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
780 Matcher<int> m1 = Eq(0);
781 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
782 int n = 0;
783 EXPECT_TRUE(m2.Matches(n));
784 n = 1;
785 EXPECT_FALSE(m2.Matches(n));
786}
787
788// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
789TEST(SafeMatcherCastTest, FromSameType) {
790 Matcher<int> m1 = Eq(0);
791 Matcher<int> m2 = SafeMatcherCast<int>(m1);
792 EXPECT_TRUE(m2.Matches(0));
793 EXPECT_FALSE(m2.Matches(1));
794}
795
1e59de90
TL
796#if !defined _MSC_VER
797
798namespace convertible_from_any {
31f18b77
FG
799TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
800 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
801 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
802 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
803}
804
805TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
806 Matcher<ConvertibleFromAny> m =
807 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
808 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
809 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
810}
1e59de90
TL
811} // namespace convertible_from_any
812
813#endif // !defined _MSC_VER
31f18b77
FG
814
815TEST(SafeMatcherCastTest, ValueIsNotCopied) {
816 int n = 42;
817 Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
818 // Verify that the matcher holds a reference to n, not to its temporary copy.
819 EXPECT_TRUE(m.Matches(n));
820}
821
822TEST(ExpectThat, TakesLiterals) {
823 EXPECT_THAT(1, 1);
824 EXPECT_THAT(1.0, 1.0);
1e59de90 825 EXPECT_THAT(std::string(), "");
31f18b77
FG
826}
827
828TEST(ExpectThat, TakesFunctions) {
829 struct Helper {
830 static void Func() {}
831 };
832 void (*func)() = Helper::Func;
833 EXPECT_THAT(func, Helper::Func);
834 EXPECT_THAT(func, &Helper::Func);
835}
836
837// Tests that A<T>() matches any value of type T.
838TEST(ATest, MatchesAnyValue) {
839 // Tests a matcher for a value type.
840 Matcher<double> m1 = A<double>();
841 EXPECT_TRUE(m1.Matches(91.43));
842 EXPECT_TRUE(m1.Matches(-15.32));
843
844 // Tests a matcher for a reference type.
845 int a = 2;
846 int b = -6;
847 Matcher<int&> m2 = A<int&>();
848 EXPECT_TRUE(m2.Matches(a));
849 EXPECT_TRUE(m2.Matches(b));
850}
851
852TEST(ATest, WorksForDerivedClass) {
853 Base base;
854 Derived derived;
855 EXPECT_THAT(&base, A<Base*>());
856 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
857 EXPECT_THAT(&derived, A<Base*>());
858 EXPECT_THAT(&derived, A<Derived*>());
859}
860
861// Tests that A<T>() describes itself properly.
862TEST(ATest, CanDescribeSelf) {
863 EXPECT_EQ("is anything", Describe(A<bool>()));
864}
865
866// Tests that An<T>() matches any value of type T.
867TEST(AnTest, MatchesAnyValue) {
868 // Tests a matcher for a value type.
869 Matcher<int> m1 = An<int>();
870 EXPECT_TRUE(m1.Matches(9143));
871 EXPECT_TRUE(m1.Matches(-1532));
872
873 // Tests a matcher for a reference type.
874 int a = 2;
875 int b = -6;
876 Matcher<int&> m2 = An<int&>();
877 EXPECT_TRUE(m2.Matches(a));
878 EXPECT_TRUE(m2.Matches(b));
879}
880
881// Tests that An<T>() describes itself properly.
882TEST(AnTest, CanDescribeSelf) {
883 EXPECT_EQ("is anything", Describe(An<int>()));
884}
885
886// Tests that _ can be used as a matcher for any type and matches any
887// value of that type.
888TEST(UnderscoreTest, MatchesAnyValue) {
889 // Uses _ as a matcher for a value type.
890 Matcher<int> m1 = _;
891 EXPECT_TRUE(m1.Matches(123));
892 EXPECT_TRUE(m1.Matches(-242));
893
894 // Uses _ as a matcher for a reference type.
895 bool a = false;
896 const bool b = true;
897 Matcher<const bool&> m2 = _;
898 EXPECT_TRUE(m2.Matches(a));
899 EXPECT_TRUE(m2.Matches(b));
900}
901
902// Tests that _ describes itself properly.
903TEST(UnderscoreTest, CanDescribeSelf) {
904 Matcher<int> m = _;
905 EXPECT_EQ("is anything", Describe(m));
906}
907
908// Tests that Eq(x) matches any value equal to x.
909TEST(EqTest, MatchesEqualValue) {
910 // 2 C-strings with same content but different addresses.
911 const char a1[] = "hi";
912 const char a2[] = "hi";
913
914 Matcher<const char*> m1 = Eq(a1);
915 EXPECT_TRUE(m1.Matches(a1));
916 EXPECT_FALSE(m1.Matches(a2));
917}
918
919// Tests that Eq(v) describes itself properly.
920
921class Unprintable {
922 public:
923 Unprintable() : c_('a') {}
924
1e59de90
TL
925 bool operator==(const Unprintable& /* rhs */) const { return true; }
926 // -Wunused-private-field: dummy accessor for `c_`.
927 char dummy_c() { return c_; }
31f18b77
FG
928 private:
929 char c_;
930};
931
932TEST(EqTest, CanDescribeSelf) {
933 Matcher<Unprintable> m = Eq(Unprintable());
934 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
935}
936
937// Tests that Eq(v) can be used to match any type that supports
938// comparing with type T, where T is v's type.
939TEST(EqTest, IsPolymorphic) {
940 Matcher<int> m1 = Eq(1);
941 EXPECT_TRUE(m1.Matches(1));
942 EXPECT_FALSE(m1.Matches(2));
943
944 Matcher<char> m2 = Eq(1);
945 EXPECT_TRUE(m2.Matches('\1'));
946 EXPECT_FALSE(m2.Matches('a'));
947}
948
949// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
950TEST(TypedEqTest, ChecksEqualityForGivenType) {
951 Matcher<char> m1 = TypedEq<char>('a');
952 EXPECT_TRUE(m1.Matches('a'));
953 EXPECT_FALSE(m1.Matches('b'));
954
955 Matcher<int> m2 = TypedEq<int>(6);
956 EXPECT_TRUE(m2.Matches(6));
957 EXPECT_FALSE(m2.Matches(7));
958}
959
960// Tests that TypedEq(v) describes itself properly.
961TEST(TypedEqTest, CanDescribeSelf) {
962 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
963}
964
965// Tests that TypedEq<T>(v) has type Matcher<T>.
966
1e59de90
TL
967// Type<T>::IsTypeOf(v) compiles if and only if the type of value v is T, where
968// T is a "bare" type (i.e. not in the form of const U or U&). If v's type is
969// not T, the compiler will generate a message about "undefined reference".
31f18b77
FG
970template <typename T>
971struct Type {
972 static bool IsTypeOf(const T& /* v */) { return true; }
973
974 template <typename T2>
975 static void IsTypeOf(T2 v);
976};
977
978TEST(TypedEqTest, HasSpecifiedType) {
979 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
980 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
981 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
982}
983
984// Tests that Ge(v) matches anything >= v.
985TEST(GeTest, ImplementsGreaterThanOrEqual) {
986 Matcher<int> m1 = Ge(0);
987 EXPECT_TRUE(m1.Matches(1));
988 EXPECT_TRUE(m1.Matches(0));
989 EXPECT_FALSE(m1.Matches(-1));
990}
991
992// Tests that Ge(v) describes itself properly.
993TEST(GeTest, CanDescribeSelf) {
994 Matcher<int> m = Ge(5);
995 EXPECT_EQ("is >= 5", Describe(m));
996}
997
998// Tests that Gt(v) matches anything > v.
999TEST(GtTest, ImplementsGreaterThan) {
1000 Matcher<double> m1 = Gt(0);
1001 EXPECT_TRUE(m1.Matches(1.0));
1002 EXPECT_FALSE(m1.Matches(0.0));
1003 EXPECT_FALSE(m1.Matches(-1.0));
1004}
1005
1006// Tests that Gt(v) describes itself properly.
1007TEST(GtTest, CanDescribeSelf) {
1008 Matcher<int> m = Gt(5);
1009 EXPECT_EQ("is > 5", Describe(m));
1010}
1011
1012// Tests that Le(v) matches anything <= v.
1013TEST(LeTest, ImplementsLessThanOrEqual) {
1014 Matcher<char> m1 = Le('b');
1015 EXPECT_TRUE(m1.Matches('a'));
1016 EXPECT_TRUE(m1.Matches('b'));
1017 EXPECT_FALSE(m1.Matches('c'));
1018}
1019
1020// Tests that Le(v) describes itself properly.
1021TEST(LeTest, CanDescribeSelf) {
1022 Matcher<int> m = Le(5);
1023 EXPECT_EQ("is <= 5", Describe(m));
1024}
1025
1026// Tests that Lt(v) matches anything < v.
1027TEST(LtTest, ImplementsLessThan) {
1e59de90 1028 Matcher<const std::string&> m1 = Lt("Hello");
31f18b77
FG
1029 EXPECT_TRUE(m1.Matches("Abc"));
1030 EXPECT_FALSE(m1.Matches("Hello"));
1031 EXPECT_FALSE(m1.Matches("Hello, world!"));
1032}
1033
1034// Tests that Lt(v) describes itself properly.
1035TEST(LtTest, CanDescribeSelf) {
1036 Matcher<int> m = Lt(5);
1037 EXPECT_EQ("is < 5", Describe(m));
1038}
1039
1040// Tests that Ne(v) matches anything != v.
1041TEST(NeTest, ImplementsNotEqual) {
1042 Matcher<int> m1 = Ne(0);
1043 EXPECT_TRUE(m1.Matches(1));
1044 EXPECT_TRUE(m1.Matches(-1));
1045 EXPECT_FALSE(m1.Matches(0));
1046}
1047
1048// Tests that Ne(v) describes itself properly.
1049TEST(NeTest, CanDescribeSelf) {
1050 Matcher<int> m = Ne(5);
1051 EXPECT_EQ("isn't equal to 5", Describe(m));
1052}
1053
1e59de90
TL
1054class MoveOnly {
1055 public:
1056 explicit MoveOnly(int i) : i_(i) {}
1057 MoveOnly(const MoveOnly&) = delete;
1058 MoveOnly(MoveOnly&&) = default;
1059 MoveOnly& operator=(const MoveOnly&) = delete;
1060 MoveOnly& operator=(MoveOnly&&) = default;
1061
1062 bool operator==(const MoveOnly& other) const { return i_ == other.i_; }
1063 bool operator!=(const MoveOnly& other) const { return i_ != other.i_; }
1064 bool operator<(const MoveOnly& other) const { return i_ < other.i_; }
1065 bool operator<=(const MoveOnly& other) const { return i_ <= other.i_; }
1066 bool operator>(const MoveOnly& other) const { return i_ > other.i_; }
1067 bool operator>=(const MoveOnly& other) const { return i_ >= other.i_; }
1068
1069 private:
1070 int i_;
1071};
1072
1073struct MoveHelper {
1074 MOCK_METHOD1(Call, void(MoveOnly));
1075};
1076
1077TEST(ComparisonBaseTest, WorksWithMoveOnly) {
1078 MoveOnly m{0};
1079 MoveHelper helper;
1080
1081 EXPECT_CALL(helper, Call(Eq(ByRef(m))));
1082 helper.Call(MoveOnly(0));
1083 EXPECT_CALL(helper, Call(Ne(ByRef(m))));
1084 helper.Call(MoveOnly(1));
1085 EXPECT_CALL(helper, Call(Le(ByRef(m))));
1086 helper.Call(MoveOnly(0));
1087 EXPECT_CALL(helper, Call(Lt(ByRef(m))));
1088 helper.Call(MoveOnly(-1));
1089 EXPECT_CALL(helper, Call(Ge(ByRef(m))));
1090 helper.Call(MoveOnly(0));
1091 EXPECT_CALL(helper, Call(Gt(ByRef(m))));
1092 helper.Call(MoveOnly(1));
1093}
1094
31f18b77
FG
1095// Tests that IsNull() matches any NULL pointer of any type.
1096TEST(IsNullTest, MatchesNullPointer) {
1097 Matcher<int*> m1 = IsNull();
1e59de90 1098 int* p1 = nullptr;
31f18b77
FG
1099 int n = 0;
1100 EXPECT_TRUE(m1.Matches(p1));
1101 EXPECT_FALSE(m1.Matches(&n));
1102
1103 Matcher<const char*> m2 = IsNull();
1e59de90 1104 const char* p2 = nullptr;
31f18b77
FG
1105 EXPECT_TRUE(m2.Matches(p2));
1106 EXPECT_FALSE(m2.Matches("hi"));
1107
31f18b77 1108 Matcher<void*> m3 = IsNull();
1e59de90 1109 void* p3 = nullptr;
31f18b77
FG
1110 EXPECT_TRUE(m3.Matches(p3));
1111 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
31f18b77
FG
1112}
1113
31f18b77
FG
1114TEST(IsNullTest, StdFunction) {
1115 const Matcher<std::function<void()>> m = IsNull();
1116
1117 EXPECT_TRUE(m.Matches(std::function<void()>()));
1118 EXPECT_FALSE(m.Matches([]{}));
1119}
31f18b77
FG
1120
1121// Tests that IsNull() describes itself properly.
1122TEST(IsNullTest, CanDescribeSelf) {
1123 Matcher<int*> m = IsNull();
1124 EXPECT_EQ("is NULL", Describe(m));
1125 EXPECT_EQ("isn't NULL", DescribeNegation(m));
1126}
1127
1128// Tests that NotNull() matches any non-NULL pointer of any type.
1129TEST(NotNullTest, MatchesNonNullPointer) {
1130 Matcher<int*> m1 = NotNull();
1e59de90 1131 int* p1 = nullptr;
31f18b77
FG
1132 int n = 0;
1133 EXPECT_FALSE(m1.Matches(p1));
1134 EXPECT_TRUE(m1.Matches(&n));
1135
1136 Matcher<const char*> m2 = NotNull();
1e59de90 1137 const char* p2 = nullptr;
31f18b77
FG
1138 EXPECT_FALSE(m2.Matches(p2));
1139 EXPECT_TRUE(m2.Matches("hi"));
1140}
1141
1142TEST(NotNullTest, LinkedPtr) {
1e59de90
TL
1143 const Matcher<std::shared_ptr<int>> m = NotNull();
1144 const std::shared_ptr<int> null_p;
1145 const std::shared_ptr<int> non_null_p(new int);
31f18b77
FG
1146
1147 EXPECT_FALSE(m.Matches(null_p));
1148 EXPECT_TRUE(m.Matches(non_null_p));
1149}
1150
1151TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1e59de90
TL
1152 const Matcher<const std::shared_ptr<double>&> m = NotNull();
1153 const std::shared_ptr<double> null_p;
1154 const std::shared_ptr<double> non_null_p(new double);
31f18b77
FG
1155
1156 EXPECT_FALSE(m.Matches(null_p));
1157 EXPECT_TRUE(m.Matches(non_null_p));
1158}
1159
31f18b77
FG
1160TEST(NotNullTest, StdFunction) {
1161 const Matcher<std::function<void()>> m = NotNull();
1162
1163 EXPECT_TRUE(m.Matches([]{}));
1164 EXPECT_FALSE(m.Matches(std::function<void()>()));
1165}
31f18b77
FG
1166
1167// Tests that NotNull() describes itself properly.
1168TEST(NotNullTest, CanDescribeSelf) {
1169 Matcher<int*> m = NotNull();
1170 EXPECT_EQ("isn't NULL", Describe(m));
1171}
1172
1173// Tests that Ref(variable) matches an argument that references
1174// 'variable'.
1175TEST(RefTest, MatchesSameVariable) {
1176 int a = 0;
1177 int b = 0;
1178 Matcher<int&> m = Ref(a);
1179 EXPECT_TRUE(m.Matches(a));
1180 EXPECT_FALSE(m.Matches(b));
1181}
1182
1183// Tests that Ref(variable) describes itself properly.
1184TEST(RefTest, CanDescribeSelf) {
1185 int n = 5;
1186 Matcher<int&> m = Ref(n);
1187 stringstream ss;
1188 ss << "references the variable @" << &n << " 5";
1e59de90 1189 EXPECT_EQ(ss.str(), Describe(m));
31f18b77
FG
1190}
1191
1192// Test that Ref(non_const_varialbe) can be used as a matcher for a
1193// const reference.
1194TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1195 int a = 0;
1196 int b = 0;
1197 Matcher<const int&> m = Ref(a);
1198 EXPECT_TRUE(m.Matches(a));
1199 EXPECT_FALSE(m.Matches(b));
1200}
1201
1202// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1203// used wherever Ref(base) can be used (Ref(derived) is a sub-type
1204// of Ref(base), but not vice versa.
1205
1206TEST(RefTest, IsCovariant) {
1207 Base base, base2;
1208 Derived derived;
1209 Matcher<const Base&> m1 = Ref(base);
1210 EXPECT_TRUE(m1.Matches(base));
1211 EXPECT_FALSE(m1.Matches(base2));
1212 EXPECT_FALSE(m1.Matches(derived));
1213
1214 m1 = Ref(derived);
1215 EXPECT_TRUE(m1.Matches(derived));
1216 EXPECT_FALSE(m1.Matches(base));
1217 EXPECT_FALSE(m1.Matches(base2));
1218}
1219
1220TEST(RefTest, ExplainsResult) {
1221 int n = 0;
1222 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1223 StartsWith("which is located @"));
1224
1225 int m = 0;
1226 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1227 StartsWith("which is located @"));
1228}
1229
1230// Tests string comparison matchers.
1231
1e59de90
TL
1232template <typename T = std::string>
1233std::string FromStringLike(internal::StringLike<T> str) {
1234 return std::string(str);
1235}
1236
1237TEST(StringLike, TestConversions) {
1238 EXPECT_EQ("foo", FromStringLike("foo"));
1239 EXPECT_EQ("foo", FromStringLike(std::string("foo")));
1240#if GTEST_INTERNAL_HAS_STRING_VIEW
1241 EXPECT_EQ("foo", FromStringLike(internal::StringView("foo")));
1242#endif // GTEST_INTERNAL_HAS_STRING_VIEW
1243
1244 // Non deducible types.
1245 EXPECT_EQ("", FromStringLike({}));
1246 EXPECT_EQ("foo", FromStringLike({'f', 'o', 'o'}));
1247 const char buf[] = "foo";
1248 EXPECT_EQ("foo", FromStringLike({buf, buf + 3}));
1249}
1250
31f18b77 1251TEST(StrEqTest, MatchesEqualString) {
1e59de90 1252 Matcher<const char*> m = StrEq(std::string("Hello"));
31f18b77
FG
1253 EXPECT_TRUE(m.Matches("Hello"));
1254 EXPECT_FALSE(m.Matches("hello"));
1e59de90 1255 EXPECT_FALSE(m.Matches(nullptr));
31f18b77 1256
1e59de90 1257 Matcher<const std::string&> m2 = StrEq("Hello");
31f18b77
FG
1258 EXPECT_TRUE(m2.Matches("Hello"));
1259 EXPECT_FALSE(m2.Matches("Hi"));
1e59de90
TL
1260
1261#if GTEST_INTERNAL_HAS_STRING_VIEW
1262 Matcher<const internal::StringView&> m3 =
1263 StrEq(internal::StringView("Hello"));
1264 EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
1265 EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
1266 EXPECT_FALSE(m3.Matches(internal::StringView()));
1267
1268 Matcher<const internal::StringView&> m_empty = StrEq("");
1269 EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
1270 EXPECT_TRUE(m_empty.Matches(internal::StringView()));
1271 EXPECT_FALSE(m_empty.Matches(internal::StringView("hello")));
1272#endif // GTEST_INTERNAL_HAS_STRING_VIEW
31f18b77
FG
1273}
1274
1275TEST(StrEqTest, CanDescribeSelf) {
1e59de90 1276 Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
31f18b77
FG
1277 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
1278 Describe(m));
1279
1e59de90 1280 std::string str("01204500800");
31f18b77 1281 str[3] = '\0';
1e59de90 1282 Matcher<std::string> m2 = StrEq(str);
31f18b77
FG
1283 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1284 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1e59de90 1285 Matcher<std::string> m3 = StrEq(str);
31f18b77
FG
1286 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1287}
1288
1289TEST(StrNeTest, MatchesUnequalString) {
1290 Matcher<const char*> m = StrNe("Hello");
1291 EXPECT_TRUE(m.Matches(""));
1e59de90 1292 EXPECT_TRUE(m.Matches(nullptr));
31f18b77
FG
1293 EXPECT_FALSE(m.Matches("Hello"));
1294
1e59de90 1295 Matcher<std::string> m2 = StrNe(std::string("Hello"));
31f18b77
FG
1296 EXPECT_TRUE(m2.Matches("hello"));
1297 EXPECT_FALSE(m2.Matches("Hello"));
1e59de90
TL
1298
1299#if GTEST_INTERNAL_HAS_STRING_VIEW
1300 Matcher<const internal::StringView> m3 = StrNe(internal::StringView("Hello"));
1301 EXPECT_TRUE(m3.Matches(internal::StringView("")));
1302 EXPECT_TRUE(m3.Matches(internal::StringView()));
1303 EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
1304#endif // GTEST_INTERNAL_HAS_STRING_VIEW
31f18b77
FG
1305}
1306
1307TEST(StrNeTest, CanDescribeSelf) {
1308 Matcher<const char*> m = StrNe("Hi");
1309 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
1310}
1311
1312TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1e59de90 1313 Matcher<const char*> m = StrCaseEq(std::string("Hello"));
31f18b77
FG
1314 EXPECT_TRUE(m.Matches("Hello"));
1315 EXPECT_TRUE(m.Matches("hello"));
1316 EXPECT_FALSE(m.Matches("Hi"));
1e59de90 1317 EXPECT_FALSE(m.Matches(nullptr));
31f18b77 1318
1e59de90 1319 Matcher<const std::string&> m2 = StrCaseEq("Hello");
31f18b77
FG
1320 EXPECT_TRUE(m2.Matches("hello"));
1321 EXPECT_FALSE(m2.Matches("Hi"));
1e59de90
TL
1322
1323#if GTEST_INTERNAL_HAS_STRING_VIEW
1324 Matcher<const internal::StringView&> m3 =
1325 StrCaseEq(internal::StringView("Hello"));
1326 EXPECT_TRUE(m3.Matches(internal::StringView("Hello")));
1327 EXPECT_TRUE(m3.Matches(internal::StringView("hello")));
1328 EXPECT_FALSE(m3.Matches(internal::StringView("Hi")));
1329 EXPECT_FALSE(m3.Matches(internal::StringView()));
1330#endif // GTEST_INTERNAL_HAS_STRING_VIEW
31f18b77
FG
1331}
1332
1333TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1e59de90
TL
1334 std::string str1("oabocdooeoo");
1335 std::string str2("OABOCDOOEOO");
1336 Matcher<const std::string&> m0 = StrCaseEq(str1);
1337 EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0')));
31f18b77
FG
1338
1339 str1[3] = str2[3] = '\0';
1e59de90 1340 Matcher<const std::string&> m1 = StrCaseEq(str1);
31f18b77
FG
1341 EXPECT_TRUE(m1.Matches(str2));
1342
1343 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1344 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1e59de90 1345 Matcher<const std::string&> m2 = StrCaseEq(str1);
31f18b77
FG
1346 str1[9] = str2[9] = '\0';
1347 EXPECT_FALSE(m2.Matches(str2));
1348
1e59de90 1349 Matcher<const std::string&> m3 = StrCaseEq(str1);
31f18b77
FG
1350 EXPECT_TRUE(m3.Matches(str2));
1351
1352 EXPECT_FALSE(m3.Matches(str2 + "x"));
1353 str2.append(1, '\0');
1354 EXPECT_FALSE(m3.Matches(str2));
1e59de90 1355 EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9)));
31f18b77
FG
1356}
1357
1358TEST(StrCaseEqTest, CanDescribeSelf) {
1e59de90 1359 Matcher<std::string> m = StrCaseEq("Hi");
31f18b77
FG
1360 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1361}
1362
1363TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1364 Matcher<const char*> m = StrCaseNe("Hello");
1365 EXPECT_TRUE(m.Matches("Hi"));
1e59de90 1366 EXPECT_TRUE(m.Matches(nullptr));
31f18b77
FG
1367 EXPECT_FALSE(m.Matches("Hello"));
1368 EXPECT_FALSE(m.Matches("hello"));
1369
1e59de90 1370 Matcher<std::string> m2 = StrCaseNe(std::string("Hello"));
31f18b77
FG
1371 EXPECT_TRUE(m2.Matches(""));
1372 EXPECT_FALSE(m2.Matches("Hello"));
1e59de90
TL
1373
1374#if GTEST_INTERNAL_HAS_STRING_VIEW
1375 Matcher<const internal::StringView> m3 =
1376 StrCaseNe(internal::StringView("Hello"));
1377 EXPECT_TRUE(m3.Matches(internal::StringView("Hi")));
1378 EXPECT_TRUE(m3.Matches(internal::StringView()));
1379 EXPECT_FALSE(m3.Matches(internal::StringView("Hello")));
1380 EXPECT_FALSE(m3.Matches(internal::StringView("hello")));
1381#endif // GTEST_INTERNAL_HAS_STRING_VIEW
31f18b77
FG
1382}
1383
1384TEST(StrCaseNeTest, CanDescribeSelf) {
1385 Matcher<const char*> m = StrCaseNe("Hi");
1386 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
1387}
1388
1389// Tests that HasSubstr() works for matching string-typed values.
1390TEST(HasSubstrTest, WorksForStringClasses) {
1e59de90
TL
1391 const Matcher<std::string> m1 = HasSubstr("foo");
1392 EXPECT_TRUE(m1.Matches(std::string("I love food.")));
1393 EXPECT_FALSE(m1.Matches(std::string("tofo")));
31f18b77
FG
1394
1395 const Matcher<const std::string&> m2 = HasSubstr("foo");
1396 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1397 EXPECT_FALSE(m2.Matches(std::string("tofo")));
1e59de90
TL
1398
1399 const Matcher<std::string> m_empty = HasSubstr("");
1400 EXPECT_TRUE(m_empty.Matches(std::string()));
1401 EXPECT_TRUE(m_empty.Matches(std::string("not empty")));
31f18b77
FG
1402}
1403
1404// Tests that HasSubstr() works for matching C-string-typed values.
1405TEST(HasSubstrTest, WorksForCStrings) {
1406 const Matcher<char*> m1 = HasSubstr("foo");
1407 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1408 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1e59de90 1409 EXPECT_FALSE(m1.Matches(nullptr));
31f18b77
FG
1410
1411 const Matcher<const char*> m2 = HasSubstr("foo");
1412 EXPECT_TRUE(m2.Matches("I love food."));
1413 EXPECT_FALSE(m2.Matches("tofo"));
1e59de90
TL
1414 EXPECT_FALSE(m2.Matches(nullptr));
1415
1416 const Matcher<const char*> m_empty = HasSubstr("");
1417 EXPECT_TRUE(m_empty.Matches("not empty"));
1418 EXPECT_TRUE(m_empty.Matches(""));
1419 EXPECT_FALSE(m_empty.Matches(nullptr));
1420}
1421
1422#if GTEST_INTERNAL_HAS_STRING_VIEW
1423// Tests that HasSubstr() works for matching StringView-typed values.
1424TEST(HasSubstrTest, WorksForStringViewClasses) {
1425 const Matcher<internal::StringView> m1 =
1426 HasSubstr(internal::StringView("foo"));
1427 EXPECT_TRUE(m1.Matches(internal::StringView("I love food.")));
1428 EXPECT_FALSE(m1.Matches(internal::StringView("tofo")));
1429 EXPECT_FALSE(m1.Matches(internal::StringView()));
1430
1431 const Matcher<const internal::StringView&> m2 = HasSubstr("foo");
1432 EXPECT_TRUE(m2.Matches(internal::StringView("I love food.")));
1433 EXPECT_FALSE(m2.Matches(internal::StringView("tofo")));
1434 EXPECT_FALSE(m2.Matches(internal::StringView()));
1435
1436 const Matcher<const internal::StringView&> m3 = HasSubstr("");
1437 EXPECT_TRUE(m3.Matches(internal::StringView("foo")));
1438 EXPECT_TRUE(m3.Matches(internal::StringView("")));
1439 EXPECT_TRUE(m3.Matches(internal::StringView()));
31f18b77 1440}
1e59de90 1441#endif // GTEST_INTERNAL_HAS_STRING_VIEW
31f18b77
FG
1442
1443// Tests that HasSubstr(s) describes itself properly.
1444TEST(HasSubstrTest, CanDescribeSelf) {
1e59de90 1445 Matcher<std::string> m = HasSubstr("foo\n\"");
31f18b77
FG
1446 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1447}
1448
1449TEST(KeyTest, CanDescribeSelf) {
1450 Matcher<const pair<std::string, int>&> m = Key("foo");
1451 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
1452 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1453}
1454
1455TEST(KeyTest, ExplainsResult) {
1456 Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1457 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1458 Explain(m, make_pair(5, true)));
1459 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1460 Explain(m, make_pair(15, true)));
1461}
1462
1463TEST(KeyTest, MatchesCorrectly) {
1464 pair<int, std::string> p(25, "foo");
1465 EXPECT_THAT(p, Key(25));
1466 EXPECT_THAT(p, Not(Key(42)));
1467 EXPECT_THAT(p, Key(Ge(20)));
1468 EXPECT_THAT(p, Not(Key(Lt(25))));
1469}
1470
1e59de90
TL
1471TEST(KeyTest, WorksWithMoveOnly) {
1472 pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
1473 EXPECT_THAT(p, Key(Eq(nullptr)));
1474}
1475
1476template <size_t I>
1477struct Tag {};
1478
1479struct PairWithGet {
1480 int member_1;
1481 std::string member_2;
1482 using first_type = int;
1483 using second_type = std::string;
1484
1485 const int& GetImpl(Tag<0>) const { return member_1; }
1486 const std::string& GetImpl(Tag<1>) const { return member_2; }
1487};
1488template <size_t I>
1489auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag<I>())) {
1490 return value.GetImpl(Tag<I>());
1491}
1492TEST(PairTest, MatchesPairWithGetCorrectly) {
1493 PairWithGet p{25, "foo"};
1494 EXPECT_THAT(p, Key(25));
1495 EXPECT_THAT(p, Not(Key(42)));
1496 EXPECT_THAT(p, Key(Ge(20)));
1497 EXPECT_THAT(p, Not(Key(Lt(25))));
1498
1499 std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
1500 EXPECT_THAT(v, Contains(Key(29)));
1501}
1502
31f18b77
FG
1503TEST(KeyTest, SafelyCastsInnerMatcher) {
1504 Matcher<int> is_positive = Gt(0);
1505 Matcher<int> is_negative = Lt(0);
1506 pair<char, bool> p('a', true);
1507 EXPECT_THAT(p, Key(is_positive));
1508 EXPECT_THAT(p, Not(Key(is_negative)));
1509}
1510
1511TEST(KeyTest, InsideContainsUsingMap) {
1512 map<int, char> container;
1513 container.insert(make_pair(1, 'a'));
1514 container.insert(make_pair(2, 'b'));
1515 container.insert(make_pair(4, 'c'));
1516 EXPECT_THAT(container, Contains(Key(1)));
1517 EXPECT_THAT(container, Not(Contains(Key(3))));
1518}
1519
1520TEST(KeyTest, InsideContainsUsingMultimap) {
1521 multimap<int, char> container;
1522 container.insert(make_pair(1, 'a'));
1523 container.insert(make_pair(2, 'b'));
1524 container.insert(make_pair(4, 'c'));
1525
1526 EXPECT_THAT(container, Not(Contains(Key(25))));
1527 container.insert(make_pair(25, 'd'));
1528 EXPECT_THAT(container, Contains(Key(25)));
1529 container.insert(make_pair(25, 'e'));
1530 EXPECT_THAT(container, Contains(Key(25)));
1531
1532 EXPECT_THAT(container, Contains(Key(1)));
1533 EXPECT_THAT(container, Not(Contains(Key(3))));
1534}
1535
1536TEST(PairTest, Typing) {
1537 // Test verifies the following type conversions can be compiled.
1538 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1539 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1540 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
1541
1542 Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1543 Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
1544}
1545
1546TEST(PairTest, CanDescribeSelf) {
1547 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
1548 EXPECT_EQ("has a first field that is equal to \"foo\""
1549 ", and has a second field that is equal to 42",
1550 Describe(m1));
1551 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1552 ", or has a second field that isn't equal to 42",
1553 DescribeNegation(m1));
1554 // Double and triple negation (1 or 2 times not and description of negation).
1555 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1556 EXPECT_EQ("has a first field that isn't equal to 13"
1557 ", and has a second field that is equal to 42",
1558 DescribeNegation(m2));
1559}
1560
1561TEST(PairTest, CanExplainMatchResultTo) {
1562 // If neither field matches, Pair() should explain about the first
1563 // field.
1564 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
1565 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1566 Explain(m, make_pair(-1, -2)));
1567
1568 // If the first field matches but the second doesn't, Pair() should
1569 // explain about the second field.
1570 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
1571 Explain(m, make_pair(1, -2)));
1572
1573 // If the first field doesn't match but the second does, Pair()
1574 // should explain about the first field.
1575 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1576 Explain(m, make_pair(-1, 2)));
1577
1578 // If both fields match, Pair() should explain about them both.
1579 EXPECT_EQ("whose both fields match, where the first field is a value "
1580 "which is 1 more than 0, and the second field is a value "
1581 "which is 2 more than 0",
1582 Explain(m, make_pair(1, 2)));
1583
1584 // If only the first match has an explanation, only this explanation should
1585 // be printed.
1586 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
1587 EXPECT_EQ("whose both fields match, where the first field is a value "
1588 "which is 1 more than 0",
1589 Explain(explain_first, make_pair(1, 0)));
1590
1591 // If only the second match has an explanation, only this explanation should
1592 // be printed.
1593 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
1594 EXPECT_EQ("whose both fields match, where the second field is a value "
1595 "which is 1 more than 0",
1596 Explain(explain_second, make_pair(0, 1)));
1597}
1598
1599TEST(PairTest, MatchesCorrectly) {
1600 pair<int, std::string> p(25, "foo");
1601
1602 // Both fields match.
1603 EXPECT_THAT(p, Pair(25, "foo"));
1604 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1605
1606 // 'first' doesnt' match, but 'second' matches.
1607 EXPECT_THAT(p, Not(Pair(42, "foo")));
1608 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1609
1610 // 'first' matches, but 'second' doesn't match.
1611 EXPECT_THAT(p, Not(Pair(25, "bar")));
1612 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1613
1614 // Neither field matches.
1615 EXPECT_THAT(p, Not(Pair(13, "bar")));
1616 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1617}
1618
1e59de90
TL
1619TEST(PairTest, WorksWithMoveOnly) {
1620 pair<std::unique_ptr<int>, std::unique_ptr<int>> p;
1621 p.second.reset(new int(7));
1622 EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr)));
1623}
1624
31f18b77
FG
1625TEST(PairTest, SafelyCastsInnerMatchers) {
1626 Matcher<int> is_positive = Gt(0);
1627 Matcher<int> is_negative = Lt(0);
1628 pair<char, bool> p('a', true);
1629 EXPECT_THAT(p, Pair(is_positive, _));
1630 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1631 EXPECT_THAT(p, Pair(_, is_positive));
1632 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1633}
1634
1635TEST(PairTest, InsideContainsUsingMap) {
1636 map<int, char> container;
1637 container.insert(make_pair(1, 'a'));
1638 container.insert(make_pair(2, 'b'));
1639 container.insert(make_pair(4, 'c'));
1640 EXPECT_THAT(container, Contains(Pair(1, 'a')));
1641 EXPECT_THAT(container, Contains(Pair(1, _)));
1642 EXPECT_THAT(container, Contains(Pair(_, 'a')));
1643 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1644}
1645
1e59de90
TL
1646TEST(FieldsAreTest, MatchesCorrectly) {
1647 std::tuple<int, std::string, double> p(25, "foo", .5);
1648
1649 // All fields match.
1650 EXPECT_THAT(p, FieldsAre(25, "foo", .5));
1651 EXPECT_THAT(p, FieldsAre(Ge(20), HasSubstr("o"), DoubleEq(.5)));
1652
1653 // Some don't match.
1654 EXPECT_THAT(p, Not(FieldsAre(26, "foo", .5)));
1655 EXPECT_THAT(p, Not(FieldsAre(25, "fo", .5)));
1656 EXPECT_THAT(p, Not(FieldsAre(25, "foo", .6)));
1657}
1658
1659TEST(FieldsAreTest, CanDescribeSelf) {
1660 Matcher<const pair<std::string, int>&> m1 = FieldsAre("foo", 42);
1661 EXPECT_EQ(
1662 "has field #0 that is equal to \"foo\""
1663 ", and has field #1 that is equal to 42",
1664 Describe(m1));
1665 EXPECT_EQ(
1666 "has field #0 that isn't equal to \"foo\""
1667 ", or has field #1 that isn't equal to 42",
1668 DescribeNegation(m1));
1669}
1670
1671TEST(FieldsAreTest, CanExplainMatchResultTo) {
1672 // The first one that fails is the one that gives the error.
1673 Matcher<std::tuple<int, int, int>> m =
1674 FieldsAre(GreaterThan(0), GreaterThan(0), GreaterThan(0));
1675
1676 EXPECT_EQ("whose field #0 does not match, which is 1 less than 0",
1677 Explain(m, std::make_tuple(-1, -2, -3)));
1678 EXPECT_EQ("whose field #1 does not match, which is 2 less than 0",
1679 Explain(m, std::make_tuple(1, -2, -3)));
1680 EXPECT_EQ("whose field #2 does not match, which is 3 less than 0",
1681 Explain(m, std::make_tuple(1, 2, -3)));
1682
1683 // If they all match, we get a long explanation of success.
1684 EXPECT_EQ(
1685 "whose all elements match, "
1686 "where field #0 is a value which is 1 more than 0"
1687 ", and field #1 is a value which is 2 more than 0"
1688 ", and field #2 is a value which is 3 more than 0",
1689 Explain(m, std::make_tuple(1, 2, 3)));
1690
1691 // Only print those that have an explanation.
1692 m = FieldsAre(GreaterThan(0), 0, GreaterThan(0));
1693 EXPECT_EQ(
1694 "whose all elements match, "
1695 "where field #0 is a value which is 1 more than 0"
1696 ", and field #2 is a value which is 3 more than 0",
1697 Explain(m, std::make_tuple(1, 0, 3)));
1698
1699 // If only one has an explanation, then print that one.
1700 m = FieldsAre(0, GreaterThan(0), 0);
1701 EXPECT_EQ(
1702 "whose all elements match, "
1703 "where field #1 is a value which is 1 more than 0",
1704 Explain(m, std::make_tuple(0, 1, 0)));
1705}
1706
1707#if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606
1708TEST(FieldsAreTest, StructuredBindings) {
1709 // testing::FieldsAre can also match aggregates and such with C++17 and up.
1710 struct MyType {
1711 int i;
1712 std::string str;
1713 };
1714 EXPECT_THAT((MyType{17, "foo"}), FieldsAre(Eq(17), HasSubstr("oo")));
1715
1716 // Test all the supported arities.
1717 struct MyVarType1 {
1718 int a;
1719 };
1720 EXPECT_THAT(MyVarType1{}, FieldsAre(0));
1721 struct MyVarType2 {
1722 int a, b;
1723 };
1724 EXPECT_THAT(MyVarType2{}, FieldsAre(0, 0));
1725 struct MyVarType3 {
1726 int a, b, c;
1727 };
1728 EXPECT_THAT(MyVarType3{}, FieldsAre(0, 0, 0));
1729 struct MyVarType4 {
1730 int a, b, c, d;
1731 };
1732 EXPECT_THAT(MyVarType4{}, FieldsAre(0, 0, 0, 0));
1733 struct MyVarType5 {
1734 int a, b, c, d, e;
1735 };
1736 EXPECT_THAT(MyVarType5{}, FieldsAre(0, 0, 0, 0, 0));
1737 struct MyVarType6 {
1738 int a, b, c, d, e, f;
1739 };
1740 EXPECT_THAT(MyVarType6{}, FieldsAre(0, 0, 0, 0, 0, 0));
1741 struct MyVarType7 {
1742 int a, b, c, d, e, f, g;
1743 };
1744 EXPECT_THAT(MyVarType7{}, FieldsAre(0, 0, 0, 0, 0, 0, 0));
1745 struct MyVarType8 {
1746 int a, b, c, d, e, f, g, h;
1747 };
1748 EXPECT_THAT(MyVarType8{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0));
1749 struct MyVarType9 {
1750 int a, b, c, d, e, f, g, h, i;
1751 };
1752 EXPECT_THAT(MyVarType9{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0));
1753 struct MyVarType10 {
1754 int a, b, c, d, e, f, g, h, i, j;
1755 };
1756 EXPECT_THAT(MyVarType10{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1757 struct MyVarType11 {
1758 int a, b, c, d, e, f, g, h, i, j, k;
1759 };
1760 EXPECT_THAT(MyVarType11{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1761 struct MyVarType12 {
1762 int a, b, c, d, e, f, g, h, i, j, k, l;
1763 };
1764 EXPECT_THAT(MyVarType12{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1765 struct MyVarType13 {
1766 int a, b, c, d, e, f, g, h, i, j, k, l, m;
1767 };
1768 EXPECT_THAT(MyVarType13{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1769 struct MyVarType14 {
1770 int a, b, c, d, e, f, g, h, i, j, k, l, m, n;
1771 };
1772 EXPECT_THAT(MyVarType14{},
1773 FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1774 struct MyVarType15 {
1775 int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o;
1776 };
1777 EXPECT_THAT(MyVarType15{},
1778 FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1779 struct MyVarType16 {
1780 int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p;
1781 };
1782 EXPECT_THAT(MyVarType16{},
1783 FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
1784}
1785#endif
1786
1787TEST(ContainsTest, WorksWithMoveOnly) {
1788 ContainerHelper helper;
1789 EXPECT_CALL(helper, Call(Contains(Pointee(2))));
1790 helper.Call(MakeUniquePtrs({1, 2}));
1791}
1792
1793TEST(PairTest, UseGetInsteadOfMembers) {
1794 PairWithGet pair{7, "ABC"};
1795 EXPECT_THAT(pair, Pair(7, "ABC"));
1796 EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB")));
1797 EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC")));
1798
1799 std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
1800 EXPECT_THAT(v,
1801 ElementsAre(Pair(11, std::string("Foo")), Pair(Ge(10), Not(""))));
1802}
1803
31f18b77
FG
1804// Tests StartsWith(s).
1805
1806TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1e59de90 1807 const Matcher<const char*> m1 = StartsWith(std::string(""));
31f18b77
FG
1808 EXPECT_TRUE(m1.Matches("Hi"));
1809 EXPECT_TRUE(m1.Matches(""));
1e59de90 1810 EXPECT_FALSE(m1.Matches(nullptr));
31f18b77 1811
1e59de90 1812 const Matcher<const std::string&> m2 = StartsWith("Hi");
31f18b77
FG
1813 EXPECT_TRUE(m2.Matches("Hi"));
1814 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1815 EXPECT_TRUE(m2.Matches("High"));
1816 EXPECT_FALSE(m2.Matches("H"));
1817 EXPECT_FALSE(m2.Matches(" Hi"));
1e59de90
TL
1818
1819#if GTEST_INTERNAL_HAS_STRING_VIEW
1820 const Matcher<internal::StringView> m_empty =
1821 StartsWith(internal::StringView(""));
1822 EXPECT_TRUE(m_empty.Matches(internal::StringView()));
1823 EXPECT_TRUE(m_empty.Matches(internal::StringView("")));
1824 EXPECT_TRUE(m_empty.Matches(internal::StringView("not empty")));
1825#endif // GTEST_INTERNAL_HAS_STRING_VIEW
31f18b77
FG
1826}
1827
1828TEST(StartsWithTest, CanDescribeSelf) {
1829 Matcher<const std::string> m = StartsWith("Hi");
1830 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1831}
1832
1833// Tests EndsWith(s).
1834
1835TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1836 const Matcher<const char*> m1 = EndsWith("");
1837 EXPECT_TRUE(m1.Matches("Hi"));
1838 EXPECT_TRUE(m1.Matches(""));
1e59de90 1839 EXPECT_FALSE(m1.Matches(nullptr));
31f18b77 1840
1e59de90 1841 const Matcher<const std::string&> m2 = EndsWith(std::string("Hi"));
31f18b77
FG
1842 EXPECT_TRUE(m2.Matches("Hi"));
1843 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1844 EXPECT_TRUE(m2.Matches("Super Hi"));
1845 EXPECT_FALSE(m2.Matches("i"));
1846 EXPECT_FALSE(m2.Matches("Hi "));
1e59de90
TL
1847
1848#if GTEST_INTERNAL_HAS_STRING_VIEW
1849 const Matcher<const internal::StringView&> m4 =
1850 EndsWith(internal::StringView(""));
1851 EXPECT_TRUE(m4.Matches("Hi"));
1852 EXPECT_TRUE(m4.Matches(""));
1853 EXPECT_TRUE(m4.Matches(internal::StringView()));
1854 EXPECT_TRUE(m4.Matches(internal::StringView("")));
1855#endif // GTEST_INTERNAL_HAS_STRING_VIEW
31f18b77
FG
1856}
1857
1858TEST(EndsWithTest, CanDescribeSelf) {
1859 Matcher<const std::string> m = EndsWith("Hi");
1860 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1861}
1862
1863// Tests MatchesRegex().
1864
1865TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1866 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1867 EXPECT_TRUE(m1.Matches("az"));
1868 EXPECT_TRUE(m1.Matches("abcz"));
1e59de90 1869 EXPECT_FALSE(m1.Matches(nullptr));
31f18b77 1870
1e59de90 1871 const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z"));
31f18b77
FG
1872 EXPECT_TRUE(m2.Matches("azbz"));
1873 EXPECT_FALSE(m2.Matches("az1"));
1874 EXPECT_FALSE(m2.Matches("1az"));
1e59de90
TL
1875
1876#if GTEST_INTERNAL_HAS_STRING_VIEW
1877 const Matcher<const internal::StringView&> m3 = MatchesRegex("a.*z");
1878 EXPECT_TRUE(m3.Matches(internal::StringView("az")));
1879 EXPECT_TRUE(m3.Matches(internal::StringView("abcz")));
1880 EXPECT_FALSE(m3.Matches(internal::StringView("1az")));
1881 EXPECT_FALSE(m3.Matches(internal::StringView()));
1882 const Matcher<const internal::StringView&> m4 =
1883 MatchesRegex(internal::StringView(""));
1884 EXPECT_TRUE(m4.Matches(internal::StringView("")));
1885 EXPECT_TRUE(m4.Matches(internal::StringView()));
1886#endif // GTEST_INTERNAL_HAS_STRING_VIEW
31f18b77
FG
1887}
1888
1889TEST(MatchesRegexTest, CanDescribeSelf) {
1e59de90 1890 Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*"));
31f18b77
FG
1891 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1892
1893 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1894 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
1e59de90
TL
1895
1896#if GTEST_INTERNAL_HAS_STRING_VIEW
1897 Matcher<const internal::StringView> m3 = MatchesRegex(new RE("0.*"));
1898 EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3));
1899#endif // GTEST_INTERNAL_HAS_STRING_VIEW
31f18b77
FG
1900}
1901
1902// Tests ContainsRegex().
1903
1904TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1e59de90 1905 const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z"));
31f18b77
FG
1906 EXPECT_TRUE(m1.Matches("az"));
1907 EXPECT_TRUE(m1.Matches("0abcz1"));
1e59de90 1908 EXPECT_FALSE(m1.Matches(nullptr));
31f18b77 1909
1e59de90 1910 const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z"));
31f18b77
FG
1911 EXPECT_TRUE(m2.Matches("azbz"));
1912 EXPECT_TRUE(m2.Matches("az1"));
1913 EXPECT_FALSE(m2.Matches("1a"));
1e59de90
TL
1914
1915#if GTEST_INTERNAL_HAS_STRING_VIEW
1916 const Matcher<const internal::StringView&> m3 =
1917 ContainsRegex(new RE("a.*z"));
1918 EXPECT_TRUE(m3.Matches(internal::StringView("azbz")));
1919 EXPECT_TRUE(m3.Matches(internal::StringView("az1")));
1920 EXPECT_FALSE(m3.Matches(internal::StringView("1a")));
1921 EXPECT_FALSE(m3.Matches(internal::StringView()));
1922 const Matcher<const internal::StringView&> m4 =
1923 ContainsRegex(internal::StringView(""));
1924 EXPECT_TRUE(m4.Matches(internal::StringView("")));
1925 EXPECT_TRUE(m4.Matches(internal::StringView()));
1926#endif // GTEST_INTERNAL_HAS_STRING_VIEW
31f18b77
FG
1927}
1928
1929TEST(ContainsRegexTest, CanDescribeSelf) {
1930 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1931 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1932
1933 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1934 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
1e59de90
TL
1935
1936#if GTEST_INTERNAL_HAS_STRING_VIEW
1937 Matcher<const internal::StringView> m3 = ContainsRegex(new RE("0.*"));
1938 EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3));
1939#endif // GTEST_INTERNAL_HAS_STRING_VIEW
31f18b77
FG
1940}
1941
1942// Tests for wide strings.
1943#if GTEST_HAS_STD_WSTRING
1944TEST(StdWideStrEqTest, MatchesEqual) {
1945 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1946 EXPECT_TRUE(m.Matches(L"Hello"));
1947 EXPECT_FALSE(m.Matches(L"hello"));
1e59de90 1948 EXPECT_FALSE(m.Matches(nullptr));
31f18b77
FG
1949
1950 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1951 EXPECT_TRUE(m2.Matches(L"Hello"));
1952 EXPECT_FALSE(m2.Matches(L"Hi"));
1953
1954 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1955 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1956 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1957
1958 ::std::wstring str(L"01204500800");
1959 str[3] = L'\0';
1960 Matcher<const ::std::wstring&> m4 = StrEq(str);
1961 EXPECT_TRUE(m4.Matches(str));
1962 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1963 Matcher<const ::std::wstring&> m5 = StrEq(str);
1964 EXPECT_TRUE(m5.Matches(str));
1965}
1966
1967TEST(StdWideStrEqTest, CanDescribeSelf) {
1968 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1969 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
1970 Describe(m));
1971
1972 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1973 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1974 Describe(m2));
1975
1976 ::std::wstring str(L"01204500800");
1977 str[3] = L'\0';
1978 Matcher<const ::std::wstring&> m4 = StrEq(str);
1979 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1980 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1981 Matcher<const ::std::wstring&> m5 = StrEq(str);
1982 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1983}
1984
1985TEST(StdWideStrNeTest, MatchesUnequalString) {
1986 Matcher<const wchar_t*> m = StrNe(L"Hello");
1987 EXPECT_TRUE(m.Matches(L""));
1e59de90 1988 EXPECT_TRUE(m.Matches(nullptr));
31f18b77
FG
1989 EXPECT_FALSE(m.Matches(L"Hello"));
1990
1991 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1992 EXPECT_TRUE(m2.Matches(L"hello"));
1993 EXPECT_FALSE(m2.Matches(L"Hello"));
1994}
1995
1996TEST(StdWideStrNeTest, CanDescribeSelf) {
1997 Matcher<const wchar_t*> m = StrNe(L"Hi");
1998 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
1999}
2000
2001TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
2002 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
2003 EXPECT_TRUE(m.Matches(L"Hello"));
2004 EXPECT_TRUE(m.Matches(L"hello"));
2005 EXPECT_FALSE(m.Matches(L"Hi"));
1e59de90 2006 EXPECT_FALSE(m.Matches(nullptr));
31f18b77
FG
2007
2008 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
2009 EXPECT_TRUE(m2.Matches(L"hello"));
2010 EXPECT_FALSE(m2.Matches(L"Hi"));
2011}
2012
2013TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
2014 ::std::wstring str1(L"oabocdooeoo");
2015 ::std::wstring str2(L"OABOCDOOEOO");
2016 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
2017 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
2018
2019 str1[3] = str2[3] = L'\0';
2020 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
2021 EXPECT_TRUE(m1.Matches(str2));
2022
2023 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
2024 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
2025 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
2026 str1[9] = str2[9] = L'\0';
2027 EXPECT_FALSE(m2.Matches(str2));
2028
2029 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
2030 EXPECT_TRUE(m3.Matches(str2));
2031
2032 EXPECT_FALSE(m3.Matches(str2 + L"x"));
2033 str2.append(1, L'\0');
2034 EXPECT_FALSE(m3.Matches(str2));
2035 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
2036}
2037
2038TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
2039 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
2040 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
2041}
2042
2043TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
2044 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
2045 EXPECT_TRUE(m.Matches(L"Hi"));
1e59de90 2046 EXPECT_TRUE(m.Matches(nullptr));
31f18b77
FG
2047 EXPECT_FALSE(m.Matches(L"Hello"));
2048 EXPECT_FALSE(m.Matches(L"hello"));
2049
2050 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
2051 EXPECT_TRUE(m2.Matches(L""));
2052 EXPECT_FALSE(m2.Matches(L"Hello"));
2053}
2054
2055TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
2056 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
2057 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
2058}
2059
2060// Tests that HasSubstr() works for matching wstring-typed values.
2061TEST(StdWideHasSubstrTest, WorksForStringClasses) {
2062 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
2063 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
2064 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
2065
2066 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
2067 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
2068 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
2069}
2070
2071// Tests that HasSubstr() works for matching C-wide-string-typed values.
2072TEST(StdWideHasSubstrTest, WorksForCStrings) {
2073 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
2074 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
2075 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1e59de90 2076 EXPECT_FALSE(m1.Matches(nullptr));
31f18b77
FG
2077
2078 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
2079 EXPECT_TRUE(m2.Matches(L"I love food."));
2080 EXPECT_FALSE(m2.Matches(L"tofo"));
1e59de90 2081 EXPECT_FALSE(m2.Matches(nullptr));
31f18b77
FG
2082}
2083
2084// Tests that HasSubstr(s) describes itself properly.
2085TEST(StdWideHasSubstrTest, CanDescribeSelf) {
2086 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
2087 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
2088}
2089
2090// Tests StartsWith(s).
2091
2092TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
2093 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
2094 EXPECT_TRUE(m1.Matches(L"Hi"));
2095 EXPECT_TRUE(m1.Matches(L""));
1e59de90 2096 EXPECT_FALSE(m1.Matches(nullptr));
31f18b77
FG
2097
2098 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
2099 EXPECT_TRUE(m2.Matches(L"Hi"));
2100 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
2101 EXPECT_TRUE(m2.Matches(L"High"));
2102 EXPECT_FALSE(m2.Matches(L"H"));
2103 EXPECT_FALSE(m2.Matches(L" Hi"));
2104}
2105
2106TEST(StdWideStartsWithTest, CanDescribeSelf) {
2107 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
2108 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
2109}
2110
2111// Tests EndsWith(s).
2112
2113TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
2114 const Matcher<const wchar_t*> m1 = EndsWith(L"");
2115 EXPECT_TRUE(m1.Matches(L"Hi"));
2116 EXPECT_TRUE(m1.Matches(L""));
1e59de90 2117 EXPECT_FALSE(m1.Matches(nullptr));
31f18b77
FG
2118
2119 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
2120 EXPECT_TRUE(m2.Matches(L"Hi"));
2121 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
2122 EXPECT_TRUE(m2.Matches(L"Super Hi"));
2123 EXPECT_FALSE(m2.Matches(L"i"));
2124 EXPECT_FALSE(m2.Matches(L"Hi "));
2125}
2126
2127TEST(StdWideEndsWithTest, CanDescribeSelf) {
2128 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
2129 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
2130}
2131
2132#endif // GTEST_HAS_STD_WSTRING
2133
1e59de90 2134typedef ::std::tuple<long, int> Tuple2; // NOLINT
31f18b77 2135
1e59de90
TL
2136// Tests that Eq() matches a 2-tuple where the first field == the
2137// second field.
2138TEST(Eq2Test, MatchesEqualArguments) {
2139 Matcher<const Tuple2&> m = Eq();
2140 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2141 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
2142}
31f18b77 2143
1e59de90
TL
2144// Tests that Eq() describes itself properly.
2145TEST(Eq2Test, CanDescribeSelf) {
2146 Matcher<const Tuple2&> m = Eq();
2147 EXPECT_EQ("are an equal pair", Describe(m));
2148}
31f18b77 2149
1e59de90
TL
2150// Tests that Ge() matches a 2-tuple where the first field >= the
2151// second field.
2152TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
2153 Matcher<const Tuple2&> m = Ge();
2154 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2155 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2156 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
31f18b77
FG
2157}
2158
1e59de90
TL
2159// Tests that Ge() describes itself properly.
2160TEST(Ge2Test, CanDescribeSelf) {
2161 Matcher<const Tuple2&> m = Ge();
2162 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
2163}
31f18b77 2164
1e59de90
TL
2165// Tests that Gt() matches a 2-tuple where the first field > the
2166// second field.
2167TEST(Gt2Test, MatchesGreaterThanArguments) {
2168 Matcher<const Tuple2&> m = Gt();
2169 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2170 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2171 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
2172}
31f18b77 2173
1e59de90
TL
2174// Tests that Gt() describes itself properly.
2175TEST(Gt2Test, CanDescribeSelf) {
2176 Matcher<const Tuple2&> m = Gt();
2177 EXPECT_EQ("are a pair where the first > the second", Describe(m));
31f18b77
FG
2178}
2179
1e59de90
TL
2180// Tests that Le() matches a 2-tuple where the first field <= the
2181// second field.
2182TEST(Le2Test, MatchesLessThanOrEqualArguments) {
2183 Matcher<const Tuple2&> m = Le();
2184 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2185 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2186 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
2187}
31f18b77 2188
1e59de90
TL
2189// Tests that Le() describes itself properly.
2190TEST(Le2Test, CanDescribeSelf) {
2191 Matcher<const Tuple2&> m = Le();
2192 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
31f18b77
FG
2193}
2194
1e59de90
TL
2195// Tests that Lt() matches a 2-tuple where the first field < the
2196// second field.
2197TEST(Lt2Test, MatchesLessThanArguments) {
2198 Matcher<const Tuple2&> m = Lt();
2199 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2200 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2201 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
31f18b77
FG
2202}
2203
1e59de90
TL
2204// Tests that Lt() describes itself properly.
2205TEST(Lt2Test, CanDescribeSelf) {
2206 Matcher<const Tuple2&> m = Lt();
2207 EXPECT_EQ("are a pair where the first < the second", Describe(m));
2208}
31f18b77 2209
1e59de90
TL
2210// Tests that Ne() matches a 2-tuple where the first field != the
2211// second field.
2212TEST(Ne2Test, MatchesUnequalArguments) {
2213 Matcher<const Tuple2&> m = Ne();
2214 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2215 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2216 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
31f18b77
FG
2217}
2218
1e59de90
TL
2219// Tests that Ne() describes itself properly.
2220TEST(Ne2Test, CanDescribeSelf) {
2221 Matcher<const Tuple2&> m = Ne();
2222 EXPECT_EQ("are an unequal pair", Describe(m));
2223}
31f18b77 2224
1e59de90
TL
2225TEST(PairMatchBaseTest, WorksWithMoveOnly) {
2226 using Pointers = std::tuple<std::unique_ptr<int>, std::unique_ptr<int>>;
2227 Matcher<Pointers> matcher = Eq();
2228 Pointers pointers;
2229 // Tested values don't matter; the point is that matcher does not copy the
2230 // matched values.
2231 EXPECT_TRUE(matcher.Matches(pointers));
31f18b77
FG
2232}
2233
1e59de90
TL
2234// Tests that IsNan() matches a NaN, with float.
2235TEST(IsNan, FloatMatchesNan) {
2236 float quiet_nan = std::numeric_limits<float>::quiet_NaN();
2237 float other_nan = std::nanf("1");
2238 float real_value = 1.0f;
31f18b77 2239
1e59de90
TL
2240 Matcher<float> m = IsNan();
2241 EXPECT_TRUE(m.Matches(quiet_nan));
2242 EXPECT_TRUE(m.Matches(other_nan));
2243 EXPECT_FALSE(m.Matches(real_value));
31f18b77 2244
1e59de90
TL
2245 Matcher<float&> m_ref = IsNan();
2246 EXPECT_TRUE(m_ref.Matches(quiet_nan));
2247 EXPECT_TRUE(m_ref.Matches(other_nan));
2248 EXPECT_FALSE(m_ref.Matches(real_value));
31f18b77 2249
1e59de90
TL
2250 Matcher<const float&> m_cref = IsNan();
2251 EXPECT_TRUE(m_cref.Matches(quiet_nan));
2252 EXPECT_TRUE(m_cref.Matches(other_nan));
2253 EXPECT_FALSE(m_cref.Matches(real_value));
31f18b77
FG
2254}
2255
1e59de90
TL
2256// Tests that IsNan() matches a NaN, with double.
2257TEST(IsNan, DoubleMatchesNan) {
2258 double quiet_nan = std::numeric_limits<double>::quiet_NaN();
2259 double other_nan = std::nan("1");
2260 double real_value = 1.0;
31f18b77 2261
1e59de90
TL
2262 Matcher<double> m = IsNan();
2263 EXPECT_TRUE(m.Matches(quiet_nan));
2264 EXPECT_TRUE(m.Matches(other_nan));
2265 EXPECT_FALSE(m.Matches(real_value));
2266
2267 Matcher<double&> m_ref = IsNan();
2268 EXPECT_TRUE(m_ref.Matches(quiet_nan));
2269 EXPECT_TRUE(m_ref.Matches(other_nan));
2270 EXPECT_FALSE(m_ref.Matches(real_value));
31f18b77 2271
1e59de90
TL
2272 Matcher<const double&> m_cref = IsNan();
2273 EXPECT_TRUE(m_cref.Matches(quiet_nan));
2274 EXPECT_TRUE(m_cref.Matches(other_nan));
2275 EXPECT_FALSE(m_cref.Matches(real_value));
31f18b77
FG
2276}
2277
1e59de90
TL
2278// Tests that IsNan() matches a NaN, with long double.
2279TEST(IsNan, LongDoubleMatchesNan) {
2280 long double quiet_nan = std::numeric_limits<long double>::quiet_NaN();
2281 long double other_nan = std::nan("1");
2282 long double real_value = 1.0;
2283
2284 Matcher<long double> m = IsNan();
2285 EXPECT_TRUE(m.Matches(quiet_nan));
2286 EXPECT_TRUE(m.Matches(other_nan));
2287 EXPECT_FALSE(m.Matches(real_value));
31f18b77 2288
1e59de90
TL
2289 Matcher<long double&> m_ref = IsNan();
2290 EXPECT_TRUE(m_ref.Matches(quiet_nan));
2291 EXPECT_TRUE(m_ref.Matches(other_nan));
2292 EXPECT_FALSE(m_ref.Matches(real_value));
31f18b77 2293
1e59de90
TL
2294 Matcher<const long double&> m_cref = IsNan();
2295 EXPECT_TRUE(m_cref.Matches(quiet_nan));
2296 EXPECT_TRUE(m_cref.Matches(other_nan));
2297 EXPECT_FALSE(m_cref.Matches(real_value));
2298}
2299
2300// Tests that IsNan() works with Not.
2301TEST(IsNan, NotMatchesNan) {
2302 Matcher<float> mf = Not(IsNan());
2303 EXPECT_FALSE(mf.Matches(std::numeric_limits<float>::quiet_NaN()));
2304 EXPECT_FALSE(mf.Matches(std::nanf("1")));
2305 EXPECT_TRUE(mf.Matches(1.0));
2306
2307 Matcher<double> md = Not(IsNan());
2308 EXPECT_FALSE(md.Matches(std::numeric_limits<double>::quiet_NaN()));
2309 EXPECT_FALSE(md.Matches(std::nan("1")));
2310 EXPECT_TRUE(md.Matches(1.0));
31f18b77 2311
1e59de90
TL
2312 Matcher<long double> mld = Not(IsNan());
2313 EXPECT_FALSE(mld.Matches(std::numeric_limits<long double>::quiet_NaN()));
2314 EXPECT_FALSE(mld.Matches(std::nanl("1")));
2315 EXPECT_TRUE(mld.Matches(1.0));
2316}
2317
2318// Tests that IsNan() can describe itself.
2319TEST(IsNan, CanDescribeSelf) {
2320 Matcher<float> mf = IsNan();
2321 EXPECT_EQ("is NaN", Describe(mf));
2322
2323 Matcher<double> md = IsNan();
2324 EXPECT_EQ("is NaN", Describe(md));
2325
2326 Matcher<long double> mld = IsNan();
2327 EXPECT_EQ("is NaN", Describe(mld));
2328}
2329
2330// Tests that IsNan() can describe itself with Not.
2331TEST(IsNan, CanDescribeSelfWithNot) {
2332 Matcher<float> mf = Not(IsNan());
2333 EXPECT_EQ("isn't NaN", Describe(mf));
2334
2335 Matcher<double> md = Not(IsNan());
2336 EXPECT_EQ("isn't NaN", Describe(md));
2337
2338 Matcher<long double> mld = Not(IsNan());
2339 EXPECT_EQ("isn't NaN", Describe(mld));
2340}
2341
2342// Tests that FloatEq() matches a 2-tuple where
2343// FloatEq(first field) matches the second field.
2344TEST(FloatEq2Test, MatchesEqualArguments) {
2345 typedef ::std::tuple<float, float> Tpl;
2346 Matcher<const Tpl&> m = FloatEq();
2347 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2348 EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f)));
2349 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2350}
2351
2352// Tests that FloatEq() describes itself properly.
2353TEST(FloatEq2Test, CanDescribeSelf) {
2354 Matcher<const ::std::tuple<float, float>&> m = FloatEq();
2355 EXPECT_EQ("are an almost-equal pair", Describe(m));
2356}
2357
2358// Tests that NanSensitiveFloatEq() matches a 2-tuple where
2359// NanSensitiveFloatEq(first field) matches the second field.
2360TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) {
2361 typedef ::std::tuple<float, float> Tpl;
2362 Matcher<const Tpl&> m = NanSensitiveFloatEq();
2363 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2364 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
2365 std::numeric_limits<float>::quiet_NaN())));
2366 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2367 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
2368 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
2369}
2370
2371// Tests that NanSensitiveFloatEq() describes itself properly.
2372TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) {
2373 Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatEq();
2374 EXPECT_EQ("are an almost-equal pair", Describe(m));
2375}
2376
2377// Tests that DoubleEq() matches a 2-tuple where
2378// DoubleEq(first field) matches the second field.
2379TEST(DoubleEq2Test, MatchesEqualArguments) {
2380 typedef ::std::tuple<double, double> Tpl;
2381 Matcher<const Tpl&> m = DoubleEq();
2382 EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
2383 EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1)));
2384 EXPECT_FALSE(m.Matches(Tpl(1.1, 1.0)));
2385}
2386
2387// Tests that DoubleEq() describes itself properly.
2388TEST(DoubleEq2Test, CanDescribeSelf) {
2389 Matcher<const ::std::tuple<double, double>&> m = DoubleEq();
2390 EXPECT_EQ("are an almost-equal pair", Describe(m));
2391}
2392
2393// Tests that NanSensitiveDoubleEq() matches a 2-tuple where
2394// NanSensitiveDoubleEq(first field) matches the second field.
2395TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) {
2396 typedef ::std::tuple<double, double> Tpl;
2397 Matcher<const Tpl&> m = NanSensitiveDoubleEq();
2398 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2399 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
2400 std::numeric_limits<double>::quiet_NaN())));
2401 EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));
2402 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
2403 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
2404}
31f18b77 2405
1e59de90
TL
2406// Tests that DoubleEq() describes itself properly.
2407TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) {
2408 Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleEq();
2409 EXPECT_EQ("are an almost-equal pair", Describe(m));
31f18b77
FG
2410}
2411
1e59de90
TL
2412// Tests that FloatEq() matches a 2-tuple where
2413// FloatNear(first field, max_abs_error) matches the second field.
2414TEST(FloatNear2Test, MatchesEqualArguments) {
2415 typedef ::std::tuple<float, float> Tpl;
2416 Matcher<const Tpl&> m = FloatNear(0.5f);
2417 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2418 EXPECT_TRUE(m.Matches(Tpl(1.3f, 1.0f)));
2419 EXPECT_FALSE(m.Matches(Tpl(1.8f, 1.0f)));
2420}
31f18b77 2421
1e59de90
TL
2422// Tests that FloatNear() describes itself properly.
2423TEST(FloatNear2Test, CanDescribeSelf) {
2424 Matcher<const ::std::tuple<float, float>&> m = FloatNear(0.5f);
2425 EXPECT_EQ("are an almost-equal pair", Describe(m));
2426}
2427
2428// Tests that NanSensitiveFloatNear() matches a 2-tuple where
2429// NanSensitiveFloatNear(first field) matches the second field.
2430TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) {
2431 typedef ::std::tuple<float, float> Tpl;
2432 Matcher<const Tpl&> m = NanSensitiveFloatNear(0.5f);
2433 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2434 EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
2435 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),
2436 std::numeric_limits<float>::quiet_NaN())));
2437 EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
2438 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));
2439 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));
2440}
2441
2442// Tests that NanSensitiveFloatNear() describes itself properly.
2443TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) {
2444 Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatNear(0.5f);
2445 EXPECT_EQ("are an almost-equal pair", Describe(m));
2446}
2447
2448// Tests that FloatEq() matches a 2-tuple where
2449// DoubleNear(first field, max_abs_error) matches the second field.
2450TEST(DoubleNear2Test, MatchesEqualArguments) {
2451 typedef ::std::tuple<double, double> Tpl;
2452 Matcher<const Tpl&> m = DoubleNear(0.5);
2453 EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));
2454 EXPECT_TRUE(m.Matches(Tpl(1.3, 1.0)));
2455 EXPECT_FALSE(m.Matches(Tpl(1.8, 1.0)));
2456}
2457
2458// Tests that DoubleNear() describes itself properly.
2459TEST(DoubleNear2Test, CanDescribeSelf) {
2460 Matcher<const ::std::tuple<double, double>&> m = DoubleNear(0.5);
2461 EXPECT_EQ("are an almost-equal pair", Describe(m));
2462}
2463
2464// Tests that NanSensitiveDoubleNear() matches a 2-tuple where
2465// NanSensitiveDoubleNear(first field) matches the second field.
2466TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) {
2467 typedef ::std::tuple<double, double> Tpl;
2468 Matcher<const Tpl&> m = NanSensitiveDoubleNear(0.5f);
2469 EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));
2470 EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));
2471 EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),
2472 std::numeric_limits<double>::quiet_NaN())));
2473 EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));
2474 EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));
2475 EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));
2476}
2477
2478// Tests that NanSensitiveDoubleNear() describes itself properly.
2479TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) {
2480 Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleNear(0.5f);
2481 EXPECT_EQ("are an almost-equal pair", Describe(m));
31f18b77
FG
2482}
2483
2484// Tests that Not(m) matches any value that doesn't match m.
2485TEST(NotTest, NegatesMatcher) {
2486 Matcher<int> m;
2487 m = Not(Eq(2));
2488 EXPECT_TRUE(m.Matches(3));
2489 EXPECT_FALSE(m.Matches(2));
2490}
2491
2492// Tests that Not(m) describes itself properly.
2493TEST(NotTest, CanDescribeSelf) {
2494 Matcher<int> m = Not(Eq(5));
2495 EXPECT_EQ("isn't equal to 5", Describe(m));
2496}
2497
2498// Tests that monomorphic matchers are safely cast by the Not matcher.
2499TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2500 // greater_than_5 is a monomorphic matcher.
2501 Matcher<int> greater_than_5 = Gt(5);
2502
2503 Matcher<const int&> m = Not(greater_than_5);
2504 Matcher<int&> m2 = Not(greater_than_5);
2505 Matcher<int&> m3 = Not(m);
2506}
2507
2508// Helper to allow easy testing of AllOf matchers with num parameters.
2509void AllOfMatches(int num, const Matcher<int>& m) {
2510 SCOPED_TRACE(Describe(m));
2511 EXPECT_TRUE(m.Matches(0));
2512 for (int i = 1; i <= num; ++i) {
2513 EXPECT_FALSE(m.Matches(i));
2514 }
2515 EXPECT_TRUE(m.Matches(num + 1));
2516}
2517
2518// Tests that AllOf(m1, ..., mn) matches any value that matches all of
2519// the given matchers.
2520TEST(AllOfTest, MatchesWhenAllMatch) {
2521 Matcher<int> m;
2522 m = AllOf(Le(2), Ge(1));
2523 EXPECT_TRUE(m.Matches(1));
2524 EXPECT_TRUE(m.Matches(2));
2525 EXPECT_FALSE(m.Matches(0));
2526 EXPECT_FALSE(m.Matches(3));
2527
2528 m = AllOf(Gt(0), Ne(1), Ne(2));
2529 EXPECT_TRUE(m.Matches(3));
2530 EXPECT_FALSE(m.Matches(2));
2531 EXPECT_FALSE(m.Matches(1));
2532 EXPECT_FALSE(m.Matches(0));
2533
2534 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2535 EXPECT_TRUE(m.Matches(4));
2536 EXPECT_FALSE(m.Matches(3));
2537 EXPECT_FALSE(m.Matches(2));
2538 EXPECT_FALSE(m.Matches(1));
2539 EXPECT_FALSE(m.Matches(0));
2540
2541 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2542 EXPECT_TRUE(m.Matches(0));
2543 EXPECT_TRUE(m.Matches(1));
2544 EXPECT_FALSE(m.Matches(3));
2545
2546 // The following tests for varying number of sub-matchers. Due to the way
2547 // the sub-matchers are handled it is enough to test every sub-matcher once
2548 // with sub-matchers using the same matcher type. Varying matcher types are
2549 // checked for above.
2550 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2551 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2552 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2553 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2554 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2555 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2556 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2557 Ne(8)));
2558 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2559 Ne(8), Ne(9)));
2560 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2561 Ne(9), Ne(10)));
1e59de90
TL
2562 AllOfMatches(
2563 50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
2564 Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), Ne(16), Ne(17),
2565 Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), Ne(23), Ne(24), Ne(25),
2566 Ne(26), Ne(27), Ne(28), Ne(29), Ne(30), Ne(31), Ne(32), Ne(33),
2567 Ne(34), Ne(35), Ne(36), Ne(37), Ne(38), Ne(39), Ne(40), Ne(41),
2568 Ne(42), Ne(43), Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2569 Ne(50)));
31f18b77
FG
2570}
2571
31f18b77
FG
2572
2573// Tests that AllOf(m1, ..., mn) describes itself properly.
2574TEST(AllOfTest, CanDescribeSelf) {
2575 Matcher<int> m;
2576 m = AllOf(Le(2), Ge(1));
2577 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
2578
2579 m = AllOf(Gt(0), Ne(1), Ne(2));
1e59de90
TL
2580 std::string expected_descr1 =
2581 "(is > 0) and (isn't equal to 1) and (isn't equal to 2)";
2582 EXPECT_EQ(expected_descr1, Describe(m));
31f18b77
FG
2583
2584 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
1e59de90
TL
2585 std::string expected_descr2 =
2586 "(is > 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't equal "
2587 "to 3)";
2588 EXPECT_EQ(expected_descr2, Describe(m));
31f18b77
FG
2589
2590 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
1e59de90
TL
2591 std::string expected_descr3 =
2592 "(is >= 0) and (is < 10) and (isn't equal to 3) and (isn't equal to 5) "
2593 "and (isn't equal to 7)";
2594 EXPECT_EQ(expected_descr3, Describe(m));
31f18b77
FG
2595}
2596
2597// Tests that AllOf(m1, ..., mn) describes its negation properly.
2598TEST(AllOfTest, CanDescribeNegation) {
2599 Matcher<int> m;
2600 m = AllOf(Le(2), Ge(1));
1e59de90
TL
2601 std::string expected_descr4 = "(isn't <= 2) or (isn't >= 1)";
2602 EXPECT_EQ(expected_descr4, DescribeNegation(m));
31f18b77
FG
2603
2604 m = AllOf(Gt(0), Ne(1), Ne(2));
1e59de90
TL
2605 std::string expected_descr5 =
2606 "(isn't > 0) or (is equal to 1) or (is equal to 2)";
2607 EXPECT_EQ(expected_descr5, DescribeNegation(m));
31f18b77
FG
2608
2609 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
1e59de90
TL
2610 std::string expected_descr6 =
2611 "(isn't > 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)";
2612 EXPECT_EQ(expected_descr6, DescribeNegation(m));
31f18b77
FG
2613
2614 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
1e59de90
TL
2615 std::string expected_desr7 =
2616 "(isn't >= 0) or (isn't < 10) or (is equal to 3) or (is equal to 5) or "
2617 "(is equal to 7)";
2618 EXPECT_EQ(expected_desr7, DescribeNegation(m));
2619
2620 m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),
2621 Ne(10), Ne(11));
2622 AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2623 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)"));
2624 AllOfMatches(11, m);
31f18b77
FG
2625}
2626
2627// Tests that monomorphic matchers are safely cast by the AllOf matcher.
2628TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2629 // greater_than_5 and less_than_10 are monomorphic matchers.
2630 Matcher<int> greater_than_5 = Gt(5);
2631 Matcher<int> less_than_10 = Lt(10);
2632
2633 Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2634 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2635 Matcher<int&> m3 = AllOf(greater_than_5, m2);
2636
2637 // Tests that BothOf works when composing itself.
2638 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2639 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2640}
2641
2642TEST(AllOfTest, ExplainsResult) {
2643 Matcher<int> m;
2644
2645 // Successful match. Both matchers need to explain. The second
2646 // matcher doesn't give an explanation, so only the first matcher's
2647 // explanation is printed.
2648 m = AllOf(GreaterThan(10), Lt(30));
2649 EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2650
2651 // Successful match. Both matchers need to explain.
2652 m = AllOf(GreaterThan(10), GreaterThan(20));
2653 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2654 Explain(m, 30));
2655
2656 // Successful match. All matchers need to explain. The second
2657 // matcher doesn't given an explanation.
2658 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2659 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2660 Explain(m, 25));
2661
2662 // Successful match. All matchers need to explain.
2663 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2664 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2665 "and which is 10 more than 30",
2666 Explain(m, 40));
2667
2668 // Failed match. The first matcher, which failed, needs to
2669 // explain.
2670 m = AllOf(GreaterThan(10), GreaterThan(20));
2671 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2672
2673 // Failed match. The second matcher, which failed, needs to
2674 // explain. Since it doesn't given an explanation, nothing is
2675 // printed.
2676 m = AllOf(GreaterThan(10), Lt(30));
2677 EXPECT_EQ("", Explain(m, 40));
2678
2679 // Failed match. The second matcher, which failed, needs to
2680 // explain.
2681 m = AllOf(GreaterThan(10), GreaterThan(20));
2682 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2683}
2684
2685// Helper to allow easy testing of AnyOf matchers with num parameters.
1e59de90 2686static void AnyOfMatches(int num, const Matcher<int>& m) {
31f18b77
FG
2687 SCOPED_TRACE(Describe(m));
2688 EXPECT_FALSE(m.Matches(0));
2689 for (int i = 1; i <= num; ++i) {
2690 EXPECT_TRUE(m.Matches(i));
2691 }
2692 EXPECT_FALSE(m.Matches(num + 1));
2693}
2694
1e59de90
TL
2695static void AnyOfStringMatches(int num, const Matcher<std::string>& m) {
2696 SCOPED_TRACE(Describe(m));
2697 EXPECT_FALSE(m.Matches(std::to_string(0)));
2698
2699 for (int i = 1; i <= num; ++i) {
2700 EXPECT_TRUE(m.Matches(std::to_string(i)));
2701 }
2702 EXPECT_FALSE(m.Matches(std::to_string(num + 1)));
2703}
2704
31f18b77
FG
2705// Tests that AnyOf(m1, ..., mn) matches any value that matches at
2706// least one of the given matchers.
2707TEST(AnyOfTest, MatchesWhenAnyMatches) {
2708 Matcher<int> m;
2709 m = AnyOf(Le(1), Ge(3));
2710 EXPECT_TRUE(m.Matches(1));
2711 EXPECT_TRUE(m.Matches(4));
2712 EXPECT_FALSE(m.Matches(2));
2713
2714 m = AnyOf(Lt(0), Eq(1), Eq(2));
2715 EXPECT_TRUE(m.Matches(-1));
2716 EXPECT_TRUE(m.Matches(1));
2717 EXPECT_TRUE(m.Matches(2));
2718 EXPECT_FALSE(m.Matches(0));
2719
2720 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2721 EXPECT_TRUE(m.Matches(-1));
2722 EXPECT_TRUE(m.Matches(1));
2723 EXPECT_TRUE(m.Matches(2));
2724 EXPECT_TRUE(m.Matches(3));
2725 EXPECT_FALSE(m.Matches(0));
2726
2727 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2728 EXPECT_TRUE(m.Matches(0));
2729 EXPECT_TRUE(m.Matches(11));
2730 EXPECT_TRUE(m.Matches(3));
2731 EXPECT_FALSE(m.Matches(2));
2732
2733 // The following tests for varying number of sub-matchers. Due to the way
2734 // the sub-matchers are handled it is enough to test every sub-matcher once
2735 // with sub-matchers using the same matcher type. Varying matcher types are
2736 // checked for above.
2737 AnyOfMatches(2, AnyOf(1, 2));
2738 AnyOfMatches(3, AnyOf(1, 2, 3));
2739 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2740 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2741 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2742 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2743 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2744 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2745 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
2746}
2747
31f18b77
FG
2748// Tests the variadic version of the AnyOfMatcher.
2749TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2750 // Also make sure AnyOf is defined in the right namespace and does not depend
2751 // on ADL.
2752 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2753
1e59de90 2754 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)"));
31f18b77
FG
2755 AnyOfMatches(11, m);
2756 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2757 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2758 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2759 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2760 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
1e59de90
TL
2761 AnyOfStringMatches(
2762 50, AnyOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
2763 "13", "14", "15", "16", "17", "18", "19", "20", "21", "22",
2764 "23", "24", "25", "26", "27", "28", "29", "30", "31", "32",
2765 "33", "34", "35", "36", "37", "38", "39", "40", "41", "42",
2766 "43", "44", "45", "46", "47", "48", "49", "50"));
2767}
2768
2769// Tests the variadic version of the ElementsAreMatcher
2770TEST(ElementsAreTest, HugeMatcher) {
2771 vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
2772
2773 EXPECT_THAT(test_vector,
2774 ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7),
2775 Eq(8), Eq(9), Eq(10), Gt(1), Eq(12)));
2776}
2777
2778// Tests the variadic version of the UnorderedElementsAreMatcher
2779TEST(ElementsAreTest, HugeMatcherStr) {
2780 vector<std::string> test_vector{
2781 "literal_string", "", "", "", "", "", "", "", "", "", "", ""};
2782
2783 EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _,
2784 _, _, _, _, _, _));
2785}
2786
2787// Tests the variadic version of the UnorderedElementsAreMatcher
2788TEST(ElementsAreTest, HugeMatcherUnordered) {
2789 vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};
2790
2791 EXPECT_THAT(test_vector, UnorderedElementsAre(
2792 Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7),
2793 Eq(3), Eq(9), Eq(12), Eq(11), Ne(122)));
31f18b77
FG
2794}
2795
31f18b77
FG
2796
2797// Tests that AnyOf(m1, ..., mn) describes itself properly.
2798TEST(AnyOfTest, CanDescribeSelf) {
2799 Matcher<int> m;
2800 m = AnyOf(Le(1), Ge(3));
1e59de90 2801
31f18b77
FG
2802 EXPECT_EQ("(is <= 1) or (is >= 3)",
2803 Describe(m));
2804
2805 m = AnyOf(Lt(0), Eq(1), Eq(2));
1e59de90 2806 EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2)", Describe(m));
31f18b77
FG
2807
2808 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
1e59de90 2809 EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)",
31f18b77
FG
2810 Describe(m));
2811
2812 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
1e59de90
TL
2813 EXPECT_EQ(
2814 "(is <= 0) or (is > 10) or (is equal to 3) or (is equal to 5) or (is "
2815 "equal to 7)",
2816 Describe(m));
31f18b77
FG
2817}
2818
2819// Tests that AnyOf(m1, ..., mn) describes its negation properly.
2820TEST(AnyOfTest, CanDescribeNegation) {
2821 Matcher<int> m;
2822 m = AnyOf(Le(1), Ge(3));
2823 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2824 DescribeNegation(m));
2825
2826 m = AnyOf(Lt(0), Eq(1), Eq(2));
1e59de90 2827 EXPECT_EQ("(isn't < 0) and (isn't equal to 1) and (isn't equal to 2)",
31f18b77
FG
2828 DescribeNegation(m));
2829
2830 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
1e59de90
TL
2831 EXPECT_EQ(
2832 "(isn't < 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't "
2833 "equal to 3)",
2834 DescribeNegation(m));
31f18b77
FG
2835
2836 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
1e59de90
TL
2837 EXPECT_EQ(
2838 "(isn't <= 0) and (isn't > 10) and (isn't equal to 3) and (isn't equal "
2839 "to 5) and (isn't equal to 7)",
2840 DescribeNegation(m));
31f18b77
FG
2841}
2842
2843// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2844TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2845 // greater_than_5 and less_than_10 are monomorphic matchers.
2846 Matcher<int> greater_than_5 = Gt(5);
2847 Matcher<int> less_than_10 = Lt(10);
2848
2849 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2850 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2851 Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2852
2853 // Tests that EitherOf works when composing itself.
2854 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2855 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2856}
2857
2858TEST(AnyOfTest, ExplainsResult) {
2859 Matcher<int> m;
2860
2861 // Failed match. Both matchers need to explain. The second
2862 // matcher doesn't give an explanation, so only the first matcher's
2863 // explanation is printed.
2864 m = AnyOf(GreaterThan(10), Lt(0));
2865 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2866
2867 // Failed match. Both matchers need to explain.
2868 m = AnyOf(GreaterThan(10), GreaterThan(20));
2869 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2870 Explain(m, 5));
2871
2872 // Failed match. All matchers need to explain. The second
2873 // matcher doesn't given an explanation.
2874 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2875 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2876 Explain(m, 5));
2877
2878 // Failed match. All matchers need to explain.
2879 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2880 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2881 "and which is 25 less than 30",
2882 Explain(m, 5));
2883
2884 // Successful match. The first matcher, which succeeded, needs to
2885 // explain.
2886 m = AnyOf(GreaterThan(10), GreaterThan(20));
2887 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2888
2889 // Successful match. The second matcher, which succeeded, needs to
2890 // explain. Since it doesn't given an explanation, nothing is
2891 // printed.
2892 m = AnyOf(GreaterThan(10), Lt(30));
2893 EXPECT_EQ("", Explain(m, 0));
2894
2895 // Successful match. The second matcher, which succeeded, needs to
2896 // explain.
2897 m = AnyOf(GreaterThan(30), GreaterThan(20));
2898 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2899}
2900
2901// The following predicate function and predicate functor are for
2902// testing the Truly(predicate) matcher.
2903
2904// Returns non-zero if the input is positive. Note that the return
2905// type of this function is not bool. It's OK as Truly() accepts any
2906// unary function or functor whose return type can be implicitly
2907// converted to bool.
2908int IsPositive(double x) {
2909 return x > 0 ? 1 : 0;
2910}
2911
2912// This functor returns true if the input is greater than the given
2913// number.
2914class IsGreaterThan {
2915 public:
2916 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2917
2918 bool operator()(int n) const { return n > threshold_; }
2919
2920 private:
2921 int threshold_;
2922};
2923
2924// For testing Truly().
2925const int foo = 0;
2926
1e59de90
TL
2927// This predicate returns true if and only if the argument references foo and
2928// has a zero value.
31f18b77
FG
2929bool ReferencesFooAndIsZero(const int& n) {
2930 return (&n == &foo) && (n == 0);
2931}
2932
2933// Tests that Truly(predicate) matches what satisfies the given
2934// predicate.
2935TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2936 Matcher<double> m = Truly(IsPositive);
2937 EXPECT_TRUE(m.Matches(2.0));
2938 EXPECT_FALSE(m.Matches(-1.5));
2939}
2940
2941// Tests that Truly(predicate_functor) works too.
2942TEST(TrulyTest, CanBeUsedWithFunctor) {
2943 Matcher<int> m = Truly(IsGreaterThan(5));
2944 EXPECT_TRUE(m.Matches(6));
2945 EXPECT_FALSE(m.Matches(4));
2946}
2947
2948// A class that can be implicitly converted to bool.
2949class ConvertibleToBool {
2950 public:
2951 explicit ConvertibleToBool(int number) : number_(number) {}
2952 operator bool() const { return number_ != 0; }
2953
2954 private:
2955 int number_;
2956};
2957
2958ConvertibleToBool IsNotZero(int number) {
2959 return ConvertibleToBool(number);
2960}
2961
2962// Tests that the predicate used in Truly() may return a class that's
2963// implicitly convertible to bool, even when the class has no
2964// operator!().
2965TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2966 Matcher<int> m = Truly(IsNotZero);
2967 EXPECT_TRUE(m.Matches(1));
2968 EXPECT_FALSE(m.Matches(0));
2969}
2970
2971// Tests that Truly(predicate) can describe itself properly.
2972TEST(TrulyTest, CanDescribeSelf) {
2973 Matcher<double> m = Truly(IsPositive);
2974 EXPECT_EQ("satisfies the given predicate",
2975 Describe(m));
2976}
2977
2978// Tests that Truly(predicate) works when the matcher takes its
2979// argument by reference.
2980TEST(TrulyTest, WorksForByRefArguments) {
2981 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2982 EXPECT_TRUE(m.Matches(foo));
2983 int n = 0;
2984 EXPECT_FALSE(m.Matches(n));
2985}
2986
2987// Tests that Matches(m) is a predicate satisfied by whatever that
2988// matches matcher m.
2989TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2990 EXPECT_TRUE(Matches(Ge(0))(1));
2991 EXPECT_FALSE(Matches(Eq('a'))('b'));
2992}
2993
2994// Tests that Matches(m) works when the matcher takes its argument by
2995// reference.
2996TEST(MatchesTest, WorksOnByRefArguments) {
2997 int m = 0, n = 0;
2998 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2999 EXPECT_FALSE(Matches(Ref(m))(n));
3000}
3001
3002// Tests that a Matcher on non-reference type can be used in
3003// Matches().
3004TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
3005 Matcher<int> eq5 = Eq(5);
3006 EXPECT_TRUE(Matches(eq5)(5));
3007 EXPECT_FALSE(Matches(eq5)(2));
3008}
3009
3010// Tests Value(value, matcher). Since Value() is a simple wrapper for
3011// Matches(), which has been tested already, we don't spend a lot of
3012// effort on testing Value().
3013TEST(ValueTest, WorksWithPolymorphicMatcher) {
3014 EXPECT_TRUE(Value("hi", StartsWith("h")));
3015 EXPECT_FALSE(Value(5, Gt(10)));
3016}
3017
3018TEST(ValueTest, WorksWithMonomorphicMatcher) {
3019 const Matcher<int> is_zero = Eq(0);
3020 EXPECT_TRUE(Value(0, is_zero));
3021 EXPECT_FALSE(Value('a', is_zero));
3022
3023 int n = 0;
3024 const Matcher<const int&> ref_n = Ref(n);
3025 EXPECT_TRUE(Value(n, ref_n));
3026 EXPECT_FALSE(Value(1, ref_n));
3027}
3028
3029TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
3030 StringMatchResultListener listener1;
3031 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
3032 EXPECT_EQ("% 2 == 0", listener1.str());
3033
3034 StringMatchResultListener listener2;
3035 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
3036 EXPECT_EQ("", listener2.str());
3037}
3038
3039TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
3040 const Matcher<int> is_even = PolymorphicIsEven();
3041 StringMatchResultListener listener1;
3042 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
3043 EXPECT_EQ("% 2 == 0", listener1.str());
3044
3045 const Matcher<const double&> is_zero = Eq(0);
3046 StringMatchResultListener listener2;
3047 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
3048 EXPECT_EQ("", listener2.str());
3049}
3050
1e59de90
TL
3051MATCHER(ConstructNoArg, "") { return true; }
3052MATCHER_P(Construct1Arg, arg1, "") { return true; }
3053MATCHER_P2(Construct2Args, arg1, arg2, "") { return true; }
3054
3055TEST(MatcherConstruct, ExplicitVsImplicit) {
3056 {
3057 // No arg constructor can be constructed with empty brace.
3058 ConstructNoArgMatcher m = {};
3059 (void)m;
3060 // And with no args
3061 ConstructNoArgMatcher m2;
3062 (void)m2;
3063 }
3064 {
3065 // The one arg constructor has an explicit constructor.
3066 // This is to prevent the implicit conversion.
3067 using M = Construct1ArgMatcherP<int>;
3068 EXPECT_TRUE((std::is_constructible<M, int>::value));
3069 EXPECT_FALSE((std::is_convertible<int, M>::value));
3070 }
3071 {
3072 // Multiple arg matchers can be constructed with an implicit construction.
3073 Construct2ArgsMatcherP2<int, double> m = {1, 2.2};
3074 (void)m;
3075 }
3076}
3077
31f18b77
FG
3078MATCHER_P(Really, inner_matcher, "") {
3079 return ExplainMatchResult(inner_matcher, arg, result_listener);
3080}
3081
3082TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
3083 EXPECT_THAT(0, Really(Eq(0)));
3084}
3085
1e59de90
TL
3086TEST(DescribeMatcherTest, WorksWithValue) {
3087 EXPECT_EQ("is equal to 42", DescribeMatcher<int>(42));
3088 EXPECT_EQ("isn't equal to 42", DescribeMatcher<int>(42, true));
3089}
3090
3091TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) {
3092 const Matcher<int> monomorphic = Le(0);
3093 EXPECT_EQ("is <= 0", DescribeMatcher<int>(monomorphic));
3094 EXPECT_EQ("isn't <= 0", DescribeMatcher<int>(monomorphic, true));
3095}
3096
3097TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) {
3098 EXPECT_EQ("is even", DescribeMatcher<int>(PolymorphicIsEven()));
3099 EXPECT_EQ("is odd", DescribeMatcher<int>(PolymorphicIsEven(), true));
3100}
3101
31f18b77 3102TEST(AllArgsTest, WorksForTuple) {
1e59de90
TL
3103 EXPECT_THAT(std::make_tuple(1, 2L), AllArgs(Lt()));
3104 EXPECT_THAT(std::make_tuple(2L, 1), Not(AllArgs(Lt())));
31f18b77
FG
3105}
3106
3107TEST(AllArgsTest, WorksForNonTuple) {
3108 EXPECT_THAT(42, AllArgs(Gt(0)));
3109 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
3110}
3111
3112class AllArgsHelper {
3113 public:
3114 AllArgsHelper() {}
3115
3116 MOCK_METHOD2(Helper, int(char x, int y));
3117
3118 private:
3119 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
3120};
3121
3122TEST(AllArgsTest, WorksInWithClause) {
3123 AllArgsHelper helper;
3124 ON_CALL(helper, Helper(_, _))
3125 .With(AllArgs(Lt()))
3126 .WillByDefault(Return(1));
3127 EXPECT_CALL(helper, Helper(_, _));
3128 EXPECT_CALL(helper, Helper(_, _))
3129 .With(AllArgs(Gt()))
3130 .WillOnce(Return(2));
3131
3132 EXPECT_EQ(1, helper.Helper('\1', 2));
3133 EXPECT_EQ(2, helper.Helper('a', 1));
3134}
3135
1e59de90
TL
3136class OptionalMatchersHelper {
3137 public:
3138 OptionalMatchersHelper() {}
3139
3140 MOCK_METHOD0(NoArgs, int());
3141
3142 MOCK_METHOD1(OneArg, int(int y));
3143
3144 MOCK_METHOD2(TwoArgs, int(char x, int y));
3145
3146 MOCK_METHOD1(Overloaded, int(char x));
3147 MOCK_METHOD2(Overloaded, int(char x, int y));
3148
3149 private:
3150 GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper);
3151};
3152
3153TEST(AllArgsTest, WorksWithoutMatchers) {
3154 OptionalMatchersHelper helper;
3155
3156 ON_CALL(helper, NoArgs).WillByDefault(Return(10));
3157 ON_CALL(helper, OneArg).WillByDefault(Return(20));
3158 ON_CALL(helper, TwoArgs).WillByDefault(Return(30));
3159
3160 EXPECT_EQ(10, helper.NoArgs());
3161 EXPECT_EQ(20, helper.OneArg(1));
3162 EXPECT_EQ(30, helper.TwoArgs('\1', 2));
3163
3164 EXPECT_CALL(helper, NoArgs).Times(1);
3165 EXPECT_CALL(helper, OneArg).WillOnce(Return(100));
3166 EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200));
3167 EXPECT_CALL(helper, TwoArgs).Times(0);
3168
3169 EXPECT_EQ(10, helper.NoArgs());
3170 EXPECT_EQ(100, helper.OneArg(1));
3171 EXPECT_EQ(200, helper.OneArg(17));
3172}
3173
31f18b77
FG
3174// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
3175// matches the matcher.
3176TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
3177 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
3178 ASSERT_THAT("Foo", EndsWith("oo"));
3179 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
3180 EXPECT_THAT("Hello", StartsWith("Hell"));
3181}
3182
3183// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
3184// doesn't match the matcher.
3185TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
3186 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
3187 // which cannot reference auto variables.
3188 static unsigned short n; // NOLINT
3189 n = 5;
3190
1e59de90 3191 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)),
31f18b77
FG
3192 "Value of: n\n"
3193 "Expected: is > 10\n"
3194 " Actual: 5" + OfType("unsigned short"));
3195 n = 0;
3196 EXPECT_NONFATAL_FAILURE(
1e59de90 3197 EXPECT_THAT(n, AllOf(Le(7), Ge(5))),
31f18b77
FG
3198 "Value of: n\n"
3199 "Expected: (is <= 7) and (is >= 5)\n"
3200 " Actual: 0" + OfType("unsigned short"));
3201}
3202
3203// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
3204// has a reference type.
3205TEST(MatcherAssertionTest, WorksForByRefArguments) {
3206 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
3207 // reference auto variables.
3208 static int n;
3209 n = 0;
3210 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
1e59de90 3211 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
31f18b77
FG
3212 "Value of: n\n"
3213 "Expected: does not reference the variable @");
3214 // Tests the "Actual" part.
1e59de90 3215 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),
31f18b77
FG
3216 "Actual: 0" + OfType("int") + ", which is located @");
3217}
3218
31f18b77
FG
3219// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
3220// monomorphic.
31f18b77
FG
3221TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
3222 Matcher<const char*> starts_with_he = StartsWith("he");
3223 ASSERT_THAT("hello", starts_with_he);
3224
1e59de90 3225 Matcher<const std::string&> ends_with_ok = EndsWith("ok");
31f18b77 3226 ASSERT_THAT("book", ends_with_ok);
1e59de90 3227 const std::string bad = "bad";
31f18b77
FG
3228 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
3229 "Value of: bad\n"
3230 "Expected: ends with \"ok\"\n"
3231 " Actual: \"bad\"");
3232 Matcher<int> is_greater_than_5 = Gt(5);
3233 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
3234 "Value of: 5\n"
3235 "Expected: is > 5\n"
3236 " Actual: 5" + OfType("int"));
3237}
31f18b77
FG
3238
3239// Tests floating-point matchers.
3240template <typename RawType>
3241class FloatingPointTest : public testing::Test {
3242 protected:
3243 typedef testing::internal::FloatingPoint<RawType> Floating;
3244 typedef typename Floating::Bits Bits;
3245
3246 FloatingPointTest()
3247 : max_ulps_(Floating::kMaxUlps),
3248 zero_bits_(Floating(0).bits()),
3249 one_bits_(Floating(1).bits()),
3250 infinity_bits_(Floating(Floating::Infinity()).bits()),
1e59de90
TL
3251 close_to_positive_zero_(
3252 Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
3253 close_to_negative_zero_(
3254 -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
3255 further_from_negative_zero_(-Floating::ReinterpretBits(
31f18b77 3256 zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
1e59de90
TL
3257 close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
3258 further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
31f18b77 3259 infinity_(Floating::Infinity()),
1e59de90
TL
3260 close_to_infinity_(
3261 Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
3262 further_from_infinity_(
3263 Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
31f18b77 3264 max_(Floating::Max()),
1e59de90
TL
3265 nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
3266 nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
31f18b77
FG
3267 }
3268
3269 void TestSize() {
3270 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
3271 }
3272
3273 // A battery of tests for FloatingEqMatcher::Matches.
3274 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
3275 void TestMatches(
3276 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
3277 Matcher<RawType> m1 = matcher_maker(0.0);
3278 EXPECT_TRUE(m1.Matches(-0.0));
3279 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
3280 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
3281 EXPECT_FALSE(m1.Matches(1.0));
3282
3283 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
3284 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
3285
3286 Matcher<RawType> m3 = matcher_maker(1.0);
3287 EXPECT_TRUE(m3.Matches(close_to_one_));
3288 EXPECT_FALSE(m3.Matches(further_from_one_));
3289
3290 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
3291 EXPECT_FALSE(m3.Matches(0.0));
3292
3293 Matcher<RawType> m4 = matcher_maker(-infinity_);
3294 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
3295
3296 Matcher<RawType> m5 = matcher_maker(infinity_);
3297 EXPECT_TRUE(m5.Matches(close_to_infinity_));
3298
3299 // This is interesting as the representations of infinity_ and nan1_
3300 // are only 1 DLP apart.
3301 EXPECT_FALSE(m5.Matches(nan1_));
3302
3303 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
3304 // some cases.
3305 Matcher<const RawType&> m6 = matcher_maker(0.0);
3306 EXPECT_TRUE(m6.Matches(-0.0));
3307 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
3308 EXPECT_FALSE(m6.Matches(1.0));
3309
3310 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
3311 // cases.
3312 Matcher<RawType&> m7 = matcher_maker(0.0);
3313 RawType x = 0.0;
3314 EXPECT_TRUE(m7.Matches(x));
3315 x = 0.01f;
3316 EXPECT_FALSE(m7.Matches(x));
3317 }
3318
3319 // Pre-calculated numbers to be used by the tests.
3320
1e59de90 3321 const Bits max_ulps_;
31f18b77
FG
3322
3323 const Bits zero_bits_; // The bits that represent 0.0.
3324 const Bits one_bits_; // The bits that represent 1.0.
3325 const Bits infinity_bits_; // The bits that represent +infinity.
3326
3327 // Some numbers close to 0.0.
3328 const RawType close_to_positive_zero_;
3329 const RawType close_to_negative_zero_;
3330 const RawType further_from_negative_zero_;
3331
3332 // Some numbers close to 1.0.
3333 const RawType close_to_one_;
3334 const RawType further_from_one_;
3335
3336 // Some numbers close to +infinity.
3337 const RawType infinity_;
3338 const RawType close_to_infinity_;
3339 const RawType further_from_infinity_;
3340
3341 // Maximum representable value that's not infinity.
3342 const RawType max_;
3343
3344 // Some NaNs.
3345 const RawType nan1_;
3346 const RawType nan2_;
31f18b77
FG
3347};
3348
3349// Tests floating-point matchers with fixed epsilons.
3350template <typename RawType>
3351class FloatingPointNearTest : public FloatingPointTest<RawType> {
3352 protected:
3353 typedef FloatingPointTest<RawType> ParentType;
3354
3355 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
3356 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
3357 void TestNearMatches(
3358 testing::internal::FloatingEqMatcher<RawType>
3359 (*matcher_maker)(RawType, RawType)) {
3360 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
3361 EXPECT_TRUE(m1.Matches(0.0));
3362 EXPECT_TRUE(m1.Matches(-0.0));
3363 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
3364 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
3365 EXPECT_FALSE(m1.Matches(1.0));
3366
3367 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
3368 EXPECT_TRUE(m2.Matches(0.0));
3369 EXPECT_TRUE(m2.Matches(-0.0));
3370 EXPECT_TRUE(m2.Matches(1.0));
3371 EXPECT_TRUE(m2.Matches(-1.0));
3372 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
3373 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
3374
3375 // Check that inf matches inf, regardless of the of the specified max
3376 // absolute error.
3377 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
3378 EXPECT_TRUE(m3.Matches(ParentType::infinity_));
3379 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
3380 EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
3381
3382 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
3383 EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
3384 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
3385 EXPECT_FALSE(m4.Matches(ParentType::infinity_));
3386
3387 // Test various overflow scenarios.
3388 Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
3389 EXPECT_TRUE(m5.Matches(ParentType::max_));
3390 EXPECT_FALSE(m5.Matches(-ParentType::max_));
3391
3392 Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
3393 EXPECT_FALSE(m6.Matches(ParentType::max_));
3394 EXPECT_TRUE(m6.Matches(-ParentType::max_));
3395
3396 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
3397 EXPECT_TRUE(m7.Matches(ParentType::max_));
3398 EXPECT_FALSE(m7.Matches(-ParentType::max_));
3399
3400 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
3401 EXPECT_FALSE(m8.Matches(ParentType::max_));
3402 EXPECT_TRUE(m8.Matches(-ParentType::max_));
3403
3404 // The difference between max() and -max() normally overflows to infinity,
3405 // but it should still match if the max_abs_error is also infinity.
3406 Matcher<RawType> m9 = matcher_maker(
3407 ParentType::max_, ParentType::infinity_);
3408 EXPECT_TRUE(m8.Matches(-ParentType::max_));
3409
3410 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
3411 // some cases.
3412 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
3413 EXPECT_TRUE(m10.Matches(-0.0));
3414 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
3415 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
3416
3417 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
3418 // cases.
3419 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
3420 RawType x = 0.0;
3421 EXPECT_TRUE(m11.Matches(x));
3422 x = 1.0f;
3423 EXPECT_TRUE(m11.Matches(x));
3424 x = -1.0f;
3425 EXPECT_TRUE(m11.Matches(x));
3426 x = 1.1f;
3427 EXPECT_FALSE(m11.Matches(x));
3428 x = -1.1f;
3429 EXPECT_FALSE(m11.Matches(x));
3430 }
3431};
3432
3433// Instantiate FloatingPointTest for testing floats.
3434typedef FloatingPointTest<float> FloatTest;
3435
3436TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
3437 TestMatches(&FloatEq);
3438}
3439
3440TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
3441 TestMatches(&NanSensitiveFloatEq);
3442}
3443
3444TEST_F(FloatTest, FloatEqCannotMatchNaN) {
3445 // FloatEq never matches NaN.
3446 Matcher<float> m = FloatEq(nan1_);
3447 EXPECT_FALSE(m.Matches(nan1_));
3448 EXPECT_FALSE(m.Matches(nan2_));
3449 EXPECT_FALSE(m.Matches(1.0));
3450}
3451
3452TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
3453 // NanSensitiveFloatEq will match NaN.
3454 Matcher<float> m = NanSensitiveFloatEq(nan1_);
3455 EXPECT_TRUE(m.Matches(nan1_));
3456 EXPECT_TRUE(m.Matches(nan2_));
3457 EXPECT_FALSE(m.Matches(1.0));
3458}
3459
3460TEST_F(FloatTest, FloatEqCanDescribeSelf) {
3461 Matcher<float> m1 = FloatEq(2.0f);
3462 EXPECT_EQ("is approximately 2", Describe(m1));
3463 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3464
3465 Matcher<float> m2 = FloatEq(0.5f);
3466 EXPECT_EQ("is approximately 0.5", Describe(m2));
3467 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3468
3469 Matcher<float> m3 = FloatEq(nan1_);
3470 EXPECT_EQ("never matches", Describe(m3));
3471 EXPECT_EQ("is anything", DescribeNegation(m3));
3472}
3473
3474TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
3475 Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
3476 EXPECT_EQ("is approximately 2", Describe(m1));
3477 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3478
3479 Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
3480 EXPECT_EQ("is approximately 0.5", Describe(m2));
3481 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3482
3483 Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
3484 EXPECT_EQ("is NaN", Describe(m3));
3485 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3486}
3487
3488// Instantiate FloatingPointTest for testing floats with a user-specified
3489// max absolute error.
3490typedef FloatingPointNearTest<float> FloatNearTest;
3491
3492TEST_F(FloatNearTest, FloatNearMatches) {
3493 TestNearMatches(&FloatNear);
3494}
3495
3496TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
3497 TestNearMatches(&NanSensitiveFloatNear);
3498}
3499
3500TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
3501 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
3502 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3503 EXPECT_EQ(
3504 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3505
3506 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
3507 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3508 EXPECT_EQ(
3509 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3510
3511 Matcher<float> m3 = FloatNear(nan1_, 0.0);
3512 EXPECT_EQ("never matches", Describe(m3));
3513 EXPECT_EQ("is anything", DescribeNegation(m3));
3514}
3515
3516TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
3517 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
3518 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3519 EXPECT_EQ(
3520 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3521
3522 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
3523 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3524 EXPECT_EQ(
3525 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3526
3527 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
3528 EXPECT_EQ("is NaN", Describe(m3));
3529 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3530}
3531
3532TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
3533 // FloatNear never matches NaN.
3534 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
3535 EXPECT_FALSE(m.Matches(nan1_));
3536 EXPECT_FALSE(m.Matches(nan2_));
3537 EXPECT_FALSE(m.Matches(1.0));
3538}
3539
3540TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
3541 // NanSensitiveFloatNear will match NaN.
3542 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
3543 EXPECT_TRUE(m.Matches(nan1_));
3544 EXPECT_TRUE(m.Matches(nan2_));
3545 EXPECT_FALSE(m.Matches(1.0));
3546}
3547
3548// Instantiate FloatingPointTest for testing doubles.
3549typedef FloatingPointTest<double> DoubleTest;
3550
3551TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
3552 TestMatches(&DoubleEq);
3553}
3554
3555TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
3556 TestMatches(&NanSensitiveDoubleEq);
3557}
3558
3559TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
3560 // DoubleEq never matches NaN.
3561 Matcher<double> m = DoubleEq(nan1_);
3562 EXPECT_FALSE(m.Matches(nan1_));
3563 EXPECT_FALSE(m.Matches(nan2_));
3564 EXPECT_FALSE(m.Matches(1.0));
3565}
3566
3567TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3568 // NanSensitiveDoubleEq will match NaN.
3569 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
3570 EXPECT_TRUE(m.Matches(nan1_));
3571 EXPECT_TRUE(m.Matches(nan2_));
3572 EXPECT_FALSE(m.Matches(1.0));
3573}
3574
3575TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3576 Matcher<double> m1 = DoubleEq(2.0);
3577 EXPECT_EQ("is approximately 2", Describe(m1));
3578 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3579
3580 Matcher<double> m2 = DoubleEq(0.5);
3581 EXPECT_EQ("is approximately 0.5", Describe(m2));
3582 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3583
3584 Matcher<double> m3 = DoubleEq(nan1_);
3585 EXPECT_EQ("never matches", Describe(m3));
3586 EXPECT_EQ("is anything", DescribeNegation(m3));
3587}
3588
3589TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3590 Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3591 EXPECT_EQ("is approximately 2", Describe(m1));
3592 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3593
3594 Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3595 EXPECT_EQ("is approximately 0.5", Describe(m2));
3596 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3597
3598 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3599 EXPECT_EQ("is NaN", Describe(m3));
3600 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3601}
3602
3603// Instantiate FloatingPointTest for testing floats with a user-specified
3604// max absolute error.
3605typedef FloatingPointNearTest<double> DoubleNearTest;
3606
3607TEST_F(DoubleNearTest, DoubleNearMatches) {
3608 TestNearMatches(&DoubleNear);
3609}
3610
3611TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3612 TestNearMatches(&NanSensitiveDoubleNear);
3613}
3614
3615TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3616 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3617 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3618 EXPECT_EQ(
3619 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3620
3621 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3622 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3623 EXPECT_EQ(
3624 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3625
3626 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3627 EXPECT_EQ("never matches", Describe(m3));
3628 EXPECT_EQ("is anything", DescribeNegation(m3));
3629}
3630
3631TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
3632 EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
3633 EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
3634 EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
3635
1e59de90
TL
3636 const std::string explanation =
3637 Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
31f18b77
FG
3638 // Different C++ implementations may print floating-point numbers
3639 // slightly differently.
3640 EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC
3641 explanation == "which is 1.2e-010 from 2.1") // MSVC
3642 << " where explanation is \"" << explanation << "\".";
3643}
3644
3645TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3646 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3647 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3648 EXPECT_EQ(
3649 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3650
3651 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3652 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3653 EXPECT_EQ(
3654 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3655
3656 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3657 EXPECT_EQ("is NaN", Describe(m3));
3658 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3659}
3660
3661TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3662 // DoubleNear never matches NaN.
3663 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3664 EXPECT_FALSE(m.Matches(nan1_));
3665 EXPECT_FALSE(m.Matches(nan2_));
3666 EXPECT_FALSE(m.Matches(1.0));
3667}
3668
3669TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3670 // NanSensitiveDoubleNear will match NaN.
3671 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3672 EXPECT_TRUE(m.Matches(nan1_));
3673 EXPECT_TRUE(m.Matches(nan2_));
3674 EXPECT_FALSE(m.Matches(1.0));
3675}
3676
3677TEST(PointeeTest, RawPointer) {
3678 const Matcher<int*> m = Pointee(Ge(0));
3679
3680 int n = 1;
3681 EXPECT_TRUE(m.Matches(&n));
3682 n = -1;
3683 EXPECT_FALSE(m.Matches(&n));
1e59de90 3684 EXPECT_FALSE(m.Matches(nullptr));
31f18b77
FG
3685}
3686
3687TEST(PointeeTest, RawPointerToConst) {
3688 const Matcher<const double*> m = Pointee(Ge(0));
3689
3690 double x = 1;
3691 EXPECT_TRUE(m.Matches(&x));
3692 x = -1;
3693 EXPECT_FALSE(m.Matches(&x));
1e59de90 3694 EXPECT_FALSE(m.Matches(nullptr));
31f18b77
FG
3695}
3696
3697TEST(PointeeTest, ReferenceToConstRawPointer) {
3698 const Matcher<int* const &> m = Pointee(Ge(0));
3699
3700 int n = 1;
3701 EXPECT_TRUE(m.Matches(&n));
3702 n = -1;
3703 EXPECT_FALSE(m.Matches(&n));
1e59de90 3704 EXPECT_FALSE(m.Matches(nullptr));
31f18b77
FG
3705}
3706
3707TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3708 const Matcher<double* &> m = Pointee(Ge(0));
3709
3710 double x = 1.0;
3711 double* p = &x;
3712 EXPECT_TRUE(m.Matches(p));
3713 x = -1;
3714 EXPECT_FALSE(m.Matches(p));
1e59de90 3715 p = nullptr;
31f18b77
FG
3716 EXPECT_FALSE(m.Matches(p));
3717}
3718
3719MATCHER_P(FieldIIs, inner_matcher, "") {
3720 return ExplainMatchResult(inner_matcher, arg.i, result_listener);
3721}
3722
3723#if GTEST_HAS_RTTI
31f18b77
FG
3724TEST(WhenDynamicCastToTest, SameType) {
3725 Derived derived;
3726 derived.i = 4;
3727
3728 // Right type. A pointer is passed down.
3729 Base* as_base_ptr = &derived;
3730 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
3731 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
3732 EXPECT_THAT(as_base_ptr,
3733 Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
3734}
3735
3736TEST(WhenDynamicCastToTest, WrongTypes) {
3737 Base base;
3738 Derived derived;
3739 OtherDerived other_derived;
3740
3741 // Wrong types. NULL is passed.
3742 EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3743 EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
3744 Base* as_base_ptr = &derived;
3745 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
3746 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
3747 as_base_ptr = &other_derived;
3748 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3749 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3750}
3751
3752TEST(WhenDynamicCastToTest, AlreadyNull) {
3753 // Already NULL.
1e59de90 3754 Base* as_base_ptr = nullptr;
31f18b77
FG
3755 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3756}
3757
3758struct AmbiguousCastTypes {
3759 class VirtualDerived : public virtual Base {};
3760 class DerivedSub1 : public VirtualDerived {};
3761 class DerivedSub2 : public VirtualDerived {};
3762 class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
3763};
3764
3765TEST(WhenDynamicCastToTest, AmbiguousCast) {
3766 AmbiguousCastTypes::DerivedSub1 sub1;
3767 AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
3768 // Multiply derived from Base. dynamic_cast<> returns NULL.
3769 Base* as_base_ptr =
3770 static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
3771 EXPECT_THAT(as_base_ptr,
3772 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
3773 as_base_ptr = &sub1;
3774 EXPECT_THAT(
3775 as_base_ptr,
3776 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
3777}
3778
3779TEST(WhenDynamicCastToTest, Describe) {
3780 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
1e59de90 3781 const std::string prefix =
31f18b77
FG
3782 "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
3783 EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
3784 EXPECT_EQ(prefix + "does not point to a value that is anything",
3785 DescribeNegation(matcher));
3786}
3787
3788TEST(WhenDynamicCastToTest, Explain) {
3789 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
1e59de90 3790 Base* null = nullptr;
31f18b77
FG
3791 EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
3792 Derived derived;
3793 EXPECT_TRUE(matcher.Matches(&derived));
3794 EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
3795
3796 // With references, the matcher itself can fail. Test for that one.
3797 Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
3798 EXPECT_THAT(Explain(ref_matcher, derived),
3799 HasSubstr("which cannot be dynamic_cast"));
3800}
3801
3802TEST(WhenDynamicCastToTest, GoodReference) {
3803 Derived derived;
3804 derived.i = 4;
3805 Base& as_base_ref = derived;
3806 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
3807 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
3808}
3809
3810TEST(WhenDynamicCastToTest, BadReference) {
3811 Derived derived;
3812 Base& as_base_ref = derived;
3813 EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
3814}
31f18b77
FG
3815#endif // GTEST_HAS_RTTI
3816
3817// Minimal const-propagating pointer.
3818template <typename T>
3819class ConstPropagatingPtr {
3820 public:
3821 typedef T element_type;
3822
3823 ConstPropagatingPtr() : val_() {}
3824 explicit ConstPropagatingPtr(T* t) : val_(t) {}
3825 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3826
3827 T* get() { return val_; }
3828 T& operator*() { return *val_; }
3829 // Most smart pointers return non-const T* and T& from the next methods.
3830 const T* get() const { return val_; }
3831 const T& operator*() const { return *val_; }
3832
3833 private:
3834 T* val_;
3835};
3836
3837TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3838 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3839 int three = 3;
3840 const ConstPropagatingPtr<int> co(&three);
3841 ConstPropagatingPtr<int> o(&three);
3842 EXPECT_TRUE(m.Matches(o));
3843 EXPECT_TRUE(m.Matches(co));
3844 *o = 6;
3845 EXPECT_FALSE(m.Matches(o));
3846 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3847}
3848
3849TEST(PointeeTest, NeverMatchesNull) {
3850 const Matcher<const char*> m = Pointee(_);
1e59de90 3851 EXPECT_FALSE(m.Matches(nullptr));
31f18b77
FG
3852}
3853
3854// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3855TEST(PointeeTest, MatchesAgainstAValue) {
3856 const Matcher<int*> m = Pointee(5);
3857
3858 int n = 5;
3859 EXPECT_TRUE(m.Matches(&n));
3860 n = -1;
3861 EXPECT_FALSE(m.Matches(&n));
1e59de90 3862 EXPECT_FALSE(m.Matches(nullptr));
31f18b77
FG
3863}
3864
3865TEST(PointeeTest, CanDescribeSelf) {
3866 const Matcher<int*> m = Pointee(Gt(3));
3867 EXPECT_EQ("points to a value that is > 3", Describe(m));
3868 EXPECT_EQ("does not point to a value that is > 3",
3869 DescribeNegation(m));
3870}
3871
3872TEST(PointeeTest, CanExplainMatchResult) {
1e59de90 3873 const Matcher<const std::string*> m = Pointee(StartsWith("Hi"));
31f18b77 3874
1e59de90 3875 EXPECT_EQ("", Explain(m, static_cast<const std::string*>(nullptr)));
31f18b77
FG
3876
3877 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
3878 long n = 3; // NOLINT
3879 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
3880 Explain(m2, &n));
3881}
3882
3883TEST(PointeeTest, AlwaysExplainsPointee) {
3884 const Matcher<int*> m = Pointee(0);
3885 int n = 42;
3886 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
3887}
3888
3889// An uncopyable class.
3890class Uncopyable {
3891 public:
3892 Uncopyable() : value_(-1) {}
3893 explicit Uncopyable(int a_value) : value_(a_value) {}
3894
3895 int value() const { return value_; }
3896 void set_value(int i) { value_ = i; }
3897
3898 private:
3899 int value_;
3900 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3901};
3902
1e59de90 3903// Returns true if and only if x.value() is positive.
31f18b77
FG
3904bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3905
3906MATCHER_P(UncopyableIs, inner_matcher, "") {
3907 return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
3908}
3909
3910// A user-defined struct for testing Field().
3911struct AStruct {
1e59de90 3912 AStruct() : x(0), y(1.0), z(5), p(nullptr) {}
31f18b77
FG
3913 AStruct(const AStruct& rhs)
3914 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3915
3916 int x; // A non-const field.
3917 const double y; // A const field.
3918 Uncopyable z; // An uncopyable field.
3919 const char* p; // A pointer field.
31f18b77
FG
3920};
3921
3922// A derived struct for testing Field().
3923struct DerivedStruct : public AStruct {
3924 char ch;
31f18b77
FG
3925};
3926
3927// Tests that Field(&Foo::field, ...) works when field is non-const.
3928TEST(FieldTest, WorksForNonConstField) {
3929 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
1e59de90 3930 Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0));
31f18b77
FG
3931
3932 AStruct a;
3933 EXPECT_TRUE(m.Matches(a));
1e59de90 3934 EXPECT_TRUE(m_with_name.Matches(a));
31f18b77
FG
3935 a.x = -1;
3936 EXPECT_FALSE(m.Matches(a));
1e59de90 3937 EXPECT_FALSE(m_with_name.Matches(a));
31f18b77
FG
3938}
3939
3940// Tests that Field(&Foo::field, ...) works when field is const.
3941TEST(FieldTest, WorksForConstField) {
3942 AStruct a;
3943
3944 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
1e59de90 3945 Matcher<AStruct> m_with_name = Field("y", &AStruct::y, Ge(0.0));
31f18b77 3946 EXPECT_TRUE(m.Matches(a));
1e59de90 3947 EXPECT_TRUE(m_with_name.Matches(a));
31f18b77 3948 m = Field(&AStruct::y, Le(0.0));
1e59de90 3949 m_with_name = Field("y", &AStruct::y, Le(0.0));
31f18b77 3950 EXPECT_FALSE(m.Matches(a));
1e59de90 3951 EXPECT_FALSE(m_with_name.Matches(a));
31f18b77
FG
3952}
3953
3954// Tests that Field(&Foo::field, ...) works when field is not copyable.
3955TEST(FieldTest, WorksForUncopyableField) {
3956 AStruct a;
3957
3958 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3959 EXPECT_TRUE(m.Matches(a));
3960 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3961 EXPECT_FALSE(m.Matches(a));
3962}
3963
3964// Tests that Field(&Foo::field, ...) works when field is a pointer.
3965TEST(FieldTest, WorksForPointerField) {
3966 // Matching against NULL.
1e59de90 3967 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr));
31f18b77
FG
3968 AStruct a;
3969 EXPECT_TRUE(m.Matches(a));
3970 a.p = "hi";
3971 EXPECT_FALSE(m.Matches(a));
3972
3973 // Matching a pointer that is not NULL.
3974 m = Field(&AStruct::p, StartsWith("hi"));
3975 a.p = "hill";
3976 EXPECT_TRUE(m.Matches(a));
3977 a.p = "hole";
3978 EXPECT_FALSE(m.Matches(a));
3979}
3980
3981// Tests that Field() works when the object is passed by reference.
3982TEST(FieldTest, WorksForByRefArgument) {
3983 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3984
3985 AStruct a;
3986 EXPECT_TRUE(m.Matches(a));
3987 a.x = -1;
3988 EXPECT_FALSE(m.Matches(a));
3989}
3990
3991// Tests that Field(&Foo::field, ...) works when the argument's type
3992// is a sub-type of Foo.
3993TEST(FieldTest, WorksForArgumentOfSubType) {
3994 // Note that the matcher expects DerivedStruct but we say AStruct
3995 // inside Field().
3996 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
3997
3998 DerivedStruct d;
3999 EXPECT_TRUE(m.Matches(d));
4000 d.x = -1;
4001 EXPECT_FALSE(m.Matches(d));
4002}
4003
4004// Tests that Field(&Foo::field, m) works when field's type and m's
4005// argument type are compatible but not the same.
4006TEST(FieldTest, WorksForCompatibleMatcherType) {
4007 // The field is an int, but the inner matcher expects a signed char.
4008 Matcher<const AStruct&> m = Field(&AStruct::x,
4009 Matcher<signed char>(Ge(0)));
4010
4011 AStruct a;
4012 EXPECT_TRUE(m.Matches(a));
4013 a.x = -1;
4014 EXPECT_FALSE(m.Matches(a));
4015}
4016
4017// Tests that Field() can describe itself.
4018TEST(FieldTest, CanDescribeSelf) {
4019 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
4020
4021 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
4022 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
4023}
4024
1e59de90
TL
4025TEST(FieldTest, CanDescribeSelfWithFieldName) {
4026 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
4027
4028 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
4029 EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
4030 DescribeNegation(m));
4031}
4032
31f18b77
FG
4033// Tests that Field() can explain the match result.
4034TEST(FieldTest, CanExplainMatchResult) {
4035 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
4036
4037 AStruct a;
4038 a.x = 1;
4039 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
4040
4041 m = Field(&AStruct::x, GreaterThan(0));
4042 EXPECT_EQ(
4043 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
4044 Explain(m, a));
4045}
4046
1e59de90
TL
4047TEST(FieldTest, CanExplainMatchResultWithFieldName) {
4048 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
4049
4050 AStruct a;
4051 a.x = 1;
4052 EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a));
4053
4054 m = Field("field_name", &AStruct::x, GreaterThan(0));
4055 EXPECT_EQ("whose field `field_name` is 1" + OfType("int") +
4056 ", which is 1 more than 0",
4057 Explain(m, a));
4058}
4059
31f18b77
FG
4060// Tests that Field() works when the argument is a pointer to const.
4061TEST(FieldForPointerTest, WorksForPointerToConst) {
4062 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
4063
4064 AStruct a;
4065 EXPECT_TRUE(m.Matches(&a));
4066 a.x = -1;
4067 EXPECT_FALSE(m.Matches(&a));
4068}
4069
4070// Tests that Field() works when the argument is a pointer to non-const.
4071TEST(FieldForPointerTest, WorksForPointerToNonConst) {
4072 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
4073
4074 AStruct a;
4075 EXPECT_TRUE(m.Matches(&a));
4076 a.x = -1;
4077 EXPECT_FALSE(m.Matches(&a));
4078}
4079
4080// Tests that Field() works when the argument is a reference to a const pointer.
4081TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
4082 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
4083
4084 AStruct a;
4085 EXPECT_TRUE(m.Matches(&a));
4086 a.x = -1;
4087 EXPECT_FALSE(m.Matches(&a));
4088}
4089
4090// Tests that Field() does not match the NULL pointer.
4091TEST(FieldForPointerTest, DoesNotMatchNull) {
4092 Matcher<const AStruct*> m = Field(&AStruct::x, _);
1e59de90 4093 EXPECT_FALSE(m.Matches(nullptr));
31f18b77
FG
4094}
4095
4096// Tests that Field(&Foo::field, ...) works when the argument's type
4097// is a sub-type of const Foo*.
4098TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
4099 // Note that the matcher expects DerivedStruct but we say AStruct
4100 // inside Field().
4101 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
4102
4103 DerivedStruct d;
4104 EXPECT_TRUE(m.Matches(&d));
4105 d.x = -1;
4106 EXPECT_FALSE(m.Matches(&d));
4107}
4108
4109// Tests that Field() can describe itself when used to match a pointer.
4110TEST(FieldForPointerTest, CanDescribeSelf) {
4111 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
4112
4113 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
4114 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
4115}
4116
1e59de90
TL
4117TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) {
4118 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
4119
4120 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m));
4121 EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
4122 DescribeNegation(m));
4123}
4124
31f18b77
FG
4125// Tests that Field() can explain the result of matching a pointer.
4126TEST(FieldForPointerTest, CanExplainMatchResult) {
4127 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
4128
4129 AStruct a;
4130 a.x = 1;
1e59de90 4131 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
31f18b77
FG
4132 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
4133 Explain(m, &a));
4134
4135 m = Field(&AStruct::x, GreaterThan(0));
4136 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
4137 ", which is 1 more than 0", Explain(m, &a));
4138}
4139
1e59de90
TL
4140TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) {
4141 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
4142
4143 AStruct a;
4144 a.x = 1;
4145 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(nullptr)));
4146 EXPECT_EQ(
4147 "which points to an object whose field `field_name` is 1" + OfType("int"),
4148 Explain(m, &a));
4149
4150 m = Field("field_name", &AStruct::x, GreaterThan(0));
4151 EXPECT_EQ("which points to an object whose field `field_name` is 1" +
4152 OfType("int") + ", which is 1 more than 0",
4153 Explain(m, &a));
4154}
4155
31f18b77
FG
4156// A user-defined class for testing Property().
4157class AClass {
4158 public:
4159 AClass() : n_(0) {}
4160
4161 // A getter that returns a non-reference.
4162 int n() const { return n_; }
4163
4164 void set_n(int new_n) { n_ = new_n; }
4165
4166 // A getter that returns a reference to const.
1e59de90
TL
4167 const std::string& s() const { return s_; }
4168
4169 const std::string& s_ref() const & { return s_; }
31f18b77 4170
1e59de90 4171 void set_s(const std::string& new_s) { s_ = new_s; }
31f18b77
FG
4172
4173 // A getter that returns a reference to non-const.
4174 double& x() const { return x_; }
1e59de90 4175
31f18b77
FG
4176 private:
4177 int n_;
1e59de90 4178 std::string s_;
31f18b77
FG
4179
4180 static double x_;
4181};
4182
4183double AClass::x_ = 0.0;
4184
4185// A derived class for testing Property().
4186class DerivedClass : public AClass {
4187 public:
4188 int k() const { return k_; }
4189 private:
4190 int k_;
4191};
4192
4193// Tests that Property(&Foo::property, ...) works when property()
4194// returns a non-reference.
4195TEST(PropertyTest, WorksForNonReferenceProperty) {
4196 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
1e59de90 4197 Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0));
31f18b77
FG
4198
4199 AClass a;
4200 a.set_n(1);
4201 EXPECT_TRUE(m.Matches(a));
1e59de90 4202 EXPECT_TRUE(m_with_name.Matches(a));
31f18b77
FG
4203
4204 a.set_n(-1);
4205 EXPECT_FALSE(m.Matches(a));
1e59de90 4206 EXPECT_FALSE(m_with_name.Matches(a));
31f18b77
FG
4207}
4208
4209// Tests that Property(&Foo::property, ...) works when property()
4210// returns a reference to const.
4211TEST(PropertyTest, WorksForReferenceToConstProperty) {
4212 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
1e59de90
TL
4213 Matcher<const AClass&> m_with_name =
4214 Property("s", &AClass::s, StartsWith("hi"));
4215
4216 AClass a;
4217 a.set_s("hill");
4218 EXPECT_TRUE(m.Matches(a));
4219 EXPECT_TRUE(m_with_name.Matches(a));
4220
4221 a.set_s("hole");
4222 EXPECT_FALSE(m.Matches(a));
4223 EXPECT_FALSE(m_with_name.Matches(a));
4224}
4225
4226// Tests that Property(&Foo::property, ...) works when property() is
4227// ref-qualified.
4228TEST(PropertyTest, WorksForRefQualifiedProperty) {
4229 Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi"));
4230 Matcher<const AClass&> m_with_name =
4231 Property("s", &AClass::s_ref, StartsWith("hi"));
31f18b77
FG
4232
4233 AClass a;
4234 a.set_s("hill");
4235 EXPECT_TRUE(m.Matches(a));
1e59de90 4236 EXPECT_TRUE(m_with_name.Matches(a));
31f18b77
FG
4237
4238 a.set_s("hole");
4239 EXPECT_FALSE(m.Matches(a));
1e59de90 4240 EXPECT_FALSE(m_with_name.Matches(a));
31f18b77
FG
4241}
4242
4243// Tests that Property(&Foo::property, ...) works when property()
4244// returns a reference to non-const.
4245TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
4246 double x = 0.0;
4247 AClass a;
4248
4249 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
4250 EXPECT_FALSE(m.Matches(a));
4251
4252 m = Property(&AClass::x, Not(Ref(x)));
4253 EXPECT_TRUE(m.Matches(a));
4254}
4255
4256// Tests that Property(&Foo::property, ...) works when the argument is
4257// passed by value.
4258TEST(PropertyTest, WorksForByValueArgument) {
4259 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
4260
4261 AClass a;
4262 a.set_s("hill");
4263 EXPECT_TRUE(m.Matches(a));
4264
4265 a.set_s("hole");
4266 EXPECT_FALSE(m.Matches(a));
4267}
4268
4269// Tests that Property(&Foo::property, ...) works when the argument's
4270// type is a sub-type of Foo.
4271TEST(PropertyTest, WorksForArgumentOfSubType) {
4272 // The matcher expects a DerivedClass, but inside the Property() we
4273 // say AClass.
4274 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
4275
4276 DerivedClass d;
4277 d.set_n(1);
4278 EXPECT_TRUE(m.Matches(d));
4279
4280 d.set_n(-1);
4281 EXPECT_FALSE(m.Matches(d));
4282}
4283
4284// Tests that Property(&Foo::property, m) works when property()'s type
4285// and m's argument type are compatible but different.
4286TEST(PropertyTest, WorksForCompatibleMatcherType) {
4287 // n() returns an int but the inner matcher expects a signed char.
4288 Matcher<const AClass&> m = Property(&AClass::n,
4289 Matcher<signed char>(Ge(0)));
4290
1e59de90
TL
4291 Matcher<const AClass&> m_with_name =
4292 Property("n", &AClass::n, Matcher<signed char>(Ge(0)));
4293
31f18b77
FG
4294 AClass a;
4295 EXPECT_TRUE(m.Matches(a));
1e59de90 4296 EXPECT_TRUE(m_with_name.Matches(a));
31f18b77
FG
4297 a.set_n(-1);
4298 EXPECT_FALSE(m.Matches(a));
1e59de90 4299 EXPECT_FALSE(m_with_name.Matches(a));
31f18b77
FG
4300}
4301
4302// Tests that Property() can describe itself.
4303TEST(PropertyTest, CanDescribeSelf) {
4304 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4305
4306 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
4307 EXPECT_EQ("is an object whose given property isn't >= 0",
4308 DescribeNegation(m));
4309}
4310
1e59de90
TL
4311TEST(PropertyTest, CanDescribeSelfWithPropertyName) {
4312 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
4313
4314 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
4315 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
4316 DescribeNegation(m));
4317}
4318
31f18b77
FG
4319// Tests that Property() can explain the match result.
4320TEST(PropertyTest, CanExplainMatchResult) {
4321 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
4322
4323 AClass a;
4324 a.set_n(1);
4325 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
4326
4327 m = Property(&AClass::n, GreaterThan(0));
4328 EXPECT_EQ(
4329 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
4330 Explain(m, a));
4331}
4332
1e59de90
TL
4333TEST(PropertyTest, CanExplainMatchResultWithPropertyName) {
4334 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
4335
4336 AClass a;
4337 a.set_n(1);
4338 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a));
4339
4340 m = Property("fancy_name", &AClass::n, GreaterThan(0));
4341 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") +
4342 ", which is 1 more than 0",
4343 Explain(m, a));
4344}
4345
31f18b77
FG
4346// Tests that Property() works when the argument is a pointer to const.
4347TEST(PropertyForPointerTest, WorksForPointerToConst) {
4348 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4349
4350 AClass a;
4351 a.set_n(1);
4352 EXPECT_TRUE(m.Matches(&a));
4353
4354 a.set_n(-1);
4355 EXPECT_FALSE(m.Matches(&a));
4356}
4357
4358// Tests that Property() works when the argument is a pointer to non-const.
4359TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
4360 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
4361
4362 AClass a;
4363 a.set_s("hill");
4364 EXPECT_TRUE(m.Matches(&a));
4365
4366 a.set_s("hole");
4367 EXPECT_FALSE(m.Matches(&a));
4368}
4369
4370// Tests that Property() works when the argument is a reference to a
4371// const pointer.
4372TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
4373 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
4374
4375 AClass a;
4376 a.set_s("hill");
4377 EXPECT_TRUE(m.Matches(&a));
4378
4379 a.set_s("hole");
4380 EXPECT_FALSE(m.Matches(&a));
4381}
4382
4383// Tests that Property() does not match the NULL pointer.
4384TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
4385 Matcher<const AClass*> m = Property(&AClass::x, _);
1e59de90 4386 EXPECT_FALSE(m.Matches(nullptr));
31f18b77
FG
4387}
4388
4389// Tests that Property(&Foo::property, ...) works when the argument's
4390// type is a sub-type of const Foo*.
4391TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
4392 // The matcher expects a DerivedClass, but inside the Property() we
4393 // say AClass.
4394 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
4395
4396 DerivedClass d;
4397 d.set_n(1);
4398 EXPECT_TRUE(m.Matches(&d));
4399
4400 d.set_n(-1);
4401 EXPECT_FALSE(m.Matches(&d));
4402}
4403
4404// Tests that Property() can describe itself when used to match a pointer.
4405TEST(PropertyForPointerTest, CanDescribeSelf) {
4406 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4407
4408 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
4409 EXPECT_EQ("is an object whose given property isn't >= 0",
4410 DescribeNegation(m));
4411}
4412
1e59de90
TL
4413TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) {
4414 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
4415
4416 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m));
4417 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
4418 DescribeNegation(m));
4419}
4420
31f18b77
FG
4421// Tests that Property() can explain the result of matching a pointer.
4422TEST(PropertyForPointerTest, CanExplainMatchResult) {
4423 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
4424
4425 AClass a;
4426 a.set_n(1);
1e59de90 4427 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
31f18b77
FG
4428 EXPECT_EQ(
4429 "which points to an object whose given property is 1" + OfType("int"),
4430 Explain(m, &a));
4431
4432 m = Property(&AClass::n, GreaterThan(0));
4433 EXPECT_EQ("which points to an object whose given property is 1" +
4434 OfType("int") + ", which is 1 more than 0",
4435 Explain(m, &a));
4436}
4437
1e59de90
TL
4438TEST(PropertyForPointerTest, CanExplainMatchResultWithPropertyName) {
4439 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
4440
4441 AClass a;
4442 a.set_n(1);
4443 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(nullptr)));
4444 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
4445 OfType("int"),
4446 Explain(m, &a));
4447
4448 m = Property("fancy_name", &AClass::n, GreaterThan(0));
4449 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
4450 OfType("int") + ", which is 1 more than 0",
4451 Explain(m, &a));
4452}
4453
31f18b77
FG
4454// Tests ResultOf.
4455
4456// Tests that ResultOf(f, ...) compiles and works as expected when f is a
4457// function pointer.
1e59de90
TL
4458std::string IntToStringFunction(int input) {
4459 return input == 1 ? "foo" : "bar";
4460}
31f18b77
FG
4461
4462TEST(ResultOfTest, WorksForFunctionPointers) {
1e59de90 4463 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));
31f18b77
FG
4464
4465 EXPECT_TRUE(matcher.Matches(1));
4466 EXPECT_FALSE(matcher.Matches(2));
4467}
4468
4469// Tests that ResultOf() can describe itself.
4470TEST(ResultOfTest, CanDescribeItself) {
4471 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
4472
4473 EXPECT_EQ("is mapped by the given callable to a value that "
4474 "is equal to \"foo\"", Describe(matcher));
4475 EXPECT_EQ("is mapped by the given callable to a value that "
4476 "isn't equal to \"foo\"", DescribeNegation(matcher));
4477}
4478
4479// Tests that ResultOf() can explain the match result.
4480int IntFunction(int input) { return input == 42 ? 80 : 90; }
4481
4482TEST(ResultOfTest, CanExplainMatchResult) {
4483 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
4484 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
4485 Explain(matcher, 36));
4486
4487 matcher = ResultOf(&IntFunction, GreaterThan(85));
4488 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
4489 ", which is 5 more than 85", Explain(matcher, 36));
4490}
4491
4492// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4493// returns a non-reference.
4494TEST(ResultOfTest, WorksForNonReferenceResults) {
4495 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
4496
4497 EXPECT_TRUE(matcher.Matches(42));
4498 EXPECT_FALSE(matcher.Matches(36));
4499}
4500
4501// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4502// returns a reference to non-const.
4503double& DoubleFunction(double& input) { return input; } // NOLINT
4504
4505Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
4506 return obj;
4507}
4508
4509TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
4510 double x = 3.14;
4511 double x2 = x;
4512 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
4513
4514 EXPECT_TRUE(matcher.Matches(x));
4515 EXPECT_FALSE(matcher.Matches(x2));
4516
4517 // Test that ResultOf works with uncopyable objects
4518 Uncopyable obj(0);
4519 Uncopyable obj2(0);
4520 Matcher<Uncopyable&> matcher2 =
4521 ResultOf(&RefUncopyableFunction, Ref(obj));
4522
4523 EXPECT_TRUE(matcher2.Matches(obj));
4524 EXPECT_FALSE(matcher2.Matches(obj2));
4525}
4526
4527// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4528// returns a reference to const.
1e59de90 4529const std::string& StringFunction(const std::string& input) { return input; }
31f18b77
FG
4530
4531TEST(ResultOfTest, WorksForReferenceToConstResults) {
1e59de90
TL
4532 std::string s = "foo";
4533 std::string s2 = s;
4534 Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));
31f18b77
FG
4535
4536 EXPECT_TRUE(matcher.Matches(s));
4537 EXPECT_FALSE(matcher.Matches(s2));
4538}
4539
4540// Tests that ResultOf(f, m) works when f(x) and m's
4541// argument types are compatible but different.
4542TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
4543 // IntFunction() returns int but the inner matcher expects a signed char.
4544 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
4545
4546 EXPECT_TRUE(matcher.Matches(36));
4547 EXPECT_FALSE(matcher.Matches(42));
4548}
4549
4550// Tests that the program aborts when ResultOf is passed
4551// a NULL function pointer.
4552TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
4553 EXPECT_DEATH_IF_SUPPORTED(
1e59de90
TL
4554 ResultOf(static_cast<std::string (*)(int dummy)>(nullptr),
4555 Eq(std::string("foo"))),
4556 "NULL function pointer is passed into ResultOf\\(\\)\\.");
31f18b77
FG
4557}
4558
4559// Tests that ResultOf(f, ...) compiles and works as expected when f is a
4560// function reference.
4561TEST(ResultOfTest, WorksForFunctionReferences) {
4562 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
4563 EXPECT_TRUE(matcher.Matches(1));
4564 EXPECT_FALSE(matcher.Matches(2));
4565}
4566
4567// Tests that ResultOf(f, ...) compiles and works as expected when f is a
4568// function object.
1e59de90
TL
4569struct Functor {
4570 std::string operator()(int input) const {
31f18b77
FG
4571 return IntToStringFunction(input);
4572 }
4573};
4574
4575TEST(ResultOfTest, WorksForFunctors) {
1e59de90 4576 Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));
31f18b77
FG
4577
4578 EXPECT_TRUE(matcher.Matches(1));
4579 EXPECT_FALSE(matcher.Matches(2));
4580}
4581
4582// Tests that ResultOf(f, ...) compiles and works as expected when f is a
1e59de90 4583// functor with more than one operator() defined. ResultOf() must work
31f18b77
FG
4584// for each defined operator().
4585struct PolymorphicFunctor {
4586 typedef int result_type;
4587 int operator()(int n) { return n; }
4588 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
1e59de90 4589 std::string operator()(int *p) { return p ? "good ptr" : "null"; }
31f18b77
FG
4590};
4591
4592TEST(ResultOfTest, WorksForPolymorphicFunctors) {
4593 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
4594
4595 EXPECT_TRUE(matcher_int.Matches(10));
4596 EXPECT_FALSE(matcher_int.Matches(2));
4597
4598 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
4599
4600 EXPECT_TRUE(matcher_string.Matches("long string"));
4601 EXPECT_FALSE(matcher_string.Matches("shrt"));
4602}
4603
1e59de90
TL
4604TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) {
4605 Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr");
4606
4607 int n = 0;
4608 EXPECT_TRUE(matcher.Matches(&n));
4609 EXPECT_FALSE(matcher.Matches(nullptr));
4610}
4611
4612TEST(ResultOfTest, WorksForLambdas) {
4613 Matcher<int> matcher = ResultOf(
4614 [](int str_len) {
4615 return std::string(static_cast<size_t>(str_len), 'x');
4616 },
4617 "xxx");
4618 EXPECT_TRUE(matcher.Matches(3));
4619 EXPECT_FALSE(matcher.Matches(1));
4620}
4621
4622TEST(ResultOfTest, WorksForNonCopyableArguments) {
4623 Matcher<std::unique_ptr<int>> matcher = ResultOf(
4624 [](const std::unique_ptr<int>& str_len) {
4625 return std::string(static_cast<size_t>(*str_len), 'x');
4626 },
4627 "xxx");
4628 EXPECT_TRUE(matcher.Matches(std::unique_ptr<int>(new int(3))));
4629 EXPECT_FALSE(matcher.Matches(std::unique_ptr<int>(new int(1))));
4630}
4631
31f18b77
FG
4632const int* ReferencingFunction(const int& n) { return &n; }
4633
4634struct ReferencingFunctor {
4635 typedef const int* result_type;
4636 result_type operator()(const int& n) { return &n; }
4637};
4638
4639TEST(ResultOfTest, WorksForReferencingCallables) {
4640 const int n = 1;
4641 const int n2 = 1;
4642 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
4643 EXPECT_TRUE(matcher2.Matches(n));
4644 EXPECT_FALSE(matcher2.Matches(n2));
4645
4646 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
4647 EXPECT_TRUE(matcher3.Matches(n));
4648 EXPECT_FALSE(matcher3.Matches(n2));
4649}
4650
4651class DivisibleByImpl {
4652 public:
4653 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
4654
4655 // For testing using ExplainMatchResultTo() with polymorphic matchers.
4656 template <typename T>
4657 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
4658 *listener << "which is " << (n % divider_) << " modulo "
4659 << divider_;
4660 return (n % divider_) == 0;
4661 }
4662
4663 void DescribeTo(ostream* os) const {
4664 *os << "is divisible by " << divider_;
4665 }
4666
4667 void DescribeNegationTo(ostream* os) const {
4668 *os << "is not divisible by " << divider_;
4669 }
4670
4671 void set_divider(int a_divider) { divider_ = a_divider; }
4672 int divider() const { return divider_; }
4673
4674 private:
4675 int divider_;
4676};
4677
4678PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
4679 return MakePolymorphicMatcher(DivisibleByImpl(n));
4680}
4681
4682// Tests that when AllOf() fails, only the first failing matcher is
4683// asked to explain why.
4684TEST(ExplainMatchResultTest, AllOf_False_False) {
4685 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
4686 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
4687}
4688
4689// Tests that when AllOf() fails, only the first failing matcher is
4690// asked to explain why.
4691TEST(ExplainMatchResultTest, AllOf_False_True) {
4692 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
4693 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
4694}
4695
4696// Tests that when AllOf() fails, only the first failing matcher is
4697// asked to explain why.
4698TEST(ExplainMatchResultTest, AllOf_True_False) {
4699 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
4700 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
4701}
4702
4703// Tests that when AllOf() succeeds, all matchers are asked to explain
4704// why.
4705TEST(ExplainMatchResultTest, AllOf_True_True) {
4706 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
4707 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
4708}
4709
4710TEST(ExplainMatchResultTest, AllOf_True_True_2) {
4711 const Matcher<int> m = AllOf(Ge(2), Le(3));
4712 EXPECT_EQ("", Explain(m, 2));
4713}
4714
4715TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
4716 const Matcher<int> m = GreaterThan(5);
4717 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
4718}
4719
4720// The following two tests verify that values without a public copy
4721// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
4722// with the help of ByRef().
4723
4724class NotCopyable {
4725 public:
4726 explicit NotCopyable(int a_value) : value_(a_value) {}
4727
4728 int value() const { return value_; }
4729
4730 bool operator==(const NotCopyable& rhs) const {
4731 return value() == rhs.value();
4732 }
4733
4734 bool operator>=(const NotCopyable& rhs) const {
4735 return value() >= rhs.value();
4736 }
4737 private:
4738 int value_;
4739
4740 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
4741};
4742
4743TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
4744 const NotCopyable const_value1(1);
4745 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
4746
4747 const NotCopyable n1(1), n2(2);
4748 EXPECT_TRUE(m.Matches(n1));
4749 EXPECT_FALSE(m.Matches(n2));
4750}
4751
4752TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
4753 NotCopyable value2(2);
4754 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
4755
4756 NotCopyable n1(1), n2(2);
4757 EXPECT_FALSE(m.Matches(n1));
4758 EXPECT_TRUE(m.Matches(n2));
4759}
4760
4761TEST(IsEmptyTest, ImplementsIsEmpty) {
4762 vector<int> container;
4763 EXPECT_THAT(container, IsEmpty());
4764 container.push_back(0);
4765 EXPECT_THAT(container, Not(IsEmpty()));
4766 container.push_back(1);
4767 EXPECT_THAT(container, Not(IsEmpty()));
4768}
4769
4770TEST(IsEmptyTest, WorksWithString) {
1e59de90 4771 std::string text;
31f18b77
FG
4772 EXPECT_THAT(text, IsEmpty());
4773 text = "foo";
4774 EXPECT_THAT(text, Not(IsEmpty()));
1e59de90 4775 text = std::string("\0", 1);
31f18b77
FG
4776 EXPECT_THAT(text, Not(IsEmpty()));
4777}
4778
4779TEST(IsEmptyTest, CanDescribeSelf) {
4780 Matcher<vector<int> > m = IsEmpty();
4781 EXPECT_EQ("is empty", Describe(m));
4782 EXPECT_EQ("isn't empty", DescribeNegation(m));
4783}
4784
4785TEST(IsEmptyTest, ExplainsResult) {
4786 Matcher<vector<int> > m = IsEmpty();
4787 vector<int> container;
4788 EXPECT_EQ("", Explain(m, container));
4789 container.push_back(0);
4790 EXPECT_EQ("whose size is 1", Explain(m, container));
4791}
4792
1e59de90
TL
4793TEST(IsEmptyTest, WorksWithMoveOnly) {
4794 ContainerHelper helper;
4795 EXPECT_CALL(helper, Call(IsEmpty()));
4796 helper.Call({});
4797}
4798
4799TEST(IsTrueTest, IsTrueIsFalse) {
4800 EXPECT_THAT(true, IsTrue());
4801 EXPECT_THAT(false, IsFalse());
4802 EXPECT_THAT(true, Not(IsFalse()));
4803 EXPECT_THAT(false, Not(IsTrue()));
4804 EXPECT_THAT(0, Not(IsTrue()));
4805 EXPECT_THAT(0, IsFalse());
4806 EXPECT_THAT(nullptr, Not(IsTrue()));
4807 EXPECT_THAT(nullptr, IsFalse());
4808 EXPECT_THAT(-1, IsTrue());
4809 EXPECT_THAT(-1, Not(IsFalse()));
4810 EXPECT_THAT(1, IsTrue());
4811 EXPECT_THAT(1, Not(IsFalse()));
4812 EXPECT_THAT(2, IsTrue());
4813 EXPECT_THAT(2, Not(IsFalse()));
4814 int a = 42;
4815 EXPECT_THAT(a, IsTrue());
4816 EXPECT_THAT(a, Not(IsFalse()));
4817 EXPECT_THAT(&a, IsTrue());
4818 EXPECT_THAT(&a, Not(IsFalse()));
4819 EXPECT_THAT(false, Not(IsTrue()));
4820 EXPECT_THAT(true, Not(IsFalse()));
4821 EXPECT_THAT(std::true_type(), IsTrue());
4822 EXPECT_THAT(std::true_type(), Not(IsFalse()));
4823 EXPECT_THAT(std::false_type(), IsFalse());
4824 EXPECT_THAT(std::false_type(), Not(IsTrue()));
4825 EXPECT_THAT(nullptr, Not(IsTrue()));
4826 EXPECT_THAT(nullptr, IsFalse());
4827 std::unique_ptr<int> null_unique;
4828 std::unique_ptr<int> nonnull_unique(new int(0));
4829 EXPECT_THAT(null_unique, Not(IsTrue()));
4830 EXPECT_THAT(null_unique, IsFalse());
4831 EXPECT_THAT(nonnull_unique, IsTrue());
4832 EXPECT_THAT(nonnull_unique, Not(IsFalse()));
4833}
4834
31f18b77
FG
4835TEST(SizeIsTest, ImplementsSizeIs) {
4836 vector<int> container;
4837 EXPECT_THAT(container, SizeIs(0));
4838 EXPECT_THAT(container, Not(SizeIs(1)));
4839 container.push_back(0);
4840 EXPECT_THAT(container, Not(SizeIs(0)));
4841 EXPECT_THAT(container, SizeIs(1));
4842 container.push_back(0);
4843 EXPECT_THAT(container, Not(SizeIs(0)));
4844 EXPECT_THAT(container, SizeIs(2));
4845}
4846
4847TEST(SizeIsTest, WorksWithMap) {
1e59de90 4848 map<std::string, int> container;
31f18b77
FG
4849 EXPECT_THAT(container, SizeIs(0));
4850 EXPECT_THAT(container, Not(SizeIs(1)));
4851 container.insert(make_pair("foo", 1));
4852 EXPECT_THAT(container, Not(SizeIs(0)));
4853 EXPECT_THAT(container, SizeIs(1));
4854 container.insert(make_pair("bar", 2));
4855 EXPECT_THAT(container, Not(SizeIs(0)));
4856 EXPECT_THAT(container, SizeIs(2));
4857}
4858
4859TEST(SizeIsTest, WorksWithReferences) {
4860 vector<int> container;
4861 Matcher<const vector<int>&> m = SizeIs(1);
4862 EXPECT_THAT(container, Not(m));
4863 container.push_back(0);
4864 EXPECT_THAT(container, m);
4865}
4866
1e59de90
TL
4867TEST(SizeIsTest, WorksWithMoveOnly) {
4868 ContainerHelper helper;
4869 EXPECT_CALL(helper, Call(SizeIs(3)));
4870 helper.Call(MakeUniquePtrs({1, 2, 3}));
4871}
4872
4873// SizeIs should work for any type that provides a size() member function.
4874// For example, a size_type member type should not need to be provided.
4875struct MinimalistCustomType {
4876 int size() const { return 1; }
4877};
4878TEST(SizeIsTest, WorksWithMinimalistCustomType) {
4879 MinimalistCustomType container;
4880 EXPECT_THAT(container, SizeIs(1));
4881 EXPECT_THAT(container, Not(SizeIs(0)));
4882}
4883
31f18b77
FG
4884TEST(SizeIsTest, CanDescribeSelf) {
4885 Matcher<vector<int> > m = SizeIs(2);
4886 EXPECT_EQ("size is equal to 2", Describe(m));
4887 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
4888}
4889
4890TEST(SizeIsTest, ExplainsResult) {
4891 Matcher<vector<int> > m1 = SizeIs(2);
4892 Matcher<vector<int> > m2 = SizeIs(Lt(2u));
4893 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
1e59de90 4894 Matcher<vector<int> > m4 = SizeIs(Gt(1u));
31f18b77
FG
4895 vector<int> container;
4896 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
4897 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
4898 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
1e59de90 4899 EXPECT_EQ("whose size 0 doesn't match", Explain(m4, container));
31f18b77
FG
4900 container.push_back(0);
4901 container.push_back(0);
4902 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
4903 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
4904 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
1e59de90 4905 EXPECT_EQ("whose size 2 matches", Explain(m4, container));
31f18b77
FG
4906}
4907
4908#if GTEST_HAS_TYPED_TEST
4909// Tests ContainerEq with different container types, and
4910// different element types.
4911
4912template <typename T>
4913class ContainerEqTest : public testing::Test {};
4914
4915typedef testing::Types<
4916 set<int>,
4917 vector<size_t>,
4918 multiset<size_t>,
4919 list<int> >
4920 ContainerEqTestTypes;
4921
1e59de90 4922TYPED_TEST_SUITE(ContainerEqTest, ContainerEqTestTypes);
31f18b77
FG
4923
4924// Tests that the filled container is equal to itself.
4925TYPED_TEST(ContainerEqTest, EqualsSelf) {
4926 static const int vals[] = {1, 1, 2, 3, 5, 8};
4927 TypeParam my_set(vals, vals + 6);
4928 const Matcher<TypeParam> m = ContainerEq(my_set);
4929 EXPECT_TRUE(m.Matches(my_set));
4930 EXPECT_EQ("", Explain(m, my_set));
4931}
4932
4933// Tests that missing values are reported.
4934TYPED_TEST(ContainerEqTest, ValueMissing) {
4935 static const int vals[] = {1, 1, 2, 3, 5, 8};
4936 static const int test_vals[] = {2, 1, 8, 5};
4937 TypeParam my_set(vals, vals + 6);
4938 TypeParam test_set(test_vals, test_vals + 4);
4939 const Matcher<TypeParam> m = ContainerEq(my_set);
4940 EXPECT_FALSE(m.Matches(test_set));
4941 EXPECT_EQ("which doesn't have these expected elements: 3",
4942 Explain(m, test_set));
4943}
4944
4945// Tests that added values are reported.
4946TYPED_TEST(ContainerEqTest, ValueAdded) {
4947 static const int vals[] = {1, 1, 2, 3, 5, 8};
4948 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4949 TypeParam my_set(vals, vals + 6);
4950 TypeParam test_set(test_vals, test_vals + 6);
4951 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4952 EXPECT_FALSE(m.Matches(test_set));
4953 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
4954}
4955
4956// Tests that added and missing values are reported together.
4957TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4958 static const int vals[] = {1, 1, 2, 3, 5, 8};
4959 static const int test_vals[] = {1, 2, 3, 8, 46};
4960 TypeParam my_set(vals, vals + 6);
4961 TypeParam test_set(test_vals, test_vals + 5);
4962 const Matcher<TypeParam> m = ContainerEq(my_set);
4963 EXPECT_FALSE(m.Matches(test_set));
4964 EXPECT_EQ("which has these unexpected elements: 46,\n"
4965 "and doesn't have these expected elements: 5",
4966 Explain(m, test_set));
4967}
4968
4969// Tests duplicated value -- expect no explanation.
4970TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4971 static const int vals[] = {1, 1, 2, 3, 5, 8};
4972 static const int test_vals[] = {1, 2, 3, 5, 8};
4973 TypeParam my_set(vals, vals + 6);
4974 TypeParam test_set(test_vals, test_vals + 5);
4975 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4976 // Depending on the container, match may be true or false
4977 // But in any case there should be no explanation.
4978 EXPECT_EQ("", Explain(m, test_set));
4979}
4980#endif // GTEST_HAS_TYPED_TEST
4981
1e59de90
TL
4982// Tests that multiple missing values are reported.
4983// Using just vector here, so order is predictable.
31f18b77
FG
4984TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4985 static const int vals[] = {1, 1, 2, 3, 5, 8};
4986 static const int test_vals[] = {2, 1, 5};
4987 vector<int> my_set(vals, vals + 6);
4988 vector<int> test_set(test_vals, test_vals + 3);
4989 const Matcher<vector<int> > m = ContainerEq(my_set);
4990 EXPECT_FALSE(m.Matches(test_set));
4991 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4992 Explain(m, test_set));
4993}
4994
4995// Tests that added values are reported.
1e59de90 4996// Using just vector here, so order is predictable.
31f18b77
FG
4997TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4998 static const int vals[] = {1, 1, 2, 3, 5, 8};
4999 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
5000 list<size_t> my_set(vals, vals + 6);
5001 list<size_t> test_set(test_vals, test_vals + 7);
5002 const Matcher<const list<size_t>&> m = ContainerEq(my_set);
5003 EXPECT_FALSE(m.Matches(test_set));
5004 EXPECT_EQ("which has these unexpected elements: 92, 46",
5005 Explain(m, test_set));
5006}
5007
5008// Tests that added and missing values are reported together.
5009TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
5010 static const int vals[] = {1, 1, 2, 3, 5, 8};
5011 static const int test_vals[] = {1, 2, 3, 92, 46};
5012 list<size_t> my_set(vals, vals + 6);
5013 list<size_t> test_set(test_vals, test_vals + 5);
5014 const Matcher<const list<size_t> > m = ContainerEq(my_set);
5015 EXPECT_FALSE(m.Matches(test_set));
5016 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
5017 "and doesn't have these expected elements: 5, 8",
5018 Explain(m, test_set));
5019}
5020
5021// Tests to see that duplicate elements are detected,
5022// but (as above) not reported in the explanation.
5023TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
5024 static const int vals[] = {1, 1, 2, 3, 5, 8};
5025 static const int test_vals[] = {1, 2, 3, 5, 8};
5026 vector<int> my_set(vals, vals + 6);
5027 vector<int> test_set(test_vals, test_vals + 5);
5028 const Matcher<vector<int> > m = ContainerEq(my_set);
5029 EXPECT_TRUE(m.Matches(my_set));
5030 EXPECT_FALSE(m.Matches(test_set));
5031 // There is nothing to report when both sets contain all the same values.
5032 EXPECT_EQ("", Explain(m, test_set));
5033}
5034
5035// Tests that ContainerEq works for non-trivial associative containers,
5036// like maps.
5037TEST(ContainerEqExtraTest, WorksForMaps) {
5038 map<int, std::string> my_map;
5039 my_map[0] = "a";
5040 my_map[1] = "b";
5041
5042 map<int, std::string> test_map;
5043 test_map[0] = "aa";
5044 test_map[1] = "b";
5045
5046 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
5047 EXPECT_TRUE(m.Matches(my_map));
5048 EXPECT_FALSE(m.Matches(test_map));
5049
5050 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
5051 "and doesn't have these expected elements: (0, \"a\")",
5052 Explain(m, test_map));
5053}
5054
5055TEST(ContainerEqExtraTest, WorksForNativeArray) {
5056 int a1[] = {1, 2, 3};
5057 int a2[] = {1, 2, 3};
5058 int b[] = {1, 2, 4};
5059
5060 EXPECT_THAT(a1, ContainerEq(a2));
5061 EXPECT_THAT(a1, Not(ContainerEq(b)));
5062}
5063
5064TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
5065 const char a1[][3] = {"hi", "lo"};
5066 const char a2[][3] = {"hi", "lo"};
5067 const char b[][3] = {"lo", "hi"};
5068
5069 // Tests using ContainerEq() in the first dimension.
5070 EXPECT_THAT(a1, ContainerEq(a2));
5071 EXPECT_THAT(a1, Not(ContainerEq(b)));
5072
5073 // Tests using ContainerEq() in the second dimension.
5074 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
5075 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
5076}
5077
5078TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
5079 const int a1[] = {1, 2, 3};
5080 const int a2[] = {1, 2, 3};
5081 const int b[] = {1, 2, 3, 4};
5082
5083 const int* const p1 = a1;
1e59de90
TL
5084 EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2));
5085 EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b)));
31f18b77
FG
5086
5087 const int c[] = {1, 3, 2};
1e59de90 5088 EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c)));
31f18b77
FG
5089}
5090
5091TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
5092 std::string a1[][3] = {
5093 {"hi", "hello", "ciao"},
5094 {"bye", "see you", "ciao"}
5095 };
5096
5097 std::string a2[][3] = {
5098 {"hi", "hello", "ciao"},
5099 {"bye", "see you", "ciao"}
5100 };
5101
5102 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
5103 EXPECT_THAT(a1, m);
5104
5105 a2[0][0] = "ha";
5106 EXPECT_THAT(a1, m);
5107}
5108
5109TEST(WhenSortedByTest, WorksForEmptyContainer) {
5110 const vector<int> numbers;
5111 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
5112 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
5113}
5114
5115TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
5116 vector<unsigned> numbers;
5117 numbers.push_back(3);
5118 numbers.push_back(1);
5119 numbers.push_back(2);
5120 numbers.push_back(2);
5121 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
5122 ElementsAre(3, 2, 2, 1)));
5123 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
5124 ElementsAre(1, 2, 2, 3))));
5125}
5126
5127TEST(WhenSortedByTest, WorksForNonVectorContainer) {
1e59de90 5128 list<std::string> words;
31f18b77
FG
5129 words.push_back("say");
5130 words.push_back("hello");
5131 words.push_back("world");
1e59de90 5132 EXPECT_THAT(words, WhenSortedBy(less<std::string>(),
31f18b77 5133 ElementsAre("hello", "say", "world")));
1e59de90 5134 EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),
31f18b77
FG
5135 ElementsAre("say", "hello", "world"))));
5136}
5137
5138TEST(WhenSortedByTest, WorksForNativeArray) {
5139 const int numbers[] = {1, 3, 2, 4};
5140 const int sorted_numbers[] = {1, 2, 3, 4};
5141 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
5142 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
5143 ElementsAreArray(sorted_numbers)));
5144 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
5145}
5146
5147TEST(WhenSortedByTest, CanDescribeSelf) {
5148 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
5149 EXPECT_EQ("(when sorted) has 2 elements where\n"
5150 "element #0 is equal to 1,\n"
5151 "element #1 is equal to 2",
5152 Describe(m));
5153 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
5154 "element #0 isn't equal to 1, or\n"
5155 "element #1 isn't equal to 2",
5156 DescribeNegation(m));
5157}
5158
5159TEST(WhenSortedByTest, ExplainsMatchResult) {
5160 const int a[] = {2, 1};
5161 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
5162 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
5163 EXPECT_EQ("which is { 1, 2 } when sorted",
5164 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
5165}
5166
5167// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
5168// need to test it as exhaustively as we test the latter.
5169
5170TEST(WhenSortedTest, WorksForEmptyContainer) {
5171 const vector<int> numbers;
5172 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
5173 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
5174}
5175
5176TEST(WhenSortedTest, WorksForNonEmptyContainer) {
1e59de90 5177 list<std::string> words;
31f18b77
FG
5178 words.push_back("3");
5179 words.push_back("1");
5180 words.push_back("2");
5181 words.push_back("2");
5182 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
5183 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
5184}
5185
5186TEST(WhenSortedTest, WorksForMapTypes) {
1e59de90
TL
5187 map<std::string, int> word_counts;
5188 word_counts["and"] = 1;
5189 word_counts["the"] = 1;
5190 word_counts["buffalo"] = 2;
5191 EXPECT_THAT(word_counts,
5192 WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),
5193 Pair("the", 1))));
5194 EXPECT_THAT(word_counts,
5195 Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
5196 Pair("buffalo", 2)))));
31f18b77
FG
5197}
5198
5199TEST(WhenSortedTest, WorksForMultiMapTypes) {
5200 multimap<int, int> ifib;
5201 ifib.insert(make_pair(8, 6));
5202 ifib.insert(make_pair(2, 3));
5203 ifib.insert(make_pair(1, 1));
5204 ifib.insert(make_pair(3, 4));
5205 ifib.insert(make_pair(1, 2));
5206 ifib.insert(make_pair(5, 5));
5207 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
5208 Pair(1, 2),
5209 Pair(2, 3),
5210 Pair(3, 4),
5211 Pair(5, 5),
5212 Pair(8, 6))));
5213 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
5214 Pair(2, 3),
5215 Pair(1, 1),
5216 Pair(3, 4),
5217 Pair(1, 2),
5218 Pair(5, 5)))));
5219}
5220
5221TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
5222 std::deque<int> d;
5223 d.push_back(2);
5224 d.push_back(1);
5225 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
5226 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
5227}
5228
5229TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
5230 std::deque<int> d;
5231 d.push_back(2);
5232 d.push_back(1);
5233 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
5234 EXPECT_THAT(d, WhenSorted(vector_match));
5235 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
5236 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
5237}
5238
5239// Deliberately bare pseudo-container.
5240// Offers only begin() and end() accessors, yielding InputIterator.
5241template <typename T>
5242class Streamlike {
5243 private:
5244 class ConstIter;
5245 public:
5246 typedef ConstIter const_iterator;
5247 typedef T value_type;
5248
5249 template <typename InIter>
5250 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
5251
5252 const_iterator begin() const {
5253 return const_iterator(this, remainder_.begin());
5254 }
5255 const_iterator end() const {
5256 return const_iterator(this, remainder_.end());
5257 }
5258
5259 private:
5260 class ConstIter : public std::iterator<std::input_iterator_tag,
5261 value_type,
5262 ptrdiff_t,
5263 const value_type*,
5264 const value_type&> {
5265 public:
5266 ConstIter(const Streamlike* s,
5267 typename std::list<value_type>::iterator pos)
5268 : s_(s), pos_(pos) {}
5269
5270 const value_type& operator*() const { return *pos_; }
5271 const value_type* operator->() const { return &*pos_; }
5272 ConstIter& operator++() {
5273 s_->remainder_.erase(pos_++);
5274 return *this;
5275 }
5276
5277 // *iter++ is required to work (see std::istreambuf_iterator).
5278 // (void)iter++ is also required to work.
5279 class PostIncrProxy {
5280 public:
5281 explicit PostIncrProxy(const value_type& value) : value_(value) {}
5282 value_type operator*() const { return value_; }
5283 private:
5284 value_type value_;
5285 };
5286 PostIncrProxy operator++(int) {
5287 PostIncrProxy proxy(**this);
5288 ++(*this);
5289 return proxy;
5290 }
5291
5292 friend bool operator==(const ConstIter& a, const ConstIter& b) {
5293 return a.s_ == b.s_ && a.pos_ == b.pos_;
5294 }
5295 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
5296 return !(a == b);
5297 }
5298
5299 private:
5300 const Streamlike* s_;
5301 typename std::list<value_type>::iterator pos_;
5302 };
5303
5304 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
5305 os << "[";
5306 typedef typename std::list<value_type>::const_iterator Iter;
5307 const char* sep = "";
5308 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
5309 os << sep << *it;
5310 sep = ",";
5311 }
5312 os << "]";
5313 return os;
5314 }
5315
5316 mutable std::list<value_type> remainder_; // modified by iteration
5317};
5318
5319TEST(StreamlikeTest, Iteration) {
5320 const int a[5] = {2, 1, 4, 5, 3};
5321 Streamlike<int> s(a, a + 5);
5322 Streamlike<int>::const_iterator it = s.begin();
5323 const int* ip = a;
5324 while (it != s.end()) {
5325 SCOPED_TRACE(ip - a);
5326 EXPECT_EQ(*ip++, *it++);
5327 }
5328}
5329
31f18b77
FG
5330TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
5331 std::forward_list<int> container;
5332 EXPECT_THAT(container, BeginEndDistanceIs(0));
5333 EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
5334 container.push_front(0);
5335 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
5336 EXPECT_THAT(container, BeginEndDistanceIs(1));
5337 container.push_front(0);
5338 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
5339 EXPECT_THAT(container, BeginEndDistanceIs(2));
5340}
31f18b77
FG
5341
5342TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
5343 const int a[5] = {1, 2, 3, 4, 5};
5344 Streamlike<int> s(a, a + 5);
5345 EXPECT_THAT(s, BeginEndDistanceIs(5));
5346}
5347
5348TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
5349 Matcher<vector<int> > m = BeginEndDistanceIs(2);
5350 EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
5351 EXPECT_EQ("distance between begin() and end() isn't equal to 2",
5352 DescribeNegation(m));
5353}
5354
1e59de90
TL
5355TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) {
5356 ContainerHelper helper;
5357 EXPECT_CALL(helper, Call(BeginEndDistanceIs(2)));
5358 helper.Call(MakeUniquePtrs({1, 2}));
5359}
5360
31f18b77
FG
5361TEST(BeginEndDistanceIsTest, ExplainsResult) {
5362 Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
5363 Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
5364 Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
5365 Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
5366 vector<int> container;
5367 EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
5368 Explain(m1, container));
5369 EXPECT_EQ("whose distance between begin() and end() 0 matches",
5370 Explain(m2, container));
5371 EXPECT_EQ("whose distance between begin() and end() 0 matches",
5372 Explain(m3, container));
5373 EXPECT_EQ(
5374 "whose distance between begin() and end() 0 doesn't match, which is 1 "
5375 "less than 1",
5376 Explain(m4, container));
5377 container.push_back(0);
5378 container.push_back(0);
5379 EXPECT_EQ("whose distance between begin() and end() 2 matches",
5380 Explain(m1, container));
5381 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
5382 Explain(m2, container));
5383 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
5384 Explain(m3, container));
5385 EXPECT_EQ(
5386 "whose distance between begin() and end() 2 matches, which is 1 more "
5387 "than 1",
5388 Explain(m4, container));
5389}
5390
5391TEST(WhenSortedTest, WorksForStreamlike) {
5392 // Streamlike 'container' provides only minimal iterator support.
5393 // Its iterators are tagged with input_iterator_tag.
5394 const int a[5] = {2, 1, 4, 5, 3};
1e59de90 5395 Streamlike<int> s(std::begin(a), std::end(a));
31f18b77
FG
5396 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
5397 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
5398}
5399
5400TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
5401 const int a[] = {2, 1, 4, 5, 3};
1e59de90 5402 Streamlike<int> s(std::begin(a), std::end(a));
31f18b77
FG
5403 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
5404 EXPECT_THAT(s, WhenSorted(vector_match));
5405 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
5406}
5407
1e59de90
TL
5408TEST(IsSupersetOfTest, WorksForNativeArray) {
5409 const int subset[] = {1, 4};
5410 const int superset[] = {1, 2, 4};
5411 const int disjoint[] = {1, 0, 3};
5412 EXPECT_THAT(subset, IsSupersetOf(subset));
5413 EXPECT_THAT(subset, Not(IsSupersetOf(superset)));
5414 EXPECT_THAT(superset, IsSupersetOf(subset));
5415 EXPECT_THAT(subset, Not(IsSupersetOf(disjoint)));
5416 EXPECT_THAT(disjoint, Not(IsSupersetOf(subset)));
5417}
5418
5419TEST(IsSupersetOfTest, WorksWithDuplicates) {
5420 const int not_enough[] = {1, 2};
5421 const int enough[] = {1, 1, 2};
5422 const int expected[] = {1, 1};
5423 EXPECT_THAT(not_enough, Not(IsSupersetOf(expected)));
5424 EXPECT_THAT(enough, IsSupersetOf(expected));
5425}
5426
5427TEST(IsSupersetOfTest, WorksForEmpty) {
5428 vector<int> numbers;
5429 vector<int> expected;
5430 EXPECT_THAT(numbers, IsSupersetOf(expected));
5431 expected.push_back(1);
5432 EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
5433 expected.clear();
5434 numbers.push_back(1);
5435 numbers.push_back(2);
5436 EXPECT_THAT(numbers, IsSupersetOf(expected));
5437 expected.push_back(1);
5438 EXPECT_THAT(numbers, IsSupersetOf(expected));
5439 expected.push_back(2);
5440 EXPECT_THAT(numbers, IsSupersetOf(expected));
5441 expected.push_back(3);
5442 EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));
5443}
5444
5445TEST(IsSupersetOfTest, WorksForStreamlike) {
5446 const int a[5] = {1, 2, 3, 4, 5};
5447 Streamlike<int> s(std::begin(a), std::end(a));
5448
5449 vector<int> expected;
5450 expected.push_back(1);
5451 expected.push_back(2);
5452 expected.push_back(5);
5453 EXPECT_THAT(s, IsSupersetOf(expected));
5454
5455 expected.push_back(0);
5456 EXPECT_THAT(s, Not(IsSupersetOf(expected)));
5457}
5458
5459TEST(IsSupersetOfTest, TakesStlContainer) {
5460 const int actual[] = {3, 1, 2};
5461
5462 ::std::list<int> expected;
5463 expected.push_back(1);
5464 expected.push_back(3);
5465 EXPECT_THAT(actual, IsSupersetOf(expected));
5466
5467 expected.push_back(4);
5468 EXPECT_THAT(actual, Not(IsSupersetOf(expected)));
5469}
5470
5471TEST(IsSupersetOfTest, Describe) {
5472 typedef std::vector<int> IntVec;
5473 IntVec expected;
5474 expected.push_back(111);
5475 expected.push_back(222);
5476 expected.push_back(333);
5477 EXPECT_THAT(
5478 Describe<IntVec>(IsSupersetOf(expected)),
5479 Eq("a surjection from elements to requirements exists such that:\n"
5480 " - an element is equal to 111\n"
5481 " - an element is equal to 222\n"
5482 " - an element is equal to 333"));
5483}
5484
5485TEST(IsSupersetOfTest, DescribeNegation) {
5486 typedef std::vector<int> IntVec;
5487 IntVec expected;
5488 expected.push_back(111);
5489 expected.push_back(222);
5490 expected.push_back(333);
5491 EXPECT_THAT(
5492 DescribeNegation<IntVec>(IsSupersetOf(expected)),
5493 Eq("no surjection from elements to requirements exists such that:\n"
5494 " - an element is equal to 111\n"
5495 " - an element is equal to 222\n"
5496 " - an element is equal to 333"));
5497}
5498
5499TEST(IsSupersetOfTest, MatchAndExplain) {
5500 std::vector<int> v;
5501 v.push_back(2);
5502 v.push_back(3);
5503 std::vector<int> expected;
5504 expected.push_back(1);
5505 expected.push_back(2);
5506 StringMatchResultListener listener;
5507 ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
5508 << listener.str();
5509 EXPECT_THAT(listener.str(),
5510 Eq("where the following matchers don't match any elements:\n"
5511 "matcher #0: is equal to 1"));
5512
5513 v.push_back(1);
5514 listener.Clear();
5515 ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
5516 << listener.str();
5517 EXPECT_THAT(listener.str(), Eq("where:\n"
5518 " - element #0 is matched by matcher #1,\n"
5519 " - element #2 is matched by matcher #0"));
5520}
5521
5522TEST(IsSupersetOfTest, WorksForRhsInitializerList) {
5523 const int numbers[] = {1, 3, 6, 2, 4, 5};
5524 EXPECT_THAT(numbers, IsSupersetOf({1, 2}));
5525 EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0})));
5526}
5527
5528TEST(IsSupersetOfTest, WorksWithMoveOnly) {
5529 ContainerHelper helper;
5530 EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)})));
5531 helper.Call(MakeUniquePtrs({1, 2}));
5532 EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)}))));
5533 helper.Call(MakeUniquePtrs({2}));
5534}
5535
5536TEST(IsSubsetOfTest, WorksForNativeArray) {
5537 const int subset[] = {1, 4};
5538 const int superset[] = {1, 2, 4};
5539 const int disjoint[] = {1, 0, 3};
5540 EXPECT_THAT(subset, IsSubsetOf(subset));
5541 EXPECT_THAT(subset, IsSubsetOf(superset));
5542 EXPECT_THAT(superset, Not(IsSubsetOf(subset)));
5543 EXPECT_THAT(subset, Not(IsSubsetOf(disjoint)));
5544 EXPECT_THAT(disjoint, Not(IsSubsetOf(subset)));
5545}
5546
5547TEST(IsSubsetOfTest, WorksWithDuplicates) {
5548 const int not_enough[] = {1, 2};
5549 const int enough[] = {1, 1, 2};
5550 const int actual[] = {1, 1};
5551 EXPECT_THAT(actual, Not(IsSubsetOf(not_enough)));
5552 EXPECT_THAT(actual, IsSubsetOf(enough));
5553}
5554
5555TEST(IsSubsetOfTest, WorksForEmpty) {
5556 vector<int> numbers;
5557 vector<int> expected;
5558 EXPECT_THAT(numbers, IsSubsetOf(expected));
5559 expected.push_back(1);
5560 EXPECT_THAT(numbers, IsSubsetOf(expected));
5561 expected.clear();
5562 numbers.push_back(1);
5563 numbers.push_back(2);
5564 EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
5565 expected.push_back(1);
5566 EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));
5567 expected.push_back(2);
5568 EXPECT_THAT(numbers, IsSubsetOf(expected));
5569 expected.push_back(3);
5570 EXPECT_THAT(numbers, IsSubsetOf(expected));
5571}
5572
5573TEST(IsSubsetOfTest, WorksForStreamlike) {
5574 const int a[5] = {1, 2};
5575 Streamlike<int> s(std::begin(a), std::end(a));
5576
5577 vector<int> expected;
5578 expected.push_back(1);
5579 EXPECT_THAT(s, Not(IsSubsetOf(expected)));
5580 expected.push_back(2);
5581 expected.push_back(5);
5582 EXPECT_THAT(s, IsSubsetOf(expected));
5583}
5584
5585TEST(IsSubsetOfTest, TakesStlContainer) {
5586 const int actual[] = {3, 1, 2};
5587
5588 ::std::list<int> expected;
5589 expected.push_back(1);
5590 expected.push_back(3);
5591 EXPECT_THAT(actual, Not(IsSubsetOf(expected)));
5592
5593 expected.push_back(2);
5594 expected.push_back(4);
5595 EXPECT_THAT(actual, IsSubsetOf(expected));
5596}
5597
5598TEST(IsSubsetOfTest, Describe) {
5599 typedef std::vector<int> IntVec;
5600 IntVec expected;
5601 expected.push_back(111);
5602 expected.push_back(222);
5603 expected.push_back(333);
5604
5605 EXPECT_THAT(
5606 Describe<IntVec>(IsSubsetOf(expected)),
5607 Eq("an injection from elements to requirements exists such that:\n"
5608 " - an element is equal to 111\n"
5609 " - an element is equal to 222\n"
5610 " - an element is equal to 333"));
5611}
5612
5613TEST(IsSubsetOfTest, DescribeNegation) {
5614 typedef std::vector<int> IntVec;
5615 IntVec expected;
5616 expected.push_back(111);
5617 expected.push_back(222);
5618 expected.push_back(333);
5619 EXPECT_THAT(
5620 DescribeNegation<IntVec>(IsSubsetOf(expected)),
5621 Eq("no injection from elements to requirements exists such that:\n"
5622 " - an element is equal to 111\n"
5623 " - an element is equal to 222\n"
5624 " - an element is equal to 333"));
5625}
5626
5627TEST(IsSubsetOfTest, MatchAndExplain) {
5628 std::vector<int> v;
5629 v.push_back(2);
5630 v.push_back(3);
5631 std::vector<int> expected;
5632 expected.push_back(1);
5633 expected.push_back(2);
5634 StringMatchResultListener listener;
5635 ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
5636 << listener.str();
5637 EXPECT_THAT(listener.str(),
5638 Eq("where the following elements don't match any matchers:\n"
5639 "element #1: 3"));
5640
5641 expected.push_back(3);
5642 listener.Clear();
5643 ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
5644 << listener.str();
5645 EXPECT_THAT(listener.str(), Eq("where:\n"
5646 " - element #0 is matched by matcher #1,\n"
5647 " - element #1 is matched by matcher #2"));
5648}
5649
5650TEST(IsSubsetOfTest, WorksForRhsInitializerList) {
5651 const int numbers[] = {1, 2, 3};
5652 EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4}));
5653 EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2})));
5654}
5655
5656TEST(IsSubsetOfTest, WorksWithMoveOnly) {
5657 ContainerHelper helper;
5658 EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)})));
5659 helper.Call(MakeUniquePtrs({1}));
5660 EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)}))));
5661 helper.Call(MakeUniquePtrs({2}));
5662}
5663
31f18b77
FG
5664// Tests using ElementsAre() and ElementsAreArray() with stream-like
5665// "containers".
5666
5667TEST(ElemensAreStreamTest, WorksForStreamlike) {
5668 const int a[5] = {1, 2, 3, 4, 5};
1e59de90 5669 Streamlike<int> s(std::begin(a), std::end(a));
31f18b77
FG
5670 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
5671 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
5672}
5673
5674TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
5675 const int a[5] = {1, 2, 3, 4, 5};
1e59de90 5676 Streamlike<int> s(std::begin(a), std::end(a));
31f18b77
FG
5677
5678 vector<int> expected;
5679 expected.push_back(1);
5680 expected.push_back(2);
5681 expected.push_back(3);
5682 expected.push_back(4);
5683 expected.push_back(5);
5684 EXPECT_THAT(s, ElementsAreArray(expected));
5685
5686 expected[3] = 0;
5687 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
5688}
5689
5690TEST(ElementsAreTest, WorksWithUncopyable) {
5691 Uncopyable objs[2];
5692 objs[0].set_value(-3);
5693 objs[1].set_value(1);
5694 EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
5695}
5696
1e59de90
TL
5697TEST(ElementsAreTest, WorksWithMoveOnly) {
5698 ContainerHelper helper;
5699 EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2))));
5700 helper.Call(MakeUniquePtrs({1, 2}));
5701
5702 EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)})));
5703 helper.Call(MakeUniquePtrs({3, 4}));
5704}
5705
31f18b77
FG
5706TEST(ElementsAreTest, TakesStlContainer) {
5707 const int actual[] = {3, 1, 2};
5708
5709 ::std::list<int> expected;
5710 expected.push_back(3);
5711 expected.push_back(1);
5712 expected.push_back(2);
5713 EXPECT_THAT(actual, ElementsAreArray(expected));
5714
5715 expected.push_back(4);
5716 EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
5717}
5718
5719// Tests for UnorderedElementsAreArray()
5720
5721TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
5722 const int a[] = {0, 1, 2, 3, 4};
1e59de90 5723 std::vector<int> s(std::begin(a), std::end(a));
31f18b77
FG
5724 do {
5725 StringMatchResultListener listener;
5726 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
5727 s, &listener)) << listener.str();
5728 } while (std::next_permutation(s.begin(), s.end()));
5729}
5730
5731TEST(UnorderedElementsAreArrayTest, VectorBool) {
5732 const bool a[] = {0, 1, 0, 1, 1};
5733 const bool b[] = {1, 0, 1, 1, 0};
1e59de90
TL
5734 std::vector<bool> expected(std::begin(a), std::end(a));
5735 std::vector<bool> actual(std::begin(b), std::end(b));
31f18b77
FG
5736 StringMatchResultListener listener;
5737 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
5738 actual, &listener)) << listener.str();
5739}
5740
5741TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
5742 // Streamlike 'container' provides only minimal iterator support.
5743 // Its iterators are tagged with input_iterator_tag, and it has no
5744 // size() or empty() methods.
5745 const int a[5] = {2, 1, 4, 5, 3};
1e59de90 5746 Streamlike<int> s(std::begin(a), std::end(a));
31f18b77
FG
5747
5748 ::std::vector<int> expected;
5749 expected.push_back(1);
5750 expected.push_back(2);
5751 expected.push_back(3);
5752 expected.push_back(4);
5753 expected.push_back(5);
5754 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
5755
5756 expected.push_back(6);
5757 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
5758}
5759
5760TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
5761 const int actual[] = {3, 1, 2};
5762
5763 ::std::list<int> expected;
5764 expected.push_back(1);
5765 expected.push_back(2);
5766 expected.push_back(3);
5767 EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
5768
5769 expected.push_back(4);
5770 EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
5771}
5772
31f18b77
FG
5773
5774TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
5775 const int a[5] = {2, 1, 4, 5, 3};
5776 EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
5777 EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
5778}
5779
5780TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
1e59de90 5781 const std::string a[5] = {"a", "b", "c", "d", "e"};
31f18b77
FG
5782 EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
5783 EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
5784}
5785
5786TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
5787 const int a[5] = {2, 1, 4, 5, 3};
5788 EXPECT_THAT(a, UnorderedElementsAreArray(
5789 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
5790 EXPECT_THAT(a, Not(UnorderedElementsAreArray(
5791 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
5792}
5793
5794TEST(UnorderedElementsAreArrayTest,
5795 TakesInitializerListOfDifferentTypedMatchers) {
5796 const int a[5] = {2, 1, 4, 5, 3};
5797 // The compiler cannot infer the type of the initializer list if its
5798 // elements have different types. We must explicitly specify the
5799 // unified element type in this case.
5800 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
5801 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
5802 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
5803 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
5804}
5805
1e59de90
TL
5806
5807TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) {
5808 ContainerHelper helper;
5809 EXPECT_CALL(helper,
5810 Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)})));
5811 helper.Call(MakeUniquePtrs({2, 1}));
5812}
31f18b77
FG
5813
5814class UnorderedElementsAreTest : public testing::Test {
5815 protected:
5816 typedef std::vector<int> IntVec;
5817};
5818
5819TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
5820 Uncopyable objs[2];
5821 objs[0].set_value(-3);
5822 objs[1].set_value(1);
5823 EXPECT_THAT(objs,
5824 UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
5825}
5826
5827TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
5828 const int a[] = {1, 2, 3};
1e59de90 5829 std::vector<int> s(std::begin(a), std::end(a));
31f18b77
FG
5830 do {
5831 StringMatchResultListener listener;
5832 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5833 s, &listener)) << listener.str();
5834 } while (std::next_permutation(s.begin(), s.end()));
5835}
5836
5837TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
5838 const int a[] = {1, 2, 3};
1e59de90 5839 std::vector<int> s(std::begin(a), std::end(a));
31f18b77
FG
5840 std::vector<Matcher<int> > mv;
5841 mv.push_back(1);
5842 mv.push_back(2);
5843 mv.push_back(2);
5844 // The element with value '3' matches nothing: fail fast.
5845 StringMatchResultListener listener;
5846 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
5847 s, &listener)) << listener.str();
5848}
5849
5850TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
5851 // Streamlike 'container' provides only minimal iterator support.
5852 // Its iterators are tagged with input_iterator_tag, and it has no
5853 // size() or empty() methods.
5854 const int a[5] = {2, 1, 4, 5, 3};
1e59de90 5855 Streamlike<int> s(std::begin(a), std::end(a));
31f18b77
FG
5856
5857 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
5858 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
5859}
5860
1e59de90
TL
5861TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) {
5862 ContainerHelper helper;
5863 EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2))));
5864 helper.Call(MakeUniquePtrs({2, 1}));
5865}
5866
31f18b77
FG
5867// One naive implementation of the matcher runs in O(N!) time, which is too
5868// slow for many real-world inputs. This test shows that our matcher can match
5869// 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
5870// iterations and obviously effectively incomputable.
5871// [ RUN ] UnorderedElementsAreTest.Performance
5872// [ OK ] UnorderedElementsAreTest.Performance (4 ms)
5873TEST_F(UnorderedElementsAreTest, Performance) {
5874 std::vector<int> s;
5875 std::vector<Matcher<int> > mv;
5876 for (int i = 0; i < 100; ++i) {
5877 s.push_back(i);
5878 mv.push_back(_);
5879 }
5880 mv[50] = Eq(0);
5881 StringMatchResultListener listener;
5882 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
5883 s, &listener)) << listener.str();
5884}
5885
5886// Another variant of 'Performance' with similar expectations.
5887// [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
5888// [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
5889TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
5890 std::vector<int> s;
5891 std::vector<Matcher<int> > mv;
5892 for (int i = 0; i < 100; ++i) {
5893 s.push_back(i);
5894 if (i & 1) {
5895 mv.push_back(_);
5896 } else {
5897 mv.push_back(i);
5898 }
5899 }
5900 StringMatchResultListener listener;
5901 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
5902 s, &listener)) << listener.str();
5903}
5904
5905TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
5906 std::vector<int> v;
5907 v.push_back(4);
5908 StringMatchResultListener listener;
5909 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5910 v, &listener)) << listener.str();
5911 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
5912}
5913
5914TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
5915 std::vector<int> v;
5916 StringMatchResultListener listener;
5917 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5918 v, &listener)) << listener.str();
5919 EXPECT_THAT(listener.str(), Eq(""));
5920}
5921
5922TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
5923 std::vector<int> v;
5924 v.push_back(1);
5925 v.push_back(1);
5926 StringMatchResultListener listener;
5927 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
5928 v, &listener)) << listener.str();
5929 EXPECT_THAT(
5930 listener.str(),
5931 Eq("where the following matchers don't match any elements:\n"
5932 "matcher #1: is equal to 2"));
5933}
5934
5935TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
5936 std::vector<int> v;
5937 v.push_back(1);
5938 v.push_back(2);
5939 StringMatchResultListener listener;
5940 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
5941 v, &listener)) << listener.str();
5942 EXPECT_THAT(
5943 listener.str(),
5944 Eq("where the following elements don't match any matchers:\n"
5945 "element #1: 2"));
5946}
5947
5948TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
5949 std::vector<int> v;
5950 v.push_back(2);
5951 v.push_back(3);
5952 StringMatchResultListener listener;
5953 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
5954 v, &listener)) << listener.str();
5955 EXPECT_THAT(
5956 listener.str(),
5957 Eq("where"
5958 " the following matchers don't match any elements:\n"
5959 "matcher #0: is equal to 1\n"
5960 "and"
5961 " where"
5962 " the following elements don't match any matchers:\n"
5963 "element #1: 3"));
5964}
5965
5966// Test helper for formatting element, matcher index pairs in expectations.
1e59de90 5967static std::string EMString(int element, int matcher) {
31f18b77
FG
5968 stringstream ss;
5969 ss << "(element #" << element << ", matcher #" << matcher << ")";
5970 return ss.str();
5971}
5972
5973TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
5974 // A situation where all elements and matchers have a match
5975 // associated with them, but the max matching is not perfect.
1e59de90 5976 std::vector<std::string> v;
31f18b77
FG
5977 v.push_back("a");
5978 v.push_back("b");
5979 v.push_back("c");
5980 StringMatchResultListener listener;
5981 EXPECT_FALSE(ExplainMatchResult(
5982 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
5983 << listener.str();
5984
1e59de90 5985 std::string prefix =
31f18b77
FG
5986 "where no permutation of the elements can satisfy all matchers, "
5987 "and the closest match is 2 of 3 matchers with the "
5988 "pairings:\n";
5989
5990 // We have to be a bit loose here, because there are 4 valid max matches.
5991 EXPECT_THAT(
5992 listener.str(),
5993 AnyOf(prefix + "{\n " + EMString(0, 0) +
5994 ",\n " + EMString(1, 2) + "\n}",
5995 prefix + "{\n " + EMString(0, 1) +
5996 ",\n " + EMString(1, 2) + "\n}",
5997 prefix + "{\n " + EMString(0, 0) +
5998 ",\n " + EMString(2, 2) + "\n}",
5999 prefix + "{\n " + EMString(0, 1) +
6000 ",\n " + EMString(2, 2) + "\n}"));
6001}
6002
6003TEST_F(UnorderedElementsAreTest, Describe) {
6004 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
6005 Eq("is empty"));
6006 EXPECT_THAT(
6007 Describe<IntVec>(UnorderedElementsAre(345)),
6008 Eq("has 1 element and that element is equal to 345"));
6009 EXPECT_THAT(
6010 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
6011 Eq("has 3 elements and there exists some permutation "
6012 "of elements such that:\n"
6013 " - element #0 is equal to 111, and\n"
6014 " - element #1 is equal to 222, and\n"
6015 " - element #2 is equal to 333"));
6016}
6017
6018TEST_F(UnorderedElementsAreTest, DescribeNegation) {
6019 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
6020 Eq("isn't empty"));
6021 EXPECT_THAT(
6022 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
6023 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
6024 EXPECT_THAT(
6025 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
6026 Eq("doesn't have 3 elements, or there exists no permutation "
6027 "of elements such that:\n"
6028 " - element #0 is equal to 123, and\n"
6029 " - element #1 is equal to 234, and\n"
6030 " - element #2 is equal to 345"));
6031}
6032
6033namespace {
6034
6035// Used as a check on the more complex max flow method used in the
6036// real testing::internal::FindMaxBipartiteMatching. This method is
6037// compatible but runs in worst-case factorial time, so we only
6038// use it in testing for small problem sizes.
6039template <typename Graph>
6040class BacktrackingMaxBPMState {
6041 public:
6042 // Does not take ownership of 'g'.
6043 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
6044
6045 ElementMatcherPairs Compute() {
6046 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
6047 return best_so_far_;
6048 }
6049 lhs_used_.assign(graph_->LhsSize(), kUnused);
6050 rhs_used_.assign(graph_->RhsSize(), kUnused);
6051 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
6052 matches_.clear();
6053 RecurseInto(irhs);
6054 if (best_so_far_.size() == graph_->RhsSize())
6055 break;
6056 }
6057 return best_so_far_;
6058 }
6059
6060 private:
6061 static const size_t kUnused = static_cast<size_t>(-1);
6062
6063 void PushMatch(size_t lhs, size_t rhs) {
6064 matches_.push_back(ElementMatcherPair(lhs, rhs));
6065 lhs_used_[lhs] = rhs;
6066 rhs_used_[rhs] = lhs;
6067 if (matches_.size() > best_so_far_.size()) {
6068 best_so_far_ = matches_;
6069 }
6070 }
6071
6072 void PopMatch() {
6073 const ElementMatcherPair& back = matches_.back();
6074 lhs_used_[back.first] = kUnused;
6075 rhs_used_[back.second] = kUnused;
6076 matches_.pop_back();
6077 }
6078
6079 bool RecurseInto(size_t irhs) {
6080 if (rhs_used_[irhs] != kUnused) {
6081 return true;
6082 }
6083 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
6084 if (lhs_used_[ilhs] != kUnused) {
6085 continue;
6086 }
6087 if (!graph_->HasEdge(ilhs, irhs)) {
6088 continue;
6089 }
6090 PushMatch(ilhs, irhs);
6091 if (best_so_far_.size() == graph_->RhsSize()) {
6092 return false;
6093 }
6094 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
6095 if (!RecurseInto(mi)) return false;
6096 }
6097 PopMatch();
6098 }
6099 return true;
6100 }
6101
6102 const Graph* graph_; // not owned
6103 std::vector<size_t> lhs_used_;
6104 std::vector<size_t> rhs_used_;
6105 ElementMatcherPairs matches_;
6106 ElementMatcherPairs best_so_far_;
6107};
6108
6109template <typename Graph>
6110const size_t BacktrackingMaxBPMState<Graph>::kUnused;
6111
6112} // namespace
6113
6114// Implement a simple backtracking algorithm to determine if it is possible
6115// to find one element per matcher, without reusing elements.
6116template <typename Graph>
6117ElementMatcherPairs
6118FindBacktrackingMaxBPM(const Graph& g) {
6119 return BacktrackingMaxBPMState<Graph>(&g).Compute();
6120}
6121
6122class BacktrackingBPMTest : public ::testing::Test { };
6123
6124// Tests the MaxBipartiteMatching algorithm with square matrices.
6125// The single int param is the # of nodes on each of the left and right sides.
1e59de90 6126class BipartiteTest : public ::testing::TestWithParam<size_t> {};
31f18b77
FG
6127
6128// Verify all match graphs up to some moderate number of edges.
6129TEST_P(BipartiteTest, Exhaustive) {
1e59de90 6130 size_t nodes = GetParam();
31f18b77
FG
6131 MatchMatrix graph(nodes, nodes);
6132 do {
6133 ElementMatcherPairs matches =
6134 internal::FindMaxBipartiteMatching(graph);
6135 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
6136 << "graph: " << graph.DebugString();
6137 // Check that all elements of matches are in the graph.
6138 // Check that elements of first and second are unique.
6139 std::vector<bool> seen_element(graph.LhsSize());
6140 std::vector<bool> seen_matcher(graph.RhsSize());
6141 SCOPED_TRACE(PrintToString(matches));
6142 for (size_t i = 0; i < matches.size(); ++i) {
6143 size_t ilhs = matches[i].first;
6144 size_t irhs = matches[i].second;
6145 EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
6146 EXPECT_FALSE(seen_element[ilhs]);
6147 EXPECT_FALSE(seen_matcher[irhs]);
6148 seen_element[ilhs] = true;
6149 seen_matcher[irhs] = true;
6150 }
6151 } while (graph.NextGraph());
6152}
6153
1e59de90
TL
6154INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteTest,
6155 ::testing::Range(size_t{0}, size_t{5}));
31f18b77
FG
6156
6157// Parameterized by a pair interpreted as (LhsSize, RhsSize).
6158class BipartiteNonSquareTest
6159 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
6160};
6161
6162TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
6163 // .......
6164 // 0:-----\ :
6165 // 1:---\ | :
6166 // 2:---\ | :
6167 // 3:-\ | | :
6168 // :.......:
6169 // 0 1 2
6170 MatchMatrix g(4, 3);
1e59de90
TL
6171 constexpr std::array<std::array<size_t, 2>, 4> kEdges = {
6172 {{{0, 2}}, {{1, 1}}, {{2, 1}}, {{3, 0}}}};
6173 for (size_t i = 0; i < kEdges.size(); ++i) {
31f18b77
FG
6174 g.SetEdge(kEdges[i][0], kEdges[i][1], true);
6175 }
6176 EXPECT_THAT(FindBacktrackingMaxBPM(g),
6177 ElementsAre(Pair(3, 0),
6178 Pair(AnyOf(1, 2), 1),
6179 Pair(0, 2))) << g.DebugString();
6180}
6181
6182// Verify a few nonsquare matrices.
6183TEST_P(BipartiteNonSquareTest, Exhaustive) {
6184 size_t nlhs = GetParam().first;
6185 size_t nrhs = GetParam().second;
6186 MatchMatrix graph(nlhs, nrhs);
6187 do {
6188 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
6189 internal::FindMaxBipartiteMatching(graph).size())
6190 << "graph: " << graph.DebugString()
6191 << "\nbacktracking: "
6192 << PrintToString(FindBacktrackingMaxBPM(graph))
6193 << "\nmax flow: "
6194 << PrintToString(internal::FindMaxBipartiteMatching(graph));
6195 } while (graph.NextGraph());
6196}
6197
1e59de90 6198INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteNonSquareTest,
31f18b77
FG
6199 testing::Values(
6200 std::make_pair(1, 2),
6201 std::make_pair(2, 1),
6202 std::make_pair(3, 2),
6203 std::make_pair(2, 3),
6204 std::make_pair(4, 1),
6205 std::make_pair(1, 4),
6206 std::make_pair(4, 3),
6207 std::make_pair(3, 4)));
6208
6209class BipartiteRandomTest
6210 : public ::testing::TestWithParam<std::pair<int, int> > {
6211};
6212
6213// Verifies a large sample of larger graphs.
6214TEST_P(BipartiteRandomTest, LargerNets) {
6215 int nodes = GetParam().first;
6216 int iters = GetParam().second;
1e59de90 6217 MatchMatrix graph(static_cast<size_t>(nodes), static_cast<size_t>(nodes));
31f18b77 6218
1e59de90 6219 auto seed = static_cast<uint32_t>(GTEST_FLAG(random_seed));
31f18b77 6220 if (seed == 0) {
1e59de90 6221 seed = static_cast<uint32_t>(time(nullptr));
31f18b77
FG
6222 }
6223
6224 for (; iters > 0; --iters, ++seed) {
1e59de90 6225 srand(static_cast<unsigned int>(seed));
31f18b77
FG
6226 graph.Randomize();
6227 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
6228 internal::FindMaxBipartiteMatching(graph).size())
6229 << " graph: " << graph.DebugString()
6230 << "\nTo reproduce the failure, rerun the test with the flag"
6231 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
6232 }
6233}
6234
6235// Test argument is a std::pair<int, int> representing (nodes, iters).
1e59de90 6236INSTANTIATE_TEST_SUITE_P(Samples, BipartiteRandomTest,
31f18b77
FG
6237 testing::Values(
6238 std::make_pair(5, 10000),
6239 std::make_pair(6, 5000),
6240 std::make_pair(7, 2000),
6241 std::make_pair(8, 500),
6242 std::make_pair(9, 100)));
6243
6244// Tests IsReadableTypeName().
6245
6246TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
6247 EXPECT_TRUE(IsReadableTypeName("int"));
6248 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
6249 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
6250 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
6251}
6252
6253TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
6254 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
6255 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
6256 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
6257}
6258
6259TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
6260 EXPECT_FALSE(
6261 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
6262 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
6263}
6264
6265TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
6266 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
6267}
6268
31f18b77
FG
6269// Tests FormatMatcherDescription().
6270
6271TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
6272 EXPECT_EQ("is even",
6273 FormatMatcherDescription(false, "IsEven", Strings()));
6274 EXPECT_EQ("not (is even)",
6275 FormatMatcherDescription(true, "IsEven", Strings()));
6276
6277 const char* params[] = {"5"};
6278 EXPECT_EQ("equals 5",
6279 FormatMatcherDescription(false, "Equals",
6280 Strings(params, params + 1)));
6281
6282 const char* params2[] = {"5", "8"};
6283 EXPECT_EQ("is in range (5, 8)",
6284 FormatMatcherDescription(false, "IsInRange",
6285 Strings(params2, params2 + 2)));
6286}
6287
6288// Tests PolymorphicMatcher::mutable_impl().
6289TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
6290 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
6291 DivisibleByImpl& impl = m.mutable_impl();
6292 EXPECT_EQ(42, impl.divider());
6293
6294 impl.set_divider(0);
6295 EXPECT_EQ(0, m.mutable_impl().divider());
6296}
6297
6298// Tests PolymorphicMatcher::impl().
6299TEST(PolymorphicMatcherTest, CanAccessImpl) {
6300 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
6301 const DivisibleByImpl& impl = m.impl();
6302 EXPECT_EQ(42, impl.divider());
6303}
6304
6305TEST(MatcherTupleTest, ExplainsMatchFailure) {
6306 stringstream ss1;
1e59de90
TL
6307 ExplainMatchFailureTupleTo(
6308 std::make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
6309 std::make_tuple('a', 10), &ss1);
31f18b77
FG
6310 EXPECT_EQ("", ss1.str()); // Successful match.
6311
6312 stringstream ss2;
1e59de90
TL
6313 ExplainMatchFailureTupleTo(
6314 std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
6315 std::make_tuple(2, 'b'), &ss2);
31f18b77
FG
6316 EXPECT_EQ(" Expected arg #0: is > 5\n"
6317 " Actual: 2, which is 3 less than 5\n"
6318 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
6319 " Actual: 'b' (98, 0x62)\n",
6320 ss2.str()); // Failed match where both arguments need explanation.
6321
6322 stringstream ss3;
1e59de90
TL
6323 ExplainMatchFailureTupleTo(
6324 std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
6325 std::make_tuple(2, 'a'), &ss3);
31f18b77
FG
6326 EXPECT_EQ(" Expected arg #0: is > 5\n"
6327 " Actual: 2, which is 3 less than 5\n",
6328 ss3.str()); // Failed match where only one argument needs
6329 // explanation.
6330}
6331
6332// Tests Each().
6333
6334TEST(EachTest, ExplainsMatchResultCorrectly) {
6335 set<int> a; // empty
6336
6337 Matcher<set<int> > m = Each(2);
6338 EXPECT_EQ("", Explain(m, a));
6339
6340 Matcher<const int(&)[1]> n = Each(1); // NOLINT
6341
6342 const int b[1] = {1};
6343 EXPECT_EQ("", Explain(n, b));
6344
6345 n = Each(3);
6346 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
6347
6348 a.insert(1);
6349 a.insert(2);
6350 a.insert(3);
6351 m = Each(GreaterThan(0));
6352 EXPECT_EQ("", Explain(m, a));
6353
6354 m = Each(GreaterThan(10));
6355 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
6356 Explain(m, a));
6357}
6358
6359TEST(EachTest, DescribesItselfCorrectly) {
6360 Matcher<vector<int> > m = Each(1);
6361 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
6362
6363 Matcher<vector<int> > m2 = Not(m);
6364 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
6365}
6366
6367TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
6368 vector<int> some_vector;
6369 EXPECT_THAT(some_vector, Each(1));
6370 some_vector.push_back(3);
6371 EXPECT_THAT(some_vector, Not(Each(1)));
6372 EXPECT_THAT(some_vector, Each(3));
6373 some_vector.push_back(1);
6374 some_vector.push_back(2);
6375 EXPECT_THAT(some_vector, Not(Each(3)));
6376 EXPECT_THAT(some_vector, Each(Lt(3.5)));
6377
1e59de90 6378 vector<std::string> another_vector;
31f18b77 6379 another_vector.push_back("fee");
1e59de90 6380 EXPECT_THAT(another_vector, Each(std::string("fee")));
31f18b77
FG
6381 another_vector.push_back("fie");
6382 another_vector.push_back("foe");
6383 another_vector.push_back("fum");
1e59de90 6384 EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));
31f18b77
FG
6385}
6386
6387TEST(EachTest, MatchesMapWhenAllElementsMatch) {
6388 map<const char*, int> my_map;
6389 const char* bar = "a string";
6390 my_map[bar] = 2;
6391 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
6392
1e59de90
TL
6393 map<std::string, int> another_map;
6394 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
31f18b77 6395 another_map["fee"] = 1;
1e59de90 6396 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
31f18b77
FG
6397 another_map["fie"] = 2;
6398 another_map["foe"] = 3;
6399 another_map["fum"] = 4;
1e59de90
TL
6400 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));
6401 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));
31f18b77
FG
6402 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
6403}
6404
6405TEST(EachTest, AcceptsMatcher) {
6406 const int a[] = {1, 2, 3};
6407 EXPECT_THAT(a, Each(Gt(0)));
6408 EXPECT_THAT(a, Not(Each(Gt(1))));
6409}
6410
6411TEST(EachTest, WorksForNativeArrayAsTuple) {
6412 const int a[] = {1, 2};
6413 const int* const pointer = a;
1e59de90
TL
6414 EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0)));
6415 EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1))));
6416}
6417
6418TEST(EachTest, WorksWithMoveOnly) {
6419 ContainerHelper helper;
6420 EXPECT_CALL(helper, Call(Each(Pointee(Gt(0)))));
6421 helper.Call(MakeUniquePtrs({1, 2}));
31f18b77
FG
6422}
6423
6424// For testing Pointwise().
6425class IsHalfOfMatcher {
6426 public:
6427 template <typename T1, typename T2>
1e59de90 6428 bool MatchAndExplain(const std::tuple<T1, T2>& a_pair,
31f18b77 6429 MatchResultListener* listener) const {
1e59de90
TL
6430 if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) {
6431 *listener << "where the second is " << std::get<1>(a_pair);
31f18b77
FG
6432 return true;
6433 } else {
1e59de90 6434 *listener << "where the second/2 is " << std::get<1>(a_pair) / 2;
31f18b77
FG
6435 return false;
6436 }
6437 }
6438
6439 void DescribeTo(ostream* os) const {
6440 *os << "are a pair where the first is half of the second";
6441 }
6442
6443 void DescribeNegationTo(ostream* os) const {
6444 *os << "are a pair where the first isn't half of the second";
6445 }
6446};
6447
6448PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
6449 return MakePolymorphicMatcher(IsHalfOfMatcher());
6450}
6451
6452TEST(PointwiseTest, DescribesSelf) {
6453 vector<int> rhs;
6454 rhs.push_back(1);
6455 rhs.push_back(2);
6456 rhs.push_back(3);
6457 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
6458 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
6459 "in { 1, 2, 3 } are a pair where the first is half of the second",
6460 Describe(m));
6461 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
6462 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
6463 "where the first isn't half of the second",
6464 DescribeNegation(m));
6465}
6466
6467TEST(PointwiseTest, MakesCopyOfRhs) {
6468 list<signed char> rhs;
6469 rhs.push_back(2);
6470 rhs.push_back(4);
6471
6472 int lhs[] = {1, 2};
6473 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
6474 EXPECT_THAT(lhs, m);
6475
6476 // Changing rhs now shouldn't affect m, which made a copy of rhs.
6477 rhs.push_back(6);
6478 EXPECT_THAT(lhs, m);
6479}
6480
6481TEST(PointwiseTest, WorksForLhsNativeArray) {
6482 const int lhs[] = {1, 2, 3};
6483 vector<int> rhs;
6484 rhs.push_back(2);
6485 rhs.push_back(4);
6486 rhs.push_back(6);
6487 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
6488 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
6489}
6490
6491TEST(PointwiseTest, WorksForRhsNativeArray) {
6492 const int rhs[] = {1, 2, 3};
6493 vector<int> lhs;
6494 lhs.push_back(2);
6495 lhs.push_back(4);
6496 lhs.push_back(6);
6497 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
6498 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
6499}
6500
1e59de90
TL
6501// Test is effective only with sanitizers.
6502TEST(PointwiseTest, WorksForVectorOfBool) {
6503 vector<bool> rhs(3, false);
6504 rhs[1] = true;
6505 vector<bool> lhs = rhs;
6506 EXPECT_THAT(lhs, Pointwise(Eq(), rhs));
6507 rhs[0] = true;
6508 EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs)));
6509}
6510
31f18b77
FG
6511
6512TEST(PointwiseTest, WorksForRhsInitializerList) {
6513 const vector<int> lhs{2, 4, 6};
6514 EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
6515 EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
6516}
6517
31f18b77
FG
6518
6519TEST(PointwiseTest, RejectsWrongSize) {
6520 const double lhs[2] = {1, 2};
6521 const int rhs[1] = {0};
6522 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
6523 EXPECT_EQ("which contains 2 values",
6524 Explain(Pointwise(Gt(), rhs), lhs));
6525
6526 const int rhs2[3] = {0, 1, 2};
6527 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
6528}
6529
6530TEST(PointwiseTest, RejectsWrongContent) {
6531 const double lhs[3] = {1, 2, 3};
6532 const int rhs[3] = {2, 6, 4};
6533 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
6534 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
6535 "where the second/2 is 3",
6536 Explain(Pointwise(IsHalfOf(), rhs), lhs));
6537}
6538
6539TEST(PointwiseTest, AcceptsCorrectContent) {
6540 const double lhs[3] = {1, 2, 3};
6541 const int rhs[3] = {2, 4, 6};
6542 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
6543 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
6544}
6545
6546TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
6547 const double lhs[3] = {1, 2, 3};
6548 const int rhs[3] = {2, 4, 6};
1e59de90 6549 const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
31f18b77
FG
6550 EXPECT_THAT(lhs, Pointwise(m1, rhs));
6551 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
6552
1e59de90
TL
6553 // This type works as a std::tuple<const double&, const int&> can be
6554 // implicitly cast to std::tuple<double, int>.
6555 const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
31f18b77
FG
6556 EXPECT_THAT(lhs, Pointwise(m2, rhs));
6557 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
6558}
6559
1e59de90
TL
6560MATCHER(PointeeEquals, "Points to an equal value") {
6561 return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)),
6562 ::testing::get<0>(arg), result_listener);
6563}
6564
6565TEST(PointwiseTest, WorksWithMoveOnly) {
6566 ContainerHelper helper;
6567 EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2})));
6568 helper.Call(MakeUniquePtrs({1, 2}));
6569}
6570
31f18b77
FG
6571TEST(UnorderedPointwiseTest, DescribesSelf) {
6572 vector<int> rhs;
6573 rhs.push_back(1);
6574 rhs.push_back(2);
6575 rhs.push_back(3);
6576 const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
6577 EXPECT_EQ(
6578 "has 3 elements and there exists some permutation of elements such "
6579 "that:\n"
6580 " - element #0 and 1 are a pair where the first is half of the second, "
6581 "and\n"
6582 " - element #1 and 2 are a pair where the first is half of the second, "
6583 "and\n"
6584 " - element #2 and 3 are a pair where the first is half of the second",
6585 Describe(m));
6586 EXPECT_EQ(
6587 "doesn't have 3 elements, or there exists no permutation of elements "
6588 "such that:\n"
6589 " - element #0 and 1 are a pair where the first is half of the second, "
6590 "and\n"
6591 " - element #1 and 2 are a pair where the first is half of the second, "
6592 "and\n"
6593 " - element #2 and 3 are a pair where the first is half of the second",
6594 DescribeNegation(m));
6595}
6596
6597TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
6598 list<signed char> rhs;
6599 rhs.push_back(2);
6600 rhs.push_back(4);
6601
6602 int lhs[] = {2, 1};
6603 const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
6604 EXPECT_THAT(lhs, m);
6605
6606 // Changing rhs now shouldn't affect m, which made a copy of rhs.
6607 rhs.push_back(6);
6608 EXPECT_THAT(lhs, m);
6609}
6610
6611TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
6612 const int lhs[] = {1, 2, 3};
6613 vector<int> rhs;
6614 rhs.push_back(4);
6615 rhs.push_back(6);
6616 rhs.push_back(2);
6617 EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
6618 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
6619}
6620
6621TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
6622 const int rhs[] = {1, 2, 3};
6623 vector<int> lhs;
6624 lhs.push_back(4);
6625 lhs.push_back(2);
6626 lhs.push_back(6);
6627 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
6628 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
6629}
6630
31f18b77
FG
6631
6632TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
6633 const vector<int> lhs{2, 4, 6};
6634 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
6635 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
6636}
6637
31f18b77
FG
6638
6639TEST(UnorderedPointwiseTest, RejectsWrongSize) {
6640 const double lhs[2] = {1, 2};
6641 const int rhs[1] = {0};
6642 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
6643 EXPECT_EQ("which has 2 elements",
6644 Explain(UnorderedPointwise(Gt(), rhs), lhs));
6645
6646 const int rhs2[3] = {0, 1, 2};
6647 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
6648}
6649
6650TEST(UnorderedPointwiseTest, RejectsWrongContent) {
6651 const double lhs[3] = {1, 2, 3};
6652 const int rhs[3] = {2, 6, 6};
6653 EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
6654 EXPECT_EQ("where the following elements don't match any matchers:\n"
6655 "element #1: 2",
6656 Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
6657}
6658
6659TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
6660 const double lhs[3] = {1, 2, 3};
6661 const int rhs[3] = {2, 4, 6};
6662 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
6663}
6664
6665TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
6666 const double lhs[3] = {1, 2, 3};
6667 const int rhs[3] = {6, 4, 2};
6668 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
6669}
6670
6671TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
6672 const double lhs[3] = {1, 2, 3};
6673 const int rhs[3] = {4, 6, 2};
1e59de90 6674 const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();
31f18b77
FG
6675 EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
6676
1e59de90
TL
6677 // This type works as a std::tuple<const double&, const int&> can be
6678 // implicitly cast to std::tuple<double, int>.
6679 const Matcher<std::tuple<double, int>> m2 = IsHalfOf();
31f18b77
FG
6680 EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
6681}
6682
1e59de90
TL
6683TEST(UnorderedPointwiseTest, WorksWithMoveOnly) {
6684 ContainerHelper helper;
6685 EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(),
6686 std::vector<int>{1, 2})));
6687 helper.Call(MakeUniquePtrs({2, 1}));
6688}
6689
6690// Sample optional type implementation with minimal requirements for use with
6691// Optional matcher.
6692template <typename T>
6693class SampleOptional {
6694 public:
6695 using value_type = T;
6696 explicit SampleOptional(T value)
6697 : value_(std::move(value)), has_value_(true) {}
6698 SampleOptional() : value_(), has_value_(false) {}
6699 operator bool() const { return has_value_; }
6700 const T& operator*() const { return value_; }
6701
6702 private:
6703 T value_;
6704 bool has_value_;
6705};
6706
6707TEST(OptionalTest, DescribesSelf) {
6708 const Matcher<SampleOptional<int>> m = Optional(Eq(1));
6709 EXPECT_EQ("value is equal to 1", Describe(m));
6710}
6711
6712TEST(OptionalTest, ExplainsSelf) {
6713 const Matcher<SampleOptional<int>> m = Optional(Eq(1));
6714 EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptional<int>(1)));
6715 EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptional<int>(2)));
6716}
6717
6718TEST(OptionalTest, MatchesNonEmptyOptional) {
6719 const Matcher<SampleOptional<int>> m1 = Optional(1);
6720 const Matcher<SampleOptional<int>> m2 = Optional(Eq(2));
6721 const Matcher<SampleOptional<int>> m3 = Optional(Lt(3));
6722 SampleOptional<int> opt(1);
6723 EXPECT_TRUE(m1.Matches(opt));
6724 EXPECT_FALSE(m2.Matches(opt));
6725 EXPECT_TRUE(m3.Matches(opt));
6726}
6727
6728TEST(OptionalTest, DoesNotMatchNullopt) {
6729 const Matcher<SampleOptional<int>> m = Optional(1);
6730 SampleOptional<int> empty;
6731 EXPECT_FALSE(m.Matches(empty));
6732}
6733
6734TEST(OptionalTest, WorksWithMoveOnly) {
6735 Matcher<SampleOptional<std::unique_ptr<int>>> m = Optional(Eq(nullptr));
6736 EXPECT_TRUE(m.Matches(SampleOptional<std::unique_ptr<int>>(nullptr)));
6737}
6738
6739class SampleVariantIntString {
6740 public:
6741 SampleVariantIntString(int i) : i_(i), has_int_(true) {}
6742 SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {}
6743
6744 template <typename T>
6745 friend bool holds_alternative(const SampleVariantIntString& value) {
6746 return value.has_int_ == std::is_same<T, int>::value;
6747 }
6748
6749 template <typename T>
6750 friend const T& get(const SampleVariantIntString& value) {
6751 return value.get_impl(static_cast<T*>(nullptr));
6752 }
6753
6754 private:
6755 const int& get_impl(int*) const { return i_; }
6756 const std::string& get_impl(std::string*) const { return s_; }
6757
6758 int i_;
6759 std::string s_;
6760 bool has_int_;
6761};
6762
6763TEST(VariantTest, DescribesSelf) {
6764 const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6765 EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type "
6766 "'.*' and the value is equal to 1"));
6767}
6768
6769TEST(VariantTest, ExplainsSelf) {
6770 const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6771 EXPECT_THAT(Explain(m, SampleVariantIntString(1)),
6772 ContainsRegex("whose value 1"));
6773 EXPECT_THAT(Explain(m, SampleVariantIntString("A")),
6774 HasSubstr("whose value is not of type '"));
6775 EXPECT_THAT(Explain(m, SampleVariantIntString(2)),
6776 "whose value 2 doesn't match");
6777}
6778
6779TEST(VariantTest, FullMatch) {
6780 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6781 EXPECT_TRUE(m.Matches(SampleVariantIntString(1)));
6782
6783 m = VariantWith<std::string>(Eq("1"));
6784 EXPECT_TRUE(m.Matches(SampleVariantIntString("1")));
6785}
6786
6787TEST(VariantTest, TypeDoesNotMatch) {
6788 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6789 EXPECT_FALSE(m.Matches(SampleVariantIntString("1")));
6790
6791 m = VariantWith<std::string>(Eq("1"));
6792 EXPECT_FALSE(m.Matches(SampleVariantIntString(1)));
6793}
6794
6795TEST(VariantTest, InnerDoesNotMatch) {
6796 Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));
6797 EXPECT_FALSE(m.Matches(SampleVariantIntString(2)));
6798
6799 m = VariantWith<std::string>(Eq("1"));
6800 EXPECT_FALSE(m.Matches(SampleVariantIntString("2")));
6801}
6802
6803class SampleAnyType {
6804 public:
6805 explicit SampleAnyType(int i) : index_(0), i_(i) {}
6806 explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {}
6807
6808 template <typename T>
6809 friend const T* any_cast(const SampleAnyType* any) {
6810 return any->get_impl(static_cast<T*>(nullptr));
6811 }
6812
6813 private:
6814 int index_;
6815 int i_;
6816 std::string s_;
6817
6818 const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; }
6819 const std::string* get_impl(std::string*) const {
6820 return index_ == 1 ? &s_ : nullptr;
6821 }
6822};
6823
6824TEST(AnyWithTest, FullMatch) {
6825 Matcher<SampleAnyType> m = AnyWith<int>(Eq(1));
6826 EXPECT_TRUE(m.Matches(SampleAnyType(1)));
6827}
6828
6829TEST(AnyWithTest, TestBadCastType) {
6830 Matcher<SampleAnyType> m = AnyWith<std::string>(Eq("fail"));
6831 EXPECT_FALSE(m.Matches(SampleAnyType(1)));
6832}
6833
6834TEST(AnyWithTest, TestUseInContainers) {
6835 std::vector<SampleAnyType> a;
6836 a.emplace_back(1);
6837 a.emplace_back(2);
6838 a.emplace_back(3);
6839 EXPECT_THAT(
6840 a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)}));
6841
6842 std::vector<SampleAnyType> b;
6843 b.emplace_back("hello");
6844 b.emplace_back("merhaba");
6845 b.emplace_back("salut");
6846 EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>("hello"),
6847 AnyWith<std::string>("merhaba"),
6848 AnyWith<std::string>("salut")}));
6849}
6850TEST(AnyWithTest, TestCompare) {
6851 EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0)));
6852}
6853
6854TEST(AnyWithTest, DescribesSelf) {
6855 const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
6856 EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type "
6857 "'.*' and the value is equal to 1"));
6858}
6859
6860TEST(AnyWithTest, ExplainsSelf) {
6861 const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));
6862
6863 EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1"));
6864 EXPECT_THAT(Explain(m, SampleAnyType("A")),
6865 HasSubstr("whose value is not of type '"));
6866 EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match");
6867}
6868
6869TEST(PointeeTest, WorksOnMoveOnlyType) {
6870 std::unique_ptr<int> p(new int(3));
6871 EXPECT_THAT(p, Pointee(Eq(3)));
6872 EXPECT_THAT(p, Not(Pointee(Eq(2))));
6873}
6874
6875TEST(NotTest, WorksOnMoveOnlyType) {
6876 std::unique_ptr<int> p(new int(3));
6877 EXPECT_THAT(p, Pointee(Eq(3)));
6878 EXPECT_THAT(p, Not(Pointee(Eq(2))));
6879}
6880
6881// Tests Args<k0, ..., kn>(m).
6882
6883TEST(ArgsTest, AcceptsZeroTemplateArg) {
6884 const std::tuple<int, bool> t(5, true);
6885 EXPECT_THAT(t, Args<>(Eq(std::tuple<>())));
6886 EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>()))));
6887}
6888
6889TEST(ArgsTest, AcceptsOneTemplateArg) {
6890 const std::tuple<int, bool> t(5, true);
6891 EXPECT_THAT(t, Args<0>(Eq(std::make_tuple(5))));
6892 EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(true))));
6893 EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(false)))));
6894}
6895
6896TEST(ArgsTest, AcceptsTwoTemplateArgs) {
6897 const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
6898
6899 EXPECT_THAT(t, (Args<0, 1>(Lt())));
6900 EXPECT_THAT(t, (Args<1, 2>(Lt())));
6901 EXPECT_THAT(t, Not(Args<0, 2>(Gt())));
6902}
6903
6904TEST(ArgsTest, AcceptsRepeatedTemplateArgs) {
6905 const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
6906 EXPECT_THAT(t, (Args<0, 0>(Eq())));
6907 EXPECT_THAT(t, Not(Args<1, 1>(Ne())));
6908}
6909
6910TEST(ArgsTest, AcceptsDecreasingTemplateArgs) {
6911 const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT
6912 EXPECT_THAT(t, (Args<2, 0>(Gt())));
6913 EXPECT_THAT(t, Not(Args<2, 1>(Lt())));
6914}
6915
6916MATCHER(SumIsZero, "") {
6917 return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0;
6918}
6919
6920TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {
6921 EXPECT_THAT(std::make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero())));
6922 EXPECT_THAT(std::make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero())));
6923}
6924
6925TEST(ArgsTest, CanBeNested) {
6926 const std::tuple<short, int, long, int> t(4, 5, 6L, 6); // NOLINT
6927 EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));
6928 EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));
6929}
6930
6931TEST(ArgsTest, CanMatchTupleByValue) {
6932 typedef std::tuple<char, int, int> Tuple3;
6933 const Matcher<Tuple3> m = Args<1, 2>(Lt());
6934 EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2)));
6935 EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2)));
6936}
6937
6938TEST(ArgsTest, CanMatchTupleByReference) {
6939 typedef std::tuple<char, char, int> Tuple3;
6940 const Matcher<const Tuple3&> m = Args<0, 1>(Lt());
6941 EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2)));
6942 EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2)));
6943}
6944
6945// Validates that arg is printed as str.
6946MATCHER_P(PrintsAs, str, "") {
6947 return testing::PrintToString(arg) == str;
6948}
6949
6950TEST(ArgsTest, AcceptsTenTemplateArgs) {
6951 EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
6952 (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
6953 PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
6954 EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),
6955 Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(
6956 PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)"))));
6957}
6958
6959TEST(ArgsTest, DescirbesSelfCorrectly) {
6960 const Matcher<std::tuple<int, bool, char> > m = Args<2, 0>(Lt());
6961 EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where "
6962 "the first < the second",
6963 Describe(m));
6964}
6965
6966TEST(ArgsTest, DescirbesNestedArgsCorrectly) {
6967 const Matcher<const std::tuple<int, bool, char, int>&> m =
6968 Args<0, 2, 3>(Args<2, 0>(Lt()));
6969 EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple "
6970 "whose fields (#2, #0) are a pair where the first < the second",
6971 Describe(m));
6972}
6973
6974TEST(ArgsTest, DescribesNegationCorrectly) {
6975 const Matcher<std::tuple<int, char> > m = Args<1, 0>(Gt());
6976 EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair "
6977 "where the first > the second",
6978 DescribeNegation(m));
6979}
6980
6981TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) {
6982 const Matcher<std::tuple<bool, int, int> > m = Args<1, 2>(Eq());
6983 EXPECT_EQ("whose fields (#1, #2) are (42, 42)",
6984 Explain(m, std::make_tuple(false, 42, 42)));
6985 EXPECT_EQ("whose fields (#1, #2) are (42, 43)",
6986 Explain(m, std::make_tuple(false, 42, 43)));
6987}
6988
6989// For testing Args<>'s explanation.
6990class LessThanMatcher : public MatcherInterface<std::tuple<char, int> > {
6991 public:
6992 void DescribeTo(::std::ostream* /*os*/) const override {}
6993
6994 bool MatchAndExplain(std::tuple<char, int> value,
6995 MatchResultListener* listener) const override {
6996 const int diff = std::get<0>(value) - std::get<1>(value);
6997 if (diff > 0) {
6998 *listener << "where the first value is " << diff
6999 << " more than the second";
7000 }
7001 return diff < 0;
7002 }
7003};
7004
7005Matcher<std::tuple<char, int> > LessThan() {
7006 return MakeMatcher(new LessThanMatcher);
7007}
7008
7009TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) {
7010 const Matcher<std::tuple<char, int, int> > m = Args<0, 2>(LessThan());
7011 EXPECT_EQ(
7012 "whose fields (#0, #2) are ('a' (97, 0x61), 42), "
7013 "where the first value is 55 more than the second",
7014 Explain(m, std::make_tuple('a', 42, 42)));
7015 EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)",
7016 Explain(m, std::make_tuple('\0', 42, 43)));
7017}
7018
7019class PredicateFormatterFromMatcherTest : public ::testing::Test {
7020 protected:
7021 enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky };
7022
7023 // A matcher that can return different results when used multiple times on the
7024 // same input. No real matcher should do this; but this lets us test that we
7025 // detect such behavior and fail appropriately.
7026 class MockMatcher : public MatcherInterface<Behavior> {
7027 public:
7028 bool MatchAndExplain(Behavior behavior,
7029 MatchResultListener* listener) const override {
7030 *listener << "[MatchAndExplain]";
7031 switch (behavior) {
7032 case kInitialSuccess:
7033 // The first call to MatchAndExplain should use a "not interested"
7034 // listener; so this is expected to return |true|. There should be no
7035 // subsequent calls.
7036 return !listener->IsInterested();
7037
7038 case kAlwaysFail:
7039 return false;
7040
7041 case kFlaky:
7042 // The first call to MatchAndExplain should use a "not interested"
7043 // listener; so this will return |false|. Subsequent calls should have
7044 // an "interested" listener; so this will return |true|, thus
7045 // simulating a flaky matcher.
7046 return listener->IsInterested();
7047 }
7048
7049 GTEST_LOG_(FATAL) << "This should never be reached";
7050 return false;
7051 }
7052
7053 void DescribeTo(ostream* os) const override { *os << "[DescribeTo]"; }
7054
7055 void DescribeNegationTo(ostream* os) const override {
7056 *os << "[DescribeNegationTo]";
7057 }
7058 };
7059
7060 AssertionResult RunPredicateFormatter(Behavior behavior) {
7061 auto matcher = MakeMatcher(new MockMatcher);
7062 PredicateFormatterFromMatcher<Matcher<Behavior>> predicate_formatter(
7063 matcher);
7064 return predicate_formatter("dummy-name", behavior);
7065 }
7066};
7067
7068TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) {
7069 AssertionResult result = RunPredicateFormatter(kInitialSuccess);
7070 EXPECT_TRUE(result); // Implicit cast to bool.
7071 std::string expect;
7072 EXPECT_EQ(expect, result.message());
7073}
7074
7075TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {
7076 AssertionResult result = RunPredicateFormatter(kAlwaysFail);
7077 EXPECT_FALSE(result); // Implicit cast to bool.
7078 std::string expect =
7079 "Value of: dummy-name\nExpected: [DescribeTo]\n"
7080 " Actual: 1" +
7081 OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
7082 EXPECT_EQ(expect, result.message());
7083}
7084
7085TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {
7086 AssertionResult result = RunPredicateFormatter(kFlaky);
7087 EXPECT_FALSE(result); // Implicit cast to bool.
7088 std::string expect =
7089 "Value of: dummy-name\nExpected: [DescribeTo]\n"
7090 " The matcher failed on the initial attempt; but passed when rerun to "
7091 "generate the explanation.\n"
7092 " Actual: 2" +
7093 OfType(internal::GetTypeName<Behavior>()) + ", [MatchAndExplain]";
7094 EXPECT_EQ(expect, result.message());
7095}
7096
7097// Tests for ElementsAre().
7098
7099TEST(ElementsAreTest, CanDescribeExpectingNoElement) {
7100 Matcher<const vector<int>&> m = ElementsAre();
7101 EXPECT_EQ("is empty", Describe(m));
7102}
7103
7104TEST(ElementsAreTest, CanDescribeExpectingOneElement) {
7105 Matcher<vector<int>> m = ElementsAre(Gt(5));
7106 EXPECT_EQ("has 1 element that is > 5", Describe(m));
7107}
7108
7109TEST(ElementsAreTest, CanDescribeExpectingManyElements) {
7110 Matcher<list<std::string>> m = ElementsAre(StrEq("one"), "two");
7111 EXPECT_EQ(
7112 "has 2 elements where\n"
7113 "element #0 is equal to \"one\",\n"
7114 "element #1 is equal to \"two\"",
7115 Describe(m));
7116}
7117
7118TEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {
7119 Matcher<vector<int>> m = ElementsAre();
7120 EXPECT_EQ("isn't empty", DescribeNegation(m));
7121}
7122
7123TEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElment) {
7124 Matcher<const list<int>&> m = ElementsAre(Gt(5));
7125 EXPECT_EQ(
7126 "doesn't have 1 element, or\n"
7127 "element #0 isn't > 5",
7128 DescribeNegation(m));
7129}
7130
7131TEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {
7132 Matcher<const list<std::string>&> m = ElementsAre("one", "two");
7133 EXPECT_EQ(
7134 "doesn't have 2 elements, or\n"
7135 "element #0 isn't equal to \"one\", or\n"
7136 "element #1 isn't equal to \"two\"",
7137 DescribeNegation(m));
7138}
7139
7140TEST(ElementsAreTest, DoesNotExplainTrivialMatch) {
7141 Matcher<const list<int>&> m = ElementsAre(1, Ne(2));
7142
7143 list<int> test_list;
7144 test_list.push_back(1);
7145 test_list.push_back(3);
7146 EXPECT_EQ("", Explain(m, test_list)); // No need to explain anything.
7147}
7148
7149TEST(ElementsAreTest, ExplainsNonTrivialMatch) {
7150 Matcher<const vector<int>&> m =
7151 ElementsAre(GreaterThan(1), 0, GreaterThan(2));
7152
7153 const int a[] = {10, 0, 100};
7154 vector<int> test_vector(std::begin(a), std::end(a));
7155 EXPECT_EQ(
7156 "whose element #0 matches, which is 9 more than 1,\n"
7157 "and whose element #2 matches, which is 98 more than 2",
7158 Explain(m, test_vector));
7159}
7160
7161TEST(ElementsAreTest, CanExplainMismatchWrongSize) {
7162 Matcher<const list<int>&> m = ElementsAre(1, 3);
7163
7164 list<int> test_list;
7165 // No need to explain when the container is empty.
7166 EXPECT_EQ("", Explain(m, test_list));
7167
7168 test_list.push_back(1);
7169 EXPECT_EQ("which has 1 element", Explain(m, test_list));
7170}
7171
7172TEST(ElementsAreTest, CanExplainMismatchRightSize) {
7173 Matcher<const vector<int>&> m = ElementsAre(1, GreaterThan(5));
7174
7175 vector<int> v;
7176 v.push_back(2);
7177 v.push_back(1);
7178 EXPECT_EQ("whose element #0 doesn't match", Explain(m, v));
7179
7180 v[0] = 1;
7181 EXPECT_EQ("whose element #1 doesn't match, which is 4 less than 5",
7182 Explain(m, v));
7183}
7184
7185TEST(ElementsAreTest, MatchesOneElementVector) {
7186 vector<std::string> test_vector;
7187 test_vector.push_back("test string");
7188
7189 EXPECT_THAT(test_vector, ElementsAre(StrEq("test string")));
7190}
7191
7192TEST(ElementsAreTest, MatchesOneElementList) {
7193 list<std::string> test_list;
7194 test_list.push_back("test string");
7195
7196 EXPECT_THAT(test_list, ElementsAre("test string"));
7197}
7198
7199TEST(ElementsAreTest, MatchesThreeElementVector) {
7200 vector<std::string> test_vector;
7201 test_vector.push_back("one");
7202 test_vector.push_back("two");
7203 test_vector.push_back("three");
7204
7205 EXPECT_THAT(test_vector, ElementsAre("one", StrEq("two"), _));
7206}
7207
7208TEST(ElementsAreTest, MatchesOneElementEqMatcher) {
7209 vector<int> test_vector;
7210 test_vector.push_back(4);
7211
7212 EXPECT_THAT(test_vector, ElementsAre(Eq(4)));
7213}
7214
7215TEST(ElementsAreTest, MatchesOneElementAnyMatcher) {
7216 vector<int> test_vector;
7217 test_vector.push_back(4);
7218
7219 EXPECT_THAT(test_vector, ElementsAre(_));
7220}
7221
7222TEST(ElementsAreTest, MatchesOneElementValue) {
7223 vector<int> test_vector;
7224 test_vector.push_back(4);
7225
7226 EXPECT_THAT(test_vector, ElementsAre(4));
7227}
7228
7229TEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {
7230 vector<int> test_vector;
7231 test_vector.push_back(1);
7232 test_vector.push_back(2);
7233 test_vector.push_back(3);
7234
7235 EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));
7236}
7237
7238TEST(ElementsAreTest, MatchesTenElementVector) {
7239 const int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
7240 vector<int> test_vector(std::begin(a), std::end(a));
7241
7242 EXPECT_THAT(test_vector,
7243 // The element list can contain values and/or matchers
7244 // of different types.
7245 ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));
7246}
7247
7248TEST(ElementsAreTest, DoesNotMatchWrongSize) {
7249 vector<std::string> test_vector;
7250 test_vector.push_back("test string");
7251 test_vector.push_back("test string");
7252
7253 Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
7254 EXPECT_FALSE(m.Matches(test_vector));
7255}
7256
7257TEST(ElementsAreTest, DoesNotMatchWrongValue) {
7258 vector<std::string> test_vector;
7259 test_vector.push_back("other string");
7260
7261 Matcher<vector<std::string>> m = ElementsAre(StrEq("test string"));
7262 EXPECT_FALSE(m.Matches(test_vector));
7263}
7264
7265TEST(ElementsAreTest, DoesNotMatchWrongOrder) {
7266 vector<std::string> test_vector;
7267 test_vector.push_back("one");
7268 test_vector.push_back("three");
7269 test_vector.push_back("two");
7270
7271 Matcher<vector<std::string>> m =
7272 ElementsAre(StrEq("one"), StrEq("two"), StrEq("three"));
7273 EXPECT_FALSE(m.Matches(test_vector));
7274}
7275
7276TEST(ElementsAreTest, WorksForNestedContainer) {
7277 constexpr std::array<const char*, 2> strings = {{"Hi", "world"}};
7278
7279 vector<list<char>> nested;
7280 for (const auto& s : strings) {
7281 nested.emplace_back(s, s + strlen(s));
7282 }
7283
7284 EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),
7285 ElementsAre('w', 'o', _, _, 'd')));
7286 EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),
7287 ElementsAre('w', 'o', _, _, 'd'))));
7288}
7289
7290TEST(ElementsAreTest, WorksWithByRefElementMatchers) {
7291 int a[] = {0, 1, 2};
7292 vector<int> v(std::begin(a), std::end(a));
7293
7294 EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));
7295 EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));
7296}
7297
7298TEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {
7299 int a[] = {0, 1, 2};
7300 vector<int> v(std::begin(a), std::end(a));
7301
7302 EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));
7303 EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));
7304}
7305
7306TEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {
7307 int array[] = {0, 1, 2};
7308 EXPECT_THAT(array, ElementsAre(0, 1, _));
7309 EXPECT_THAT(array, Not(ElementsAre(1, _, _)));
7310 EXPECT_THAT(array, Not(ElementsAre(0, _)));
7311}
7312
7313class NativeArrayPassedAsPointerAndSize {
7314 public:
7315 NativeArrayPassedAsPointerAndSize() {}
7316
7317 MOCK_METHOD(void, Helper, (int* array, int size));
7318
7319 private:
7320 GTEST_DISALLOW_COPY_AND_ASSIGN_(NativeArrayPassedAsPointerAndSize);
7321};
7322
7323TEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {
7324 int array[] = {0, 1};
7325 ::std::tuple<int*, size_t> array_as_tuple(array, 2);
7326 EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));
7327 EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));
7328
7329 NativeArrayPassedAsPointerAndSize helper;
7330 EXPECT_CALL(helper, Helper(_, _)).With(ElementsAre(0, 1));
7331 helper.Helper(array, 2);
7332}
7333
7334TEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {
7335 const char a2[][3] = {"hi", "lo"};
7336 EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\0'),
7337 ElementsAre('l', 'o', '\0')));
7338 EXPECT_THAT(a2, ElementsAre(StrEq("hi"), StrEq("lo")));
7339 EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\0')),
7340 ElementsAre('l', 'o', '\0')));
7341}
7342
7343TEST(ElementsAreTest, AcceptsStringLiteral) {
7344 std::string array[] = {"hi", "one", "two"};
7345 EXPECT_THAT(array, ElementsAre("hi", "one", "two"));
7346 EXPECT_THAT(array, Not(ElementsAre("hi", "one", "too")));
7347}
7348
7349// Declared here with the size unknown. Defined AFTER the following test.
7350extern const char kHi[];
7351
7352TEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {
7353 // The size of kHi is not known in this test, but ElementsAre() should
7354 // still accept it.
7355
7356 std::string array1[] = {"hi"};
7357 EXPECT_THAT(array1, ElementsAre(kHi));
7358
7359 std::string array2[] = {"ho"};
7360 EXPECT_THAT(array2, Not(ElementsAre(kHi)));
7361}
7362
7363const char kHi[] = "hi";
7364
7365TEST(ElementsAreTest, MakesCopyOfArguments) {
7366 int x = 1;
7367 int y = 2;
7368 // This should make a copy of x and y.
7369 ::testing::internal::ElementsAreMatcher<std::tuple<int, int>>
7370 polymorphic_matcher = ElementsAre(x, y);
7371 // Changing x and y now shouldn't affect the meaning of the above matcher.
7372 x = y = 0;
7373 const int array1[] = {1, 2};
7374 EXPECT_THAT(array1, polymorphic_matcher);
7375 const int array2[] = {0, 0};
7376 EXPECT_THAT(array2, Not(polymorphic_matcher));
7377}
7378
7379// Tests for ElementsAreArray(). Since ElementsAreArray() shares most
7380// of the implementation with ElementsAre(), we don't test it as
7381// thoroughly here.
7382
7383TEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {
7384 const int a[] = {1, 2, 3};
7385
7386 vector<int> test_vector(std::begin(a), std::end(a));
7387 EXPECT_THAT(test_vector, ElementsAreArray(a));
7388
7389 test_vector[2] = 0;
7390 EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
7391}
7392
7393TEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {
7394 std::array<const char*, 3> a = {{"one", "two", "three"}};
7395
7396 vector<std::string> test_vector(std::begin(a), std::end(a));
7397 EXPECT_THAT(test_vector, ElementsAreArray(a.data(), a.size()));
7398
7399 const char** p = a.data();
7400 test_vector[0] = "1";
7401 EXPECT_THAT(test_vector, Not(ElementsAreArray(p, a.size())));
7402}
7403
7404TEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {
7405 const char* a[] = {"one", "two", "three"};
7406
7407 vector<std::string> test_vector(std::begin(a), std::end(a));
7408 EXPECT_THAT(test_vector, ElementsAreArray(a));
7409
7410 test_vector[0] = "1";
7411 EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));
7412}
7413
7414TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {
7415 const Matcher<std::string> kMatcherArray[] = {StrEq("one"), StrEq("two"),
7416 StrEq("three")};
7417
7418 vector<std::string> test_vector;
7419 test_vector.push_back("one");
7420 test_vector.push_back("two");
7421 test_vector.push_back("three");
7422 EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));
7423
7424 test_vector.push_back("three");
7425 EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));
7426}
7427
7428TEST(ElementsAreArrayTest, CanBeCreatedWithVector) {
7429 const int a[] = {1, 2, 3};
7430 vector<int> test_vector(std::begin(a), std::end(a));
7431 const vector<int> expected(std::begin(a), std::end(a));
7432 EXPECT_THAT(test_vector, ElementsAreArray(expected));
7433 test_vector.push_back(4);
7434 EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
7435}
7436
7437TEST(ElementsAreArrayTest, TakesInitializerList) {
7438 const int a[5] = {1, 2, 3, 4, 5};
7439 EXPECT_THAT(a, ElementsAreArray({1, 2, 3, 4, 5}));
7440 EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 5, 4})));
7441 EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 4, 6})));
7442}
7443
7444TEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {
7445 const std::string a[5] = {"a", "b", "c", "d", "e"};
7446 EXPECT_THAT(a, ElementsAreArray({"a", "b", "c", "d", "e"}));
7447 EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "e", "d"})));
7448 EXPECT_THAT(a, Not(ElementsAreArray({"a", "b", "c", "d", "ef"})));
7449}
7450
7451TEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
7452 const int a[5] = {1, 2, 3, 4, 5};
7453 EXPECT_THAT(a, ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
7454 EXPECT_THAT(a, Not(ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
7455}
7456
7457TEST(ElementsAreArrayTest, TakesInitializerListOfDifferentTypedMatchers) {
7458 const int a[5] = {1, 2, 3, 4, 5};
7459 // The compiler cannot infer the type of the initializer list if its
7460 // elements have different types. We must explicitly specify the
7461 // unified element type in this case.
7462 EXPECT_THAT(
7463 a, ElementsAreArray<Matcher<int>>({Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
7464 EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int>>(
7465 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
7466}
7467
7468TEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {
7469 const int a[] = {1, 2, 3};
7470 const Matcher<int> kMatchers[] = {Eq(1), Eq(2), Eq(3)};
7471 vector<int> test_vector(std::begin(a), std::end(a));
7472 const vector<Matcher<int>> expected(std::begin(kMatchers),
7473 std::end(kMatchers));
7474 EXPECT_THAT(test_vector, ElementsAreArray(expected));
7475 test_vector.push_back(4);
7476 EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));
7477}
7478
7479TEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {
7480 const int a[] = {1, 2, 3};
7481 const vector<int> test_vector(std::begin(a), std::end(a));
7482 const vector<int> expected(std::begin(a), std::end(a));
7483 EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));
7484 // Pointers are iterators, too.
7485 EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a)));
7486 // The empty range of NULL pointers should also be okay.
7487 int* const null_int = nullptr;
7488 EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));
7489 EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));
7490}
7491
7492// Since ElementsAre() and ElementsAreArray() share much of the
7493// implementation, we only do a sanity test for native arrays here.
7494TEST(ElementsAreArrayTest, WorksWithNativeArray) {
7495 ::std::string a[] = {"hi", "ho"};
7496 ::std::string b[] = {"hi", "ho"};
7497
7498 EXPECT_THAT(a, ElementsAreArray(b));
7499 EXPECT_THAT(a, ElementsAreArray(b, 2));
7500 EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));
7501}
7502
7503TEST(ElementsAreArrayTest, SourceLifeSpan) {
7504 const int a[] = {1, 2, 3};
7505 vector<int> test_vector(std::begin(a), std::end(a));
7506 vector<int> expect(std::begin(a), std::end(a));
7507 ElementsAreArrayMatcher<int> matcher_maker =
7508 ElementsAreArray(expect.begin(), expect.end());
7509 EXPECT_THAT(test_vector, matcher_maker);
7510 // Changing in place the values that initialized matcher_maker should not
7511 // affect matcher_maker anymore. It should have made its own copy of them.
7512 for (int& i : expect) {
7513 i += 10;
7514 }
7515 EXPECT_THAT(test_vector, matcher_maker);
7516 test_vector.push_back(3);
7517 EXPECT_THAT(test_vector, Not(matcher_maker));
7518}
7519
7520// Tests for the MATCHER*() macro family.
7521
7522// Tests that a simple MATCHER() definition works.
7523
7524MATCHER(IsEven, "") { return (arg % 2) == 0; }
7525
7526TEST(MatcherMacroTest, Works) {
7527 const Matcher<int> m = IsEven();
7528 EXPECT_TRUE(m.Matches(6));
7529 EXPECT_FALSE(m.Matches(7));
7530
7531 EXPECT_EQ("is even", Describe(m));
7532 EXPECT_EQ("not (is even)", DescribeNegation(m));
7533 EXPECT_EQ("", Explain(m, 6));
7534 EXPECT_EQ("", Explain(m, 7));
7535}
7536
7537// This also tests that the description string can reference 'negation'.
7538MATCHER(IsEven2, negation ? "is odd" : "is even") {
7539 if ((arg % 2) == 0) {
7540 // Verifies that we can stream to result_listener, a listener
7541 // supplied by the MATCHER macro implicitly.
7542 *result_listener << "OK";
7543 return true;
7544 } else {
7545 *result_listener << "% 2 == " << (arg % 2);
7546 return false;
7547 }
7548}
7549
7550// This also tests that the description string can reference matcher
7551// parameters.
7552MATCHER_P2(EqSumOf, x, y,
7553 std::string(negation ? "doesn't equal" : "equals") + " the sum of " +
7554 PrintToString(x) + " and " + PrintToString(y)) {
7555 if (arg == (x + y)) {
7556 *result_listener << "OK";
7557 return true;
7558 } else {
7559 // Verifies that we can stream to the underlying stream of
7560 // result_listener.
7561 if (result_listener->stream() != nullptr) {
7562 *result_listener->stream() << "diff == " << (x + y - arg);
7563 }
7564 return false;
7565 }
7566}
7567
7568// Tests that the matcher description can reference 'negation' and the
7569// matcher parameters.
7570TEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) {
7571 const Matcher<int> m1 = IsEven2();
7572 EXPECT_EQ("is even", Describe(m1));
7573 EXPECT_EQ("is odd", DescribeNegation(m1));
7574
7575 const Matcher<int> m2 = EqSumOf(5, 9);
7576 EXPECT_EQ("equals the sum of 5 and 9", Describe(m2));
7577 EXPECT_EQ("doesn't equal the sum of 5 and 9", DescribeNegation(m2));
7578}
7579
7580// Tests explaining match result in a MATCHER* macro.
7581TEST(MatcherMacroTest, CanExplainMatchResult) {
7582 const Matcher<int> m1 = IsEven2();
7583 EXPECT_EQ("OK", Explain(m1, 4));
7584 EXPECT_EQ("% 2 == 1", Explain(m1, 5));
7585
7586 const Matcher<int> m2 = EqSumOf(1, 2);
7587 EXPECT_EQ("OK", Explain(m2, 3));
7588 EXPECT_EQ("diff == -1", Explain(m2, 4));
7589}
7590
7591// Tests that the body of MATCHER() can reference the type of the
7592// value being matched.
7593
7594MATCHER(IsEmptyString, "") {
7595 StaticAssertTypeEq<::std::string, arg_type>();
7596 return arg.empty();
7597}
7598
7599MATCHER(IsEmptyStringByRef, "") {
7600 StaticAssertTypeEq<const ::std::string&, arg_type>();
7601 return arg.empty();
7602}
7603
7604TEST(MatcherMacroTest, CanReferenceArgType) {
7605 const Matcher<::std::string> m1 = IsEmptyString();
7606 EXPECT_TRUE(m1.Matches(""));
7607
7608 const Matcher<const ::std::string&> m2 = IsEmptyStringByRef();
7609 EXPECT_TRUE(m2.Matches(""));
7610}
7611
7612// Tests that MATCHER() can be used in a namespace.
7613
7614namespace matcher_test {
7615MATCHER(IsOdd, "") { return (arg % 2) != 0; }
7616} // namespace matcher_test
7617
7618TEST(MatcherMacroTest, WorksInNamespace) {
7619 Matcher<int> m = matcher_test::IsOdd();
7620 EXPECT_FALSE(m.Matches(4));
7621 EXPECT_TRUE(m.Matches(5));
7622}
7623
7624// Tests that Value() can be used to compose matchers.
7625MATCHER(IsPositiveOdd, "") {
7626 return Value(arg, matcher_test::IsOdd()) && arg > 0;
7627}
7628
7629TEST(MatcherMacroTest, CanBeComposedUsingValue) {
7630 EXPECT_THAT(3, IsPositiveOdd());
7631 EXPECT_THAT(4, Not(IsPositiveOdd()));
7632 EXPECT_THAT(-1, Not(IsPositiveOdd()));
7633}
7634
7635// Tests that a simple MATCHER_P() definition works.
7636
7637MATCHER_P(IsGreaterThan32And, n, "") { return arg > 32 && arg > n; }
7638
7639TEST(MatcherPMacroTest, Works) {
7640 const Matcher<int> m = IsGreaterThan32And(5);
7641 EXPECT_TRUE(m.Matches(36));
7642 EXPECT_FALSE(m.Matches(5));
7643
7644 EXPECT_EQ("is greater than 32 and 5", Describe(m));
7645 EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
7646 EXPECT_EQ("", Explain(m, 36));
7647 EXPECT_EQ("", Explain(m, 5));
7648}
7649
7650// Tests that the description is calculated correctly from the matcher name.
7651MATCHER_P(_is_Greater_Than32and_, n, "") { return arg > 32 && arg > n; }
7652
7653TEST(MatcherPMacroTest, GeneratesCorrectDescription) {
7654 const Matcher<int> m = _is_Greater_Than32and_(5);
7655
7656 EXPECT_EQ("is greater than 32 and 5", Describe(m));
7657 EXPECT_EQ("not (is greater than 32 and 5)", DescribeNegation(m));
7658 EXPECT_EQ("", Explain(m, 36));
7659 EXPECT_EQ("", Explain(m, 5));
7660}
7661
7662// Tests that a MATCHER_P matcher can be explicitly instantiated with
7663// a reference parameter type.
7664
7665class UncopyableFoo {
7666 public:
7667 explicit UncopyableFoo(char value) : value_(value) { (void)value_; }
7668
7669 UncopyableFoo(const UncopyableFoo&) = delete;
7670 void operator=(const UncopyableFoo&) = delete;
7671
7672 private:
7673 char value_;
7674};
7675
7676MATCHER_P(ReferencesUncopyable, variable, "") { return &arg == &variable; }
7677
7678TEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) {
7679 UncopyableFoo foo1('1'), foo2('2');
7680 const Matcher<const UncopyableFoo&> m =
7681 ReferencesUncopyable<const UncopyableFoo&>(foo1);
7682
7683 EXPECT_TRUE(m.Matches(foo1));
7684 EXPECT_FALSE(m.Matches(foo2));
7685
7686 // We don't want the address of the parameter printed, as most
7687 // likely it will just annoy the user. If the address is
7688 // interesting, the user should consider passing the parameter by
7689 // pointer instead.
7690 EXPECT_EQ("references uncopyable 1-byte object <31>", Describe(m));
7691}
7692
7693// Tests that the body of MATCHER_Pn() can reference the parameter
7694// types.
7695
7696MATCHER_P3(ParamTypesAreIntLongAndChar, foo, bar, baz, "") {
7697 StaticAssertTypeEq<int, foo_type>();
7698 StaticAssertTypeEq<long, bar_type>(); // NOLINT
7699 StaticAssertTypeEq<char, baz_type>();
7700 return arg == 0;
7701}
7702
7703TEST(MatcherPnMacroTest, CanReferenceParamTypes) {
7704 EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L, 'a'));
7705}
7706
7707// Tests that a MATCHER_Pn matcher can be explicitly instantiated with
7708// reference parameter types.
7709
7710MATCHER_P2(ReferencesAnyOf, variable1, variable2, "") {
7711 return &arg == &variable1 || &arg == &variable2;
7712}
7713
7714TEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) {
7715 UncopyableFoo foo1('1'), foo2('2'), foo3('3');
7716 const Matcher<const UncopyableFoo&> const_m =
7717 ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
7718
7719 EXPECT_TRUE(const_m.Matches(foo1));
7720 EXPECT_TRUE(const_m.Matches(foo2));
7721 EXPECT_FALSE(const_m.Matches(foo3));
7722
7723 const Matcher<UncopyableFoo&> m =
7724 ReferencesAnyOf<UncopyableFoo&, UncopyableFoo&>(foo1, foo2);
7725
7726 EXPECT_TRUE(m.Matches(foo1));
7727 EXPECT_TRUE(m.Matches(foo2));
7728 EXPECT_FALSE(m.Matches(foo3));
7729}
7730
7731TEST(MatcherPnMacroTest,
7732 GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) {
7733 UncopyableFoo foo1('1'), foo2('2');
7734 const Matcher<const UncopyableFoo&> m =
7735 ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);
7736
7737 // We don't want the addresses of the parameters printed, as most
7738 // likely they will just annoy the user. If the addresses are
7739 // interesting, the user should consider passing the parameters by
7740 // pointers instead.
7741 EXPECT_EQ("references any of (1-byte object <31>, 1-byte object <32>)",
7742 Describe(m));
7743}
7744
7745// Tests that a simple MATCHER_P2() definition works.
7746
7747MATCHER_P2(IsNotInClosedRange, low, hi, "") { return arg < low || arg > hi; }
7748
7749TEST(MatcherPnMacroTest, Works) {
7750 const Matcher<const long&> m = IsNotInClosedRange(10, 20); // NOLINT
7751 EXPECT_TRUE(m.Matches(36L));
7752 EXPECT_FALSE(m.Matches(15L));
7753
7754 EXPECT_EQ("is not in closed range (10, 20)", Describe(m));
7755 EXPECT_EQ("not (is not in closed range (10, 20))", DescribeNegation(m));
7756 EXPECT_EQ("", Explain(m, 36L));
7757 EXPECT_EQ("", Explain(m, 15L));
7758}
7759
7760// Tests that MATCHER*() definitions can be overloaded on the number
7761// of parameters; also tests MATCHER_Pn() where n >= 3.
7762
7763MATCHER(EqualsSumOf, "") { return arg == 0; }
7764MATCHER_P(EqualsSumOf, a, "") { return arg == a; }
7765MATCHER_P2(EqualsSumOf, a, b, "") { return arg == a + b; }
7766MATCHER_P3(EqualsSumOf, a, b, c, "") { return arg == a + b + c; }
7767MATCHER_P4(EqualsSumOf, a, b, c, d, "") { return arg == a + b + c + d; }
7768MATCHER_P5(EqualsSumOf, a, b, c, d, e, "") { return arg == a + b + c + d + e; }
7769MATCHER_P6(EqualsSumOf, a, b, c, d, e, f, "") {
7770 return arg == a + b + c + d + e + f;
7771}
7772MATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, "") {
7773 return arg == a + b + c + d + e + f + g;
7774}
7775MATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, "") {
7776 return arg == a + b + c + d + e + f + g + h;
7777}
7778MATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, "") {
7779 return arg == a + b + c + d + e + f + g + h + i;
7780}
7781MATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, "") {
7782 return arg == a + b + c + d + e + f + g + h + i + j;
7783}
7784
7785TEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) {
7786 EXPECT_THAT(0, EqualsSumOf());
7787 EXPECT_THAT(1, EqualsSumOf(1));
7788 EXPECT_THAT(12, EqualsSumOf(10, 2));
7789 EXPECT_THAT(123, EqualsSumOf(100, 20, 3));
7790 EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4));
7791 EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5));
7792 EXPECT_THAT("abcdef",
7793 EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f'));
7794 EXPECT_THAT("abcdefg",
7795 EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g'));
7796 EXPECT_THAT("abcdefgh", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",
7797 'f', 'g', "h"));
7798 EXPECT_THAT("abcdefghi", EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e",
7799 'f', 'g', "h", 'i'));
7800 EXPECT_THAT("abcdefghij",
7801 EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g', "h",
7802 'i', ::std::string("j")));
7803
7804 EXPECT_THAT(1, Not(EqualsSumOf()));
7805 EXPECT_THAT(-1, Not(EqualsSumOf(1)));
7806 EXPECT_THAT(-12, Not(EqualsSumOf(10, 2)));
7807 EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3)));
7808 EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4)));
7809 EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5)));
7810 EXPECT_THAT("abcdef ",
7811 Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f')));
7812 EXPECT_THAT("abcdefg ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
7813 "e", 'f', 'g')));
7814 EXPECT_THAT("abcdefgh ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
7815 "e", 'f', 'g', "h")));
7816 EXPECT_THAT("abcdefghi ", Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d",
7817 "e", 'f', 'g', "h", 'i')));
7818 EXPECT_THAT("abcdefghij ",
7819 Not(EqualsSumOf(::std::string("a"), 'b', 'c', "d", "e", 'f', 'g',
7820 "h", 'i', ::std::string("j"))));
7821}
7822
7823// Tests that a MATCHER_Pn() definition can be instantiated with any
7824// compatible parameter types.
7825TEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) {
7826 EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast<char>(3)));
7827 EXPECT_THAT("abcd", EqualsSumOf(::std::string("a"), "b", 'c', "d"));
7828
7829 EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast<char>(3))));
7830 EXPECT_THAT("abcde", Not(EqualsSumOf(::std::string("a"), "b", 'c', "d")));
7831}
7832
7833// Tests that the matcher body can promote the parameter types.
7834
7835MATCHER_P2(EqConcat, prefix, suffix, "") {
7836 // The following lines promote the two parameters to desired types.
7837 std::string prefix_str(prefix);
7838 char suffix_char = static_cast<char>(suffix);
7839 return arg == prefix_str + suffix_char;
7840}
7841
7842TEST(MatcherPnMacroTest, SimpleTypePromotion) {
7843 Matcher<std::string> no_promo = EqConcat(std::string("foo"), 't');
7844 Matcher<const std::string&> promo = EqConcat("foo", static_cast<int>('t'));
7845 EXPECT_FALSE(no_promo.Matches("fool"));
7846 EXPECT_FALSE(promo.Matches("fool"));
7847 EXPECT_TRUE(no_promo.Matches("foot"));
7848 EXPECT_TRUE(promo.Matches("foot"));
7849}
7850
7851// Verifies the type of a MATCHER*.
7852
7853TEST(MatcherPnMacroTest, TypesAreCorrect) {
7854 // EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable.
7855 EqualsSumOfMatcher a0 = EqualsSumOf();
7856
7857 // EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable.
7858 EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1);
7859
7860 // EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk
7861 // variable, and so on.
7862 EqualsSumOfMatcherP2<int, char> a2 = EqualsSumOf(1, '2');
7863 EqualsSumOfMatcherP3<int, int, char> a3 = EqualsSumOf(1, 2, '3');
7864 EqualsSumOfMatcherP4<int, int, int, char> a4 = EqualsSumOf(1, 2, 3, '4');
7865 EqualsSumOfMatcherP5<int, int, int, int, char> a5 =
7866 EqualsSumOf(1, 2, 3, 4, '5');
7867 EqualsSumOfMatcherP6<int, int, int, int, int, char> a6 =
7868 EqualsSumOf(1, 2, 3, 4, 5, '6');
7869 EqualsSumOfMatcherP7<int, int, int, int, int, int, char> a7 =
7870 EqualsSumOf(1, 2, 3, 4, 5, 6, '7');
7871 EqualsSumOfMatcherP8<int, int, int, int, int, int, int, char> a8 =
7872 EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8');
7873 EqualsSumOfMatcherP9<int, int, int, int, int, int, int, int, char> a9 =
7874 EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9');
7875 EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 =
7876 EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');
7877
7878 // Avoid "unused variable" warnings.
7879 (void)a0;
7880 (void)a1;
7881 (void)a2;
7882 (void)a3;
7883 (void)a4;
7884 (void)a5;
7885 (void)a6;
7886 (void)a7;
7887 (void)a8;
7888 (void)a9;
7889 (void)a10;
7890}
7891
7892// Tests that matcher-typed parameters can be used in Value() inside a
7893// MATCHER_Pn definition.
7894
7895// Succeeds if arg matches exactly 2 of the 3 matchers.
7896MATCHER_P3(TwoOf, m1, m2, m3, "") {
7897 const int count = static_cast<int>(Value(arg, m1)) +
7898 static_cast<int>(Value(arg, m2)) +
7899 static_cast<int>(Value(arg, m3));
7900 return count == 2;
7901}
7902
7903TEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) {
7904 EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10)));
7905 EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0))));
7906}
7907
7908// Tests Contains().
7909
7910TEST(ContainsTest, ListMatchesWhenElementIsInContainer) {
7911 list<int> some_list;
7912 some_list.push_back(3);
7913 some_list.push_back(1);
7914 some_list.push_back(2);
7915 EXPECT_THAT(some_list, Contains(1));
7916 EXPECT_THAT(some_list, Contains(Gt(2.5)));
7917 EXPECT_THAT(some_list, Contains(Eq(2.0f)));
7918
7919 list<std::string> another_list;
7920 another_list.push_back("fee");
7921 another_list.push_back("fie");
7922 another_list.push_back("foe");
7923 another_list.push_back("fum");
7924 EXPECT_THAT(another_list, Contains(std::string("fee")));
7925}
7926
7927TEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {
7928 list<int> some_list;
7929 some_list.push_back(3);
7930 some_list.push_back(1);
7931 EXPECT_THAT(some_list, Not(Contains(4)));
7932}
7933
7934TEST(ContainsTest, SetMatchesWhenElementIsInContainer) {
7935 set<int> some_set;
7936 some_set.insert(3);
7937 some_set.insert(1);
7938 some_set.insert(2);
7939 EXPECT_THAT(some_set, Contains(Eq(1.0)));
7940 EXPECT_THAT(some_set, Contains(Eq(3.0f)));
7941 EXPECT_THAT(some_set, Contains(2));
7942
7943 set<std::string> another_set;
7944 another_set.insert("fee");
7945 another_set.insert("fie");
7946 another_set.insert("foe");
7947 another_set.insert("fum");
7948 EXPECT_THAT(another_set, Contains(Eq(std::string("fum"))));
7949}
7950
7951TEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {
7952 set<int> some_set;
7953 some_set.insert(3);
7954 some_set.insert(1);
7955 EXPECT_THAT(some_set, Not(Contains(4)));
7956
7957 set<std::string> c_string_set;
7958 c_string_set.insert("hello");
7959 EXPECT_THAT(c_string_set, Not(Contains(std::string("goodbye"))));
7960}
7961
7962TEST(ContainsTest, ExplainsMatchResultCorrectly) {
7963 const int a[2] = {1, 2};
7964 Matcher<const int(&)[2]> m = Contains(2);
7965 EXPECT_EQ("whose element #1 matches", Explain(m, a));
7966
7967 m = Contains(3);
7968 EXPECT_EQ("", Explain(m, a));
7969
7970 m = Contains(GreaterThan(0));
7971 EXPECT_EQ("whose element #0 matches, which is 1 more than 0", Explain(m, a));
7972
7973 m = Contains(GreaterThan(10));
7974 EXPECT_EQ("", Explain(m, a));
7975}
7976
7977TEST(ContainsTest, DescribesItselfCorrectly) {
7978 Matcher<vector<int>> m = Contains(1);
7979 EXPECT_EQ("contains at least one element that is equal to 1", Describe(m));
7980
7981 Matcher<vector<int>> m2 = Not(m);
7982 EXPECT_EQ("doesn't contain any element that is equal to 1", Describe(m2));
7983}
7984
7985TEST(ContainsTest, MapMatchesWhenElementIsInContainer) {
7986 map<std::string, int> my_map;
7987 const char* bar = "a string";
7988 my_map[bar] = 2;
7989 EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));
7990
7991 map<std::string, int> another_map;
7992 another_map["fee"] = 1;
7993 another_map["fie"] = 2;
7994 another_map["foe"] = 3;
7995 another_map["fum"] = 4;
7996 EXPECT_THAT(another_map,
7997 Contains(pair<const std::string, int>(std::string("fee"), 1)));
7998 EXPECT_THAT(another_map, Contains(pair<const std::string, int>("fie", 2)));
7999}
8000
8001TEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {
8002 map<int, int> some_map;
8003 some_map[1] = 11;
8004 some_map[2] = 22;
8005 EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));
8006}
8007
8008TEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {
8009 const char* string_array[] = {"fee", "fie", "foe", "fum"};
8010 EXPECT_THAT(string_array, Contains(Eq(std::string("fum"))));
8011}
8012
8013TEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {
8014 int int_array[] = {1, 2, 3, 4};
8015 EXPECT_THAT(int_array, Not(Contains(5)));
8016}
8017
8018TEST(ContainsTest, AcceptsMatcher) {
8019 const int a[] = {1, 2, 3};
8020 EXPECT_THAT(a, Contains(Gt(2)));
8021 EXPECT_THAT(a, Not(Contains(Gt(4))));
8022}
8023
8024TEST(ContainsTest, WorksForNativeArrayAsTuple) {
8025 const int a[] = {1, 2};
8026 const int* const pointer = a;
8027 EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1));
8028 EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3))));
8029}
8030
8031TEST(ContainsTest, WorksForTwoDimensionalNativeArray) {
8032 int a[][3] = {{1, 2, 3}, {4, 5, 6}};
8033 EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));
8034 EXPECT_THAT(a, Contains(Contains(5)));
8035 EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));
8036 EXPECT_THAT(a, Contains(Not(Contains(5))));
8037}
8038
8039TEST(AllOfArrayTest, BasicForms) {
8040 // Iterator
8041 std::vector<int> v0{};
8042 std::vector<int> v1{1};
8043 std::vector<int> v2{2, 3};
8044 std::vector<int> v3{4, 4, 4};
8045 EXPECT_THAT(0, AllOfArray(v0.begin(), v0.end()));
8046 EXPECT_THAT(1, AllOfArray(v1.begin(), v1.end()));
8047 EXPECT_THAT(2, Not(AllOfArray(v1.begin(), v1.end())));
8048 EXPECT_THAT(3, Not(AllOfArray(v2.begin(), v2.end())));
8049 EXPECT_THAT(4, AllOfArray(v3.begin(), v3.end()));
8050 // Pointer + size
8051 int ar[6] = {1, 2, 3, 4, 4, 4};
8052 EXPECT_THAT(0, AllOfArray(ar, 0));
8053 EXPECT_THAT(1, AllOfArray(ar, 1));
8054 EXPECT_THAT(2, Not(AllOfArray(ar, 1)));
8055 EXPECT_THAT(3, Not(AllOfArray(ar + 1, 3)));
8056 EXPECT_THAT(4, AllOfArray(ar + 3, 3));
8057 // Array
8058 // int ar0[0]; Not usable
8059 int ar1[1] = {1};
8060 int ar2[2] = {2, 3};
8061 int ar3[3] = {4, 4, 4};
8062 // EXPECT_THAT(0, Not(AllOfArray(ar0))); // Cannot work
8063 EXPECT_THAT(1, AllOfArray(ar1));
8064 EXPECT_THAT(2, Not(AllOfArray(ar1)));
8065 EXPECT_THAT(3, Not(AllOfArray(ar2)));
8066 EXPECT_THAT(4, AllOfArray(ar3));
8067 // Container
8068 EXPECT_THAT(0, AllOfArray(v0));
8069 EXPECT_THAT(1, AllOfArray(v1));
8070 EXPECT_THAT(2, Not(AllOfArray(v1)));
8071 EXPECT_THAT(3, Not(AllOfArray(v2)));
8072 EXPECT_THAT(4, AllOfArray(v3));
8073 // Initializer
8074 EXPECT_THAT(0, AllOfArray<int>({})); // Requires template arg.
8075 EXPECT_THAT(1, AllOfArray({1}));
8076 EXPECT_THAT(2, Not(AllOfArray({1})));
8077 EXPECT_THAT(3, Not(AllOfArray({2, 3})));
8078 EXPECT_THAT(4, AllOfArray({4, 4, 4}));
8079}
8080
8081TEST(AllOfArrayTest, Matchers) {
8082 // vector
8083 std::vector<Matcher<int>> matchers{Ge(1), Lt(2)};
8084 EXPECT_THAT(0, Not(AllOfArray(matchers)));
8085 EXPECT_THAT(1, AllOfArray(matchers));
8086 EXPECT_THAT(2, Not(AllOfArray(matchers)));
8087 // initializer_list
8088 EXPECT_THAT(0, Not(AllOfArray({Ge(0), Ge(1)})));
8089 EXPECT_THAT(1, AllOfArray({Ge(0), Ge(1)}));
8090}
8091
8092TEST(AnyOfArrayTest, BasicForms) {
8093 // Iterator
8094 std::vector<int> v0{};
8095 std::vector<int> v1{1};
8096 std::vector<int> v2{2, 3};
8097 EXPECT_THAT(0, Not(AnyOfArray(v0.begin(), v0.end())));
8098 EXPECT_THAT(1, AnyOfArray(v1.begin(), v1.end()));
8099 EXPECT_THAT(2, Not(AnyOfArray(v1.begin(), v1.end())));
8100 EXPECT_THAT(3, AnyOfArray(v2.begin(), v2.end()));
8101 EXPECT_THAT(4, Not(AnyOfArray(v2.begin(), v2.end())));
8102 // Pointer + size
8103 int ar[3] = {1, 2, 3};
8104 EXPECT_THAT(0, Not(AnyOfArray(ar, 0)));
8105 EXPECT_THAT(1, AnyOfArray(ar, 1));
8106 EXPECT_THAT(2, Not(AnyOfArray(ar, 1)));
8107 EXPECT_THAT(3, AnyOfArray(ar + 1, 2));
8108 EXPECT_THAT(4, Not(AnyOfArray(ar + 1, 2)));
8109 // Array
8110 // int ar0[0]; Not usable
8111 int ar1[1] = {1};
8112 int ar2[2] = {2, 3};
8113 // EXPECT_THAT(0, Not(AnyOfArray(ar0))); // Cannot work
8114 EXPECT_THAT(1, AnyOfArray(ar1));
8115 EXPECT_THAT(2, Not(AnyOfArray(ar1)));
8116 EXPECT_THAT(3, AnyOfArray(ar2));
8117 EXPECT_THAT(4, Not(AnyOfArray(ar2)));
8118 // Container
8119 EXPECT_THAT(0, Not(AnyOfArray(v0)));
8120 EXPECT_THAT(1, AnyOfArray(v1));
8121 EXPECT_THAT(2, Not(AnyOfArray(v1)));
8122 EXPECT_THAT(3, AnyOfArray(v2));
8123 EXPECT_THAT(4, Not(AnyOfArray(v2)));
8124 // Initializer
8125 EXPECT_THAT(0, Not(AnyOfArray<int>({}))); // Requires template arg.
8126 EXPECT_THAT(1, AnyOfArray({1}));
8127 EXPECT_THAT(2, Not(AnyOfArray({1})));
8128 EXPECT_THAT(3, AnyOfArray({2, 3}));
8129 EXPECT_THAT(4, Not(AnyOfArray({2, 3})));
8130}
8131
8132TEST(AnyOfArrayTest, Matchers) {
8133 // We negate test AllOfArrayTest.Matchers.
8134 // vector
8135 std::vector<Matcher<int>> matchers{Lt(1), Ge(2)};
8136 EXPECT_THAT(0, AnyOfArray(matchers));
8137 EXPECT_THAT(1, Not(AnyOfArray(matchers)));
8138 EXPECT_THAT(2, AnyOfArray(matchers));
8139 // initializer_list
8140 EXPECT_THAT(0, AnyOfArray({Lt(0), Lt(1)}));
8141 EXPECT_THAT(1, Not(AllOfArray({Lt(0), Lt(1)})));
8142}
8143
8144TEST(AnyOfArrayTest, ExplainsMatchResultCorrectly) {
8145 // AnyOfArray and AllOfArry use the same underlying template-template,
8146 // thus it is sufficient to test one here.
8147 const std::vector<int> v0{};
8148 const std::vector<int> v1{1};
8149 const std::vector<int> v2{2, 3};
8150 const Matcher<int> m0 = AnyOfArray(v0);
8151 const Matcher<int> m1 = AnyOfArray(v1);
8152 const Matcher<int> m2 = AnyOfArray(v2);
8153 EXPECT_EQ("", Explain(m0, 0));
8154 EXPECT_EQ("", Explain(m1, 1));
8155 EXPECT_EQ("", Explain(m1, 2));
8156 EXPECT_EQ("", Explain(m2, 3));
8157 EXPECT_EQ("", Explain(m2, 4));
8158 EXPECT_EQ("()", Describe(m0));
8159 EXPECT_EQ("(is equal to 1)", Describe(m1));
8160 EXPECT_EQ("(is equal to 2) or (is equal to 3)", Describe(m2));
8161 EXPECT_EQ("()", DescribeNegation(m0));
8162 EXPECT_EQ("(isn't equal to 1)", DescribeNegation(m1));
8163 EXPECT_EQ("(isn't equal to 2) and (isn't equal to 3)", DescribeNegation(m2));
8164 // Explain with matchers
8165 const Matcher<int> g1 = AnyOfArray({GreaterThan(1)});
8166 const Matcher<int> g2 = AnyOfArray({GreaterThan(1), GreaterThan(2)});
8167 // Explains the first positiv match and all prior negative matches...
8168 EXPECT_EQ("which is 1 less than 1", Explain(g1, 0));
8169 EXPECT_EQ("which is the same as 1", Explain(g1, 1));
8170 EXPECT_EQ("which is 1 more than 1", Explain(g1, 2));
8171 EXPECT_EQ("which is 1 less than 1, and which is 2 less than 2",
8172 Explain(g2, 0));
8173 EXPECT_EQ("which is the same as 1, and which is 1 less than 2",
8174 Explain(g2, 1));
8175 EXPECT_EQ("which is 1 more than 1", // Only the first
8176 Explain(g2, 2));
8177}
8178
8179TEST(AllOfTest, HugeMatcher) {
8180 // Verify that using AllOf with many arguments doesn't cause
8181 // the compiler to exceed template instantiation depth limit.
8182 EXPECT_THAT(0, testing::AllOf(_, _, _, _, _, _, _, _, _,
8183 testing::AllOf(_, _, _, _, _, _, _, _, _, _)));
8184}
8185
8186TEST(AnyOfTest, HugeMatcher) {
8187 // Verify that using AnyOf with many arguments doesn't cause
8188 // the compiler to exceed template instantiation depth limit.
8189 EXPECT_THAT(0, testing::AnyOf(_, _, _, _, _, _, _, _, _,
8190 testing::AnyOf(_, _, _, _, _, _, _, _, _, _)));
8191}
8192
8193namespace adl_test {
8194
8195// Verifies that the implementation of ::testing::AllOf and ::testing::AnyOf
8196// don't issue unqualified recursive calls. If they do, the argument dependent
8197// name lookup will cause AllOf/AnyOf in the 'adl_test' namespace to be found
8198// as a candidate and the compilation will break due to an ambiguous overload.
8199
8200// The matcher must be in the same namespace as AllOf/AnyOf to make argument
8201// dependent lookup find those.
8202MATCHER(M, "") {
8203 (void)arg;
8204 return true;
8205}
8206
8207template <typename T1, typename T2>
8208bool AllOf(const T1& /*t1*/, const T2& /*t2*/) {
8209 return true;
8210}
8211
8212TEST(AllOfTest, DoesNotCallAllOfUnqualified) {
8213 EXPECT_THAT(42,
8214 testing::AllOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
8215}
8216
8217template <typename T1, typename T2>
8218bool AnyOf(const T1&, const T2&) {
8219 return true;
8220}
8221
8222TEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {
8223 EXPECT_THAT(42,
8224 testing::AnyOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));
8225}
8226
8227} // namespace adl_test
8228
8229TEST(AllOfTest, WorksOnMoveOnlyType) {
8230 std::unique_ptr<int> p(new int(3));
8231 EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5))));
8232 EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3)))));
8233}
8234
8235TEST(AnyOfTest, WorksOnMoveOnlyType) {
8236 std::unique_ptr<int> p(new int(3));
8237 EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5))));
8238 EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5)))));
8239}
8240
8241MATCHER(IsNotNull, "") { return arg != nullptr; }
8242
8243// Verifies that a matcher defined using MATCHER() can work on
8244// move-only types.
8245TEST(MatcherMacroTest, WorksOnMoveOnlyType) {
8246 std::unique_ptr<int> p(new int(3));
8247 EXPECT_THAT(p, IsNotNull());
8248 EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));
8249}
8250
8251MATCHER_P(UniquePointee, pointee, "") { return *arg == pointee; }
8252
8253// Verifies that a matcher defined using MATCHER_P*() can work on
8254// move-only types.
8255TEST(MatcherPMacroTest, WorksOnMoveOnlyType) {
8256 std::unique_ptr<int> p(new int(3));
8257 EXPECT_THAT(p, UniquePointee(3));
8258 EXPECT_THAT(p, Not(UniquePointee(2)));
8259}
8260
8261#if GTEST_HAS_EXCEPTIONS
8262
8263// std::function<void()> is used below for compatibility with older copies of
8264// GCC. Normally, a raw lambda is all that is needed.
8265
8266// Test that examples from documentation compile
8267TEST(ThrowsTest, Examples) {
8268 EXPECT_THAT(
8269 std::function<void()>([]() { throw std::runtime_error("message"); }),
8270 Throws<std::runtime_error>());
8271
8272 EXPECT_THAT(
8273 std::function<void()>([]() { throw std::runtime_error("message"); }),
8274 ThrowsMessage<std::runtime_error>(HasSubstr("message")));
8275}
8276
8277TEST(ThrowsTest, DoesNotGenerateDuplicateCatchClauseWarning) {
8278 EXPECT_THAT(std::function<void()>([]() { throw std::exception(); }),
8279 Throws<std::exception>());
8280}
8281
8282TEST(ThrowsTest, CallableExecutedExactlyOnce) {
8283 size_t a = 0;
8284
8285 EXPECT_THAT(std::function<void()>([&a]() {
8286 a++;
8287 throw 10;
8288 }),
8289 Throws<int>());
8290 EXPECT_EQ(a, 1u);
8291
8292 EXPECT_THAT(std::function<void()>([&a]() {
8293 a++;
8294 throw std::runtime_error("message");
8295 }),
8296 Throws<std::runtime_error>());
8297 EXPECT_EQ(a, 2u);
8298
8299 EXPECT_THAT(std::function<void()>([&a]() {
8300 a++;
8301 throw std::runtime_error("message");
8302 }),
8303 ThrowsMessage<std::runtime_error>(HasSubstr("message")));
8304 EXPECT_EQ(a, 3u);
8305
8306 EXPECT_THAT(std::function<void()>([&a]() {
8307 a++;
8308 throw std::runtime_error("message");
8309 }),
8310 Throws<std::runtime_error>(
8311 Property(&std::runtime_error::what, HasSubstr("message"))));
8312 EXPECT_EQ(a, 4u);
8313}
8314
8315TEST(ThrowsTest, Describe) {
8316 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8317 std::stringstream ss;
8318 matcher.DescribeTo(&ss);
8319 auto explanation = ss.str();
8320 EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));
8321}
8322
8323TEST(ThrowsTest, Success) {
8324 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8325 StringMatchResultListener listener;
8326 EXPECT_TRUE(matcher.MatchAndExplain(
8327 []() { throw std::runtime_error("error message"); }, &listener));
8328 EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
8329}
8330
8331TEST(ThrowsTest, FailWrongType) {
8332 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8333 StringMatchResultListener listener;
8334 EXPECT_FALSE(matcher.MatchAndExplain(
8335 []() { throw std::logic_error("error message"); }, &listener));
8336 EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));
8337 EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));
8338}
8339
8340TEST(ThrowsTest, FailWrongTypeNonStd) {
8341 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8342 StringMatchResultListener listener;
8343 EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
8344 EXPECT_THAT(listener.str(),
8345 HasSubstr("throws an exception of an unknown type"));
8346}
8347
8348TEST(ThrowsTest, FailNoThrow) {
8349 Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();
8350 StringMatchResultListener listener;
8351 EXPECT_FALSE(matcher.MatchAndExplain([]() { (void)0; }, &listener));
8352 EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));
8353}
8354
8355class ThrowsPredicateTest
8356 : public TestWithParam<Matcher<std::function<void()>>> {};
8357
8358TEST_P(ThrowsPredicateTest, Describe) {
8359 Matcher<std::function<void()>> matcher = GetParam();
8360 std::stringstream ss;
8361 matcher.DescribeTo(&ss);
8362 auto explanation = ss.str();
8363 EXPECT_THAT(explanation, HasSubstr("std::runtime_error"));
8364 EXPECT_THAT(explanation, HasSubstr("error message"));
8365}
8366
8367TEST_P(ThrowsPredicateTest, Success) {
8368 Matcher<std::function<void()>> matcher = GetParam();
8369 StringMatchResultListener listener;
8370 EXPECT_TRUE(matcher.MatchAndExplain(
8371 []() { throw std::runtime_error("error message"); }, &listener));
8372 EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
8373}
8374
8375TEST_P(ThrowsPredicateTest, FailWrongType) {
8376 Matcher<std::function<void()>> matcher = GetParam();
8377 StringMatchResultListener listener;
8378 EXPECT_FALSE(matcher.MatchAndExplain(
8379 []() { throw std::logic_error("error message"); }, &listener));
8380 EXPECT_THAT(listener.str(), HasSubstr("std::logic_error"));
8381 EXPECT_THAT(listener.str(), HasSubstr("\"error message\""));
8382}
8383
8384TEST_P(ThrowsPredicateTest, FailWrongTypeNonStd) {
8385 Matcher<std::function<void()>> matcher = GetParam();
8386 StringMatchResultListener listener;
8387 EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));
8388 EXPECT_THAT(listener.str(),
8389 HasSubstr("throws an exception of an unknown type"));
8390}
8391
8392TEST_P(ThrowsPredicateTest, FailWrongMessage) {
8393 Matcher<std::function<void()>> matcher = GetParam();
8394 StringMatchResultListener listener;
8395 EXPECT_FALSE(matcher.MatchAndExplain(
8396 []() { throw std::runtime_error("wrong message"); }, &listener));
8397 EXPECT_THAT(listener.str(), HasSubstr("std::runtime_error"));
8398 EXPECT_THAT(listener.str(), Not(HasSubstr("wrong message")));
8399}
8400
8401TEST_P(ThrowsPredicateTest, FailNoThrow) {
8402 Matcher<std::function<void()>> matcher = GetParam();
8403 StringMatchResultListener listener;
8404 EXPECT_FALSE(matcher.MatchAndExplain([]() {}, &listener));
8405 EXPECT_THAT(listener.str(), HasSubstr("does not throw any exception"));
8406}
8407
8408INSTANTIATE_TEST_SUITE_P(
8409 AllMessagePredicates, ThrowsPredicateTest,
8410 Values(Matcher<std::function<void()>>(
8411 ThrowsMessage<std::runtime_error>(HasSubstr("error message")))));
8412
8413// Tests that Throws<E1>(Matcher<E2>{}) compiles even when E2 != const E1&.
8414TEST(ThrowsPredicateCompilesTest, ExceptionMatcherAcceptsBroadType) {
8415 {
8416 Matcher<std::function<void()>> matcher =
8417 ThrowsMessage<std::runtime_error>(HasSubstr("error message"));
8418 EXPECT_TRUE(
8419 matcher.Matches([]() { throw std::runtime_error("error message"); }));
8420 EXPECT_FALSE(
8421 matcher.Matches([]() { throw std::runtime_error("wrong message"); }));
8422 }
8423
8424 {
8425 Matcher<uint64_t> inner = Eq(10);
8426 Matcher<std::function<void()>> matcher = Throws<uint32_t>(inner);
8427 EXPECT_TRUE(matcher.Matches([]() { throw(uint32_t) 10; }));
8428 EXPECT_FALSE(matcher.Matches([]() { throw(uint32_t) 11; }));
8429 }
8430}
8431
8432// Tests that ThrowsMessage("message") is equivalent
8433// to ThrowsMessage(Eq<std::string>("message")).
8434TEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) {
8435 Matcher<std::function<void()>> matcher =
8436 ThrowsMessage<std::runtime_error>("error message");
8437 EXPECT_TRUE(
8438 matcher.Matches([]() { throw std::runtime_error("error message"); }));
8439 EXPECT_FALSE(matcher.Matches(
8440 []() { throw std::runtime_error("wrong error message"); }));
8441}
8442
8443#endif // GTEST_HAS_EXCEPTIONS
8444
8445} // namespace
8446} // namespace gmock_matchers_test
8447} // namespace testing
8448
8449#ifdef _MSC_VER
8450# pragma warning(pop)
8451#endif