1 // Copyright 2007, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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.
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.
30 // Author: wan@google.com (Zhanyong Wan)
32 // Google Mock - a framework for writing C++ mock classes.
34 // This file tests some commonly used argument matchers.
36 #include "gmock/gmock-matchers.h"
37 #include "gmock/gmock-more-matchers.h"
54 #include "gmock/gmock.h"
55 #include "gtest/gtest.h"
56 #include "gtest/gtest-spi.h"
58 #if GTEST_HAS_STD_FORWARD_LIST_
59 # include <forward_list> // NOLINT
63 # include <type_traits>
67 namespace gmock_matchers_test
{
79 using std::stringstream
;
82 using testing::AllArgs
;
87 using testing::ContainsRegex
;
88 using testing::DoubleEq
;
89 using testing::DoubleNear
;
90 using testing::EndsWith
;
92 using testing::ExplainMatchResult
;
94 using testing::FloatEq
;
95 using testing::FloatNear
;
98 using testing::HasSubstr
;
99 using testing::IsEmpty
;
100 using testing::IsNull
;
104 using testing::MakeMatcher
;
105 using testing::MakePolymorphicMatcher
;
106 using testing::MatchResultListener
;
107 using testing::Matcher
;
108 using testing::MatcherCast
;
109 using testing::MatcherInterface
;
110 using testing::Matches
;
111 using testing::MatchesRegex
;
112 using testing::NanSensitiveDoubleEq
;
113 using testing::NanSensitiveDoubleNear
;
114 using testing::NanSensitiveFloatEq
;
115 using testing::NanSensitiveFloatNear
;
118 using testing::NotNull
;
120 using testing::Pointee
;
121 using testing::Pointwise
;
122 using testing::PolymorphicMatcher
;
123 using testing::Property
;
125 using testing::ResultOf
;
126 using testing::SizeIs
;
127 using testing::StartsWith
;
128 using testing::StrCaseEq
;
129 using testing::StrCaseNe
;
130 using testing::StrEq
;
131 using testing::StrNe
;
132 using testing::StringMatchResultListener
;
133 using testing::Truly
;
134 using testing::TypedEq
;
135 using testing::UnorderedPointwise
;
136 using testing::Value
;
137 using testing::WhenSorted
;
138 using testing::WhenSortedBy
;
141 using testing::internal::DummyMatchResultListener
;
142 using testing::internal::ElementMatcherPair
;
143 using testing::internal::ElementMatcherPairs
;
144 using testing::internal::ExplainMatchFailureTupleTo
;
145 using testing::internal::FloatingEqMatcher
;
146 using testing::internal::FormatMatcherDescription
;
147 using testing::internal::IsReadableTypeName
;
148 using testing::internal::linked_ptr
;
149 using testing::internal::MatchMatrix
;
150 using testing::internal::RE
;
151 using testing::internal::scoped_ptr
;
152 using testing::internal::StreamMatchResultListener
;
153 using testing::internal::Strings
;
154 using testing::internal::linked_ptr
;
155 using testing::internal::scoped_ptr
;
156 using testing::internal::string
;
157 using testing::make_tuple
;
158 using testing::tuple
;
160 // For testing ExplainMatchResultTo().
161 class GreaterThanMatcher
: public MatcherInterface
<int> {
163 explicit GreaterThanMatcher(int rhs
) : rhs_(rhs
) {}
165 virtual void DescribeTo(ostream
* os
) const {
166 *os
<< "is > " << rhs_
;
169 virtual bool MatchAndExplain(int lhs
,
170 MatchResultListener
* listener
) const {
171 const int diff
= lhs
- rhs_
;
173 *listener
<< "which is " << diff
<< " more than " << rhs_
;
174 } else if (diff
== 0) {
175 *listener
<< "which is the same as " << rhs_
;
177 *listener
<< "which is " << -diff
<< " less than " << rhs_
;
187 Matcher
<int> GreaterThan(int n
) {
188 return MakeMatcher(new GreaterThanMatcher(n
));
191 std::string
OfType(const std::string
& type_name
) {
193 return " (of type " + type_name
+ ")";
199 // Returns the description of the given matcher.
200 template <typename T
>
201 std::string
Describe(const Matcher
<T
>& m
) {
202 return DescribeMatcher
<T
>(m
);
205 // Returns the description of the negation of the given matcher.
206 template <typename T
>
207 std::string
DescribeNegation(const Matcher
<T
>& m
) {
208 return DescribeMatcher
<T
>(m
, true);
211 // Returns the reason why x matches, or doesn't match, m.
212 template <typename MatcherType
, typename Value
>
213 std::string
Explain(const MatcherType
& m
, const Value
& x
) {
214 StringMatchResultListener listener
;
215 ExplainMatchResult(m
, x
, &listener
);
216 return listener
.str();
219 TEST(MonotonicMatcherTest
, IsPrintable
) {
221 ss
<< GreaterThan(5);
222 EXPECT_EQ("is > 5", ss
.str());
225 TEST(MatchResultListenerTest
, StreamingWorks
) {
226 StringMatchResultListener listener
;
227 listener
<< "hi" << 5;
228 EXPECT_EQ("hi5", listener
.str());
231 EXPECT_EQ("", listener
.str());
234 EXPECT_EQ("42", listener
.str());
236 // Streaming shouldn't crash when the underlying ostream is NULL.
237 DummyMatchResultListener dummy
;
241 TEST(MatchResultListenerTest
, CanAccessUnderlyingStream
) {
242 EXPECT_TRUE(DummyMatchResultListener().stream() == NULL
);
243 EXPECT_TRUE(StreamMatchResultListener(NULL
).stream() == NULL
);
245 EXPECT_EQ(&std::cout
, StreamMatchResultListener(&std::cout
).stream());
248 TEST(MatchResultListenerTest
, IsInterestedWorks
) {
249 EXPECT_TRUE(StringMatchResultListener().IsInterested());
250 EXPECT_TRUE(StreamMatchResultListener(&std::cout
).IsInterested());
252 EXPECT_FALSE(DummyMatchResultListener().IsInterested());
253 EXPECT_FALSE(StreamMatchResultListener(NULL
).IsInterested());
256 // Makes sure that the MatcherInterface<T> interface doesn't
258 class EvenMatcherImpl
: public MatcherInterface
<int> {
260 virtual bool MatchAndExplain(int x
,
261 MatchResultListener
* /* listener */) const {
265 virtual void DescribeTo(ostream
* os
) const {
266 *os
<< "is an even number";
269 // We deliberately don't define DescribeNegationTo() and
270 // ExplainMatchResultTo() here, to make sure the definition of these
271 // two methods is optional.
274 // Makes sure that the MatcherInterface API doesn't change.
275 TEST(MatcherInterfaceTest
, CanBeImplementedUsingPublishedAPI
) {
279 // Tests implementing a monomorphic matcher using MatchAndExplain().
281 class NewEvenMatcherImpl
: public MatcherInterface
<int> {
283 virtual bool MatchAndExplain(int x
, MatchResultListener
* listener
) const {
284 const bool match
= x
% 2 == 0;
285 // Verifies that we can stream to a listener directly.
286 *listener
<< "value % " << 2;
287 if (listener
->stream() != NULL
) {
288 // Verifies that we can stream to a listener's underlying stream
290 *listener
->stream() << " == " << (x
% 2);
295 virtual void DescribeTo(ostream
* os
) const {
296 *os
<< "is an even number";
300 TEST(MatcherInterfaceTest
, CanBeImplementedUsingNewAPI
) {
301 Matcher
<int> m
= MakeMatcher(new NewEvenMatcherImpl
);
302 EXPECT_TRUE(m
.Matches(2));
303 EXPECT_FALSE(m
.Matches(3));
304 EXPECT_EQ("value % 2 == 0", Explain(m
, 2));
305 EXPECT_EQ("value % 2 == 1", Explain(m
, 3));
308 // Tests default-constructing a matcher.
309 TEST(MatcherTest
, CanBeDefaultConstructed
) {
313 // Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
314 TEST(MatcherTest
, CanBeConstructedFromMatcherInterface
) {
315 const MatcherInterface
<int>* impl
= new EvenMatcherImpl
;
316 Matcher
<int> m(impl
);
317 EXPECT_TRUE(m
.Matches(4));
318 EXPECT_FALSE(m
.Matches(5));
321 // Tests that value can be used in place of Eq(value).
322 TEST(MatcherTest
, CanBeImplicitlyConstructedFromValue
) {
324 EXPECT_TRUE(m1
.Matches(5));
325 EXPECT_FALSE(m1
.Matches(6));
328 // Tests that NULL can be used in place of Eq(NULL).
329 TEST(MatcherTest
, CanBeImplicitlyConstructedFromNULL
) {
330 Matcher
<int*> m1
= NULL
;
331 EXPECT_TRUE(m1
.Matches(NULL
));
333 EXPECT_FALSE(m1
.Matches(&n
));
336 // Tests that matchers can be constructed from a variable that is not properly
337 // defined. This should be illegal, but many users rely on this accidentally.
339 virtual ~Undefined() = 0;
340 static const int kInt
= 1;
343 TEST(MatcherTest
, CanBeConstructedFromUndefinedVariable
) {
344 Matcher
<int> m1
= Undefined::kInt
;
345 EXPECT_TRUE(m1
.Matches(1));
346 EXPECT_FALSE(m1
.Matches(2));
349 // Test that a matcher parameterized with an abstract class compiles.
350 TEST(MatcherTest
, CanAcceptAbstractClass
) { Matcher
<const Undefined
&> m
= _
; }
352 // Tests that matchers are copyable.
353 TEST(MatcherTest
, IsCopyable
) {
354 // Tests the copy constructor.
355 Matcher
<bool> m1
= Eq(false);
356 EXPECT_TRUE(m1
.Matches(false));
357 EXPECT_FALSE(m1
.Matches(true));
359 // Tests the assignment operator.
361 EXPECT_TRUE(m1
.Matches(true));
362 EXPECT_FALSE(m1
.Matches(false));
365 // Tests that Matcher<T>::DescribeTo() calls
366 // MatcherInterface<T>::DescribeTo().
367 TEST(MatcherTest
, CanDescribeItself
) {
368 EXPECT_EQ("is an even number",
369 Describe(Matcher
<int>(new EvenMatcherImpl
)));
372 // Tests Matcher<T>::MatchAndExplain().
373 TEST(MatcherTest
, MatchAndExplain
) {
374 Matcher
<int> m
= GreaterThan(0);
375 StringMatchResultListener listener1
;
376 EXPECT_TRUE(m
.MatchAndExplain(42, &listener1
));
377 EXPECT_EQ("which is 42 more than 0", listener1
.str());
379 StringMatchResultListener listener2
;
380 EXPECT_FALSE(m
.MatchAndExplain(-9, &listener2
));
381 EXPECT_EQ("which is 9 less than 0", listener2
.str());
384 // Tests that a C-string literal can be implicitly converted to a
385 // Matcher<std::string> or Matcher<const std::string&>.
386 TEST(StringMatcherTest
, CanBeImplicitlyConstructedFromCStringLiteral
) {
387 Matcher
<std::string
> m1
= "hi";
388 EXPECT_TRUE(m1
.Matches("hi"));
389 EXPECT_FALSE(m1
.Matches("hello"));
391 Matcher
<const std::string
&> m2
= "hi";
392 EXPECT_TRUE(m2
.Matches("hi"));
393 EXPECT_FALSE(m2
.Matches("hello"));
396 // Tests that a string object can be implicitly converted to a
397 // Matcher<std::string> or Matcher<const std::string&>.
398 TEST(StringMatcherTest
, CanBeImplicitlyConstructedFromString
) {
399 Matcher
<std::string
> m1
= std::string("hi");
400 EXPECT_TRUE(m1
.Matches("hi"));
401 EXPECT_FALSE(m1
.Matches("hello"));
403 Matcher
<const std::string
&> m2
= std::string("hi");
404 EXPECT_TRUE(m2
.Matches("hi"));
405 EXPECT_FALSE(m2
.Matches("hello"));
408 #if GTEST_HAS_GLOBAL_STRING
409 // Tests that a ::string object can be implicitly converted to a
410 // Matcher<std::string> or Matcher<const std::string&>.
411 TEST(StringMatcherTest
, CanBeImplicitlyConstructedFromGlobalString
) {
412 Matcher
<std::string
> m1
= ::string("hi");
413 EXPECT_TRUE(m1
.Matches("hi"));
414 EXPECT_FALSE(m1
.Matches("hello"));
416 Matcher
<const std::string
&> m2
= ::string("hi");
417 EXPECT_TRUE(m2
.Matches("hi"));
418 EXPECT_FALSE(m2
.Matches("hello"));
420 #endif // GTEST_HAS_GLOBAL_STRING
422 #if GTEST_HAS_GLOBAL_STRING
423 // Tests that a C-string literal can be implicitly converted to a
424 // Matcher<::string> or Matcher<const ::string&>.
425 TEST(GlobalStringMatcherTest
, CanBeImplicitlyConstructedFromCStringLiteral
) {
426 Matcher
< ::string
> m1
= "hi";
427 EXPECT_TRUE(m1
.Matches("hi"));
428 EXPECT_FALSE(m1
.Matches("hello"));
430 Matcher
<const ::string
&> m2
= "hi";
431 EXPECT_TRUE(m2
.Matches("hi"));
432 EXPECT_FALSE(m2
.Matches("hello"));
435 // Tests that a std::string object can be implicitly converted to a
436 // Matcher<::string> or Matcher<const ::string&>.
437 TEST(GlobalStringMatcherTest
, CanBeImplicitlyConstructedFromString
) {
438 Matcher
< ::string
> m1
= std::string("hi");
439 EXPECT_TRUE(m1
.Matches("hi"));
440 EXPECT_FALSE(m1
.Matches("hello"));
442 Matcher
<const ::string
&> m2
= std::string("hi");
443 EXPECT_TRUE(m2
.Matches("hi"));
444 EXPECT_FALSE(m2
.Matches("hello"));
447 // Tests that a ::string object can be implicitly converted to a
448 // Matcher<::string> or Matcher<const ::string&>.
449 TEST(GlobalStringMatcherTest
, CanBeImplicitlyConstructedFromGlobalString
) {
450 Matcher
< ::string
> m1
= ::string("hi");
451 EXPECT_TRUE(m1
.Matches("hi"));
452 EXPECT_FALSE(m1
.Matches("hello"));
454 Matcher
<const ::string
&> m2
= ::string("hi");
455 EXPECT_TRUE(m2
.Matches("hi"));
456 EXPECT_FALSE(m2
.Matches("hello"));
458 #endif // GTEST_HAS_GLOBAL_STRING
461 // Tests that a C-string literal can be implicitly converted to a
462 // Matcher<absl::string_view> or Matcher<const absl::string_view&>.
463 TEST(StringViewMatcherTest
, CanBeImplicitlyConstructedFromCStringLiteral
) {
464 Matcher
<absl::string_view
> m1
= "cats";
465 EXPECT_TRUE(m1
.Matches("cats"));
466 EXPECT_FALSE(m1
.Matches("dogs"));
468 Matcher
<const absl::string_view
&> m2
= "cats";
469 EXPECT_TRUE(m2
.Matches("cats"));
470 EXPECT_FALSE(m2
.Matches("dogs"));
473 // Tests that a std::string object can be implicitly converted to a
474 // Matcher<absl::string_view> or Matcher<const absl::string_view&>.
475 TEST(StringViewMatcherTest
, CanBeImplicitlyConstructedFromString
) {
476 Matcher
<absl::string_view
> m1
= std::string("cats");
477 EXPECT_TRUE(m1
.Matches("cats"));
478 EXPECT_FALSE(m1
.Matches("dogs"));
480 Matcher
<const absl::string_view
&> m2
= std::string("cats");
481 EXPECT_TRUE(m2
.Matches("cats"));
482 EXPECT_FALSE(m2
.Matches("dogs"));
485 #if GTEST_HAS_GLOBAL_STRING
486 // Tests that a ::string object can be implicitly converted to a
487 // Matcher<absl::string_view> or Matcher<const absl::string_view&>.
488 TEST(StringViewMatcherTest
, CanBeImplicitlyConstructedFromGlobalString
) {
489 Matcher
<absl::string_view
> m1
= ::string("cats");
490 EXPECT_TRUE(m1
.Matches("cats"));
491 EXPECT_FALSE(m1
.Matches("dogs"));
493 Matcher
<const absl::string_view
&> m2
= ::string("cats");
494 EXPECT_TRUE(m2
.Matches("cats"));
495 EXPECT_FALSE(m2
.Matches("dogs"));
497 #endif // GTEST_HAS_GLOBAL_STRING
499 // Tests that a absl::string_view object can be implicitly converted to a
500 // Matcher<absl::string_view> or Matcher<const absl::string_view&>.
501 TEST(StringViewMatcherTest
, CanBeImplicitlyConstructedFromStringView
) {
502 Matcher
<absl::string_view
> m1
= absl::string_view("cats");
503 EXPECT_TRUE(m1
.Matches("cats"));
504 EXPECT_FALSE(m1
.Matches("dogs"));
506 Matcher
<const absl::string_view
&> m2
= absl::string_view("cats");
507 EXPECT_TRUE(m2
.Matches("cats"));
508 EXPECT_FALSE(m2
.Matches("dogs"));
510 #endif // GTEST_HAS_ABSL
512 // Tests that MakeMatcher() constructs a Matcher<T> from a
513 // MatcherInterface* without requiring the user to explicitly
515 TEST(MakeMatcherTest
, ConstructsMatcherFromMatcherInterface
) {
516 const MatcherInterface
<int>* dummy_impl
= NULL
;
517 Matcher
<int> m
= MakeMatcher(dummy_impl
);
520 // Tests that MakePolymorphicMatcher() can construct a polymorphic
521 // matcher from its implementation using the old API.
523 class ReferencesBarOrIsZeroImpl
{
525 template <typename T
>
526 bool MatchAndExplain(const T
& x
,
527 MatchResultListener
* /* listener */) const {
529 return p
== &g_bar
|| x
== 0;
532 void DescribeTo(ostream
* os
) const { *os
<< "g_bar or zero"; }
534 void DescribeNegationTo(ostream
* os
) const {
535 *os
<< "doesn't reference g_bar and is not zero";
539 // This function verifies that MakePolymorphicMatcher() returns a
540 // PolymorphicMatcher<T> where T is the argument's type.
541 PolymorphicMatcher
<ReferencesBarOrIsZeroImpl
> ReferencesBarOrIsZero() {
542 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
545 TEST(MakePolymorphicMatcherTest
, ConstructsMatcherUsingOldAPI
) {
546 // Using a polymorphic matcher to match a reference type.
547 Matcher
<const int&> m1
= ReferencesBarOrIsZero();
548 EXPECT_TRUE(m1
.Matches(0));
549 // Verifies that the identity of a by-reference argument is preserved.
550 EXPECT_TRUE(m1
.Matches(g_bar
));
551 EXPECT_FALSE(m1
.Matches(1));
552 EXPECT_EQ("g_bar or zero", Describe(m1
));
554 // Using a polymorphic matcher to match a value type.
555 Matcher
<double> m2
= ReferencesBarOrIsZero();
556 EXPECT_TRUE(m2
.Matches(0.0));
557 EXPECT_FALSE(m2
.Matches(0.1));
558 EXPECT_EQ("g_bar or zero", Describe(m2
));
561 // Tests implementing a polymorphic matcher using MatchAndExplain().
563 class PolymorphicIsEvenImpl
{
565 void DescribeTo(ostream
* os
) const { *os
<< "is even"; }
567 void DescribeNegationTo(ostream
* os
) const {
571 template <typename T
>
572 bool MatchAndExplain(const T
& x
, MatchResultListener
* listener
) const {
573 // Verifies that we can stream to the listener directly.
574 *listener
<< "% " << 2;
575 if (listener
->stream() != NULL
) {
576 // Verifies that we can stream to the listener's underlying stream
578 *listener
->stream() << " == " << (x
% 2);
584 PolymorphicMatcher
<PolymorphicIsEvenImpl
> PolymorphicIsEven() {
585 return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
588 TEST(MakePolymorphicMatcherTest
, ConstructsMatcherUsingNewAPI
) {
589 // Using PolymorphicIsEven() as a Matcher<int>.
590 const Matcher
<int> m1
= PolymorphicIsEven();
591 EXPECT_TRUE(m1
.Matches(42));
592 EXPECT_FALSE(m1
.Matches(43));
593 EXPECT_EQ("is even", Describe(m1
));
595 const Matcher
<int> not_m1
= Not(m1
);
596 EXPECT_EQ("is odd", Describe(not_m1
));
598 EXPECT_EQ("% 2 == 0", Explain(m1
, 42));
600 // Using PolymorphicIsEven() as a Matcher<char>.
601 const Matcher
<char> m2
= PolymorphicIsEven();
602 EXPECT_TRUE(m2
.Matches('\x42'));
603 EXPECT_FALSE(m2
.Matches('\x43'));
604 EXPECT_EQ("is even", Describe(m2
));
606 const Matcher
<char> not_m2
= Not(m2
);
607 EXPECT_EQ("is odd", Describe(not_m2
));
609 EXPECT_EQ("% 2 == 0", Explain(m2
, '\x42'));
612 // Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
613 TEST(MatcherCastTest
, FromPolymorphicMatcher
) {
614 Matcher
<int> m
= MatcherCast
<int>(Eq(5));
615 EXPECT_TRUE(m
.Matches(5));
616 EXPECT_FALSE(m
.Matches(6));
619 // For testing casting matchers between compatible types.
622 // An int can be statically (although not implicitly) cast to a
624 explicit IntValue(int a_value
) : value_(a_value
) {}
626 int value() const { return value_
; }
631 // For testing casting matchers between compatible types.
632 bool IsPositiveIntValue(const IntValue
& foo
) {
633 return foo
.value() > 0;
636 // Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
637 // can be statically converted to U.
638 TEST(MatcherCastTest
, FromCompatibleType
) {
639 Matcher
<double> m1
= Eq(2.0);
640 Matcher
<int> m2
= MatcherCast
<int>(m1
);
641 EXPECT_TRUE(m2
.Matches(2));
642 EXPECT_FALSE(m2
.Matches(3));
644 Matcher
<IntValue
> m3
= Truly(IsPositiveIntValue
);
645 Matcher
<int> m4
= MatcherCast
<int>(m3
);
646 // In the following, the arguments 1 and 0 are statically converted
647 // to IntValue objects, and then tested by the IsPositiveIntValue()
649 EXPECT_TRUE(m4
.Matches(1));
650 EXPECT_FALSE(m4
.Matches(0));
653 // Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
654 TEST(MatcherCastTest
, FromConstReferenceToNonReference
) {
655 Matcher
<const int&> m1
= Eq(0);
656 Matcher
<int> m2
= MatcherCast
<int>(m1
);
657 EXPECT_TRUE(m2
.Matches(0));
658 EXPECT_FALSE(m2
.Matches(1));
661 // Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
662 TEST(MatcherCastTest
, FromReferenceToNonReference
) {
663 Matcher
<int&> m1
= Eq(0);
664 Matcher
<int> m2
= MatcherCast
<int>(m1
);
665 EXPECT_TRUE(m2
.Matches(0));
666 EXPECT_FALSE(m2
.Matches(1));
669 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
670 TEST(MatcherCastTest
, FromNonReferenceToConstReference
) {
671 Matcher
<int> m1
= Eq(0);
672 Matcher
<const int&> m2
= MatcherCast
<const int&>(m1
);
673 EXPECT_TRUE(m2
.Matches(0));
674 EXPECT_FALSE(m2
.Matches(1));
677 // Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
678 TEST(MatcherCastTest
, FromNonReferenceToReference
) {
679 Matcher
<int> m1
= Eq(0);
680 Matcher
<int&> m2
= MatcherCast
<int&>(m1
);
682 EXPECT_TRUE(m2
.Matches(n
));
684 EXPECT_FALSE(m2
.Matches(n
));
687 // Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
688 TEST(MatcherCastTest
, FromSameType
) {
689 Matcher
<int> m1
= Eq(0);
690 Matcher
<int> m2
= MatcherCast
<int>(m1
);
691 EXPECT_TRUE(m2
.Matches(0));
692 EXPECT_FALSE(m2
.Matches(1));
695 // Tests that MatcherCast<T>(m) works when m is a value of the same type as the
696 // value type of the Matcher.
697 TEST(MatcherCastTest
, FromAValue
) {
698 Matcher
<int> m
= MatcherCast
<int>(42);
699 EXPECT_TRUE(m
.Matches(42));
700 EXPECT_FALSE(m
.Matches(239));
703 // Tests that MatcherCast<T>(m) works when m is a value of the type implicitly
704 // convertible to the value type of the Matcher.
705 TEST(MatcherCastTest
, FromAnImplicitlyConvertibleValue
) {
706 const int kExpected
= 'c';
707 Matcher
<int> m
= MatcherCast
<int>('c');
708 EXPECT_TRUE(m
.Matches(kExpected
));
709 EXPECT_FALSE(m
.Matches(kExpected
+ 1));
712 struct NonImplicitlyConstructibleTypeWithOperatorEq
{
713 friend bool operator==(
714 const NonImplicitlyConstructibleTypeWithOperatorEq
& /* ignored */,
718 friend bool operator==(
720 const NonImplicitlyConstructibleTypeWithOperatorEq
& /* ignored */) {
725 // Tests that MatcherCast<T>(m) works when m is a neither a matcher nor
726 // implicitly convertible to the value type of the Matcher, but the value type
727 // of the matcher has operator==() overload accepting m.
728 TEST(MatcherCastTest
, NonImplicitlyConstructibleTypeWithOperatorEq
) {
729 Matcher
<NonImplicitlyConstructibleTypeWithOperatorEq
> m1
=
730 MatcherCast
<NonImplicitlyConstructibleTypeWithOperatorEq
>(42);
731 EXPECT_TRUE(m1
.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
733 Matcher
<NonImplicitlyConstructibleTypeWithOperatorEq
> m2
=
734 MatcherCast
<NonImplicitlyConstructibleTypeWithOperatorEq
>(239);
735 EXPECT_FALSE(m2
.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));
737 // When updating the following lines please also change the comment to
738 // namespace convertible_from_any.
740 MatcherCast
<int>(NonImplicitlyConstructibleTypeWithOperatorEq());
741 EXPECT_TRUE(m3
.Matches(42));
742 EXPECT_FALSE(m3
.Matches(239));
745 // ConvertibleFromAny does not work with MSVC. resulting in
746 // error C2440: 'initializing': cannot convert from 'Eq' to 'M'
747 // No constructor could take the source type, or constructor overload
748 // resolution was ambiguous
750 #if !defined _MSC_VER
752 // The below ConvertibleFromAny struct is implicitly constructible from anything
753 // and when in the same namespace can interact with other tests. In particular,
754 // if it is in the same namespace as other tests and one removes
755 // NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...);
756 // then the corresponding test still compiles (and it should not!) by implicitly
757 // converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny
759 namespace convertible_from_any
{
760 // Implicitly convertible from any type.
761 struct ConvertibleFromAny
{
762 ConvertibleFromAny(int a_value
) : value(a_value
) {}
763 template <typename T
>
764 ConvertibleFromAny(const T
& /*a_value*/) : value(-1) {
765 ADD_FAILURE() << "Conversion constructor called";
770 bool operator==(const ConvertibleFromAny
& a
, const ConvertibleFromAny
& b
) {
771 return a
.value
== b
.value
;
774 ostream
& operator<<(ostream
& os
, const ConvertibleFromAny
& a
) {
775 return os
<< a
.value
;
778 TEST(MatcherCastTest
, ConversionConstructorIsUsed
) {
779 Matcher
<ConvertibleFromAny
> m
= MatcherCast
<ConvertibleFromAny
>(1);
780 EXPECT_TRUE(m
.Matches(ConvertibleFromAny(1)));
781 EXPECT_FALSE(m
.Matches(ConvertibleFromAny(2)));
784 TEST(MatcherCastTest
, FromConvertibleFromAny
) {
785 Matcher
<ConvertibleFromAny
> m
=
786 MatcherCast
<ConvertibleFromAny
>(Eq(ConvertibleFromAny(1)));
787 EXPECT_TRUE(m
.Matches(ConvertibleFromAny(1)));
788 EXPECT_FALSE(m
.Matches(ConvertibleFromAny(2)));
790 } // namespace convertible_from_any
792 #endif // !defined _MSC_VER
794 struct IntReferenceWrapper
{
795 IntReferenceWrapper(const int& a_value
) : value(&a_value
) {}
799 bool operator==(const IntReferenceWrapper
& a
, const IntReferenceWrapper
& b
) {
800 return a
.value
== b
.value
;
803 TEST(MatcherCastTest
, ValueIsNotCopied
) {
805 Matcher
<IntReferenceWrapper
> m
= MatcherCast
<IntReferenceWrapper
>(n
);
806 // Verify that the matcher holds a reference to n, not to its temporary copy.
807 EXPECT_TRUE(m
.Matches(n
));
815 GTEST_DISALLOW_COPY_AND_ASSIGN_(Base
);
818 class Derived
: public Base
{
820 Derived() : Base() {}
824 class OtherDerived
: public Base
{};
826 // Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
827 TEST(SafeMatcherCastTest
, FromPolymorphicMatcher
) {
828 Matcher
<char> m2
= SafeMatcherCast
<char>(Eq(32));
829 EXPECT_TRUE(m2
.Matches(' '));
830 EXPECT_FALSE(m2
.Matches('\n'));
833 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
834 // T and U are arithmetic types and T can be losslessly converted to
836 TEST(SafeMatcherCastTest
, FromLosslesslyConvertibleArithmeticType
) {
837 Matcher
<double> m1
= DoubleEq(1.0);
838 Matcher
<float> m2
= SafeMatcherCast
<float>(m1
);
839 EXPECT_TRUE(m2
.Matches(1.0f
));
840 EXPECT_FALSE(m2
.Matches(2.0f
));
842 Matcher
<char> m3
= SafeMatcherCast
<char>(TypedEq
<int>('a'));
843 EXPECT_TRUE(m3
.Matches('a'));
844 EXPECT_FALSE(m3
.Matches('b'));
847 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
848 // are pointers or references to a derived and a base class, correspondingly.
849 TEST(SafeMatcherCastTest
, FromBaseClass
) {
851 Matcher
<Base
*> m1
= Eq(&d
);
852 Matcher
<Derived
*> m2
= SafeMatcherCast
<Derived
*>(m1
);
853 EXPECT_TRUE(m2
.Matches(&d
));
854 EXPECT_FALSE(m2
.Matches(&d2
));
856 Matcher
<Base
&> m3
= Ref(d
);
857 Matcher
<Derived
&> m4
= SafeMatcherCast
<Derived
&>(m3
);
858 EXPECT_TRUE(m4
.Matches(d
));
859 EXPECT_FALSE(m4
.Matches(d2
));
862 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
863 TEST(SafeMatcherCastTest
, FromConstReferenceToReference
) {
865 Matcher
<const int&> m1
= Ref(n
);
866 Matcher
<int&> m2
= SafeMatcherCast
<int&>(m1
);
868 EXPECT_TRUE(m2
.Matches(n
));
869 EXPECT_FALSE(m2
.Matches(n1
));
872 // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
873 TEST(SafeMatcherCastTest
, FromNonReferenceToConstReference
) {
874 Matcher
<int> m1
= Eq(0);
875 Matcher
<const int&> m2
= SafeMatcherCast
<const int&>(m1
);
876 EXPECT_TRUE(m2
.Matches(0));
877 EXPECT_FALSE(m2
.Matches(1));
880 // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
881 TEST(SafeMatcherCastTest
, FromNonReferenceToReference
) {
882 Matcher
<int> m1
= Eq(0);
883 Matcher
<int&> m2
= SafeMatcherCast
<int&>(m1
);
885 EXPECT_TRUE(m2
.Matches(n
));
887 EXPECT_FALSE(m2
.Matches(n
));
890 // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
891 TEST(SafeMatcherCastTest
, FromSameType
) {
892 Matcher
<int> m1
= Eq(0);
893 Matcher
<int> m2
= SafeMatcherCast
<int>(m1
);
894 EXPECT_TRUE(m2
.Matches(0));
895 EXPECT_FALSE(m2
.Matches(1));
898 #if !defined _MSC_VER
900 namespace convertible_from_any
{
901 TEST(SafeMatcherCastTest
, ConversionConstructorIsUsed
) {
902 Matcher
<ConvertibleFromAny
> m
= SafeMatcherCast
<ConvertibleFromAny
>(1);
903 EXPECT_TRUE(m
.Matches(ConvertibleFromAny(1)));
904 EXPECT_FALSE(m
.Matches(ConvertibleFromAny(2)));
907 TEST(SafeMatcherCastTest
, FromConvertibleFromAny
) {
908 Matcher
<ConvertibleFromAny
> m
=
909 SafeMatcherCast
<ConvertibleFromAny
>(Eq(ConvertibleFromAny(1)));
910 EXPECT_TRUE(m
.Matches(ConvertibleFromAny(1)));
911 EXPECT_FALSE(m
.Matches(ConvertibleFromAny(2)));
913 } // namespace convertible_from_any
915 #endif // !defined _MSC_VER
917 TEST(SafeMatcherCastTest
, ValueIsNotCopied
) {
919 Matcher
<IntReferenceWrapper
> m
= SafeMatcherCast
<IntReferenceWrapper
>(n
);
920 // Verify that the matcher holds a reference to n, not to its temporary copy.
921 EXPECT_TRUE(m
.Matches(n
));
924 TEST(ExpectThat
, TakesLiterals
) {
926 EXPECT_THAT(1.0, 1.0);
927 EXPECT_THAT(std::string(), "");
930 TEST(ExpectThat
, TakesFunctions
) {
932 static void Func() {}
934 void (*func
)() = Helper::Func
;
935 EXPECT_THAT(func
, Helper::Func
);
936 EXPECT_THAT(func
, &Helper::Func
);
939 // Tests that A<T>() matches any value of type T.
940 TEST(ATest
, MatchesAnyValue
) {
941 // Tests a matcher for a value type.
942 Matcher
<double> m1
= A
<double>();
943 EXPECT_TRUE(m1
.Matches(91.43));
944 EXPECT_TRUE(m1
.Matches(-15.32));
946 // Tests a matcher for a reference type.
949 Matcher
<int&> m2
= A
<int&>();
950 EXPECT_TRUE(m2
.Matches(a
));
951 EXPECT_TRUE(m2
.Matches(b
));
954 TEST(ATest
, WorksForDerivedClass
) {
957 EXPECT_THAT(&base
, A
<Base
*>());
958 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
959 EXPECT_THAT(&derived
, A
<Base
*>());
960 EXPECT_THAT(&derived
, A
<Derived
*>());
963 // Tests that A<T>() describes itself properly.
964 TEST(ATest
, CanDescribeSelf
) {
965 EXPECT_EQ("is anything", Describe(A
<bool>()));
968 // Tests that An<T>() matches any value of type T.
969 TEST(AnTest
, MatchesAnyValue
) {
970 // Tests a matcher for a value type.
971 Matcher
<int> m1
= An
<int>();
972 EXPECT_TRUE(m1
.Matches(9143));
973 EXPECT_TRUE(m1
.Matches(-1532));
975 // Tests a matcher for a reference type.
978 Matcher
<int&> m2
= An
<int&>();
979 EXPECT_TRUE(m2
.Matches(a
));
980 EXPECT_TRUE(m2
.Matches(b
));
983 // Tests that An<T>() describes itself properly.
984 TEST(AnTest
, CanDescribeSelf
) {
985 EXPECT_EQ("is anything", Describe(An
<int>()));
988 // Tests that _ can be used as a matcher for any type and matches any
989 // value of that type.
990 TEST(UnderscoreTest
, MatchesAnyValue
) {
991 // Uses _ as a matcher for a value type.
993 EXPECT_TRUE(m1
.Matches(123));
994 EXPECT_TRUE(m1
.Matches(-242));
996 // Uses _ as a matcher for a reference type.
999 Matcher
<const bool&> m2
= _
;
1000 EXPECT_TRUE(m2
.Matches(a
));
1001 EXPECT_TRUE(m2
.Matches(b
));
1004 // Tests that _ describes itself properly.
1005 TEST(UnderscoreTest
, CanDescribeSelf
) {
1007 EXPECT_EQ("is anything", Describe(m
));
1010 // Tests that Eq(x) matches any value equal to x.
1011 TEST(EqTest
, MatchesEqualValue
) {
1012 // 2 C-strings with same content but different addresses.
1013 const char a1
[] = "hi";
1014 const char a2
[] = "hi";
1016 Matcher
<const char*> m1
= Eq(a1
);
1017 EXPECT_TRUE(m1
.Matches(a1
));
1018 EXPECT_FALSE(m1
.Matches(a2
));
1021 // Tests that Eq(v) describes itself properly.
1025 Unprintable() : c_('a') {}
1027 bool operator==(const Unprintable
& /* rhs */) const { return true; }
1032 TEST(EqTest
, CanDescribeSelf
) {
1033 Matcher
<Unprintable
> m
= Eq(Unprintable());
1034 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m
));
1037 // Tests that Eq(v) can be used to match any type that supports
1038 // comparing with type T, where T is v's type.
1039 TEST(EqTest
, IsPolymorphic
) {
1040 Matcher
<int> m1
= Eq(1);
1041 EXPECT_TRUE(m1
.Matches(1));
1042 EXPECT_FALSE(m1
.Matches(2));
1044 Matcher
<char> m2
= Eq(1);
1045 EXPECT_TRUE(m2
.Matches('\1'));
1046 EXPECT_FALSE(m2
.Matches('a'));
1049 // Tests that TypedEq<T>(v) matches values of type T that's equal to v.
1050 TEST(TypedEqTest
, ChecksEqualityForGivenType
) {
1051 Matcher
<char> m1
= TypedEq
<char>('a');
1052 EXPECT_TRUE(m1
.Matches('a'));
1053 EXPECT_FALSE(m1
.Matches('b'));
1055 Matcher
<int> m2
= TypedEq
<int>(6);
1056 EXPECT_TRUE(m2
.Matches(6));
1057 EXPECT_FALSE(m2
.Matches(7));
1060 // Tests that TypedEq(v) describes itself properly.
1061 TEST(TypedEqTest
, CanDescribeSelf
) {
1062 EXPECT_EQ("is equal to 2", Describe(TypedEq
<int>(2)));
1065 // Tests that TypedEq<T>(v) has type Matcher<T>.
1067 // Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
1068 // is a "bare" type (i.e. not in the form of const U or U&). If v's
1069 // type is not T, the compiler will generate a message about
1070 // "undefined reference".
1071 template <typename T
>
1073 static bool IsTypeOf(const T
& /* v */) { return true; }
1075 template <typename T2
>
1076 static void IsTypeOf(T2 v
);
1079 TEST(TypedEqTest
, HasSpecifiedType
) {
1080 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
1081 Type
<Matcher
<int> >::IsTypeOf(TypedEq
<int>(5));
1082 Type
<Matcher
<double> >::IsTypeOf(TypedEq
<double>(5));
1085 // Tests that Ge(v) matches anything >= v.
1086 TEST(GeTest
, ImplementsGreaterThanOrEqual
) {
1087 Matcher
<int> m1
= Ge(0);
1088 EXPECT_TRUE(m1
.Matches(1));
1089 EXPECT_TRUE(m1
.Matches(0));
1090 EXPECT_FALSE(m1
.Matches(-1));
1093 // Tests that Ge(v) describes itself properly.
1094 TEST(GeTest
, CanDescribeSelf
) {
1095 Matcher
<int> m
= Ge(5);
1096 EXPECT_EQ("is >= 5", Describe(m
));
1099 // Tests that Gt(v) matches anything > v.
1100 TEST(GtTest
, ImplementsGreaterThan
) {
1101 Matcher
<double> m1
= Gt(0);
1102 EXPECT_TRUE(m1
.Matches(1.0));
1103 EXPECT_FALSE(m1
.Matches(0.0));
1104 EXPECT_FALSE(m1
.Matches(-1.0));
1107 // Tests that Gt(v) describes itself properly.
1108 TEST(GtTest
, CanDescribeSelf
) {
1109 Matcher
<int> m
= Gt(5);
1110 EXPECT_EQ("is > 5", Describe(m
));
1113 // Tests that Le(v) matches anything <= v.
1114 TEST(LeTest
, ImplementsLessThanOrEqual
) {
1115 Matcher
<char> m1
= Le('b');
1116 EXPECT_TRUE(m1
.Matches('a'));
1117 EXPECT_TRUE(m1
.Matches('b'));
1118 EXPECT_FALSE(m1
.Matches('c'));
1121 // Tests that Le(v) describes itself properly.
1122 TEST(LeTest
, CanDescribeSelf
) {
1123 Matcher
<int> m
= Le(5);
1124 EXPECT_EQ("is <= 5", Describe(m
));
1127 // Tests that Lt(v) matches anything < v.
1128 TEST(LtTest
, ImplementsLessThan
) {
1129 Matcher
<const std::string
&> m1
= Lt("Hello");
1130 EXPECT_TRUE(m1
.Matches("Abc"));
1131 EXPECT_FALSE(m1
.Matches("Hello"));
1132 EXPECT_FALSE(m1
.Matches("Hello, world!"));
1135 // Tests that Lt(v) describes itself properly.
1136 TEST(LtTest
, CanDescribeSelf
) {
1137 Matcher
<int> m
= Lt(5);
1138 EXPECT_EQ("is < 5", Describe(m
));
1141 // Tests that Ne(v) matches anything != v.
1142 TEST(NeTest
, ImplementsNotEqual
) {
1143 Matcher
<int> m1
= Ne(0);
1144 EXPECT_TRUE(m1
.Matches(1));
1145 EXPECT_TRUE(m1
.Matches(-1));
1146 EXPECT_FALSE(m1
.Matches(0));
1149 // Tests that Ne(v) describes itself properly.
1150 TEST(NeTest
, CanDescribeSelf
) {
1151 Matcher
<int> m
= Ne(5);
1152 EXPECT_EQ("isn't equal to 5", Describe(m
));
1155 // Tests that IsNull() matches any NULL pointer of any type.
1156 TEST(IsNullTest
, MatchesNullPointer
) {
1157 Matcher
<int*> m1
= IsNull();
1160 EXPECT_TRUE(m1
.Matches(p1
));
1161 EXPECT_FALSE(m1
.Matches(&n
));
1163 Matcher
<const char*> m2
= IsNull();
1164 const char* p2
= NULL
;
1165 EXPECT_TRUE(m2
.Matches(p2
));
1166 EXPECT_FALSE(m2
.Matches("hi"));
1168 #if !GTEST_OS_SYMBIAN
1169 // Nokia's Symbian compiler generates:
1170 // gmock-matchers.h: ambiguous access to overloaded function
1171 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
1172 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
1173 // MatcherInterface<void *> *)'
1174 // gmock-matchers.h: (point of instantiation: 'testing::
1175 // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
1176 // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc
1177 Matcher
<void*> m3
= IsNull();
1179 EXPECT_TRUE(m3
.Matches(p3
));
1180 EXPECT_FALSE(m3
.Matches(reinterpret_cast<void*>(0xbeef)));
1184 TEST(IsNullTest
, LinkedPtr
) {
1185 const Matcher
<linked_ptr
<int> > m
= IsNull();
1186 const linked_ptr
<int> null_p
;
1187 const linked_ptr
<int> non_null_p(new int);
1189 EXPECT_TRUE(m
.Matches(null_p
));
1190 EXPECT_FALSE(m
.Matches(non_null_p
));
1193 TEST(IsNullTest
, ReferenceToConstLinkedPtr
) {
1194 const Matcher
<const linked_ptr
<double>&> m
= IsNull();
1195 const linked_ptr
<double> null_p
;
1196 const linked_ptr
<double> non_null_p(new double);
1198 EXPECT_TRUE(m
.Matches(null_p
));
1199 EXPECT_FALSE(m
.Matches(non_null_p
));
1202 #if GTEST_LANG_CXX11
1203 TEST(IsNullTest
, StdFunction
) {
1204 const Matcher
<std::function
<void()>> m
= IsNull();
1206 EXPECT_TRUE(m
.Matches(std::function
<void()>()));
1207 EXPECT_FALSE(m
.Matches([]{}));
1209 #endif // GTEST_LANG_CXX11
1211 // Tests that IsNull() describes itself properly.
1212 TEST(IsNullTest
, CanDescribeSelf
) {
1213 Matcher
<int*> m
= IsNull();
1214 EXPECT_EQ("is NULL", Describe(m
));
1215 EXPECT_EQ("isn't NULL", DescribeNegation(m
));
1218 // Tests that NotNull() matches any non-NULL pointer of any type.
1219 TEST(NotNullTest
, MatchesNonNullPointer
) {
1220 Matcher
<int*> m1
= NotNull();
1223 EXPECT_FALSE(m1
.Matches(p1
));
1224 EXPECT_TRUE(m1
.Matches(&n
));
1226 Matcher
<const char*> m2
= NotNull();
1227 const char* p2
= NULL
;
1228 EXPECT_FALSE(m2
.Matches(p2
));
1229 EXPECT_TRUE(m2
.Matches("hi"));
1232 TEST(NotNullTest
, LinkedPtr
) {
1233 const Matcher
<linked_ptr
<int> > m
= NotNull();
1234 const linked_ptr
<int> null_p
;
1235 const linked_ptr
<int> non_null_p(new int);
1237 EXPECT_FALSE(m
.Matches(null_p
));
1238 EXPECT_TRUE(m
.Matches(non_null_p
));
1241 TEST(NotNullTest
, ReferenceToConstLinkedPtr
) {
1242 const Matcher
<const linked_ptr
<double>&> m
= NotNull();
1243 const linked_ptr
<double> null_p
;
1244 const linked_ptr
<double> non_null_p(new double);
1246 EXPECT_FALSE(m
.Matches(null_p
));
1247 EXPECT_TRUE(m
.Matches(non_null_p
));
1250 #if GTEST_LANG_CXX11
1251 TEST(NotNullTest
, StdFunction
) {
1252 const Matcher
<std::function
<void()>> m
= NotNull();
1254 EXPECT_TRUE(m
.Matches([]{}));
1255 EXPECT_FALSE(m
.Matches(std::function
<void()>()));
1257 #endif // GTEST_LANG_CXX11
1259 // Tests that NotNull() describes itself properly.
1260 TEST(NotNullTest
, CanDescribeSelf
) {
1261 Matcher
<int*> m
= NotNull();
1262 EXPECT_EQ("isn't NULL", Describe(m
));
1265 // Tests that Ref(variable) matches an argument that references
1267 TEST(RefTest
, MatchesSameVariable
) {
1270 Matcher
<int&> m
= Ref(a
);
1271 EXPECT_TRUE(m
.Matches(a
));
1272 EXPECT_FALSE(m
.Matches(b
));
1275 // Tests that Ref(variable) describes itself properly.
1276 TEST(RefTest
, CanDescribeSelf
) {
1278 Matcher
<int&> m
= Ref(n
);
1280 ss
<< "references the variable @" << &n
<< " 5";
1281 EXPECT_EQ(ss
.str(), Describe(m
));
1284 // Test that Ref(non_const_varialbe) can be used as a matcher for a
1286 TEST(RefTest
, CanBeUsedAsMatcherForConstReference
) {
1289 Matcher
<const int&> m
= Ref(a
);
1290 EXPECT_TRUE(m
.Matches(a
));
1291 EXPECT_FALSE(m
.Matches(b
));
1294 // Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1295 // used wherever Ref(base) can be used (Ref(derived) is a sub-type
1296 // of Ref(base), but not vice versa.
1298 TEST(RefTest
, IsCovariant
) {
1301 Matcher
<const Base
&> m1
= Ref(base
);
1302 EXPECT_TRUE(m1
.Matches(base
));
1303 EXPECT_FALSE(m1
.Matches(base2
));
1304 EXPECT_FALSE(m1
.Matches(derived
));
1307 EXPECT_TRUE(m1
.Matches(derived
));
1308 EXPECT_FALSE(m1
.Matches(base
));
1309 EXPECT_FALSE(m1
.Matches(base2
));
1312 TEST(RefTest
, ExplainsResult
) {
1314 EXPECT_THAT(Explain(Matcher
<const int&>(Ref(n
)), n
),
1315 StartsWith("which is located @"));
1318 EXPECT_THAT(Explain(Matcher
<const int&>(Ref(n
)), m
),
1319 StartsWith("which is located @"));
1322 // Tests string comparison matchers.
1324 TEST(StrEqTest
, MatchesEqualString
) {
1325 Matcher
<const char*> m
= StrEq(std::string("Hello"));
1326 EXPECT_TRUE(m
.Matches("Hello"));
1327 EXPECT_FALSE(m
.Matches("hello"));
1328 EXPECT_FALSE(m
.Matches(NULL
));
1330 Matcher
<const std::string
&> m2
= StrEq("Hello");
1331 EXPECT_TRUE(m2
.Matches("Hello"));
1332 EXPECT_FALSE(m2
.Matches("Hi"));
1335 Matcher
<const absl::string_view
&> m3
= StrEq("Hello");
1336 EXPECT_TRUE(m3
.Matches(absl::string_view("Hello")));
1337 EXPECT_FALSE(m3
.Matches(absl::string_view("hello")));
1338 EXPECT_FALSE(m3
.Matches(absl::string_view()));
1339 #endif // GTEST_HAS_ABSL
1342 TEST(StrEqTest
, CanDescribeSelf
) {
1343 Matcher
<std::string
> m
= StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1344 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
1347 std::string
str("01204500800");
1349 Matcher
<std::string
> m2
= StrEq(str
);
1350 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2
));
1351 str
[0] = str
[6] = str
[7] = str
[9] = str
[10] = '\0';
1352 Matcher
<std::string
> m3
= StrEq(str
);
1353 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3
));
1356 TEST(StrNeTest
, MatchesUnequalString
) {
1357 Matcher
<const char*> m
= StrNe("Hello");
1358 EXPECT_TRUE(m
.Matches(""));
1359 EXPECT_TRUE(m
.Matches(NULL
));
1360 EXPECT_FALSE(m
.Matches("Hello"));
1362 Matcher
<std::string
> m2
= StrNe(std::string("Hello"));
1363 EXPECT_TRUE(m2
.Matches("hello"));
1364 EXPECT_FALSE(m2
.Matches("Hello"));
1367 Matcher
<const absl::string_view
> m3
= StrNe("Hello");
1368 EXPECT_TRUE(m3
.Matches(absl::string_view("")));
1369 EXPECT_TRUE(m3
.Matches(absl::string_view()));
1370 EXPECT_FALSE(m3
.Matches(absl::string_view("Hello")));
1371 #endif // GTEST_HAS_ABSL
1374 TEST(StrNeTest
, CanDescribeSelf
) {
1375 Matcher
<const char*> m
= StrNe("Hi");
1376 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m
));
1379 TEST(StrCaseEqTest
, MatchesEqualStringIgnoringCase
) {
1380 Matcher
<const char*> m
= StrCaseEq(std::string("Hello"));
1381 EXPECT_TRUE(m
.Matches("Hello"));
1382 EXPECT_TRUE(m
.Matches("hello"));
1383 EXPECT_FALSE(m
.Matches("Hi"));
1384 EXPECT_FALSE(m
.Matches(NULL
));
1386 Matcher
<const std::string
&> m2
= StrCaseEq("Hello");
1387 EXPECT_TRUE(m2
.Matches("hello"));
1388 EXPECT_FALSE(m2
.Matches("Hi"));
1391 Matcher
<const absl::string_view
&> m3
= StrCaseEq(std::string("Hello"));
1392 EXPECT_TRUE(m3
.Matches(absl::string_view("Hello")));
1393 EXPECT_TRUE(m3
.Matches(absl::string_view("hello")));
1394 EXPECT_FALSE(m3
.Matches(absl::string_view("Hi")));
1395 EXPECT_FALSE(m3
.Matches(absl::string_view()));
1396 #endif // GTEST_HAS_ABSL
1399 TEST(StrCaseEqTest
, MatchesEqualStringWith0IgnoringCase
) {
1400 std::string
str1("oabocdooeoo");
1401 std::string
str2("OABOCDOOEOO");
1402 Matcher
<const std::string
&> m0
= StrCaseEq(str1
);
1403 EXPECT_FALSE(m0
.Matches(str2
+ std::string(1, '\0')));
1405 str1
[3] = str2
[3] = '\0';
1406 Matcher
<const std::string
&> m1
= StrCaseEq(str1
);
1407 EXPECT_TRUE(m1
.Matches(str2
));
1409 str1
[0] = str1
[6] = str1
[7] = str1
[10] = '\0';
1410 str2
[0] = str2
[6] = str2
[7] = str2
[10] = '\0';
1411 Matcher
<const std::string
&> m2
= StrCaseEq(str1
);
1412 str1
[9] = str2
[9] = '\0';
1413 EXPECT_FALSE(m2
.Matches(str2
));
1415 Matcher
<const std::string
&> m3
= StrCaseEq(str1
);
1416 EXPECT_TRUE(m3
.Matches(str2
));
1418 EXPECT_FALSE(m3
.Matches(str2
+ "x"));
1419 str2
.append(1, '\0');
1420 EXPECT_FALSE(m3
.Matches(str2
));
1421 EXPECT_FALSE(m3
.Matches(std::string(str2
, 0, 9)));
1424 TEST(StrCaseEqTest
, CanDescribeSelf
) {
1425 Matcher
<std::string
> m
= StrCaseEq("Hi");
1426 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m
));
1429 TEST(StrCaseNeTest
, MatchesUnequalStringIgnoringCase
) {
1430 Matcher
<const char*> m
= StrCaseNe("Hello");
1431 EXPECT_TRUE(m
.Matches("Hi"));
1432 EXPECT_TRUE(m
.Matches(NULL
));
1433 EXPECT_FALSE(m
.Matches("Hello"));
1434 EXPECT_FALSE(m
.Matches("hello"));
1436 Matcher
<std::string
> m2
= StrCaseNe(std::string("Hello"));
1437 EXPECT_TRUE(m2
.Matches(""));
1438 EXPECT_FALSE(m2
.Matches("Hello"));
1441 Matcher
<const absl::string_view
> m3
= StrCaseNe("Hello");
1442 EXPECT_TRUE(m3
.Matches(absl::string_view("Hi")));
1443 EXPECT_TRUE(m3
.Matches(absl::string_view()));
1444 EXPECT_FALSE(m3
.Matches(absl::string_view("Hello")));
1445 EXPECT_FALSE(m3
.Matches(absl::string_view("hello")));
1446 #endif // GTEST_HAS_ABSL
1449 TEST(StrCaseNeTest
, CanDescribeSelf
) {
1450 Matcher
<const char*> m
= StrCaseNe("Hi");
1451 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m
));
1454 // Tests that HasSubstr() works for matching string-typed values.
1455 TEST(HasSubstrTest
, WorksForStringClasses
) {
1456 const Matcher
<std::string
> m1
= HasSubstr("foo");
1457 EXPECT_TRUE(m1
.Matches(std::string("I love food.")));
1458 EXPECT_FALSE(m1
.Matches(std::string("tofo")));
1460 const Matcher
<const std::string
&> m2
= HasSubstr("foo");
1461 EXPECT_TRUE(m2
.Matches(std::string("I love food.")));
1462 EXPECT_FALSE(m2
.Matches(std::string("tofo")));
1465 // Tests that HasSubstr() works for matching C-string-typed values.
1466 TEST(HasSubstrTest
, WorksForCStrings
) {
1467 const Matcher
<char*> m1
= HasSubstr("foo");
1468 EXPECT_TRUE(m1
.Matches(const_cast<char*>("I love food.")));
1469 EXPECT_FALSE(m1
.Matches(const_cast<char*>("tofo")));
1470 EXPECT_FALSE(m1
.Matches(NULL
));
1472 const Matcher
<const char*> m2
= HasSubstr("foo");
1473 EXPECT_TRUE(m2
.Matches("I love food."));
1474 EXPECT_FALSE(m2
.Matches("tofo"));
1475 EXPECT_FALSE(m2
.Matches(NULL
));
1479 // Tests that HasSubstr() works for matching absl::string_view-typed values.
1480 TEST(HasSubstrTest
, WorksForStringViewClasses
) {
1481 const Matcher
<absl::string_view
> m1
= HasSubstr("foo");
1482 EXPECT_TRUE(m1
.Matches(absl::string_view("I love food.")));
1483 EXPECT_FALSE(m1
.Matches(absl::string_view("tofo")));
1484 EXPECT_FALSE(m1
.Matches(absl::string_view()));
1486 const Matcher
<const absl::string_view
&> m2
= HasSubstr("foo");
1487 EXPECT_TRUE(m2
.Matches(absl::string_view("I love food.")));
1488 EXPECT_FALSE(m2
.Matches(absl::string_view("tofo")));
1489 EXPECT_FALSE(m2
.Matches(absl::string_view()));
1491 const Matcher
<const absl::string_view
&> m3
= HasSubstr("");
1492 EXPECT_TRUE(m3
.Matches(absl::string_view("foo")));
1493 EXPECT_FALSE(m3
.Matches(absl::string_view()));
1495 #endif // GTEST_HAS_ABSL
1497 // Tests that HasSubstr(s) describes itself properly.
1498 TEST(HasSubstrTest
, CanDescribeSelf
) {
1499 Matcher
<std::string
> m
= HasSubstr("foo\n\"");
1500 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m
));
1503 TEST(KeyTest
, CanDescribeSelf
) {
1504 Matcher
<const pair
<std::string
, int>&> m
= Key("foo");
1505 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m
));
1506 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m
));
1509 TEST(KeyTest
, ExplainsResult
) {
1510 Matcher
<pair
<int, bool> > m
= Key(GreaterThan(10));
1511 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1512 Explain(m
, make_pair(5, true)));
1513 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1514 Explain(m
, make_pair(15, true)));
1517 TEST(KeyTest
, MatchesCorrectly
) {
1518 pair
<int, std::string
> p(25, "foo");
1519 EXPECT_THAT(p
, Key(25));
1520 EXPECT_THAT(p
, Not(Key(42)));
1521 EXPECT_THAT(p
, Key(Ge(20)));
1522 EXPECT_THAT(p
, Not(Key(Lt(25))));
1525 #if GTEST_LANG_CXX11
1529 struct PairWithGet
{
1532 using first_type
= int;
1533 using second_type
= string
;
1535 const int& GetImpl(Tag
<0>) const { return member_1
; }
1536 const string
& GetImpl(Tag
<1>) const { return member_2
; }
1539 auto get(const PairWithGet
& value
) -> decltype(value
.GetImpl(Tag
<I
>())) {
1540 return value
.GetImpl(Tag
<I
>());
1542 TEST(PairTest
, MatchesPairWithGetCorrectly
) {
1543 PairWithGet p
{25, "foo"};
1544 EXPECT_THAT(p
, Key(25));
1545 EXPECT_THAT(p
, Not(Key(42)));
1546 EXPECT_THAT(p
, Key(Ge(20)));
1547 EXPECT_THAT(p
, Not(Key(Lt(25))));
1549 std::vector
<PairWithGet
> v
= {{11, "Foo"}, {29, "gMockIsBestMock"}};
1550 EXPECT_THAT(v
, Contains(Key(29)));
1552 #endif // GTEST_LANG_CXX11
1554 TEST(KeyTest
, SafelyCastsInnerMatcher
) {
1555 Matcher
<int> is_positive
= Gt(0);
1556 Matcher
<int> is_negative
= Lt(0);
1557 pair
<char, bool> p('a', true);
1558 EXPECT_THAT(p
, Key(is_positive
));
1559 EXPECT_THAT(p
, Not(Key(is_negative
)));
1562 TEST(KeyTest
, InsideContainsUsingMap
) {
1563 map
<int, char> container
;
1564 container
.insert(make_pair(1, 'a'));
1565 container
.insert(make_pair(2, 'b'));
1566 container
.insert(make_pair(4, 'c'));
1567 EXPECT_THAT(container
, Contains(Key(1)));
1568 EXPECT_THAT(container
, Not(Contains(Key(3))));
1571 TEST(KeyTest
, InsideContainsUsingMultimap
) {
1572 multimap
<int, char> container
;
1573 container
.insert(make_pair(1, 'a'));
1574 container
.insert(make_pair(2, 'b'));
1575 container
.insert(make_pair(4, 'c'));
1577 EXPECT_THAT(container
, Not(Contains(Key(25))));
1578 container
.insert(make_pair(25, 'd'));
1579 EXPECT_THAT(container
, Contains(Key(25)));
1580 container
.insert(make_pair(25, 'e'));
1581 EXPECT_THAT(container
, Contains(Key(25)));
1583 EXPECT_THAT(container
, Contains(Key(1)));
1584 EXPECT_THAT(container
, Not(Contains(Key(3))));
1587 TEST(PairTest
, Typing
) {
1588 // Test verifies the following type conversions can be compiled.
1589 Matcher
<const pair
<const char*, int>&> m1
= Pair("foo", 42);
1590 Matcher
<const pair
<const char*, int> > m2
= Pair("foo", 42);
1591 Matcher
<pair
<const char*, int> > m3
= Pair("foo", 42);
1593 Matcher
<pair
<int, const std::string
> > m4
= Pair(25, "42");
1594 Matcher
<pair
<const std::string
, int> > m5
= Pair("25", 42);
1597 TEST(PairTest
, CanDescribeSelf
) {
1598 Matcher
<const pair
<std::string
, int>&> m1
= Pair("foo", 42);
1599 EXPECT_EQ("has a first field that is equal to \"foo\""
1600 ", and has a second field that is equal to 42",
1602 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1603 ", or has a second field that isn't equal to 42",
1604 DescribeNegation(m1
));
1605 // Double and triple negation (1 or 2 times not and description of negation).
1606 Matcher
<const pair
<int, int>&> m2
= Not(Pair(Not(13), 42));
1607 EXPECT_EQ("has a first field that isn't equal to 13"
1608 ", and has a second field that is equal to 42",
1609 DescribeNegation(m2
));
1612 TEST(PairTest
, CanExplainMatchResultTo
) {
1613 // If neither field matches, Pair() should explain about the first
1615 const Matcher
<pair
<int, int> > m
= Pair(GreaterThan(0), GreaterThan(0));
1616 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1617 Explain(m
, make_pair(-1, -2)));
1619 // If the first field matches but the second doesn't, Pair() should
1620 // explain about the second field.
1621 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
1622 Explain(m
, make_pair(1, -2)));
1624 // If the first field doesn't match but the second does, Pair()
1625 // should explain about the first field.
1626 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1627 Explain(m
, make_pair(-1, 2)));
1629 // If both fields match, Pair() should explain about them both.
1630 EXPECT_EQ("whose both fields match, where the first field is a value "
1631 "which is 1 more than 0, and the second field is a value "
1632 "which is 2 more than 0",
1633 Explain(m
, make_pair(1, 2)));
1635 // If only the first match has an explanation, only this explanation should
1637 const Matcher
<pair
<int, int> > explain_first
= Pair(GreaterThan(0), 0);
1638 EXPECT_EQ("whose both fields match, where the first field is a value "
1639 "which is 1 more than 0",
1640 Explain(explain_first
, make_pair(1, 0)));
1642 // If only the second match has an explanation, only this explanation should
1644 const Matcher
<pair
<int, int> > explain_second
= Pair(0, GreaterThan(0));
1645 EXPECT_EQ("whose both fields match, where the second field is a value "
1646 "which is 1 more than 0",
1647 Explain(explain_second
, make_pair(0, 1)));
1650 TEST(PairTest
, MatchesCorrectly
) {
1651 pair
<int, std::string
> p(25, "foo");
1653 // Both fields match.
1654 EXPECT_THAT(p
, Pair(25, "foo"));
1655 EXPECT_THAT(p
, Pair(Ge(20), HasSubstr("o")));
1657 // 'first' doesnt' match, but 'second' matches.
1658 EXPECT_THAT(p
, Not(Pair(42, "foo")));
1659 EXPECT_THAT(p
, Not(Pair(Lt(25), "foo")));
1661 // 'first' matches, but 'second' doesn't match.
1662 EXPECT_THAT(p
, Not(Pair(25, "bar")));
1663 EXPECT_THAT(p
, Not(Pair(25, Not("foo"))));
1665 // Neither field matches.
1666 EXPECT_THAT(p
, Not(Pair(13, "bar")));
1667 EXPECT_THAT(p
, Not(Pair(Lt(13), HasSubstr("a"))));
1670 TEST(PairTest
, SafelyCastsInnerMatchers
) {
1671 Matcher
<int> is_positive
= Gt(0);
1672 Matcher
<int> is_negative
= Lt(0);
1673 pair
<char, bool> p('a', true);
1674 EXPECT_THAT(p
, Pair(is_positive
, _
));
1675 EXPECT_THAT(p
, Not(Pair(is_negative
, _
)));
1676 EXPECT_THAT(p
, Pair(_
, is_positive
));
1677 EXPECT_THAT(p
, Not(Pair(_
, is_negative
)));
1680 TEST(PairTest
, InsideContainsUsingMap
) {
1681 map
<int, char> container
;
1682 container
.insert(make_pair(1, 'a'));
1683 container
.insert(make_pair(2, 'b'));
1684 container
.insert(make_pair(4, 'c'));
1685 EXPECT_THAT(container
, Contains(Pair(1, 'a')));
1686 EXPECT_THAT(container
, Contains(Pair(1, _
)));
1687 EXPECT_THAT(container
, Contains(Pair(_
, 'a')));
1688 EXPECT_THAT(container
, Not(Contains(Pair(3, _
))));
1691 #if GTEST_LANG_CXX11
1692 TEST(PairTest
, UseGetInsteadOfMembers
) {
1693 PairWithGet pair
{7, "ABC"};
1694 EXPECT_THAT(pair
, Pair(7, "ABC"));
1695 EXPECT_THAT(pair
, Pair(Ge(7), HasSubstr("AB")));
1696 EXPECT_THAT(pair
, Not(Pair(Lt(7), "ABC")));
1698 std::vector
<PairWithGet
> v
= {{11, "Foo"}, {29, "gMockIsBestMock"}};
1699 EXPECT_THAT(v
, ElementsAre(Pair(11, string("Foo")), Pair(Ge(10), Not(""))));
1701 #endif // GTEST_LANG_CXX11
1703 // Tests StartsWith(s).
1705 TEST(StartsWithTest
, MatchesStringWithGivenPrefix
) {
1706 const Matcher
<const char*> m1
= StartsWith(std::string(""));
1707 EXPECT_TRUE(m1
.Matches("Hi"));
1708 EXPECT_TRUE(m1
.Matches(""));
1709 EXPECT_FALSE(m1
.Matches(NULL
));
1711 const Matcher
<const std::string
&> m2
= StartsWith("Hi");
1712 EXPECT_TRUE(m2
.Matches("Hi"));
1713 EXPECT_TRUE(m2
.Matches("Hi Hi!"));
1714 EXPECT_TRUE(m2
.Matches("High"));
1715 EXPECT_FALSE(m2
.Matches("H"));
1716 EXPECT_FALSE(m2
.Matches(" Hi"));
1719 TEST(StartsWithTest
, CanDescribeSelf
) {
1720 Matcher
<const std::string
> m
= StartsWith("Hi");
1721 EXPECT_EQ("starts with \"Hi\"", Describe(m
));
1724 // Tests EndsWith(s).
1726 TEST(EndsWithTest
, MatchesStringWithGivenSuffix
) {
1727 const Matcher
<const char*> m1
= EndsWith("");
1728 EXPECT_TRUE(m1
.Matches("Hi"));
1729 EXPECT_TRUE(m1
.Matches(""));
1730 EXPECT_FALSE(m1
.Matches(NULL
));
1732 const Matcher
<const std::string
&> m2
= EndsWith(std::string("Hi"));
1733 EXPECT_TRUE(m2
.Matches("Hi"));
1734 EXPECT_TRUE(m2
.Matches("Wow Hi Hi"));
1735 EXPECT_TRUE(m2
.Matches("Super Hi"));
1736 EXPECT_FALSE(m2
.Matches("i"));
1737 EXPECT_FALSE(m2
.Matches("Hi "));
1739 #if GTEST_HAS_GLOBAL_STRING
1740 const Matcher
<const ::string
&> m3
= EndsWith(::string("Hi"));
1741 EXPECT_TRUE(m3
.Matches("Hi"));
1742 EXPECT_TRUE(m3
.Matches("Wow Hi Hi"));
1743 EXPECT_TRUE(m3
.Matches("Super Hi"));
1744 EXPECT_FALSE(m3
.Matches("i"));
1745 EXPECT_FALSE(m3
.Matches("Hi "));
1746 #endif // GTEST_HAS_GLOBAL_STRING
1749 const Matcher
<const absl::string_view
&> m4
= EndsWith("");
1750 EXPECT_TRUE(m4
.Matches("Hi"));
1751 EXPECT_TRUE(m4
.Matches(""));
1752 // Default-constructed absl::string_view should not match anything, in order
1753 // to distinguish it from an empty string.
1754 EXPECT_FALSE(m4
.Matches(absl::string_view()));
1755 #endif // GTEST_HAS_ABSL
1758 TEST(EndsWithTest
, CanDescribeSelf
) {
1759 Matcher
<const std::string
> m
= EndsWith("Hi");
1760 EXPECT_EQ("ends with \"Hi\"", Describe(m
));
1763 // Tests MatchesRegex().
1765 TEST(MatchesRegexTest
, MatchesStringMatchingGivenRegex
) {
1766 const Matcher
<const char*> m1
= MatchesRegex("a.*z");
1767 EXPECT_TRUE(m1
.Matches("az"));
1768 EXPECT_TRUE(m1
.Matches("abcz"));
1769 EXPECT_FALSE(m1
.Matches(NULL
));
1771 const Matcher
<const std::string
&> m2
= MatchesRegex(new RE("a.*z"));
1772 EXPECT_TRUE(m2
.Matches("azbz"));
1773 EXPECT_FALSE(m2
.Matches("az1"));
1774 EXPECT_FALSE(m2
.Matches("1az"));
1777 const Matcher
<const absl::string_view
&> m3
= MatchesRegex("a.*z");
1778 EXPECT_TRUE(m3
.Matches(absl::string_view("az")));
1779 EXPECT_TRUE(m3
.Matches(absl::string_view("abcz")));
1780 EXPECT_FALSE(m3
.Matches(absl::string_view("1az")));
1781 // Default-constructed absl::string_view should not match anything, in order
1782 // to distinguish it from an empty string.
1783 EXPECT_FALSE(m3
.Matches(absl::string_view()));
1784 const Matcher
<const absl::string_view
&> m4
= MatchesRegex("");
1785 EXPECT_FALSE(m4
.Matches(absl::string_view()));
1786 #endif // GTEST_HAS_ABSL
1789 TEST(MatchesRegexTest
, CanDescribeSelf
) {
1790 Matcher
<const std::string
> m1
= MatchesRegex(std::string("Hi.*"));
1791 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1
));
1793 Matcher
<const char*> m2
= MatchesRegex(new RE("a.*"));
1794 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2
));
1797 Matcher
<const absl::string_view
> m3
= MatchesRegex(new RE("0.*"));
1798 EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3
));
1799 #endif // GTEST_HAS_ABSL
1802 // Tests ContainsRegex().
1804 TEST(ContainsRegexTest
, MatchesStringContainingGivenRegex
) {
1805 const Matcher
<const char*> m1
= ContainsRegex(std::string("a.*z"));
1806 EXPECT_TRUE(m1
.Matches("az"));
1807 EXPECT_TRUE(m1
.Matches("0abcz1"));
1808 EXPECT_FALSE(m1
.Matches(NULL
));
1810 const Matcher
<const std::string
&> m2
= ContainsRegex(new RE("a.*z"));
1811 EXPECT_TRUE(m2
.Matches("azbz"));
1812 EXPECT_TRUE(m2
.Matches("az1"));
1813 EXPECT_FALSE(m2
.Matches("1a"));
1816 const Matcher
<const absl::string_view
&> m3
= ContainsRegex(new RE("a.*z"));
1817 EXPECT_TRUE(m3
.Matches(absl::string_view("azbz")));
1818 EXPECT_TRUE(m3
.Matches(absl::string_view("az1")));
1819 EXPECT_FALSE(m3
.Matches(absl::string_view("1a")));
1820 // Default-constructed absl::string_view should not match anything, in order
1821 // to distinguish it from an empty string.
1822 EXPECT_FALSE(m3
.Matches(absl::string_view()));
1823 const Matcher
<const absl::string_view
&> m4
= ContainsRegex("");
1824 EXPECT_FALSE(m4
.Matches(absl::string_view()));
1825 #endif // GTEST_HAS_ABSL
1828 TEST(ContainsRegexTest
, CanDescribeSelf
) {
1829 Matcher
<const std::string
> m1
= ContainsRegex("Hi.*");
1830 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1
));
1832 Matcher
<const char*> m2
= ContainsRegex(new RE("a.*"));
1833 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2
));
1836 Matcher
<const absl::string_view
> m3
= ContainsRegex(new RE("0.*"));
1837 EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3
));
1838 #endif // GTEST_HAS_ABSL
1841 // Tests for wide strings.
1842 #if GTEST_HAS_STD_WSTRING
1843 TEST(StdWideStrEqTest
, MatchesEqual
) {
1844 Matcher
<const wchar_t*> m
= StrEq(::std::wstring(L
"Hello"));
1845 EXPECT_TRUE(m
.Matches(L
"Hello"));
1846 EXPECT_FALSE(m
.Matches(L
"hello"));
1847 EXPECT_FALSE(m
.Matches(NULL
));
1849 Matcher
<const ::std::wstring
&> m2
= StrEq(L
"Hello");
1850 EXPECT_TRUE(m2
.Matches(L
"Hello"));
1851 EXPECT_FALSE(m2
.Matches(L
"Hi"));
1853 Matcher
<const ::std::wstring
&> m3
= StrEq(L
"\xD3\x576\x8D3\xC74D");
1854 EXPECT_TRUE(m3
.Matches(L
"\xD3\x576\x8D3\xC74D"));
1855 EXPECT_FALSE(m3
.Matches(L
"\xD3\x576\x8D3\xC74E"));
1857 ::std::wstring
str(L
"01204500800");
1859 Matcher
<const ::std::wstring
&> m4
= StrEq(str
);
1860 EXPECT_TRUE(m4
.Matches(str
));
1861 str
[0] = str
[6] = str
[7] = str
[9] = str
[10] = L
'\0';
1862 Matcher
<const ::std::wstring
&> m5
= StrEq(str
);
1863 EXPECT_TRUE(m5
.Matches(str
));
1866 TEST(StdWideStrEqTest
, CanDescribeSelf
) {
1867 Matcher
< ::std::wstring
> m
= StrEq(L
"Hi-\'\"?\\\a\b\f\n\r\t\v");
1868 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
1871 Matcher
< ::std::wstring
> m2
= StrEq(L
"\xD3\x576\x8D3\xC74D");
1872 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1875 ::std::wstring
str(L
"01204500800");
1877 Matcher
<const ::std::wstring
&> m4
= StrEq(str
);
1878 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4
));
1879 str
[0] = str
[6] = str
[7] = str
[9] = str
[10] = L
'\0';
1880 Matcher
<const ::std::wstring
&> m5
= StrEq(str
);
1881 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5
));
1884 TEST(StdWideStrNeTest
, MatchesUnequalString
) {
1885 Matcher
<const wchar_t*> m
= StrNe(L
"Hello");
1886 EXPECT_TRUE(m
.Matches(L
""));
1887 EXPECT_TRUE(m
.Matches(NULL
));
1888 EXPECT_FALSE(m
.Matches(L
"Hello"));
1890 Matcher
< ::std::wstring
> m2
= StrNe(::std::wstring(L
"Hello"));
1891 EXPECT_TRUE(m2
.Matches(L
"hello"));
1892 EXPECT_FALSE(m2
.Matches(L
"Hello"));
1895 TEST(StdWideStrNeTest
, CanDescribeSelf
) {
1896 Matcher
<const wchar_t*> m
= StrNe(L
"Hi");
1897 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m
));
1900 TEST(StdWideStrCaseEqTest
, MatchesEqualStringIgnoringCase
) {
1901 Matcher
<const wchar_t*> m
= StrCaseEq(::std::wstring(L
"Hello"));
1902 EXPECT_TRUE(m
.Matches(L
"Hello"));
1903 EXPECT_TRUE(m
.Matches(L
"hello"));
1904 EXPECT_FALSE(m
.Matches(L
"Hi"));
1905 EXPECT_FALSE(m
.Matches(NULL
));
1907 Matcher
<const ::std::wstring
&> m2
= StrCaseEq(L
"Hello");
1908 EXPECT_TRUE(m2
.Matches(L
"hello"));
1909 EXPECT_FALSE(m2
.Matches(L
"Hi"));
1912 TEST(StdWideStrCaseEqTest
, MatchesEqualStringWith0IgnoringCase
) {
1913 ::std::wstring
str1(L
"oabocdooeoo");
1914 ::std::wstring
str2(L
"OABOCDOOEOO");
1915 Matcher
<const ::std::wstring
&> m0
= StrCaseEq(str1
);
1916 EXPECT_FALSE(m0
.Matches(str2
+ ::std::wstring(1, L
'\0')));
1918 str1
[3] = str2
[3] = L
'\0';
1919 Matcher
<const ::std::wstring
&> m1
= StrCaseEq(str1
);
1920 EXPECT_TRUE(m1
.Matches(str2
));
1922 str1
[0] = str1
[6] = str1
[7] = str1
[10] = L
'\0';
1923 str2
[0] = str2
[6] = str2
[7] = str2
[10] = L
'\0';
1924 Matcher
<const ::std::wstring
&> m2
= StrCaseEq(str1
);
1925 str1
[9] = str2
[9] = L
'\0';
1926 EXPECT_FALSE(m2
.Matches(str2
));
1928 Matcher
<const ::std::wstring
&> m3
= StrCaseEq(str1
);
1929 EXPECT_TRUE(m3
.Matches(str2
));
1931 EXPECT_FALSE(m3
.Matches(str2
+ L
"x"));
1932 str2
.append(1, L
'\0');
1933 EXPECT_FALSE(m3
.Matches(str2
));
1934 EXPECT_FALSE(m3
.Matches(::std::wstring(str2
, 0, 9)));
1937 TEST(StdWideStrCaseEqTest
, CanDescribeSelf
) {
1938 Matcher
< ::std::wstring
> m
= StrCaseEq(L
"Hi");
1939 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m
));
1942 TEST(StdWideStrCaseNeTest
, MatchesUnequalStringIgnoringCase
) {
1943 Matcher
<const wchar_t*> m
= StrCaseNe(L
"Hello");
1944 EXPECT_TRUE(m
.Matches(L
"Hi"));
1945 EXPECT_TRUE(m
.Matches(NULL
));
1946 EXPECT_FALSE(m
.Matches(L
"Hello"));
1947 EXPECT_FALSE(m
.Matches(L
"hello"));
1949 Matcher
< ::std::wstring
> m2
= StrCaseNe(::std::wstring(L
"Hello"));
1950 EXPECT_TRUE(m2
.Matches(L
""));
1951 EXPECT_FALSE(m2
.Matches(L
"Hello"));
1954 TEST(StdWideStrCaseNeTest
, CanDescribeSelf
) {
1955 Matcher
<const wchar_t*> m
= StrCaseNe(L
"Hi");
1956 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m
));
1959 // Tests that HasSubstr() works for matching wstring-typed values.
1960 TEST(StdWideHasSubstrTest
, WorksForStringClasses
) {
1961 const Matcher
< ::std::wstring
> m1
= HasSubstr(L
"foo");
1962 EXPECT_TRUE(m1
.Matches(::std::wstring(L
"I love food.")));
1963 EXPECT_FALSE(m1
.Matches(::std::wstring(L
"tofo")));
1965 const Matcher
<const ::std::wstring
&> m2
= HasSubstr(L
"foo");
1966 EXPECT_TRUE(m2
.Matches(::std::wstring(L
"I love food.")));
1967 EXPECT_FALSE(m2
.Matches(::std::wstring(L
"tofo")));
1970 // Tests that HasSubstr() works for matching C-wide-string-typed values.
1971 TEST(StdWideHasSubstrTest
, WorksForCStrings
) {
1972 const Matcher
<wchar_t*> m1
= HasSubstr(L
"foo");
1973 EXPECT_TRUE(m1
.Matches(const_cast<wchar_t*>(L
"I love food.")));
1974 EXPECT_FALSE(m1
.Matches(const_cast<wchar_t*>(L
"tofo")));
1975 EXPECT_FALSE(m1
.Matches(NULL
));
1977 const Matcher
<const wchar_t*> m2
= HasSubstr(L
"foo");
1978 EXPECT_TRUE(m2
.Matches(L
"I love food."));
1979 EXPECT_FALSE(m2
.Matches(L
"tofo"));
1980 EXPECT_FALSE(m2
.Matches(NULL
));
1983 // Tests that HasSubstr(s) describes itself properly.
1984 TEST(StdWideHasSubstrTest
, CanDescribeSelf
) {
1985 Matcher
< ::std::wstring
> m
= HasSubstr(L
"foo\n\"");
1986 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m
));
1989 // Tests StartsWith(s).
1991 TEST(StdWideStartsWithTest
, MatchesStringWithGivenPrefix
) {
1992 const Matcher
<const wchar_t*> m1
= StartsWith(::std::wstring(L
""));
1993 EXPECT_TRUE(m1
.Matches(L
"Hi"));
1994 EXPECT_TRUE(m1
.Matches(L
""));
1995 EXPECT_FALSE(m1
.Matches(NULL
));
1997 const Matcher
<const ::std::wstring
&> m2
= StartsWith(L
"Hi");
1998 EXPECT_TRUE(m2
.Matches(L
"Hi"));
1999 EXPECT_TRUE(m2
.Matches(L
"Hi Hi!"));
2000 EXPECT_TRUE(m2
.Matches(L
"High"));
2001 EXPECT_FALSE(m2
.Matches(L
"H"));
2002 EXPECT_FALSE(m2
.Matches(L
" Hi"));
2005 TEST(StdWideStartsWithTest
, CanDescribeSelf
) {
2006 Matcher
<const ::std::wstring
> m
= StartsWith(L
"Hi");
2007 EXPECT_EQ("starts with L\"Hi\"", Describe(m
));
2010 // Tests EndsWith(s).
2012 TEST(StdWideEndsWithTest
, MatchesStringWithGivenSuffix
) {
2013 const Matcher
<const wchar_t*> m1
= EndsWith(L
"");
2014 EXPECT_TRUE(m1
.Matches(L
"Hi"));
2015 EXPECT_TRUE(m1
.Matches(L
""));
2016 EXPECT_FALSE(m1
.Matches(NULL
));
2018 const Matcher
<const ::std::wstring
&> m2
= EndsWith(::std::wstring(L
"Hi"));
2019 EXPECT_TRUE(m2
.Matches(L
"Hi"));
2020 EXPECT_TRUE(m2
.Matches(L
"Wow Hi Hi"));
2021 EXPECT_TRUE(m2
.Matches(L
"Super Hi"));
2022 EXPECT_FALSE(m2
.Matches(L
"i"));
2023 EXPECT_FALSE(m2
.Matches(L
"Hi "));
2026 TEST(StdWideEndsWithTest
, CanDescribeSelf
) {
2027 Matcher
<const ::std::wstring
> m
= EndsWith(L
"Hi");
2028 EXPECT_EQ("ends with L\"Hi\"", Describe(m
));
2031 #endif // GTEST_HAS_STD_WSTRING
2033 #if GTEST_HAS_GLOBAL_WSTRING
2034 TEST(GlobalWideStrEqTest
, MatchesEqual
) {
2035 Matcher
<const wchar_t*> m
= StrEq(::wstring(L
"Hello"));
2036 EXPECT_TRUE(m
.Matches(L
"Hello"));
2037 EXPECT_FALSE(m
.Matches(L
"hello"));
2038 EXPECT_FALSE(m
.Matches(NULL
));
2040 Matcher
<const ::wstring
&> m2
= StrEq(L
"Hello");
2041 EXPECT_TRUE(m2
.Matches(L
"Hello"));
2042 EXPECT_FALSE(m2
.Matches(L
"Hi"));
2044 Matcher
<const ::wstring
&> m3
= StrEq(L
"\xD3\x576\x8D3\xC74D");
2045 EXPECT_TRUE(m3
.Matches(L
"\xD3\x576\x8D3\xC74D"));
2046 EXPECT_FALSE(m3
.Matches(L
"\xD3\x576\x8D3\xC74E"));
2048 ::wstring
str(L
"01204500800");
2050 Matcher
<const ::wstring
&> m4
= StrEq(str
);
2051 EXPECT_TRUE(m4
.Matches(str
));
2052 str
[0] = str
[6] = str
[7] = str
[9] = str
[10] = L
'\0';
2053 Matcher
<const ::wstring
&> m5
= StrEq(str
);
2054 EXPECT_TRUE(m5
.Matches(str
));
2057 TEST(GlobalWideStrEqTest
, CanDescribeSelf
) {
2058 Matcher
< ::wstring
> m
= StrEq(L
"Hi-\'\"?\\\a\b\f\n\r\t\v");
2059 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
2062 Matcher
< ::wstring
> m2
= StrEq(L
"\xD3\x576\x8D3\xC74D");
2063 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
2066 ::wstring
str(L
"01204500800");
2068 Matcher
<const ::wstring
&> m4
= StrEq(str
);
2069 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4
));
2070 str
[0] = str
[6] = str
[7] = str
[9] = str
[10] = L
'\0';
2071 Matcher
<const ::wstring
&> m5
= StrEq(str
);
2072 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5
));
2075 TEST(GlobalWideStrNeTest
, MatchesUnequalString
) {
2076 Matcher
<const wchar_t*> m
= StrNe(L
"Hello");
2077 EXPECT_TRUE(m
.Matches(L
""));
2078 EXPECT_TRUE(m
.Matches(NULL
));
2079 EXPECT_FALSE(m
.Matches(L
"Hello"));
2081 Matcher
< ::wstring
> m2
= StrNe(::wstring(L
"Hello"));
2082 EXPECT_TRUE(m2
.Matches(L
"hello"));
2083 EXPECT_FALSE(m2
.Matches(L
"Hello"));
2086 TEST(GlobalWideStrNeTest
, CanDescribeSelf
) {
2087 Matcher
<const wchar_t*> m
= StrNe(L
"Hi");
2088 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m
));
2091 TEST(GlobalWideStrCaseEqTest
, MatchesEqualStringIgnoringCase
) {
2092 Matcher
<const wchar_t*> m
= StrCaseEq(::wstring(L
"Hello"));
2093 EXPECT_TRUE(m
.Matches(L
"Hello"));
2094 EXPECT_TRUE(m
.Matches(L
"hello"));
2095 EXPECT_FALSE(m
.Matches(L
"Hi"));
2096 EXPECT_FALSE(m
.Matches(NULL
));
2098 Matcher
<const ::wstring
&> m2
= StrCaseEq(L
"Hello");
2099 EXPECT_TRUE(m2
.Matches(L
"hello"));
2100 EXPECT_FALSE(m2
.Matches(L
"Hi"));
2103 TEST(GlobalWideStrCaseEqTest
, MatchesEqualStringWith0IgnoringCase
) {
2104 ::wstring
str1(L
"oabocdooeoo");
2105 ::wstring
str2(L
"OABOCDOOEOO");
2106 Matcher
<const ::wstring
&> m0
= StrCaseEq(str1
);
2107 EXPECT_FALSE(m0
.Matches(str2
+ ::wstring(1, L
'\0')));
2109 str1
[3] = str2
[3] = L
'\0';
2110 Matcher
<const ::wstring
&> m1
= StrCaseEq(str1
);
2111 EXPECT_TRUE(m1
.Matches(str2
));
2113 str1
[0] = str1
[6] = str1
[7] = str1
[10] = L
'\0';
2114 str2
[0] = str2
[6] = str2
[7] = str2
[10] = L
'\0';
2115 Matcher
<const ::wstring
&> m2
= StrCaseEq(str1
);
2116 str1
[9] = str2
[9] = L
'\0';
2117 EXPECT_FALSE(m2
.Matches(str2
));
2119 Matcher
<const ::wstring
&> m3
= StrCaseEq(str1
);
2120 EXPECT_TRUE(m3
.Matches(str2
));
2122 EXPECT_FALSE(m3
.Matches(str2
+ L
"x"));
2123 str2
.append(1, L
'\0');
2124 EXPECT_FALSE(m3
.Matches(str2
));
2125 EXPECT_FALSE(m3
.Matches(::wstring(str2
, 0, 9)));
2128 TEST(GlobalWideStrCaseEqTest
, CanDescribeSelf
) {
2129 Matcher
< ::wstring
> m
= StrCaseEq(L
"Hi");
2130 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m
));
2133 TEST(GlobalWideStrCaseNeTest
, MatchesUnequalStringIgnoringCase
) {
2134 Matcher
<const wchar_t*> m
= StrCaseNe(L
"Hello");
2135 EXPECT_TRUE(m
.Matches(L
"Hi"));
2136 EXPECT_TRUE(m
.Matches(NULL
));
2137 EXPECT_FALSE(m
.Matches(L
"Hello"));
2138 EXPECT_FALSE(m
.Matches(L
"hello"));
2140 Matcher
< ::wstring
> m2
= StrCaseNe(::wstring(L
"Hello"));
2141 EXPECT_TRUE(m2
.Matches(L
""));
2142 EXPECT_FALSE(m2
.Matches(L
"Hello"));
2145 TEST(GlobalWideStrCaseNeTest
, CanDescribeSelf
) {
2146 Matcher
<const wchar_t*> m
= StrCaseNe(L
"Hi");
2147 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m
));
2150 // Tests that HasSubstr() works for matching wstring-typed values.
2151 TEST(GlobalWideHasSubstrTest
, WorksForStringClasses
) {
2152 const Matcher
< ::wstring
> m1
= HasSubstr(L
"foo");
2153 EXPECT_TRUE(m1
.Matches(::wstring(L
"I love food.")));
2154 EXPECT_FALSE(m1
.Matches(::wstring(L
"tofo")));
2156 const Matcher
<const ::wstring
&> m2
= HasSubstr(L
"foo");
2157 EXPECT_TRUE(m2
.Matches(::wstring(L
"I love food.")));
2158 EXPECT_FALSE(m2
.Matches(::wstring(L
"tofo")));
2161 // Tests that HasSubstr() works for matching C-wide-string-typed values.
2162 TEST(GlobalWideHasSubstrTest
, WorksForCStrings
) {
2163 const Matcher
<wchar_t*> m1
= HasSubstr(L
"foo");
2164 EXPECT_TRUE(m1
.Matches(const_cast<wchar_t*>(L
"I love food.")));
2165 EXPECT_FALSE(m1
.Matches(const_cast<wchar_t*>(L
"tofo")));
2166 EXPECT_FALSE(m1
.Matches(NULL
));
2168 const Matcher
<const wchar_t*> m2
= HasSubstr(L
"foo");
2169 EXPECT_TRUE(m2
.Matches(L
"I love food."));
2170 EXPECT_FALSE(m2
.Matches(L
"tofo"));
2171 EXPECT_FALSE(m2
.Matches(NULL
));
2174 // Tests that HasSubstr(s) describes itself properly.
2175 TEST(GlobalWideHasSubstrTest
, CanDescribeSelf
) {
2176 Matcher
< ::wstring
> m
= HasSubstr(L
"foo\n\"");
2177 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m
));
2180 // Tests StartsWith(s).
2182 TEST(GlobalWideStartsWithTest
, MatchesStringWithGivenPrefix
) {
2183 const Matcher
<const wchar_t*> m1
= StartsWith(::wstring(L
""));
2184 EXPECT_TRUE(m1
.Matches(L
"Hi"));
2185 EXPECT_TRUE(m1
.Matches(L
""));
2186 EXPECT_FALSE(m1
.Matches(NULL
));
2188 const Matcher
<const ::wstring
&> m2
= StartsWith(L
"Hi");
2189 EXPECT_TRUE(m2
.Matches(L
"Hi"));
2190 EXPECT_TRUE(m2
.Matches(L
"Hi Hi!"));
2191 EXPECT_TRUE(m2
.Matches(L
"High"));
2192 EXPECT_FALSE(m2
.Matches(L
"H"));
2193 EXPECT_FALSE(m2
.Matches(L
" Hi"));
2196 TEST(GlobalWideStartsWithTest
, CanDescribeSelf
) {
2197 Matcher
<const ::wstring
> m
= StartsWith(L
"Hi");
2198 EXPECT_EQ("starts with L\"Hi\"", Describe(m
));
2201 // Tests EndsWith(s).
2203 TEST(GlobalWideEndsWithTest
, MatchesStringWithGivenSuffix
) {
2204 const Matcher
<const wchar_t*> m1
= EndsWith(L
"");
2205 EXPECT_TRUE(m1
.Matches(L
"Hi"));
2206 EXPECT_TRUE(m1
.Matches(L
""));
2207 EXPECT_FALSE(m1
.Matches(NULL
));
2209 const Matcher
<const ::wstring
&> m2
= EndsWith(::wstring(L
"Hi"));
2210 EXPECT_TRUE(m2
.Matches(L
"Hi"));
2211 EXPECT_TRUE(m2
.Matches(L
"Wow Hi Hi"));
2212 EXPECT_TRUE(m2
.Matches(L
"Super Hi"));
2213 EXPECT_FALSE(m2
.Matches(L
"i"));
2214 EXPECT_FALSE(m2
.Matches(L
"Hi "));
2217 TEST(GlobalWideEndsWithTest
, CanDescribeSelf
) {
2218 Matcher
<const ::wstring
> m
= EndsWith(L
"Hi");
2219 EXPECT_EQ("ends with L\"Hi\"", Describe(m
));
2222 #endif // GTEST_HAS_GLOBAL_WSTRING
2225 typedef ::testing::tuple
<long, int> Tuple2
; // NOLINT
2227 // Tests that Eq() matches a 2-tuple where the first field == the
2229 TEST(Eq2Test
, MatchesEqualArguments
) {
2230 Matcher
<const Tuple2
&> m
= Eq();
2231 EXPECT_TRUE(m
.Matches(Tuple2(5L, 5)));
2232 EXPECT_FALSE(m
.Matches(Tuple2(5L, 6)));
2235 // Tests that Eq() describes itself properly.
2236 TEST(Eq2Test
, CanDescribeSelf
) {
2237 Matcher
<const Tuple2
&> m
= Eq();
2238 EXPECT_EQ("are an equal pair", Describe(m
));
2241 // Tests that Ge() matches a 2-tuple where the first field >= the
2243 TEST(Ge2Test
, MatchesGreaterThanOrEqualArguments
) {
2244 Matcher
<const Tuple2
&> m
= Ge();
2245 EXPECT_TRUE(m
.Matches(Tuple2(5L, 4)));
2246 EXPECT_TRUE(m
.Matches(Tuple2(5L, 5)));
2247 EXPECT_FALSE(m
.Matches(Tuple2(5L, 6)));
2250 // Tests that Ge() describes itself properly.
2251 TEST(Ge2Test
, CanDescribeSelf
) {
2252 Matcher
<const Tuple2
&> m
= Ge();
2253 EXPECT_EQ("are a pair where the first >= the second", Describe(m
));
2256 // Tests that Gt() matches a 2-tuple where the first field > the
2258 TEST(Gt2Test
, MatchesGreaterThanArguments
) {
2259 Matcher
<const Tuple2
&> m
= Gt();
2260 EXPECT_TRUE(m
.Matches(Tuple2(5L, 4)));
2261 EXPECT_FALSE(m
.Matches(Tuple2(5L, 5)));
2262 EXPECT_FALSE(m
.Matches(Tuple2(5L, 6)));
2265 // Tests that Gt() describes itself properly.
2266 TEST(Gt2Test
, CanDescribeSelf
) {
2267 Matcher
<const Tuple2
&> m
= Gt();
2268 EXPECT_EQ("are a pair where the first > the second", Describe(m
));
2271 // Tests that Le() matches a 2-tuple where the first field <= the
2273 TEST(Le2Test
, MatchesLessThanOrEqualArguments
) {
2274 Matcher
<const Tuple2
&> m
= Le();
2275 EXPECT_TRUE(m
.Matches(Tuple2(5L, 6)));
2276 EXPECT_TRUE(m
.Matches(Tuple2(5L, 5)));
2277 EXPECT_FALSE(m
.Matches(Tuple2(5L, 4)));
2280 // Tests that Le() describes itself properly.
2281 TEST(Le2Test
, CanDescribeSelf
) {
2282 Matcher
<const Tuple2
&> m
= Le();
2283 EXPECT_EQ("are a pair where the first <= the second", Describe(m
));
2286 // Tests that Lt() matches a 2-tuple where the first field < the
2288 TEST(Lt2Test
, MatchesLessThanArguments
) {
2289 Matcher
<const Tuple2
&> m
= Lt();
2290 EXPECT_TRUE(m
.Matches(Tuple2(5L, 6)));
2291 EXPECT_FALSE(m
.Matches(Tuple2(5L, 5)));
2292 EXPECT_FALSE(m
.Matches(Tuple2(5L, 4)));
2295 // Tests that Lt() describes itself properly.
2296 TEST(Lt2Test
, CanDescribeSelf
) {
2297 Matcher
<const Tuple2
&> m
= Lt();
2298 EXPECT_EQ("are a pair where the first < the second", Describe(m
));
2301 // Tests that Ne() matches a 2-tuple where the first field != the
2303 TEST(Ne2Test
, MatchesUnequalArguments
) {
2304 Matcher
<const Tuple2
&> m
= Ne();
2305 EXPECT_TRUE(m
.Matches(Tuple2(5L, 6)));
2306 EXPECT_TRUE(m
.Matches(Tuple2(5L, 4)));
2307 EXPECT_FALSE(m
.Matches(Tuple2(5L, 5)));
2310 // Tests that Ne() describes itself properly.
2311 TEST(Ne2Test
, CanDescribeSelf
) {
2312 Matcher
<const Tuple2
&> m
= Ne();
2313 EXPECT_EQ("are an unequal pair", Describe(m
));
2316 // Tests that FloatEq() matches a 2-tuple where
2317 // FloatEq(first field) matches the second field.
2318 TEST(FloatEq2Test
, MatchesEqualArguments
) {
2319 typedef ::testing::tuple
<float, float> Tpl
;
2320 Matcher
<const Tpl
&> m
= FloatEq();
2321 EXPECT_TRUE(m
.Matches(Tpl(1.0f
, 1.0f
)));
2322 EXPECT_TRUE(m
.Matches(Tpl(0.3f
, 0.1f
+ 0.1f
+ 0.1f
)));
2323 EXPECT_FALSE(m
.Matches(Tpl(1.1f
, 1.0f
)));
2326 // Tests that FloatEq() describes itself properly.
2327 TEST(FloatEq2Test
, CanDescribeSelf
) {
2328 Matcher
<const ::testing::tuple
<float, float>&> m
= FloatEq();
2329 EXPECT_EQ("are an almost-equal pair", Describe(m
));
2332 // Tests that NanSensitiveFloatEq() matches a 2-tuple where
2333 // NanSensitiveFloatEq(first field) matches the second field.
2334 TEST(NanSensitiveFloatEqTest
, MatchesEqualArgumentsWithNaN
) {
2335 typedef ::testing::tuple
<float, float> Tpl
;
2336 Matcher
<const Tpl
&> m
= NanSensitiveFloatEq();
2337 EXPECT_TRUE(m
.Matches(Tpl(1.0f
, 1.0f
)));
2338 EXPECT_TRUE(m
.Matches(Tpl(std::numeric_limits
<float>::quiet_NaN(),
2339 std::numeric_limits
<float>::quiet_NaN())));
2340 EXPECT_FALSE(m
.Matches(Tpl(1.1f
, 1.0f
)));
2341 EXPECT_FALSE(m
.Matches(Tpl(1.0f
, std::numeric_limits
<float>::quiet_NaN())));
2342 EXPECT_FALSE(m
.Matches(Tpl(std::numeric_limits
<float>::quiet_NaN(), 1.0f
)));
2345 // Tests that NanSensitiveFloatEq() describes itself properly.
2346 TEST(NanSensitiveFloatEqTest
, CanDescribeSelfWithNaNs
) {
2347 Matcher
<const ::testing::tuple
<float, float>&> m
= NanSensitiveFloatEq();
2348 EXPECT_EQ("are an almost-equal pair", Describe(m
));
2351 // Tests that DoubleEq() matches a 2-tuple where
2352 // DoubleEq(first field) matches the second field.
2353 TEST(DoubleEq2Test
, MatchesEqualArguments
) {
2354 typedef ::testing::tuple
<double, double> Tpl
;
2355 Matcher
<const Tpl
&> m
= DoubleEq();
2356 EXPECT_TRUE(m
.Matches(Tpl(1.0, 1.0)));
2357 EXPECT_TRUE(m
.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1)));
2358 EXPECT_FALSE(m
.Matches(Tpl(1.1, 1.0)));
2361 // Tests that DoubleEq() describes itself properly.
2362 TEST(DoubleEq2Test
, CanDescribeSelf
) {
2363 Matcher
<const ::testing::tuple
<double, double>&> m
= DoubleEq();
2364 EXPECT_EQ("are an almost-equal pair", Describe(m
));
2367 // Tests that NanSensitiveDoubleEq() matches a 2-tuple where
2368 // NanSensitiveDoubleEq(first field) matches the second field.
2369 TEST(NanSensitiveDoubleEqTest
, MatchesEqualArgumentsWithNaN
) {
2370 typedef ::testing::tuple
<double, double> Tpl
;
2371 Matcher
<const Tpl
&> m
= NanSensitiveDoubleEq();
2372 EXPECT_TRUE(m
.Matches(Tpl(1.0f
, 1.0f
)));
2373 EXPECT_TRUE(m
.Matches(Tpl(std::numeric_limits
<double>::quiet_NaN(),
2374 std::numeric_limits
<double>::quiet_NaN())));
2375 EXPECT_FALSE(m
.Matches(Tpl(1.1f
, 1.0f
)));
2376 EXPECT_FALSE(m
.Matches(Tpl(1.0f
, std::numeric_limits
<double>::quiet_NaN())));
2377 EXPECT_FALSE(m
.Matches(Tpl(std::numeric_limits
<double>::quiet_NaN(), 1.0f
)));
2380 // Tests that DoubleEq() describes itself properly.
2381 TEST(NanSensitiveDoubleEqTest
, CanDescribeSelfWithNaNs
) {
2382 Matcher
<const ::testing::tuple
<double, double>&> m
= NanSensitiveDoubleEq();
2383 EXPECT_EQ("are an almost-equal pair", Describe(m
));
2386 // Tests that FloatEq() matches a 2-tuple where
2387 // FloatNear(first field, max_abs_error) matches the second field.
2388 TEST(FloatNear2Test
, MatchesEqualArguments
) {
2389 typedef ::testing::tuple
<float, float> Tpl
;
2390 Matcher
<const Tpl
&> m
= FloatNear(0.5f
);
2391 EXPECT_TRUE(m
.Matches(Tpl(1.0f
, 1.0f
)));
2392 EXPECT_TRUE(m
.Matches(Tpl(1.3f
, 1.0f
)));
2393 EXPECT_FALSE(m
.Matches(Tpl(1.8f
, 1.0f
)));
2396 // Tests that FloatNear() describes itself properly.
2397 TEST(FloatNear2Test
, CanDescribeSelf
) {
2398 Matcher
<const ::testing::tuple
<float, float>&> m
= FloatNear(0.5f
);
2399 EXPECT_EQ("are an almost-equal pair", Describe(m
));
2402 // Tests that NanSensitiveFloatNear() matches a 2-tuple where
2403 // NanSensitiveFloatNear(first field) matches the second field.
2404 TEST(NanSensitiveFloatNearTest
, MatchesNearbyArgumentsWithNaN
) {
2405 typedef ::testing::tuple
<float, float> Tpl
;
2406 Matcher
<const Tpl
&> m
= NanSensitiveFloatNear(0.5f
);
2407 EXPECT_TRUE(m
.Matches(Tpl(1.0f
, 1.0f
)));
2408 EXPECT_TRUE(m
.Matches(Tpl(1.1f
, 1.0f
)));
2409 EXPECT_TRUE(m
.Matches(Tpl(std::numeric_limits
<float>::quiet_NaN(),
2410 std::numeric_limits
<float>::quiet_NaN())));
2411 EXPECT_FALSE(m
.Matches(Tpl(1.6f
, 1.0f
)));
2412 EXPECT_FALSE(m
.Matches(Tpl(1.0f
, std::numeric_limits
<float>::quiet_NaN())));
2413 EXPECT_FALSE(m
.Matches(Tpl(std::numeric_limits
<float>::quiet_NaN(), 1.0f
)));
2416 // Tests that NanSensitiveFloatNear() describes itself properly.
2417 TEST(NanSensitiveFloatNearTest
, CanDescribeSelfWithNaNs
) {
2418 Matcher
<const ::testing::tuple
<float, float>&> m
=
2419 NanSensitiveFloatNear(0.5f
);
2420 EXPECT_EQ("are an almost-equal pair", Describe(m
));
2423 // Tests that FloatEq() matches a 2-tuple where
2424 // DoubleNear(first field, max_abs_error) matches the second field.
2425 TEST(DoubleNear2Test
, MatchesEqualArguments
) {
2426 typedef ::testing::tuple
<double, double> Tpl
;
2427 Matcher
<const Tpl
&> m
= DoubleNear(0.5);
2428 EXPECT_TRUE(m
.Matches(Tpl(1.0, 1.0)));
2429 EXPECT_TRUE(m
.Matches(Tpl(1.3, 1.0)));
2430 EXPECT_FALSE(m
.Matches(Tpl(1.8, 1.0)));
2433 // Tests that DoubleNear() describes itself properly.
2434 TEST(DoubleNear2Test
, CanDescribeSelf
) {
2435 Matcher
<const ::testing::tuple
<double, double>&> m
= DoubleNear(0.5);
2436 EXPECT_EQ("are an almost-equal pair", Describe(m
));
2439 // Tests that NanSensitiveDoubleNear() matches a 2-tuple where
2440 // NanSensitiveDoubleNear(first field) matches the second field.
2441 TEST(NanSensitiveDoubleNearTest
, MatchesNearbyArgumentsWithNaN
) {
2442 typedef ::testing::tuple
<double, double> Tpl
;
2443 Matcher
<const Tpl
&> m
= NanSensitiveDoubleNear(0.5f
);
2444 EXPECT_TRUE(m
.Matches(Tpl(1.0f
, 1.0f
)));
2445 EXPECT_TRUE(m
.Matches(Tpl(1.1f
, 1.0f
)));
2446 EXPECT_TRUE(m
.Matches(Tpl(std::numeric_limits
<double>::quiet_NaN(),
2447 std::numeric_limits
<double>::quiet_NaN())));
2448 EXPECT_FALSE(m
.Matches(Tpl(1.6f
, 1.0f
)));
2449 EXPECT_FALSE(m
.Matches(Tpl(1.0f
, std::numeric_limits
<double>::quiet_NaN())));
2450 EXPECT_FALSE(m
.Matches(Tpl(std::numeric_limits
<double>::quiet_NaN(), 1.0f
)));
2453 // Tests that NanSensitiveDoubleNear() describes itself properly.
2454 TEST(NanSensitiveDoubleNearTest
, CanDescribeSelfWithNaNs
) {
2455 Matcher
<const ::testing::tuple
<double, double>&> m
=
2456 NanSensitiveDoubleNear(0.5f
);
2457 EXPECT_EQ("are an almost-equal pair", Describe(m
));
2460 // Tests that Not(m) matches any value that doesn't match m.
2461 TEST(NotTest
, NegatesMatcher
) {
2464 EXPECT_TRUE(m
.Matches(3));
2465 EXPECT_FALSE(m
.Matches(2));
2468 // Tests that Not(m) describes itself properly.
2469 TEST(NotTest
, CanDescribeSelf
) {
2470 Matcher
<int> m
= Not(Eq(5));
2471 EXPECT_EQ("isn't equal to 5", Describe(m
));
2474 // Tests that monomorphic matchers are safely cast by the Not matcher.
2475 TEST(NotTest
, NotMatcherSafelyCastsMonomorphicMatchers
) {
2476 // greater_than_5 is a monomorphic matcher.
2477 Matcher
<int> greater_than_5
= Gt(5);
2479 Matcher
<const int&> m
= Not(greater_than_5
);
2480 Matcher
<int&> m2
= Not(greater_than_5
);
2481 Matcher
<int&> m3
= Not(m
);
2484 // Helper to allow easy testing of AllOf matchers with num parameters.
2485 void AllOfMatches(int num
, const Matcher
<int>& m
) {
2486 SCOPED_TRACE(Describe(m
));
2487 EXPECT_TRUE(m
.Matches(0));
2488 for (int i
= 1; i
<= num
; ++i
) {
2489 EXPECT_FALSE(m
.Matches(i
));
2491 EXPECT_TRUE(m
.Matches(num
+ 1));
2494 // Tests that AllOf(m1, ..., mn) matches any value that matches all of
2495 // the given matchers.
2496 TEST(AllOfTest
, MatchesWhenAllMatch
) {
2498 m
= AllOf(Le(2), Ge(1));
2499 EXPECT_TRUE(m
.Matches(1));
2500 EXPECT_TRUE(m
.Matches(2));
2501 EXPECT_FALSE(m
.Matches(0));
2502 EXPECT_FALSE(m
.Matches(3));
2504 m
= AllOf(Gt(0), Ne(1), Ne(2));
2505 EXPECT_TRUE(m
.Matches(3));
2506 EXPECT_FALSE(m
.Matches(2));
2507 EXPECT_FALSE(m
.Matches(1));
2508 EXPECT_FALSE(m
.Matches(0));
2510 m
= AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2511 EXPECT_TRUE(m
.Matches(4));
2512 EXPECT_FALSE(m
.Matches(3));
2513 EXPECT_FALSE(m
.Matches(2));
2514 EXPECT_FALSE(m
.Matches(1));
2515 EXPECT_FALSE(m
.Matches(0));
2517 m
= AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2518 EXPECT_TRUE(m
.Matches(0));
2519 EXPECT_TRUE(m
.Matches(1));
2520 EXPECT_FALSE(m
.Matches(3));
2522 // The following tests for varying number of sub-matchers. Due to the way
2523 // the sub-matchers are handled it is enough to test every sub-matcher once
2524 // with sub-matchers using the same matcher type. Varying matcher types are
2525 // checked for above.
2526 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2527 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2528 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2529 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2530 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2531 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2532 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2534 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2536 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2540 #if GTEST_LANG_CXX11
2541 // Tests the variadic version of the AllOfMatcher.
2542 TEST(AllOfTest
, VariadicMatchesWhenAllMatch
) {
2543 // Make sure AllOf is defined in the right namespace and does not depend on
2545 ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2546 Matcher
<int> m
= AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2547 Ne(9), Ne(10), Ne(11));
2548 EXPECT_THAT(Describe(m
), EndsWith("and (isn't equal to 11)"));
2549 AllOfMatches(11, m
);
2550 AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2551 Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
2552 Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22),
2553 Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29),
2554 Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36),
2555 Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43),
2556 Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2560 #endif // GTEST_LANG_CXX11
2562 // Tests that AllOf(m1, ..., mn) describes itself properly.
2563 TEST(AllOfTest
, CanDescribeSelf
) {
2565 m
= AllOf(Le(2), Ge(1));
2566 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m
));
2568 m
= AllOf(Gt(0), Ne(1), Ne(2));
2569 EXPECT_EQ("(is > 0) and "
2570 "((isn't equal to 1) and "
2571 "(isn't equal to 2))",
2575 m
= AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2576 EXPECT_EQ("((is > 0) and "
2577 "(isn't equal to 1)) and "
2578 "((isn't equal to 2) and "
2579 "(isn't equal to 3))",
2583 m
= AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2584 EXPECT_EQ("((is >= 0) and "
2586 "((isn't equal to 3) and "
2587 "((isn't equal to 5) and "
2588 "(isn't equal to 7)))",
2592 // Tests that AllOf(m1, ..., mn) describes its negation properly.
2593 TEST(AllOfTest
, CanDescribeNegation
) {
2595 m
= AllOf(Le(2), Ge(1));
2596 EXPECT_EQ("(isn't <= 2) or "
2598 DescribeNegation(m
));
2600 m
= AllOf(Gt(0), Ne(1), Ne(2));
2601 EXPECT_EQ("(isn't > 0) or "
2602 "((is equal to 1) or "
2604 DescribeNegation(m
));
2607 m
= AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2608 EXPECT_EQ("((isn't > 0) or "
2609 "(is equal to 1)) or "
2610 "((is equal to 2) or "
2612 DescribeNegation(m
));
2615 m
= AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2616 EXPECT_EQ("((isn't >= 0) or "
2618 "((is equal to 3) or "
2619 "((is equal to 5) or "
2620 "(is equal to 7)))",
2621 DescribeNegation(m
));
2624 // Tests that monomorphic matchers are safely cast by the AllOf matcher.
2625 TEST(AllOfTest
, AllOfMatcherSafelyCastsMonomorphicMatchers
) {
2626 // greater_than_5 and less_than_10 are monomorphic matchers.
2627 Matcher
<int> greater_than_5
= Gt(5);
2628 Matcher
<int> less_than_10
= Lt(10);
2630 Matcher
<const int&> m
= AllOf(greater_than_5
, less_than_10
);
2631 Matcher
<int&> m2
= AllOf(greater_than_5
, less_than_10
);
2632 Matcher
<int&> m3
= AllOf(greater_than_5
, m2
);
2634 // Tests that BothOf works when composing itself.
2635 Matcher
<const int&> m4
= AllOf(greater_than_5
, less_than_10
, less_than_10
);
2636 Matcher
<int&> m5
= AllOf(greater_than_5
, less_than_10
, less_than_10
);
2639 TEST(AllOfTest
, ExplainsResult
) {
2642 // Successful match. Both matchers need to explain. The second
2643 // matcher doesn't give an explanation, so only the first matcher's
2644 // explanation is printed.
2645 m
= AllOf(GreaterThan(10), Lt(30));
2646 EXPECT_EQ("which is 15 more than 10", Explain(m
, 25));
2648 // Successful match. Both matchers need to explain.
2649 m
= AllOf(GreaterThan(10), GreaterThan(20));
2650 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2653 // Successful match. All matchers need to explain. The second
2654 // matcher doesn't given an explanation.
2655 m
= AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2656 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2659 // Successful match. All matchers need to explain.
2660 m
= AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2661 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2662 "and which is 10 more than 30",
2665 // Failed match. The first matcher, which failed, needs to
2667 m
= AllOf(GreaterThan(10), GreaterThan(20));
2668 EXPECT_EQ("which is 5 less than 10", Explain(m
, 5));
2670 // Failed match. The second matcher, which failed, needs to
2671 // explain. Since it doesn't given an explanation, nothing is
2673 m
= AllOf(GreaterThan(10), Lt(30));
2674 EXPECT_EQ("", Explain(m
, 40));
2676 // Failed match. The second matcher, which failed, needs to
2678 m
= AllOf(GreaterThan(10), GreaterThan(20));
2679 EXPECT_EQ("which is 5 less than 20", Explain(m
, 15));
2682 // Helper to allow easy testing of AnyOf matchers with num parameters.
2683 void AnyOfMatches(int num
, const Matcher
<int>& m
) {
2684 SCOPED_TRACE(Describe(m
));
2685 EXPECT_FALSE(m
.Matches(0));
2686 for (int i
= 1; i
<= num
; ++i
) {
2687 EXPECT_TRUE(m
.Matches(i
));
2689 EXPECT_FALSE(m
.Matches(num
+ 1));
2692 // Tests that AnyOf(m1, ..., mn) matches any value that matches at
2693 // least one of the given matchers.
2694 TEST(AnyOfTest
, MatchesWhenAnyMatches
) {
2696 m
= AnyOf(Le(1), Ge(3));
2697 EXPECT_TRUE(m
.Matches(1));
2698 EXPECT_TRUE(m
.Matches(4));
2699 EXPECT_FALSE(m
.Matches(2));
2701 m
= AnyOf(Lt(0), Eq(1), Eq(2));
2702 EXPECT_TRUE(m
.Matches(-1));
2703 EXPECT_TRUE(m
.Matches(1));
2704 EXPECT_TRUE(m
.Matches(2));
2705 EXPECT_FALSE(m
.Matches(0));
2707 m
= AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2708 EXPECT_TRUE(m
.Matches(-1));
2709 EXPECT_TRUE(m
.Matches(1));
2710 EXPECT_TRUE(m
.Matches(2));
2711 EXPECT_TRUE(m
.Matches(3));
2712 EXPECT_FALSE(m
.Matches(0));
2714 m
= AnyOf(Le(0), Gt(10), 3, 5, 7);
2715 EXPECT_TRUE(m
.Matches(0));
2716 EXPECT_TRUE(m
.Matches(11));
2717 EXPECT_TRUE(m
.Matches(3));
2718 EXPECT_FALSE(m
.Matches(2));
2720 // The following tests for varying number of sub-matchers. Due to the way
2721 // the sub-matchers are handled it is enough to test every sub-matcher once
2722 // with sub-matchers using the same matcher type. Varying matcher types are
2723 // checked for above.
2724 AnyOfMatches(2, AnyOf(1, 2));
2725 AnyOfMatches(3, AnyOf(1, 2, 3));
2726 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2727 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2728 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2729 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2730 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2731 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2732 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
2735 #if GTEST_LANG_CXX11
2736 // Tests the variadic version of the AnyOfMatcher.
2737 TEST(AnyOfTest
, VariadicMatchesWhenAnyMatches
) {
2738 // Also make sure AnyOf is defined in the right namespace and does not depend
2740 Matcher
<int> m
= ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2742 EXPECT_THAT(Describe(m
), EndsWith("or (is equal to 11)"));
2743 AnyOfMatches(11, m
);
2744 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2745 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2746 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2747 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2748 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2751 // Tests the variadic version of the ElementsAreMatcher
2752 TEST(ElementsAreTest
, HugeMatcher
) {
2753 vector
<int> test_vector
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
2755 EXPECT_THAT(test_vector
,
2756 ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7),
2757 Eq(8), Eq(9), Eq(10), Gt(1), Eq(12)));
2760 // Tests the variadic version of the UnorderedElementsAreMatcher
2761 TEST(ElementsAreTest
, HugeMatcherStr
) {
2762 vector
<string
> test_vector
{
2763 "literal_string", "", "", "", "", "", "", "", "", "", "", ""};
2765 EXPECT_THAT(test_vector
, UnorderedElementsAre("literal_string", _
, _
, _
, _
, _
,
2769 // Tests the variadic version of the UnorderedElementsAreMatcher
2770 TEST(ElementsAreTest
, HugeMatcherUnordered
) {
2771 vector
<int> test_vector
{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};
2773 EXPECT_THAT(test_vector
, UnorderedElementsAre(
2774 Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7),
2775 Eq(3), Eq(9), Eq(12), Eq(11), Ne(122)));
2778 #endif // GTEST_LANG_CXX11
2780 // Tests that AnyOf(m1, ..., mn) describes itself properly.
2781 TEST(AnyOfTest
, CanDescribeSelf
) {
2783 m
= AnyOf(Le(1), Ge(3));
2784 EXPECT_EQ("(is <= 1) or (is >= 3)",
2787 m
= AnyOf(Lt(0), Eq(1), Eq(2));
2788 EXPECT_EQ("(is < 0) or "
2789 "((is equal to 1) or (is equal to 2))",
2792 m
= AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2793 EXPECT_EQ("((is < 0) or "
2794 "(is equal to 1)) or "
2795 "((is equal to 2) or "
2799 m
= AnyOf(Le(0), Gt(10), 3, 5, 7);
2800 EXPECT_EQ("((is <= 0) or "
2802 "((is equal to 3) or "
2803 "((is equal to 5) or "
2804 "(is equal to 7)))",
2808 // Tests that AnyOf(m1, ..., mn) describes its negation properly.
2809 TEST(AnyOfTest
, CanDescribeNegation
) {
2811 m
= AnyOf(Le(1), Ge(3));
2812 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2813 DescribeNegation(m
));
2815 m
= AnyOf(Lt(0), Eq(1), Eq(2));
2816 EXPECT_EQ("(isn't < 0) and "
2817 "((isn't equal to 1) and (isn't equal to 2))",
2818 DescribeNegation(m
));
2820 m
= AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2821 EXPECT_EQ("((isn't < 0) and "
2822 "(isn't equal to 1)) and "
2823 "((isn't equal to 2) and "
2824 "(isn't equal to 3))",
2825 DescribeNegation(m
));
2827 m
= AnyOf(Le(0), Gt(10), 3, 5, 7);
2828 EXPECT_EQ("((isn't <= 0) and "
2829 "(isn't > 10)) and "
2830 "((isn't equal to 3) and "
2831 "((isn't equal to 5) and "
2832 "(isn't equal to 7)))",
2833 DescribeNegation(m
));
2836 // Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2837 TEST(AnyOfTest
, AnyOfMatcherSafelyCastsMonomorphicMatchers
) {
2838 // greater_than_5 and less_than_10 are monomorphic matchers.
2839 Matcher
<int> greater_than_5
= Gt(5);
2840 Matcher
<int> less_than_10
= Lt(10);
2842 Matcher
<const int&> m
= AnyOf(greater_than_5
, less_than_10
);
2843 Matcher
<int&> m2
= AnyOf(greater_than_5
, less_than_10
);
2844 Matcher
<int&> m3
= AnyOf(greater_than_5
, m2
);
2846 // Tests that EitherOf works when composing itself.
2847 Matcher
<const int&> m4
= AnyOf(greater_than_5
, less_than_10
, less_than_10
);
2848 Matcher
<int&> m5
= AnyOf(greater_than_5
, less_than_10
, less_than_10
);
2851 TEST(AnyOfTest
, ExplainsResult
) {
2854 // Failed match. Both matchers need to explain. The second
2855 // matcher doesn't give an explanation, so only the first matcher's
2856 // explanation is printed.
2857 m
= AnyOf(GreaterThan(10), Lt(0));
2858 EXPECT_EQ("which is 5 less than 10", Explain(m
, 5));
2860 // Failed match. Both matchers need to explain.
2861 m
= AnyOf(GreaterThan(10), GreaterThan(20));
2862 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2865 // Failed match. All matchers need to explain. The second
2866 // matcher doesn't given an explanation.
2867 m
= AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2868 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2871 // Failed match. All matchers need to explain.
2872 m
= AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2873 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2874 "and which is 25 less than 30",
2877 // Successful match. The first matcher, which succeeded, needs to
2879 m
= AnyOf(GreaterThan(10), GreaterThan(20));
2880 EXPECT_EQ("which is 5 more than 10", Explain(m
, 15));
2882 // Successful match. The second matcher, which succeeded, needs to
2883 // explain. Since it doesn't given an explanation, nothing is
2885 m
= AnyOf(GreaterThan(10), Lt(30));
2886 EXPECT_EQ("", Explain(m
, 0));
2888 // Successful match. The second matcher, which succeeded, needs to
2890 m
= AnyOf(GreaterThan(30), GreaterThan(20));
2891 EXPECT_EQ("which is 5 more than 20", Explain(m
, 25));
2894 // The following predicate function and predicate functor are for
2895 // testing the Truly(predicate) matcher.
2897 // Returns non-zero if the input is positive. Note that the return
2898 // type of this function is not bool. It's OK as Truly() accepts any
2899 // unary function or functor whose return type can be implicitly
2900 // converted to bool.
2901 int IsPositive(double x
) {
2902 return x
> 0 ? 1 : 0;
2905 // This functor returns true if the input is greater than the given
2907 class IsGreaterThan
{
2909 explicit IsGreaterThan(int threshold
) : threshold_(threshold
) {}
2911 bool operator()(int n
) const { return n
> threshold_
; }
2917 // For testing Truly().
2920 // This predicate returns true iff the argument references foo and has
2922 bool ReferencesFooAndIsZero(const int& n
) {
2923 return (&n
== &foo
) && (n
== 0);
2926 // Tests that Truly(predicate) matches what satisfies the given
2928 TEST(TrulyTest
, MatchesWhatSatisfiesThePredicate
) {
2929 Matcher
<double> m
= Truly(IsPositive
);
2930 EXPECT_TRUE(m
.Matches(2.0));
2931 EXPECT_FALSE(m
.Matches(-1.5));
2934 // Tests that Truly(predicate_functor) works too.
2935 TEST(TrulyTest
, CanBeUsedWithFunctor
) {
2936 Matcher
<int> m
= Truly(IsGreaterThan(5));
2937 EXPECT_TRUE(m
.Matches(6));
2938 EXPECT_FALSE(m
.Matches(4));
2941 // A class that can be implicitly converted to bool.
2942 class ConvertibleToBool
{
2944 explicit ConvertibleToBool(int number
) : number_(number
) {}
2945 operator bool() const { return number_
!= 0; }
2951 ConvertibleToBool
IsNotZero(int number
) {
2952 return ConvertibleToBool(number
);
2955 // Tests that the predicate used in Truly() may return a class that's
2956 // implicitly convertible to bool, even when the class has no
2958 TEST(TrulyTest
, PredicateCanReturnAClassConvertibleToBool
) {
2959 Matcher
<int> m
= Truly(IsNotZero
);
2960 EXPECT_TRUE(m
.Matches(1));
2961 EXPECT_FALSE(m
.Matches(0));
2964 // Tests that Truly(predicate) can describe itself properly.
2965 TEST(TrulyTest
, CanDescribeSelf
) {
2966 Matcher
<double> m
= Truly(IsPositive
);
2967 EXPECT_EQ("satisfies the given predicate",
2971 // Tests that Truly(predicate) works when the matcher takes its
2972 // argument by reference.
2973 TEST(TrulyTest
, WorksForByRefArguments
) {
2974 Matcher
<const int&> m
= Truly(ReferencesFooAndIsZero
);
2975 EXPECT_TRUE(m
.Matches(foo
));
2977 EXPECT_FALSE(m
.Matches(n
));
2980 // Tests that Matches(m) is a predicate satisfied by whatever that
2981 // matches matcher m.
2982 TEST(MatchesTest
, IsSatisfiedByWhatMatchesTheMatcher
) {
2983 EXPECT_TRUE(Matches(Ge(0))(1));
2984 EXPECT_FALSE(Matches(Eq('a'))('b'));
2987 // Tests that Matches(m) works when the matcher takes its argument by
2989 TEST(MatchesTest
, WorksOnByRefArguments
) {
2991 EXPECT_TRUE(Matches(AllOf(Ref(n
), Eq(0)))(n
));
2992 EXPECT_FALSE(Matches(Ref(m
))(n
));
2995 // Tests that a Matcher on non-reference type can be used in
2997 TEST(MatchesTest
, WorksWithMatcherOnNonRefType
) {
2998 Matcher
<int> eq5
= Eq(5);
2999 EXPECT_TRUE(Matches(eq5
)(5));
3000 EXPECT_FALSE(Matches(eq5
)(2));
3003 // Tests Value(value, matcher). Since Value() is a simple wrapper for
3004 // Matches(), which has been tested already, we don't spend a lot of
3005 // effort on testing Value().
3006 TEST(ValueTest
, WorksWithPolymorphicMatcher
) {
3007 EXPECT_TRUE(Value("hi", StartsWith("h")));
3008 EXPECT_FALSE(Value(5, Gt(10)));
3011 TEST(ValueTest
, WorksWithMonomorphicMatcher
) {
3012 const Matcher
<int> is_zero
= Eq(0);
3013 EXPECT_TRUE(Value(0, is_zero
));
3014 EXPECT_FALSE(Value('a', is_zero
));
3017 const Matcher
<const int&> ref_n
= Ref(n
);
3018 EXPECT_TRUE(Value(n
, ref_n
));
3019 EXPECT_FALSE(Value(1, ref_n
));
3022 TEST(ExplainMatchResultTest
, WorksWithPolymorphicMatcher
) {
3023 StringMatchResultListener listener1
;
3024 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1
));
3025 EXPECT_EQ("% 2 == 0", listener1
.str());
3027 StringMatchResultListener listener2
;
3028 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2
));
3029 EXPECT_EQ("", listener2
.str());
3032 TEST(ExplainMatchResultTest
, WorksWithMonomorphicMatcher
) {
3033 const Matcher
<int> is_even
= PolymorphicIsEven();
3034 StringMatchResultListener listener1
;
3035 EXPECT_TRUE(ExplainMatchResult(is_even
, 42, &listener1
));
3036 EXPECT_EQ("% 2 == 0", listener1
.str());
3038 const Matcher
<const double&> is_zero
= Eq(0);
3039 StringMatchResultListener listener2
;
3040 EXPECT_FALSE(ExplainMatchResult(is_zero
, 1.5, &listener2
));
3041 EXPECT_EQ("", listener2
.str());
3044 MATCHER_P(Really
, inner_matcher
, "") {
3045 return ExplainMatchResult(inner_matcher
, arg
, result_listener
);
3048 TEST(ExplainMatchResultTest
, WorksInsideMATCHER
) {
3049 EXPECT_THAT(0, Really(Eq(0)));
3052 TEST(DescribeMatcherTest
, WorksWithValue
) {
3053 EXPECT_EQ("is equal to 42", DescribeMatcher
<int>(42));
3054 EXPECT_EQ("isn't equal to 42", DescribeMatcher
<int>(42, true));
3057 TEST(DescribeMatcherTest
, WorksWithMonomorphicMatcher
) {
3058 const Matcher
<int> monomorphic
= Le(0);
3059 EXPECT_EQ("is <= 0", DescribeMatcher
<int>(monomorphic
));
3060 EXPECT_EQ("isn't <= 0", DescribeMatcher
<int>(monomorphic
, true));
3063 TEST(DescribeMatcherTest
, WorksWithPolymorphicMatcher
) {
3064 EXPECT_EQ("is even", DescribeMatcher
<int>(PolymorphicIsEven()));
3065 EXPECT_EQ("is odd", DescribeMatcher
<int>(PolymorphicIsEven(), true));
3068 TEST(AllArgsTest
, WorksForTuple
) {
3069 EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
3070 EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
3073 TEST(AllArgsTest
, WorksForNonTuple
) {
3074 EXPECT_THAT(42, AllArgs(Gt(0)));
3075 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
3078 class AllArgsHelper
{
3082 MOCK_METHOD2(Helper
, int(char x
, int y
));
3085 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper
);
3088 TEST(AllArgsTest
, WorksInWithClause
) {
3089 AllArgsHelper helper
;
3090 ON_CALL(helper
, Helper(_
, _
))
3091 .With(AllArgs(Lt()))
3092 .WillByDefault(Return(1));
3093 EXPECT_CALL(helper
, Helper(_
, _
));
3094 EXPECT_CALL(helper
, Helper(_
, _
))
3095 .With(AllArgs(Gt()))
3096 .WillOnce(Return(2));
3098 EXPECT_EQ(1, helper
.Helper('\1', 2));
3099 EXPECT_EQ(2, helper
.Helper('a', 1));
3102 class OptionalMatchersHelper
{
3104 OptionalMatchersHelper() {}
3106 MOCK_METHOD0(NoArgs
, int());
3108 MOCK_METHOD1(OneArg
, int(int y
));
3110 MOCK_METHOD2(TwoArgs
, int(char x
, int y
));
3112 MOCK_METHOD1(Overloaded
, int(char x
));
3113 MOCK_METHOD2(Overloaded
, int(char x
, int y
));
3116 GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper
);
3119 TEST(AllArgsTest
, WorksWithoutMatchers
) {
3120 OptionalMatchersHelper helper
;
3122 ON_CALL(helper
, NoArgs
).WillByDefault(Return(10));
3123 ON_CALL(helper
, OneArg
).WillByDefault(Return(20));
3124 ON_CALL(helper
, TwoArgs
).WillByDefault(Return(30));
3126 EXPECT_EQ(10, helper
.NoArgs());
3127 EXPECT_EQ(20, helper
.OneArg(1));
3128 EXPECT_EQ(30, helper
.TwoArgs('\1', 2));
3130 EXPECT_CALL(helper
, NoArgs
).Times(1);
3131 EXPECT_CALL(helper
, OneArg
).WillOnce(Return(100));
3132 EXPECT_CALL(helper
, OneArg(17)).WillOnce(Return(200));
3133 EXPECT_CALL(helper
, TwoArgs
).Times(0);
3135 EXPECT_EQ(10, helper
.NoArgs());
3136 EXPECT_EQ(100, helper
.OneArg(1));
3137 EXPECT_EQ(200, helper
.OneArg(17));
3140 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
3141 // matches the matcher.
3142 TEST(MatcherAssertionTest
, WorksWhenMatcherIsSatisfied
) {
3143 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
3144 ASSERT_THAT("Foo", EndsWith("oo"));
3145 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
3146 EXPECT_THAT("Hello", StartsWith("Hell"));
3149 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
3150 // doesn't match the matcher.
3151 TEST(MatcherAssertionTest
, WorksWhenMatcherIsNotSatisfied
) {
3152 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
3153 // which cannot reference auto variables.
3154 static unsigned short n
; // NOLINT
3157 // VC++ prior to version 8.0 SP1 has a bug where it will not see any
3158 // functions declared in the namespace scope from within nested classes.
3159 // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
3160 // namespace-level functions invoked inside them need to be explicitly
3162 EXPECT_FATAL_FAILURE(ASSERT_THAT(n
, ::testing::Gt(10)),
3164 "Expected: is > 10\n"
3165 " Actual: 5" + OfType("unsigned short"));
3167 EXPECT_NONFATAL_FAILURE(
3168 EXPECT_THAT(n
, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
3170 "Expected: (is <= 7) and (is >= 5)\n"
3171 " Actual: 0" + OfType("unsigned short"));
3174 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
3175 // has a reference type.
3176 TEST(MatcherAssertionTest
, WorksForByRefArguments
) {
3177 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
3178 // reference auto variables.
3181 EXPECT_THAT(n
, AllOf(Le(7), Ref(n
)));
3182 EXPECT_FATAL_FAILURE(ASSERT_THAT(n
, ::testing::Not(::testing::Ref(n
))),
3184 "Expected: does not reference the variable @");
3185 // Tests the "Actual" part.
3186 EXPECT_FATAL_FAILURE(ASSERT_THAT(n
, ::testing::Not(::testing::Ref(n
))),
3187 "Actual: 0" + OfType("int") + ", which is located @");
3190 #if !GTEST_OS_SYMBIAN
3191 // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
3194 // ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
3195 // Symbian compiler: it tries to compile
3196 // template<T, U> class MatcherCastImpl { ...
3197 // virtual bool MatchAndExplain(T x, ...) const {
3198 // return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
3199 // with U == string and T == const char*
3200 // With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
3201 // the compiler silently crashes with no output.
3202 // If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
3203 // the code compiles but the converted string is bogus.
3204 TEST(MatcherAssertionTest
, WorksForMonomorphicMatcher
) {
3205 Matcher
<const char*> starts_with_he
= StartsWith("he");
3206 ASSERT_THAT("hello", starts_with_he
);
3208 Matcher
<const std::string
&> ends_with_ok
= EndsWith("ok");
3209 ASSERT_THAT("book", ends_with_ok
);
3210 const std::string bad
= "bad";
3211 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad
, ends_with_ok
),
3213 "Expected: ends with \"ok\"\n"
3214 " Actual: \"bad\"");
3215 Matcher
<int> is_greater_than_5
= Gt(5);
3216 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5
),
3218 "Expected: is > 5\n"
3219 " Actual: 5" + OfType("int"));
3221 #endif // !GTEST_OS_SYMBIAN
3223 // Tests floating-point matchers.
3224 template <typename RawType
>
3225 class FloatingPointTest
: public testing::Test
{
3227 typedef testing::internal::FloatingPoint
<RawType
> Floating
;
3228 typedef typename
Floating::Bits Bits
;
3231 : max_ulps_(Floating::kMaxUlps
),
3232 zero_bits_(Floating(0).bits()),
3233 one_bits_(Floating(1).bits()),
3234 infinity_bits_(Floating(Floating::Infinity()).bits()),
3235 close_to_positive_zero_(
3236 Floating::ReinterpretBits(zero_bits_
+ max_ulps_
/2)),
3237 close_to_negative_zero_(
3238 -Floating::ReinterpretBits(zero_bits_
+ max_ulps_
- max_ulps_
/2)),
3239 further_from_negative_zero_(-Floating::ReinterpretBits(
3240 zero_bits_
+ max_ulps_
+ 1 - max_ulps_
/2)),
3241 close_to_one_(Floating::ReinterpretBits(one_bits_
+ max_ulps_
)),
3242 further_from_one_(Floating::ReinterpretBits(one_bits_
+ max_ulps_
+ 1)),
3243 infinity_(Floating::Infinity()),
3245 Floating::ReinterpretBits(infinity_bits_
- max_ulps_
)),
3246 further_from_infinity_(
3247 Floating::ReinterpretBits(infinity_bits_
- max_ulps_
- 1)),
3248 max_(Floating::Max()),
3249 nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask
| 1)),
3250 nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask
| 200)) {
3254 EXPECT_EQ(sizeof(RawType
), sizeof(Bits
));
3257 // A battery of tests for FloatingEqMatcher::Matches.
3258 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
3260 testing::internal::FloatingEqMatcher
<RawType
> (*matcher_maker
)(RawType
)) {
3261 Matcher
<RawType
> m1
= matcher_maker(0.0);
3262 EXPECT_TRUE(m1
.Matches(-0.0));
3263 EXPECT_TRUE(m1
.Matches(close_to_positive_zero_
));
3264 EXPECT_TRUE(m1
.Matches(close_to_negative_zero_
));
3265 EXPECT_FALSE(m1
.Matches(1.0));
3267 Matcher
<RawType
> m2
= matcher_maker(close_to_positive_zero_
);
3268 EXPECT_FALSE(m2
.Matches(further_from_negative_zero_
));
3270 Matcher
<RawType
> m3
= matcher_maker(1.0);
3271 EXPECT_TRUE(m3
.Matches(close_to_one_
));
3272 EXPECT_FALSE(m3
.Matches(further_from_one_
));
3274 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
3275 EXPECT_FALSE(m3
.Matches(0.0));
3277 Matcher
<RawType
> m4
= matcher_maker(-infinity_
);
3278 EXPECT_TRUE(m4
.Matches(-close_to_infinity_
));
3280 Matcher
<RawType
> m5
= matcher_maker(infinity_
);
3281 EXPECT_TRUE(m5
.Matches(close_to_infinity_
));
3283 // This is interesting as the representations of infinity_ and nan1_
3284 // are only 1 DLP apart.
3285 EXPECT_FALSE(m5
.Matches(nan1_
));
3287 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
3289 Matcher
<const RawType
&> m6
= matcher_maker(0.0);
3290 EXPECT_TRUE(m6
.Matches(-0.0));
3291 EXPECT_TRUE(m6
.Matches(close_to_positive_zero_
));
3292 EXPECT_FALSE(m6
.Matches(1.0));
3294 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
3296 Matcher
<RawType
&> m7
= matcher_maker(0.0);
3298 EXPECT_TRUE(m7
.Matches(x
));
3300 EXPECT_FALSE(m7
.Matches(x
));
3303 // Pre-calculated numbers to be used by the tests.
3305 const Bits max_ulps_
;
3307 const Bits zero_bits_
; // The bits that represent 0.0.
3308 const Bits one_bits_
; // The bits that represent 1.0.
3309 const Bits infinity_bits_
; // The bits that represent +infinity.
3311 // Some numbers close to 0.0.
3312 const RawType close_to_positive_zero_
;
3313 const RawType close_to_negative_zero_
;
3314 const RawType further_from_negative_zero_
;
3316 // Some numbers close to 1.0.
3317 const RawType close_to_one_
;
3318 const RawType further_from_one_
;
3320 // Some numbers close to +infinity.
3321 const RawType infinity_
;
3322 const RawType close_to_infinity_
;
3323 const RawType further_from_infinity_
;
3325 // Maximum representable value that's not infinity.
3329 const RawType nan1_
;
3330 const RawType nan2_
;
3333 // Tests floating-point matchers with fixed epsilons.
3334 template <typename RawType
>
3335 class FloatingPointNearTest
: public FloatingPointTest
<RawType
> {
3337 typedef FloatingPointTest
<RawType
> ParentType
;
3339 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
3340 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
3341 void TestNearMatches(
3342 testing::internal::FloatingEqMatcher
<RawType
>
3343 (*matcher_maker
)(RawType
, RawType
)) {
3344 Matcher
<RawType
> m1
= matcher_maker(0.0, 0.0);
3345 EXPECT_TRUE(m1
.Matches(0.0));
3346 EXPECT_TRUE(m1
.Matches(-0.0));
3347 EXPECT_FALSE(m1
.Matches(ParentType::close_to_positive_zero_
));
3348 EXPECT_FALSE(m1
.Matches(ParentType::close_to_negative_zero_
));
3349 EXPECT_FALSE(m1
.Matches(1.0));
3351 Matcher
<RawType
> m2
= matcher_maker(0.0, 1.0);
3352 EXPECT_TRUE(m2
.Matches(0.0));
3353 EXPECT_TRUE(m2
.Matches(-0.0));
3354 EXPECT_TRUE(m2
.Matches(1.0));
3355 EXPECT_TRUE(m2
.Matches(-1.0));
3356 EXPECT_FALSE(m2
.Matches(ParentType::close_to_one_
));
3357 EXPECT_FALSE(m2
.Matches(-ParentType::close_to_one_
));
3359 // Check that inf matches inf, regardless of the of the specified max
3361 Matcher
<RawType
> m3
= matcher_maker(ParentType::infinity_
, 0.0);
3362 EXPECT_TRUE(m3
.Matches(ParentType::infinity_
));
3363 EXPECT_FALSE(m3
.Matches(ParentType::close_to_infinity_
));
3364 EXPECT_FALSE(m3
.Matches(-ParentType::infinity_
));
3366 Matcher
<RawType
> m4
= matcher_maker(-ParentType::infinity_
, 0.0);
3367 EXPECT_TRUE(m4
.Matches(-ParentType::infinity_
));
3368 EXPECT_FALSE(m4
.Matches(-ParentType::close_to_infinity_
));
3369 EXPECT_FALSE(m4
.Matches(ParentType::infinity_
));
3371 // Test various overflow scenarios.
3372 Matcher
<RawType
> m5
= matcher_maker(ParentType::max_
, ParentType::max_
);
3373 EXPECT_TRUE(m5
.Matches(ParentType::max_
));
3374 EXPECT_FALSE(m5
.Matches(-ParentType::max_
));
3376 Matcher
<RawType
> m6
= matcher_maker(-ParentType::max_
, ParentType::max_
);
3377 EXPECT_FALSE(m6
.Matches(ParentType::max_
));
3378 EXPECT_TRUE(m6
.Matches(-ParentType::max_
));
3380 Matcher
<RawType
> m7
= matcher_maker(ParentType::max_
, 0);
3381 EXPECT_TRUE(m7
.Matches(ParentType::max_
));
3382 EXPECT_FALSE(m7
.Matches(-ParentType::max_
));
3384 Matcher
<RawType
> m8
= matcher_maker(-ParentType::max_
, 0);
3385 EXPECT_FALSE(m8
.Matches(ParentType::max_
));
3386 EXPECT_TRUE(m8
.Matches(-ParentType::max_
));
3388 // The difference between max() and -max() normally overflows to infinity,
3389 // but it should still match if the max_abs_error is also infinity.
3390 Matcher
<RawType
> m9
= matcher_maker(
3391 ParentType::max_
, ParentType::infinity_
);
3392 EXPECT_TRUE(m8
.Matches(-ParentType::max_
));
3394 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
3396 Matcher
<const RawType
&> m10
= matcher_maker(0.0, 1.0);
3397 EXPECT_TRUE(m10
.Matches(-0.0));
3398 EXPECT_TRUE(m10
.Matches(ParentType::close_to_positive_zero_
));
3399 EXPECT_FALSE(m10
.Matches(ParentType::close_to_one_
));
3401 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
3403 Matcher
<RawType
&> m11
= matcher_maker(0.0, 1.0);
3405 EXPECT_TRUE(m11
.Matches(x
));
3407 EXPECT_TRUE(m11
.Matches(x
));
3409 EXPECT_TRUE(m11
.Matches(x
));
3411 EXPECT_FALSE(m11
.Matches(x
));
3413 EXPECT_FALSE(m11
.Matches(x
));
3417 // Instantiate FloatingPointTest for testing floats.
3418 typedef FloatingPointTest
<float> FloatTest
;
3420 TEST_F(FloatTest
, FloatEqApproximatelyMatchesFloats
) {
3421 TestMatches(&FloatEq
);
3424 TEST_F(FloatTest
, NanSensitiveFloatEqApproximatelyMatchesFloats
) {
3425 TestMatches(&NanSensitiveFloatEq
);
3428 TEST_F(FloatTest
, FloatEqCannotMatchNaN
) {
3429 // FloatEq never matches NaN.
3430 Matcher
<float> m
= FloatEq(nan1_
);
3431 EXPECT_FALSE(m
.Matches(nan1_
));
3432 EXPECT_FALSE(m
.Matches(nan2_
));
3433 EXPECT_FALSE(m
.Matches(1.0));
3436 TEST_F(FloatTest
, NanSensitiveFloatEqCanMatchNaN
) {
3437 // NanSensitiveFloatEq will match NaN.
3438 Matcher
<float> m
= NanSensitiveFloatEq(nan1_
);
3439 EXPECT_TRUE(m
.Matches(nan1_
));
3440 EXPECT_TRUE(m
.Matches(nan2_
));
3441 EXPECT_FALSE(m
.Matches(1.0));
3444 TEST_F(FloatTest
, FloatEqCanDescribeSelf
) {
3445 Matcher
<float> m1
= FloatEq(2.0f
);
3446 EXPECT_EQ("is approximately 2", Describe(m1
));
3447 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1
));
3449 Matcher
<float> m2
= FloatEq(0.5f
);
3450 EXPECT_EQ("is approximately 0.5", Describe(m2
));
3451 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2
));
3453 Matcher
<float> m3
= FloatEq(nan1_
);
3454 EXPECT_EQ("never matches", Describe(m3
));
3455 EXPECT_EQ("is anything", DescribeNegation(m3
));
3458 TEST_F(FloatTest
, NanSensitiveFloatEqCanDescribeSelf
) {
3459 Matcher
<float> m1
= NanSensitiveFloatEq(2.0f
);
3460 EXPECT_EQ("is approximately 2", Describe(m1
));
3461 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1
));
3463 Matcher
<float> m2
= NanSensitiveFloatEq(0.5f
);
3464 EXPECT_EQ("is approximately 0.5", Describe(m2
));
3465 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2
));
3467 Matcher
<float> m3
= NanSensitiveFloatEq(nan1_
);
3468 EXPECT_EQ("is NaN", Describe(m3
));
3469 EXPECT_EQ("isn't NaN", DescribeNegation(m3
));
3472 // Instantiate FloatingPointTest for testing floats with a user-specified
3473 // max absolute error.
3474 typedef FloatingPointNearTest
<float> FloatNearTest
;
3476 TEST_F(FloatNearTest
, FloatNearMatches
) {
3477 TestNearMatches(&FloatNear
);
3480 TEST_F(FloatNearTest
, NanSensitiveFloatNearApproximatelyMatchesFloats
) {
3481 TestNearMatches(&NanSensitiveFloatNear
);
3484 TEST_F(FloatNearTest
, FloatNearCanDescribeSelf
) {
3485 Matcher
<float> m1
= FloatNear(2.0f
, 0.5f
);
3486 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1
));
3488 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1
));
3490 Matcher
<float> m2
= FloatNear(0.5f
, 0.5f
);
3491 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2
));
3493 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2
));
3495 Matcher
<float> m3
= FloatNear(nan1_
, 0.0);
3496 EXPECT_EQ("never matches", Describe(m3
));
3497 EXPECT_EQ("is anything", DescribeNegation(m3
));
3500 TEST_F(FloatNearTest
, NanSensitiveFloatNearCanDescribeSelf
) {
3501 Matcher
<float> m1
= NanSensitiveFloatNear(2.0f
, 0.5f
);
3502 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1
));
3504 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1
));
3506 Matcher
<float> m2
= NanSensitiveFloatNear(0.5f
, 0.5f
);
3507 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2
));
3509 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2
));
3511 Matcher
<float> m3
= NanSensitiveFloatNear(nan1_
, 0.1f
);
3512 EXPECT_EQ("is NaN", Describe(m3
));
3513 EXPECT_EQ("isn't NaN", DescribeNegation(m3
));
3516 TEST_F(FloatNearTest
, FloatNearCannotMatchNaN
) {
3517 // FloatNear never matches NaN.
3518 Matcher
<float> m
= FloatNear(ParentType::nan1_
, 0.1f
);
3519 EXPECT_FALSE(m
.Matches(nan1_
));
3520 EXPECT_FALSE(m
.Matches(nan2_
));
3521 EXPECT_FALSE(m
.Matches(1.0));
3524 TEST_F(FloatNearTest
, NanSensitiveFloatNearCanMatchNaN
) {
3525 // NanSensitiveFloatNear will match NaN.
3526 Matcher
<float> m
= NanSensitiveFloatNear(nan1_
, 0.1f
);
3527 EXPECT_TRUE(m
.Matches(nan1_
));
3528 EXPECT_TRUE(m
.Matches(nan2_
));
3529 EXPECT_FALSE(m
.Matches(1.0));
3532 // Instantiate FloatingPointTest for testing doubles.
3533 typedef FloatingPointTest
<double> DoubleTest
;
3535 TEST_F(DoubleTest
, DoubleEqApproximatelyMatchesDoubles
) {
3536 TestMatches(&DoubleEq
);
3539 TEST_F(DoubleTest
, NanSensitiveDoubleEqApproximatelyMatchesDoubles
) {
3540 TestMatches(&NanSensitiveDoubleEq
);
3543 TEST_F(DoubleTest
, DoubleEqCannotMatchNaN
) {
3544 // DoubleEq never matches NaN.
3545 Matcher
<double> m
= DoubleEq(nan1_
);
3546 EXPECT_FALSE(m
.Matches(nan1_
));
3547 EXPECT_FALSE(m
.Matches(nan2_
));
3548 EXPECT_FALSE(m
.Matches(1.0));
3551 TEST_F(DoubleTest
, NanSensitiveDoubleEqCanMatchNaN
) {
3552 // NanSensitiveDoubleEq will match NaN.
3553 Matcher
<double> m
= NanSensitiveDoubleEq(nan1_
);
3554 EXPECT_TRUE(m
.Matches(nan1_
));
3555 EXPECT_TRUE(m
.Matches(nan2_
));
3556 EXPECT_FALSE(m
.Matches(1.0));
3559 TEST_F(DoubleTest
, DoubleEqCanDescribeSelf
) {
3560 Matcher
<double> m1
= DoubleEq(2.0);
3561 EXPECT_EQ("is approximately 2", Describe(m1
));
3562 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1
));
3564 Matcher
<double> m2
= DoubleEq(0.5);
3565 EXPECT_EQ("is approximately 0.5", Describe(m2
));
3566 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2
));
3568 Matcher
<double> m3
= DoubleEq(nan1_
);
3569 EXPECT_EQ("never matches", Describe(m3
));
3570 EXPECT_EQ("is anything", DescribeNegation(m3
));
3573 TEST_F(DoubleTest
, NanSensitiveDoubleEqCanDescribeSelf
) {
3574 Matcher
<double> m1
= NanSensitiveDoubleEq(2.0);
3575 EXPECT_EQ("is approximately 2", Describe(m1
));
3576 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1
));
3578 Matcher
<double> m2
= NanSensitiveDoubleEq(0.5);
3579 EXPECT_EQ("is approximately 0.5", Describe(m2
));
3580 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2
));
3582 Matcher
<double> m3
= NanSensitiveDoubleEq(nan1_
);
3583 EXPECT_EQ("is NaN", Describe(m3
));
3584 EXPECT_EQ("isn't NaN", DescribeNegation(m3
));
3587 // Instantiate FloatingPointTest for testing floats with a user-specified
3588 // max absolute error.
3589 typedef FloatingPointNearTest
<double> DoubleNearTest
;
3591 TEST_F(DoubleNearTest
, DoubleNearMatches
) {
3592 TestNearMatches(&DoubleNear
);
3595 TEST_F(DoubleNearTest
, NanSensitiveDoubleNearApproximatelyMatchesDoubles
) {
3596 TestNearMatches(&NanSensitiveDoubleNear
);
3599 TEST_F(DoubleNearTest
, DoubleNearCanDescribeSelf
) {
3600 Matcher
<double> m1
= DoubleNear(2.0, 0.5);
3601 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1
));
3603 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1
));
3605 Matcher
<double> m2
= DoubleNear(0.5, 0.5);
3606 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2
));
3608 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2
));
3610 Matcher
<double> m3
= DoubleNear(nan1_
, 0.0);
3611 EXPECT_EQ("never matches", Describe(m3
));
3612 EXPECT_EQ("is anything", DescribeNegation(m3
));
3615 TEST_F(DoubleNearTest
, ExplainsResultWhenMatchFails
) {
3616 EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
3617 EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
3618 EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
3620 const std::string explanation
=
3621 Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
3622 // Different C++ implementations may print floating-point numbers
3623 // slightly differently.
3624 EXPECT_TRUE(explanation
== "which is 1.2e-10 from 2.1" || // GCC
3625 explanation
== "which is 1.2e-010 from 2.1") // MSVC
3626 << " where explanation is \"" << explanation
<< "\".";
3629 TEST_F(DoubleNearTest
, NanSensitiveDoubleNearCanDescribeSelf
) {
3630 Matcher
<double> m1
= NanSensitiveDoubleNear(2.0, 0.5);
3631 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1
));
3633 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1
));
3635 Matcher
<double> m2
= NanSensitiveDoubleNear(0.5, 0.5);
3636 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2
));
3638 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2
));
3640 Matcher
<double> m3
= NanSensitiveDoubleNear(nan1_
, 0.1);
3641 EXPECT_EQ("is NaN", Describe(m3
));
3642 EXPECT_EQ("isn't NaN", DescribeNegation(m3
));
3645 TEST_F(DoubleNearTest
, DoubleNearCannotMatchNaN
) {
3646 // DoubleNear never matches NaN.
3647 Matcher
<double> m
= DoubleNear(ParentType::nan1_
, 0.1);
3648 EXPECT_FALSE(m
.Matches(nan1_
));
3649 EXPECT_FALSE(m
.Matches(nan2_
));
3650 EXPECT_FALSE(m
.Matches(1.0));
3653 TEST_F(DoubleNearTest
, NanSensitiveDoubleNearCanMatchNaN
) {
3654 // NanSensitiveDoubleNear will match NaN.
3655 Matcher
<double> m
= NanSensitiveDoubleNear(nan1_
, 0.1);
3656 EXPECT_TRUE(m
.Matches(nan1_
));
3657 EXPECT_TRUE(m
.Matches(nan2_
));
3658 EXPECT_FALSE(m
.Matches(1.0));
3661 TEST(PointeeTest
, RawPointer
) {
3662 const Matcher
<int*> m
= Pointee(Ge(0));
3665 EXPECT_TRUE(m
.Matches(&n
));
3667 EXPECT_FALSE(m
.Matches(&n
));
3668 EXPECT_FALSE(m
.Matches(NULL
));
3671 TEST(PointeeTest
, RawPointerToConst
) {
3672 const Matcher
<const double*> m
= Pointee(Ge(0));
3675 EXPECT_TRUE(m
.Matches(&x
));
3677 EXPECT_FALSE(m
.Matches(&x
));
3678 EXPECT_FALSE(m
.Matches(NULL
));
3681 TEST(PointeeTest
, ReferenceToConstRawPointer
) {
3682 const Matcher
<int* const &> m
= Pointee(Ge(0));
3685 EXPECT_TRUE(m
.Matches(&n
));
3687 EXPECT_FALSE(m
.Matches(&n
));
3688 EXPECT_FALSE(m
.Matches(NULL
));
3691 TEST(PointeeTest
, ReferenceToNonConstRawPointer
) {
3692 const Matcher
<double* &> m
= Pointee(Ge(0));
3696 EXPECT_TRUE(m
.Matches(p
));
3698 EXPECT_FALSE(m
.Matches(p
));
3700 EXPECT_FALSE(m
.Matches(p
));
3703 MATCHER_P(FieldIIs
, inner_matcher
, "") {
3704 return ExplainMatchResult(inner_matcher
, arg
.i
, result_listener
);
3708 TEST(WhenDynamicCastToTest
, SameType
) {
3712 // Right type. A pointer is passed down.
3713 Base
* as_base_ptr
= &derived
;
3714 EXPECT_THAT(as_base_ptr
, WhenDynamicCastTo
<Derived
*>(Not(IsNull())));
3715 EXPECT_THAT(as_base_ptr
, WhenDynamicCastTo
<Derived
*>(Pointee(FieldIIs(4))));
3716 EXPECT_THAT(as_base_ptr
,
3717 Not(WhenDynamicCastTo
<Derived
*>(Pointee(FieldIIs(5)))));
3720 TEST(WhenDynamicCastToTest
, WrongTypes
) {
3723 OtherDerived other_derived
;
3725 // Wrong types. NULL is passed.
3726 EXPECT_THAT(&base
, Not(WhenDynamicCastTo
<Derived
*>(Pointee(_
))));
3727 EXPECT_THAT(&base
, WhenDynamicCastTo
<Derived
*>(IsNull()));
3728 Base
* as_base_ptr
= &derived
;
3729 EXPECT_THAT(as_base_ptr
, Not(WhenDynamicCastTo
<OtherDerived
*>(Pointee(_
))));
3730 EXPECT_THAT(as_base_ptr
, WhenDynamicCastTo
<OtherDerived
*>(IsNull()));
3731 as_base_ptr
= &other_derived
;
3732 EXPECT_THAT(as_base_ptr
, Not(WhenDynamicCastTo
<Derived
*>(Pointee(_
))));
3733 EXPECT_THAT(as_base_ptr
, WhenDynamicCastTo
<Derived
*>(IsNull()));
3736 TEST(WhenDynamicCastToTest
, AlreadyNull
) {
3738 Base
* as_base_ptr
= NULL
;
3739 EXPECT_THAT(as_base_ptr
, WhenDynamicCastTo
<Derived
*>(IsNull()));
3742 struct AmbiguousCastTypes
{
3743 class VirtualDerived
: public virtual Base
{};
3744 class DerivedSub1
: public VirtualDerived
{};
3745 class DerivedSub2
: public VirtualDerived
{};
3746 class ManyDerivedInHierarchy
: public DerivedSub1
, public DerivedSub2
{};
3749 TEST(WhenDynamicCastToTest
, AmbiguousCast
) {
3750 AmbiguousCastTypes::DerivedSub1 sub1
;
3751 AmbiguousCastTypes::ManyDerivedInHierarchy many_derived
;
3752 // Multiply derived from Base. dynamic_cast<> returns NULL.
3754 static_cast<AmbiguousCastTypes::DerivedSub1
*>(&many_derived
);
3755 EXPECT_THAT(as_base_ptr
,
3756 WhenDynamicCastTo
<AmbiguousCastTypes::VirtualDerived
*>(IsNull()));
3757 as_base_ptr
= &sub1
;
3760 WhenDynamicCastTo
<AmbiguousCastTypes::VirtualDerived
*>(Not(IsNull())));
3763 TEST(WhenDynamicCastToTest
, Describe
) {
3764 Matcher
<Base
*> matcher
= WhenDynamicCastTo
<Derived
*>(Pointee(_
));
3765 const std::string prefix
=
3766 "when dynamic_cast to " + internal::GetTypeName
<Derived
*>() + ", ";
3767 EXPECT_EQ(prefix
+ "points to a value that is anything", Describe(matcher
));
3768 EXPECT_EQ(prefix
+ "does not point to a value that is anything",
3769 DescribeNegation(matcher
));
3772 TEST(WhenDynamicCastToTest
, Explain
) {
3773 Matcher
<Base
*> matcher
= WhenDynamicCastTo
<Derived
*>(Pointee(_
));
3775 EXPECT_THAT(Explain(matcher
, null
), HasSubstr("NULL"));
3777 EXPECT_TRUE(matcher
.Matches(&derived
));
3778 EXPECT_THAT(Explain(matcher
, &derived
), HasSubstr("which points to "));
3780 // With references, the matcher itself can fail. Test for that one.
3781 Matcher
<const Base
&> ref_matcher
= WhenDynamicCastTo
<const OtherDerived
&>(_
);
3782 EXPECT_THAT(Explain(ref_matcher
, derived
),
3783 HasSubstr("which cannot be dynamic_cast"));
3786 TEST(WhenDynamicCastToTest
, GoodReference
) {
3789 Base
& as_base_ref
= derived
;
3790 EXPECT_THAT(as_base_ref
, WhenDynamicCastTo
<const Derived
&>(FieldIIs(4)));
3791 EXPECT_THAT(as_base_ref
, WhenDynamicCastTo
<const Derived
&>(Not(FieldIIs(5))));
3794 TEST(WhenDynamicCastToTest
, BadReference
) {
3796 Base
& as_base_ref
= derived
;
3797 EXPECT_THAT(as_base_ref
, Not(WhenDynamicCastTo
<const OtherDerived
&>(_
)));
3799 #endif // GTEST_HAS_RTTI
3801 // Minimal const-propagating pointer.
3802 template <typename T
>
3803 class ConstPropagatingPtr
{
3805 typedef T element_type
;
3807 ConstPropagatingPtr() : val_() {}
3808 explicit ConstPropagatingPtr(T
* t
) : val_(t
) {}
3809 ConstPropagatingPtr(const ConstPropagatingPtr
& other
) : val_(other
.val_
) {}
3811 T
* get() { return val_
; }
3812 T
& operator*() { return *val_
; }
3813 // Most smart pointers return non-const T* and T& from the next methods.
3814 const T
* get() const { return val_
; }
3815 const T
& operator*() const { return *val_
; }
3821 TEST(PointeeTest
, WorksWithConstPropagatingPointers
) {
3822 const Matcher
< ConstPropagatingPtr
<int> > m
= Pointee(Lt(5));
3824 const ConstPropagatingPtr
<int> co(&three
);
3825 ConstPropagatingPtr
<int> o(&three
);
3826 EXPECT_TRUE(m
.Matches(o
));
3827 EXPECT_TRUE(m
.Matches(co
));
3829 EXPECT_FALSE(m
.Matches(o
));
3830 EXPECT_FALSE(m
.Matches(ConstPropagatingPtr
<int>()));
3833 TEST(PointeeTest
, NeverMatchesNull
) {
3834 const Matcher
<const char*> m
= Pointee(_
);
3835 EXPECT_FALSE(m
.Matches(NULL
));
3838 // Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3839 TEST(PointeeTest
, MatchesAgainstAValue
) {
3840 const Matcher
<int*> m
= Pointee(5);
3843 EXPECT_TRUE(m
.Matches(&n
));
3845 EXPECT_FALSE(m
.Matches(&n
));
3846 EXPECT_FALSE(m
.Matches(NULL
));
3849 TEST(PointeeTest
, CanDescribeSelf
) {
3850 const Matcher
<int*> m
= Pointee(Gt(3));
3851 EXPECT_EQ("points to a value that is > 3", Describe(m
));
3852 EXPECT_EQ("does not point to a value that is > 3",
3853 DescribeNegation(m
));
3856 TEST(PointeeTest
, CanExplainMatchResult
) {
3857 const Matcher
<const std::string
*> m
= Pointee(StartsWith("Hi"));
3859 EXPECT_EQ("", Explain(m
, static_cast<const std::string
*>(NULL
)));
3861 const Matcher
<long*> m2
= Pointee(GreaterThan(1)); // NOLINT
3862 long n
= 3; // NOLINT
3863 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
3867 TEST(PointeeTest
, AlwaysExplainsPointee
) {
3868 const Matcher
<int*> m
= Pointee(0);
3870 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m
, &n
));
3873 // An uncopyable class.
3876 Uncopyable() : value_(-1) {}
3877 explicit Uncopyable(int a_value
) : value_(a_value
) {}
3879 int value() const { return value_
; }
3880 void set_value(int i
) { value_
= i
; }
3884 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable
);
3887 // Returns true iff x.value() is positive.
3888 bool ValueIsPositive(const Uncopyable
& x
) { return x
.value() > 0; }
3890 MATCHER_P(UncopyableIs
, inner_matcher
, "") {
3891 return ExplainMatchResult(inner_matcher
, arg
.value(), result_listener
);
3894 // A user-defined struct for testing Field().
3896 AStruct() : x(0), y(1.0), z(5), p(NULL
) {}
3897 AStruct(const AStruct
& rhs
)
3898 : x(rhs
.x
), y(rhs
.y
), z(rhs
.z
.value()), p(rhs
.p
) {}
3900 int x
; // A non-const field.
3901 const double y
; // A const field.
3902 Uncopyable z
; // An uncopyable field.
3903 const char* p
; // A pointer field.
3906 GTEST_DISALLOW_ASSIGN_(AStruct
);
3909 // A derived struct for testing Field().
3910 struct DerivedStruct
: public AStruct
{
3914 GTEST_DISALLOW_ASSIGN_(DerivedStruct
);
3917 // Tests that Field(&Foo::field, ...) works when field is non-const.
3918 TEST(FieldTest
, WorksForNonConstField
) {
3919 Matcher
<AStruct
> m
= Field(&AStruct::x
, Ge(0));
3920 Matcher
<AStruct
> m_with_name
= Field("x", &AStruct::x
, Ge(0));
3923 EXPECT_TRUE(m
.Matches(a
));
3924 EXPECT_TRUE(m_with_name
.Matches(a
));
3926 EXPECT_FALSE(m
.Matches(a
));
3927 EXPECT_FALSE(m_with_name
.Matches(a
));
3930 // Tests that Field(&Foo::field, ...) works when field is const.
3931 TEST(FieldTest
, WorksForConstField
) {
3934 Matcher
<AStruct
> m
= Field(&AStruct::y
, Ge(0.0));
3935 Matcher
<AStruct
> m_with_name
= Field("y", &AStruct::y
, Ge(0.0));
3936 EXPECT_TRUE(m
.Matches(a
));
3937 EXPECT_TRUE(m_with_name
.Matches(a
));
3938 m
= Field(&AStruct::y
, Le(0.0));
3939 m_with_name
= Field("y", &AStruct::y
, Le(0.0));
3940 EXPECT_FALSE(m
.Matches(a
));
3941 EXPECT_FALSE(m_with_name
.Matches(a
));
3944 // Tests that Field(&Foo::field, ...) works when field is not copyable.
3945 TEST(FieldTest
, WorksForUncopyableField
) {
3948 Matcher
<AStruct
> m
= Field(&AStruct::z
, Truly(ValueIsPositive
));
3949 EXPECT_TRUE(m
.Matches(a
));
3950 m
= Field(&AStruct::z
, Not(Truly(ValueIsPositive
)));
3951 EXPECT_FALSE(m
.Matches(a
));
3954 // Tests that Field(&Foo::field, ...) works when field is a pointer.
3955 TEST(FieldTest
, WorksForPointerField
) {
3956 // Matching against NULL.
3957 Matcher
<AStruct
> m
= Field(&AStruct::p
, static_cast<const char*>(NULL
));
3959 EXPECT_TRUE(m
.Matches(a
));
3961 EXPECT_FALSE(m
.Matches(a
));
3963 // Matching a pointer that is not NULL.
3964 m
= Field(&AStruct::p
, StartsWith("hi"));
3966 EXPECT_TRUE(m
.Matches(a
));
3968 EXPECT_FALSE(m
.Matches(a
));
3971 // Tests that Field() works when the object is passed by reference.
3972 TEST(FieldTest
, WorksForByRefArgument
) {
3973 Matcher
<const AStruct
&> m
= Field(&AStruct::x
, Ge(0));
3976 EXPECT_TRUE(m
.Matches(a
));
3978 EXPECT_FALSE(m
.Matches(a
));
3981 // Tests that Field(&Foo::field, ...) works when the argument's type
3982 // is a sub-type of Foo.
3983 TEST(FieldTest
, WorksForArgumentOfSubType
) {
3984 // Note that the matcher expects DerivedStruct but we say AStruct
3986 Matcher
<const DerivedStruct
&> m
= Field(&AStruct::x
, Ge(0));
3989 EXPECT_TRUE(m
.Matches(d
));
3991 EXPECT_FALSE(m
.Matches(d
));
3994 // Tests that Field(&Foo::field, m) works when field's type and m's
3995 // argument type are compatible but not the same.
3996 TEST(FieldTest
, WorksForCompatibleMatcherType
) {
3997 // The field is an int, but the inner matcher expects a signed char.
3998 Matcher
<const AStruct
&> m
= Field(&AStruct::x
,
3999 Matcher
<signed char>(Ge(0)));
4002 EXPECT_TRUE(m
.Matches(a
));
4004 EXPECT_FALSE(m
.Matches(a
));
4007 // Tests that Field() can describe itself.
4008 TEST(FieldTest
, CanDescribeSelf
) {
4009 Matcher
<const AStruct
&> m
= Field(&AStruct::x
, Ge(0));
4011 EXPECT_EQ("is an object whose given field is >= 0", Describe(m
));
4012 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m
));
4015 TEST(FieldTest
, CanDescribeSelfWithFieldName
) {
4016 Matcher
<const AStruct
&> m
= Field("field_name", &AStruct::x
, Ge(0));
4018 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m
));
4019 EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
4020 DescribeNegation(m
));
4023 // Tests that Field() can explain the match result.
4024 TEST(FieldTest
, CanExplainMatchResult
) {
4025 Matcher
<const AStruct
&> m
= Field(&AStruct::x
, Ge(0));
4029 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m
, a
));
4031 m
= Field(&AStruct::x
, GreaterThan(0));
4033 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
4037 TEST(FieldTest
, CanExplainMatchResultWithFieldName
) {
4038 Matcher
<const AStruct
&> m
= Field("field_name", &AStruct::x
, Ge(0));
4042 EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m
, a
));
4044 m
= Field("field_name", &AStruct::x
, GreaterThan(0));
4045 EXPECT_EQ("whose field `field_name` is 1" + OfType("int") +
4046 ", which is 1 more than 0",
4050 // Tests that Field() works when the argument is a pointer to const.
4051 TEST(FieldForPointerTest
, WorksForPointerToConst
) {
4052 Matcher
<const AStruct
*> m
= Field(&AStruct::x
, Ge(0));
4055 EXPECT_TRUE(m
.Matches(&a
));
4057 EXPECT_FALSE(m
.Matches(&a
));
4060 // Tests that Field() works when the argument is a pointer to non-const.
4061 TEST(FieldForPointerTest
, WorksForPointerToNonConst
) {
4062 Matcher
<AStruct
*> m
= Field(&AStruct::x
, Ge(0));
4065 EXPECT_TRUE(m
.Matches(&a
));
4067 EXPECT_FALSE(m
.Matches(&a
));
4070 // Tests that Field() works when the argument is a reference to a const pointer.
4071 TEST(FieldForPointerTest
, WorksForReferenceToConstPointer
) {
4072 Matcher
<AStruct
* const&> m
= Field(&AStruct::x
, Ge(0));
4075 EXPECT_TRUE(m
.Matches(&a
));
4077 EXPECT_FALSE(m
.Matches(&a
));
4080 // Tests that Field() does not match the NULL pointer.
4081 TEST(FieldForPointerTest
, DoesNotMatchNull
) {
4082 Matcher
<const AStruct
*> m
= Field(&AStruct::x
, _
);
4083 EXPECT_FALSE(m
.Matches(NULL
));
4086 // Tests that Field(&Foo::field, ...) works when the argument's type
4087 // is a sub-type of const Foo*.
4088 TEST(FieldForPointerTest
, WorksForArgumentOfSubType
) {
4089 // Note that the matcher expects DerivedStruct but we say AStruct
4091 Matcher
<DerivedStruct
*> m
= Field(&AStruct::x
, Ge(0));
4094 EXPECT_TRUE(m
.Matches(&d
));
4096 EXPECT_FALSE(m
.Matches(&d
));
4099 // Tests that Field() can describe itself when used to match a pointer.
4100 TEST(FieldForPointerTest
, CanDescribeSelf
) {
4101 Matcher
<const AStruct
*> m
= Field(&AStruct::x
, Ge(0));
4103 EXPECT_EQ("is an object whose given field is >= 0", Describe(m
));
4104 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m
));
4107 TEST(FieldForPointerTest
, CanDescribeSelfWithFieldName
) {
4108 Matcher
<const AStruct
*> m
= Field("field_name", &AStruct::x
, Ge(0));
4110 EXPECT_EQ("is an object whose field `field_name` is >= 0", Describe(m
));
4111 EXPECT_EQ("is an object whose field `field_name` isn't >= 0",
4112 DescribeNegation(m
));
4115 // Tests that Field() can explain the result of matching a pointer.
4116 TEST(FieldForPointerTest
, CanExplainMatchResult
) {
4117 Matcher
<const AStruct
*> m
= Field(&AStruct::x
, Ge(0));
4121 EXPECT_EQ("", Explain(m
, static_cast<const AStruct
*>(NULL
)));
4122 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
4125 m
= Field(&AStruct::x
, GreaterThan(0));
4126 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
4127 ", which is 1 more than 0", Explain(m
, &a
));
4130 TEST(FieldForPointerTest
, CanExplainMatchResultWithFieldName
) {
4131 Matcher
<const AStruct
*> m
= Field("field_name", &AStruct::x
, Ge(0));
4135 EXPECT_EQ("", Explain(m
, static_cast<const AStruct
*>(NULL
)));
4137 "which points to an object whose field `field_name` is 1" + OfType("int"),
4140 m
= Field("field_name", &AStruct::x
, GreaterThan(0));
4141 EXPECT_EQ("which points to an object whose field `field_name` is 1" +
4142 OfType("int") + ", which is 1 more than 0",
4146 // A user-defined class for testing Property().
4151 // A getter that returns a non-reference.
4152 int n() const { return n_
; }
4154 void set_n(int new_n
) { n_
= new_n
; }
4156 // A getter that returns a reference to const.
4157 const std::string
& s() const { return s_
; }
4159 #if GTEST_LANG_CXX11
4160 const std::string
& s_ref() const & { return s_
; }
4163 void set_s(const std::string
& new_s
) { s_
= new_s
; }
4165 // A getter that returns a reference to non-const.
4166 double& x() const { return x_
; }
4175 double AClass::x_
= 0.0;
4177 // A derived class for testing Property().
4178 class DerivedClass
: public AClass
{
4180 int k() const { return k_
; }
4185 // Tests that Property(&Foo::property, ...) works when property()
4186 // returns a non-reference.
4187 TEST(PropertyTest
, WorksForNonReferenceProperty
) {
4188 Matcher
<const AClass
&> m
= Property(&AClass::n
, Ge(0));
4189 Matcher
<const AClass
&> m_with_name
= Property("n", &AClass::n
, Ge(0));
4193 EXPECT_TRUE(m
.Matches(a
));
4194 EXPECT_TRUE(m_with_name
.Matches(a
));
4197 EXPECT_FALSE(m
.Matches(a
));
4198 EXPECT_FALSE(m_with_name
.Matches(a
));
4201 // Tests that Property(&Foo::property, ...) works when property()
4202 // returns a reference to const.
4203 TEST(PropertyTest
, WorksForReferenceToConstProperty
) {
4204 Matcher
<const AClass
&> m
= Property(&AClass::s
, StartsWith("hi"));
4205 Matcher
<const AClass
&> m_with_name
=
4206 Property("s", &AClass::s
, StartsWith("hi"));
4210 EXPECT_TRUE(m
.Matches(a
));
4211 EXPECT_TRUE(m_with_name
.Matches(a
));
4214 EXPECT_FALSE(m
.Matches(a
));
4215 EXPECT_FALSE(m_with_name
.Matches(a
));
4218 #if GTEST_LANG_CXX11
4219 // Tests that Property(&Foo::property, ...) works when property() is
4221 TEST(PropertyTest
, WorksForRefQualifiedProperty
) {
4222 Matcher
<const AClass
&> m
= Property(&AClass::s_ref
, StartsWith("hi"));
4226 EXPECT_TRUE(m
.Matches(a
));
4229 EXPECT_FALSE(m
.Matches(a
));
4233 // Tests that Property(&Foo::property, ...) works when property()
4234 // returns a reference to non-const.
4235 TEST(PropertyTest
, WorksForReferenceToNonConstProperty
) {
4239 Matcher
<const AClass
&> m
= Property(&AClass::x
, Ref(x
));
4240 EXPECT_FALSE(m
.Matches(a
));
4242 m
= Property(&AClass::x
, Not(Ref(x
)));
4243 EXPECT_TRUE(m
.Matches(a
));
4246 // Tests that Property(&Foo::property, ...) works when the argument is
4248 TEST(PropertyTest
, WorksForByValueArgument
) {
4249 Matcher
<AClass
> m
= Property(&AClass::s
, StartsWith("hi"));
4253 EXPECT_TRUE(m
.Matches(a
));
4256 EXPECT_FALSE(m
.Matches(a
));
4259 // Tests that Property(&Foo::property, ...) works when the argument's
4260 // type is a sub-type of Foo.
4261 TEST(PropertyTest
, WorksForArgumentOfSubType
) {
4262 // The matcher expects a DerivedClass, but inside the Property() we
4264 Matcher
<const DerivedClass
&> m
= Property(&AClass::n
, Ge(0));
4268 EXPECT_TRUE(m
.Matches(d
));
4271 EXPECT_FALSE(m
.Matches(d
));
4274 // Tests that Property(&Foo::property, m) works when property()'s type
4275 // and m's argument type are compatible but different.
4276 TEST(PropertyTest
, WorksForCompatibleMatcherType
) {
4277 // n() returns an int but the inner matcher expects a signed char.
4278 Matcher
<const AClass
&> m
= Property(&AClass::n
,
4279 Matcher
<signed char>(Ge(0)));
4281 Matcher
<const AClass
&> m_with_name
=
4282 Property("n", &AClass::n
, Matcher
<signed char>(Ge(0)));
4285 EXPECT_TRUE(m
.Matches(a
));
4286 EXPECT_TRUE(m_with_name
.Matches(a
));
4288 EXPECT_FALSE(m
.Matches(a
));
4289 EXPECT_FALSE(m_with_name
.Matches(a
));
4292 // Tests that Property() can describe itself.
4293 TEST(PropertyTest
, CanDescribeSelf
) {
4294 Matcher
<const AClass
&> m
= Property(&AClass::n
, Ge(0));
4296 EXPECT_EQ("is an object whose given property is >= 0", Describe(m
));
4297 EXPECT_EQ("is an object whose given property isn't >= 0",
4298 DescribeNegation(m
));
4301 TEST(PropertyTest
, CanDescribeSelfWithPropertyName
) {
4302 Matcher
<const AClass
&> m
= Property("fancy_name", &AClass::n
, Ge(0));
4304 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m
));
4305 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
4306 DescribeNegation(m
));
4309 // Tests that Property() can explain the match result.
4310 TEST(PropertyTest
, CanExplainMatchResult
) {
4311 Matcher
<const AClass
&> m
= Property(&AClass::n
, Ge(0));
4315 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m
, a
));
4317 m
= Property(&AClass::n
, GreaterThan(0));
4319 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
4323 TEST(PropertyTest
, CanExplainMatchResultWithPropertyName
) {
4324 Matcher
<const AClass
&> m
= Property("fancy_name", &AClass::n
, Ge(0));
4328 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m
, a
));
4330 m
= Property("fancy_name", &AClass::n
, GreaterThan(0));
4331 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int") +
4332 ", which is 1 more than 0",
4336 // Tests that Property() works when the argument is a pointer to const.
4337 TEST(PropertyForPointerTest
, WorksForPointerToConst
) {
4338 Matcher
<const AClass
*> m
= Property(&AClass::n
, Ge(0));
4342 EXPECT_TRUE(m
.Matches(&a
));
4345 EXPECT_FALSE(m
.Matches(&a
));
4348 // Tests that Property() works when the argument is a pointer to non-const.
4349 TEST(PropertyForPointerTest
, WorksForPointerToNonConst
) {
4350 Matcher
<AClass
*> m
= Property(&AClass::s
, StartsWith("hi"));
4354 EXPECT_TRUE(m
.Matches(&a
));
4357 EXPECT_FALSE(m
.Matches(&a
));
4360 // Tests that Property() works when the argument is a reference to a
4362 TEST(PropertyForPointerTest
, WorksForReferenceToConstPointer
) {
4363 Matcher
<AClass
* const&> m
= Property(&AClass::s
, StartsWith("hi"));
4367 EXPECT_TRUE(m
.Matches(&a
));
4370 EXPECT_FALSE(m
.Matches(&a
));
4373 // Tests that Property() does not match the NULL pointer.
4374 TEST(PropertyForPointerTest
, WorksForReferenceToNonConstProperty
) {
4375 Matcher
<const AClass
*> m
= Property(&AClass::x
, _
);
4376 EXPECT_FALSE(m
.Matches(NULL
));
4379 // Tests that Property(&Foo::property, ...) works when the argument's
4380 // type is a sub-type of const Foo*.
4381 TEST(PropertyForPointerTest
, WorksForArgumentOfSubType
) {
4382 // The matcher expects a DerivedClass, but inside the Property() we
4384 Matcher
<const DerivedClass
*> m
= Property(&AClass::n
, Ge(0));
4388 EXPECT_TRUE(m
.Matches(&d
));
4391 EXPECT_FALSE(m
.Matches(&d
));
4394 // Tests that Property() can describe itself when used to match a pointer.
4395 TEST(PropertyForPointerTest
, CanDescribeSelf
) {
4396 Matcher
<const AClass
*> m
= Property(&AClass::n
, Ge(0));
4398 EXPECT_EQ("is an object whose given property is >= 0", Describe(m
));
4399 EXPECT_EQ("is an object whose given property isn't >= 0",
4400 DescribeNegation(m
));
4403 TEST(PropertyForPointerTest
, CanDescribeSelfWithPropertyDescription
) {
4404 Matcher
<const AClass
*> m
= Property("fancy_name", &AClass::n
, Ge(0));
4406 EXPECT_EQ("is an object whose property `fancy_name` is >= 0", Describe(m
));
4407 EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0",
4408 DescribeNegation(m
));
4411 // Tests that Property() can explain the result of matching a pointer.
4412 TEST(PropertyForPointerTest
, CanExplainMatchResult
) {
4413 Matcher
<const AClass
*> m
= Property(&AClass::n
, Ge(0));
4417 EXPECT_EQ("", Explain(m
, static_cast<const AClass
*>(NULL
)));
4419 "which points to an object whose given property is 1" + OfType("int"),
4422 m
= Property(&AClass::n
, GreaterThan(0));
4423 EXPECT_EQ("which points to an object whose given property is 1" +
4424 OfType("int") + ", which is 1 more than 0",
4428 TEST(PropertyForPointerTest
, CanExplainMatchResultWithPropertyName
) {
4429 Matcher
<const AClass
*> m
= Property("fancy_name", &AClass::n
, Ge(0));
4433 EXPECT_EQ("", Explain(m
, static_cast<const AClass
*>(NULL
)));
4434 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
4438 m
= Property("fancy_name", &AClass::n
, GreaterThan(0));
4439 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
4440 OfType("int") + ", which is 1 more than 0",
4446 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4447 // function pointer.
4448 std::string
IntToStringFunction(int input
) {
4449 return input
== 1 ? "foo" : "bar";
4452 TEST(ResultOfTest
, WorksForFunctionPointers
) {
4453 Matcher
<int> matcher
= ResultOf(&IntToStringFunction
, Eq(std::string("foo")));
4455 EXPECT_TRUE(matcher
.Matches(1));
4456 EXPECT_FALSE(matcher
.Matches(2));
4459 // Tests that ResultOf() can describe itself.
4460 TEST(ResultOfTest
, CanDescribeItself
) {
4461 Matcher
<int> matcher
= ResultOf(&IntToStringFunction
, StrEq("foo"));
4463 EXPECT_EQ("is mapped by the given callable to a value that "
4464 "is equal to \"foo\"", Describe(matcher
));
4465 EXPECT_EQ("is mapped by the given callable to a value that "
4466 "isn't equal to \"foo\"", DescribeNegation(matcher
));
4469 // Tests that ResultOf() can explain the match result.
4470 int IntFunction(int input
) { return input
== 42 ? 80 : 90; }
4472 TEST(ResultOfTest
, CanExplainMatchResult
) {
4473 Matcher
<int> matcher
= ResultOf(&IntFunction
, Ge(85));
4474 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
4475 Explain(matcher
, 36));
4477 matcher
= ResultOf(&IntFunction
, GreaterThan(85));
4478 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
4479 ", which is 5 more than 85", Explain(matcher
, 36));
4482 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4483 // returns a non-reference.
4484 TEST(ResultOfTest
, WorksForNonReferenceResults
) {
4485 Matcher
<int> matcher
= ResultOf(&IntFunction
, Eq(80));
4487 EXPECT_TRUE(matcher
.Matches(42));
4488 EXPECT_FALSE(matcher
.Matches(36));
4491 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4492 // returns a reference to non-const.
4493 double& DoubleFunction(double& input
) { return input
; } // NOLINT
4495 Uncopyable
& RefUncopyableFunction(Uncopyable
& obj
) { // NOLINT
4499 TEST(ResultOfTest
, WorksForReferenceToNonConstResults
) {
4502 Matcher
<double&> matcher
= ResultOf(&DoubleFunction
, Ref(x
));
4504 EXPECT_TRUE(matcher
.Matches(x
));
4505 EXPECT_FALSE(matcher
.Matches(x2
));
4507 // Test that ResultOf works with uncopyable objects
4510 Matcher
<Uncopyable
&> matcher2
=
4511 ResultOf(&RefUncopyableFunction
, Ref(obj
));
4513 EXPECT_TRUE(matcher2
.Matches(obj
));
4514 EXPECT_FALSE(matcher2
.Matches(obj2
));
4517 // Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4518 // returns a reference to const.
4519 const std::string
& StringFunction(const std::string
& input
) { return input
; }
4521 TEST(ResultOfTest
, WorksForReferenceToConstResults
) {
4522 std::string s
= "foo";
4524 Matcher
<const std::string
&> matcher
= ResultOf(&StringFunction
, Ref(s
));
4526 EXPECT_TRUE(matcher
.Matches(s
));
4527 EXPECT_FALSE(matcher
.Matches(s2
));
4530 // Tests that ResultOf(f, m) works when f(x) and m's
4531 // argument types are compatible but different.
4532 TEST(ResultOfTest
, WorksForCompatibleMatcherTypes
) {
4533 // IntFunction() returns int but the inner matcher expects a signed char.
4534 Matcher
<int> matcher
= ResultOf(IntFunction
, Matcher
<signed char>(Ge(85)));
4536 EXPECT_TRUE(matcher
.Matches(36));
4537 EXPECT_FALSE(matcher
.Matches(42));
4540 // Tests that the program aborts when ResultOf is passed
4541 // a NULL function pointer.
4542 TEST(ResultOfDeathTest
, DiesOnNullFunctionPointers
) {
4543 EXPECT_DEATH_IF_SUPPORTED(
4544 ResultOf(static_cast<std::string (*)(int dummy
)>(NULL
),
4545 Eq(std::string("foo"))),
4546 "NULL function pointer is passed into ResultOf\\(\\)\\.");
4549 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4550 // function reference.
4551 TEST(ResultOfTest
, WorksForFunctionReferences
) {
4552 Matcher
<int> matcher
= ResultOf(IntToStringFunction
, StrEq("foo"));
4553 EXPECT_TRUE(matcher
.Matches(1));
4554 EXPECT_FALSE(matcher
.Matches(2));
4557 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4559 struct Functor
: public ::std::unary_function
<int, std::string
> {
4560 result_type
operator()(argument_type input
) const {
4561 return IntToStringFunction(input
);
4565 TEST(ResultOfTest
, WorksForFunctors
) {
4566 Matcher
<int> matcher
= ResultOf(Functor(), Eq(std::string("foo")));
4568 EXPECT_TRUE(matcher
.Matches(1));
4569 EXPECT_FALSE(matcher
.Matches(2));
4572 // Tests that ResultOf(f, ...) compiles and works as expected when f is a
4573 // functor with more then one operator() defined. ResultOf() must work
4574 // for each defined operator().
4575 struct PolymorphicFunctor
{
4576 typedef int result_type
;
4577 int operator()(int n
) { return n
; }
4578 int operator()(const char* s
) { return static_cast<int>(strlen(s
)); }
4581 TEST(ResultOfTest
, WorksForPolymorphicFunctors
) {
4582 Matcher
<int> matcher_int
= ResultOf(PolymorphicFunctor(), Ge(5));
4584 EXPECT_TRUE(matcher_int
.Matches(10));
4585 EXPECT_FALSE(matcher_int
.Matches(2));
4587 Matcher
<const char*> matcher_string
= ResultOf(PolymorphicFunctor(), Ge(5));
4589 EXPECT_TRUE(matcher_string
.Matches("long string"));
4590 EXPECT_FALSE(matcher_string
.Matches("shrt"));
4593 const int* ReferencingFunction(const int& n
) { return &n
; }
4595 struct ReferencingFunctor
{
4596 typedef const int* result_type
;
4597 result_type
operator()(const int& n
) { return &n
; }
4600 TEST(ResultOfTest
, WorksForReferencingCallables
) {
4603 Matcher
<const int&> matcher2
= ResultOf(ReferencingFunction
, Eq(&n
));
4604 EXPECT_TRUE(matcher2
.Matches(n
));
4605 EXPECT_FALSE(matcher2
.Matches(n2
));
4607 Matcher
<const int&> matcher3
= ResultOf(ReferencingFunctor(), Eq(&n
));
4608 EXPECT_TRUE(matcher3
.Matches(n
));
4609 EXPECT_FALSE(matcher3
.Matches(n2
));
4612 class DivisibleByImpl
{
4614 explicit DivisibleByImpl(int a_divider
) : divider_(a_divider
) {}
4616 // For testing using ExplainMatchResultTo() with polymorphic matchers.
4617 template <typename T
>
4618 bool MatchAndExplain(const T
& n
, MatchResultListener
* listener
) const {
4619 *listener
<< "which is " << (n
% divider_
) << " modulo "
4621 return (n
% divider_
) == 0;
4624 void DescribeTo(ostream
* os
) const {
4625 *os
<< "is divisible by " << divider_
;
4628 void DescribeNegationTo(ostream
* os
) const {
4629 *os
<< "is not divisible by " << divider_
;
4632 void set_divider(int a_divider
) { divider_
= a_divider
; }
4633 int divider() const { return divider_
; }
4639 PolymorphicMatcher
<DivisibleByImpl
> DivisibleBy(int n
) {
4640 return MakePolymorphicMatcher(DivisibleByImpl(n
));
4643 // Tests that when AllOf() fails, only the first failing matcher is
4644 // asked to explain why.
4645 TEST(ExplainMatchResultTest
, AllOf_False_False
) {
4646 const Matcher
<int> m
= AllOf(DivisibleBy(4), DivisibleBy(3));
4647 EXPECT_EQ("which is 1 modulo 4", Explain(m
, 5));
4650 // Tests that when AllOf() fails, only the first failing matcher is
4651 // asked to explain why.
4652 TEST(ExplainMatchResultTest
, AllOf_False_True
) {
4653 const Matcher
<int> m
= AllOf(DivisibleBy(4), DivisibleBy(3));
4654 EXPECT_EQ("which is 2 modulo 4", Explain(m
, 6));
4657 // Tests that when AllOf() fails, only the first failing matcher is
4658 // asked to explain why.
4659 TEST(ExplainMatchResultTest
, AllOf_True_False
) {
4660 const Matcher
<int> m
= AllOf(Ge(1), DivisibleBy(3));
4661 EXPECT_EQ("which is 2 modulo 3", Explain(m
, 5));
4664 // Tests that when AllOf() succeeds, all matchers are asked to explain
4666 TEST(ExplainMatchResultTest
, AllOf_True_True
) {
4667 const Matcher
<int> m
= AllOf(DivisibleBy(2), DivisibleBy(3));
4668 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m
, 6));
4671 TEST(ExplainMatchResultTest
, AllOf_True_True_2
) {
4672 const Matcher
<int> m
= AllOf(Ge(2), Le(3));
4673 EXPECT_EQ("", Explain(m
, 2));
4676 TEST(ExplainmatcherResultTest
, MonomorphicMatcher
) {
4677 const Matcher
<int> m
= GreaterThan(5);
4678 EXPECT_EQ("which is 1 more than 5", Explain(m
, 6));
4681 // The following two tests verify that values without a public copy
4682 // ctor can be used as arguments to matchers like Eq(), Ge(), and etc
4683 // with the help of ByRef().
4687 explicit NotCopyable(int a_value
) : value_(a_value
) {}
4689 int value() const { return value_
; }
4691 bool operator==(const NotCopyable
& rhs
) const {
4692 return value() == rhs
.value();
4695 bool operator>=(const NotCopyable
& rhs
) const {
4696 return value() >= rhs
.value();
4701 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable
);
4704 TEST(ByRefTest
, AllowsNotCopyableConstValueInMatchers
) {
4705 const NotCopyable
const_value1(1);
4706 const Matcher
<const NotCopyable
&> m
= Eq(ByRef(const_value1
));
4708 const NotCopyable
n1(1), n2(2);
4709 EXPECT_TRUE(m
.Matches(n1
));
4710 EXPECT_FALSE(m
.Matches(n2
));
4713 TEST(ByRefTest
, AllowsNotCopyableValueInMatchers
) {
4714 NotCopyable
value2(2);
4715 const Matcher
<NotCopyable
&> m
= Ge(ByRef(value2
));
4717 NotCopyable
n1(1), n2(2);
4718 EXPECT_FALSE(m
.Matches(n1
));
4719 EXPECT_TRUE(m
.Matches(n2
));
4722 TEST(IsEmptyTest
, ImplementsIsEmpty
) {
4723 vector
<int> container
;
4724 EXPECT_THAT(container
, IsEmpty());
4725 container
.push_back(0);
4726 EXPECT_THAT(container
, Not(IsEmpty()));
4727 container
.push_back(1);
4728 EXPECT_THAT(container
, Not(IsEmpty()));
4731 TEST(IsEmptyTest
, WorksWithString
) {
4733 EXPECT_THAT(text
, IsEmpty());
4735 EXPECT_THAT(text
, Not(IsEmpty()));
4736 text
= std::string("\0", 1);
4737 EXPECT_THAT(text
, Not(IsEmpty()));
4740 TEST(IsEmptyTest
, CanDescribeSelf
) {
4741 Matcher
<vector
<int> > m
= IsEmpty();
4742 EXPECT_EQ("is empty", Describe(m
));
4743 EXPECT_EQ("isn't empty", DescribeNegation(m
));
4746 TEST(IsEmptyTest
, ExplainsResult
) {
4747 Matcher
<vector
<int> > m
= IsEmpty();
4748 vector
<int> container
;
4749 EXPECT_EQ("", Explain(m
, container
));
4750 container
.push_back(0);
4751 EXPECT_EQ("whose size is 1", Explain(m
, container
));
4754 TEST(IsTrueTest
, IsTrueIsFalse
) {
4755 EXPECT_THAT(true, IsTrue());
4756 EXPECT_THAT(false, IsFalse());
4757 EXPECT_THAT(true, Not(IsFalse()));
4758 EXPECT_THAT(false, Not(IsTrue()));
4759 EXPECT_THAT(0, Not(IsTrue()));
4760 EXPECT_THAT(0, IsFalse());
4761 EXPECT_THAT(NULL
, Not(IsTrue()));
4762 EXPECT_THAT(NULL
, IsFalse());
4763 EXPECT_THAT(-1, IsTrue());
4764 EXPECT_THAT(-1, Not(IsFalse()));
4765 EXPECT_THAT(1, IsTrue());
4766 EXPECT_THAT(1, Not(IsFalse()));
4767 EXPECT_THAT(2, IsTrue());
4768 EXPECT_THAT(2, Not(IsFalse()));
4770 EXPECT_THAT(a
, IsTrue());
4771 EXPECT_THAT(a
, Not(IsFalse()));
4772 EXPECT_THAT(&a
, IsTrue());
4773 EXPECT_THAT(&a
, Not(IsFalse()));
4774 EXPECT_THAT(false, Not(IsTrue()));
4775 EXPECT_THAT(true, Not(IsFalse()));
4776 #if GTEST_LANG_CXX11
4777 EXPECT_THAT(std::true_type(), IsTrue());
4778 EXPECT_THAT(std::true_type(), Not(IsFalse()));
4779 EXPECT_THAT(std::false_type(), IsFalse());
4780 EXPECT_THAT(std::false_type(), Not(IsTrue()));
4781 EXPECT_THAT(nullptr, Not(IsTrue()));
4782 EXPECT_THAT(nullptr, IsFalse());
4783 std::unique_ptr
<int> null_unique
;
4784 std::unique_ptr
<int> nonnull_unique(new int(0));
4785 EXPECT_THAT(null_unique
, Not(IsTrue()));
4786 EXPECT_THAT(null_unique
, IsFalse());
4787 EXPECT_THAT(nonnull_unique
, IsTrue());
4788 EXPECT_THAT(nonnull_unique
, Not(IsFalse()));
4789 #endif // GTEST_LANG_CXX11
4792 TEST(SizeIsTest
, ImplementsSizeIs
) {
4793 vector
<int> container
;
4794 EXPECT_THAT(container
, SizeIs(0));
4795 EXPECT_THAT(container
, Not(SizeIs(1)));
4796 container
.push_back(0);
4797 EXPECT_THAT(container
, Not(SizeIs(0)));
4798 EXPECT_THAT(container
, SizeIs(1));
4799 container
.push_back(0);
4800 EXPECT_THAT(container
, Not(SizeIs(0)));
4801 EXPECT_THAT(container
, SizeIs(2));
4804 TEST(SizeIsTest
, WorksWithMap
) {
4805 map
<std::string
, int> container
;
4806 EXPECT_THAT(container
, SizeIs(0));
4807 EXPECT_THAT(container
, Not(SizeIs(1)));
4808 container
.insert(make_pair("foo", 1));
4809 EXPECT_THAT(container
, Not(SizeIs(0)));
4810 EXPECT_THAT(container
, SizeIs(1));
4811 container
.insert(make_pair("bar", 2));
4812 EXPECT_THAT(container
, Not(SizeIs(0)));
4813 EXPECT_THAT(container
, SizeIs(2));
4816 TEST(SizeIsTest
, WorksWithReferences
) {
4817 vector
<int> container
;
4818 Matcher
<const vector
<int>&> m
= SizeIs(1);
4819 EXPECT_THAT(container
, Not(m
));
4820 container
.push_back(0);
4821 EXPECT_THAT(container
, m
);
4824 TEST(SizeIsTest
, CanDescribeSelf
) {
4825 Matcher
<vector
<int> > m
= SizeIs(2);
4826 EXPECT_EQ("size is equal to 2", Describe(m
));
4827 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m
));
4830 TEST(SizeIsTest
, ExplainsResult
) {
4831 Matcher
<vector
<int> > m1
= SizeIs(2);
4832 Matcher
<vector
<int> > m2
= SizeIs(Lt(2u));
4833 Matcher
<vector
<int> > m3
= SizeIs(AnyOf(0, 3));
4834 Matcher
<vector
<int> > m4
= SizeIs(GreaterThan(1));
4835 vector
<int> container
;
4836 EXPECT_EQ("whose size 0 doesn't match", Explain(m1
, container
));
4837 EXPECT_EQ("whose size 0 matches", Explain(m2
, container
));
4838 EXPECT_EQ("whose size 0 matches", Explain(m3
, container
));
4839 EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
4840 Explain(m4
, container
));
4841 container
.push_back(0);
4842 container
.push_back(0);
4843 EXPECT_EQ("whose size 2 matches", Explain(m1
, container
));
4844 EXPECT_EQ("whose size 2 doesn't match", Explain(m2
, container
));
4845 EXPECT_EQ("whose size 2 doesn't match", Explain(m3
, container
));
4846 EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
4847 Explain(m4
, container
));
4850 #if GTEST_HAS_TYPED_TEST
4851 // Tests ContainerEq with different container types, and
4852 // different element types.
4854 template <typename T
>
4855 class ContainerEqTest
: public testing::Test
{};
4857 typedef testing::Types
<
4862 ContainerEqTestTypes
;
4864 TYPED_TEST_CASE(ContainerEqTest
, ContainerEqTestTypes
);
4866 // Tests that the filled container is equal to itself.
4867 TYPED_TEST(ContainerEqTest
, EqualsSelf
) {
4868 static const int vals
[] = {1, 1, 2, 3, 5, 8};
4869 TypeParam
my_set(vals
, vals
+ 6);
4870 const Matcher
<TypeParam
> m
= ContainerEq(my_set
);
4871 EXPECT_TRUE(m
.Matches(my_set
));
4872 EXPECT_EQ("", Explain(m
, my_set
));
4875 // Tests that missing values are reported.
4876 TYPED_TEST(ContainerEqTest
, ValueMissing
) {
4877 static const int vals
[] = {1, 1, 2, 3, 5, 8};
4878 static const int test_vals
[] = {2, 1, 8, 5};
4879 TypeParam
my_set(vals
, vals
+ 6);
4880 TypeParam
test_set(test_vals
, test_vals
+ 4);
4881 const Matcher
<TypeParam
> m
= ContainerEq(my_set
);
4882 EXPECT_FALSE(m
.Matches(test_set
));
4883 EXPECT_EQ("which doesn't have these expected elements: 3",
4884 Explain(m
, test_set
));
4887 // Tests that added values are reported.
4888 TYPED_TEST(ContainerEqTest
, ValueAdded
) {
4889 static const int vals
[] = {1, 1, 2, 3, 5, 8};
4890 static const int test_vals
[] = {1, 2, 3, 5, 8, 46};
4891 TypeParam
my_set(vals
, vals
+ 6);
4892 TypeParam
test_set(test_vals
, test_vals
+ 6);
4893 const Matcher
<const TypeParam
&> m
= ContainerEq(my_set
);
4894 EXPECT_FALSE(m
.Matches(test_set
));
4895 EXPECT_EQ("which has these unexpected elements: 46", Explain(m
, test_set
));
4898 // Tests that added and missing values are reported together.
4899 TYPED_TEST(ContainerEqTest
, ValueAddedAndRemoved
) {
4900 static const int vals
[] = {1, 1, 2, 3, 5, 8};
4901 static const int test_vals
[] = {1, 2, 3, 8, 46};
4902 TypeParam
my_set(vals
, vals
+ 6);
4903 TypeParam
test_set(test_vals
, test_vals
+ 5);
4904 const Matcher
<TypeParam
> m
= ContainerEq(my_set
);
4905 EXPECT_FALSE(m
.Matches(test_set
));
4906 EXPECT_EQ("which has these unexpected elements: 46,\n"
4907 "and doesn't have these expected elements: 5",
4908 Explain(m
, test_set
));
4911 // Tests duplicated value -- expect no explanation.
4912 TYPED_TEST(ContainerEqTest
, DuplicateDifference
) {
4913 static const int vals
[] = {1, 1, 2, 3, 5, 8};
4914 static const int test_vals
[] = {1, 2, 3, 5, 8};
4915 TypeParam
my_set(vals
, vals
+ 6);
4916 TypeParam
test_set(test_vals
, test_vals
+ 5);
4917 const Matcher
<const TypeParam
&> m
= ContainerEq(my_set
);
4918 // Depending on the container, match may be true or false
4919 // But in any case there should be no explanation.
4920 EXPECT_EQ("", Explain(m
, test_set
));
4922 #endif // GTEST_HAS_TYPED_TEST
4924 // Tests that mutliple missing values are reported.
4925 // Using just vector here, so order is predictable.
4926 TEST(ContainerEqExtraTest
, MultipleValuesMissing
) {
4927 static const int vals
[] = {1, 1, 2, 3, 5, 8};
4928 static const int test_vals
[] = {2, 1, 5};
4929 vector
<int> my_set(vals
, vals
+ 6);
4930 vector
<int> test_set(test_vals
, test_vals
+ 3);
4931 const Matcher
<vector
<int> > m
= ContainerEq(my_set
);
4932 EXPECT_FALSE(m
.Matches(test_set
));
4933 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4934 Explain(m
, test_set
));
4937 // Tests that added values are reported.
4938 // Using just vector here, so order is predictable.
4939 TEST(ContainerEqExtraTest
, MultipleValuesAdded
) {
4940 static const int vals
[] = {1, 1, 2, 3, 5, 8};
4941 static const int test_vals
[] = {1, 2, 92, 3, 5, 8, 46};
4942 list
<size_t> my_set(vals
, vals
+ 6);
4943 list
<size_t> test_set(test_vals
, test_vals
+ 7);
4944 const Matcher
<const list
<size_t>&> m
= ContainerEq(my_set
);
4945 EXPECT_FALSE(m
.Matches(test_set
));
4946 EXPECT_EQ("which has these unexpected elements: 92, 46",
4947 Explain(m
, test_set
));
4950 // Tests that added and missing values are reported together.
4951 TEST(ContainerEqExtraTest
, MultipleValuesAddedAndRemoved
) {
4952 static const int vals
[] = {1, 1, 2, 3, 5, 8};
4953 static const int test_vals
[] = {1, 2, 3, 92, 46};
4954 list
<size_t> my_set(vals
, vals
+ 6);
4955 list
<size_t> test_set(test_vals
, test_vals
+ 5);
4956 const Matcher
<const list
<size_t> > m
= ContainerEq(my_set
);
4957 EXPECT_FALSE(m
.Matches(test_set
));
4958 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4959 "and doesn't have these expected elements: 5, 8",
4960 Explain(m
, test_set
));
4963 // Tests to see that duplicate elements are detected,
4964 // but (as above) not reported in the explanation.
4965 TEST(ContainerEqExtraTest
, MultiSetOfIntDuplicateDifference
) {
4966 static const int vals
[] = {1, 1, 2, 3, 5, 8};
4967 static const int test_vals
[] = {1, 2, 3, 5, 8};
4968 vector
<int> my_set(vals
, vals
+ 6);
4969 vector
<int> test_set(test_vals
, test_vals
+ 5);
4970 const Matcher
<vector
<int> > m
= ContainerEq(my_set
);
4971 EXPECT_TRUE(m
.Matches(my_set
));
4972 EXPECT_FALSE(m
.Matches(test_set
));
4973 // There is nothing to report when both sets contain all the same values.
4974 EXPECT_EQ("", Explain(m
, test_set
));
4977 // Tests that ContainerEq works for non-trivial associative containers,
4979 TEST(ContainerEqExtraTest
, WorksForMaps
) {
4980 map
<int, std::string
> my_map
;
4984 map
<int, std::string
> test_map
;
4988 const Matcher
<const map
<int, std::string
>&> m
= ContainerEq(my_map
);
4989 EXPECT_TRUE(m
.Matches(my_map
));
4990 EXPECT_FALSE(m
.Matches(test_map
));
4992 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
4993 "and doesn't have these expected elements: (0, \"a\")",
4994 Explain(m
, test_map
));
4997 TEST(ContainerEqExtraTest
, WorksForNativeArray
) {
4998 int a1
[] = {1, 2, 3};
4999 int a2
[] = {1, 2, 3};
5000 int b
[] = {1, 2, 4};
5002 EXPECT_THAT(a1
, ContainerEq(a2
));
5003 EXPECT_THAT(a1
, Not(ContainerEq(b
)));
5006 TEST(ContainerEqExtraTest
, WorksForTwoDimensionalNativeArray
) {
5007 const char a1
[][3] = {"hi", "lo"};
5008 const char a2
[][3] = {"hi", "lo"};
5009 const char b
[][3] = {"lo", "hi"};
5011 // Tests using ContainerEq() in the first dimension.
5012 EXPECT_THAT(a1
, ContainerEq(a2
));
5013 EXPECT_THAT(a1
, Not(ContainerEq(b
)));
5015 // Tests using ContainerEq() in the second dimension.
5016 EXPECT_THAT(a1
, ElementsAre(ContainerEq(a2
[0]), ContainerEq(a2
[1])));
5017 EXPECT_THAT(a1
, ElementsAre(Not(ContainerEq(b
[0])), ContainerEq(a2
[1])));
5020 TEST(ContainerEqExtraTest
, WorksForNativeArrayAsTuple
) {
5021 const int a1
[] = {1, 2, 3};
5022 const int a2
[] = {1, 2, 3};
5023 const int b
[] = {1, 2, 3, 4};
5025 const int* const p1
= a1
;
5026 EXPECT_THAT(make_tuple(p1
, 3), ContainerEq(a2
));
5027 EXPECT_THAT(make_tuple(p1
, 3), Not(ContainerEq(b
)));
5029 const int c
[] = {1, 3, 2};
5030 EXPECT_THAT(make_tuple(p1
, 3), Not(ContainerEq(c
)));
5033 TEST(ContainerEqExtraTest
, CopiesNativeArrayParameter
) {
5034 std::string a1
[][3] = {
5035 {"hi", "hello", "ciao"},
5036 {"bye", "see you", "ciao"}
5039 std::string a2
[][3] = {
5040 {"hi", "hello", "ciao"},
5041 {"bye", "see you", "ciao"}
5044 const Matcher
<const std::string(&)[2][3]> m
= ContainerEq(a2
);
5051 TEST(WhenSortedByTest
, WorksForEmptyContainer
) {
5052 const vector
<int> numbers
;
5053 EXPECT_THAT(numbers
, WhenSortedBy(less
<int>(), ElementsAre()));
5054 EXPECT_THAT(numbers
, Not(WhenSortedBy(less
<int>(), ElementsAre(1))));
5057 TEST(WhenSortedByTest
, WorksForNonEmptyContainer
) {
5058 vector
<unsigned> numbers
;
5059 numbers
.push_back(3);
5060 numbers
.push_back(1);
5061 numbers
.push_back(2);
5062 numbers
.push_back(2);
5063 EXPECT_THAT(numbers
, WhenSortedBy(greater
<unsigned>(),
5064 ElementsAre(3, 2, 2, 1)));
5065 EXPECT_THAT(numbers
, Not(WhenSortedBy(greater
<unsigned>(),
5066 ElementsAre(1, 2, 2, 3))));
5069 TEST(WhenSortedByTest
, WorksForNonVectorContainer
) {
5070 list
<std::string
> words
;
5071 words
.push_back("say");
5072 words
.push_back("hello");
5073 words
.push_back("world");
5074 EXPECT_THAT(words
, WhenSortedBy(less
<std::string
>(),
5075 ElementsAre("hello", "say", "world")));
5076 EXPECT_THAT(words
, Not(WhenSortedBy(less
<std::string
>(),
5077 ElementsAre("say", "hello", "world"))));
5080 TEST(WhenSortedByTest
, WorksForNativeArray
) {
5081 const int numbers
[] = {1, 3, 2, 4};
5082 const int sorted_numbers
[] = {1, 2, 3, 4};
5083 EXPECT_THAT(numbers
, WhenSortedBy(less
<int>(), ElementsAre(1, 2, 3, 4)));
5084 EXPECT_THAT(numbers
, WhenSortedBy(less
<int>(),
5085 ElementsAreArray(sorted_numbers
)));
5086 EXPECT_THAT(numbers
, Not(WhenSortedBy(less
<int>(), ElementsAre(1, 3, 2, 4))));
5089 TEST(WhenSortedByTest
, CanDescribeSelf
) {
5090 const Matcher
<vector
<int> > m
= WhenSortedBy(less
<int>(), ElementsAre(1, 2));
5091 EXPECT_EQ("(when sorted) has 2 elements where\n"
5092 "element #0 is equal to 1,\n"
5093 "element #1 is equal to 2",
5095 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
5096 "element #0 isn't equal to 1, or\n"
5097 "element #1 isn't equal to 2",
5098 DescribeNegation(m
));
5101 TEST(WhenSortedByTest
, ExplainsMatchResult
) {
5102 const int a
[] = {2, 1};
5103 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
5104 Explain(WhenSortedBy(less
<int>(), ElementsAre(2, 3)), a
));
5105 EXPECT_EQ("which is { 1, 2 } when sorted",
5106 Explain(WhenSortedBy(less
<int>(), ElementsAre(1, 2)), a
));
5109 // WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
5110 // need to test it as exhaustively as we test the latter.
5112 TEST(WhenSortedTest
, WorksForEmptyContainer
) {
5113 const vector
<int> numbers
;
5114 EXPECT_THAT(numbers
, WhenSorted(ElementsAre()));
5115 EXPECT_THAT(numbers
, Not(WhenSorted(ElementsAre(1))));
5118 TEST(WhenSortedTest
, WorksForNonEmptyContainer
) {
5119 list
<std::string
> words
;
5120 words
.push_back("3");
5121 words
.push_back("1");
5122 words
.push_back("2");
5123 words
.push_back("2");
5124 EXPECT_THAT(words
, WhenSorted(ElementsAre("1", "2", "2", "3")));
5125 EXPECT_THAT(words
, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
5128 TEST(WhenSortedTest
, WorksForMapTypes
) {
5129 map
<std::string
, int> word_counts
;
5130 word_counts
["and"] = 1;
5131 word_counts
["the"] = 1;
5132 word_counts
["buffalo"] = 2;
5133 EXPECT_THAT(word_counts
,
5134 WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),
5136 EXPECT_THAT(word_counts
,
5137 Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
5138 Pair("buffalo", 2)))));
5141 TEST(WhenSortedTest
, WorksForMultiMapTypes
) {
5142 multimap
<int, int> ifib
;
5143 ifib
.insert(make_pair(8, 6));
5144 ifib
.insert(make_pair(2, 3));
5145 ifib
.insert(make_pair(1, 1));
5146 ifib
.insert(make_pair(3, 4));
5147 ifib
.insert(make_pair(1, 2));
5148 ifib
.insert(make_pair(5, 5));
5149 EXPECT_THAT(ifib
, WhenSorted(ElementsAre(Pair(1, 1),
5155 EXPECT_THAT(ifib
, Not(WhenSorted(ElementsAre(Pair(8, 6),
5163 TEST(WhenSortedTest
, WorksForPolymorphicMatcher
) {
5167 EXPECT_THAT(d
, WhenSorted(ElementsAre(1, 2)));
5168 EXPECT_THAT(d
, Not(WhenSorted(ElementsAre(2, 1))));
5171 TEST(WhenSortedTest
, WorksForVectorConstRefMatcher
) {
5175 Matcher
<const std::vector
<int>&> vector_match
= ElementsAre(1, 2);
5176 EXPECT_THAT(d
, WhenSorted(vector_match
));
5177 Matcher
<const std::vector
<int>&> not_vector_match
= ElementsAre(2, 1);
5178 EXPECT_THAT(d
, Not(WhenSorted(not_vector_match
)));
5181 // Deliberately bare pseudo-container.
5182 // Offers only begin() and end() accessors, yielding InputIterator.
5183 template <typename T
>
5188 typedef ConstIter const_iterator
;
5189 typedef T value_type
;
5191 template <typename InIter
>
5192 Streamlike(InIter first
, InIter last
) : remainder_(first
, last
) {}
5194 const_iterator
begin() const {
5195 return const_iterator(this, remainder_
.begin());
5197 const_iterator
end() const {
5198 return const_iterator(this, remainder_
.end());
5202 class ConstIter
: public std::iterator
<std::input_iterator_tag
,
5206 const value_type
&> {
5208 ConstIter(const Streamlike
* s
,
5209 typename
std::list
<value_type
>::iterator pos
)
5210 : s_(s
), pos_(pos
) {}
5212 const value_type
& operator*() const { return *pos_
; }
5213 const value_type
* operator->() const { return &*pos_
; }
5214 ConstIter
& operator++() {
5215 s_
->remainder_
.erase(pos_
++);
5219 // *iter++ is required to work (see std::istreambuf_iterator).
5220 // (void)iter++ is also required to work.
5221 class PostIncrProxy
{
5223 explicit PostIncrProxy(const value_type
& value
) : value_(value
) {}
5224 value_type
operator*() const { return value_
; }
5228 PostIncrProxy
operator++(int) {
5229 PostIncrProxy
proxy(**this);
5234 friend bool operator==(const ConstIter
& a
, const ConstIter
& b
) {
5235 return a
.s_
== b
.s_
&& a
.pos_
== b
.pos_
;
5237 friend bool operator!=(const ConstIter
& a
, const ConstIter
& b
) {
5242 const Streamlike
* s_
;
5243 typename
std::list
<value_type
>::iterator pos_
;
5246 friend std::ostream
& operator<<(std::ostream
& os
, const Streamlike
& s
) {
5248 typedef typename
std::list
<value_type
>::const_iterator Iter
;
5249 const char* sep
= "";
5250 for (Iter it
= s
.remainder_
.begin(); it
!= s
.remainder_
.end(); ++it
) {
5258 mutable std::list
<value_type
> remainder_
; // modified by iteration
5261 TEST(StreamlikeTest
, Iteration
) {
5262 const int a
[5] = {2, 1, 4, 5, 3};
5263 Streamlike
<int> s(a
, a
+ 5);
5264 Streamlike
<int>::const_iterator it
= s
.begin();
5266 while (it
!= s
.end()) {
5267 SCOPED_TRACE(ip
- a
);
5268 EXPECT_EQ(*ip
++, *it
++);
5272 #if GTEST_HAS_STD_FORWARD_LIST_
5273 TEST(BeginEndDistanceIsTest
, WorksWithForwardList
) {
5274 std::forward_list
<int> container
;
5275 EXPECT_THAT(container
, BeginEndDistanceIs(0));
5276 EXPECT_THAT(container
, Not(BeginEndDistanceIs(1)));
5277 container
.push_front(0);
5278 EXPECT_THAT(container
, Not(BeginEndDistanceIs(0)));
5279 EXPECT_THAT(container
, BeginEndDistanceIs(1));
5280 container
.push_front(0);
5281 EXPECT_THAT(container
, Not(BeginEndDistanceIs(0)));
5282 EXPECT_THAT(container
, BeginEndDistanceIs(2));
5284 #endif // GTEST_HAS_STD_FORWARD_LIST_
5286 TEST(BeginEndDistanceIsTest
, WorksWithNonStdList
) {
5287 const int a
[5] = {1, 2, 3, 4, 5};
5288 Streamlike
<int> s(a
, a
+ 5);
5289 EXPECT_THAT(s
, BeginEndDistanceIs(5));
5292 TEST(BeginEndDistanceIsTest
, CanDescribeSelf
) {
5293 Matcher
<vector
<int> > m
= BeginEndDistanceIs(2);
5294 EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m
));
5295 EXPECT_EQ("distance between begin() and end() isn't equal to 2",
5296 DescribeNegation(m
));
5299 TEST(BeginEndDistanceIsTest
, ExplainsResult
) {
5300 Matcher
<vector
<int> > m1
= BeginEndDistanceIs(2);
5301 Matcher
<vector
<int> > m2
= BeginEndDistanceIs(Lt(2));
5302 Matcher
<vector
<int> > m3
= BeginEndDistanceIs(AnyOf(0, 3));
5303 Matcher
<vector
<int> > m4
= BeginEndDistanceIs(GreaterThan(1));
5304 vector
<int> container
;
5305 EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
5306 Explain(m1
, container
));
5307 EXPECT_EQ("whose distance between begin() and end() 0 matches",
5308 Explain(m2
, container
));
5309 EXPECT_EQ("whose distance between begin() and end() 0 matches",
5310 Explain(m3
, container
));
5312 "whose distance between begin() and end() 0 doesn't match, which is 1 "
5314 Explain(m4
, container
));
5315 container
.push_back(0);
5316 container
.push_back(0);
5317 EXPECT_EQ("whose distance between begin() and end() 2 matches",
5318 Explain(m1
, container
));
5319 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
5320 Explain(m2
, container
));
5321 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
5322 Explain(m3
, container
));
5324 "whose distance between begin() and end() 2 matches, which is 1 more "
5326 Explain(m4
, container
));
5329 TEST(WhenSortedTest
, WorksForStreamlike
) {
5330 // Streamlike 'container' provides only minimal iterator support.
5331 // Its iterators are tagged with input_iterator_tag.
5332 const int a
[5] = {2, 1, 4, 5, 3};
5333 Streamlike
<int> s(a
, a
+ GTEST_ARRAY_SIZE_(a
));
5334 EXPECT_THAT(s
, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
5335 EXPECT_THAT(s
, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
5338 TEST(WhenSortedTest
, WorksForVectorConstRefMatcherOnStreamlike
) {
5339 const int a
[] = {2, 1, 4, 5, 3};
5340 Streamlike
<int> s(a
, a
+ GTEST_ARRAY_SIZE_(a
));
5341 Matcher
<const std::vector
<int>&> vector_match
= ElementsAre(1, 2, 3, 4, 5);
5342 EXPECT_THAT(s
, WhenSorted(vector_match
));
5343 EXPECT_THAT(s
, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
5346 TEST(IsSupersetOfTest
, WorksForNativeArray
) {
5347 const int subset
[] = {1, 4};
5348 const int superset
[] = {1, 2, 4};
5349 const int disjoint
[] = {1, 0, 3};
5350 EXPECT_THAT(subset
, IsSupersetOf(subset
));
5351 EXPECT_THAT(subset
, Not(IsSupersetOf(superset
)));
5352 EXPECT_THAT(superset
, IsSupersetOf(subset
));
5353 EXPECT_THAT(subset
, Not(IsSupersetOf(disjoint
)));
5354 EXPECT_THAT(disjoint
, Not(IsSupersetOf(subset
)));
5357 TEST(IsSupersetOfTest
, WorksWithDuplicates
) {
5358 const int not_enough
[] = {1, 2};
5359 const int enough
[] = {1, 1, 2};
5360 const int expected
[] = {1, 1};
5361 EXPECT_THAT(not_enough
, Not(IsSupersetOf(expected
)));
5362 EXPECT_THAT(enough
, IsSupersetOf(expected
));
5365 TEST(IsSupersetOfTest
, WorksForEmpty
) {
5366 vector
<int> numbers
;
5367 vector
<int> expected
;
5368 EXPECT_THAT(numbers
, IsSupersetOf(expected
));
5369 expected
.push_back(1);
5370 EXPECT_THAT(numbers
, Not(IsSupersetOf(expected
)));
5372 numbers
.push_back(1);
5373 numbers
.push_back(2);
5374 EXPECT_THAT(numbers
, IsSupersetOf(expected
));
5375 expected
.push_back(1);
5376 EXPECT_THAT(numbers
, IsSupersetOf(expected
));
5377 expected
.push_back(2);
5378 EXPECT_THAT(numbers
, IsSupersetOf(expected
));
5379 expected
.push_back(3);
5380 EXPECT_THAT(numbers
, Not(IsSupersetOf(expected
)));
5383 TEST(IsSupersetOfTest
, WorksForStreamlike
) {
5384 const int a
[5] = {1, 2, 3, 4, 5};
5385 Streamlike
<int> s(a
, a
+ GTEST_ARRAY_SIZE_(a
));
5387 vector
<int> expected
;
5388 expected
.push_back(1);
5389 expected
.push_back(2);
5390 expected
.push_back(5);
5391 EXPECT_THAT(s
, IsSupersetOf(expected
));
5393 expected
.push_back(0);
5394 EXPECT_THAT(s
, Not(IsSupersetOf(expected
)));
5397 TEST(IsSupersetOfTest
, TakesStlContainer
) {
5398 const int actual
[] = {3, 1, 2};
5400 ::std::list
<int> expected
;
5401 expected
.push_back(1);
5402 expected
.push_back(3);
5403 EXPECT_THAT(actual
, IsSupersetOf(expected
));
5405 expected
.push_back(4);
5406 EXPECT_THAT(actual
, Not(IsSupersetOf(expected
)));
5409 TEST(IsSupersetOfTest
, Describe
) {
5410 typedef std::vector
<int> IntVec
;
5412 expected
.push_back(111);
5413 expected
.push_back(222);
5414 expected
.push_back(333);
5416 Describe
<IntVec
>(IsSupersetOf(expected
)),
5417 Eq("a surjection from elements to requirements exists such that:\n"
5418 " - an element is equal to 111\n"
5419 " - an element is equal to 222\n"
5420 " - an element is equal to 333"));
5423 TEST(IsSupersetOfTest
, DescribeNegation
) {
5424 typedef std::vector
<int> IntVec
;
5426 expected
.push_back(111);
5427 expected
.push_back(222);
5428 expected
.push_back(333);
5430 DescribeNegation
<IntVec
>(IsSupersetOf(expected
)),
5431 Eq("no surjection from elements to requirements exists such that:\n"
5432 " - an element is equal to 111\n"
5433 " - an element is equal to 222\n"
5434 " - an element is equal to 333"));
5437 TEST(IsSupersetOfTest
, MatchAndExplain
) {
5441 std::vector
<int> expected
;
5442 expected
.push_back(1);
5443 expected
.push_back(2);
5444 StringMatchResultListener listener
;
5445 ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected
), v
, &listener
))
5447 EXPECT_THAT(listener
.str(),
5448 Eq("where the following matchers don't match any elements:\n"
5449 "matcher #0: is equal to 1"));
5453 ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected
), v
, &listener
))
5455 EXPECT_THAT(listener
.str(), Eq("where:\n"
5456 " - element #0 is matched by matcher #1,\n"
5457 " - element #2 is matched by matcher #0"));
5460 #if GTEST_HAS_STD_INITIALIZER_LIST_
5461 TEST(IsSupersetOfTest
, WorksForRhsInitializerList
) {
5462 const int numbers
[] = {1, 3, 6, 2, 4, 5};
5463 EXPECT_THAT(numbers
, IsSupersetOf({1, 2}));
5464 EXPECT_THAT(numbers
, Not(IsSupersetOf({3, 0})));
5468 TEST(IsSubsetOfTest
, WorksForNativeArray
) {
5469 const int subset
[] = {1, 4};
5470 const int superset
[] = {1, 2, 4};
5471 const int disjoint
[] = {1, 0, 3};
5472 EXPECT_THAT(subset
, IsSubsetOf(subset
));
5473 EXPECT_THAT(subset
, IsSubsetOf(superset
));
5474 EXPECT_THAT(superset
, Not(IsSubsetOf(subset
)));
5475 EXPECT_THAT(subset
, Not(IsSubsetOf(disjoint
)));
5476 EXPECT_THAT(disjoint
, Not(IsSubsetOf(subset
)));
5479 TEST(IsSubsetOfTest
, WorksWithDuplicates
) {
5480 const int not_enough
[] = {1, 2};
5481 const int enough
[] = {1, 1, 2};
5482 const int actual
[] = {1, 1};
5483 EXPECT_THAT(actual
, Not(IsSubsetOf(not_enough
)));
5484 EXPECT_THAT(actual
, IsSubsetOf(enough
));
5487 TEST(IsSubsetOfTest
, WorksForEmpty
) {
5488 vector
<int> numbers
;
5489 vector
<int> expected
;
5490 EXPECT_THAT(numbers
, IsSubsetOf(expected
));
5491 expected
.push_back(1);
5492 EXPECT_THAT(numbers
, IsSubsetOf(expected
));
5494 numbers
.push_back(1);
5495 numbers
.push_back(2);
5496 EXPECT_THAT(numbers
, Not(IsSubsetOf(expected
)));
5497 expected
.push_back(1);
5498 EXPECT_THAT(numbers
, Not(IsSubsetOf(expected
)));
5499 expected
.push_back(2);
5500 EXPECT_THAT(numbers
, IsSubsetOf(expected
));
5501 expected
.push_back(3);
5502 EXPECT_THAT(numbers
, IsSubsetOf(expected
));
5505 TEST(IsSubsetOfTest
, WorksForStreamlike
) {
5506 const int a
[5] = {1, 2};
5507 Streamlike
<int> s(a
, a
+ GTEST_ARRAY_SIZE_(a
));
5509 vector
<int> expected
;
5510 expected
.push_back(1);
5511 EXPECT_THAT(s
, Not(IsSubsetOf(expected
)));
5512 expected
.push_back(2);
5513 expected
.push_back(5);
5514 EXPECT_THAT(s
, IsSubsetOf(expected
));
5517 TEST(IsSubsetOfTest
, TakesStlContainer
) {
5518 const int actual
[] = {3, 1, 2};
5520 ::std::list
<int> expected
;
5521 expected
.push_back(1);
5522 expected
.push_back(3);
5523 EXPECT_THAT(actual
, Not(IsSubsetOf(expected
)));
5525 expected
.push_back(2);
5526 expected
.push_back(4);
5527 EXPECT_THAT(actual
, IsSubsetOf(expected
));
5530 TEST(IsSubsetOfTest
, Describe
) {
5531 typedef std::vector
<int> IntVec
;
5533 expected
.push_back(111);
5534 expected
.push_back(222);
5535 expected
.push_back(333);
5538 Describe
<IntVec
>(IsSubsetOf(expected
)),
5539 Eq("an injection from elements to requirements exists such that:\n"
5540 " - an element is equal to 111\n"
5541 " - an element is equal to 222\n"
5542 " - an element is equal to 333"));
5545 TEST(IsSubsetOfTest
, DescribeNegation
) {
5546 typedef std::vector
<int> IntVec
;
5548 expected
.push_back(111);
5549 expected
.push_back(222);
5550 expected
.push_back(333);
5552 DescribeNegation
<IntVec
>(IsSubsetOf(expected
)),
5553 Eq("no injection from elements to requirements exists such that:\n"
5554 " - an element is equal to 111\n"
5555 " - an element is equal to 222\n"
5556 " - an element is equal to 333"));
5559 TEST(IsSubsetOfTest
, MatchAndExplain
) {
5563 std::vector
<int> expected
;
5564 expected
.push_back(1);
5565 expected
.push_back(2);
5566 StringMatchResultListener listener
;
5567 ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected
), v
, &listener
))
5569 EXPECT_THAT(listener
.str(),
5570 Eq("where the following elements don't match any matchers:\n"
5573 expected
.push_back(3);
5575 ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected
), v
, &listener
))
5577 EXPECT_THAT(listener
.str(), Eq("where:\n"
5578 " - element #0 is matched by matcher #1,\n"
5579 " - element #1 is matched by matcher #2"));
5582 #if GTEST_HAS_STD_INITIALIZER_LIST_
5583 TEST(IsSubsetOfTest
, WorksForRhsInitializerList
) {
5584 const int numbers
[] = {1, 2, 3};
5585 EXPECT_THAT(numbers
, IsSubsetOf({1, 2, 3, 4}));
5586 EXPECT_THAT(numbers
, Not(IsSubsetOf({1, 2})));
5590 // Tests using ElementsAre() and ElementsAreArray() with stream-like
5593 TEST(ElemensAreStreamTest
, WorksForStreamlike
) {
5594 const int a
[5] = {1, 2, 3, 4, 5};
5595 Streamlike
<int> s(a
, a
+ GTEST_ARRAY_SIZE_(a
));
5596 EXPECT_THAT(s
, ElementsAre(1, 2, 3, 4, 5));
5597 EXPECT_THAT(s
, Not(ElementsAre(2, 1, 4, 5, 3)));
5600 TEST(ElemensAreArrayStreamTest
, WorksForStreamlike
) {
5601 const int a
[5] = {1, 2, 3, 4, 5};
5602 Streamlike
<int> s(a
, a
+ GTEST_ARRAY_SIZE_(a
));
5604 vector
<int> expected
;
5605 expected
.push_back(1);
5606 expected
.push_back(2);
5607 expected
.push_back(3);
5608 expected
.push_back(4);
5609 expected
.push_back(5);
5610 EXPECT_THAT(s
, ElementsAreArray(expected
));
5613 EXPECT_THAT(s
, Not(ElementsAreArray(expected
)));
5616 TEST(ElementsAreTest
, WorksWithUncopyable
) {
5618 objs
[0].set_value(-3);
5619 objs
[1].set_value(1);
5620 EXPECT_THAT(objs
, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive
)));
5623 TEST(ElementsAreTest
, TakesStlContainer
) {
5624 const int actual
[] = {3, 1, 2};
5626 ::std::list
<int> expected
;
5627 expected
.push_back(3);
5628 expected
.push_back(1);
5629 expected
.push_back(2);
5630 EXPECT_THAT(actual
, ElementsAreArray(expected
));
5632 expected
.push_back(4);
5633 EXPECT_THAT(actual
, Not(ElementsAreArray(expected
)));
5636 // Tests for UnorderedElementsAreArray()
5638 TEST(UnorderedElementsAreArrayTest
, SucceedsWhenExpected
) {
5639 const int a
[] = {0, 1, 2, 3, 4};
5640 std::vector
<int> s(a
, a
+ GTEST_ARRAY_SIZE_(a
));
5642 StringMatchResultListener listener
;
5643 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a
),
5644 s
, &listener
)) << listener
.str();
5645 } while (std::next_permutation(s
.begin(), s
.end()));
5648 TEST(UnorderedElementsAreArrayTest
, VectorBool
) {
5649 const bool a
[] = {0, 1, 0, 1, 1};
5650 const bool b
[] = {1, 0, 1, 1, 0};
5651 std::vector
<bool> expected(a
, a
+ GTEST_ARRAY_SIZE_(a
));
5652 std::vector
<bool> actual(b
, b
+ GTEST_ARRAY_SIZE_(b
));
5653 StringMatchResultListener listener
;
5654 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected
),
5655 actual
, &listener
)) << listener
.str();
5658 TEST(UnorderedElementsAreArrayTest
, WorksForStreamlike
) {
5659 // Streamlike 'container' provides only minimal iterator support.
5660 // Its iterators are tagged with input_iterator_tag, and it has no
5661 // size() or empty() methods.
5662 const int a
[5] = {2, 1, 4, 5, 3};
5663 Streamlike
<int> s(a
, a
+ GTEST_ARRAY_SIZE_(a
));
5665 ::std::vector
<int> expected
;
5666 expected
.push_back(1);
5667 expected
.push_back(2);
5668 expected
.push_back(3);
5669 expected
.push_back(4);
5670 expected
.push_back(5);
5671 EXPECT_THAT(s
, UnorderedElementsAreArray(expected
));
5673 expected
.push_back(6);
5674 EXPECT_THAT(s
, Not(UnorderedElementsAreArray(expected
)));
5677 TEST(UnorderedElementsAreArrayTest
, TakesStlContainer
) {
5678 const int actual
[] = {3, 1, 2};
5680 ::std::list
<int> expected
;
5681 expected
.push_back(1);
5682 expected
.push_back(2);
5683 expected
.push_back(3);
5684 EXPECT_THAT(actual
, UnorderedElementsAreArray(expected
));
5686 expected
.push_back(4);
5687 EXPECT_THAT(actual
, Not(UnorderedElementsAreArray(expected
)));
5690 #if GTEST_HAS_STD_INITIALIZER_LIST_
5692 TEST(UnorderedElementsAreArrayTest
, TakesInitializerList
) {
5693 const int a
[5] = {2, 1, 4, 5, 3};
5694 EXPECT_THAT(a
, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
5695 EXPECT_THAT(a
, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
5698 TEST(UnorderedElementsAreArrayTest
, TakesInitializerListOfCStrings
) {
5699 const std::string a
[5] = {"a", "b", "c", "d", "e"};
5700 EXPECT_THAT(a
, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
5701 EXPECT_THAT(a
, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
5704 TEST(UnorderedElementsAreArrayTest
, TakesInitializerListOfSameTypedMatchers
) {
5705 const int a
[5] = {2, 1, 4, 5, 3};
5706 EXPECT_THAT(a
, UnorderedElementsAreArray(
5707 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
5708 EXPECT_THAT(a
, Not(UnorderedElementsAreArray(
5709 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
5712 TEST(UnorderedElementsAreArrayTest
,
5713 TakesInitializerListOfDifferentTypedMatchers
) {
5714 const int a
[5] = {2, 1, 4, 5, 3};
5715 // The compiler cannot infer the type of the initializer list if its
5716 // elements have different types. We must explicitly specify the
5717 // unified element type in this case.
5718 EXPECT_THAT(a
, UnorderedElementsAreArray
<Matcher
<int> >(
5719 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
5720 EXPECT_THAT(a
, Not(UnorderedElementsAreArray
<Matcher
<int> >(
5721 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
5724 #endif // GTEST_HAS_STD_INITIALIZER_LIST_
5726 class UnorderedElementsAreTest
: public testing::Test
{
5728 typedef std::vector
<int> IntVec
;
5731 TEST_F(UnorderedElementsAreTest
, WorksWithUncopyable
) {
5733 objs
[0].set_value(-3);
5734 objs
[1].set_value(1);
5736 UnorderedElementsAre(Truly(ValueIsPositive
), UncopyableIs(-3)));
5739 TEST_F(UnorderedElementsAreTest
, SucceedsWhenExpected
) {
5740 const int a
[] = {1, 2, 3};
5741 std::vector
<int> s(a
, a
+ GTEST_ARRAY_SIZE_(a
));
5743 StringMatchResultListener listener
;
5744 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5745 s
, &listener
)) << listener
.str();
5746 } while (std::next_permutation(s
.begin(), s
.end()));
5749 TEST_F(UnorderedElementsAreTest
, FailsWhenAnElementMatchesNoMatcher
) {
5750 const int a
[] = {1, 2, 3};
5751 std::vector
<int> s(a
, a
+ GTEST_ARRAY_SIZE_(a
));
5752 std::vector
<Matcher
<int> > mv
;
5756 // The element with value '3' matches nothing: fail fast.
5757 StringMatchResultListener listener
;
5758 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv
),
5759 s
, &listener
)) << listener
.str();
5762 TEST_F(UnorderedElementsAreTest
, WorksForStreamlike
) {
5763 // Streamlike 'container' provides only minimal iterator support.
5764 // Its iterators are tagged with input_iterator_tag, and it has no
5765 // size() or empty() methods.
5766 const int a
[5] = {2, 1, 4, 5, 3};
5767 Streamlike
<int> s(a
, a
+ GTEST_ARRAY_SIZE_(a
));
5769 EXPECT_THAT(s
, UnorderedElementsAre(1, 2, 3, 4, 5));
5770 EXPECT_THAT(s
, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
5773 // One naive implementation of the matcher runs in O(N!) time, which is too
5774 // slow for many real-world inputs. This test shows that our matcher can match
5775 // 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
5776 // iterations and obviously effectively incomputable.
5777 // [ RUN ] UnorderedElementsAreTest.Performance
5778 // [ OK ] UnorderedElementsAreTest.Performance (4 ms)
5779 TEST_F(UnorderedElementsAreTest
, Performance
) {
5781 std::vector
<Matcher
<int> > mv
;
5782 for (int i
= 0; i
< 100; ++i
) {
5787 StringMatchResultListener listener
;
5788 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv
),
5789 s
, &listener
)) << listener
.str();
5792 // Another variant of 'Performance' with similar expectations.
5793 // [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
5794 // [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
5795 TEST_F(UnorderedElementsAreTest
, PerformanceHalfStrict
) {
5797 std::vector
<Matcher
<int> > mv
;
5798 for (int i
= 0; i
< 100; ++i
) {
5806 StringMatchResultListener listener
;
5807 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv
),
5808 s
, &listener
)) << listener
.str();
5811 TEST_F(UnorderedElementsAreTest
, FailMessageCountWrong
) {
5814 StringMatchResultListener listener
;
5815 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5816 v
, &listener
)) << listener
.str();
5817 EXPECT_THAT(listener
.str(), Eq("which has 1 element"));
5820 TEST_F(UnorderedElementsAreTest
, FailMessageCountWrongZero
) {
5822 StringMatchResultListener listener
;
5823 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
5824 v
, &listener
)) << listener
.str();
5825 EXPECT_THAT(listener
.str(), Eq(""));
5828 TEST_F(UnorderedElementsAreTest
, FailMessageUnmatchedMatchers
) {
5832 StringMatchResultListener listener
;
5833 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
5834 v
, &listener
)) << listener
.str();
5837 Eq("where the following matchers don't match any elements:\n"
5838 "matcher #1: is equal to 2"));
5841 TEST_F(UnorderedElementsAreTest
, FailMessageUnmatchedElements
) {
5845 StringMatchResultListener listener
;
5846 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
5847 v
, &listener
)) << listener
.str();
5850 Eq("where the following elements don't match any matchers:\n"
5854 TEST_F(UnorderedElementsAreTest
, FailMessageUnmatchedMatcherAndElement
) {
5858 StringMatchResultListener listener
;
5859 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
5860 v
, &listener
)) << listener
.str();
5864 " the following matchers don't match any elements:\n"
5865 "matcher #0: is equal to 1\n"
5868 " the following elements don't match any matchers:\n"
5872 // Test helper for formatting element, matcher index pairs in expectations.
5873 static std::string
EMString(int element
, int matcher
) {
5875 ss
<< "(element #" << element
<< ", matcher #" << matcher
<< ")";
5879 TEST_F(UnorderedElementsAreTest
, FailMessageImperfectMatchOnly
) {
5880 // A situation where all elements and matchers have a match
5881 // associated with them, but the max matching is not perfect.
5882 std::vector
<std::string
> v
;
5886 StringMatchResultListener listener
;
5887 EXPECT_FALSE(ExplainMatchResult(
5888 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v
, &listener
))
5891 std::string prefix
=
5892 "where no permutation of the elements can satisfy all matchers, "
5893 "and the closest match is 2 of 3 matchers with the "
5896 // We have to be a bit loose here, because there are 4 valid max matches.
5899 AnyOf(prefix
+ "{\n " + EMString(0, 0) +
5900 ",\n " + EMString(1, 2) + "\n}",
5901 prefix
+ "{\n " + EMString(0, 1) +
5902 ",\n " + EMString(1, 2) + "\n}",
5903 prefix
+ "{\n " + EMString(0, 0) +
5904 ",\n " + EMString(2, 2) + "\n}",
5905 prefix
+ "{\n " + EMString(0, 1) +
5906 ",\n " + EMString(2, 2) + "\n}"));
5909 TEST_F(UnorderedElementsAreTest
, Describe
) {
5910 EXPECT_THAT(Describe
<IntVec
>(UnorderedElementsAre()),
5913 Describe
<IntVec
>(UnorderedElementsAre(345)),
5914 Eq("has 1 element and that element is equal to 345"));
5916 Describe
<IntVec
>(UnorderedElementsAre(111, 222, 333)),
5917 Eq("has 3 elements and there exists some permutation "
5918 "of elements such that:\n"
5919 " - element #0 is equal to 111, and\n"
5920 " - element #1 is equal to 222, and\n"
5921 " - element #2 is equal to 333"));
5924 TEST_F(UnorderedElementsAreTest
, DescribeNegation
) {
5925 EXPECT_THAT(DescribeNegation
<IntVec
>(UnorderedElementsAre()),
5928 DescribeNegation
<IntVec
>(UnorderedElementsAre(345)),
5929 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
5931 DescribeNegation
<IntVec
>(UnorderedElementsAre(123, 234, 345)),
5932 Eq("doesn't have 3 elements, or there exists no permutation "
5933 "of elements such that:\n"
5934 " - element #0 is equal to 123, and\n"
5935 " - element #1 is equal to 234, and\n"
5936 " - element #2 is equal to 345"));
5941 // Used as a check on the more complex max flow method used in the
5942 // real testing::internal::FindMaxBipartiteMatching. This method is
5943 // compatible but runs in worst-case factorial time, so we only
5944 // use it in testing for small problem sizes.
5945 template <typename Graph
>
5946 class BacktrackingMaxBPMState
{
5948 // Does not take ownership of 'g'.
5949 explicit BacktrackingMaxBPMState(const Graph
* g
) : graph_(g
) { }
5951 ElementMatcherPairs
Compute() {
5952 if (graph_
->LhsSize() == 0 || graph_
->RhsSize() == 0) {
5953 return best_so_far_
;
5955 lhs_used_
.assign(graph_
->LhsSize(), kUnused
);
5956 rhs_used_
.assign(graph_
->RhsSize(), kUnused
);
5957 for (size_t irhs
= 0; irhs
< graph_
->RhsSize(); ++irhs
) {
5960 if (best_so_far_
.size() == graph_
->RhsSize())
5963 return best_so_far_
;
5967 static const size_t kUnused
= static_cast<size_t>(-1);
5969 void PushMatch(size_t lhs
, size_t rhs
) {
5970 matches_
.push_back(ElementMatcherPair(lhs
, rhs
));
5971 lhs_used_
[lhs
] = rhs
;
5972 rhs_used_
[rhs
] = lhs
;
5973 if (matches_
.size() > best_so_far_
.size()) {
5974 best_so_far_
= matches_
;
5979 const ElementMatcherPair
& back
= matches_
.back();
5980 lhs_used_
[back
.first
] = kUnused
;
5981 rhs_used_
[back
.second
] = kUnused
;
5982 matches_
.pop_back();
5985 bool RecurseInto(size_t irhs
) {
5986 if (rhs_used_
[irhs
] != kUnused
) {
5989 for (size_t ilhs
= 0; ilhs
< graph_
->LhsSize(); ++ilhs
) {
5990 if (lhs_used_
[ilhs
] != kUnused
) {
5993 if (!graph_
->HasEdge(ilhs
, irhs
)) {
5996 PushMatch(ilhs
, irhs
);
5997 if (best_so_far_
.size() == graph_
->RhsSize()) {
6000 for (size_t mi
= irhs
+ 1; mi
< graph_
->RhsSize(); ++mi
) {
6001 if (!RecurseInto(mi
)) return false;
6008 const Graph
* graph_
; // not owned
6009 std::vector
<size_t> lhs_used_
;
6010 std::vector
<size_t> rhs_used_
;
6011 ElementMatcherPairs matches_
;
6012 ElementMatcherPairs best_so_far_
;
6015 template <typename Graph
>
6016 const size_t BacktrackingMaxBPMState
<Graph
>::kUnused
;
6020 // Implement a simple backtracking algorithm to determine if it is possible
6021 // to find one element per matcher, without reusing elements.
6022 template <typename Graph
>
6024 FindBacktrackingMaxBPM(const Graph
& g
) {
6025 return BacktrackingMaxBPMState
<Graph
>(&g
).Compute();
6028 class BacktrackingBPMTest
: public ::testing::Test
{ };
6030 // Tests the MaxBipartiteMatching algorithm with square matrices.
6031 // The single int param is the # of nodes on each of the left and right sides.
6032 class BipartiteTest
: public ::testing::TestWithParam
<int> { };
6034 // Verify all match graphs up to some moderate number of edges.
6035 TEST_P(BipartiteTest
, Exhaustive
) {
6036 int nodes
= GetParam();
6037 MatchMatrix
graph(nodes
, nodes
);
6039 ElementMatcherPairs matches
=
6040 internal::FindMaxBipartiteMatching(graph
);
6041 EXPECT_EQ(FindBacktrackingMaxBPM(graph
).size(), matches
.size())
6042 << "graph: " << graph
.DebugString();
6043 // Check that all elements of matches are in the graph.
6044 // Check that elements of first and second are unique.
6045 std::vector
<bool> seen_element(graph
.LhsSize());
6046 std::vector
<bool> seen_matcher(graph
.RhsSize());
6047 SCOPED_TRACE(PrintToString(matches
));
6048 for (size_t i
= 0; i
< matches
.size(); ++i
) {
6049 size_t ilhs
= matches
[i
].first
;
6050 size_t irhs
= matches
[i
].second
;
6051 EXPECT_TRUE(graph
.HasEdge(ilhs
, irhs
));
6052 EXPECT_FALSE(seen_element
[ilhs
]);
6053 EXPECT_FALSE(seen_matcher
[irhs
]);
6054 seen_element
[ilhs
] = true;
6055 seen_matcher
[irhs
] = true;
6057 } while (graph
.NextGraph());
6060 INSTANTIATE_TEST_CASE_P(AllGraphs
, BipartiteTest
,
6061 ::testing::Range(0, 5));
6063 // Parameterized by a pair interpreted as (LhsSize, RhsSize).
6064 class BipartiteNonSquareTest
6065 : public ::testing::TestWithParam
<std::pair
<size_t, size_t> > {
6068 TEST_F(BipartiteNonSquareTest
, SimpleBacktracking
) {
6076 MatchMatrix
g(4, 3);
6077 static const int kEdges
[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}};
6078 for (size_t i
= 0; i
< GTEST_ARRAY_SIZE_(kEdges
); ++i
) {
6079 g
.SetEdge(kEdges
[i
][0], kEdges
[i
][1], true);
6081 EXPECT_THAT(FindBacktrackingMaxBPM(g
),
6082 ElementsAre(Pair(3, 0),
6083 Pair(AnyOf(1, 2), 1),
6084 Pair(0, 2))) << g
.DebugString();
6087 // Verify a few nonsquare matrices.
6088 TEST_P(BipartiteNonSquareTest
, Exhaustive
) {
6089 size_t nlhs
= GetParam().first
;
6090 size_t nrhs
= GetParam().second
;
6091 MatchMatrix
graph(nlhs
, nrhs
);
6093 EXPECT_EQ(FindBacktrackingMaxBPM(graph
).size(),
6094 internal::FindMaxBipartiteMatching(graph
).size())
6095 << "graph: " << graph
.DebugString()
6096 << "\nbacktracking: "
6097 << PrintToString(FindBacktrackingMaxBPM(graph
))
6099 << PrintToString(internal::FindMaxBipartiteMatching(graph
));
6100 } while (graph
.NextGraph());
6103 INSTANTIATE_TEST_CASE_P(AllGraphs
, BipartiteNonSquareTest
,
6105 std::make_pair(1, 2),
6106 std::make_pair(2, 1),
6107 std::make_pair(3, 2),
6108 std::make_pair(2, 3),
6109 std::make_pair(4, 1),
6110 std::make_pair(1, 4),
6111 std::make_pair(4, 3),
6112 std::make_pair(3, 4)));
6114 class BipartiteRandomTest
6115 : public ::testing::TestWithParam
<std::pair
<int, int> > {
6118 // Verifies a large sample of larger graphs.
6119 TEST_P(BipartiteRandomTest
, LargerNets
) {
6120 int nodes
= GetParam().first
;
6121 int iters
= GetParam().second
;
6122 MatchMatrix
graph(nodes
, nodes
);
6124 testing::internal::Int32 seed
= GTEST_FLAG(random_seed
);
6126 seed
= static_cast<testing::internal::Int32
>(time(NULL
));
6129 for (; iters
> 0; --iters
, ++seed
) {
6130 srand(static_cast<int>(seed
));
6132 EXPECT_EQ(FindBacktrackingMaxBPM(graph
).size(),
6133 internal::FindMaxBipartiteMatching(graph
).size())
6134 << " graph: " << graph
.DebugString()
6135 << "\nTo reproduce the failure, rerun the test with the flag"
6136 " --" << GTEST_FLAG_PREFIX_
<< "random_seed=" << seed
;
6140 // Test argument is a std::pair<int, int> representing (nodes, iters).
6141 INSTANTIATE_TEST_CASE_P(Samples
, BipartiteRandomTest
,
6143 std::make_pair(5, 10000),
6144 std::make_pair(6, 5000),
6145 std::make_pair(7, 2000),
6146 std::make_pair(8, 500),
6147 std::make_pair(9, 100)));
6149 // Tests IsReadableTypeName().
6151 TEST(IsReadableTypeNameTest
, ReturnsTrueForShortNames
) {
6152 EXPECT_TRUE(IsReadableTypeName("int"));
6153 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
6154 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
6155 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
6158 TEST(IsReadableTypeNameTest
, ReturnsTrueForLongNonTemplateNonFunctionNames
) {
6159 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
6160 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
6161 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
6164 TEST(IsReadableTypeNameTest
, ReturnsFalseForLongTemplateNames
) {
6166 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
6167 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
6170 TEST(IsReadableTypeNameTest
, ReturnsFalseForLongFunctionTypeNames
) {
6171 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
6174 // Tests FormatMatcherDescription().
6176 TEST(FormatMatcherDescriptionTest
, WorksForEmptyDescription
) {
6177 EXPECT_EQ("is even",
6178 FormatMatcherDescription(false, "IsEven", Strings()));
6179 EXPECT_EQ("not (is even)",
6180 FormatMatcherDescription(true, "IsEven", Strings()));
6182 const char* params
[] = {"5"};
6183 EXPECT_EQ("equals 5",
6184 FormatMatcherDescription(false, "Equals",
6185 Strings(params
, params
+ 1)));
6187 const char* params2
[] = {"5", "8"};
6188 EXPECT_EQ("is in range (5, 8)",
6189 FormatMatcherDescription(false, "IsInRange",
6190 Strings(params2
, params2
+ 2)));
6193 // Tests PolymorphicMatcher::mutable_impl().
6194 TEST(PolymorphicMatcherTest
, CanAccessMutableImpl
) {
6195 PolymorphicMatcher
<DivisibleByImpl
> m(DivisibleByImpl(42));
6196 DivisibleByImpl
& impl
= m
.mutable_impl();
6197 EXPECT_EQ(42, impl
.divider());
6199 impl
.set_divider(0);
6200 EXPECT_EQ(0, m
.mutable_impl().divider());
6203 // Tests PolymorphicMatcher::impl().
6204 TEST(PolymorphicMatcherTest
, CanAccessImpl
) {
6205 const PolymorphicMatcher
<DivisibleByImpl
> m(DivisibleByImpl(42));
6206 const DivisibleByImpl
& impl
= m
.impl();
6207 EXPECT_EQ(42, impl
.divider());
6210 TEST(MatcherTupleTest
, ExplainsMatchFailure
) {
6212 ExplainMatchFailureTupleTo(make_tuple(Matcher
<char>(Eq('a')), GreaterThan(5)),
6213 make_tuple('a', 10), &ss1
);
6214 EXPECT_EQ("", ss1
.str()); // Successful match.
6217 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher
<char>(Eq('a'))),
6218 make_tuple(2, 'b'), &ss2
);
6219 EXPECT_EQ(" Expected arg #0: is > 5\n"
6220 " Actual: 2, which is 3 less than 5\n"
6221 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
6222 " Actual: 'b' (98, 0x62)\n",
6223 ss2
.str()); // Failed match where both arguments need explanation.
6226 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher
<char>(Eq('a'))),
6227 make_tuple(2, 'a'), &ss3
);
6228 EXPECT_EQ(" Expected arg #0: is > 5\n"
6229 " Actual: 2, which is 3 less than 5\n",
6230 ss3
.str()); // Failed match where only one argument needs
6236 TEST(EachTest
, ExplainsMatchResultCorrectly
) {
6237 set
<int> a
; // empty
6239 Matcher
<set
<int> > m
= Each(2);
6240 EXPECT_EQ("", Explain(m
, a
));
6242 Matcher
<const int(&)[1]> n
= Each(1); // NOLINT
6244 const int b
[1] = {1};
6245 EXPECT_EQ("", Explain(n
, b
));
6248 EXPECT_EQ("whose element #0 doesn't match", Explain(n
, b
));
6253 m
= Each(GreaterThan(0));
6254 EXPECT_EQ("", Explain(m
, a
));
6256 m
= Each(GreaterThan(10));
6257 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
6261 TEST(EachTest
, DescribesItselfCorrectly
) {
6262 Matcher
<vector
<int> > m
= Each(1);
6263 EXPECT_EQ("only contains elements that is equal to 1", Describe(m
));
6265 Matcher
<vector
<int> > m2
= Not(m
);
6266 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2
));
6269 TEST(EachTest
, MatchesVectorWhenAllElementsMatch
) {
6270 vector
<int> some_vector
;
6271 EXPECT_THAT(some_vector
, Each(1));
6272 some_vector
.push_back(3);
6273 EXPECT_THAT(some_vector
, Not(Each(1)));
6274 EXPECT_THAT(some_vector
, Each(3));
6275 some_vector
.push_back(1);
6276 some_vector
.push_back(2);
6277 EXPECT_THAT(some_vector
, Not(Each(3)));
6278 EXPECT_THAT(some_vector
, Each(Lt(3.5)));
6280 vector
<std::string
> another_vector
;
6281 another_vector
.push_back("fee");
6282 EXPECT_THAT(another_vector
, Each(std::string("fee")));
6283 another_vector
.push_back("fie");
6284 another_vector
.push_back("foe");
6285 another_vector
.push_back("fum");
6286 EXPECT_THAT(another_vector
, Not(Each(std::string("fee"))));
6289 TEST(EachTest
, MatchesMapWhenAllElementsMatch
) {
6290 map
<const char*, int> my_map
;
6291 const char* bar
= "a string";
6293 EXPECT_THAT(my_map
, Each(make_pair(bar
, 2)));
6295 map
<std::string
, int> another_map
;
6296 EXPECT_THAT(another_map
, Each(make_pair(std::string("fee"), 1)));
6297 another_map
["fee"] = 1;
6298 EXPECT_THAT(another_map
, Each(make_pair(std::string("fee"), 1)));
6299 another_map
["fie"] = 2;
6300 another_map
["foe"] = 3;
6301 another_map
["fum"] = 4;
6302 EXPECT_THAT(another_map
, Not(Each(make_pair(std::string("fee"), 1))));
6303 EXPECT_THAT(another_map
, Not(Each(make_pair(std::string("fum"), 1))));
6304 EXPECT_THAT(another_map
, Each(Pair(_
, Gt(0))));
6307 TEST(EachTest
, AcceptsMatcher
) {
6308 const int a
[] = {1, 2, 3};
6309 EXPECT_THAT(a
, Each(Gt(0)));
6310 EXPECT_THAT(a
, Not(Each(Gt(1))));
6313 TEST(EachTest
, WorksForNativeArrayAsTuple
) {
6314 const int a
[] = {1, 2};
6315 const int* const pointer
= a
;
6316 EXPECT_THAT(make_tuple(pointer
, 2), Each(Gt(0)));
6317 EXPECT_THAT(make_tuple(pointer
, 2), Not(Each(Gt(1))));
6320 // For testing Pointwise().
6321 class IsHalfOfMatcher
{
6323 template <typename T1
, typename T2
>
6324 bool MatchAndExplain(const tuple
<T1
, T2
>& a_pair
,
6325 MatchResultListener
* listener
) const {
6326 if (get
<0>(a_pair
) == get
<1>(a_pair
)/2) {
6327 *listener
<< "where the second is " << get
<1>(a_pair
);
6330 *listener
<< "where the second/2 is " << get
<1>(a_pair
)/2;
6335 void DescribeTo(ostream
* os
) const {
6336 *os
<< "are a pair where the first is half of the second";
6339 void DescribeNegationTo(ostream
* os
) const {
6340 *os
<< "are a pair where the first isn't half of the second";
6344 PolymorphicMatcher
<IsHalfOfMatcher
> IsHalfOf() {
6345 return MakePolymorphicMatcher(IsHalfOfMatcher());
6348 TEST(PointwiseTest
, DescribesSelf
) {
6353 const Matcher
<const vector
<int>&> m
= Pointwise(IsHalfOf(), rhs
);
6354 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
6355 "in { 1, 2, 3 } are a pair where the first is half of the second",
6357 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
6358 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
6359 "where the first isn't half of the second",
6360 DescribeNegation(m
));
6363 TEST(PointwiseTest
, MakesCopyOfRhs
) {
6364 list
<signed char> rhs
;
6369 const Matcher
<const int (&)[2]> m
= Pointwise(IsHalfOf(), rhs
);
6370 EXPECT_THAT(lhs
, m
);
6372 // Changing rhs now shouldn't affect m, which made a copy of rhs.
6374 EXPECT_THAT(lhs
, m
);
6377 TEST(PointwiseTest
, WorksForLhsNativeArray
) {
6378 const int lhs
[] = {1, 2, 3};
6383 EXPECT_THAT(lhs
, Pointwise(Lt(), rhs
));
6384 EXPECT_THAT(lhs
, Not(Pointwise(Gt(), rhs
)));
6387 TEST(PointwiseTest
, WorksForRhsNativeArray
) {
6388 const int rhs
[] = {1, 2, 3};
6393 EXPECT_THAT(lhs
, Pointwise(Gt(), rhs
));
6394 EXPECT_THAT(lhs
, Not(Pointwise(Lt(), rhs
)));
6397 // Test is effective only with sanitizers.
6398 TEST(PointwiseTest
, WorksForVectorOfBool
) {
6399 vector
<bool> rhs(3, false);
6401 vector
<bool> lhs
= rhs
;
6402 EXPECT_THAT(lhs
, Pointwise(Eq(), rhs
));
6404 EXPECT_THAT(lhs
, Not(Pointwise(Eq(), rhs
)));
6407 #if GTEST_HAS_STD_INITIALIZER_LIST_
6409 TEST(PointwiseTest
, WorksForRhsInitializerList
) {
6410 const vector
<int> lhs
{2, 4, 6};
6411 EXPECT_THAT(lhs
, Pointwise(Gt(), {1, 2, 3}));
6412 EXPECT_THAT(lhs
, Not(Pointwise(Lt(), {3, 3, 7})));
6415 #endif // GTEST_HAS_STD_INITIALIZER_LIST_
6417 TEST(PointwiseTest
, RejectsWrongSize
) {
6418 const double lhs
[2] = {1, 2};
6419 const int rhs
[1] = {0};
6420 EXPECT_THAT(lhs
, Not(Pointwise(Gt(), rhs
)));
6421 EXPECT_EQ("which contains 2 values",
6422 Explain(Pointwise(Gt(), rhs
), lhs
));
6424 const int rhs2
[3] = {0, 1, 2};
6425 EXPECT_THAT(lhs
, Not(Pointwise(Gt(), rhs2
)));
6428 TEST(PointwiseTest
, RejectsWrongContent
) {
6429 const double lhs
[3] = {1, 2, 3};
6430 const int rhs
[3] = {2, 6, 4};
6431 EXPECT_THAT(lhs
, Not(Pointwise(IsHalfOf(), rhs
)));
6432 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
6433 "where the second/2 is 3",
6434 Explain(Pointwise(IsHalfOf(), rhs
), lhs
));
6437 TEST(PointwiseTest
, AcceptsCorrectContent
) {
6438 const double lhs
[3] = {1, 2, 3};
6439 const int rhs
[3] = {2, 4, 6};
6440 EXPECT_THAT(lhs
, Pointwise(IsHalfOf(), rhs
));
6441 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs
), lhs
));
6444 TEST(PointwiseTest
, AllowsMonomorphicInnerMatcher
) {
6445 const double lhs
[3] = {1, 2, 3};
6446 const int rhs
[3] = {2, 4, 6};
6447 const Matcher
<tuple
<const double&, const int&> > m1
= IsHalfOf();
6448 EXPECT_THAT(lhs
, Pointwise(m1
, rhs
));
6449 EXPECT_EQ("", Explain(Pointwise(m1
, rhs
), lhs
));
6451 // This type works as a tuple<const double&, const int&> can be
6452 // implicitly cast to tuple<double, int>.
6453 const Matcher
<tuple
<double, int> > m2
= IsHalfOf();
6454 EXPECT_THAT(lhs
, Pointwise(m2
, rhs
));
6455 EXPECT_EQ("", Explain(Pointwise(m2
, rhs
), lhs
));
6458 TEST(UnorderedPointwiseTest
, DescribesSelf
) {
6463 const Matcher
<const vector
<int>&> m
= UnorderedPointwise(IsHalfOf(), rhs
);
6465 "has 3 elements and there exists some permutation of elements such "
6467 " - element #0 and 1 are a pair where the first is half of the second, "
6469 " - element #1 and 2 are a pair where the first is half of the second, "
6471 " - element #2 and 3 are a pair where the first is half of the second",
6474 "doesn't have 3 elements, or there exists no permutation of elements "
6476 " - element #0 and 1 are a pair where the first is half of the second, "
6478 " - element #1 and 2 are a pair where the first is half of the second, "
6480 " - element #2 and 3 are a pair where the first is half of the second",
6481 DescribeNegation(m
));
6484 TEST(UnorderedPointwiseTest
, MakesCopyOfRhs
) {
6485 list
<signed char> rhs
;
6490 const Matcher
<const int (&)[2]> m
= UnorderedPointwise(IsHalfOf(), rhs
);
6491 EXPECT_THAT(lhs
, m
);
6493 // Changing rhs now shouldn't affect m, which made a copy of rhs.
6495 EXPECT_THAT(lhs
, m
);
6498 TEST(UnorderedPointwiseTest
, WorksForLhsNativeArray
) {
6499 const int lhs
[] = {1, 2, 3};
6504 EXPECT_THAT(lhs
, UnorderedPointwise(Lt(), rhs
));
6505 EXPECT_THAT(lhs
, Not(UnorderedPointwise(Gt(), rhs
)));
6508 TEST(UnorderedPointwiseTest
, WorksForRhsNativeArray
) {
6509 const int rhs
[] = {1, 2, 3};
6514 EXPECT_THAT(lhs
, UnorderedPointwise(Gt(), rhs
));
6515 EXPECT_THAT(lhs
, Not(UnorderedPointwise(Lt(), rhs
)));
6518 #if GTEST_HAS_STD_INITIALIZER_LIST_
6520 TEST(UnorderedPointwiseTest
, WorksForRhsInitializerList
) {
6521 const vector
<int> lhs
{2, 4, 6};
6522 EXPECT_THAT(lhs
, UnorderedPointwise(Gt(), {5, 1, 3}));
6523 EXPECT_THAT(lhs
, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
6526 #endif // GTEST_HAS_STD_INITIALIZER_LIST_
6528 TEST(UnorderedPointwiseTest
, RejectsWrongSize
) {
6529 const double lhs
[2] = {1, 2};
6530 const int rhs
[1] = {0};
6531 EXPECT_THAT(lhs
, Not(UnorderedPointwise(Gt(), rhs
)));
6532 EXPECT_EQ("which has 2 elements",
6533 Explain(UnorderedPointwise(Gt(), rhs
), lhs
));
6535 const int rhs2
[3] = {0, 1, 2};
6536 EXPECT_THAT(lhs
, Not(UnorderedPointwise(Gt(), rhs2
)));
6539 TEST(UnorderedPointwiseTest
, RejectsWrongContent
) {
6540 const double lhs
[3] = {1, 2, 3};
6541 const int rhs
[3] = {2, 6, 6};
6542 EXPECT_THAT(lhs
, Not(UnorderedPointwise(IsHalfOf(), rhs
)));
6543 EXPECT_EQ("where the following elements don't match any matchers:\n"
6545 Explain(UnorderedPointwise(IsHalfOf(), rhs
), lhs
));
6548 TEST(UnorderedPointwiseTest
, AcceptsCorrectContentInSameOrder
) {
6549 const double lhs
[3] = {1, 2, 3};
6550 const int rhs
[3] = {2, 4, 6};
6551 EXPECT_THAT(lhs
, UnorderedPointwise(IsHalfOf(), rhs
));
6554 TEST(UnorderedPointwiseTest
, AcceptsCorrectContentInDifferentOrder
) {
6555 const double lhs
[3] = {1, 2, 3};
6556 const int rhs
[3] = {6, 4, 2};
6557 EXPECT_THAT(lhs
, UnorderedPointwise(IsHalfOf(), rhs
));
6560 TEST(UnorderedPointwiseTest
, AllowsMonomorphicInnerMatcher
) {
6561 const double lhs
[3] = {1, 2, 3};
6562 const int rhs
[3] = {4, 6, 2};
6563 const Matcher
<tuple
<const double&, const int&> > m1
= IsHalfOf();
6564 EXPECT_THAT(lhs
, UnorderedPointwise(m1
, rhs
));
6566 // This type works as a tuple<const double&, const int&> can be
6567 // implicitly cast to tuple<double, int>.
6568 const Matcher
<tuple
<double, int> > m2
= IsHalfOf();
6569 EXPECT_THAT(lhs
, UnorderedPointwise(m2
, rhs
));
6572 // Sample optional type implementation with minimal requirements for use with
6573 // Optional matcher.
6574 class SampleOptionalInt
{
6576 typedef int value_type
;
6577 explicit SampleOptionalInt(int value
) : value_(value
), has_value_(true) {}
6578 SampleOptionalInt() : value_(0), has_value_(false) {}
6579 operator bool() const {
6582 const int& operator*() const {
6590 TEST(OptionalTest
, DescribesSelf
) {
6591 const Matcher
<SampleOptionalInt
> m
= Optional(Eq(1));
6592 EXPECT_EQ("value is equal to 1", Describe(m
));
6595 TEST(OptionalTest
, ExplainsSelf
) {
6596 const Matcher
<SampleOptionalInt
> m
= Optional(Eq(1));
6597 EXPECT_EQ("whose value 1 matches", Explain(m
, SampleOptionalInt(1)));
6598 EXPECT_EQ("whose value 2 doesn't match", Explain(m
, SampleOptionalInt(2)));
6601 TEST(OptionalTest
, MatchesNonEmptyOptional
) {
6602 const Matcher
<SampleOptionalInt
> m1
= Optional(1);
6603 const Matcher
<SampleOptionalInt
> m2
= Optional(Eq(2));
6604 const Matcher
<SampleOptionalInt
> m3
= Optional(Lt(3));
6605 SampleOptionalInt
opt(1);
6606 EXPECT_TRUE(m1
.Matches(opt
));
6607 EXPECT_FALSE(m2
.Matches(opt
));
6608 EXPECT_TRUE(m3
.Matches(opt
));
6611 TEST(OptionalTest
, DoesNotMatchNullopt
) {
6612 const Matcher
<SampleOptionalInt
> m
= Optional(1);
6613 SampleOptionalInt empty
;
6614 EXPECT_FALSE(m
.Matches(empty
));
6617 class SampleVariantIntString
{
6619 SampleVariantIntString(int i
) : i_(i
), has_int_(true) {}
6620 SampleVariantIntString(const std::string
& s
) : s_(s
), has_int_(false) {}
6622 template <typename T
>
6623 friend bool holds_alternative(const SampleVariantIntString
& value
) {
6624 return value
.has_int_
== internal::IsSame
<T
, int>::value
;
6627 template <typename T
>
6628 friend const T
& get(const SampleVariantIntString
& value
) {
6629 return value
.get_impl(static_cast<T
*>(NULL
));
6633 const int& get_impl(int*) const { return i_
; }
6634 const std::string
& get_impl(std::string
*) const { return s_
; }
6641 TEST(VariantTest
, DescribesSelf
) {
6642 const Matcher
<SampleVariantIntString
> m
= VariantWith
<int>(Eq(1));
6643 EXPECT_THAT(Describe(m
), ContainsRegex("is a variant<> with value of type "
6644 "'.*' and the value is equal to 1"));
6647 TEST(VariantTest
, ExplainsSelf
) {
6648 const Matcher
<SampleVariantIntString
> m
= VariantWith
<int>(Eq(1));
6649 EXPECT_THAT(Explain(m
, SampleVariantIntString(1)),
6650 ContainsRegex("whose value 1"));
6651 EXPECT_THAT(Explain(m
, SampleVariantIntString("A")),
6652 HasSubstr("whose value is not of type '"));
6653 EXPECT_THAT(Explain(m
, SampleVariantIntString(2)),
6654 "whose value 2 doesn't match");
6657 TEST(VariantTest
, FullMatch
) {
6658 Matcher
<SampleVariantIntString
> m
= VariantWith
<int>(Eq(1));
6659 EXPECT_TRUE(m
.Matches(SampleVariantIntString(1)));
6661 m
= VariantWith
<std::string
>(Eq("1"));
6662 EXPECT_TRUE(m
.Matches(SampleVariantIntString("1")));
6665 TEST(VariantTest
, TypeDoesNotMatch
) {
6666 Matcher
<SampleVariantIntString
> m
= VariantWith
<int>(Eq(1));
6667 EXPECT_FALSE(m
.Matches(SampleVariantIntString("1")));
6669 m
= VariantWith
<std::string
>(Eq("1"));
6670 EXPECT_FALSE(m
.Matches(SampleVariantIntString(1)));
6673 TEST(VariantTest
, InnerDoesNotMatch
) {
6674 Matcher
<SampleVariantIntString
> m
= VariantWith
<int>(Eq(1));
6675 EXPECT_FALSE(m
.Matches(SampleVariantIntString(2)));
6677 m
= VariantWith
<std::string
>(Eq("1"));
6678 EXPECT_FALSE(m
.Matches(SampleVariantIntString("2")));
6681 class SampleAnyType
{
6683 explicit SampleAnyType(int i
) : index_(0), i_(i
) {}
6684 explicit SampleAnyType(const std::string
& s
) : index_(1), s_(s
) {}
6686 template <typename T
>
6687 friend const T
* any_cast(const SampleAnyType
* any
) {
6688 return any
->get_impl(static_cast<T
*>(NULL
));
6696 const int* get_impl(int*) const { return index_
== 0 ? &i_
: NULL
; }
6697 const std::string
* get_impl(std::string
*) const {
6698 return index_
== 1 ? &s_
: NULL
;
6702 TEST(AnyWithTest
, FullMatch
) {
6703 Matcher
<SampleAnyType
> m
= AnyWith
<int>(Eq(1));
6704 EXPECT_TRUE(m
.Matches(SampleAnyType(1)));
6707 TEST(AnyWithTest
, TestBadCastType
) {
6708 Matcher
<SampleAnyType
> m
= AnyWith
<std::string
>(Eq("fail"));
6709 EXPECT_FALSE(m
.Matches(SampleAnyType(1)));
6712 #if GTEST_LANG_CXX11
6713 TEST(AnyWithTest
, TestUseInContainers
) {
6714 std::vector
<SampleAnyType
> a
;
6719 a
, ElementsAreArray({AnyWith
<int>(1), AnyWith
<int>(2), AnyWith
<int>(3)}));
6721 std::vector
<SampleAnyType
> b
;
6722 b
.emplace_back("hello");
6723 b
.emplace_back("merhaba");
6724 b
.emplace_back("salut");
6725 EXPECT_THAT(b
, ElementsAreArray({AnyWith
<std::string
>("hello"),
6726 AnyWith
<std::string
>("merhaba"),
6727 AnyWith
<std::string
>("salut")}));
6729 #endif // GTEST_LANG_CXX11
6730 TEST(AnyWithTest
, TestCompare
) {
6731 EXPECT_THAT(SampleAnyType(1), AnyWith
<int>(Gt(0)));
6734 TEST(AnyWithTest
, DescribesSelf
) {
6735 const Matcher
<const SampleAnyType
&> m
= AnyWith
<int>(Eq(1));
6736 EXPECT_THAT(Describe(m
), ContainsRegex("is an 'any' type with value of type "
6737 "'.*' and the value is equal to 1"));
6740 TEST(AnyWithTest
, ExplainsSelf
) {
6741 const Matcher
<const SampleAnyType
&> m
= AnyWith
<int>(Eq(1));
6743 EXPECT_THAT(Explain(m
, SampleAnyType(1)), ContainsRegex("whose value 1"));
6744 EXPECT_THAT(Explain(m
, SampleAnyType("A")),
6745 HasSubstr("whose value is not of type '"));
6746 EXPECT_THAT(Explain(m
, SampleAnyType(2)), "whose value 2 doesn't match");
6749 #if GTEST_LANG_CXX11
6751 TEST(PointeeTest
, WorksOnMoveOnlyType
) {
6752 std::unique_ptr
<int> p(new int(3));
6753 EXPECT_THAT(p
, Pointee(Eq(3)));
6754 EXPECT_THAT(p
, Not(Pointee(Eq(2))));
6757 TEST(NotTest
, WorksOnMoveOnlyType
) {
6758 std::unique_ptr
<int> p(new int(3));
6759 EXPECT_THAT(p
, Pointee(Eq(3)));
6760 EXPECT_THAT(p
, Not(Pointee(Eq(2))));
6763 #endif // GTEST_LANG_CXX11
6765 } // namespace gmock_matchers_test
6766 } // namespace testing