Wire Sysio Wire Sysion 1.0.0
Loading...
Searching...
No Matches
gmock-matchers_test.cc
Go to the documentation of this file.
1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file tests some commonly used argument matchers.
35
38
39#include <string.h>
40#include <time.h>
41#include <deque>
42#include <functional>
43#include <iostream>
44#include <iterator>
45#include <limits>
46#include <list>
47#include <map>
48#include <memory>
49#include <set>
50#include <sstream>
51#include <string>
52#include <utility>
53#include <vector>
54#include "gmock/gmock.h"
55#include "gtest/gtest.h"
56#include "gtest/gtest-spi.h"
57
58#if GTEST_HAS_STD_FORWARD_LIST_
59# include <forward_list> // NOLINT
60#endif
61
62#if GTEST_LANG_CXX11
63# include <type_traits>
64#endif
65
66namespace testing {
67namespace gmock_matchers_test {
68
69using std::greater;
70using std::less;
71using std::list;
72using std::make_pair;
73using std::map;
74using std::multimap;
75using std::multiset;
76using std::ostream;
77using std::pair;
78using std::set;
79using std::stringstream;
80using std::vector;
81using testing::A;
83using testing::AllOf;
84using testing::An;
85using testing::AnyOf;
86using testing::ByRef;
91using testing::Eq;
93using testing::Field;
96using testing::Ge;
97using testing::Gt;
99using testing::IsEmpty;
100using testing::IsNull;
101using testing::Key;
102using testing::Le;
103using testing::Lt;
107using testing::Matcher;
110using testing::Matches;
116using testing::Ne;
117using testing::Not;
118using testing::NotNull;
119using testing::Pair;
120using testing::Pointee;
124using testing::Ref;
126using testing::SizeIs;
130using testing::StrEq;
131using testing::StrNe;
133using testing::Truly;
134using testing::TypedEq;
136using testing::Value;
139using testing::_;
140using testing::get;
157using testing::make_tuple;
158using testing::tuple;
159
160// For testing ExplainMatchResultTo().
162 public:
163 explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
164
165 virtual void DescribeTo(ostream* os) const {
166 *os << "is > " << rhs_;
167 }
168
169 virtual bool MatchAndExplain(int lhs,
170 MatchResultListener* listener) const {
171 const int diff = lhs - rhs_;
172 if (diff > 0) {
173 *listener << "which is " << diff << " more than " << rhs_;
174 } else if (diff == 0) {
175 *listener << "which is the same as " << rhs_;
176 } else {
177 *listener << "which is " << -diff << " less than " << rhs_;
178 }
179
180 return lhs > rhs_;
181 }
182
183 private:
184 int rhs_;
185};
186
188 return MakeMatcher(new GreaterThanMatcher(n));
189}
190
191std::string OfType(const std::string& type_name) {
192#if GTEST_HAS_RTTI
193 return " (of type " + type_name + ")";
194#else
195 return "";
196#endif
197}
198
199// Returns the description of the given matcher.
200template <typename T>
201std::string Describe(const Matcher<T>& m) {
202 return DescribeMatcher<T>(m);
203}
204
205// Returns the description of the negation of the given matcher.
206template <typename T>
207std::string DescribeNegation(const Matcher<T>& m) {
208 return DescribeMatcher<T>(m, true);
209}
210
211// Returns the reason why x matches, or doesn't match, m.
212template <typename MatcherType, typename Value>
213std::string Explain(const MatcherType& m, const Value& x) {
215 ExplainMatchResult(m, x, &listener);
216 return listener.str();
217}
218
219TEST(MonotonicMatcherTest, IsPrintable) {
220 stringstream ss;
221 ss << GreaterThan(5);
222 EXPECT_EQ("is > 5", ss.str());
223}
224
225TEST(MatchResultListenerTest, StreamingWorks) {
227 listener << "hi" << 5;
228 EXPECT_EQ("hi5", listener.str());
229
230 listener.Clear();
231 EXPECT_EQ("", listener.str());
232
233 listener << 42;
234 EXPECT_EQ("42", listener.str());
235
236 // Streaming shouldn't crash when the underlying ostream is NULL.
238 dummy << "hi" << 5;
239}
240
241TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
242 EXPECT_TRUE(DummyMatchResultListener().stream() == NULL);
243 EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL);
244
245 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
246}
247
248TEST(MatchResultListenerTest, IsInterestedWorks) {
249 EXPECT_TRUE(StringMatchResultListener().IsInterested());
250 EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
251
252 EXPECT_FALSE(DummyMatchResultListener().IsInterested());
253 EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested());
254}
255
256// Makes sure that the MatcherInterface<T> interface doesn't
257// change.
259 public:
260 virtual bool MatchAndExplain(int x,
261 MatchResultListener* /* listener */) const {
262 return x % 2 == 0;
263 }
264
265 virtual void DescribeTo(ostream* os) const {
266 *os << "is an even number";
267 }
268
269 // We deliberately don't define DescribeNegationTo() and
270 // ExplainMatchResultTo() here, to make sure the definition of these
271 // two methods is optional.
272};
273
274// Makes sure that the MatcherInterface API doesn't change.
275TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
277}
278
279// Tests implementing a monomorphic matcher using MatchAndExplain().
280
282 public:
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
289 // too.
290 *listener->stream() << " == " << (x % 2);
291 }
292 return match;
293 }
294
295 virtual void DescribeTo(ostream* os) const {
296 *os << "is an even number";
297 }
298};
299
300TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
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));
306}
307
308// Tests default-constructing a matcher.
309TEST(MatcherTest, CanBeDefaultConstructed) {
311}
312
313// Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
314TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
317 EXPECT_TRUE(m.Matches(4));
318 EXPECT_FALSE(m.Matches(5));
319}
320
321// Tests that value can be used in place of Eq(value).
322TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
323 Matcher<int> m1 = 5;
324 EXPECT_TRUE(m1.Matches(5));
325 EXPECT_FALSE(m1.Matches(6));
326}
327
328// Tests that NULL can be used in place of Eq(NULL).
329TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
330 Matcher<int*> m1 = NULL;
331 EXPECT_TRUE(m1.Matches(NULL));
332 int n = 0;
333 EXPECT_FALSE(m1.Matches(&n));
334}
335
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.
338struct Undefined {
339 virtual ~Undefined() = 0;
340 static const int kInt = 1;
341};
342
343TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) {
345 EXPECT_TRUE(m1.Matches(1));
346 EXPECT_FALSE(m1.Matches(2));
347}
348
349// Test that a matcher parameterized with an abstract class compiles.
350TEST(MatcherTest, CanAcceptAbstractClass) { Matcher<const Undefined&> m = _; }
351
352// Tests that matchers are copyable.
353TEST(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));
358
359 // Tests the assignment operator.
360 m1 = Eq(true);
361 EXPECT_TRUE(m1.Matches(true));
362 EXPECT_FALSE(m1.Matches(false));
363}
364
365// Tests that Matcher<T>::DescribeTo() calls
366// MatcherInterface<T>::DescribeTo().
367TEST(MatcherTest, CanDescribeItself) {
368 EXPECT_EQ("is an even number",
370}
371
372// Tests Matcher<T>::MatchAndExplain().
373TEST(MatcherTest, MatchAndExplain) {
376 EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
377 EXPECT_EQ("which is 42 more than 0", listener1.str());
378
380 EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
381 EXPECT_EQ("which is 9 less than 0", listener2.str());
382}
383
384// Tests that a C-string literal can be implicitly converted to a
385// Matcher<std::string> or Matcher<const std::string&>.
386TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
387 Matcher<std::string> m1 = "hi";
388 EXPECT_TRUE(m1.Matches("hi"));
389 EXPECT_FALSE(m1.Matches("hello"));
390
392 EXPECT_TRUE(m2.Matches("hi"));
393 EXPECT_FALSE(m2.Matches("hello"));
394}
395
396// Tests that a string object can be implicitly converted to a
397// Matcher<std::string> or Matcher<const std::string&>.
398TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
399 Matcher<std::string> m1 = std::string("hi");
400 EXPECT_TRUE(m1.Matches("hi"));
401 EXPECT_FALSE(m1.Matches("hello"));
402
403 Matcher<const std::string&> m2 = std::string("hi");
404 EXPECT_TRUE(m2.Matches("hi"));
405 EXPECT_FALSE(m2.Matches("hello"));
406}
407
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&>.
411TEST(StringMatcherTest, CanBeImplicitlyConstructedFromGlobalString) {
413 EXPECT_TRUE(m1.Matches("hi"));
414 EXPECT_FALSE(m1.Matches("hello"));
415
417 EXPECT_TRUE(m2.Matches("hi"));
418 EXPECT_FALSE(m2.Matches("hello"));
419}
420#endif // GTEST_HAS_GLOBAL_STRING
421
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&>.
425TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
426 Matcher< ::string> m1 = "hi";
427 EXPECT_TRUE(m1.Matches("hi"));
428 EXPECT_FALSE(m1.Matches("hello"));
429
430 Matcher<const ::string&> m2 = "hi";
431 EXPECT_TRUE(m2.Matches("hi"));
432 EXPECT_FALSE(m2.Matches("hello"));
433}
434
435// Tests that a std::string object can be implicitly converted to a
436// Matcher<::string> or Matcher<const ::string&>.
437TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromString) {
438 Matcher< ::string> m1 = std::string("hi");
439 EXPECT_TRUE(m1.Matches("hi"));
440 EXPECT_FALSE(m1.Matches("hello"));
441
442 Matcher<const ::string&> m2 = std::string("hi");
443 EXPECT_TRUE(m2.Matches("hi"));
444 EXPECT_FALSE(m2.Matches("hello"));
445}
446
447// Tests that a ::string object can be implicitly converted to a
448// Matcher<::string> or Matcher<const ::string&>.
449TEST(GlobalStringMatcherTest, CanBeImplicitlyConstructedFromGlobalString) {
450 Matcher< ::string> m1 = ::string("hi");
451 EXPECT_TRUE(m1.Matches("hi"));
452 EXPECT_FALSE(m1.Matches("hello"));
453
454 Matcher<const ::string&> m2 = ::string("hi");
455 EXPECT_TRUE(m2.Matches("hi"));
456 EXPECT_FALSE(m2.Matches("hello"));
457}
458#endif // GTEST_HAS_GLOBAL_STRING
459
460#if GTEST_HAS_ABSL
461// Tests that a C-string literal can be implicitly converted to a
462// Matcher<absl::string_view> or Matcher<const absl::string_view&>.
463TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
464 Matcher<absl::string_view> m1 = "cats";
465 EXPECT_TRUE(m1.Matches("cats"));
466 EXPECT_FALSE(m1.Matches("dogs"));
467
468 Matcher<const absl::string_view&> m2 = "cats";
469 EXPECT_TRUE(m2.Matches("cats"));
470 EXPECT_FALSE(m2.Matches("dogs"));
471}
472
473// Tests that a std::string object can be implicitly converted to a
474// Matcher<absl::string_view> or Matcher<const absl::string_view&>.
475TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {
476 Matcher<absl::string_view> m1 = std::string("cats");
477 EXPECT_TRUE(m1.Matches("cats"));
478 EXPECT_FALSE(m1.Matches("dogs"));
479
480 Matcher<const absl::string_view&> m2 = std::string("cats");
481 EXPECT_TRUE(m2.Matches("cats"));
482 EXPECT_FALSE(m2.Matches("dogs"));
483}
484
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&>.
488TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromGlobalString) {
489 Matcher<absl::string_view> m1 = ::string("cats");
490 EXPECT_TRUE(m1.Matches("cats"));
491 EXPECT_FALSE(m1.Matches("dogs"));
492
493 Matcher<const absl::string_view&> m2 = ::string("cats");
494 EXPECT_TRUE(m2.Matches("cats"));
495 EXPECT_FALSE(m2.Matches("dogs"));
496}
497#endif // GTEST_HAS_GLOBAL_STRING
498
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&>.
501TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {
502 Matcher<absl::string_view> m1 = absl::string_view("cats");
503 EXPECT_TRUE(m1.Matches("cats"));
504 EXPECT_FALSE(m1.Matches("dogs"));
505
506 Matcher<const absl::string_view&> m2 = absl::string_view("cats");
507 EXPECT_TRUE(m2.Matches("cats"));
508 EXPECT_FALSE(m2.Matches("dogs"));
509}
510#endif // GTEST_HAS_ABSL
511
512// Tests that MakeMatcher() constructs a Matcher<T> from a
513// MatcherInterface* without requiring the user to explicitly
514// write the type.
515TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
516 const MatcherInterface<int>* dummy_impl = NULL;
517 Matcher<int> m = MakeMatcher(dummy_impl);
518}
519
520// Tests that MakePolymorphicMatcher() can construct a polymorphic
521// matcher from its implementation using the old API.
522const int g_bar = 1;
524 public:
525 template <typename T>
526 bool MatchAndExplain(const T& x,
527 MatchResultListener* /* listener */) const {
528 const void* p = &x;
529 return p == &g_bar || x == 0;
530 }
531
532 void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
533
534 void DescribeNegationTo(ostream* os) const {
535 *os << "doesn't reference g_bar and is not zero";
536 }
537};
538
539// This function verifies that MakePolymorphicMatcher() returns a
540// PolymorphicMatcher<T> where T is the argument's type.
544
545TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
546 // Using a polymorphic matcher to match a reference type.
548 EXPECT_TRUE(m1.Matches(0));
549 // Verifies that the identity of a by-reference argument is preserved.
551 EXPECT_FALSE(m1.Matches(1));
552 EXPECT_EQ("g_bar or zero", Describe(m1));
553
554 // Using a polymorphic matcher to match a value type.
556 EXPECT_TRUE(m2.Matches(0.0));
557 EXPECT_FALSE(m2.Matches(0.1));
558 EXPECT_EQ("g_bar or zero", Describe(m2));
559}
560
561// Tests implementing a polymorphic matcher using MatchAndExplain().
562
564 public:
565 void DescribeTo(ostream* os) const { *os << "is even"; }
566
567 void DescribeNegationTo(ostream* os) const {
568 *os << "is odd";
569 }
570
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
577 // too.
578 *listener->stream() << " == " << (x % 2);
579 }
580 return (x % 2) == 0;
581 }
582};
583
587
588TEST(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));
594
595 const Matcher<int> not_m1 = Not(m1);
596 EXPECT_EQ("is odd", Describe(not_m1));
597
598 EXPECT_EQ("% 2 == 0", Explain(m1, 42));
599
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));
605
606 const Matcher<char> not_m2 = Not(m2);
607 EXPECT_EQ("is odd", Describe(not_m2));
608
609 EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
610}
611
612// Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
613TEST(MatcherCastTest, FromPolymorphicMatcher) {
615 EXPECT_TRUE(m.Matches(5));
616 EXPECT_FALSE(m.Matches(6));
617}
618
619// For testing casting matchers between compatible types.
620class IntValue {
621 public:
622 // An int can be statically (although not implicitly) cast to a
623 // IntValue.
624 explicit IntValue(int a_value) : value_(a_value) {}
625
626 int value() const { return value_; }
627 private:
628 int value_;
629};
630
631// For testing casting matchers between compatible types.
633 return foo.value() > 0;
634}
635
636// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
637// can be statically converted to U.
638TEST(MatcherCastTest, FromCompatibleType) {
639 Matcher<double> m1 = Eq(2.0);
641 EXPECT_TRUE(m2.Matches(2));
642 EXPECT_FALSE(m2.Matches(3));
643
646 // In the following, the arguments 1 and 0 are statically converted
647 // to IntValue objects, and then tested by the IsPositiveIntValue()
648 // predicate.
649 EXPECT_TRUE(m4.Matches(1));
650 EXPECT_FALSE(m4.Matches(0));
651}
652
653// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
654TEST(MatcherCastTest, FromConstReferenceToNonReference) {
655 Matcher<const int&> m1 = Eq(0);
657 EXPECT_TRUE(m2.Matches(0));
658 EXPECT_FALSE(m2.Matches(1));
659}
660
661// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
662TEST(MatcherCastTest, FromReferenceToNonReference) {
663 Matcher<int&> m1 = Eq(0);
665 EXPECT_TRUE(m2.Matches(0));
666 EXPECT_FALSE(m2.Matches(1));
667}
668
669// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
670TEST(MatcherCastTest, FromNonReferenceToConstReference) {
671 Matcher<int> m1 = Eq(0);
673 EXPECT_TRUE(m2.Matches(0));
674 EXPECT_FALSE(m2.Matches(1));
675}
676
677// Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
678TEST(MatcherCastTest, FromNonReferenceToReference) {
679 Matcher<int> m1 = Eq(0);
681 int n = 0;
682 EXPECT_TRUE(m2.Matches(n));
683 n = 1;
684 EXPECT_FALSE(m2.Matches(n));
685}
686
687// Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
688TEST(MatcherCastTest, FromSameType) {
689 Matcher<int> m1 = Eq(0);
691 EXPECT_TRUE(m2.Matches(0));
692 EXPECT_FALSE(m2.Matches(1));
693}
694
695// Tests that MatcherCast<T>(m) works when m is a value of the same type as the
696// value type of the Matcher.
697TEST(MatcherCastTest, FromAValue) {
699 EXPECT_TRUE(m.Matches(42));
700 EXPECT_FALSE(m.Matches(239));
701}
702
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.
705TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) {
706 const int kExpected = 'c';
708 EXPECT_TRUE(m.Matches(kExpected));
709 EXPECT_FALSE(m.Matches(kExpected + 1));
710}
711
713 friend bool operator==(
715 int rhs) {
716 return 42 == rhs;
717 }
718 friend bool operator==(
719 int lhs,
721 return lhs == 42;
722 }
723};
724
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.
744
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
749
750#if !defined _MSC_VER
751
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
758// in m3.Matcher().
759namespace convertible_from_any {
760// Implicitly convertible from any type.
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";
766 }
767 int value;
768};
769
771 return a.value == b.value;
772}
773
774ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
775 return os << a.value;
776}
777
778TEST(MatcherCastTest, ConversionConstructorIsUsed) {
782}
783
790} // namespace convertible_from_any
791
792#endif // !defined _MSC_VER
793
795 IntReferenceWrapper(const int& a_value) : value(&a_value) {}
796 const int* value;
797};
798
800 return a.value == b.value;
801}
802
803TEST(MatcherCastTest, ValueIsNotCopied) {
804 int n = 42;
806 // Verify that the matcher holds a reference to n, not to its temporary copy.
807 EXPECT_TRUE(m.Matches(n));
808}
809
810class Base {
811 public:
812 virtual ~Base() {}
813 Base() {}
814 private:
816};
817
818class Derived : public Base {
819 public:
820 Derived() : Base() {}
821 int i;
822};
823
824class OtherDerived : public Base {};
825
826// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
827TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
829 EXPECT_TRUE(m2.Matches(' '));
830 EXPECT_FALSE(m2.Matches('\n'));
831}
832
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
835// U.
836TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
837 Matcher<double> m1 = DoubleEq(1.0);
839 EXPECT_TRUE(m2.Matches(1.0f));
840 EXPECT_FALSE(m2.Matches(2.0f));
841
842 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
843 EXPECT_TRUE(m3.Matches('a'));
844 EXPECT_FALSE(m3.Matches('b'));
845}
846
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.
849TEST(SafeMatcherCastTest, FromBaseClass) {
850 Derived d, d2;
851 Matcher<Base*> m1 = Eq(&d);
853 EXPECT_TRUE(m2.Matches(&d));
854 EXPECT_FALSE(m2.Matches(&d2));
855
856 Matcher<Base&> m3 = Ref(d);
858 EXPECT_TRUE(m4.Matches(d));
859 EXPECT_FALSE(m4.Matches(d2));
860}
861
862// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
863TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
864 int n = 0;
865 Matcher<const int&> m1 = Ref(n);
867 int n1 = 0;
868 EXPECT_TRUE(m2.Matches(n));
869 EXPECT_FALSE(m2.Matches(n1));
870}
871
872// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
873TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
874 Matcher<int> m1 = Eq(0);
876 EXPECT_TRUE(m2.Matches(0));
877 EXPECT_FALSE(m2.Matches(1));
878}
879
880// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
881TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
882 Matcher<int> m1 = Eq(0);
884 int n = 0;
885 EXPECT_TRUE(m2.Matches(n));
886 n = 1;
887 EXPECT_FALSE(m2.Matches(n));
888}
889
890// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
891TEST(SafeMatcherCastTest, FromSameType) {
892 Matcher<int> m1 = Eq(0);
894 EXPECT_TRUE(m2.Matches(0));
895 EXPECT_FALSE(m2.Matches(1));
896}
897
898#if !defined _MSC_VER
899
900namespace convertible_from_any {
901TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
905}
906
913} // namespace convertible_from_any
914
915#endif // !defined _MSC_VER
916
917TEST(SafeMatcherCastTest, ValueIsNotCopied) {
918 int n = 42;
920 // Verify that the matcher holds a reference to n, not to its temporary copy.
921 EXPECT_TRUE(m.Matches(n));
922}
923
924TEST(ExpectThat, TakesLiterals) {
925 EXPECT_THAT(1, 1);
926 EXPECT_THAT(1.0, 1.0);
927 EXPECT_THAT(std::string(), "");
928}
929
930TEST(ExpectThat, TakesFunctions) {
931 struct Helper {
932 static void Func() {}
933 };
934 void (*func)() = Helper::Func;
935 EXPECT_THAT(func, Helper::Func);
936 EXPECT_THAT(func, &Helper::Func);
937}
938
939// Tests that A<T>() matches any value of type T.
940TEST(ATest, MatchesAnyValue) {
941 // Tests a matcher for a value type.
943 EXPECT_TRUE(m1.Matches(91.43));
944 EXPECT_TRUE(m1.Matches(-15.32));
945
946 // Tests a matcher for a reference type.
947 int a = 2;
948 int b = -6;
949 Matcher<int&> m2 = A<int&>();
950 EXPECT_TRUE(m2.Matches(a));
951 EXPECT_TRUE(m2.Matches(b));
952}
953
954TEST(ATest, WorksForDerivedClass) {
955 Base base;
956 Derived derived;
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*>());
961}
962
963// Tests that A<T>() describes itself properly.
964TEST(ATest, CanDescribeSelf) {
965 EXPECT_EQ("is anything", Describe(A<bool>()));
966}
967
968// Tests that An<T>() matches any value of type T.
969TEST(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));
974
975 // Tests a matcher for a reference type.
976 int a = 2;
977 int b = -6;
978 Matcher<int&> m2 = An<int&>();
979 EXPECT_TRUE(m2.Matches(a));
980 EXPECT_TRUE(m2.Matches(b));
981}
982
983// Tests that An<T>() describes itself properly.
984TEST(AnTest, CanDescribeSelf) {
985 EXPECT_EQ("is anything", Describe(An<int>()));
986}
987
988// Tests that _ can be used as a matcher for any type and matches any
989// value of that type.
990TEST(UnderscoreTest, MatchesAnyValue) {
991 // Uses _ as a matcher for a value type.
992 Matcher<int> m1 = _;
993 EXPECT_TRUE(m1.Matches(123));
994 EXPECT_TRUE(m1.Matches(-242));
995
996 // Uses _ as a matcher for a reference type.
997 bool a = false;
998 const bool b = true;
1000 EXPECT_TRUE(m2.Matches(a));
1001 EXPECT_TRUE(m2.Matches(b));
1002}
1003
1004// Tests that _ describes itself properly.
1005TEST(UnderscoreTest, CanDescribeSelf) {
1006 Matcher<int> m = _;
1007 EXPECT_EQ("is anything", Describe(m));
1008}
1009
1010// Tests that Eq(x) matches any value equal to x.
1011TEST(EqTest, MatchesEqualValue) {
1012 // 2 C-strings with same content but different addresses.
1013 const char a1[] = "hi";
1014 const char a2[] = "hi";
1015
1016 Matcher<const char*> m1 = Eq(a1);
1017 EXPECT_TRUE(m1.Matches(a1));
1018 EXPECT_FALSE(m1.Matches(a2));
1019}
1020
1021// Tests that Eq(v) describes itself properly.
1022
1024 public:
1025 Unprintable() : c_('a') {}
1026
1027 bool operator==(const Unprintable& /* rhs */) const { return true; }
1028 private:
1029 char c_;
1030};
1031
1032TEST(EqTest, CanDescribeSelf) {
1034 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
1035}
1036
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.
1039TEST(EqTest, IsPolymorphic) {
1040 Matcher<int> m1 = Eq(1);
1041 EXPECT_TRUE(m1.Matches(1));
1042 EXPECT_FALSE(m1.Matches(2));
1043
1044 Matcher<char> m2 = Eq(1);
1045 EXPECT_TRUE(m2.Matches('\1'));
1046 EXPECT_FALSE(m2.Matches('a'));
1047}
1048
1049// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
1050TEST(TypedEqTest, ChecksEqualityForGivenType) {
1051 Matcher<char> m1 = TypedEq<char>('a');
1052 EXPECT_TRUE(m1.Matches('a'));
1053 EXPECT_FALSE(m1.Matches('b'));
1054
1055 Matcher<int> m2 = TypedEq<int>(6);
1056 EXPECT_TRUE(m2.Matches(6));
1057 EXPECT_FALSE(m2.Matches(7));
1058}
1059
1060// Tests that TypedEq(v) describes itself properly.
1061TEST(TypedEqTest, CanDescribeSelf) {
1062 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
1063}
1064
1065// Tests that TypedEq<T>(v) has type Matcher<T>.
1066
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".
1071template <typename T>
1072struct Type {
1073 static bool IsTypeOf(const T& /* v */) { return true; }
1074
1075 template <typename T2>
1076 static void IsTypeOf(T2 v);
1077};
1078
1079TEST(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));
1083}
1084
1085// Tests that Ge(v) matches anything >= v.
1086TEST(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));
1091}
1092
1093// Tests that Ge(v) describes itself properly.
1094TEST(GeTest, CanDescribeSelf) {
1095 Matcher<int> m = Ge(5);
1096 EXPECT_EQ("is >= 5", Describe(m));
1097}
1098
1099// Tests that Gt(v) matches anything > v.
1100TEST(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));
1105}
1106
1107// Tests that Gt(v) describes itself properly.
1108TEST(GtTest, CanDescribeSelf) {
1109 Matcher<int> m = Gt(5);
1110 EXPECT_EQ("is > 5", Describe(m));
1111}
1112
1113// Tests that Le(v) matches anything <= v.
1114TEST(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'));
1119}
1120
1121// Tests that Le(v) describes itself properly.
1122TEST(LeTest, CanDescribeSelf) {
1123 Matcher<int> m = Le(5);
1124 EXPECT_EQ("is <= 5", Describe(m));
1125}
1126
1127// Tests that Lt(v) matches anything < v.
1128TEST(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!"));
1133}
1134
1135// Tests that Lt(v) describes itself properly.
1136TEST(LtTest, CanDescribeSelf) {
1137 Matcher<int> m = Lt(5);
1138 EXPECT_EQ("is < 5", Describe(m));
1139}
1140
1141// Tests that Ne(v) matches anything != v.
1142TEST(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));
1147}
1148
1149// Tests that Ne(v) describes itself properly.
1150TEST(NeTest, CanDescribeSelf) {
1151 Matcher<int> m = Ne(5);
1152 EXPECT_EQ("isn't equal to 5", Describe(m));
1153}
1154
1155// Tests that IsNull() matches any NULL pointer of any type.
1156TEST(IsNullTest, MatchesNullPointer) {
1157 Matcher<int*> m1 = IsNull();
1158 int* p1 = NULL;
1159 int n = 0;
1160 EXPECT_TRUE(m1.Matches(p1));
1161 EXPECT_FALSE(m1.Matches(&n));
1162
1164 const char* p2 = NULL;
1165 EXPECT_TRUE(m2.Matches(p2));
1166 EXPECT_FALSE(m2.Matches("hi"));
1167
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();
1178 void* p3 = NULL;
1179 EXPECT_TRUE(m3.Matches(p3));
1180 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
1181#endif
1182}
1183
1184TEST(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);
1188
1189 EXPECT_TRUE(m.Matches(null_p));
1190 EXPECT_FALSE(m.Matches(non_null_p));
1191}
1192
1193TEST(IsNullTest, ReferenceToConstLinkedPtr) {
1195 const linked_ptr<double> null_p;
1196 const linked_ptr<double> non_null_p(new double);
1197
1198 EXPECT_TRUE(m.Matches(null_p));
1199 EXPECT_FALSE(m.Matches(non_null_p));
1200}
1201
1202#if GTEST_LANG_CXX11
1203TEST(IsNullTest, StdFunction) {
1204 const Matcher<std::function<void()>> m = IsNull();
1205
1206 EXPECT_TRUE(m.Matches(std::function<void()>()));
1207 EXPECT_FALSE(m.Matches([]{}));
1208}
1209#endif // GTEST_LANG_CXX11
1210
1211// Tests that IsNull() describes itself properly.
1212TEST(IsNullTest, CanDescribeSelf) {
1213 Matcher<int*> m = IsNull();
1214 EXPECT_EQ("is NULL", Describe(m));
1215 EXPECT_EQ("isn't NULL", DescribeNegation(m));
1216}
1217
1218// Tests that NotNull() matches any non-NULL pointer of any type.
1219TEST(NotNullTest, MatchesNonNullPointer) {
1220 Matcher<int*> m1 = NotNull();
1221 int* p1 = NULL;
1222 int n = 0;
1223 EXPECT_FALSE(m1.Matches(p1));
1224 EXPECT_TRUE(m1.Matches(&n));
1225
1227 const char* p2 = NULL;
1228 EXPECT_FALSE(m2.Matches(p2));
1229 EXPECT_TRUE(m2.Matches("hi"));
1230}
1231
1232TEST(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);
1236
1237 EXPECT_FALSE(m.Matches(null_p));
1238 EXPECT_TRUE(m.Matches(non_null_p));
1239}
1240
1241TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1243 const linked_ptr<double> null_p;
1244 const linked_ptr<double> non_null_p(new double);
1245
1246 EXPECT_FALSE(m.Matches(null_p));
1247 EXPECT_TRUE(m.Matches(non_null_p));
1248}
1249
1250#if GTEST_LANG_CXX11
1251TEST(NotNullTest, StdFunction) {
1252 const Matcher<std::function<void()>> m = NotNull();
1253
1254 EXPECT_TRUE(m.Matches([]{}));
1255 EXPECT_FALSE(m.Matches(std::function<void()>()));
1256}
1257#endif // GTEST_LANG_CXX11
1258
1259// Tests that NotNull() describes itself properly.
1260TEST(NotNullTest, CanDescribeSelf) {
1261 Matcher<int*> m = NotNull();
1262 EXPECT_EQ("isn't NULL", Describe(m));
1263}
1264
1265// Tests that Ref(variable) matches an argument that references
1266// 'variable'.
1267TEST(RefTest, MatchesSameVariable) {
1268 int a = 0;
1269 int b = 0;
1270 Matcher<int&> m = Ref(a);
1271 EXPECT_TRUE(m.Matches(a));
1272 EXPECT_FALSE(m.Matches(b));
1273}
1274
1275// Tests that Ref(variable) describes itself properly.
1276TEST(RefTest, CanDescribeSelf) {
1277 int n = 5;
1278 Matcher<int&> m = Ref(n);
1279 stringstream ss;
1280 ss << "references the variable @" << &n << " 5";
1281 EXPECT_EQ(ss.str(), Describe(m));
1282}
1283
1284// Test that Ref(non_const_varialbe) can be used as a matcher for a
1285// const reference.
1286TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1287 int a = 0;
1288 int b = 0;
1290 EXPECT_TRUE(m.Matches(a));
1291 EXPECT_FALSE(m.Matches(b));
1292}
1293
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.
1297
1298TEST(RefTest, IsCovariant) {
1299 Base base, base2;
1300 Derived derived;
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));
1305
1306 m1 = Ref(derived);
1307 EXPECT_TRUE(m1.Matches(derived));
1308 EXPECT_FALSE(m1.Matches(base));
1309 EXPECT_FALSE(m1.Matches(base2));
1310}
1311
1312TEST(RefTest, ExplainsResult) {
1313 int n = 0;
1315 StartsWith("which is located @"));
1316
1317 int m = 0;
1319 StartsWith("which is located @"));
1320}
1321
1322// Tests string comparison matchers.
1323
1324TEST(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));
1329
1330 Matcher<const std::string&> m2 = StrEq("Hello");
1331 EXPECT_TRUE(m2.Matches("Hello"));
1332 EXPECT_FALSE(m2.Matches("Hi"));
1333
1334#if GTEST_HAS_ABSL
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
1340}
1341
1342TEST(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\"",
1345 Describe(m));
1346
1347 std::string str("01204500800");
1348 str[3] = '\0';
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));
1354}
1355
1356TEST(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"));
1361
1362 Matcher<std::string> m2 = StrNe(std::string("Hello"));
1363 EXPECT_TRUE(m2.Matches("hello"));
1364 EXPECT_FALSE(m2.Matches("Hello"));
1365
1366#if GTEST_HAS_ABSL
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
1372}
1373
1374TEST(StrNeTest, CanDescribeSelf) {
1375 Matcher<const char*> m = StrNe("Hi");
1376 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
1377}
1378
1379TEST(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));
1385
1387 EXPECT_TRUE(m2.Matches("hello"));
1388 EXPECT_FALSE(m2.Matches("Hi"));
1389
1390#if GTEST_HAS_ABSL
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
1397}
1398
1399TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1400 std::string str1("oabocdooeoo");
1401 std::string str2("OABOCDOOEOO");
1403 EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0')));
1404
1405 str1[3] = str2[3] = '\0';
1407 EXPECT_TRUE(m1.Matches(str2));
1408
1409 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1410 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1412 str1[9] = str2[9] = '\0';
1413 EXPECT_FALSE(m2.Matches(str2));
1414
1416 EXPECT_TRUE(m3.Matches(str2));
1417
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)));
1422}
1423
1424TEST(StrCaseEqTest, CanDescribeSelf) {
1426 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1427}
1428
1429TEST(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"));
1435
1436 Matcher<std::string> m2 = StrCaseNe(std::string("Hello"));
1437 EXPECT_TRUE(m2.Matches(""));
1438 EXPECT_FALSE(m2.Matches("Hello"));
1439
1440#if GTEST_HAS_ABSL
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
1447}
1448
1449TEST(StrCaseNeTest, CanDescribeSelf) {
1451 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
1452}
1453
1454// Tests that HasSubstr() works for matching string-typed values.
1455TEST(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")));
1459
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")));
1463}
1464
1465// Tests that HasSubstr() works for matching C-string-typed values.
1466TEST(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));
1471
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));
1476}
1477
1478#if GTEST_HAS_ABSL
1479// Tests that HasSubstr() works for matching absl::string_view-typed values.
1480TEST(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()));
1485
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()));
1490
1492 EXPECT_TRUE(m3.Matches(absl::string_view("foo")));
1493 EXPECT_FALSE(m3.Matches(absl::string_view()));
1494}
1495#endif // GTEST_HAS_ABSL
1496
1497// Tests that HasSubstr(s) describes itself properly.
1498TEST(HasSubstrTest, CanDescribeSelf) {
1499 Matcher<std::string> m = HasSubstr("foo\n\"");
1500 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1501}
1502
1503TEST(KeyTest, CanDescribeSelf) {
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));
1507}
1508
1509TEST(KeyTest, ExplainsResult) {
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)));
1515}
1516
1517TEST(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))));
1523}
1524
1525#if GTEST_LANG_CXX11
1526template <size_t I>
1527struct Tag {};
1528
1529struct PairWithGet {
1530 int member_1;
1531 string member_2;
1532 using first_type = int;
1533 using second_type = string;
1534
1535 const int& GetImpl(Tag<0>) const { return member_1; }
1536 const string& GetImpl(Tag<1>) const { return member_2; }
1537};
1538template <size_t I>
1539auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag<I>())) {
1540 return value.GetImpl(Tag<I>());
1541}
1542TEST(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))));
1548
1549 std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
1550 EXPECT_THAT(v, Contains(Key(29)));
1551}
1552#endif // GTEST_LANG_CXX11
1553
1554TEST(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)));
1560}
1561
1562TEST(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))));
1569}
1570
1571TEST(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'));
1576
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)));
1582
1583 EXPECT_THAT(container, Contains(Key(1)));
1584 EXPECT_THAT(container, Not(Contains(Key(3))));
1585}
1586
1587TEST(PairTest, Typing) {
1588 // Test verifies the following type conversions can be compiled.
1591 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
1592
1595}
1596
1597TEST(PairTest, CanDescribeSelf) {
1599 EXPECT_EQ("has a first field that is equal to \"foo\""
1600 ", and has a second field that is equal to 42",
1601 Describe(m1));
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));
1610}
1611
1612TEST(PairTest, CanExplainMatchResultTo) {
1613 // If neither field matches, Pair() should explain about the first
1614 // field.
1616 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
1617 Explain(m, make_pair(-1, -2)));
1618
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)));
1623
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)));
1628
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)));
1634
1635 // If only the first match has an explanation, only this explanation should
1636 // be printed.
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)));
1641
1642 // If only the second match has an explanation, only this explanation should
1643 // be printed.
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)));
1648}
1649
1650TEST(PairTest, MatchesCorrectly) {
1651 pair<int, std::string> p(25, "foo");
1652
1653 // Both fields match.
1654 EXPECT_THAT(p, Pair(25, "foo"));
1655 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1656
1657 // 'first' doesnt' match, but 'second' matches.
1658 EXPECT_THAT(p, Not(Pair(42, "foo")));
1659 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1660
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"))));
1664
1665 // Neither field matches.
1666 EXPECT_THAT(p, Not(Pair(13, "bar")));
1667 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1668}
1669
1670TEST(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)));
1678}
1679
1680TEST(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, _))));
1689}
1690
1691#if GTEST_LANG_CXX11
1692TEST(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")));
1697
1698 std::vector<PairWithGet> v = {{11, "Foo"}, {29, "gMockIsBestMock"}};
1699 EXPECT_THAT(v, ElementsAre(Pair(11, string("Foo")), Pair(Ge(10), Not(""))));
1700}
1701#endif // GTEST_LANG_CXX11
1702
1703// Tests StartsWith(s).
1704
1705TEST(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));
1710
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"));
1717}
1718
1719TEST(StartsWithTest, CanDescribeSelf) {
1721 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1722}
1723
1724// Tests EndsWith(s).
1725
1726TEST(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));
1731
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 "));
1738
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
1747
1748#if GTEST_HAS_ABSL
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
1756}
1757
1758TEST(EndsWithTest, CanDescribeSelf) {
1760 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1761}
1762
1763// Tests MatchesRegex().
1764
1765TEST(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));
1770
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"));
1775
1776#if GTEST_HAS_ABSL
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()));
1785 EXPECT_FALSE(m4.Matches(absl::string_view()));
1786#endif // GTEST_HAS_ABSL
1787}
1788
1789TEST(MatchesRegexTest, CanDescribeSelf) {
1790 Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*"));
1791 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1792
1793 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1794 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
1795
1796#if GTEST_HAS_ABSL
1798 EXPECT_EQ("matches regular expression \"0.*\"", Describe(m3));
1799#endif // GTEST_HAS_ABSL
1800}
1801
1802// Tests ContainsRegex().
1803
1804TEST(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));
1809
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"));
1814
1815#if GTEST_HAS_ABSL
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()));
1824 EXPECT_FALSE(m4.Matches(absl::string_view()));
1825#endif // GTEST_HAS_ABSL
1826}
1827
1828TEST(ContainsRegexTest, CanDescribeSelf) {
1830 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1831
1832 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1833 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
1834
1835#if GTEST_HAS_ABSL
1837 EXPECT_EQ("contains regular expression \"0.*\"", Describe(m3));
1838#endif // GTEST_HAS_ABSL
1839}
1840
1841// Tests for wide strings.
1842#if GTEST_HAS_STD_WSTRING
1843TEST(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));
1848
1850 EXPECT_TRUE(m2.Matches(L"Hello"));
1851 EXPECT_FALSE(m2.Matches(L"Hi"));
1852
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"));
1856
1857 ::std::wstring str(L"01204500800");
1858 str[3] = L'\0';
1860 EXPECT_TRUE(m4.Matches(str));
1861 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1863 EXPECT_TRUE(m5.Matches(str));
1864}
1865
1866TEST(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\"",
1869 Describe(m));
1870
1871 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1872 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1873 Describe(m2));
1874
1875 ::std::wstring str(L"01204500800");
1876 str[3] = L'\0';
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));
1882}
1883
1884TEST(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"));
1889
1890 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1891 EXPECT_TRUE(m2.Matches(L"hello"));
1892 EXPECT_FALSE(m2.Matches(L"Hello"));
1893}
1894
1895TEST(StdWideStrNeTest, CanDescribeSelf) {
1896 Matcher<const wchar_t*> m = StrNe(L"Hi");
1897 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
1898}
1899
1900TEST(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));
1906
1907 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1908 EXPECT_TRUE(m2.Matches(L"hello"));
1909 EXPECT_FALSE(m2.Matches(L"Hi"));
1910}
1911
1912TEST(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')));
1917
1918 str1[3] = str2[3] = L'\0';
1919 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1920 EXPECT_TRUE(m1.Matches(str2));
1921
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));
1927
1928 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1929 EXPECT_TRUE(m3.Matches(str2));
1930
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)));
1935}
1936
1937TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1938 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1939 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1940}
1941
1942TEST(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"));
1948
1949 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1950 EXPECT_TRUE(m2.Matches(L""));
1951 EXPECT_FALSE(m2.Matches(L"Hello"));
1952}
1953
1954TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1955 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
1956 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
1957}
1958
1959// Tests that HasSubstr() works for matching wstring-typed values.
1960TEST(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")));
1964
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")));
1968}
1969
1970// Tests that HasSubstr() works for matching C-wide-string-typed values.
1971TEST(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));
1976
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));
1981}
1982
1983// Tests that HasSubstr(s) describes itself properly.
1984TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1985 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1986 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1987}
1988
1989// Tests StartsWith(s).
1990
1991TEST(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));
1996
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"));
2003}
2004
2005TEST(StdWideStartsWithTest, CanDescribeSelf) {
2006 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
2007 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
2008}
2009
2010// Tests EndsWith(s).
2011
2012TEST(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));
2017
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 "));
2024}
2025
2026TEST(StdWideEndsWithTest, CanDescribeSelf) {
2027 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
2028 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
2029}
2030
2031#endif // GTEST_HAS_STD_WSTRING
2032
2033#if GTEST_HAS_GLOBAL_WSTRING
2034TEST(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));
2039
2040 Matcher<const ::wstring&> m2 = StrEq(L"Hello");
2041 EXPECT_TRUE(m2.Matches(L"Hello"));
2042 EXPECT_FALSE(m2.Matches(L"Hi"));
2043
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"));
2047
2048 ::wstring str(L"01204500800");
2049 str[3] = L'\0';
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));
2055}
2056
2057TEST(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\"",
2060 Describe(m));
2061
2062 Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
2063 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
2064 Describe(m2));
2065
2066 ::wstring str(L"01204500800");
2067 str[3] = L'\0';
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));
2073}
2074
2075TEST(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"));
2080
2081 Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
2082 EXPECT_TRUE(m2.Matches(L"hello"));
2083 EXPECT_FALSE(m2.Matches(L"Hello"));
2084}
2085
2086TEST(GlobalWideStrNeTest, CanDescribeSelf) {
2087 Matcher<const wchar_t*> m = StrNe(L"Hi");
2088 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
2089}
2090
2091TEST(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));
2097
2098 Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
2099 EXPECT_TRUE(m2.Matches(L"hello"));
2100 EXPECT_FALSE(m2.Matches(L"Hi"));
2101}
2102
2103TEST(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')));
2108
2109 str1[3] = str2[3] = L'\0';
2110 Matcher<const ::wstring&> m1 = StrCaseEq(str1);
2111 EXPECT_TRUE(m1.Matches(str2));
2112
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));
2118
2119 Matcher<const ::wstring&> m3 = StrCaseEq(str1);
2120 EXPECT_TRUE(m3.Matches(str2));
2121
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)));
2126}
2127
2128TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
2129 Matcher< ::wstring> m = StrCaseEq(L"Hi");
2130 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
2131}
2132
2133TEST(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"));
2139
2140 Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
2141 EXPECT_TRUE(m2.Matches(L""));
2142 EXPECT_FALSE(m2.Matches(L"Hello"));
2143}
2144
2145TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
2146 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
2147 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
2148}
2149
2150// Tests that HasSubstr() works for matching wstring-typed values.
2151TEST(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")));
2155
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")));
2159}
2160
2161// Tests that HasSubstr() works for matching C-wide-string-typed values.
2162TEST(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));
2167
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));
2172}
2173
2174// Tests that HasSubstr(s) describes itself properly.
2175TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
2176 Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
2177 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
2178}
2179
2180// Tests StartsWith(s).
2181
2182TEST(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));
2187
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"));
2194}
2195
2196TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
2197 Matcher<const ::wstring> m = StartsWith(L"Hi");
2198 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
2199}
2200
2201// Tests EndsWith(s).
2202
2203TEST(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));
2208
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 "));
2215}
2216
2217TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
2218 Matcher<const ::wstring> m = EndsWith(L"Hi");
2219 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
2220}
2221
2222#endif // GTEST_HAS_GLOBAL_WSTRING
2223
2224
2225typedef ::testing::tuple<long, int> Tuple2; // NOLINT
2226
2227// Tests that Eq() matches a 2-tuple where the first field == the
2228// second field.
2229TEST(Eq2Test, MatchesEqualArguments) {
2231 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2232 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
2233}
2234
2235// Tests that Eq() describes itself properly.
2236TEST(Eq2Test, CanDescribeSelf) {
2238 EXPECT_EQ("are an equal pair", Describe(m));
2239}
2240
2241// Tests that Ge() matches a 2-tuple where the first field >= the
2242// second field.
2243TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
2245 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2246 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2247 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
2248}
2249
2250// Tests that Ge() describes itself properly.
2251TEST(Ge2Test, CanDescribeSelf) {
2253 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
2254}
2255
2256// Tests that Gt() matches a 2-tuple where the first field > the
2257// second field.
2258TEST(Gt2Test, MatchesGreaterThanArguments) {
2260 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2261 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2262 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
2263}
2264
2265// Tests that Gt() describes itself properly.
2266TEST(Gt2Test, CanDescribeSelf) {
2268 EXPECT_EQ("are a pair where the first > the second", Describe(m));
2269}
2270
2271// Tests that Le() matches a 2-tuple where the first field <= the
2272// second field.
2273TEST(Le2Test, MatchesLessThanOrEqualArguments) {
2275 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2276 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
2277 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
2278}
2279
2280// Tests that Le() describes itself properly.
2281TEST(Le2Test, CanDescribeSelf) {
2283 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
2284}
2285
2286// Tests that Lt() matches a 2-tuple where the first field < the
2287// second field.
2288TEST(Lt2Test, MatchesLessThanArguments) {
2290 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2291 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2292 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
2293}
2294
2295// Tests that Lt() describes itself properly.
2296TEST(Lt2Test, CanDescribeSelf) {
2298 EXPECT_EQ("are a pair where the first < the second", Describe(m));
2299}
2300
2301// Tests that Ne() matches a 2-tuple where the first field != the
2302// second field.
2303TEST(Ne2Test, MatchesUnequalArguments) {
2305 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2306 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2307 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2308}
2309
2310// Tests that Ne() describes itself properly.
2311TEST(Ne2Test, CanDescribeSelf) {
2313 EXPECT_EQ("are an unequal pair", Describe(m));
2314}
2315
2316// Tests that FloatEq() matches a 2-tuple where
2317// FloatEq(first field) matches the second field.
2318TEST(FloatEq2Test, MatchesEqualArguments) {
2319 typedef ::testing::tuple<float, float> Tpl;
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)));
2324}
2325
2326// Tests that FloatEq() describes itself properly.
2327TEST(FloatEq2Test, CanDescribeSelf) {
2329 EXPECT_EQ("are an almost-equal pair", Describe(m));
2330}
2331
2332// Tests that NanSensitiveFloatEq() matches a 2-tuple where
2333// NanSensitiveFloatEq(first field) matches the second field.
2334TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) {
2335 typedef ::testing::tuple<float, float> Tpl;
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)));
2343}
2344
2345// Tests that NanSensitiveFloatEq() describes itself properly.
2346TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) {
2348 EXPECT_EQ("are an almost-equal pair", Describe(m));
2349}
2350
2351// Tests that DoubleEq() matches a 2-tuple where
2352// DoubleEq(first field) matches the second field.
2353TEST(DoubleEq2Test, MatchesEqualArguments) {
2354 typedef ::testing::tuple<double, double> Tpl;
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)));
2359}
2360
2361// Tests that DoubleEq() describes itself properly.
2362TEST(DoubleEq2Test, CanDescribeSelf) {
2364 EXPECT_EQ("are an almost-equal pair", Describe(m));
2365}
2366
2367// Tests that NanSensitiveDoubleEq() matches a 2-tuple where
2368// NanSensitiveDoubleEq(first field) matches the second field.
2369TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) {
2370 typedef ::testing::tuple<double, double> Tpl;
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)));
2378}
2379
2380// Tests that DoubleEq() describes itself properly.
2381TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) {
2383 EXPECT_EQ("are an almost-equal pair", Describe(m));
2384}
2385
2386// Tests that FloatEq() matches a 2-tuple where
2387// FloatNear(first field, max_abs_error) matches the second field.
2388TEST(FloatNear2Test, MatchesEqualArguments) {
2389 typedef ::testing::tuple<float, float> Tpl;
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)));
2394}
2395
2396// Tests that FloatNear() describes itself properly.
2397TEST(FloatNear2Test, CanDescribeSelf) {
2399 EXPECT_EQ("are an almost-equal pair", Describe(m));
2400}
2401
2402// Tests that NanSensitiveFloatNear() matches a 2-tuple where
2403// NanSensitiveFloatNear(first field) matches the second field.
2404TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) {
2405 typedef ::testing::tuple<float, float> Tpl;
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)));
2414}
2415
2416// Tests that NanSensitiveFloatNear() describes itself properly.
2417TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) {
2420 EXPECT_EQ("are an almost-equal pair", Describe(m));
2421}
2422
2423// Tests that FloatEq() matches a 2-tuple where
2424// DoubleNear(first field, max_abs_error) matches the second field.
2425TEST(DoubleNear2Test, MatchesEqualArguments) {
2426 typedef ::testing::tuple<double, double> Tpl;
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)));
2431}
2432
2433// Tests that DoubleNear() describes itself properly.
2434TEST(DoubleNear2Test, CanDescribeSelf) {
2436 EXPECT_EQ("are an almost-equal pair", Describe(m));
2437}
2438
2439// Tests that NanSensitiveDoubleNear() matches a 2-tuple where
2440// NanSensitiveDoubleNear(first field) matches the second field.
2441TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) {
2442 typedef ::testing::tuple<double, double> Tpl;
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)));
2451}
2452
2453// Tests that NanSensitiveDoubleNear() describes itself properly.
2454TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) {
2457 EXPECT_EQ("are an almost-equal pair", Describe(m));
2458}
2459
2460// Tests that Not(m) matches any value that doesn't match m.
2461TEST(NotTest, NegatesMatcher) {
2462 Matcher<int> m;
2463 m = Not(Eq(2));
2464 EXPECT_TRUE(m.Matches(3));
2465 EXPECT_FALSE(m.Matches(2));
2466}
2467
2468// Tests that Not(m) describes itself properly.
2469TEST(NotTest, CanDescribeSelf) {
2470 Matcher<int> m = Not(Eq(5));
2471 EXPECT_EQ("isn't equal to 5", Describe(m));
2472}
2473
2474// Tests that monomorphic matchers are safely cast by the Not matcher.
2475TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2476 // greater_than_5 is a monomorphic matcher.
2477 Matcher<int> greater_than_5 = Gt(5);
2478
2479 Matcher<const int&> m = Not(greater_than_5);
2480 Matcher<int&> m2 = Not(greater_than_5);
2481 Matcher<int&> m3 = Not(m);
2482}
2483
2484// Helper to allow easy testing of AllOf matchers with num parameters.
2485void AllOfMatches(int num, const Matcher<int>& m) {
2487 EXPECT_TRUE(m.Matches(0));
2488 for (int i = 1; i <= num; ++i) {
2489 EXPECT_FALSE(m.Matches(i));
2490 }
2491 EXPECT_TRUE(m.Matches(num + 1));
2492}
2493
2494// Tests that AllOf(m1, ..., mn) matches any value that matches all of
2495// the given matchers.
2496TEST(AllOfTest, MatchesWhenAllMatch) {
2497 Matcher<int> m;
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));
2503
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));
2509
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));
2516
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));
2521
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),
2533 Ne(8)));
2534 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2535 Ne(8), Ne(9)));
2536 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2537 Ne(9), Ne(10)));
2538}
2539
2540#if GTEST_LANG_CXX11
2541// Tests the variadic version of the AllOfMatcher.
2542TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
2543 // Make sure AllOf is defined in the right namespace and does not depend on
2544 // ADL.
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),
2557 Ne(50)));
2558}
2559
2560#endif // GTEST_LANG_CXX11
2561
2562// Tests that AllOf(m1, ..., mn) describes itself properly.
2563TEST(AllOfTest, CanDescribeSelf) {
2564 Matcher<int> m;
2565 m = AllOf(Le(2), Ge(1));
2566 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
2567
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))",
2572 Describe(m));
2573
2574
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))",
2580 Describe(m));
2581
2582
2583 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2584 EXPECT_EQ("((is >= 0) and "
2585 "(is < 10)) and "
2586 "((isn't equal to 3) and "
2587 "((isn't equal to 5) and "
2588 "(isn't equal to 7)))",
2589 Describe(m));
2590}
2591
2592// Tests that AllOf(m1, ..., mn) describes its negation properly.
2593TEST(AllOfTest, CanDescribeNegation) {
2594 Matcher<int> m;
2595 m = AllOf(Le(2), Ge(1));
2596 EXPECT_EQ("(isn't <= 2) or "
2597 "(isn't >= 1)",
2598 DescribeNegation(m));
2599
2600 m = AllOf(Gt(0), Ne(1), Ne(2));
2601 EXPECT_EQ("(isn't > 0) or "
2602 "((is equal to 1) or "
2603 "(is equal to 2))",
2604 DescribeNegation(m));
2605
2606
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 "
2611 "(is equal to 3))",
2612 DescribeNegation(m));
2613
2614
2615 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2616 EXPECT_EQ("((isn't >= 0) or "
2617 "(isn't < 10)) or "
2618 "((is equal to 3) or "
2619 "((is equal to 5) or "
2620 "(is equal to 7)))",
2621 DescribeNegation(m));
2622}
2623
2624// Tests that monomorphic matchers are safely cast by the AllOf matcher.
2625TEST(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);
2629
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);
2633
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);
2637}
2638
2639TEST(AllOfTest, ExplainsResult) {
2640 Matcher<int> m;
2641
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));
2647
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",
2651 Explain(m, 30));
2652
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",
2657 Explain(m, 25));
2658
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",
2663 Explain(m, 40));
2664
2665 // Failed match. The first matcher, which failed, needs to
2666 // explain.
2667 m = AllOf(GreaterThan(10), GreaterThan(20));
2668 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2669
2670 // Failed match. The second matcher, which failed, needs to
2671 // explain. Since it doesn't given an explanation, nothing is
2672 // printed.
2673 m = AllOf(GreaterThan(10), Lt(30));
2674 EXPECT_EQ("", Explain(m, 40));
2675
2676 // Failed match. The second matcher, which failed, needs to
2677 // explain.
2678 m = AllOf(GreaterThan(10), GreaterThan(20));
2679 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2680}
2681
2682// Helper to allow easy testing of AnyOf matchers with num parameters.
2683void AnyOfMatches(int num, const Matcher<int>& m) {
2685 EXPECT_FALSE(m.Matches(0));
2686 for (int i = 1; i <= num; ++i) {
2687 EXPECT_TRUE(m.Matches(i));
2688 }
2689 EXPECT_FALSE(m.Matches(num + 1));
2690}
2691
2692// Tests that AnyOf(m1, ..., mn) matches any value that matches at
2693// least one of the given matchers.
2694TEST(AnyOfTest, MatchesWhenAnyMatches) {
2695 Matcher<int> m;
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));
2700
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));
2706
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));
2713
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));
2719
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));
2733}
2734
2735#if GTEST_LANG_CXX11
2736// Tests the variadic version of the AnyOfMatcher.
2737TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2738 // Also make sure AnyOf is defined in the right namespace and does not depend
2739 // on ADL.
2740 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2741
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));
2749}
2750
2751// Tests the variadic version of the ElementsAreMatcher
2752TEST(ElementsAreTest, HugeMatcher) {
2753 vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
2754
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)));
2758}
2759
2760// Tests the variadic version of the UnorderedElementsAreMatcher
2761TEST(ElementsAreTest, HugeMatcherStr) {
2762 vector<string> test_vector{
2763 "literal_string", "", "", "", "", "", "", "", "", "", "", ""};
2764
2765 EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string", _, _, _, _, _,
2766 _, _, _, _, _, _));
2767}
2768
2769// Tests the variadic version of the UnorderedElementsAreMatcher
2770TEST(ElementsAreTest, HugeMatcherUnordered) {
2771 vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};
2772
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)));
2776}
2777
2778#endif // GTEST_LANG_CXX11
2779
2780// Tests that AnyOf(m1, ..., mn) describes itself properly.
2781TEST(AnyOfTest, CanDescribeSelf) {
2782 Matcher<int> m;
2783 m = AnyOf(Le(1), Ge(3));
2784 EXPECT_EQ("(is <= 1) or (is >= 3)",
2785 Describe(m));
2786
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))",
2790 Describe(m));
2791
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 "
2796 "(is equal to 3))",
2797 Describe(m));
2798
2799 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2800 EXPECT_EQ("((is <= 0) or "
2801 "(is > 10)) or "
2802 "((is equal to 3) or "
2803 "((is equal to 5) or "
2804 "(is equal to 7)))",
2805 Describe(m));
2806}
2807
2808// Tests that AnyOf(m1, ..., mn) describes its negation properly.
2809TEST(AnyOfTest, CanDescribeNegation) {
2810 Matcher<int> m;
2811 m = AnyOf(Le(1), Ge(3));
2812 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2813 DescribeNegation(m));
2814
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));
2819
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));
2826
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));
2834}
2835
2836// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2837TEST(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);
2841
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);
2845
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);
2849}
2850
2851TEST(AnyOfTest, ExplainsResult) {
2852 Matcher<int> m;
2853
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));
2859
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",
2863 Explain(m, 5));
2864
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",
2869 Explain(m, 5));
2870
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",
2875 Explain(m, 5));
2876
2877 // Successful match. The first matcher, which succeeded, needs to
2878 // explain.
2879 m = AnyOf(GreaterThan(10), GreaterThan(20));
2880 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2881
2882 // Successful match. The second matcher, which succeeded, needs to
2883 // explain. Since it doesn't given an explanation, nothing is
2884 // printed.
2885 m = AnyOf(GreaterThan(10), Lt(30));
2886 EXPECT_EQ("", Explain(m, 0));
2887
2888 // Successful match. The second matcher, which succeeded, needs to
2889 // explain.
2890 m = AnyOf(GreaterThan(30), GreaterThan(20));
2891 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2892}
2893
2894// The following predicate function and predicate functor are for
2895// testing the Truly(predicate) matcher.
2896
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.
2901int IsPositive(double x) {
2902 return x > 0 ? 1 : 0;
2903}
2904
2905// This functor returns true if the input is greater than the given
2906// number.
2908 public:
2909 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2910
2911 bool operator()(int n) const { return n > threshold_; }
2912
2913 private:
2914 int threshold_;
2915};
2916
2917// For testing Truly().
2918const int foo = 0;
2919
2920// This predicate returns true iff the argument references foo and has
2921// a zero value.
2922bool ReferencesFooAndIsZero(const int& n) {
2923 return (&n == &foo) && (n == 0);
2924}
2925
2926// Tests that Truly(predicate) matches what satisfies the given
2927// predicate.
2928TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2930 EXPECT_TRUE(m.Matches(2.0));
2931 EXPECT_FALSE(m.Matches(-1.5));
2932}
2933
2934// Tests that Truly(predicate_functor) works too.
2935TEST(TrulyTest, CanBeUsedWithFunctor) {
2937 EXPECT_TRUE(m.Matches(6));
2938 EXPECT_FALSE(m.Matches(4));
2939}
2940
2941// A class that can be implicitly converted to bool.
2943 public:
2944 explicit ConvertibleToBool(int number) : number_(number) {}
2945 operator bool() const { return number_ != 0; }
2946
2947 private:
2948 int number_;
2949};
2950
2952 return ConvertibleToBool(number);
2953}
2954
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
2957// operator!().
2958TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2959 Matcher<int> m = Truly(IsNotZero);
2960 EXPECT_TRUE(m.Matches(1));
2961 EXPECT_FALSE(m.Matches(0));
2962}
2963
2964// Tests that Truly(predicate) can describe itself properly.
2965TEST(TrulyTest, CanDescribeSelf) {
2967 EXPECT_EQ("satisfies the given predicate",
2968 Describe(m));
2969}
2970
2971// Tests that Truly(predicate) works when the matcher takes its
2972// argument by reference.
2973TEST(TrulyTest, WorksForByRefArguments) {
2976 int n = 0;
2977 EXPECT_FALSE(m.Matches(n));
2978}
2979
2980// Tests that Matches(m) is a predicate satisfied by whatever that
2981// matches matcher m.
2982TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2983 EXPECT_TRUE(Matches(Ge(0))(1));
2984 EXPECT_FALSE(Matches(Eq('a'))('b'));
2985}
2986
2987// Tests that Matches(m) works when the matcher takes its argument by
2988// reference.
2989TEST(MatchesTest, WorksOnByRefArguments) {
2990 int m = 0, n = 0;
2991 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2992 EXPECT_FALSE(Matches(Ref(m))(n));
2993}
2994
2995// Tests that a Matcher on non-reference type can be used in
2996// Matches().
2997TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
2998 Matcher<int> eq5 = Eq(5);
2999 EXPECT_TRUE(Matches(eq5)(5));
3000 EXPECT_FALSE(Matches(eq5)(2));
3001}
3002
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().
3006TEST(ValueTest, WorksWithPolymorphicMatcher) {
3007 EXPECT_TRUE(Value("hi", StartsWith("h")));
3008 EXPECT_FALSE(Value(5, Gt(10)));
3009}
3010
3011TEST(ValueTest, WorksWithMonomorphicMatcher) {
3012 const Matcher<int> is_zero = Eq(0);
3013 EXPECT_TRUE(Value(0, is_zero));
3014 EXPECT_FALSE(Value('a', is_zero));
3015
3016 int n = 0;
3017 const Matcher<const int&> ref_n = Ref(n);
3018 EXPECT_TRUE(Value(n, ref_n));
3019 EXPECT_FALSE(Value(1, ref_n));
3020}
3021
3022TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
3023 StringMatchResultListener listener1;
3025 EXPECT_EQ("% 2 == 0", listener1.str());
3026
3027 StringMatchResultListener listener2;
3028 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
3029 EXPECT_EQ("", listener2.str());
3030}
3031
3032TEST(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());
3037
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());
3042}
3043
3044MATCHER_P(Really, inner_matcher, "") {
3045 return ExplainMatchResult(inner_matcher, arg, result_listener);
3046}
3047
3048TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
3049 EXPECT_THAT(0, Really(Eq(0)));
3050}
3051
3052TEST(DescribeMatcherTest, WorksWithValue) {
3053 EXPECT_EQ("is equal to 42", DescribeMatcher<int>(42));
3054 EXPECT_EQ("isn't equal to 42", DescribeMatcher<int>(42, true));
3055}
3056
3057TEST(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));
3061}
3062
3063TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) {
3066}
3067
3068TEST(AllArgsTest, WorksForTuple) {
3069 EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
3070 EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
3071}
3072
3073TEST(AllArgsTest, WorksForNonTuple) {
3074 EXPECT_THAT(42, AllArgs(Gt(0)));
3075 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
3076}
3077
3079 public:
3081
3082 MOCK_METHOD2(Helper, int(char x, int y));
3083
3084 private:
3086};
3087
3088TEST(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));
3097
3098 EXPECT_EQ(1, helper.Helper('\1', 2));
3099 EXPECT_EQ(2, helper.Helper('a', 1));
3100}
3101
3103 public:
3105
3106 MOCK_METHOD0(NoArgs, int());
3107
3108 MOCK_METHOD1(OneArg, int(int y));
3109
3110 MOCK_METHOD2(TwoArgs, int(char x, int y));
3111
3112 MOCK_METHOD1(Overloaded, int(char x));
3113 MOCK_METHOD2(Overloaded, int(char x, int y));
3114
3115 private:
3117};
3118
3119TEST(AllArgsTest, WorksWithoutMatchers) {
3121
3122 ON_CALL(helper, NoArgs).WillByDefault(Return(10));
3123 ON_CALL(helper, OneArg).WillByDefault(Return(20));
3124 ON_CALL(helper, TwoArgs).WillByDefault(Return(30));
3125
3126 EXPECT_EQ(10, helper.NoArgs());
3127 EXPECT_EQ(20, helper.OneArg(1));
3128 EXPECT_EQ(30, helper.TwoArgs('\1', 2));
3129
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);
3134
3135 EXPECT_EQ(10, helper.NoArgs());
3136 EXPECT_EQ(100, helper.OneArg(1));
3137 EXPECT_EQ(200, helper.OneArg(17));
3138}
3139
3140// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
3141// matches the matcher.
3142TEST(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"));
3147}
3148
3149// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
3150// doesn't match the matcher.
3151TEST(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
3155 n = 5;
3156
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
3161 // resolved.
3163 "Value of: n\n"
3164 "Expected: is > 10\n"
3165 " Actual: 5" + OfType("unsigned short"));
3166 n = 0;
3169 "Value of: n\n"
3170 "Expected: (is <= 7) and (is >= 5)\n"
3171 " Actual: 0" + OfType("unsigned short"));
3172}
3173
3174// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
3175// has a reference type.
3176TEST(MatcherAssertionTest, WorksForByRefArguments) {
3177 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
3178 // reference auto variables.
3179 static int n;
3180 n = 0;
3181 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
3183 "Value of: n\n"
3184 "Expected: does not reference the variable @");
3185 // Tests the "Actual" part.
3187 "Actual: 0" + OfType("int") + ", which is located @");
3188}
3189
3190#if !GTEST_OS_SYMBIAN
3191// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
3192// monomorphic.
3193
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.
3204TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
3205 Matcher<const char*> starts_with_he = StartsWith("he");
3206 ASSERT_THAT("hello", starts_with_he);
3207
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),
3212 "Value of: bad\n"
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),
3217 "Value of: 5\n"
3218 "Expected: is > 5\n"
3219 " Actual: 5" + OfType("int"));
3220}
3221#endif // !GTEST_OS_SYMBIAN
3222
3223// Tests floating-point matchers.
3224template <typename RawType>
3226 protected:
3228 typedef typename Floating::Bits Bits;
3229
3231 : max_ulps_(Floating::kMaxUlps),
3232 zero_bits_(Floating(0).bits()),
3233 one_bits_(Floating(1).bits()),
3234 infinity_bits_(Floating(Floating::Infinity()).bits()),
3236 Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
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_)),
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)) {
3251 }
3252
3253 void TestSize() {
3254 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
3255 }
3256
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));
3265 EXPECT_FALSE(m1.Matches(1.0));
3266
3267 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
3269
3270 Matcher<RawType> m3 = matcher_maker(1.0);
3273
3274 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
3275 EXPECT_FALSE(m3.Matches(0.0));
3276
3277 Matcher<RawType> m4 = matcher_maker(-infinity_);
3279
3280 Matcher<RawType> m5 = matcher_maker(infinity_);
3282
3283 // This is interesting as the representations of infinity_ and nan1_
3284 // are only 1 DLP apart.
3286
3287 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
3288 // some cases.
3289 Matcher<const RawType&> m6 = matcher_maker(0.0);
3290 EXPECT_TRUE(m6.Matches(-0.0));
3292 EXPECT_FALSE(m6.Matches(1.0));
3293
3294 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
3295 // cases.
3296 Matcher<RawType&> m7 = matcher_maker(0.0);
3297 RawType x = 0.0;
3298 EXPECT_TRUE(m7.Matches(x));
3299 x = 0.01f;
3300 EXPECT_FALSE(m7.Matches(x));
3301 }
3302
3303 // Pre-calculated numbers to be used by the tests.
3304
3306
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.
3310
3311 // Some numbers close to 0.0.
3315
3316 // Some numbers close to 1.0.
3317 const RawType close_to_one_;
3318 const RawType further_from_one_;
3319
3320 // Some numbers close to +infinity.
3321 const RawType infinity_;
3322 const RawType close_to_infinity_;
3324
3325 // Maximum representable value that's not infinity.
3326 const RawType max_;
3327
3328 // Some NaNs.
3329 const RawType nan1_;
3330 const RawType nan2_;
3331};
3332
3333// Tests floating-point matchers with fixed epsilons.
3334template <typename RawType>
3336 protected:
3338
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.
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));
3349 EXPECT_FALSE(m1.Matches(1.0));
3350
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));
3358
3359 // Check that inf matches inf, regardless of the of the specified max
3360 // absolute error.
3361 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
3365
3366 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
3370
3371 // Test various overflow scenarios.
3375
3379
3380 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
3383
3384 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
3387
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(
3393
3394 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
3395 // some cases.
3396 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
3397 EXPECT_TRUE(m10.Matches(-0.0));
3400
3401 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
3402 // cases.
3403 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
3404 RawType x = 0.0;
3405 EXPECT_TRUE(m11.Matches(x));
3406 x = 1.0f;
3407 EXPECT_TRUE(m11.Matches(x));
3408 x = -1.0f;
3409 EXPECT_TRUE(m11.Matches(x));
3410 x = 1.1f;
3411 EXPECT_FALSE(m11.Matches(x));
3412 x = -1.1f;
3413 EXPECT_FALSE(m11.Matches(x));
3414 }
3415};
3416
3417// Instantiate FloatingPointTest for testing floats.
3419
3420TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
3421 TestMatches(&FloatEq);
3422}
3423
3424TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
3425 TestMatches(&NanSensitiveFloatEq);
3426}
3427
3428TEST_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));
3434}
3435
3436TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
3437 // NanSensitiveFloatEq will match NaN.
3439 EXPECT_TRUE(m.Matches(nan1_));
3440 EXPECT_TRUE(m.Matches(nan2_));
3441 EXPECT_FALSE(m.Matches(1.0));
3442}
3443
3444TEST_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));
3448
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));
3452
3453 Matcher<float> m3 = FloatEq(nan1_);
3454 EXPECT_EQ("never matches", Describe(m3));
3455 EXPECT_EQ("is anything", DescribeNegation(m3));
3456}
3457
3458TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
3460 EXPECT_EQ("is approximately 2", Describe(m1));
3461 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3462
3464 EXPECT_EQ("is approximately 0.5", Describe(m2));
3465 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3466
3468 EXPECT_EQ("is NaN", Describe(m3));
3469 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3470}
3471
3472// Instantiate FloatingPointTest for testing floats with a user-specified
3473// max absolute error.
3475
3476TEST_F(FloatNearTest, FloatNearMatches) {
3477 TestNearMatches(&FloatNear);
3478}
3479
3480TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
3481 TestNearMatches(&NanSensitiveFloatNear);
3482}
3483
3484TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
3485 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
3486 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3487 EXPECT_EQ(
3488 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3489
3490 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
3491 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3492 EXPECT_EQ(
3493 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3494
3495 Matcher<float> m3 = FloatNear(nan1_, 0.0);
3496 EXPECT_EQ("never matches", Describe(m3));
3497 EXPECT_EQ("is anything", DescribeNegation(m3));
3498}
3499
3500TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
3501 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
3502 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3503 EXPECT_EQ(
3504 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3505
3506 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
3507 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3508 EXPECT_EQ(
3509 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3510
3511 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
3512 EXPECT_EQ("is NaN", Describe(m3));
3513 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3514}
3515
3516TEST_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));
3522}
3523
3524TEST_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));
3530}
3531
3532// Instantiate FloatingPointTest for testing doubles.
3534
3535TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
3536 TestMatches(&DoubleEq);
3537}
3538
3539TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
3540 TestMatches(&NanSensitiveDoubleEq);
3541}
3542
3543TEST_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));
3549}
3550
3551TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3552 // NanSensitiveDoubleEq will match NaN.
3554 EXPECT_TRUE(m.Matches(nan1_));
3555 EXPECT_TRUE(m.Matches(nan2_));
3556 EXPECT_FALSE(m.Matches(1.0));
3557}
3558
3559TEST_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));
3563
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));
3567
3568 Matcher<double> m3 = DoubleEq(nan1_);
3569 EXPECT_EQ("never matches", Describe(m3));
3570 EXPECT_EQ("is anything", DescribeNegation(m3));
3571}
3572
3573TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3575 EXPECT_EQ("is approximately 2", Describe(m1));
3576 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
3577
3579 EXPECT_EQ("is approximately 0.5", Describe(m2));
3580 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
3581
3583 EXPECT_EQ("is NaN", Describe(m3));
3584 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3585}
3586
3587// Instantiate FloatingPointTest for testing floats with a user-specified
3588// max absolute error.
3590
3591TEST_F(DoubleNearTest, DoubleNearMatches) {
3592 TestNearMatches(&DoubleNear);
3593}
3594
3595TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3596 TestNearMatches(&NanSensitiveDoubleNear);
3597}
3598
3599TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3600 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3601 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3602 EXPECT_EQ(
3603 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3604
3605 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3606 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3607 EXPECT_EQ(
3608 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3609
3610 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3611 EXPECT_EQ("never matches", Describe(m3));
3612 EXPECT_EQ("is anything", DescribeNegation(m3));
3613}
3614
3615TEST_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));
3619
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 << "\".";
3627}
3628
3629TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3631 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3632 EXPECT_EQ(
3633 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3634
3636 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3637 EXPECT_EQ(
3638 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3639
3640 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3641 EXPECT_EQ("is NaN", Describe(m3));
3642 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3643}
3644
3645TEST_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));
3651}
3652
3653TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3654 // NanSensitiveDoubleNear will match NaN.
3656 EXPECT_TRUE(m.Matches(nan1_));
3657 EXPECT_TRUE(m.Matches(nan2_));
3658 EXPECT_FALSE(m.Matches(1.0));
3659}
3660
3661TEST(PointeeTest, RawPointer) {
3662 const Matcher<int*> m = Pointee(Ge(0));
3663
3664 int n = 1;
3665 EXPECT_TRUE(m.Matches(&n));
3666 n = -1;
3667 EXPECT_FALSE(m.Matches(&n));
3668 EXPECT_FALSE(m.Matches(NULL));
3669}
3670
3671TEST(PointeeTest, RawPointerToConst) {
3672 const Matcher<const double*> m = Pointee(Ge(0));
3673
3674 double x = 1;
3675 EXPECT_TRUE(m.Matches(&x));
3676 x = -1;
3677 EXPECT_FALSE(m.Matches(&x));
3678 EXPECT_FALSE(m.Matches(NULL));
3679}
3680
3681TEST(PointeeTest, ReferenceToConstRawPointer) {
3682 const Matcher<int* const &> m = Pointee(Ge(0));
3683
3684 int n = 1;
3685 EXPECT_TRUE(m.Matches(&n));
3686 n = -1;
3687 EXPECT_FALSE(m.Matches(&n));
3688 EXPECT_FALSE(m.Matches(NULL));
3689}
3690
3691TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3692 const Matcher<double* &> m = Pointee(Ge(0));
3693
3694 double x = 1.0;
3695 double* p = &x;
3696 EXPECT_TRUE(m.Matches(p));
3697 x = -1;
3699 p = NULL;
3701}
3702
3703MATCHER_P(FieldIIs, inner_matcher, "") {
3704 return ExplainMatchResult(inner_matcher, arg.i, result_listener);
3705}
3706
3707#if GTEST_HAS_RTTI
3708TEST(WhenDynamicCastToTest, SameType) {
3709 Derived derived;
3710 derived.i = 4;
3711
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)))));
3718}
3719
3720TEST(WhenDynamicCastToTest, WrongTypes) {
3721 Base base;
3722 Derived derived;
3723 OtherDerived other_derived;
3724
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()));
3734}
3735
3736TEST(WhenDynamicCastToTest, AlreadyNull) {
3737 // Already NULL.
3738 Base* as_base_ptr = NULL;
3739 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3740}
3741
3742struct AmbiguousCastTypes {
3743 class VirtualDerived : public virtual Base {};
3744 class DerivedSub1 : public VirtualDerived {};
3745 class DerivedSub2 : public VirtualDerived {};
3746 class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
3747};
3748
3749TEST(WhenDynamicCastToTest, AmbiguousCast) {
3750 AmbiguousCastTypes::DerivedSub1 sub1;
3751 AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
3752 // Multiply derived from Base. dynamic_cast<> returns NULL.
3753 Base* as_base_ptr =
3754 static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
3755 EXPECT_THAT(as_base_ptr,
3756 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
3757 as_base_ptr = &sub1;
3759 as_base_ptr,
3760 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
3761}
3762
3763TEST(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));
3770}
3771
3772TEST(WhenDynamicCastToTest, Explain) {
3773 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3774 Base* null = NULL;
3775 EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
3776 Derived derived;
3777 EXPECT_TRUE(matcher.Matches(&derived));
3778 EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
3779
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"));
3784}
3785
3786TEST(WhenDynamicCastToTest, GoodReference) {
3787 Derived derived;
3788 derived.i = 4;
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))));
3792}
3793
3794TEST(WhenDynamicCastToTest, BadReference) {
3795 Derived derived;
3796 Base& as_base_ref = derived;
3797 EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
3798}
3799#endif // GTEST_HAS_RTTI
3800
3801// Minimal const-propagating pointer.
3802template <typename T>
3804 public:
3806
3808 explicit ConstPropagatingPtr(T* t) : val_(t) {}
3809 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3810
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_; }
3816
3817 private:
3818 T* val_;
3819};
3820
3821TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3823 int three = 3;
3824 const ConstPropagatingPtr<int> co(&three);
3825 ConstPropagatingPtr<int> o(&three);
3826 EXPECT_TRUE(m.Matches(o));
3827 EXPECT_TRUE(m.Matches(co));
3828 *o = 6;
3829 EXPECT_FALSE(m.Matches(o));
3831}
3832
3833TEST(PointeeTest, NeverMatchesNull) {
3834 const Matcher<const char*> m = Pointee(_);
3835 EXPECT_FALSE(m.Matches(NULL));
3836}
3837
3838// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3839TEST(PointeeTest, MatchesAgainstAValue) {
3840 const Matcher<int*> m = Pointee(5);
3841
3842 int n = 5;
3843 EXPECT_TRUE(m.Matches(&n));
3844 n = -1;
3845 EXPECT_FALSE(m.Matches(&n));
3846 EXPECT_FALSE(m.Matches(NULL));
3847}
3848
3849TEST(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));
3854}
3855
3856TEST(PointeeTest, CanExplainMatchResult) {
3858
3859 EXPECT_EQ("", Explain(m, static_cast<const std::string*>(NULL)));
3860
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",
3864 Explain(m2, &n));
3865}
3866
3867TEST(PointeeTest, AlwaysExplainsPointee) {
3868 const Matcher<int*> m = Pointee(0);
3869 int n = 42;
3870 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
3871}
3872
3873// An uncopyable class.
3875 public:
3876 Uncopyable() : value_(-1) {}
3877 explicit Uncopyable(int a_value) : value_(a_value) {}
3878
3879 int value() const { return value_; }
3880 void set_value(int i) { value_ = i; }
3881
3882 private:
3883 int value_;
3885};
3886
3887// Returns true iff x.value() is positive.
3888bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3889
3890MATCHER_P(UncopyableIs, inner_matcher, "") {
3891 return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
3892}
3893
3894// A user-defined struct for testing Field().
3895struct AStruct {
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) {}
3899
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.
3904
3905 private:
3907};
3908
3909// A derived struct for testing Field().
3910struct DerivedStruct : public AStruct {
3911 char ch;
3912
3913 private:
3915};
3916
3917// Tests that Field(&Foo::field, ...) works when field is non-const.
3918TEST(FieldTest, WorksForNonConstField) {
3920 Matcher<AStruct> m_with_name = Field("x", &AStruct::x, Ge(0));
3921
3922 AStruct a;
3923 EXPECT_TRUE(m.Matches(a));
3924 EXPECT_TRUE(m_with_name.Matches(a));
3925 a.x = -1;
3927 EXPECT_FALSE(m_with_name.Matches(a));
3928}
3929
3930// Tests that Field(&Foo::field, ...) works when field is const.
3931TEST(FieldTest, WorksForConstField) {
3932 AStruct a;
3933
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));
3941 EXPECT_FALSE(m_with_name.Matches(a));
3942}
3943
3944// Tests that Field(&Foo::field, ...) works when field is not copyable.
3945TEST(FieldTest, WorksForUncopyableField) {
3946 AStruct a;
3947
3949 EXPECT_TRUE(m.Matches(a));
3952}
3953
3954// Tests that Field(&Foo::field, ...) works when field is a pointer.
3955TEST(FieldTest, WorksForPointerField) {
3956 // Matching against NULL.
3957 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
3958 AStruct a;
3959 EXPECT_TRUE(m.Matches(a));
3960 a.p = "hi";
3962
3963 // Matching a pointer that is not NULL.
3964 m = Field(&AStruct::p, StartsWith("hi"));
3965 a.p = "hill";
3966 EXPECT_TRUE(m.Matches(a));
3967 a.p = "hole";
3969}
3970
3971// Tests that Field() works when the object is passed by reference.
3972TEST(FieldTest, WorksForByRefArgument) {
3974
3975 AStruct a;
3976 EXPECT_TRUE(m.Matches(a));
3977 a.x = -1;
3979}
3980
3981// Tests that Field(&Foo::field, ...) works when the argument's type
3982// is a sub-type of Foo.
3983TEST(FieldTest, WorksForArgumentOfSubType) {
3984 // Note that the matcher expects DerivedStruct but we say AStruct
3985 // inside Field().
3987
3989 EXPECT_TRUE(m.Matches(d));
3990 d.x = -1;
3992}
3993
3994// Tests that Field(&Foo::field, m) works when field's type and m's
3995// argument type are compatible but not the same.
3996TEST(FieldTest, WorksForCompatibleMatcherType) {
3997 // The field is an int, but the inner matcher expects a signed char.
4000
4001 AStruct a;
4002 EXPECT_TRUE(m.Matches(a));
4003 a.x = -1;
4005}
4006
4007// Tests that Field() can describe itself.
4008TEST(FieldTest, CanDescribeSelf) {
4010
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));
4013}
4014
4015TEST(FieldTest, CanDescribeSelfWithFieldName) {
4016 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
4017
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));
4021}
4022
4023// Tests that Field() can explain the match result.
4024TEST(FieldTest, CanExplainMatchResult) {
4026
4027 AStruct a;
4028 a.x = 1;
4029 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
4030
4031 m = Field(&AStruct::x, GreaterThan(0));
4032 EXPECT_EQ(
4033 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
4034 Explain(m, a));
4035}
4036
4037TEST(FieldTest, CanExplainMatchResultWithFieldName) {
4038 Matcher<const AStruct&> m = Field("field_name", &AStruct::x, Ge(0));
4039
4040 AStruct a;
4041 a.x = 1;
4042 EXPECT_EQ("whose field `field_name` is 1" + OfType("int"), Explain(m, a));
4043
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",
4047 Explain(m, a));
4048}
4049
4050// Tests that Field() works when the argument is a pointer to const.
4051TEST(FieldForPointerTest, WorksForPointerToConst) {
4053
4054 AStruct a;
4055 EXPECT_TRUE(m.Matches(&a));
4056 a.x = -1;
4057 EXPECT_FALSE(m.Matches(&a));
4058}
4059
4060// Tests that Field() works when the argument is a pointer to non-const.
4061TEST(FieldForPointerTest, WorksForPointerToNonConst) {
4063
4064 AStruct a;
4065 EXPECT_TRUE(m.Matches(&a));
4066 a.x = -1;
4067 EXPECT_FALSE(m.Matches(&a));
4068}
4069
4070// Tests that Field() works when the argument is a reference to a const pointer.
4071TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
4073
4074 AStruct a;
4075 EXPECT_TRUE(m.Matches(&a));
4076 a.x = -1;
4077 EXPECT_FALSE(m.Matches(&a));
4078}
4079
4080// Tests that Field() does not match the NULL pointer.
4081TEST(FieldForPointerTest, DoesNotMatchNull) {
4083 EXPECT_FALSE(m.Matches(NULL));
4084}
4085
4086// Tests that Field(&Foo::field, ...) works when the argument's type
4087// is a sub-type of const Foo*.
4088TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
4089 // Note that the matcher expects DerivedStruct but we say AStruct
4090 // inside Field().
4092
4094 EXPECT_TRUE(m.Matches(&d));
4095 d.x = -1;
4096 EXPECT_FALSE(m.Matches(&d));
4097}
4098
4099// Tests that Field() can describe itself when used to match a pointer.
4100TEST(FieldForPointerTest, CanDescribeSelf) {
4102
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));
4105}
4106
4107TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) {
4108 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
4109
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));
4113}
4114
4115// Tests that Field() can explain the result of matching a pointer.
4116TEST(FieldForPointerTest, CanExplainMatchResult) {
4118
4119 AStruct a;
4120 a.x = 1;
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"),
4123 Explain(m, &a));
4124
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));
4128}
4129
4130TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) {
4131 Matcher<const AStruct*> m = Field("field_name", &AStruct::x, Ge(0));
4132
4133 AStruct a;
4134 a.x = 1;
4135 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
4136 EXPECT_EQ(
4137 "which points to an object whose field `field_name` is 1" + OfType("int"),
4138 Explain(m, &a));
4139
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",
4143 Explain(m, &a));
4144}
4145
4146// A user-defined class for testing Property().
4147class AClass {
4148 public:
4149 AClass() : n_(0) {}
4150
4151 // A getter that returns a non-reference.
4152 int n() const { return n_; }
4153
4154 void set_n(int new_n) { n_ = new_n; }
4155
4156 // A getter that returns a reference to const.
4157 const std::string& s() const { return s_; }
4158
4159#if GTEST_LANG_CXX11
4160 const std::string& s_ref() const & { return s_; }
4161#endif
4162
4163 void set_s(const std::string& new_s) { s_ = new_s; }
4164
4165 // A getter that returns a reference to non-const.
4166 double& x() const { return x_; }
4167
4168 private:
4169 int n_;
4170 std::string s_;
4171
4172 static double x_;
4173};
4174
4175double AClass::x_ = 0.0;
4176
4177// A derived class for testing Property().
4178class DerivedClass : public AClass {
4179 public:
4180 int k() const { return k_; }
4181 private:
4182 int k_;
4183};
4184
4185// Tests that Property(&Foo::property, ...) works when property()
4186// returns a non-reference.
4187TEST(PropertyTest, WorksForNonReferenceProperty) {
4189 Matcher<const AClass&> m_with_name = Property("n", &AClass::n, Ge(0));
4190
4191 AClass a;
4192 a.set_n(1);
4193 EXPECT_TRUE(m.Matches(a));
4194 EXPECT_TRUE(m_with_name.Matches(a));
4195
4196 a.set_n(-1);
4198 EXPECT_FALSE(m_with_name.Matches(a));
4199}
4200
4201// Tests that Property(&Foo::property, ...) works when property()
4202// returns a reference to const.
4203TEST(PropertyTest, WorksForReferenceToConstProperty) {
4205 Matcher<const AClass&> m_with_name =
4206 Property("s", &AClass::s, StartsWith("hi"));
4207
4208 AClass a;
4209 a.set_s("hill");
4210 EXPECT_TRUE(m.Matches(a));
4211 EXPECT_TRUE(m_with_name.Matches(a));
4212
4213 a.set_s("hole");
4215 EXPECT_FALSE(m_with_name.Matches(a));
4216}
4217
4218#if GTEST_LANG_CXX11
4219// Tests that Property(&Foo::property, ...) works when property() is
4220// ref-qualified.
4221TEST(PropertyTest, WorksForRefQualifiedProperty) {
4222 Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi"));
4223
4224 AClass a;
4225 a.set_s("hill");
4226 EXPECT_TRUE(m.Matches(a));
4227
4228 a.set_s("hole");
4230}
4231#endif
4232
4233// Tests that Property(&Foo::property, ...) works when property()
4234// returns a reference to non-const.
4235TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
4236 double x = 0.0;
4237 AClass a;
4238
4241
4242 m = Property(&AClass::x, Not(Ref(x)));
4243 EXPECT_TRUE(m.Matches(a));
4244}
4245
4246// Tests that Property(&Foo::property, ...) works when the argument is
4247// passed by value.
4248TEST(PropertyTest, WorksForByValueArgument) {
4250
4251 AClass a;
4252 a.set_s("hill");
4253 EXPECT_TRUE(m.Matches(a));
4254
4255 a.set_s("hole");
4257}
4258
4259// Tests that Property(&Foo::property, ...) works when the argument's
4260// type is a sub-type of Foo.
4261TEST(PropertyTest, WorksForArgumentOfSubType) {
4262 // The matcher expects a DerivedClass, but inside the Property() we
4263 // say AClass.
4265
4267 d.set_n(1);
4268 EXPECT_TRUE(m.Matches(d));
4269
4270 d.set_n(-1);
4272}
4273
4274// Tests that Property(&Foo::property, m) works when property()'s type
4275// and m's argument type are compatible but different.
4276TEST(PropertyTest, WorksForCompatibleMatcherType) {
4277 // n() returns an int but the inner matcher expects a signed char.
4280
4281 Matcher<const AClass&> m_with_name =
4283
4284 AClass a;
4285 EXPECT_TRUE(m.Matches(a));
4286 EXPECT_TRUE(m_with_name.Matches(a));
4287 a.set_n(-1);
4289 EXPECT_FALSE(m_with_name.Matches(a));
4290}
4291
4292// Tests that Property() can describe itself.
4293TEST(PropertyTest, CanDescribeSelf) {
4295
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));
4299}
4300
4301TEST(PropertyTest, CanDescribeSelfWithPropertyName) {
4302 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
4303
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));
4307}
4308
4309// Tests that Property() can explain the match result.
4310TEST(PropertyTest, CanExplainMatchResult) {
4312
4313 AClass a;
4314 a.set_n(1);
4315 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
4316
4317 m = Property(&AClass::n, GreaterThan(0));
4318 EXPECT_EQ(
4319 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
4320 Explain(m, a));
4321}
4322
4323TEST(PropertyTest, CanExplainMatchResultWithPropertyName) {
4324 Matcher<const AClass&> m = Property("fancy_name", &AClass::n, Ge(0));
4325
4326 AClass a;
4327 a.set_n(1);
4328 EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int"), Explain(m, a));
4329
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",
4333 Explain(m, a));
4334}
4335
4336// Tests that Property() works when the argument is a pointer to const.
4337TEST(PropertyForPointerTest, WorksForPointerToConst) {
4339
4340 AClass a;
4341 a.set_n(1);
4342 EXPECT_TRUE(m.Matches(&a));
4343
4344 a.set_n(-1);
4345 EXPECT_FALSE(m.Matches(&a));
4346}
4347
4348// Tests that Property() works when the argument is a pointer to non-const.
4349TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
4351
4352 AClass a;
4353 a.set_s("hill");
4354 EXPECT_TRUE(m.Matches(&a));
4355
4356 a.set_s("hole");
4357 EXPECT_FALSE(m.Matches(&a));
4358}
4359
4360// Tests that Property() works when the argument is a reference to a
4361// const pointer.
4362TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
4364
4365 AClass a;
4366 a.set_s("hill");
4367 EXPECT_TRUE(m.Matches(&a));
4368
4369 a.set_s("hole");
4370 EXPECT_FALSE(m.Matches(&a));
4371}
4372
4373// Tests that Property() does not match the NULL pointer.
4374TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
4376 EXPECT_FALSE(m.Matches(NULL));
4377}
4378
4379// Tests that Property(&Foo::property, ...) works when the argument's
4380// type is a sub-type of const Foo*.
4381TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
4382 // The matcher expects a DerivedClass, but inside the Property() we
4383 // say AClass.
4385
4387 d.set_n(1);
4388 EXPECT_TRUE(m.Matches(&d));
4389
4390 d.set_n(-1);
4391 EXPECT_FALSE(m.Matches(&d));
4392}
4393
4394// Tests that Property() can describe itself when used to match a pointer.
4395TEST(PropertyForPointerTest, CanDescribeSelf) {
4397
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));
4401}
4402
4403TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) {
4404 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
4405
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));
4409}
4410
4411// Tests that Property() can explain the result of matching a pointer.
4412TEST(PropertyForPointerTest, CanExplainMatchResult) {
4414
4415 AClass a;
4416 a.set_n(1);
4417 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
4418 EXPECT_EQ(
4419 "which points to an object whose given property is 1" + OfType("int"),
4420 Explain(m, &a));
4421
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",
4425 Explain(m, &a));
4426}
4427
4428TEST(PropertyForPointerTest, CanExplainMatchResultWithPropertyName) {
4429 Matcher<const AClass*> m = Property("fancy_name", &AClass::n, Ge(0));
4430
4431 AClass a;
4432 a.set_n(1);
4433 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
4434 EXPECT_EQ("which points to an object whose property `fancy_name` is 1" +
4435 OfType("int"),
4436 Explain(m, &a));
4437
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",
4441 Explain(m, &a));
4442}
4443
4444// Tests ResultOf.
4445
4446// Tests that ResultOf(f, ...) compiles and works as expected when f is a
4447// function pointer.
4448std::string IntToStringFunction(int input) {
4449 return input == 1 ? "foo" : "bar";
4450}
4451
4452TEST(ResultOfTest, WorksForFunctionPointers) {
4453 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));
4454
4455 EXPECT_TRUE(matcher.Matches(1));
4456 EXPECT_FALSE(matcher.Matches(2));
4457}
4458
4459// Tests that ResultOf() can describe itself.
4460TEST(ResultOfTest, CanDescribeItself) {
4461 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
4462
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));
4467}
4468
4469// Tests that ResultOf() can explain the match result.
4470int IntFunction(int input) { return input == 42 ? 80 : 90; }
4471
4472TEST(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));
4476
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));
4480}
4481
4482// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4483// returns a non-reference.
4484TEST(ResultOfTest, WorksForNonReferenceResults) {
4485 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
4486
4487 EXPECT_TRUE(matcher.Matches(42));
4488 EXPECT_FALSE(matcher.Matches(36));
4489}
4490
4491// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4492// returns a reference to non-const.
4493double& DoubleFunction(double& input) { return input; } // NOLINT
4494
4496 return obj;
4497}
4498
4499TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
4500 double x = 3.14;
4501 double x2 = x;
4503
4504 EXPECT_TRUE(matcher.Matches(x));
4505 EXPECT_FALSE(matcher.Matches(x2));
4506
4507 // Test that ResultOf works with uncopyable objects
4508 Uncopyable obj(0);
4509 Uncopyable obj2(0);
4510 Matcher<Uncopyable&> matcher2 =
4512
4513 EXPECT_TRUE(matcher2.Matches(obj));
4514 EXPECT_FALSE(matcher2.Matches(obj2));
4515}
4516
4517// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
4518// returns a reference to const.
4519const std::string& StringFunction(const std::string& input) { return input; }
4520
4521TEST(ResultOfTest, WorksForReferenceToConstResults) {
4522 std::string s = "foo";
4523 std::string s2 = s;
4525
4526 EXPECT_TRUE(matcher.Matches(s));
4527 EXPECT_FALSE(matcher.Matches(s2));
4528}
4529
4530// Tests that ResultOf(f, m) works when f(x) and m's
4531// argument types are compatible but different.
4532TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
4533 // IntFunction() returns int but the inner matcher expects a signed char.
4535
4536 EXPECT_TRUE(matcher.Matches(36));
4537 EXPECT_FALSE(matcher.Matches(42));
4538}
4539
4540// Tests that the program aborts when ResultOf is passed
4541// a NULL function pointer.
4542TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
4544 ResultOf(static_cast<std::string (*)(int dummy)>(NULL),
4545 Eq(std::string("foo"))),
4546 "NULL function pointer is passed into ResultOf\\(\\)\\.");
4547}
4548
4549// Tests that ResultOf(f, ...) compiles and works as expected when f is a
4550// function reference.
4551TEST(ResultOfTest, WorksForFunctionReferences) {
4553 EXPECT_TRUE(matcher.Matches(1));
4554 EXPECT_FALSE(matcher.Matches(2));
4555}
4556
4557// Tests that ResultOf(f, ...) compiles and works as expected when f is a
4558// function object.
4559struct Functor : public ::std::unary_function<int, std::string> {
4560 result_type operator()(argument_type input) const {
4561 return IntToStringFunction(input);
4562 }
4563};
4564
4565TEST(ResultOfTest, WorksForFunctors) {
4566 Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));
4567
4568 EXPECT_TRUE(matcher.Matches(1));
4569 EXPECT_FALSE(matcher.Matches(2));
4570}
4571
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().
4576 typedef int result_type;
4577 int operator()(int n) { return n; }
4578 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
4579};
4580
4581TEST(ResultOfTest, WorksForPolymorphicFunctors) {
4582 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
4583
4584 EXPECT_TRUE(matcher_int.Matches(10));
4585 EXPECT_FALSE(matcher_int.Matches(2));
4586
4587 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
4588
4589 EXPECT_TRUE(matcher_string.Matches("long string"));
4590 EXPECT_FALSE(matcher_string.Matches("shrt"));
4591}
4592
4593const int* ReferencingFunction(const int& n) { return &n; }
4594
4596 typedef const int* result_type;
4597 result_type operator()(const int& n) { return &n; }
4598};
4599
4600TEST(ResultOfTest, WorksForReferencingCallables) {
4601 const int n = 1;
4602 const int n2 = 1;
4604 EXPECT_TRUE(matcher2.Matches(n));
4605 EXPECT_FALSE(matcher2.Matches(n2));
4606
4608 EXPECT_TRUE(matcher3.Matches(n));
4609 EXPECT_FALSE(matcher3.Matches(n2));
4610}
4611
4613 public:
4614 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
4615
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 "
4620 << divider_;
4621 return (n % divider_) == 0;
4622 }
4623
4624 void DescribeTo(ostream* os) const {
4625 *os << "is divisible by " << divider_;
4626 }
4627
4628 void DescribeNegationTo(ostream* os) const {
4629 *os << "is not divisible by " << divider_;
4630 }
4631
4632 void set_divider(int a_divider) { divider_ = a_divider; }
4633 int divider() const { return divider_; }
4634
4635 private:
4636 int divider_;
4637};
4638
4642
4643// Tests that when AllOf() fails, only the first failing matcher is
4644// asked to explain why.
4645TEST(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));
4648}
4649
4650// Tests that when AllOf() fails, only the first failing matcher is
4651// asked to explain why.
4652TEST(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));
4655}
4656
4657// Tests that when AllOf() fails, only the first failing matcher is
4658// asked to explain why.
4659TEST(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));
4662}
4663
4664// Tests that when AllOf() succeeds, all matchers are asked to explain
4665// why.
4666TEST(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));
4669}
4670
4671TEST(ExplainMatchResultTest, AllOf_True_True_2) {
4672 const Matcher<int> m = AllOf(Ge(2), Le(3));
4673 EXPECT_EQ("", Explain(m, 2));
4674}
4675
4676TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
4677 const Matcher<int> m = GreaterThan(5);
4678 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
4679}
4680
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().
4684
4686 public:
4687 explicit NotCopyable(int a_value) : value_(a_value) {}
4688
4689 int value() const { return value_; }
4690
4691 bool operator==(const NotCopyable& rhs) const {
4692 return value() == rhs.value();
4693 }
4694
4695 bool operator>=(const NotCopyable& rhs) const {
4696 return value() >= rhs.value();
4697 }
4698 private:
4699 int value_;
4700
4702};
4703
4704TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
4705 const NotCopyable const_value1(1);
4706 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
4707
4708 const NotCopyable n1(1), n2(2);
4709 EXPECT_TRUE(m.Matches(n1));
4710 EXPECT_FALSE(m.Matches(n2));
4711}
4712
4713TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
4714 NotCopyable value2(2);
4715 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
4716
4717 NotCopyable n1(1), n2(2);
4718 EXPECT_FALSE(m.Matches(n1));
4719 EXPECT_TRUE(m.Matches(n2));
4720}
4721
4722TEST(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()));
4729}
4730
4731TEST(IsEmptyTest, WorksWithString) {
4732 std::string text;
4733 EXPECT_THAT(text, IsEmpty());
4734 text = "foo";
4735 EXPECT_THAT(text, Not(IsEmpty()));
4736 text = std::string("\0", 1);
4737 EXPECT_THAT(text, Not(IsEmpty()));
4738}
4739
4740TEST(IsEmptyTest, CanDescribeSelf) {
4741 Matcher<vector<int> > m = IsEmpty();
4742 EXPECT_EQ("is empty", Describe(m));
4743 EXPECT_EQ("isn't empty", DescribeNegation(m));
4744}
4745
4746TEST(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));
4752}
4753
4754TEST(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()));
4769 int a = 42;
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
4790}
4791
4792TEST(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));
4802}
4803
4804TEST(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));
4814}
4815
4816TEST(SizeIsTest, WorksWithReferences) {
4817 vector<int> container;
4819 EXPECT_THAT(container, Not(m));
4820 container.push_back(0);
4821 EXPECT_THAT(container, m);
4822}
4823
4824TEST(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));
4828}
4829
4830TEST(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));
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));
4848}
4849
4850#if GTEST_HAS_TYPED_TEST
4851// Tests ContainerEq with different container types, and
4852// different element types.
4853
4854template <typename T>
4855class ContainerEqTest : public testing::Test {};
4856
4857typedef testing::Types<
4858 set<int>,
4859 vector<size_t>,
4860 multiset<size_t>,
4861 list<int> >
4862 ContainerEqTestTypes;
4863
4864TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
4865
4866// Tests that the filled container is equal to itself.
4867TYPED_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));
4873}
4874
4875// Tests that missing values are reported.
4876TYPED_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));
4885}
4886
4887// Tests that added values are reported.
4888TYPED_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));
4896}
4897
4898// Tests that added and missing values are reported together.
4899TYPED_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));
4909}
4910
4911// Tests duplicated value -- expect no explanation.
4912TYPED_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));
4921}
4922#endif // GTEST_HAS_TYPED_TEST
4923
4924// Tests that mutliple missing values are reported.
4925// Using just vector here, so order is predictable.
4926TEST(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));
4935}
4936
4937// Tests that added values are reported.
4938// Using just vector here, so order is predictable.
4939TEST(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));
4948}
4949
4950// Tests that added and missing values are reported together.
4951TEST(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));
4961}
4962
4963// Tests to see that duplicate elements are detected,
4964// but (as above) not reported in the explanation.
4965TEST(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));
4975}
4976
4977// Tests that ContainerEq works for non-trivial associative containers,
4978// like maps.
4979TEST(ContainerEqExtraTest, WorksForMaps) {
4980 map<int, std::string> my_map;
4981 my_map[0] = "a";
4982 my_map[1] = "b";
4983
4984 map<int, std::string> test_map;
4985 test_map[0] = "aa";
4986 test_map[1] = "b";
4987
4989 EXPECT_TRUE(m.Matches(my_map));
4990 EXPECT_FALSE(m.Matches(test_map));
4991
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));
4995}
4996
4997TEST(ContainerEqExtraTest, WorksForNativeArray) {
4998 int a1[] = {1, 2, 3};
4999 int a2[] = {1, 2, 3};
5000 int b[] = {1, 2, 4};
5001
5002 EXPECT_THAT(a1, ContainerEq(a2));
5003 EXPECT_THAT(a1, Not(ContainerEq(b)));
5004}
5005
5006TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
5007 const char a1[][3] = {"hi", "lo"};
5008 const char a2[][3] = {"hi", "lo"};
5009 const char b[][3] = {"lo", "hi"};
5010
5011 // Tests using ContainerEq() in the first dimension.
5012 EXPECT_THAT(a1, ContainerEq(a2));
5013 EXPECT_THAT(a1, Not(ContainerEq(b)));
5014
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])));
5018}
5019
5020TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
5021 const int a1[] = {1, 2, 3};
5022 const int a2[] = {1, 2, 3};
5023 const int b[] = {1, 2, 3, 4};
5024
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)));
5028
5029 const int c[] = {1, 3, 2};
5030 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
5031}
5032
5033TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
5034 std::string a1[][3] = {
5035 {"hi", "hello", "ciao"},
5036 {"bye", "see you", "ciao"}
5037 };
5038
5039 std::string a2[][3] = {
5040 {"hi", "hello", "ciao"},
5041 {"bye", "see you", "ciao"}
5042 };
5043
5044 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
5045 EXPECT_THAT(a1, m);
5046
5047 a2[0][0] = "ha";
5048 EXPECT_THAT(a1, m);
5049}
5050
5051TEST(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))));
5055}
5056
5057TEST(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))));
5067}
5068
5069TEST(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"))));
5078}
5079
5080TEST(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))));
5087}
5088
5089TEST(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",
5094 Describe(m));
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));
5099}
5100
5101TEST(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));
5107}
5108
5109// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
5110// need to test it as exhaustively as we test the latter.
5111
5112TEST(WhenSortedTest, WorksForEmptyContainer) {
5113 const vector<int> numbers;
5114 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
5115 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
5116}
5117
5118TEST(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"))));
5126}
5127
5128TEST(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),
5135 Pair("the", 1))));
5136 EXPECT_THAT(word_counts,
5137 Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
5138 Pair("buffalo", 2)))));
5139}
5140
5141TEST(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));
5150 Pair(1, 2),
5151 Pair(2, 3),
5152 Pair(3, 4),
5153 Pair(5, 5),
5154 Pair(8, 6))));
5156 Pair(2, 3),
5157 Pair(1, 1),
5158 Pair(3, 4),
5159 Pair(1, 2),
5160 Pair(5, 5)))));
5161}
5162
5163TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
5164 std::deque<int> d;
5165 d.push_back(2);
5166 d.push_back(1);
5169}
5170
5171TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
5172 std::deque<int> d;
5173 d.push_back(2);
5174 d.push_back(1);
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)));
5179}
5180
5181// Deliberately bare pseudo-container.
5182// Offers only begin() and end() accessors, yielding InputIterator.
5183template <typename T>
5185 private:
5186 class ConstIter;
5187 public:
5188 typedef ConstIter const_iterator;
5189 typedef T value_type;
5190
5191 template <typename InIter>
5192 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
5193
5195 return const_iterator(this, remainder_.begin());
5196 }
5198 return const_iterator(this, remainder_.end());
5199 }
5200
5201 private:
5202 class ConstIter : public std::iterator<std::input_iterator_tag,
5203 value_type,
5204 ptrdiff_t,
5205 const value_type*,
5206 const value_type&> {
5207 public:
5208 ConstIter(const Streamlike* s,
5209 typename std::list<value_type>::iterator pos)
5210 : s_(s), pos_(pos) {}
5211
5212 const value_type& operator*() const { return *pos_; }
5213 const value_type* operator->() const { return &*pos_; }
5214 ConstIter& operator++() {
5215 s_->remainder_.erase(pos_++);
5216 return *this;
5217 }
5218
5219 // *iter++ is required to work (see std::istreambuf_iterator).
5220 // (void)iter++ is also required to work.
5222 public:
5223 explicit PostIncrProxy(const value_type& value) : value_(value) {}
5224 value_type operator*() const { return value_; }
5225 private:
5226 value_type value_;
5227 };
5228 PostIncrProxy operator++(int) {
5229 PostIncrProxy proxy(**this);
5230 ++(*this);
5231 return proxy;
5232 }
5233
5234 friend bool operator==(const ConstIter& a, const ConstIter& b) {
5235 return a.s_ == b.s_ && a.pos_ == b.pos_;
5236 }
5237 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
5238 return !(a == b);
5239 }
5240
5241 private:
5242 const Streamlike* s_;
5243 typename std::list<value_type>::iterator pos_;
5244 };
5245
5246 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
5247 os << "[";
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) {
5251 os << sep << *it;
5252 sep = ",";
5253 }
5254 os << "]";
5255 return os;
5256 }
5257
5258 mutable std::list<value_type> remainder_; // modified by iteration
5259};
5260
5261TEST(StreamlikeTest, Iteration) {
5262 const int a[5] = {2, 1, 4, 5, 3};
5263 Streamlike<int> s(a, a + 5);
5265 const int* ip = a;
5266 while (it != s.end()) {
5267 SCOPED_TRACE(ip - a);
5268 EXPECT_EQ(*ip++, *it++);
5269 }
5270}
5271
5272#if GTEST_HAS_STD_FORWARD_LIST_
5273TEST(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));
5283}
5284#endif // GTEST_HAS_STD_FORWARD_LIST_
5285
5286TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
5287 const int a[5] = {1, 2, 3, 4, 5};
5288 Streamlike<int> s(a, a + 5);
5290}
5291
5292TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
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));
5297}
5298
5299TEST(BeginEndDistanceIsTest, ExplainsResult) {
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));
5311 EXPECT_EQ(
5312 "whose distance between begin() and end() 0 doesn't match, which is 1 "
5313 "less than 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));
5323 EXPECT_EQ(
5324 "whose distance between begin() and end() 2 matches, which is 1 more "
5325 "than 1",
5326 Explain(m4, container));
5327}
5328
5329TEST(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};
5334 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
5335 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
5336}
5337
5338TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
5339 const int a[] = {2, 1, 4, 5, 3};
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))));
5344}
5345
5346TEST(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)));
5355}
5356
5357TEST(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));
5363}
5364
5365TEST(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)));
5371 expected.clear();
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)));
5381}
5382
5383TEST(IsSupersetOfTest, WorksForStreamlike) {
5384 const int a[5] = {1, 2, 3, 4, 5};
5386
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));
5392
5393 expected.push_back(0);
5394 EXPECT_THAT(s, Not(IsSupersetOf(expected)));
5395}
5396
5397TEST(IsSupersetOfTest, TakesStlContainer) {
5398 const int actual[] = {3, 1, 2};
5399
5400 ::std::list<int> expected;
5401 expected.push_back(1);
5402 expected.push_back(3);
5403 EXPECT_THAT(actual, IsSupersetOf(expected));
5404
5405 expected.push_back(4);
5406 EXPECT_THAT(actual, Not(IsSupersetOf(expected)));
5407}
5408
5409TEST(IsSupersetOfTest, Describe) {
5410 typedef std::vector<int> IntVec;
5411 IntVec expected;
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"));
5421}
5422
5423TEST(IsSupersetOfTest, DescribeNegation) {
5424 typedef std::vector<int> IntVec;
5425 IntVec expected;
5426 expected.push_back(111);
5427 expected.push_back(222);
5428 expected.push_back(333);
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"));
5435}
5436
5437TEST(IsSupersetOfTest, MatchAndExplain) {
5438 std::vector<int> v;
5439 v.push_back(2);
5440 v.push_back(3);
5441 std::vector<int> expected;
5442 expected.push_back(1);
5443 expected.push_back(2);
5445 ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
5446 << listener.str();
5447 EXPECT_THAT(listener.str(),
5448 Eq("where the following matchers don't match any elements:\n"
5449 "matcher #0: is equal to 1"));
5450
5451 v.push_back(1);
5452 listener.Clear();
5453 ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))
5454 << listener.str();
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"));
5458}
5459
5460#if GTEST_HAS_STD_INITIALIZER_LIST_
5461TEST(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})));
5465}
5466#endif
5467
5468TEST(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)));
5477}
5478
5479TEST(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));
5485}
5486
5487TEST(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));
5493 expected.clear();
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));
5503}
5504
5505TEST(IsSubsetOfTest, WorksForStreamlike) {
5506 const int a[5] = {1, 2};
5508
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));
5515}
5516
5517TEST(IsSubsetOfTest, TakesStlContainer) {
5518 const int actual[] = {3, 1, 2};
5519
5520 ::std::list<int> expected;
5521 expected.push_back(1);
5522 expected.push_back(3);
5523 EXPECT_THAT(actual, Not(IsSubsetOf(expected)));
5524
5525 expected.push_back(2);
5526 expected.push_back(4);
5527 EXPECT_THAT(actual, IsSubsetOf(expected));
5528}
5529
5530TEST(IsSubsetOfTest, Describe) {
5531 typedef std::vector<int> IntVec;
5532 IntVec expected;
5533 expected.push_back(111);
5534 expected.push_back(222);
5535 expected.push_back(333);
5536
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"));
5543}
5544
5545TEST(IsSubsetOfTest, DescribeNegation) {
5546 typedef std::vector<int> IntVec;
5547 IntVec expected;
5548 expected.push_back(111);
5549 expected.push_back(222);
5550 expected.push_back(333);
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"));
5557}
5558
5559TEST(IsSubsetOfTest, MatchAndExplain) {
5560 std::vector<int> v;
5561 v.push_back(2);
5562 v.push_back(3);
5563 std::vector<int> expected;
5564 expected.push_back(1);
5565 expected.push_back(2);
5567 ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
5568 << listener.str();
5569 EXPECT_THAT(listener.str(),
5570 Eq("where the following elements don't match any matchers:\n"
5571 "element #1: 3"));
5572
5573 expected.push_back(3);
5574 listener.Clear();
5575 ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))
5576 << listener.str();
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"));
5580}
5581
5582#if GTEST_HAS_STD_INITIALIZER_LIST_
5583TEST(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})));
5587}
5588#endif
5589
5590// Tests using ElementsAre() and ElementsAreArray() with stream-like
5591// "containers".
5592
5593TEST(ElemensAreStreamTest, WorksForStreamlike) {
5594 const int a[5] = {1, 2, 3, 4, 5};
5596 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
5597 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
5598}
5599
5600TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
5601 const int a[5] = {1, 2, 3, 4, 5};
5603
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));
5611
5612 expected[3] = 0;
5613 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
5614}
5615
5616TEST(ElementsAreTest, WorksWithUncopyable) {
5617 Uncopyable objs[2];
5618 objs[0].set_value(-3);
5619 objs[1].set_value(1);
5620 EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
5621}
5622
5623TEST(ElementsAreTest, TakesStlContainer) {
5624 const int actual[] = {3, 1, 2};
5625
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));
5631
5632 expected.push_back(4);
5633 EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
5634}
5635
5636// Tests for UnorderedElementsAreArray()
5637
5638TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
5639 const int a[] = {0, 1, 2, 3, 4};
5640 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5641 do {
5644 s, &listener)) << listener.str();
5645 } while (std::next_permutation(s.begin(), s.end()));
5646}
5647
5648TEST(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));
5655 actual, &listener)) << listener.str();
5656}
5657
5658TEST(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};
5664
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);
5672
5673 expected.push_back(6);
5675}
5676
5677TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
5678 const int actual[] = {3, 1, 2};
5679
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));
5685
5686 expected.push_back(4);
5687 EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
5688}
5689
5690#if GTEST_HAS_STD_INITIALIZER_LIST_
5691
5692TEST(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})));
5696}
5697
5698TEST(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"})));
5702}
5703
5704TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
5705 const int a[5] = {2, 1, 4, 5, 3};
5707 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
5709 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
5710}
5711
5712TEST(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)}));
5721 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
5722}
5723
5724#endif // GTEST_HAS_STD_INITIALIZER_LIST_
5725
5727 protected:
5728 typedef std::vector<int> IntVec;
5729};
5730
5731TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
5732 Uncopyable objs[2];
5733 objs[0].set_value(-3);
5734 objs[1].set_value(1);
5735 EXPECT_THAT(objs,
5736 UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
5737}
5738
5739TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
5740 const int a[] = {1, 2, 3};
5741 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
5742 do {
5745 s, &listener)) << listener.str();
5746 } while (std::next_permutation(s.begin(), s.end()));
5747}
5748
5749TEST_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;
5753 mv.push_back(1);
5754 mv.push_back(2);
5755 mv.push_back(2);
5756 // The element with value '3' matches nothing: fail fast.
5759 s, &listener)) << listener.str();
5760}
5761
5762TEST_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};
5768
5769 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
5770 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
5771}
5772
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)
5780 std::vector<int> s;
5781 std::vector<Matcher<int> > mv;
5782 for (int i = 0; i < 100; ++i) {
5783 s.push_back(i);
5784 mv.push_back(_);
5785 }
5786 mv[50] = Eq(0);
5789 s, &listener)) << listener.str();
5790}
5791
5792// Another variant of 'Performance' with similar expectations.
5793// [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
5794// [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
5795TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
5796 std::vector<int> s;
5797 std::vector<Matcher<int> > mv;
5798 for (int i = 0; i < 100; ++i) {
5799 s.push_back(i);
5800 if (i & 1) {
5801 mv.push_back(_);
5802 } else {
5803 mv.push_back(i);
5804 }
5805 }
5808 s, &listener)) << listener.str();
5809}
5810
5811TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
5812 std::vector<int> v;
5813 v.push_back(4);
5816 v, &listener)) << listener.str();
5817 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
5818}
5819
5820TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
5821 std::vector<int> v;
5824 v, &listener)) << listener.str();
5825 EXPECT_THAT(listener.str(), Eq(""));
5826}
5827
5828TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
5829 std::vector<int> v;
5830 v.push_back(1);
5831 v.push_back(1);
5834 v, &listener)) << listener.str();
5836 listener.str(),
5837 Eq("where the following matchers don't match any elements:\n"
5838 "matcher #1: is equal to 2"));
5839}
5840
5841TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
5842 std::vector<int> v;
5843 v.push_back(1);
5844 v.push_back(2);
5847 v, &listener)) << listener.str();
5849 listener.str(),
5850 Eq("where the following elements don't match any matchers:\n"
5851 "element #1: 2"));
5852}
5853
5854TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
5855 std::vector<int> v;
5856 v.push_back(2);
5857 v.push_back(3);
5860 v, &listener)) << listener.str();
5862 listener.str(),
5863 Eq("where"
5864 " the following matchers don't match any elements:\n"
5865 "matcher #0: is equal to 1\n"
5866 "and"
5867 " where"
5868 " the following elements don't match any matchers:\n"
5869 "element #1: 3"));
5870}
5871
5872// Test helper for formatting element, matcher index pairs in expectations.
5873static std::string EMString(int element, int matcher) {
5874 stringstream ss;
5875 ss << "(element #" << element << ", matcher #" << matcher << ")";
5876 return ss.str();
5877}
5878
5879TEST_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;
5883 v.push_back("a");
5884 v.push_back("b");
5885 v.push_back("c");
5888 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
5889 << listener.str();
5890
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 "
5894 "pairings:\n";
5895
5896 // We have to be a bit loose here, because there are 4 valid max matches.
5898 listener.str(),
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}"));
5907}
5908
5911 Eq("is empty"));
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"));
5922}
5923
5926 Eq("isn't empty"));
5929 Eq("doesn't have 1 element, or has 1 element that isn't equal to 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"));
5937}
5938
5939namespace {
5940
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.
5945template <typename Graph>
5946class BacktrackingMaxBPMState {
5947 public:
5948 // Does not take ownership of 'g'.
5949 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
5950
5951 ElementMatcherPairs Compute() {
5952 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
5953 return best_so_far_;
5954 }
5955 lhs_used_.assign(graph_->LhsSize(), kUnused);
5956 rhs_used_.assign(graph_->RhsSize(), kUnused);
5957 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
5958 matches_.clear();
5959 RecurseInto(irhs);
5960 if (best_so_far_.size() == graph_->RhsSize())
5961 break;
5962 }
5963 return best_so_far_;
5964 }
5965
5966 private:
5967 static const size_t kUnused = static_cast<size_t>(-1);
5968
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_;
5975 }
5976 }
5977
5978 void PopMatch() {
5979 const ElementMatcherPair& back = matches_.back();
5980 lhs_used_[back.first] = kUnused;
5981 rhs_used_[back.second] = kUnused;
5982 matches_.pop_back();
5983 }
5984
5985 bool RecurseInto(size_t irhs) {
5986 if (rhs_used_[irhs] != kUnused) {
5987 return true;
5988 }
5989 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
5990 if (lhs_used_[ilhs] != kUnused) {
5991 continue;
5992 }
5993 if (!graph_->HasEdge(ilhs, irhs)) {
5994 continue;
5995 }
5996 PushMatch(ilhs, irhs);
5997 if (best_so_far_.size() == graph_->RhsSize()) {
5998 return false;
5999 }
6000 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
6001 if (!RecurseInto(mi)) return false;
6002 }
6003 PopMatch();
6004 }
6005 return true;
6006 }
6007
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_;
6013};
6014
6015template <typename Graph>
6016const size_t BacktrackingMaxBPMState<Graph>::kUnused;
6017
6018} // namespace
6019
6020// Implement a simple backtracking algorithm to determine if it is possible
6021// to find one element per matcher, without reusing elements.
6022template <typename Graph>
6024FindBacktrackingMaxBPM(const Graph& g) {
6025 return BacktrackingMaxBPMState<Graph>(&g).Compute();
6026}
6027
6029
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.
6033
6034// Verify all match graphs up to some moderate number of edges.
6035TEST_P(BipartiteTest, Exhaustive) {
6036 int nodes = GetParam();
6037 MatchMatrix graph(nodes, nodes);
6038 do {
6039 ElementMatcherPairs matches =
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;
6056 }
6057 } while (graph.NextGraph());
6058}
6059
6061 ::testing::Range(0, 5));
6062
6063// Parameterized by a pair interpreted as (LhsSize, RhsSize).
6065 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
6066};
6067
6068TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
6069 // .......
6070 // 0:-----\ :
6071 // 1:---\ | :
6072 // 2:---\ | :
6073 // 3:-\ | | :
6074 // :.......:
6075 // 0 1 2
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);
6080 }
6082 ElementsAre(Pair(3, 0),
6083 Pair(AnyOf(1, 2), 1),
6084 Pair(0, 2))) << g.DebugString();
6085}
6086
6087// Verify a few nonsquare matrices.
6089 size_t nlhs = GetParam().first;
6090 size_t nrhs = GetParam().second;
6091 MatchMatrix graph(nlhs, nrhs);
6092 do {
6093 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
6095 << "graph: " << graph.DebugString()
6096 << "\nbacktracking: "
6098 << "\nmax flow: "
6100 } while (graph.NextGraph());
6101}
6102
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)));
6113
6115 : public ::testing::TestWithParam<std::pair<int, int> > {
6116};
6117
6118// Verifies a large sample of larger graphs.
6120 int nodes = GetParam().first;
6121 int iters = GetParam().second;
6122 MatchMatrix graph(nodes, nodes);
6123
6124 testing::internal::Int32 seed = GTEST_FLAG(random_seed);
6125 if (seed == 0) {
6126 seed = static_cast<testing::internal::Int32>(time(NULL));
6127 }
6128
6129 for (; iters > 0; --iters, ++seed) {
6130 srand(static_cast<int>(seed));
6131 graph.Randomize();
6132 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
6134 << " graph: " << graph.DebugString()
6135 << "\nTo reproduce the failure, rerun the test with the flag"
6136 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
6137 }
6138}
6139
6140// Test argument is a std::pair<int, int> representing (nodes, iters).
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)));
6148
6149// Tests IsReadableTypeName().
6150
6151TEST(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)"));
6156}
6157
6158TEST(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"));
6162}
6163
6164TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
6166 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
6167 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
6168}
6169
6170TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
6171 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
6172}
6173
6174// Tests FormatMatcherDescription().
6175
6176TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
6177 EXPECT_EQ("is even",
6178 FormatMatcherDescription(false, "IsEven", Strings()));
6179 EXPECT_EQ("not (is even)",
6180 FormatMatcherDescription(true, "IsEven", Strings()));
6181
6182 const char* params[] = {"5"};
6183 EXPECT_EQ("equals 5",
6184 FormatMatcherDescription(false, "Equals",
6185 Strings(params, params + 1)));
6186
6187 const char* params2[] = {"5", "8"};
6188 EXPECT_EQ("is in range (5, 8)",
6189 FormatMatcherDescription(false, "IsInRange",
6190 Strings(params2, params2 + 2)));
6191}
6192
6193// Tests PolymorphicMatcher::mutable_impl().
6194TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
6197 EXPECT_EQ(42, impl.divider());
6198
6199 impl.set_divider(0);
6200 EXPECT_EQ(0, m.mutable_impl().divider());
6201}
6202
6203// Tests PolymorphicMatcher::impl().
6204TEST(PolymorphicMatcherTest, CanAccessImpl) {
6206 const DivisibleByImpl& impl = m.impl();
6207 EXPECT_EQ(42, impl.divider());
6208}
6209
6210TEST(MatcherTupleTest, ExplainsMatchFailure) {
6211 stringstream ss1;
6212 ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
6213 make_tuple('a', 10), &ss1);
6214 EXPECT_EQ("", ss1.str()); // Successful match.
6215
6216 stringstream ss2;
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.
6224
6225 stringstream ss3;
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
6231 // explanation.
6232}
6233
6234// Tests Each().
6235
6236TEST(EachTest, ExplainsMatchResultCorrectly) {
6237 set<int> a; // empty
6238
6239 Matcher<set<int> > m = Each(2);
6240 EXPECT_EQ("", Explain(m, a));
6241
6242 Matcher<const int(&)[1]> n = Each(1); // NOLINT
6243
6244 const int b[1] = {1};
6245 EXPECT_EQ("", Explain(n, b));
6246
6247 n = Each(3);
6248 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
6249
6250 a.insert(1);
6251 a.insert(2);
6252 a.insert(3);
6253 m = Each(GreaterThan(0));
6254 EXPECT_EQ("", Explain(m, a));
6255
6256 m = Each(GreaterThan(10));
6257 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
6258 Explain(m, a));
6259}
6260
6261TEST(EachTest, DescribesItselfCorrectly) {
6262 Matcher<vector<int> > m = Each(1);
6263 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
6264
6265 Matcher<vector<int> > m2 = Not(m);
6266 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
6267}
6268
6269TEST(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)));
6279
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"))));
6287}
6288
6289TEST(EachTest, MatchesMapWhenAllElementsMatch) {
6290 map<const char*, int> my_map;
6291 const char* bar = "a string";
6292 my_map[bar] = 2;
6293 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
6294
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))));
6305}
6306
6307TEST(EachTest, AcceptsMatcher) {
6308 const int a[] = {1, 2, 3};
6309 EXPECT_THAT(a, Each(Gt(0)));
6310 EXPECT_THAT(a, Not(Each(Gt(1))));
6311}
6312
6313TEST(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))));
6318}
6319
6320// For testing Pointwise().
6322 public:
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);
6328 return true;
6329 } else {
6330 *listener << "where the second/2 is " << get<1>(a_pair)/2;
6331 return false;
6332 }
6333 }
6334
6335 void DescribeTo(ostream* os) const {
6336 *os << "are a pair where the first is half of the second";
6337 }
6338
6339 void DescribeNegationTo(ostream* os) const {
6340 *os << "are a pair where the first isn't half of the second";
6341 }
6342};
6343
6347
6348TEST(PointwiseTest, DescribesSelf) {
6349 vector<int> rhs;
6350 rhs.push_back(1);
6351 rhs.push_back(2);
6352 rhs.push_back(3);
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",
6356 Describe(m));
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));
6361}
6362
6363TEST(PointwiseTest, MakesCopyOfRhs) {
6364 list<signed char> rhs;
6365 rhs.push_back(2);
6366 rhs.push_back(4);
6367
6368 int lhs[] = {1, 2};
6369 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
6370 EXPECT_THAT(lhs, m);
6371
6372 // Changing rhs now shouldn't affect m, which made a copy of rhs.
6373 rhs.push_back(6);
6374 EXPECT_THAT(lhs, m);
6375}
6376
6377TEST(PointwiseTest, WorksForLhsNativeArray) {
6378 const int lhs[] = {1, 2, 3};
6379 vector<int> rhs;
6380 rhs.push_back(2);
6381 rhs.push_back(4);
6382 rhs.push_back(6);
6383 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
6384 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
6385}
6386
6387TEST(PointwiseTest, WorksForRhsNativeArray) {
6388 const int rhs[] = {1, 2, 3};
6389 vector<int> lhs;
6390 lhs.push_back(2);
6391 lhs.push_back(4);
6392 lhs.push_back(6);
6393 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
6394 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
6395}
6396
6397// Test is effective only with sanitizers.
6398TEST(PointwiseTest, WorksForVectorOfBool) {
6399 vector<bool> rhs(3, false);
6400 rhs[1] = true;
6401 vector<bool> lhs = rhs;
6402 EXPECT_THAT(lhs, Pointwise(Eq(), rhs));
6403 rhs[0] = true;
6404 EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs)));
6405}
6406
6407#if GTEST_HAS_STD_INITIALIZER_LIST_
6408
6409TEST(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})));
6413}
6414
6415#endif // GTEST_HAS_STD_INITIALIZER_LIST_
6416
6417TEST(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));
6423
6424 const int rhs2[3] = {0, 1, 2};
6425 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
6426}
6427
6428TEST(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));
6435}
6436
6437TEST(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));
6442}
6443
6444TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
6445 const double lhs[3] = {1, 2, 3};
6446 const int rhs[3] = {2, 4, 6};
6448 EXPECT_THAT(lhs, Pointwise(m1, rhs));
6449 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
6450
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));
6456}
6457
6458TEST(UnorderedPointwiseTest, DescribesSelf) {
6459 vector<int> rhs;
6460 rhs.push_back(1);
6461 rhs.push_back(2);
6462 rhs.push_back(3);
6464 EXPECT_EQ(
6465 "has 3 elements and there exists some permutation of elements such "
6466 "that:\n"
6467 " - element #0 and 1 are a pair where the first is half of the second, "
6468 "and\n"
6469 " - element #1 and 2 are a pair where the first is half of the second, "
6470 "and\n"
6471 " - element #2 and 3 are a pair where the first is half of the second",
6472 Describe(m));
6473 EXPECT_EQ(
6474 "doesn't have 3 elements, or there exists no permutation of elements "
6475 "such that:\n"
6476 " - element #0 and 1 are a pair where the first is half of the second, "
6477 "and\n"
6478 " - element #1 and 2 are a pair where the first is half of the second, "
6479 "and\n"
6480 " - element #2 and 3 are a pair where the first is half of the second",
6481 DescribeNegation(m));
6482}
6483
6484TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
6485 list<signed char> rhs;
6486 rhs.push_back(2);
6487 rhs.push_back(4);
6488
6489 int lhs[] = {2, 1};
6490 const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
6491 EXPECT_THAT(lhs, m);
6492
6493 // Changing rhs now shouldn't affect m, which made a copy of rhs.
6494 rhs.push_back(6);
6495 EXPECT_THAT(lhs, m);
6496}
6497
6498TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
6499 const int lhs[] = {1, 2, 3};
6500 vector<int> rhs;
6501 rhs.push_back(4);
6502 rhs.push_back(6);
6503 rhs.push_back(2);
6504 EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
6505 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
6506}
6507
6508TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
6509 const int rhs[] = {1, 2, 3};
6510 vector<int> lhs;
6511 lhs.push_back(4);
6512 lhs.push_back(2);
6513 lhs.push_back(6);
6514 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
6515 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
6516}
6517
6518#if GTEST_HAS_STD_INITIALIZER_LIST_
6519
6520TEST(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})));
6524}
6525
6526#endif // GTEST_HAS_STD_INITIALIZER_LIST_
6527
6528TEST(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));
6534
6535 const int rhs2[3] = {0, 1, 2};
6536 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
6537}
6538
6539TEST(UnorderedPointwiseTest, RejectsWrongContent) {
6540 const double lhs[3] = {1, 2, 3};
6541 const int rhs[3] = {2, 6, 6};
6543 EXPECT_EQ("where the following elements don't match any matchers:\n"
6544 "element #1: 2",
6545 Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
6546}
6547
6548TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
6549 const double lhs[3] = {1, 2, 3};
6550 const int rhs[3] = {2, 4, 6};
6552}
6553
6554TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
6555 const double lhs[3] = {1, 2, 3};
6556 const int rhs[3] = {6, 4, 2};
6558}
6559
6560TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
6561 const double lhs[3] = {1, 2, 3};
6562 const int rhs[3] = {4, 6, 2};
6564 EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
6565
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));
6570}
6571
6572// Sample optional type implementation with minimal requirements for use with
6573// Optional matcher.
6575 public:
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 {
6580 return has_value_;
6581 }
6582 const int& operator*() const {
6583 return value_;
6584 }
6585 private:
6586 int value_;
6587 bool has_value_;
6588};
6589
6590TEST(OptionalTest, DescribesSelf) {
6592 EXPECT_EQ("value is equal to 1", Describe(m));
6593}
6594
6595TEST(OptionalTest, ExplainsSelf) {
6597 EXPECT_EQ("whose value 1 matches", Explain(m, SampleOptionalInt(1)));
6598 EXPECT_EQ("whose value 2 doesn't match", Explain(m, SampleOptionalInt(2)));
6599}
6600
6601TEST(OptionalTest, MatchesNonEmptyOptional) {
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));
6609}
6610
6611TEST(OptionalTest, DoesNotMatchNullopt) {
6613 SampleOptionalInt empty;
6614 EXPECT_FALSE(m.Matches(empty));
6615}
6616
6618 public:
6619 SampleVariantIntString(int i) : i_(i), has_int_(true) {}
6620 SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {}
6621
6622 template <typename T>
6624 return value.has_int_ == internal::IsSame<T, int>::value;
6625 }
6626
6627 template <typename T>
6628 friend const T& get(const SampleVariantIntString& value) {
6629 return value.get_impl(static_cast<T*>(NULL));
6630 }
6631
6632 private:
6633 const int& get_impl(int*) const { return i_; }
6634 const std::string& get_impl(std::string*) const { return s_; }
6635
6636 int i_;
6637 std::string s_;
6638 bool has_int_;
6639};
6640
6641TEST(VariantTest, DescribesSelf) {
6643 EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type "
6644 "'.*' and the value is equal to 1"));
6645}
6646
6647TEST(VariantTest, ExplainsSelf) {
6650 ContainsRegex("whose value 1"));
6652 HasSubstr("whose value is not of type '"));
6654 "whose value 2 doesn't match");
6655}
6656
6664
6665TEST(VariantTest, TypeDoesNotMatch) {
6668
6669 m = VariantWith<std::string>(Eq("1"));
6671}
6672
6673TEST(VariantTest, InnerDoesNotMatch) {
6676
6677 m = VariantWith<std::string>(Eq("1"));
6679}
6680
6682 public:
6683 explicit SampleAnyType(int i) : index_(0), i_(i) {}
6684 explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {}
6685
6686 template <typename T>
6687 friend const T* any_cast(const SampleAnyType* any) {
6688 return any->get_impl(static_cast<T*>(NULL));
6689 }
6690
6691 private:
6692 int index_;
6693 int i_;
6694 std::string s_;
6695
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;
6699 }
6700};
6701
6702TEST(AnyWithTest, FullMatch) {
6705}
6706
6707TEST(AnyWithTest, TestBadCastType) {
6710}
6711
6712#if GTEST_LANG_CXX11
6713TEST(AnyWithTest, TestUseInContainers) {
6714 std::vector<SampleAnyType> a;
6715 a.emplace_back(1);
6716 a.emplace_back(2);
6717 a.emplace_back(3);
6720
6721 std::vector<SampleAnyType> b;
6722 b.emplace_back("hello");
6723 b.emplace_back("merhaba");
6724 b.emplace_back("salut");
6726 AnyWith<std::string>("merhaba"),
6727 AnyWith<std::string>("salut")}));
6728}
6729#endif // GTEST_LANG_CXX11
6730TEST(AnyWithTest, TestCompare) {
6732}
6733
6734TEST(AnyWithTest, DescribesSelf) {
6736 EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type "
6737 "'.*' and the value is equal to 1"));
6738}
6739
6740TEST(AnyWithTest, ExplainsSelf) {
6742
6743 EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1"));
6745 HasSubstr("whose value is not of type '"));
6746 EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match");
6747}
6748
6749#if GTEST_LANG_CXX11
6750
6751TEST(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))));
6755}
6756
6757TEST(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))));
6761}
6762
6763#endif // GTEST_LANG_CXX11
6764
6765} // namespace gmock_matchers_test
6766} // namespace testing
6767
Unary< NodeType::optional > Optional
Definition Regexp.cpp:53
const mie::Vuint & p
Definition bn.cpp:27
const Impl & impl() const
void set_s(const std::string &new_s)
MOCK_METHOD2(Helper, int(char x, int y))
bool MatchAndExplain(const T &n, MatchResultListener *listener) const
virtual bool MatchAndExplain(int x, MatchResultListener *) const
void TestNearMatches(testing::internal::FloatingEqMatcher< RawType >(*matcher_maker)(RawType, RawType))
testing::internal::FloatingPoint< RawType > Floating
void TestMatches(testing::internal::FloatingEqMatcher< RawType >(*matcher_maker)(RawType))
virtual bool MatchAndExplain(int lhs, MatchResultListener *listener) const
bool MatchAndExplain(const tuple< T1, T2 > &a_pair, MatchResultListener *listener) const
virtual bool MatchAndExplain(int x, MatchResultListener *listener) const
bool operator==(const NotCopyable &rhs) const
bool operator>=(const NotCopyable &rhs) const
MOCK_METHOD2(Overloaded, int(char x, int y))
bool MatchAndExplain(const T &x, MatchResultListener *listener) const
bool MatchAndExplain(const T &x, MatchResultListener *) const
friend const T * any_cast(const SampleAnyType *any)
friend bool holds_alternative(const SampleVariantIntString &value)
friend const T & get(const SampleVariantIntString &value)
PostIncrProxy(const value_type &value)
value_type operator*() const
friend std::ostream & operator<<(std::ostream &os, const Streamlike &s)
TypeWithSize< sizeof(RawType)>::UInt Bits
bool HasEdge(size_t ilhs, size_t irhs) const
void SetEdge(size_t ilhs, size_t irhs, bool b)
bool MatchAndExplain(GTEST_REFERENCE_TO_CONST_(T) x, MatchResultListener *listener) const
bool Matches(GTEST_REFERENCE_TO_CONST_(T) x) const
GenericValue< UTF8<> > Value
GenericValue with UTF8 encoding.
Definition document.h:2110
os_t os
#define MATCHER_P(name, p0, description)
#define ASSERT_THAT(value, matcher)
#define EXPECT_THAT(value, matcher)
#define EXPECT_CALL(obj, call)
#define ON_CALL(obj, call)
#define EXPECT_DEATH_IF_SUPPORTED(statement, regex)
#define INSTANTIATE_TEST_CASE_P(prefix, test_case_name, generator,...)
#define TEST_P(test_case_name, test_name)
#define GTEST_FLAG_PREFIX_
Definition gtest-port.h:293
#define GTEST_FLAG(name)
#define GTEST_ARRAY_SIZE_(array)
#define GTEST_DISALLOW_ASSIGN_(type)
Definition gtest-port.h:912
#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)
Definition gtest-port.h:917
#define EXPECT_FATAL_FAILURE(statement, substr)
Definition gtest-spi.h:137
#define EXPECT_NONFATAL_FAILURE(statement, substr)
Definition gtest-spi.h:203
#define TEST_F(test_fixture, test_name)
Definition gtest.h:2304
#define EXPECT_EQ(val1, val2)
Definition gtest.h:1954
#define SCOPED_TRACE(message)
Definition gtest.h:2202
#define ASSERT_FALSE(condition)
Definition gtest.h:1904
#define EXPECT_TRUE(condition)
Definition gtest.h:1895
#define TEST(test_case_name, test_name)
Definition gtest.h:2275
#define ADD_FAILURE()
Definition gtest.h:1844
#define ASSERT_TRUE(condition)
Definition gtest.h:1901
#define EXPECT_FALSE(condition)
Definition gtest.h:1898
void diff(const std::string &a, const std::string &b)
Definition jmp.cpp:18
return str
Definition CLI11.hpp:1359
bool operator==(const ConvertibleFromAny &a, const ConvertibleFromAny &b)
ostream & operator<<(ostream &os, const ConvertibleFromAny &a)
ElementMatcherPairs FindBacktrackingMaxBPM(const Graph &g)
const std::string & StringFunction(const std::string &input)
FloatingPointTest< float > FloatTest
ConvertibleToBool IsNotZero(int number)
bool operator==(const IntReferenceWrapper &a, const IntReferenceWrapper &b)
FloatingPointNearTest< float > FloatNearTest
Uncopyable & RefUncopyableFunction(Uncopyable &obj)
PolymorphicMatcher< IsHalfOfMatcher > IsHalfOf()
void AllOfMatches(int num, const Matcher< int > &m)
std::string Explain(const MatcherType &m, const Value &x)
bool IsPositiveIntValue(const IntValue &foo)
std::string Describe(const Matcher< T > &m)
PolymorphicMatcher< DivisibleByImpl > DivisibleBy(int n)
bool ValueIsPositive(const Uncopyable &x)
PolymorphicMatcher< PolymorphicIsEvenImpl > PolymorphicIsEven()
::testing::tuple< long, int > Tuple2
FloatingPointTest< double > DoubleTest
std::string IntToStringFunction(int input)
std::string DescribeNegation(const Matcher< T > &m)
void AnyOfMatches(int num, const Matcher< int > &m)
double & DoubleFunction(double &input)
const int * ReferencingFunction(const int &n)
PolymorphicMatcher< ReferencesBarOrIsZeroImpl > ReferencesBarOrIsZero()
std::string OfType(const std::string &type_name)
FloatingPointNearTest< double > DoubleNearTest
::std::vector< ElementMatcherPair > ElementMatcherPairs
::std::pair< size_t, size_t > ElementMatcherPair
::std::vector< ::std::string > Strings
std::string GetTypeName()
::std::string string
TypeWithSize< 4 >::Int Int32
bool IsReadableTypeName(const std::string &type_name)
GTEST_API_ std::string FormatMatcherDescription(bool negation, const char *matcher_name, const Strings &param_values)
GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix &g)
void ExplainMatchFailureTupleTo(const MatcherTuple &matchers, const ValueTuple &values, ::std::ostream *os)
internal::NotMatcher< InnerMatcher > Not(InnerMatcher m)
internal::Le2Matcher Le()
internal::PointwiseMatcher< TupleMatcher, GTEST_REMOVE_CONST_(Container)> Pointwise(const TupleMatcher &tuple_matcher, const Container &rhs)
Matcher< Lhs > TypedEq(const Rhs &rhs)
Matcher< T > An()
internal::ValueArray1< T1 > Values(T1 v1)
PolymorphicMatcher< internal::StrEqualityMatcher< std::string > > StrCaseEq(const std::string &str)
internal::Ne2Matcher Ne()
PolymorphicMatcher< internal::variant_matcher::VariantMatcher< T > > VariantWith(const Matcher< const T & > &matcher)
internal::FloatingEq2Matcher< double > DoubleEq()
PolymorphicMatcher< internal::NotNullMatcher > NotNull()
PolymorphicMatcher< internal::HasSubstrMatcher< std::string > > HasSubstr(const std::string &substring)
internal::WhenSortedByMatcher< Comparator, ContainerMatcher > WhenSortedBy(const Comparator &comparator, const ContainerMatcher &container_matcher)
InnerMatcher AllArgs(const InnerMatcher &matcher)
PolymorphicMatcher< internal::IsNullMatcher > IsNull()
internal::WhenSortedByMatcher< internal::LessComparator, ContainerMatcher > WhenSorted(const ContainerMatcher &container_matcher)
internal::FloatingEqMatcher< float > NanSensitiveFloatNear(float rhs, float max_abs_error)
internal::EachMatcher< M > Each(M matcher)
internal::Lt2Matcher Lt()
internal::Gt2Matcher Gt()
TYPED_TEST(CodeLocationForTYPEDTEST, Verify)
internal::FloatingEqMatcher< double > DoubleNear(double rhs, double max_abs_error)
PolymorphicMatcher< internal::StrEqualityMatcher< std::string > > StrCaseNe(const std::string &str)
PolymorphicMatcher< internal::MatchesRegexMatcher > MatchesRegex(const internal::RE *regex)
internal::UnorderedElementsAreArrayMatcher< typename ::std::iterator_traits< Iter >::value_type > IsSubsetOf(Iter first, Iter last)
PolymorphicMatcher< internal::PropertyMatcher< Class, PropertyType, PropertyType(Class::*)() const > > Property(PropertyType(Class::*property)() const, const PropertyMatcher &matcher)
PolymorphicAction< internal::ReturnVoidAction > Return()
PolymorphicMatcher< internal::TrulyMatcher< Predicate > > Truly(Predicate pred)
const internal::AnythingMatcher _
PolymorphicMatcher< internal::ContainerEqMatcher< GTEST_REMOVE_CONST_(Container)> > ContainerEq(const Container &rhs)
internal::ParamGenerator< T > Range(T start, T end, IncrementT step)
internal::AllOfResult2< M1, M2 >::type AllOf(M1 m1, M2 m2)
Matcher< T > A()
PolymorphicMatcher< internal::StartsWithMatcher< std::string > > StartsWith(const std::string &prefix)
PolymorphicMatcher< internal::EndsWithMatcher< std::string > > EndsWith(const std::string &suffix)
internal::ResultOfMatcher< Callable > ResultOf(Callable callable, const ResultOfMatcher &matcher)
bool ExplainMatchResult(M matcher, const T &value, MatchResultListener *listener)
internal::ElementsAreArrayMatcher< typename ::std::iterator_traits< Iter >::value_type > ElementsAreArray(Iter first, Iter last)
internal::ElementsAreMatcher< ::testing::tuple<> > ElementsAre()
internal::FloatingEqMatcher< float > FloatNear(float rhs, float max_abs_error)
internal::UnorderedElementsAreMatcher< ::testing::tuple<> > UnorderedElementsAre()
internal::FloatingEq2Matcher< float > NanSensitiveFloatEq()
internal::Ge2Matcher Ge()
PolymorphicMatcher< internal::MatchesRegexMatcher > ContainsRegex(const internal::RE *regex)
internal::UnorderedElementsAreArrayMatcher< typename ::std::iterator_traits< Iter >::value_type > IsSupersetOf(Iter first, Iter last)
internal::KeyMatcher< M > Key(M inner_matcher)
internal::SizeIsMatcher< SizeMatcher > SizeIs(const SizeMatcher &size_matcher)
::std::string PrintToString(const T &value)
internal::ContainsMatcher< M > Contains(M matcher)
internal::Eq2Matcher Eq()
internal::PairMatcher< FirstMatcher, SecondMatcher > Pair(FirstMatcher first_matcher, SecondMatcher second_matcher)
PolymorphicMatcher< Impl > MakePolymorphicMatcher(const Impl &impl)
internal::FloatingEq2Matcher< float > FloatEq()
internal::FloatingEq2Matcher< double > NanSensitiveDoubleEq()
internal::ReferenceWrapper< T > ByRef(T &l_value)
PolymorphicMatcher< internal::FieldMatcher< Class, FieldType > > Field(FieldType Class::*field, const FieldMatcher &matcher)
internal::FloatingEqMatcher< double > NanSensitiveDoubleNear(double rhs, double max_abs_error)
internal::BeginEndDistanceIsMatcher< DistanceMatcher > BeginEndDistanceIs(const DistanceMatcher &distance_matcher)
Matcher< T > MakeMatcher(const MatcherInterface< T > *impl)
internal::UnorderedElementsAreArrayMatcher< typename ::std::iterator_traits< Iter >::value_type > UnorderedElementsAreArray(Iter first, Iter last)
PolymorphicMatcher< internal::StrEqualityMatcher< std::string > > StrEq(const std::string &str)
internal::AnyOfResult2< M1, M2 >::type AnyOf(M1 m1, M2 m2)
Matcher< T > MatcherCast(const M &matcher)
Matcher< T > SafeMatcherCast(const M &polymorphic_matcher)
bool Value(const T &value, M matcher)
internal::UnorderedElementsAreArrayMatcher< typename internal::BoundSecondMatcher< Tuple2Matcher, typename internal::StlContainerView< GTEST_REMOVE_CONST_(RhsContainer)>::type::value_type > > UnorderedPointwise(const Tuple2Matcher &tuple2_matcher, const RhsContainer &rhs_container)
internal::RefMatcher< T & > Ref(T &x)
TYPED_TEST_CASE(CodeLocationForTYPEDTEST, int)
internal::MatcherAsPredicate< M > Matches(M matcher)
internal::PointeeMatcher< InnerMatcher > Pointee(const InnerMatcher &inner_matcher)
PolymorphicMatcher< internal::any_cast_matcher::AnyCastMatcher< T > > AnyWith(const Matcher< const T & > &matcher)
std::string DescribeMatcher(const M &matcher, bool negation=false)
PolymorphicMatcher< internal::StrEqualityMatcher< std::string > > StrNe(const std::string &str)
#define value
Definition pkcs11.h:157
const GenericPointer< typename T::ValueType > & pointer
Definition pointer.h:1181
const GenericPointer< typename T::ValueType > T2 T::AllocatorType & a
Definition pointer.h:1181
#define T(meth, val, expected)
result_type operator()(argument_type input) const
friend bool operator==(const NonImplicitlyConstructibleTypeWithOperatorEq &, int rhs)
friend bool operator==(int lhs, const NonImplicitlyConstructibleTypeWithOperatorEq &)
account_query_db::get_accounts_by_authorizers_params params
CK_ULONG d
char * s