blob: f5ab7c818dad96402566fca0343999fa7d8eb3a2 [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
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
zhanyong.wan53e08c42010-09-14 05:38:21 +000036#include "gmock/gmock-matchers.h"
zhanyong.wan320814a2013-03-01 00:20:30 +000037#include "gmock/gmock-more-matchers.h"
shiqiane35fdd92008-12-10 05:08:54 +000038
39#include <string.h>
zhanyong.wanfb25d532013-07-28 08:24:00 +000040#include <time.h>
zhanyong.wana9a59e02013-03-27 16:14:55 +000041#include <deque>
shiqiane35fdd92008-12-10 05:08:54 +000042#include <functional>
zhanyong.wana862f1d2010-03-15 21:23:04 +000043#include <iostream>
zhanyong.wana9a59e02013-03-27 16:14:55 +000044#include <iterator>
zhanyong.wan616180e2013-06-18 18:49:51 +000045#include <limits>
zhanyong.wan6a896b52009-01-16 01:13:50 +000046#include <list>
47#include <map>
48#include <set>
shiqiane35fdd92008-12-10 05:08:54 +000049#include <sstream>
zhanyong.wan6a896b52009-01-16 01:13:50 +000050#include <string>
zhanyong.wanf5e1ce52009-09-16 07:02:02 +000051#include <utility>
zhanyong.wan6a896b52009-01-16 01:13:50 +000052#include <vector>
zhanyong.wan53e08c42010-09-14 05:38:21 +000053#include "gmock/gmock.h"
54#include "gtest/gtest.h"
55#include "gtest/gtest-spi.h"
shiqiane35fdd92008-12-10 05:08:54 +000056
kosak5b9cbbb2014-11-17 00:28:55 +000057#if GTEST_HAS_STD_FORWARD_LIST_
kosakb6a34882014-03-12 21:06:46 +000058# include <forward_list> // NOLINT
59#endif
60
shiqiane35fdd92008-12-10 05:08:54 +000061namespace testing {
zhanyong.wan4a5330d2009-02-19 00:36:44 +000062
63namespace internal {
vladlosev587c1b32011-05-20 00:42:22 +000064GTEST_API_ string JoinAsTuple(const Strings& fields);
zhanyong.wan4a5330d2009-02-19 00:36:44 +000065} // namespace internal
66
shiqiane35fdd92008-12-10 05:08:54 +000067namespace gmock_matchers_test {
68
zhanyong.wan898725c2011-09-16 16:45:39 +000069using std::greater;
70using std::less;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000071using std::list;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000072using std::make_pair;
zhanyong.wanb5937da2009-07-16 20:26:41 +000073using std::map;
74using std::multimap;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000075using std::multiset;
76using std::ostream;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000077using std::pair;
zhanyong.wan33605ba2010-04-22 23:37:47 +000078using std::set;
shiqiane35fdd92008-12-10 05:08:54 +000079using std::stringstream;
zhanyong.wan33605ba2010-04-22 23:37:47 +000080using std::vector;
shiqiane35fdd92008-12-10 05:08:54 +000081using testing::A;
zhanyong.wanbf550852009-06-09 06:09:53 +000082using testing::AllArgs;
shiqiane35fdd92008-12-10 05:08:54 +000083using testing::AllOf;
84using testing::An;
85using testing::AnyOf;
86using testing::ByRef;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000087using testing::ContainsRegex;
shiqiane35fdd92008-12-10 05:08:54 +000088using testing::DoubleEq;
zhanyong.wan616180e2013-06-18 18:49:51 +000089using testing::DoubleNear;
shiqiane35fdd92008-12-10 05:08:54 +000090using testing::EndsWith;
91using testing::Eq;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000092using testing::ExplainMatchResult;
shiqiane35fdd92008-12-10 05:08:54 +000093using testing::Field;
94using testing::FloatEq;
zhanyong.wan616180e2013-06-18 18:49:51 +000095using testing::FloatNear;
shiqiane35fdd92008-12-10 05:08:54 +000096using testing::Ge;
97using testing::Gt;
98using testing::HasSubstr;
zhanyong.wan320814a2013-03-01 00:20:30 +000099using testing::IsEmpty;
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000100using testing::IsNull;
zhanyong.wanb5937da2009-07-16 20:26:41 +0000101using testing::Key;
shiqiane35fdd92008-12-10 05:08:54 +0000102using testing::Le;
103using testing::Lt;
104using testing::MakeMatcher;
105using testing::MakePolymorphicMatcher;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000106using testing::MatchResultListener;
shiqiane35fdd92008-12-10 05:08:54 +0000107using testing::Matcher;
108using testing::MatcherCast;
109using testing::MatcherInterface;
110using testing::Matches;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000111using testing::MatchesRegex;
shiqiane35fdd92008-12-10 05:08:54 +0000112using testing::NanSensitiveDoubleEq;
zhanyong.wan616180e2013-06-18 18:49:51 +0000113using testing::NanSensitiveDoubleNear;
shiqiane35fdd92008-12-10 05:08:54 +0000114using testing::NanSensitiveFloatEq;
zhanyong.wan616180e2013-06-18 18:49:51 +0000115using testing::NanSensitiveFloatNear;
shiqiane35fdd92008-12-10 05:08:54 +0000116using testing::Ne;
117using testing::Not;
118using testing::NotNull;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000119using testing::Pair;
shiqiane35fdd92008-12-10 05:08:54 +0000120using testing::Pointee;
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000121using testing::Pointwise;
shiqiane35fdd92008-12-10 05:08:54 +0000122using testing::PolymorphicMatcher;
123using testing::Property;
124using testing::Ref;
125using testing::ResultOf;
zhanyong.wana31d9ce2013-03-01 01:50:17 +0000126using testing::SizeIs;
shiqiane35fdd92008-12-10 05:08:54 +0000127using testing::StartsWith;
128using testing::StrCaseEq;
129using testing::StrCaseNe;
130using testing::StrEq;
131using testing::StrNe;
kosak2336e9c2014-07-28 22:57:30 +0000132using testing::StringMatchResultListener;
shiqiane35fdd92008-12-10 05:08:54 +0000133using testing::Truly;
134using testing::TypedEq;
kosak2336e9c2014-07-28 22:57:30 +0000135using testing::UnorderedPointwise;
zhanyong.wanb8243162009-06-04 05:48:20 +0000136using testing::Value;
zhanyong.wan898725c2011-09-16 16:45:39 +0000137using testing::WhenSorted;
138using testing::WhenSortedBy;
shiqiane35fdd92008-12-10 05:08:54 +0000139using testing::_;
kosak2336e9c2014-07-28 22:57:30 +0000140using testing::get;
zhanyong.wana862f1d2010-03-15 21:23:04 +0000141using testing::internal::DummyMatchResultListener;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000142using testing::internal::ElementMatcherPair;
143using testing::internal::ElementMatcherPairs;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000144using testing::internal::ExplainMatchFailureTupleTo;
shiqiane35fdd92008-12-10 05:08:54 +0000145using testing::internal::FloatingEqMatcher;
zhanyong.wanb4140802010-06-08 22:53:57 +0000146using testing::internal::FormatMatcherDescription;
zhanyong.wan736baa82010-09-27 17:44:16 +0000147using testing::internal::IsReadableTypeName;
zhanyong.wan4a5330d2009-02-19 00:36:44 +0000148using testing::internal::JoinAsTuple;
kosakf6df4c62015-07-19 22:58:38 +0000149using testing::internal::linked_ptr;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000150using testing::internal::MatchMatrix;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000151using testing::internal::RE;
kosakf6df4c62015-07-19 22:58:38 +0000152using testing::internal::scoped_ptr;
zhanyong.wana862f1d2010-03-15 21:23:04 +0000153using testing::internal::StreamMatchResultListener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000154using testing::internal::Strings;
vladlosev79b83502009-11-18 00:43:37 +0000155using testing::internal::linked_ptr;
vladloseve56daa72009-11-18 01:08:08 +0000156using testing::internal::scoped_ptr;
shiqiane35fdd92008-12-10 05:08:54 +0000157using testing::internal::string;
kosak2336e9c2014-07-28 22:57:30 +0000158using testing::make_tuple;
159using testing::tuple;
shiqiane35fdd92008-12-10 05:08:54 +0000160
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000161// For testing ExplainMatchResultTo().
162class GreaterThanMatcher : public MatcherInterface<int> {
163 public:
164 explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
165
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000166 virtual void DescribeTo(ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000167 *os << "is > " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000168 }
169
zhanyong.wandb22c222010-01-28 21:52:29 +0000170 virtual bool MatchAndExplain(int lhs,
171 MatchResultListener* listener) const {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000172 const int diff = lhs - rhs_;
173 if (diff > 0) {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000174 *listener << "which is " << diff << " more than " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000175 } else if (diff == 0) {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000176 *listener << "which is the same as " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000177 } else {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000178 *listener << "which is " << -diff << " less than " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000179 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000180
181 return lhs > rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000182 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000183
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000184 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000185 int rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000186};
187
188Matcher<int> GreaterThan(int n) {
189 return MakeMatcher(new GreaterThanMatcher(n));
190}
191
Nico Weber09fd5b32017-05-15 17:07:03 -0400192std::string OfType(const std::string& type_name) {
zhanyong.wan736baa82010-09-27 17:44:16 +0000193#if GTEST_HAS_RTTI
194 return " (of type " + type_name + ")";
195#else
196 return "";
197#endif
198}
199
shiqiane35fdd92008-12-10 05:08:54 +0000200// Returns the description of the given matcher.
201template <typename T>
Nico Weber09fd5b32017-05-15 17:07:03 -0400202std::string Describe(const Matcher<T>& m) {
shiqiane35fdd92008-12-10 05:08:54 +0000203 stringstream ss;
204 m.DescribeTo(&ss);
205 return ss.str();
206}
207
208// Returns the description of the negation of the given matcher.
209template <typename T>
Nico Weber09fd5b32017-05-15 17:07:03 -0400210std::string DescribeNegation(const Matcher<T>& m) {
shiqiane35fdd92008-12-10 05:08:54 +0000211 stringstream ss;
212 m.DescribeNegationTo(&ss);
213 return ss.str();
214}
215
216// Returns the reason why x matches, or doesn't match, m.
217template <typename MatcherType, typename Value>
Nico Weber09fd5b32017-05-15 17:07:03 -0400218std::string Explain(const MatcherType& m, const Value& x) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000219 StringMatchResultListener listener;
220 ExplainMatchResult(m, x, &listener);
221 return listener.str();
shiqiane35fdd92008-12-10 05:08:54 +0000222}
223
zhanyong.wana862f1d2010-03-15 21:23:04 +0000224TEST(MatchResultListenerTest, StreamingWorks) {
225 StringMatchResultListener listener;
226 listener << "hi" << 5;
227 EXPECT_EQ("hi5", listener.str());
228
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000229 listener.Clear();
230 EXPECT_EQ("", listener.str());
231
232 listener << 42;
233 EXPECT_EQ("42", listener.str());
234
zhanyong.wana862f1d2010-03-15 21:23:04 +0000235 // Streaming shouldn't crash when the underlying ostream is NULL.
236 DummyMatchResultListener dummy;
237 dummy << "hi" << 5;
238}
239
240TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
241 EXPECT_TRUE(DummyMatchResultListener().stream() == NULL);
242 EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL);
243
244 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
245}
246
247TEST(MatchResultListenerTest, IsInterestedWorks) {
248 EXPECT_TRUE(StringMatchResultListener().IsInterested());
249 EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
250
251 EXPECT_FALSE(DummyMatchResultListener().IsInterested());
252 EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested());
253}
254
shiqiane35fdd92008-12-10 05:08:54 +0000255// Makes sure that the MatcherInterface<T> interface doesn't
256// change.
257class EvenMatcherImpl : public MatcherInterface<int> {
258 public:
zhanyong.wandb22c222010-01-28 21:52:29 +0000259 virtual bool MatchAndExplain(int x,
260 MatchResultListener* /* listener */) const {
261 return x % 2 == 0;
262 }
shiqiane35fdd92008-12-10 05:08:54 +0000263
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000264 virtual void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +0000265 *os << "is an even number";
266 }
267
268 // We deliberately don't define DescribeNegationTo() and
269 // ExplainMatchResultTo() here, to make sure the definition of these
270 // two methods is optional.
271};
272
zhanyong.wana862f1d2010-03-15 21:23:04 +0000273// Makes sure that the MatcherInterface API doesn't change.
274TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
shiqiane35fdd92008-12-10 05:08:54 +0000275 EvenMatcherImpl m;
276}
277
zhanyong.wan82113312010-01-08 21:55:40 +0000278// Tests implementing a monomorphic matcher using MatchAndExplain().
279
280class NewEvenMatcherImpl : public MatcherInterface<int> {
281 public:
282 virtual bool MatchAndExplain(int x, MatchResultListener* listener) const {
283 const bool match = x % 2 == 0;
284 // Verifies that we can stream to a listener directly.
285 *listener << "value % " << 2;
286 if (listener->stream() != NULL) {
287 // Verifies that we can stream to a listener's underlying stream
288 // too.
289 *listener->stream() << " == " << (x % 2);
290 }
291 return match;
292 }
293
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000294 virtual void DescribeTo(ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000295 *os << "is an even number";
296 }
297};
298
299TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
300 Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
301 EXPECT_TRUE(m.Matches(2));
302 EXPECT_FALSE(m.Matches(3));
303 EXPECT_EQ("value % 2 == 0", Explain(m, 2));
304 EXPECT_EQ("value % 2 == 1", Explain(m, 3));
305}
306
shiqiane35fdd92008-12-10 05:08:54 +0000307// Tests default-constructing a matcher.
308TEST(MatcherTest, CanBeDefaultConstructed) {
309 Matcher<double> m;
310}
311
312// Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
313TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
314 const MatcherInterface<int>* impl = new EvenMatcherImpl;
315 Matcher<int> m(impl);
316 EXPECT_TRUE(m.Matches(4));
317 EXPECT_FALSE(m.Matches(5));
318}
319
320// Tests that value can be used in place of Eq(value).
321TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
322 Matcher<int> m1 = 5;
323 EXPECT_TRUE(m1.Matches(5));
324 EXPECT_FALSE(m1.Matches(6));
325}
326
327// Tests that NULL can be used in place of Eq(NULL).
328TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
329 Matcher<int*> m1 = NULL;
330 EXPECT_TRUE(m1.Matches(NULL));
331 int n = 0;
332 EXPECT_FALSE(m1.Matches(&n));
333}
334
335// Tests that matchers are copyable.
336TEST(MatcherTest, IsCopyable) {
337 // Tests the copy constructor.
338 Matcher<bool> m1 = Eq(false);
339 EXPECT_TRUE(m1.Matches(false));
340 EXPECT_FALSE(m1.Matches(true));
341
342 // Tests the assignment operator.
343 m1 = Eq(true);
344 EXPECT_TRUE(m1.Matches(true));
345 EXPECT_FALSE(m1.Matches(false));
346}
347
348// Tests that Matcher<T>::DescribeTo() calls
349// MatcherInterface<T>::DescribeTo().
350TEST(MatcherTest, CanDescribeItself) {
351 EXPECT_EQ("is an even number",
352 Describe(Matcher<int>(new EvenMatcherImpl)));
353}
354
zhanyong.wan82113312010-01-08 21:55:40 +0000355// Tests Matcher<T>::MatchAndExplain().
356TEST(MatcherTest, MatchAndExplain) {
357 Matcher<int> m = GreaterThan(0);
zhanyong.wan34b034c2010-03-05 21:23:23 +0000358 StringMatchResultListener listener1;
zhanyong.wan82113312010-01-08 21:55:40 +0000359 EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000360 EXPECT_EQ("which is 42 more than 0", listener1.str());
zhanyong.wan82113312010-01-08 21:55:40 +0000361
zhanyong.wan34b034c2010-03-05 21:23:23 +0000362 StringMatchResultListener listener2;
zhanyong.wan82113312010-01-08 21:55:40 +0000363 EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000364 EXPECT_EQ("which is 9 less than 0", listener2.str());
zhanyong.wan82113312010-01-08 21:55:40 +0000365}
366
shiqiane35fdd92008-12-10 05:08:54 +0000367// Tests that a C-string literal can be implicitly converted to a
368// Matcher<string> or Matcher<const string&>.
369TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
370 Matcher<string> m1 = "hi";
371 EXPECT_TRUE(m1.Matches("hi"));
372 EXPECT_FALSE(m1.Matches("hello"));
373
374 Matcher<const string&> m2 = "hi";
375 EXPECT_TRUE(m2.Matches("hi"));
376 EXPECT_FALSE(m2.Matches("hello"));
377}
378
379// Tests that a string object can be implicitly converted to a
380// Matcher<string> or Matcher<const string&>.
381TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
382 Matcher<string> m1 = string("hi");
383 EXPECT_TRUE(m1.Matches("hi"));
384 EXPECT_FALSE(m1.Matches("hello"));
385
386 Matcher<const string&> m2 = string("hi");
387 EXPECT_TRUE(m2.Matches("hi"));
388 EXPECT_FALSE(m2.Matches("hello"));
389}
390
zhanyong.wan1f122a02013-03-25 16:27:03 +0000391#if GTEST_HAS_STRING_PIECE_
392// Tests that a C-string literal can be implicitly converted to a
393// Matcher<StringPiece> or Matcher<const StringPiece&>.
394TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
395 Matcher<StringPiece> m1 = "cats";
396 EXPECT_TRUE(m1.Matches("cats"));
397 EXPECT_FALSE(m1.Matches("dogs"));
398
399 Matcher<const StringPiece&> m2 = "cats";
400 EXPECT_TRUE(m2.Matches("cats"));
401 EXPECT_FALSE(m2.Matches("dogs"));
402}
403
404// Tests that a string object can be implicitly converted to a
405// Matcher<StringPiece> or Matcher<const StringPiece&>.
406TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromString) {
407 Matcher<StringPiece> m1 = string("cats");
408 EXPECT_TRUE(m1.Matches("cats"));
409 EXPECT_FALSE(m1.Matches("dogs"));
410
411 Matcher<const StringPiece&> m2 = string("cats");
412 EXPECT_TRUE(m2.Matches("cats"));
413 EXPECT_FALSE(m2.Matches("dogs"));
414}
415
416// Tests that a StringPiece object can be implicitly converted to a
417// Matcher<StringPiece> or Matcher<const StringPiece&>.
418TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromStringPiece) {
419 Matcher<StringPiece> m1 = StringPiece("cats");
420 EXPECT_TRUE(m1.Matches("cats"));
421 EXPECT_FALSE(m1.Matches("dogs"));
422
423 Matcher<const StringPiece&> m2 = StringPiece("cats");
424 EXPECT_TRUE(m2.Matches("cats"));
425 EXPECT_FALSE(m2.Matches("dogs"));
426}
427#endif // GTEST_HAS_STRING_PIECE_
428
shiqiane35fdd92008-12-10 05:08:54 +0000429// Tests that MakeMatcher() constructs a Matcher<T> from a
430// MatcherInterface* without requiring the user to explicitly
431// write the type.
432TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
433 const MatcherInterface<int>* dummy_impl = NULL;
434 Matcher<int> m = MakeMatcher(dummy_impl);
435}
436
zhanyong.wan82113312010-01-08 21:55:40 +0000437// Tests that MakePolymorphicMatcher() can construct a polymorphic
438// matcher from its implementation using the old API.
zhanyong.wan33605ba2010-04-22 23:37:47 +0000439const int g_bar = 1;
shiqiane35fdd92008-12-10 05:08:54 +0000440class ReferencesBarOrIsZeroImpl {
441 public:
442 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +0000443 bool MatchAndExplain(const T& x,
444 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000445 const void* p = &x;
zhanyong.wan33605ba2010-04-22 23:37:47 +0000446 return p == &g_bar || x == 0;
shiqiane35fdd92008-12-10 05:08:54 +0000447 }
448
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000449 void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
shiqiane35fdd92008-12-10 05:08:54 +0000450
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000451 void DescribeNegationTo(ostream* os) const {
zhanyong.wan33605ba2010-04-22 23:37:47 +0000452 *os << "doesn't reference g_bar and is not zero";
shiqiane35fdd92008-12-10 05:08:54 +0000453 }
454};
455
456// This function verifies that MakePolymorphicMatcher() returns a
457// PolymorphicMatcher<T> where T is the argument's type.
458PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
459 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
460}
461
zhanyong.wan82113312010-01-08 21:55:40 +0000462TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
shiqiane35fdd92008-12-10 05:08:54 +0000463 // Using a polymorphic matcher to match a reference type.
464 Matcher<const int&> m1 = ReferencesBarOrIsZero();
465 EXPECT_TRUE(m1.Matches(0));
466 // Verifies that the identity of a by-reference argument is preserved.
zhanyong.wan33605ba2010-04-22 23:37:47 +0000467 EXPECT_TRUE(m1.Matches(g_bar));
shiqiane35fdd92008-12-10 05:08:54 +0000468 EXPECT_FALSE(m1.Matches(1));
zhanyong.wan33605ba2010-04-22 23:37:47 +0000469 EXPECT_EQ("g_bar or zero", Describe(m1));
shiqiane35fdd92008-12-10 05:08:54 +0000470
471 // Using a polymorphic matcher to match a value type.
472 Matcher<double> m2 = ReferencesBarOrIsZero();
473 EXPECT_TRUE(m2.Matches(0.0));
474 EXPECT_FALSE(m2.Matches(0.1));
zhanyong.wan33605ba2010-04-22 23:37:47 +0000475 EXPECT_EQ("g_bar or zero", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +0000476}
477
zhanyong.wan82113312010-01-08 21:55:40 +0000478// Tests implementing a polymorphic matcher using MatchAndExplain().
479
480class PolymorphicIsEvenImpl {
481 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000482 void DescribeTo(ostream* os) const { *os << "is even"; }
zhanyong.wan82113312010-01-08 21:55:40 +0000483
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000484 void DescribeNegationTo(ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000485 *os << "is odd";
486 }
zhanyong.wan82113312010-01-08 21:55:40 +0000487
zhanyong.wandb22c222010-01-28 21:52:29 +0000488 template <typename T>
489 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
490 // Verifies that we can stream to the listener directly.
491 *listener << "% " << 2;
492 if (listener->stream() != NULL) {
493 // Verifies that we can stream to the listener's underlying stream
494 // too.
495 *listener->stream() << " == " << (x % 2);
496 }
497 return (x % 2) == 0;
zhanyong.wan82113312010-01-08 21:55:40 +0000498 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000499};
zhanyong.wan82113312010-01-08 21:55:40 +0000500
501PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
502 return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
503}
504
505TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
506 // Using PolymorphicIsEven() as a Matcher<int>.
507 const Matcher<int> m1 = PolymorphicIsEven();
508 EXPECT_TRUE(m1.Matches(42));
509 EXPECT_FALSE(m1.Matches(43));
510 EXPECT_EQ("is even", Describe(m1));
511
512 const Matcher<int> not_m1 = Not(m1);
513 EXPECT_EQ("is odd", Describe(not_m1));
514
515 EXPECT_EQ("% 2 == 0", Explain(m1, 42));
516
517 // Using PolymorphicIsEven() as a Matcher<char>.
518 const Matcher<char> m2 = PolymorphicIsEven();
519 EXPECT_TRUE(m2.Matches('\x42'));
520 EXPECT_FALSE(m2.Matches('\x43'));
521 EXPECT_EQ("is even", Describe(m2));
522
523 const Matcher<char> not_m2 = Not(m2);
524 EXPECT_EQ("is odd", Describe(not_m2));
525
526 EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
527}
528
shiqiane35fdd92008-12-10 05:08:54 +0000529// Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
530TEST(MatcherCastTest, FromPolymorphicMatcher) {
531 Matcher<int> m = MatcherCast<int>(Eq(5));
532 EXPECT_TRUE(m.Matches(5));
533 EXPECT_FALSE(m.Matches(6));
534}
535
536// For testing casting matchers between compatible types.
537class IntValue {
538 public:
539 // An int can be statically (although not implicitly) cast to a
540 // IntValue.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000541 explicit IntValue(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +0000542
543 int value() const { return value_; }
544 private:
545 int value_;
546};
547
548// For testing casting matchers between compatible types.
549bool IsPositiveIntValue(const IntValue& foo) {
550 return foo.value() > 0;
551}
552
553// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
554// can be statically converted to U.
555TEST(MatcherCastTest, FromCompatibleType) {
556 Matcher<double> m1 = Eq(2.0);
557 Matcher<int> m2 = MatcherCast<int>(m1);
558 EXPECT_TRUE(m2.Matches(2));
559 EXPECT_FALSE(m2.Matches(3));
560
561 Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
562 Matcher<int> m4 = MatcherCast<int>(m3);
563 // In the following, the arguments 1 and 0 are statically converted
564 // to IntValue objects, and then tested by the IsPositiveIntValue()
565 // predicate.
566 EXPECT_TRUE(m4.Matches(1));
567 EXPECT_FALSE(m4.Matches(0));
568}
569
570// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
571TEST(MatcherCastTest, FromConstReferenceToNonReference) {
572 Matcher<const int&> m1 = Eq(0);
573 Matcher<int> m2 = MatcherCast<int>(m1);
574 EXPECT_TRUE(m2.Matches(0));
575 EXPECT_FALSE(m2.Matches(1));
576}
577
578// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
579TEST(MatcherCastTest, FromReferenceToNonReference) {
580 Matcher<int&> m1 = Eq(0);
581 Matcher<int> m2 = MatcherCast<int>(m1);
582 EXPECT_TRUE(m2.Matches(0));
583 EXPECT_FALSE(m2.Matches(1));
584}
585
586// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
587TEST(MatcherCastTest, FromNonReferenceToConstReference) {
588 Matcher<int> m1 = Eq(0);
589 Matcher<const int&> m2 = MatcherCast<const int&>(m1);
590 EXPECT_TRUE(m2.Matches(0));
591 EXPECT_FALSE(m2.Matches(1));
592}
593
594// Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
595TEST(MatcherCastTest, FromNonReferenceToReference) {
596 Matcher<int> m1 = Eq(0);
597 Matcher<int&> m2 = MatcherCast<int&>(m1);
598 int n = 0;
599 EXPECT_TRUE(m2.Matches(n));
600 n = 1;
601 EXPECT_FALSE(m2.Matches(n));
602}
603
604// Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
605TEST(MatcherCastTest, FromSameType) {
606 Matcher<int> m1 = Eq(0);
607 Matcher<int> m2 = MatcherCast<int>(m1);
608 EXPECT_TRUE(m2.Matches(0));
609 EXPECT_FALSE(m2.Matches(1));
610}
611
kosak506340a2014-11-17 01:47:54 +0000612// Implicitly convertible from any type.
jgm79a367e2012-04-10 16:02:11 +0000613struct ConvertibleFromAny {
614 ConvertibleFromAny(int a_value) : value(a_value) {}
615 template <typename T>
mazong1123531bf5c2016-07-14 13:44:46 +0800616 explicit ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
jgm79a367e2012-04-10 16:02:11 +0000617 ADD_FAILURE() << "Conversion constructor called";
618 }
619 int value;
620};
621
622bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
623 return a.value == b.value;
624}
625
626ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
627 return os << a.value;
628}
629
630TEST(MatcherCastTest, ConversionConstructorIsUsed) {
631 Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
632 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
633 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
634}
635
636TEST(MatcherCastTest, FromConvertibleFromAny) {
637 Matcher<ConvertibleFromAny> m =
638 MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
639 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
640 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
641}
642
kosak5f2a6ca2013-12-03 01:43:07 +0000643struct IntReferenceWrapper {
644 IntReferenceWrapper(const int& a_value) : value(&a_value) {}
645 const int* value;
646};
647
648bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
649 return a.value == b.value;
650}
651
652TEST(MatcherCastTest, ValueIsNotCopied) {
653 int n = 42;
654 Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
655 // Verify that the matcher holds a reference to n, not to its temporary copy.
656 EXPECT_TRUE(m.Matches(n));
657}
658
billydonahue1f5fdea2014-05-19 17:54:51 +0000659class Base {
660 public:
661 virtual ~Base() {}
662 Base() {}
663 private:
664 GTEST_DISALLOW_COPY_AND_ASSIGN_(Base);
665};
666
667class Derived : public Base {
668 public:
669 Derived() : Base() {}
670 int i;
671};
672
673class OtherDerived : public Base {};
zhanyong.wan18490652009-05-11 18:54:08 +0000674
675// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
676TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
677 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
678 EXPECT_TRUE(m2.Matches(' '));
679 EXPECT_FALSE(m2.Matches('\n'));
680}
681
zhanyong.wan16cf4732009-05-14 20:55:30 +0000682// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
683// T and U are arithmetic types and T can be losslessly converted to
684// U.
685TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
zhanyong.wan18490652009-05-11 18:54:08 +0000686 Matcher<double> m1 = DoubleEq(1.0);
zhanyong.wan16cf4732009-05-14 20:55:30 +0000687 Matcher<float> m2 = SafeMatcherCast<float>(m1);
688 EXPECT_TRUE(m2.Matches(1.0f));
689 EXPECT_FALSE(m2.Matches(2.0f));
690
691 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
692 EXPECT_TRUE(m3.Matches('a'));
693 EXPECT_FALSE(m3.Matches('b'));
zhanyong.wan18490652009-05-11 18:54:08 +0000694}
695
696// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
697// are pointers or references to a derived and a base class, correspondingly.
698TEST(SafeMatcherCastTest, FromBaseClass) {
699 Derived d, d2;
700 Matcher<Base*> m1 = Eq(&d);
701 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
702 EXPECT_TRUE(m2.Matches(&d));
703 EXPECT_FALSE(m2.Matches(&d2));
704
705 Matcher<Base&> m3 = Ref(d);
706 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
707 EXPECT_TRUE(m4.Matches(d));
708 EXPECT_FALSE(m4.Matches(d2));
709}
710
711// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
712TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
713 int n = 0;
714 Matcher<const int&> m1 = Ref(n);
715 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
716 int n1 = 0;
717 EXPECT_TRUE(m2.Matches(n));
718 EXPECT_FALSE(m2.Matches(n1));
719}
720
721// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
722TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
723 Matcher<int> m1 = Eq(0);
724 Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
725 EXPECT_TRUE(m2.Matches(0));
726 EXPECT_FALSE(m2.Matches(1));
727}
728
729// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
730TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
731 Matcher<int> m1 = Eq(0);
732 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
733 int n = 0;
734 EXPECT_TRUE(m2.Matches(n));
735 n = 1;
736 EXPECT_FALSE(m2.Matches(n));
737}
738
739// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
740TEST(SafeMatcherCastTest, FromSameType) {
741 Matcher<int> m1 = Eq(0);
742 Matcher<int> m2 = SafeMatcherCast<int>(m1);
743 EXPECT_TRUE(m2.Matches(0));
744 EXPECT_FALSE(m2.Matches(1));
745}
746
jgm79a367e2012-04-10 16:02:11 +0000747TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
748 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
749 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
750 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
751}
752
753TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
754 Matcher<ConvertibleFromAny> m =
755 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
756 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
757 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
758}
759
kosak5f2a6ca2013-12-03 01:43:07 +0000760TEST(SafeMatcherCastTest, ValueIsNotCopied) {
761 int n = 42;
762 Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
763 // Verify that the matcher holds a reference to n, not to its temporary copy.
764 EXPECT_TRUE(m.Matches(n));
765}
766
kosak9b1a9442015-04-28 23:06:58 +0000767TEST(ExpectThat, TakesLiterals) {
768 EXPECT_THAT(1, 1);
769 EXPECT_THAT(1.0, 1.0);
770 EXPECT_THAT(string(), "");
771}
772
773TEST(ExpectThat, TakesFunctions) {
774 struct Helper {
775 static void Func() {}
776 };
777 void (*func)() = Helper::Func;
778 EXPECT_THAT(func, Helper::Func);
779 EXPECT_THAT(func, &Helper::Func);
780}
781
shiqiane35fdd92008-12-10 05:08:54 +0000782// Tests that A<T>() matches any value of type T.
783TEST(ATest, MatchesAnyValue) {
784 // Tests a matcher for a value type.
785 Matcher<double> m1 = A<double>();
786 EXPECT_TRUE(m1.Matches(91.43));
787 EXPECT_TRUE(m1.Matches(-15.32));
788
789 // Tests a matcher for a reference type.
790 int a = 2;
791 int b = -6;
792 Matcher<int&> m2 = A<int&>();
793 EXPECT_TRUE(m2.Matches(a));
794 EXPECT_TRUE(m2.Matches(b));
795}
796
zhanyong.wanf4274522013-04-24 02:49:43 +0000797TEST(ATest, WorksForDerivedClass) {
798 Base base;
799 Derived derived;
800 EXPECT_THAT(&base, A<Base*>());
801 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
802 EXPECT_THAT(&derived, A<Base*>());
803 EXPECT_THAT(&derived, A<Derived*>());
804}
805
shiqiane35fdd92008-12-10 05:08:54 +0000806// Tests that A<T>() describes itself properly.
807TEST(ATest, CanDescribeSelf) {
808 EXPECT_EQ("is anything", Describe(A<bool>()));
809}
810
811// Tests that An<T>() matches any value of type T.
812TEST(AnTest, MatchesAnyValue) {
813 // Tests a matcher for a value type.
814 Matcher<int> m1 = An<int>();
815 EXPECT_TRUE(m1.Matches(9143));
816 EXPECT_TRUE(m1.Matches(-1532));
817
818 // Tests a matcher for a reference type.
819 int a = 2;
820 int b = -6;
821 Matcher<int&> m2 = An<int&>();
822 EXPECT_TRUE(m2.Matches(a));
823 EXPECT_TRUE(m2.Matches(b));
824}
825
826// Tests that An<T>() describes itself properly.
827TEST(AnTest, CanDescribeSelf) {
828 EXPECT_EQ("is anything", Describe(An<int>()));
829}
830
831// Tests that _ can be used as a matcher for any type and matches any
832// value of that type.
833TEST(UnderscoreTest, MatchesAnyValue) {
834 // Uses _ as a matcher for a value type.
835 Matcher<int> m1 = _;
836 EXPECT_TRUE(m1.Matches(123));
837 EXPECT_TRUE(m1.Matches(-242));
838
839 // Uses _ as a matcher for a reference type.
840 bool a = false;
841 const bool b = true;
842 Matcher<const bool&> m2 = _;
843 EXPECT_TRUE(m2.Matches(a));
844 EXPECT_TRUE(m2.Matches(b));
845}
846
847// Tests that _ describes itself properly.
848TEST(UnderscoreTest, CanDescribeSelf) {
849 Matcher<int> m = _;
850 EXPECT_EQ("is anything", Describe(m));
851}
852
853// Tests that Eq(x) matches any value equal to x.
854TEST(EqTest, MatchesEqualValue) {
855 // 2 C-strings with same content but different addresses.
856 const char a1[] = "hi";
857 const char a2[] = "hi";
858
859 Matcher<const char*> m1 = Eq(a1);
860 EXPECT_TRUE(m1.Matches(a1));
861 EXPECT_FALSE(m1.Matches(a2));
862}
863
864// Tests that Eq(v) describes itself properly.
865
866class Unprintable {
867 public:
868 Unprintable() : c_('a') {}
869
shiqiane35fdd92008-12-10 05:08:54 +0000870 private:
871 char c_;
872};
873
mazong1123dc2dbf12016-07-14 16:49:42 +0800874inline bool operator==(const Unprintable& /* lhs */,
875 const Unprintable& /* rhs */) {
876 return true;
877}
mazong1123531bf5c2016-07-14 13:44:46 +0800878
shiqiane35fdd92008-12-10 05:08:54 +0000879TEST(EqTest, CanDescribeSelf) {
880 Matcher<Unprintable> m = Eq(Unprintable());
881 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
882}
883
884// Tests that Eq(v) can be used to match any type that supports
885// comparing with type T, where T is v's type.
886TEST(EqTest, IsPolymorphic) {
887 Matcher<int> m1 = Eq(1);
888 EXPECT_TRUE(m1.Matches(1));
889 EXPECT_FALSE(m1.Matches(2));
890
891 Matcher<char> m2 = Eq(1);
892 EXPECT_TRUE(m2.Matches('\1'));
893 EXPECT_FALSE(m2.Matches('a'));
894}
895
896// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
897TEST(TypedEqTest, ChecksEqualityForGivenType) {
898 Matcher<char> m1 = TypedEq<char>('a');
899 EXPECT_TRUE(m1.Matches('a'));
900 EXPECT_FALSE(m1.Matches('b'));
901
902 Matcher<int> m2 = TypedEq<int>(6);
903 EXPECT_TRUE(m2.Matches(6));
904 EXPECT_FALSE(m2.Matches(7));
905}
906
907// Tests that TypedEq(v) describes itself properly.
908TEST(TypedEqTest, CanDescribeSelf) {
909 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
910}
911
912// Tests that TypedEq<T>(v) has type Matcher<T>.
913
914// Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
915// is a "bare" type (i.e. not in the form of const U or U&). If v's
916// type is not T, the compiler will generate a message about
917// "undefined referece".
918template <typename T>
919struct Type {
zhanyong.wan32de5f52009-12-23 00:13:23 +0000920 static bool IsTypeOf(const T& /* v */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000921
922 template <typename T2>
923 static void IsTypeOf(T2 v);
924};
925
926TEST(TypedEqTest, HasSpecifiedType) {
927 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
928 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
929 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
930}
931
932// Tests that Ge(v) matches anything >= v.
933TEST(GeTest, ImplementsGreaterThanOrEqual) {
934 Matcher<int> m1 = Ge(0);
935 EXPECT_TRUE(m1.Matches(1));
936 EXPECT_TRUE(m1.Matches(0));
937 EXPECT_FALSE(m1.Matches(-1));
938}
939
940// Tests that Ge(v) describes itself properly.
941TEST(GeTest, CanDescribeSelf) {
942 Matcher<int> m = Ge(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000943 EXPECT_EQ("is >= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000944}
945
946// Tests that Gt(v) matches anything > v.
947TEST(GtTest, ImplementsGreaterThan) {
948 Matcher<double> m1 = Gt(0);
949 EXPECT_TRUE(m1.Matches(1.0));
950 EXPECT_FALSE(m1.Matches(0.0));
951 EXPECT_FALSE(m1.Matches(-1.0));
952}
953
954// Tests that Gt(v) describes itself properly.
955TEST(GtTest, CanDescribeSelf) {
956 Matcher<int> m = Gt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000957 EXPECT_EQ("is > 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000958}
959
960// Tests that Le(v) matches anything <= v.
961TEST(LeTest, ImplementsLessThanOrEqual) {
962 Matcher<char> m1 = Le('b');
963 EXPECT_TRUE(m1.Matches('a'));
964 EXPECT_TRUE(m1.Matches('b'));
965 EXPECT_FALSE(m1.Matches('c'));
966}
967
968// Tests that Le(v) describes itself properly.
969TEST(LeTest, CanDescribeSelf) {
970 Matcher<int> m = Le(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000971 EXPECT_EQ("is <= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000972}
973
974// Tests that Lt(v) matches anything < v.
975TEST(LtTest, ImplementsLessThan) {
Nico Weber09fd5b32017-05-15 17:07:03 -0400976 Matcher<const std::string&> m1 = Lt("Hello");
shiqiane35fdd92008-12-10 05:08:54 +0000977 EXPECT_TRUE(m1.Matches("Abc"));
978 EXPECT_FALSE(m1.Matches("Hello"));
979 EXPECT_FALSE(m1.Matches("Hello, world!"));
980}
981
982// Tests that Lt(v) describes itself properly.
983TEST(LtTest, CanDescribeSelf) {
984 Matcher<int> m = Lt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000985 EXPECT_EQ("is < 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000986}
987
988// Tests that Ne(v) matches anything != v.
989TEST(NeTest, ImplementsNotEqual) {
990 Matcher<int> m1 = Ne(0);
991 EXPECT_TRUE(m1.Matches(1));
992 EXPECT_TRUE(m1.Matches(-1));
993 EXPECT_FALSE(m1.Matches(0));
994}
995
996// Tests that Ne(v) describes itself properly.
997TEST(NeTest, CanDescribeSelf) {
998 Matcher<int> m = Ne(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000999 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001000}
1001
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001002// Tests that IsNull() matches any NULL pointer of any type.
1003TEST(IsNullTest, MatchesNullPointer) {
1004 Matcher<int*> m1 = IsNull();
1005 int* p1 = NULL;
1006 int n = 0;
1007 EXPECT_TRUE(m1.Matches(p1));
1008 EXPECT_FALSE(m1.Matches(&n));
1009
1010 Matcher<const char*> m2 = IsNull();
1011 const char* p2 = NULL;
1012 EXPECT_TRUE(m2.Matches(p2));
1013 EXPECT_FALSE(m2.Matches("hi"));
1014
zhanyong.wan95b12332009-09-25 18:55:50 +00001015#if !GTEST_OS_SYMBIAN
1016 // Nokia's Symbian compiler generates:
1017 // gmock-matchers.h: ambiguous access to overloaded function
1018 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
1019 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
1020 // MatcherInterface<void *> *)'
1021 // gmock-matchers.h: (point of instantiation: 'testing::
1022 // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
1023 // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001024 Matcher<void*> m3 = IsNull();
1025 void* p3 = NULL;
1026 EXPECT_TRUE(m3.Matches(p3));
1027 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
zhanyong.wan95b12332009-09-25 18:55:50 +00001028#endif
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001029}
1030
vladlosev79b83502009-11-18 00:43:37 +00001031TEST(IsNullTest, LinkedPtr) {
1032 const Matcher<linked_ptr<int> > m = IsNull();
1033 const linked_ptr<int> null_p;
1034 const linked_ptr<int> non_null_p(new int);
1035
1036 EXPECT_TRUE(m.Matches(null_p));
1037 EXPECT_FALSE(m.Matches(non_null_p));
1038}
1039
1040TEST(IsNullTest, ReferenceToConstLinkedPtr) {
1041 const Matcher<const linked_ptr<double>&> m = IsNull();
1042 const linked_ptr<double> null_p;
1043 const linked_ptr<double> non_null_p(new double);
1044
1045 EXPECT_TRUE(m.Matches(null_p));
1046 EXPECT_FALSE(m.Matches(non_null_p));
1047}
1048
Mark Mentovaia0435dc2015-10-12 17:57:51 -04001049#if GTEST_HAS_STD_FUNCTION_
kosak6305ff52015-04-28 22:36:31 +00001050TEST(IsNullTest, StdFunction) {
1051 const Matcher<std::function<void()>> m = IsNull();
1052
1053 EXPECT_TRUE(m.Matches(std::function<void()>()));
1054 EXPECT_FALSE(m.Matches([]{}));
1055}
Mark Mentovaia0435dc2015-10-12 17:57:51 -04001056#endif // GTEST_HAS_STD_FUNCTION_
kosak6305ff52015-04-28 22:36:31 +00001057
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001058// Tests that IsNull() describes itself properly.
1059TEST(IsNullTest, CanDescribeSelf) {
1060 Matcher<int*> m = IsNull();
1061 EXPECT_EQ("is NULL", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001062 EXPECT_EQ("isn't NULL", DescribeNegation(m));
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001063}
1064
shiqiane35fdd92008-12-10 05:08:54 +00001065// Tests that NotNull() matches any non-NULL pointer of any type.
1066TEST(NotNullTest, MatchesNonNullPointer) {
1067 Matcher<int*> m1 = NotNull();
1068 int* p1 = NULL;
1069 int n = 0;
1070 EXPECT_FALSE(m1.Matches(p1));
1071 EXPECT_TRUE(m1.Matches(&n));
1072
1073 Matcher<const char*> m2 = NotNull();
1074 const char* p2 = NULL;
1075 EXPECT_FALSE(m2.Matches(p2));
1076 EXPECT_TRUE(m2.Matches("hi"));
1077}
1078
vladlosev79b83502009-11-18 00:43:37 +00001079TEST(NotNullTest, LinkedPtr) {
1080 const Matcher<linked_ptr<int> > m = NotNull();
1081 const linked_ptr<int> null_p;
1082 const linked_ptr<int> non_null_p(new int);
1083
1084 EXPECT_FALSE(m.Matches(null_p));
1085 EXPECT_TRUE(m.Matches(non_null_p));
1086}
1087
1088TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1089 const Matcher<const linked_ptr<double>&> m = NotNull();
1090 const linked_ptr<double> null_p;
1091 const linked_ptr<double> non_null_p(new double);
1092
1093 EXPECT_FALSE(m.Matches(null_p));
1094 EXPECT_TRUE(m.Matches(non_null_p));
1095}
1096
Mark Mentovaia0435dc2015-10-12 17:57:51 -04001097#if GTEST_HAS_STD_FUNCTION_
kosak6305ff52015-04-28 22:36:31 +00001098TEST(NotNullTest, StdFunction) {
1099 const Matcher<std::function<void()>> m = NotNull();
1100
1101 EXPECT_TRUE(m.Matches([]{}));
1102 EXPECT_FALSE(m.Matches(std::function<void()>()));
1103}
Mark Mentovaia0435dc2015-10-12 17:57:51 -04001104#endif // GTEST_HAS_STD_FUNCTION_
kosak6305ff52015-04-28 22:36:31 +00001105
shiqiane35fdd92008-12-10 05:08:54 +00001106// Tests that NotNull() describes itself properly.
1107TEST(NotNullTest, CanDescribeSelf) {
1108 Matcher<int*> m = NotNull();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001109 EXPECT_EQ("isn't NULL", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001110}
1111
1112// Tests that Ref(variable) matches an argument that references
1113// 'variable'.
1114TEST(RefTest, MatchesSameVariable) {
1115 int a = 0;
1116 int b = 0;
1117 Matcher<int&> m = Ref(a);
1118 EXPECT_TRUE(m.Matches(a));
1119 EXPECT_FALSE(m.Matches(b));
1120}
1121
1122// Tests that Ref(variable) describes itself properly.
1123TEST(RefTest, CanDescribeSelf) {
1124 int n = 5;
1125 Matcher<int&> m = Ref(n);
1126 stringstream ss;
1127 ss << "references the variable @" << &n << " 5";
Nico Weber09fd5b32017-05-15 17:07:03 -04001128 EXPECT_EQ(ss.str(), Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001129}
1130
1131// Test that Ref(non_const_varialbe) can be used as a matcher for a
1132// const reference.
1133TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1134 int a = 0;
1135 int b = 0;
1136 Matcher<const int&> m = Ref(a);
1137 EXPECT_TRUE(m.Matches(a));
1138 EXPECT_FALSE(m.Matches(b));
1139}
1140
1141// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1142// used wherever Ref(base) can be used (Ref(derived) is a sub-type
1143// of Ref(base), but not vice versa.
1144
shiqiane35fdd92008-12-10 05:08:54 +00001145TEST(RefTest, IsCovariant) {
1146 Base base, base2;
1147 Derived derived;
1148 Matcher<const Base&> m1 = Ref(base);
1149 EXPECT_TRUE(m1.Matches(base));
1150 EXPECT_FALSE(m1.Matches(base2));
1151 EXPECT_FALSE(m1.Matches(derived));
1152
1153 m1 = Ref(derived);
1154 EXPECT_TRUE(m1.Matches(derived));
1155 EXPECT_FALSE(m1.Matches(base));
1156 EXPECT_FALSE(m1.Matches(base2));
1157}
1158
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001159TEST(RefTest, ExplainsResult) {
1160 int n = 0;
1161 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1162 StartsWith("which is located @"));
1163
1164 int m = 0;
1165 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1166 StartsWith("which is located @"));
1167}
1168
shiqiane35fdd92008-12-10 05:08:54 +00001169// Tests string comparison matchers.
1170
1171TEST(StrEqTest, MatchesEqualString) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001172 Matcher<const char*> m = StrEq(std::string("Hello"));
shiqiane35fdd92008-12-10 05:08:54 +00001173 EXPECT_TRUE(m.Matches("Hello"));
1174 EXPECT_FALSE(m.Matches("hello"));
1175 EXPECT_FALSE(m.Matches(NULL));
1176
Nico Weber09fd5b32017-05-15 17:07:03 -04001177 Matcher<const std::string&> m2 = StrEq("Hello");
shiqiane35fdd92008-12-10 05:08:54 +00001178 EXPECT_TRUE(m2.Matches("Hello"));
1179 EXPECT_FALSE(m2.Matches("Hi"));
1180}
1181
1182TEST(StrEqTest, CanDescribeSelf) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001183 Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
vladlosevaa432202011-04-01 21:58:42 +00001184 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
shiqiane35fdd92008-12-10 05:08:54 +00001185 Describe(m));
1186
Nico Weber09fd5b32017-05-15 17:07:03 -04001187 std::string str("01204500800");
shiqiane35fdd92008-12-10 05:08:54 +00001188 str[3] = '\0';
Nico Weber09fd5b32017-05-15 17:07:03 -04001189 Matcher<std::string> m2 = StrEq(str);
shiqiane35fdd92008-12-10 05:08:54 +00001190 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1191 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
Nico Weber09fd5b32017-05-15 17:07:03 -04001192 Matcher<std::string> m3 = StrEq(str);
shiqiane35fdd92008-12-10 05:08:54 +00001193 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1194}
1195
1196TEST(StrNeTest, MatchesUnequalString) {
1197 Matcher<const char*> m = StrNe("Hello");
1198 EXPECT_TRUE(m.Matches(""));
1199 EXPECT_TRUE(m.Matches(NULL));
1200 EXPECT_FALSE(m.Matches("Hello"));
1201
Nico Weber09fd5b32017-05-15 17:07:03 -04001202 Matcher<std::string> m2 = StrNe(std::string("Hello"));
shiqiane35fdd92008-12-10 05:08:54 +00001203 EXPECT_TRUE(m2.Matches("hello"));
1204 EXPECT_FALSE(m2.Matches("Hello"));
1205}
1206
1207TEST(StrNeTest, CanDescribeSelf) {
1208 Matcher<const char*> m = StrNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001209 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001210}
1211
1212TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1213 Matcher<const char*> m = StrCaseEq(string("Hello"));
1214 EXPECT_TRUE(m.Matches("Hello"));
1215 EXPECT_TRUE(m.Matches("hello"));
1216 EXPECT_FALSE(m.Matches("Hi"));
1217 EXPECT_FALSE(m.Matches(NULL));
1218
1219 Matcher<const string&> m2 = StrCaseEq("Hello");
1220 EXPECT_TRUE(m2.Matches("hello"));
1221 EXPECT_FALSE(m2.Matches("Hi"));
1222}
1223
1224TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001225 std::string str1("oabocdooeoo");
1226 std::string str2("OABOCDOOEOO");
1227 Matcher<const std::string&> m0 = StrCaseEq(str1);
1228 EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0')));
shiqiane35fdd92008-12-10 05:08:54 +00001229
1230 str1[3] = str2[3] = '\0';
Nico Weber09fd5b32017-05-15 17:07:03 -04001231 Matcher<const std::string&> m1 = StrCaseEq(str1);
shiqiane35fdd92008-12-10 05:08:54 +00001232 EXPECT_TRUE(m1.Matches(str2));
1233
1234 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1235 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
Nico Weber09fd5b32017-05-15 17:07:03 -04001236 Matcher<const std::string&> m2 = StrCaseEq(str1);
shiqiane35fdd92008-12-10 05:08:54 +00001237 str1[9] = str2[9] = '\0';
1238 EXPECT_FALSE(m2.Matches(str2));
1239
Nico Weber09fd5b32017-05-15 17:07:03 -04001240 Matcher<const std::string&> m3 = StrCaseEq(str1);
shiqiane35fdd92008-12-10 05:08:54 +00001241 EXPECT_TRUE(m3.Matches(str2));
1242
1243 EXPECT_FALSE(m3.Matches(str2 + "x"));
1244 str2.append(1, '\0');
1245 EXPECT_FALSE(m3.Matches(str2));
Nico Weber09fd5b32017-05-15 17:07:03 -04001246 EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9)));
shiqiane35fdd92008-12-10 05:08:54 +00001247}
1248
1249TEST(StrCaseEqTest, CanDescribeSelf) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001250 Matcher<std::string> m = StrCaseEq("Hi");
shiqiane35fdd92008-12-10 05:08:54 +00001251 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1252}
1253
1254TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1255 Matcher<const char*> m = StrCaseNe("Hello");
1256 EXPECT_TRUE(m.Matches("Hi"));
1257 EXPECT_TRUE(m.Matches(NULL));
1258 EXPECT_FALSE(m.Matches("Hello"));
1259 EXPECT_FALSE(m.Matches("hello"));
1260
Nico Weber09fd5b32017-05-15 17:07:03 -04001261 Matcher<std::string> m2 = StrCaseNe(std::string("Hello"));
shiqiane35fdd92008-12-10 05:08:54 +00001262 EXPECT_TRUE(m2.Matches(""));
1263 EXPECT_FALSE(m2.Matches("Hello"));
1264}
1265
1266TEST(StrCaseNeTest, CanDescribeSelf) {
1267 Matcher<const char*> m = StrCaseNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001268 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001269}
1270
1271// Tests that HasSubstr() works for matching string-typed values.
1272TEST(HasSubstrTest, WorksForStringClasses) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001273 const Matcher<std::string> m1 = HasSubstr("foo");
1274 EXPECT_TRUE(m1.Matches(std::string("I love food.")));
1275 EXPECT_FALSE(m1.Matches(std::string("tofo")));
shiqiane35fdd92008-12-10 05:08:54 +00001276
1277 const Matcher<const std::string&> m2 = HasSubstr("foo");
1278 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1279 EXPECT_FALSE(m2.Matches(std::string("tofo")));
1280}
1281
1282// Tests that HasSubstr() works for matching C-string-typed values.
1283TEST(HasSubstrTest, WorksForCStrings) {
1284 const Matcher<char*> m1 = HasSubstr("foo");
1285 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1286 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1287 EXPECT_FALSE(m1.Matches(NULL));
1288
1289 const Matcher<const char*> m2 = HasSubstr("foo");
1290 EXPECT_TRUE(m2.Matches("I love food."));
1291 EXPECT_FALSE(m2.Matches("tofo"));
1292 EXPECT_FALSE(m2.Matches(NULL));
1293}
1294
1295// Tests that HasSubstr(s) describes itself properly.
1296TEST(HasSubstrTest, CanDescribeSelf) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001297 Matcher<std::string> m = HasSubstr("foo\n\"");
shiqiane35fdd92008-12-10 05:08:54 +00001298 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1299}
1300
zhanyong.wanb5937da2009-07-16 20:26:41 +00001301TEST(KeyTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001302 Matcher<const pair<std::string, int>&> m = Key("foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001303 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001304 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1305}
1306
1307TEST(KeyTest, ExplainsResult) {
1308 Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1309 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1310 Explain(m, make_pair(5, true)));
1311 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1312 Explain(m, make_pair(15, true)));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001313}
1314
1315TEST(KeyTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001316 pair<int, std::string> p(25, "foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001317 EXPECT_THAT(p, Key(25));
1318 EXPECT_THAT(p, Not(Key(42)));
1319 EXPECT_THAT(p, Key(Ge(20)));
1320 EXPECT_THAT(p, Not(Key(Lt(25))));
1321}
1322
1323TEST(KeyTest, SafelyCastsInnerMatcher) {
1324 Matcher<int> is_positive = Gt(0);
1325 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001326 pair<char, bool> p('a', true);
zhanyong.wanb5937da2009-07-16 20:26:41 +00001327 EXPECT_THAT(p, Key(is_positive));
1328 EXPECT_THAT(p, Not(Key(is_negative)));
1329}
1330
1331TEST(KeyTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001332 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001333 container.insert(make_pair(1, 'a'));
1334 container.insert(make_pair(2, 'b'));
1335 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001336 EXPECT_THAT(container, Contains(Key(1)));
1337 EXPECT_THAT(container, Not(Contains(Key(3))));
1338}
1339
1340TEST(KeyTest, InsideContainsUsingMultimap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001341 multimap<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001342 container.insert(make_pair(1, 'a'));
1343 container.insert(make_pair(2, 'b'));
1344 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001345
1346 EXPECT_THAT(container, Not(Contains(Key(25))));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001347 container.insert(make_pair(25, 'd'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001348 EXPECT_THAT(container, Contains(Key(25)));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001349 container.insert(make_pair(25, 'e'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001350 EXPECT_THAT(container, Contains(Key(25)));
1351
1352 EXPECT_THAT(container, Contains(Key(1)));
1353 EXPECT_THAT(container, Not(Contains(Key(3))));
1354}
1355
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001356TEST(PairTest, Typing) {
1357 // Test verifies the following type conversions can be compiled.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001358 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1359 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1360 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001361
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001362 Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1363 Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001364}
1365
1366TEST(PairTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001367 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001368 EXPECT_EQ("has a first field that is equal to \"foo\""
1369 ", and has a second field that is equal to 42",
1370 Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001371 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1372 ", or has a second field that isn't equal to 42",
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001373 DescribeNegation(m1));
1374 // Double and triple negation (1 or 2 times not and description of negation).
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001375 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1376 EXPECT_EQ("has a first field that isn't equal to 13"
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001377 ", and has a second field that is equal to 42",
1378 DescribeNegation(m2));
1379}
1380
1381TEST(PairTest, CanExplainMatchResultTo) {
zhanyong.wan82113312010-01-08 21:55:40 +00001382 // If neither field matches, Pair() should explain about the first
1383 // field.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001384 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001385 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001386 Explain(m, make_pair(-1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001387
zhanyong.wan82113312010-01-08 21:55:40 +00001388 // If the first field matches but the second doesn't, Pair() should
1389 // explain about the second field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001390 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001391 Explain(m, make_pair(1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001392
zhanyong.wan82113312010-01-08 21:55:40 +00001393 // If the first field doesn't match but the second does, Pair()
1394 // should explain about the first field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001395 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001396 Explain(m, make_pair(-1, 2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001397
zhanyong.wan82113312010-01-08 21:55:40 +00001398 // If both fields match, Pair() should explain about them both.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001399 EXPECT_EQ("whose both fields match, where the first field is a value "
1400 "which is 1 more than 0, and the second field is a value "
1401 "which is 2 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001402 Explain(m, make_pair(1, 2)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001403
1404 // If only the first match has an explanation, only this explanation should
1405 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001406 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001407 EXPECT_EQ("whose both fields match, where the first field is a value "
1408 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001409 Explain(explain_first, make_pair(1, 0)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001410
1411 // If only the second match has an explanation, only this explanation should
1412 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001413 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001414 EXPECT_EQ("whose both fields match, where the second field is a value "
1415 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001416 Explain(explain_second, make_pair(0, 1)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001417}
1418
1419TEST(PairTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001420 pair<int, std::string> p(25, "foo");
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001421
1422 // Both fields match.
1423 EXPECT_THAT(p, Pair(25, "foo"));
1424 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1425
1426 // 'first' doesnt' match, but 'second' matches.
1427 EXPECT_THAT(p, Not(Pair(42, "foo")));
1428 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1429
1430 // 'first' matches, but 'second' doesn't match.
1431 EXPECT_THAT(p, Not(Pair(25, "bar")));
1432 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1433
1434 // Neither field matches.
1435 EXPECT_THAT(p, Not(Pair(13, "bar")));
1436 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1437}
1438
1439TEST(PairTest, SafelyCastsInnerMatchers) {
1440 Matcher<int> is_positive = Gt(0);
1441 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001442 pair<char, bool> p('a', true);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001443 EXPECT_THAT(p, Pair(is_positive, _));
1444 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1445 EXPECT_THAT(p, Pair(_, is_positive));
1446 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1447}
1448
1449TEST(PairTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001450 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001451 container.insert(make_pair(1, 'a'));
1452 container.insert(make_pair(2, 'b'));
1453 container.insert(make_pair(4, 'c'));
zhanyong.wan95b12332009-09-25 18:55:50 +00001454 EXPECT_THAT(container, Contains(Pair(1, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001455 EXPECT_THAT(container, Contains(Pair(1, _)));
zhanyong.wan95b12332009-09-25 18:55:50 +00001456 EXPECT_THAT(container, Contains(Pair(_, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001457 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1458}
1459
shiqiane35fdd92008-12-10 05:08:54 +00001460// Tests StartsWith(s).
1461
1462TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001463 const Matcher<const char*> m1 = StartsWith(std::string(""));
shiqiane35fdd92008-12-10 05:08:54 +00001464 EXPECT_TRUE(m1.Matches("Hi"));
1465 EXPECT_TRUE(m1.Matches(""));
1466 EXPECT_FALSE(m1.Matches(NULL));
1467
Nico Weber09fd5b32017-05-15 17:07:03 -04001468 const Matcher<const std::string&> m2 = StartsWith("Hi");
shiqiane35fdd92008-12-10 05:08:54 +00001469 EXPECT_TRUE(m2.Matches("Hi"));
1470 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1471 EXPECT_TRUE(m2.Matches("High"));
1472 EXPECT_FALSE(m2.Matches("H"));
1473 EXPECT_FALSE(m2.Matches(" Hi"));
1474}
1475
1476TEST(StartsWithTest, CanDescribeSelf) {
1477 Matcher<const std::string> m = StartsWith("Hi");
1478 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1479}
1480
1481// Tests EndsWith(s).
1482
1483TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1484 const Matcher<const char*> m1 = EndsWith("");
1485 EXPECT_TRUE(m1.Matches("Hi"));
1486 EXPECT_TRUE(m1.Matches(""));
1487 EXPECT_FALSE(m1.Matches(NULL));
1488
1489 const Matcher<const string&> m2 = EndsWith(string("Hi"));
1490 EXPECT_TRUE(m2.Matches("Hi"));
1491 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1492 EXPECT_TRUE(m2.Matches("Super Hi"));
1493 EXPECT_FALSE(m2.Matches("i"));
1494 EXPECT_FALSE(m2.Matches("Hi "));
1495}
1496
1497TEST(EndsWithTest, CanDescribeSelf) {
1498 Matcher<const std::string> m = EndsWith("Hi");
1499 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1500}
1501
shiqiane35fdd92008-12-10 05:08:54 +00001502// Tests MatchesRegex().
1503
1504TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1505 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1506 EXPECT_TRUE(m1.Matches("az"));
1507 EXPECT_TRUE(m1.Matches("abcz"));
1508 EXPECT_FALSE(m1.Matches(NULL));
1509
Nico Weber09fd5b32017-05-15 17:07:03 -04001510 const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z"));
shiqiane35fdd92008-12-10 05:08:54 +00001511 EXPECT_TRUE(m2.Matches("azbz"));
1512 EXPECT_FALSE(m2.Matches("az1"));
1513 EXPECT_FALSE(m2.Matches("1az"));
1514}
1515
1516TEST(MatchesRegexTest, CanDescribeSelf) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001517 Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*"));
shiqiane35fdd92008-12-10 05:08:54 +00001518 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1519
zhanyong.wand14aaed2010-01-14 05:36:32 +00001520 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1521 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001522}
1523
1524// Tests ContainsRegex().
1525
1526TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
Nico Weber09fd5b32017-05-15 17:07:03 -04001527 const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z"));
shiqiane35fdd92008-12-10 05:08:54 +00001528 EXPECT_TRUE(m1.Matches("az"));
1529 EXPECT_TRUE(m1.Matches("0abcz1"));
1530 EXPECT_FALSE(m1.Matches(NULL));
1531
Nico Weber09fd5b32017-05-15 17:07:03 -04001532 const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z"));
shiqiane35fdd92008-12-10 05:08:54 +00001533 EXPECT_TRUE(m2.Matches("azbz"));
1534 EXPECT_TRUE(m2.Matches("az1"));
1535 EXPECT_FALSE(m2.Matches("1a"));
1536}
1537
1538TEST(ContainsRegexTest, CanDescribeSelf) {
1539 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1540 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1541
zhanyong.wand14aaed2010-01-14 05:36:32 +00001542 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1543 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001544}
shiqiane35fdd92008-12-10 05:08:54 +00001545
1546// Tests for wide strings.
1547#if GTEST_HAS_STD_WSTRING
1548TEST(StdWideStrEqTest, MatchesEqual) {
1549 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1550 EXPECT_TRUE(m.Matches(L"Hello"));
1551 EXPECT_FALSE(m.Matches(L"hello"));
1552 EXPECT_FALSE(m.Matches(NULL));
1553
1554 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1555 EXPECT_TRUE(m2.Matches(L"Hello"));
1556 EXPECT_FALSE(m2.Matches(L"Hi"));
1557
1558 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1559 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1560 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1561
1562 ::std::wstring str(L"01204500800");
1563 str[3] = L'\0';
1564 Matcher<const ::std::wstring&> m4 = StrEq(str);
1565 EXPECT_TRUE(m4.Matches(str));
1566 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1567 Matcher<const ::std::wstring&> m5 = StrEq(str);
1568 EXPECT_TRUE(m5.Matches(str));
1569}
1570
1571TEST(StdWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001572 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1573 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001574 Describe(m));
1575
1576 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1577 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1578 Describe(m2));
1579
1580 ::std::wstring str(L"01204500800");
1581 str[3] = L'\0';
1582 Matcher<const ::std::wstring&> m4 = StrEq(str);
1583 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1584 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1585 Matcher<const ::std::wstring&> m5 = StrEq(str);
1586 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1587}
1588
1589TEST(StdWideStrNeTest, MatchesUnequalString) {
1590 Matcher<const wchar_t*> m = StrNe(L"Hello");
1591 EXPECT_TRUE(m.Matches(L""));
1592 EXPECT_TRUE(m.Matches(NULL));
1593 EXPECT_FALSE(m.Matches(L"Hello"));
1594
1595 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1596 EXPECT_TRUE(m2.Matches(L"hello"));
1597 EXPECT_FALSE(m2.Matches(L"Hello"));
1598}
1599
1600TEST(StdWideStrNeTest, CanDescribeSelf) {
1601 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001602 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001603}
1604
1605TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1606 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1607 EXPECT_TRUE(m.Matches(L"Hello"));
1608 EXPECT_TRUE(m.Matches(L"hello"));
1609 EXPECT_FALSE(m.Matches(L"Hi"));
1610 EXPECT_FALSE(m.Matches(NULL));
1611
1612 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1613 EXPECT_TRUE(m2.Matches(L"hello"));
1614 EXPECT_FALSE(m2.Matches(L"Hi"));
1615}
1616
1617TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1618 ::std::wstring str1(L"oabocdooeoo");
1619 ::std::wstring str2(L"OABOCDOOEOO");
1620 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1621 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1622
1623 str1[3] = str2[3] = L'\0';
1624 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1625 EXPECT_TRUE(m1.Matches(str2));
1626
1627 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1628 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1629 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1630 str1[9] = str2[9] = L'\0';
1631 EXPECT_FALSE(m2.Matches(str2));
1632
1633 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1634 EXPECT_TRUE(m3.Matches(str2));
1635
1636 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1637 str2.append(1, L'\0');
1638 EXPECT_FALSE(m3.Matches(str2));
1639 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1640}
1641
1642TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1643 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1644 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1645}
1646
1647TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1648 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1649 EXPECT_TRUE(m.Matches(L"Hi"));
1650 EXPECT_TRUE(m.Matches(NULL));
1651 EXPECT_FALSE(m.Matches(L"Hello"));
1652 EXPECT_FALSE(m.Matches(L"hello"));
1653
1654 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1655 EXPECT_TRUE(m2.Matches(L""));
1656 EXPECT_FALSE(m2.Matches(L"Hello"));
1657}
1658
1659TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1660 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001661 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001662}
1663
1664// Tests that HasSubstr() works for matching wstring-typed values.
1665TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1666 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1667 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1668 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1669
1670 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1671 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1672 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1673}
1674
1675// Tests that HasSubstr() works for matching C-wide-string-typed values.
1676TEST(StdWideHasSubstrTest, WorksForCStrings) {
1677 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1678 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1679 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1680 EXPECT_FALSE(m1.Matches(NULL));
1681
1682 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1683 EXPECT_TRUE(m2.Matches(L"I love food."));
1684 EXPECT_FALSE(m2.Matches(L"tofo"));
1685 EXPECT_FALSE(m2.Matches(NULL));
1686}
1687
1688// Tests that HasSubstr(s) describes itself properly.
1689TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1690 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1691 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1692}
1693
1694// Tests StartsWith(s).
1695
1696TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1697 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1698 EXPECT_TRUE(m1.Matches(L"Hi"));
1699 EXPECT_TRUE(m1.Matches(L""));
1700 EXPECT_FALSE(m1.Matches(NULL));
1701
1702 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1703 EXPECT_TRUE(m2.Matches(L"Hi"));
1704 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1705 EXPECT_TRUE(m2.Matches(L"High"));
1706 EXPECT_FALSE(m2.Matches(L"H"));
1707 EXPECT_FALSE(m2.Matches(L" Hi"));
1708}
1709
1710TEST(StdWideStartsWithTest, CanDescribeSelf) {
1711 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
1712 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1713}
1714
1715// Tests EndsWith(s).
1716
1717TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
1718 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1719 EXPECT_TRUE(m1.Matches(L"Hi"));
1720 EXPECT_TRUE(m1.Matches(L""));
1721 EXPECT_FALSE(m1.Matches(NULL));
1722
1723 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
1724 EXPECT_TRUE(m2.Matches(L"Hi"));
1725 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1726 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1727 EXPECT_FALSE(m2.Matches(L"i"));
1728 EXPECT_FALSE(m2.Matches(L"Hi "));
1729}
1730
1731TEST(StdWideEndsWithTest, CanDescribeSelf) {
1732 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
1733 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1734}
1735
1736#endif // GTEST_HAS_STD_WSTRING
1737
1738#if GTEST_HAS_GLOBAL_WSTRING
1739TEST(GlobalWideStrEqTest, MatchesEqual) {
1740 Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
1741 EXPECT_TRUE(m.Matches(L"Hello"));
1742 EXPECT_FALSE(m.Matches(L"hello"));
1743 EXPECT_FALSE(m.Matches(NULL));
1744
1745 Matcher<const ::wstring&> m2 = StrEq(L"Hello");
1746 EXPECT_TRUE(m2.Matches(L"Hello"));
1747 EXPECT_FALSE(m2.Matches(L"Hi"));
1748
1749 Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1750 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1751 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1752
1753 ::wstring str(L"01204500800");
1754 str[3] = L'\0';
1755 Matcher<const ::wstring&> m4 = StrEq(str);
1756 EXPECT_TRUE(m4.Matches(str));
1757 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1758 Matcher<const ::wstring&> m5 = StrEq(str);
1759 EXPECT_TRUE(m5.Matches(str));
1760}
1761
1762TEST(GlobalWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001763 Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1764 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001765 Describe(m));
1766
1767 Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1768 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1769 Describe(m2));
1770
1771 ::wstring str(L"01204500800");
1772 str[3] = L'\0';
1773 Matcher<const ::wstring&> m4 = StrEq(str);
1774 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1775 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1776 Matcher<const ::wstring&> m5 = StrEq(str);
1777 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1778}
1779
1780TEST(GlobalWideStrNeTest, MatchesUnequalString) {
1781 Matcher<const wchar_t*> m = StrNe(L"Hello");
1782 EXPECT_TRUE(m.Matches(L""));
1783 EXPECT_TRUE(m.Matches(NULL));
1784 EXPECT_FALSE(m.Matches(L"Hello"));
1785
1786 Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
1787 EXPECT_TRUE(m2.Matches(L"hello"));
1788 EXPECT_FALSE(m2.Matches(L"Hello"));
1789}
1790
1791TEST(GlobalWideStrNeTest, CanDescribeSelf) {
1792 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001793 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001794}
1795
1796TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1797 Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
1798 EXPECT_TRUE(m.Matches(L"Hello"));
1799 EXPECT_TRUE(m.Matches(L"hello"));
1800 EXPECT_FALSE(m.Matches(L"Hi"));
1801 EXPECT_FALSE(m.Matches(NULL));
1802
1803 Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
1804 EXPECT_TRUE(m2.Matches(L"hello"));
1805 EXPECT_FALSE(m2.Matches(L"Hi"));
1806}
1807
1808TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1809 ::wstring str1(L"oabocdooeoo");
1810 ::wstring str2(L"OABOCDOOEOO");
1811 Matcher<const ::wstring&> m0 = StrCaseEq(str1);
1812 EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
1813
1814 str1[3] = str2[3] = L'\0';
1815 Matcher<const ::wstring&> m1 = StrCaseEq(str1);
1816 EXPECT_TRUE(m1.Matches(str2));
1817
1818 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1819 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1820 Matcher<const ::wstring&> m2 = StrCaseEq(str1);
1821 str1[9] = str2[9] = L'\0';
1822 EXPECT_FALSE(m2.Matches(str2));
1823
1824 Matcher<const ::wstring&> m3 = StrCaseEq(str1);
1825 EXPECT_TRUE(m3.Matches(str2));
1826
1827 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1828 str2.append(1, L'\0');
1829 EXPECT_FALSE(m3.Matches(str2));
1830 EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
1831}
1832
1833TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
1834 Matcher< ::wstring> m = StrCaseEq(L"Hi");
1835 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1836}
1837
1838TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1839 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1840 EXPECT_TRUE(m.Matches(L"Hi"));
1841 EXPECT_TRUE(m.Matches(NULL));
1842 EXPECT_FALSE(m.Matches(L"Hello"));
1843 EXPECT_FALSE(m.Matches(L"hello"));
1844
1845 Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
1846 EXPECT_TRUE(m2.Matches(L""));
1847 EXPECT_FALSE(m2.Matches(L"Hello"));
1848}
1849
1850TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
1851 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001852 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001853}
1854
1855// Tests that HasSubstr() works for matching wstring-typed values.
1856TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
1857 const Matcher< ::wstring> m1 = HasSubstr(L"foo");
1858 EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
1859 EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
1860
1861 const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
1862 EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
1863 EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
1864}
1865
1866// Tests that HasSubstr() works for matching C-wide-string-typed values.
1867TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
1868 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1869 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1870 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1871 EXPECT_FALSE(m1.Matches(NULL));
1872
1873 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1874 EXPECT_TRUE(m2.Matches(L"I love food."));
1875 EXPECT_FALSE(m2.Matches(L"tofo"));
1876 EXPECT_FALSE(m2.Matches(NULL));
1877}
1878
1879// Tests that HasSubstr(s) describes itself properly.
1880TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
1881 Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
1882 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1883}
1884
1885// Tests StartsWith(s).
1886
1887TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
1888 const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
1889 EXPECT_TRUE(m1.Matches(L"Hi"));
1890 EXPECT_TRUE(m1.Matches(L""));
1891 EXPECT_FALSE(m1.Matches(NULL));
1892
1893 const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
1894 EXPECT_TRUE(m2.Matches(L"Hi"));
1895 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1896 EXPECT_TRUE(m2.Matches(L"High"));
1897 EXPECT_FALSE(m2.Matches(L"H"));
1898 EXPECT_FALSE(m2.Matches(L" Hi"));
1899}
1900
1901TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
1902 Matcher<const ::wstring> m = StartsWith(L"Hi");
1903 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1904}
1905
1906// Tests EndsWith(s).
1907
1908TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
1909 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1910 EXPECT_TRUE(m1.Matches(L"Hi"));
1911 EXPECT_TRUE(m1.Matches(L""));
1912 EXPECT_FALSE(m1.Matches(NULL));
1913
1914 const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
1915 EXPECT_TRUE(m2.Matches(L"Hi"));
1916 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1917 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1918 EXPECT_FALSE(m2.Matches(L"i"));
1919 EXPECT_FALSE(m2.Matches(L"Hi "));
1920}
1921
1922TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
1923 Matcher<const ::wstring> m = EndsWith(L"Hi");
1924 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1925}
1926
1927#endif // GTEST_HAS_GLOBAL_WSTRING
1928
1929
kosakbd018832014-04-02 20:30:00 +00001930typedef ::testing::tuple<long, int> Tuple2; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00001931
1932// Tests that Eq() matches a 2-tuple where the first field == the
1933// second field.
1934TEST(Eq2Test, MatchesEqualArguments) {
1935 Matcher<const Tuple2&> m = Eq();
1936 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1937 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1938}
1939
1940// Tests that Eq() describes itself properly.
1941TEST(Eq2Test, CanDescribeSelf) {
1942 Matcher<const Tuple2&> m = Eq();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001943 EXPECT_EQ("are an equal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001944}
1945
1946// Tests that Ge() matches a 2-tuple where the first field >= the
1947// second field.
1948TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
1949 Matcher<const Tuple2&> m = Ge();
1950 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1951 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1952 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1953}
1954
1955// Tests that Ge() describes itself properly.
1956TEST(Ge2Test, CanDescribeSelf) {
1957 Matcher<const Tuple2&> m = Ge();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001958 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001959}
1960
1961// Tests that Gt() matches a 2-tuple where the first field > the
1962// second field.
1963TEST(Gt2Test, MatchesGreaterThanArguments) {
1964 Matcher<const Tuple2&> m = Gt();
1965 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1966 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1967 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1968}
1969
1970// Tests that Gt() describes itself properly.
1971TEST(Gt2Test, CanDescribeSelf) {
1972 Matcher<const Tuple2&> m = Gt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001973 EXPECT_EQ("are a pair where the first > the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001974}
1975
1976// Tests that Le() matches a 2-tuple where the first field <= the
1977// second field.
1978TEST(Le2Test, MatchesLessThanOrEqualArguments) {
1979 Matcher<const Tuple2&> m = Le();
1980 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1981 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1982 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1983}
1984
1985// Tests that Le() describes itself properly.
1986TEST(Le2Test, CanDescribeSelf) {
1987 Matcher<const Tuple2&> m = Le();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001988 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001989}
1990
1991// Tests that Lt() matches a 2-tuple where the first field < the
1992// second field.
1993TEST(Lt2Test, MatchesLessThanArguments) {
1994 Matcher<const Tuple2&> m = Lt();
1995 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1996 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1997 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1998}
1999
2000// Tests that Lt() describes itself properly.
2001TEST(Lt2Test, CanDescribeSelf) {
2002 Matcher<const Tuple2&> m = Lt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002003 EXPECT_EQ("are a pair where the first < the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002004}
2005
2006// Tests that Ne() matches a 2-tuple where the first field != the
2007// second field.
2008TEST(Ne2Test, MatchesUnequalArguments) {
2009 Matcher<const Tuple2&> m = Ne();
2010 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2011 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2012 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2013}
2014
2015// Tests that Ne() describes itself properly.
2016TEST(Ne2Test, CanDescribeSelf) {
2017 Matcher<const Tuple2&> m = Ne();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002018 EXPECT_EQ("are an unequal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002019}
2020
2021// Tests that Not(m) matches any value that doesn't match m.
2022TEST(NotTest, NegatesMatcher) {
2023 Matcher<int> m;
2024 m = Not(Eq(2));
2025 EXPECT_TRUE(m.Matches(3));
2026 EXPECT_FALSE(m.Matches(2));
2027}
2028
2029// Tests that Not(m) describes itself properly.
2030TEST(NotTest, CanDescribeSelf) {
2031 Matcher<int> m = Not(Eq(5));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002032 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002033}
2034
zhanyong.wan18490652009-05-11 18:54:08 +00002035// Tests that monomorphic matchers are safely cast by the Not matcher.
2036TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2037 // greater_than_5 is a monomorphic matcher.
2038 Matcher<int> greater_than_5 = Gt(5);
2039
2040 Matcher<const int&> m = Not(greater_than_5);
2041 Matcher<int&> m2 = Not(greater_than_5);
2042 Matcher<int&> m3 = Not(m);
2043}
2044
zhanyong.wan02c15052010-06-09 19:21:30 +00002045// Helper to allow easy testing of AllOf matchers with num parameters.
2046void AllOfMatches(int num, const Matcher<int>& m) {
2047 SCOPED_TRACE(Describe(m));
2048 EXPECT_TRUE(m.Matches(0));
2049 for (int i = 1; i <= num; ++i) {
2050 EXPECT_FALSE(m.Matches(i));
2051 }
2052 EXPECT_TRUE(m.Matches(num + 1));
2053}
2054
shiqiane35fdd92008-12-10 05:08:54 +00002055// Tests that AllOf(m1, ..., mn) matches any value that matches all of
2056// the given matchers.
2057TEST(AllOfTest, MatchesWhenAllMatch) {
2058 Matcher<int> m;
2059 m = AllOf(Le(2), Ge(1));
2060 EXPECT_TRUE(m.Matches(1));
2061 EXPECT_TRUE(m.Matches(2));
2062 EXPECT_FALSE(m.Matches(0));
2063 EXPECT_FALSE(m.Matches(3));
2064
2065 m = AllOf(Gt(0), Ne(1), Ne(2));
2066 EXPECT_TRUE(m.Matches(3));
2067 EXPECT_FALSE(m.Matches(2));
2068 EXPECT_FALSE(m.Matches(1));
2069 EXPECT_FALSE(m.Matches(0));
2070
2071 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2072 EXPECT_TRUE(m.Matches(4));
2073 EXPECT_FALSE(m.Matches(3));
2074 EXPECT_FALSE(m.Matches(2));
2075 EXPECT_FALSE(m.Matches(1));
2076 EXPECT_FALSE(m.Matches(0));
2077
2078 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2079 EXPECT_TRUE(m.Matches(0));
2080 EXPECT_TRUE(m.Matches(1));
2081 EXPECT_FALSE(m.Matches(3));
zhanyong.wan02c15052010-06-09 19:21:30 +00002082
2083 // The following tests for varying number of sub-matchers. Due to the way
2084 // the sub-matchers are handled it is enough to test every sub-matcher once
2085 // with sub-matchers using the same matcher type. Varying matcher types are
2086 // checked for above.
2087 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2088 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2089 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2090 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2091 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2092 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2093 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2094 Ne(8)));
2095 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2096 Ne(8), Ne(9)));
2097 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2098 Ne(9), Ne(10)));
shiqiane35fdd92008-12-10 05:08:54 +00002099}
2100
zhanyong.wan616180e2013-06-18 18:49:51 +00002101#if GTEST_LANG_CXX11
2102// Tests the variadic version of the AllOfMatcher.
2103TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
2104 // Make sure AllOf is defined in the right namespace and does not depend on
2105 // ADL.
2106 ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2107 Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2108 Ne(9), Ne(10), Ne(11));
2109 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))"));
2110 AllOfMatches(11, m);
2111 AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2112 Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
2113 Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22),
2114 Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29),
2115 Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36),
2116 Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43),
2117 Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2118 Ne(50)));
2119}
2120
2121#endif // GTEST_LANG_CXX11
2122
shiqiane35fdd92008-12-10 05:08:54 +00002123// Tests that AllOf(m1, ..., mn) describes itself properly.
2124TEST(AllOfTest, CanDescribeSelf) {
2125 Matcher<int> m;
2126 m = AllOf(Le(2), Ge(1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002127 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002128
2129 m = AllOf(Gt(0), Ne(1), Ne(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002130 EXPECT_EQ("(is > 0) and "
2131 "((isn't equal to 1) and "
2132 "(isn't equal to 2))",
shiqiane35fdd92008-12-10 05:08:54 +00002133 Describe(m));
2134
2135
2136 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002137 EXPECT_EQ("((is > 0) and "
2138 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002139 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002140 "(isn't equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002141 Describe(m));
2142
2143
2144 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002145 EXPECT_EQ("((is >= 0) and "
2146 "(is < 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002147 "((isn't equal to 3) and "
2148 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002149 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002150 Describe(m));
2151}
2152
2153// Tests that AllOf(m1, ..., mn) describes its negation properly.
2154TEST(AllOfTest, CanDescribeNegation) {
2155 Matcher<int> m;
2156 m = AllOf(Le(2), Ge(1));
2157 EXPECT_EQ("(isn't <= 2) or "
2158 "(isn't >= 1)",
2159 DescribeNegation(m));
2160
2161 m = AllOf(Gt(0), Ne(1), Ne(2));
2162 EXPECT_EQ("(isn't > 0) or "
2163 "((is equal to 1) or "
2164 "(is equal to 2))",
2165 DescribeNegation(m));
2166
2167
2168 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002169 EXPECT_EQ("((isn't > 0) or "
2170 "(is equal to 1)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002171 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002172 "(is equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002173 DescribeNegation(m));
2174
2175
2176 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002177 EXPECT_EQ("((isn't >= 0) or "
2178 "(isn't < 10)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002179 "((is equal to 3) or "
2180 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002181 "(is equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002182 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00002183}
2184
zhanyong.wan18490652009-05-11 18:54:08 +00002185// Tests that monomorphic matchers are safely cast by the AllOf matcher.
2186TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2187 // greater_than_5 and less_than_10 are monomorphic matchers.
2188 Matcher<int> greater_than_5 = Gt(5);
2189 Matcher<int> less_than_10 = Lt(10);
2190
2191 Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2192 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2193 Matcher<int&> m3 = AllOf(greater_than_5, m2);
2194
2195 // Tests that BothOf works when composing itself.
2196 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2197 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2198}
2199
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002200TEST(AllOfTest, ExplainsResult) {
2201 Matcher<int> m;
2202
2203 // Successful match. Both matchers need to explain. The second
2204 // matcher doesn't give an explanation, so only the first matcher's
2205 // explanation is printed.
2206 m = AllOf(GreaterThan(10), Lt(30));
2207 EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2208
2209 // Successful match. Both matchers need to explain.
2210 m = AllOf(GreaterThan(10), GreaterThan(20));
2211 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2212 Explain(m, 30));
2213
2214 // Successful match. All matchers need to explain. The second
2215 // matcher doesn't given an explanation.
2216 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2217 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2218 Explain(m, 25));
2219
2220 // Successful match. All matchers need to explain.
2221 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2222 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2223 "and which is 10 more than 30",
2224 Explain(m, 40));
2225
2226 // Failed match. The first matcher, which failed, needs to
2227 // explain.
2228 m = AllOf(GreaterThan(10), GreaterThan(20));
2229 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2230
2231 // Failed match. The second matcher, which failed, needs to
2232 // explain. Since it doesn't given an explanation, nothing is
2233 // printed.
2234 m = AllOf(GreaterThan(10), Lt(30));
2235 EXPECT_EQ("", Explain(m, 40));
2236
2237 // Failed match. The second matcher, which failed, needs to
2238 // explain.
2239 m = AllOf(GreaterThan(10), GreaterThan(20));
2240 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2241}
2242
zhanyong.wan02c15052010-06-09 19:21:30 +00002243// Helper to allow easy testing of AnyOf matchers with num parameters.
2244void AnyOfMatches(int num, const Matcher<int>& m) {
2245 SCOPED_TRACE(Describe(m));
2246 EXPECT_FALSE(m.Matches(0));
2247 for (int i = 1; i <= num; ++i) {
2248 EXPECT_TRUE(m.Matches(i));
2249 }
2250 EXPECT_FALSE(m.Matches(num + 1));
2251}
2252
shiqiane35fdd92008-12-10 05:08:54 +00002253// Tests that AnyOf(m1, ..., mn) matches any value that matches at
2254// least one of the given matchers.
2255TEST(AnyOfTest, MatchesWhenAnyMatches) {
2256 Matcher<int> m;
2257 m = AnyOf(Le(1), Ge(3));
2258 EXPECT_TRUE(m.Matches(1));
2259 EXPECT_TRUE(m.Matches(4));
2260 EXPECT_FALSE(m.Matches(2));
2261
2262 m = AnyOf(Lt(0), Eq(1), Eq(2));
2263 EXPECT_TRUE(m.Matches(-1));
2264 EXPECT_TRUE(m.Matches(1));
2265 EXPECT_TRUE(m.Matches(2));
2266 EXPECT_FALSE(m.Matches(0));
2267
2268 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2269 EXPECT_TRUE(m.Matches(-1));
2270 EXPECT_TRUE(m.Matches(1));
2271 EXPECT_TRUE(m.Matches(2));
2272 EXPECT_TRUE(m.Matches(3));
2273 EXPECT_FALSE(m.Matches(0));
2274
2275 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2276 EXPECT_TRUE(m.Matches(0));
2277 EXPECT_TRUE(m.Matches(11));
2278 EXPECT_TRUE(m.Matches(3));
2279 EXPECT_FALSE(m.Matches(2));
zhanyong.wan02c15052010-06-09 19:21:30 +00002280
2281 // The following tests for varying number of sub-matchers. Due to the way
2282 // the sub-matchers are handled it is enough to test every sub-matcher once
2283 // with sub-matchers using the same matcher type. Varying matcher types are
2284 // checked for above.
2285 AnyOfMatches(2, AnyOf(1, 2));
2286 AnyOfMatches(3, AnyOf(1, 2, 3));
2287 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2288 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2289 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2290 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2291 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2292 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2293 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
shiqiane35fdd92008-12-10 05:08:54 +00002294}
2295
zhanyong.wan616180e2013-06-18 18:49:51 +00002296#if GTEST_LANG_CXX11
2297// Tests the variadic version of the AnyOfMatcher.
2298TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2299 // Also make sure AnyOf is defined in the right namespace and does not depend
2300 // on ADL.
2301 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2302
2303 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))"));
2304 AnyOfMatches(11, m);
2305 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2306 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2307 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2308 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2309 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2310}
2311
2312#endif // GTEST_LANG_CXX11
2313
shiqiane35fdd92008-12-10 05:08:54 +00002314// Tests that AnyOf(m1, ..., mn) describes itself properly.
2315TEST(AnyOfTest, CanDescribeSelf) {
2316 Matcher<int> m;
2317 m = AnyOf(Le(1), Ge(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002318 EXPECT_EQ("(is <= 1) or (is >= 3)",
shiqiane35fdd92008-12-10 05:08:54 +00002319 Describe(m));
2320
2321 m = AnyOf(Lt(0), Eq(1), Eq(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002322 EXPECT_EQ("(is < 0) or "
shiqiane35fdd92008-12-10 05:08:54 +00002323 "((is equal to 1) or (is equal to 2))",
2324 Describe(m));
2325
2326 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002327 EXPECT_EQ("((is < 0) or "
2328 "(is equal to 1)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002329 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002330 "(is equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002331 Describe(m));
2332
2333 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002334 EXPECT_EQ("((is <= 0) or "
2335 "(is > 10)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002336 "((is equal to 3) or "
2337 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002338 "(is equal to 7)))",
shiqiane35fdd92008-12-10 05:08:54 +00002339 Describe(m));
2340}
2341
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002342// Tests that AnyOf(m1, ..., mn) describes its negation properly.
2343TEST(AnyOfTest, CanDescribeNegation) {
2344 Matcher<int> m;
2345 m = AnyOf(Le(1), Ge(3));
2346 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2347 DescribeNegation(m));
2348
2349 m = AnyOf(Lt(0), Eq(1), Eq(2));
2350 EXPECT_EQ("(isn't < 0) and "
2351 "((isn't equal to 1) and (isn't equal to 2))",
2352 DescribeNegation(m));
2353
2354 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002355 EXPECT_EQ("((isn't < 0) and "
2356 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002357 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002358 "(isn't equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002359 DescribeNegation(m));
2360
2361 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002362 EXPECT_EQ("((isn't <= 0) and "
2363 "(isn't > 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002364 "((isn't equal to 3) and "
2365 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002366 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002367 DescribeNegation(m));
2368}
2369
zhanyong.wan18490652009-05-11 18:54:08 +00002370// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2371TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2372 // greater_than_5 and less_than_10 are monomorphic matchers.
2373 Matcher<int> greater_than_5 = Gt(5);
2374 Matcher<int> less_than_10 = Lt(10);
2375
2376 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2377 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2378 Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2379
2380 // Tests that EitherOf works when composing itself.
2381 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2382 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2383}
2384
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002385TEST(AnyOfTest, ExplainsResult) {
2386 Matcher<int> m;
2387
2388 // Failed match. Both matchers need to explain. The second
2389 // matcher doesn't give an explanation, so only the first matcher's
2390 // explanation is printed.
2391 m = AnyOf(GreaterThan(10), Lt(0));
2392 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2393
2394 // Failed match. Both matchers need to explain.
2395 m = AnyOf(GreaterThan(10), GreaterThan(20));
2396 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2397 Explain(m, 5));
2398
2399 // Failed match. All matchers need to explain. The second
2400 // matcher doesn't given an explanation.
2401 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2402 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2403 Explain(m, 5));
2404
2405 // Failed match. All matchers need to explain.
2406 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2407 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2408 "and which is 25 less than 30",
2409 Explain(m, 5));
2410
2411 // Successful match. The first matcher, which succeeded, needs to
2412 // explain.
2413 m = AnyOf(GreaterThan(10), GreaterThan(20));
2414 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2415
2416 // Successful match. The second matcher, which succeeded, needs to
2417 // explain. Since it doesn't given an explanation, nothing is
2418 // printed.
2419 m = AnyOf(GreaterThan(10), Lt(30));
2420 EXPECT_EQ("", Explain(m, 0));
2421
2422 // Successful match. The second matcher, which succeeded, needs to
2423 // explain.
2424 m = AnyOf(GreaterThan(30), GreaterThan(20));
2425 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2426}
2427
shiqiane35fdd92008-12-10 05:08:54 +00002428// The following predicate function and predicate functor are for
2429// testing the Truly(predicate) matcher.
2430
2431// Returns non-zero if the input is positive. Note that the return
2432// type of this function is not bool. It's OK as Truly() accepts any
2433// unary function or functor whose return type can be implicitly
2434// converted to bool.
2435int IsPositive(double x) {
2436 return x > 0 ? 1 : 0;
2437}
2438
2439// This functor returns true if the input is greater than the given
2440// number.
2441class IsGreaterThan {
2442 public:
2443 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2444
2445 bool operator()(int n) const { return n > threshold_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002446
shiqiane35fdd92008-12-10 05:08:54 +00002447 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002448 int threshold_;
shiqiane35fdd92008-12-10 05:08:54 +00002449};
2450
2451// For testing Truly().
2452const int foo = 0;
2453
2454// This predicate returns true iff the argument references foo and has
2455// a zero value.
2456bool ReferencesFooAndIsZero(const int& n) {
2457 return (&n == &foo) && (n == 0);
2458}
2459
2460// Tests that Truly(predicate) matches what satisfies the given
2461// predicate.
2462TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2463 Matcher<double> m = Truly(IsPositive);
2464 EXPECT_TRUE(m.Matches(2.0));
2465 EXPECT_FALSE(m.Matches(-1.5));
2466}
2467
2468// Tests that Truly(predicate_functor) works too.
2469TEST(TrulyTest, CanBeUsedWithFunctor) {
2470 Matcher<int> m = Truly(IsGreaterThan(5));
2471 EXPECT_TRUE(m.Matches(6));
2472 EXPECT_FALSE(m.Matches(4));
2473}
2474
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00002475// A class that can be implicitly converted to bool.
2476class ConvertibleToBool {
2477 public:
2478 explicit ConvertibleToBool(int number) : number_(number) {}
2479 operator bool() const { return number_ != 0; }
2480
2481 private:
2482 int number_;
2483};
2484
2485ConvertibleToBool IsNotZero(int number) {
2486 return ConvertibleToBool(number);
2487}
2488
2489// Tests that the predicate used in Truly() may return a class that's
2490// implicitly convertible to bool, even when the class has no
2491// operator!().
2492TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2493 Matcher<int> m = Truly(IsNotZero);
2494 EXPECT_TRUE(m.Matches(1));
2495 EXPECT_FALSE(m.Matches(0));
2496}
2497
shiqiane35fdd92008-12-10 05:08:54 +00002498// Tests that Truly(predicate) can describe itself properly.
2499TEST(TrulyTest, CanDescribeSelf) {
2500 Matcher<double> m = Truly(IsPositive);
2501 EXPECT_EQ("satisfies the given predicate",
2502 Describe(m));
2503}
2504
2505// Tests that Truly(predicate) works when the matcher takes its
2506// argument by reference.
2507TEST(TrulyTest, WorksForByRefArguments) {
2508 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2509 EXPECT_TRUE(m.Matches(foo));
2510 int n = 0;
2511 EXPECT_FALSE(m.Matches(n));
2512}
2513
2514// Tests that Matches(m) is a predicate satisfied by whatever that
2515// matches matcher m.
2516TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2517 EXPECT_TRUE(Matches(Ge(0))(1));
2518 EXPECT_FALSE(Matches(Eq('a'))('b'));
2519}
2520
2521// Tests that Matches(m) works when the matcher takes its argument by
2522// reference.
2523TEST(MatchesTest, WorksOnByRefArguments) {
2524 int m = 0, n = 0;
2525 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2526 EXPECT_FALSE(Matches(Ref(m))(n));
2527}
2528
2529// Tests that a Matcher on non-reference type can be used in
2530// Matches().
2531TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
2532 Matcher<int> eq5 = Eq(5);
2533 EXPECT_TRUE(Matches(eq5)(5));
2534 EXPECT_FALSE(Matches(eq5)(2));
2535}
2536
zhanyong.wanb8243162009-06-04 05:48:20 +00002537// Tests Value(value, matcher). Since Value() is a simple wrapper for
2538// Matches(), which has been tested already, we don't spend a lot of
2539// effort on testing Value().
2540TEST(ValueTest, WorksWithPolymorphicMatcher) {
2541 EXPECT_TRUE(Value("hi", StartsWith("h")));
2542 EXPECT_FALSE(Value(5, Gt(10)));
2543}
2544
2545TEST(ValueTest, WorksWithMonomorphicMatcher) {
2546 const Matcher<int> is_zero = Eq(0);
2547 EXPECT_TRUE(Value(0, is_zero));
2548 EXPECT_FALSE(Value('a', is_zero));
2549
2550 int n = 0;
2551 const Matcher<const int&> ref_n = Ref(n);
2552 EXPECT_TRUE(Value(n, ref_n));
2553 EXPECT_FALSE(Value(1, ref_n));
2554}
2555
zhanyong.wana862f1d2010-03-15 21:23:04 +00002556TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002557 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002558 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002559 EXPECT_EQ("% 2 == 0", listener1.str());
2560
2561 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002562 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002563 EXPECT_EQ("", listener2.str());
2564}
2565
zhanyong.wana862f1d2010-03-15 21:23:04 +00002566TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002567 const Matcher<int> is_even = PolymorphicIsEven();
2568 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002569 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002570 EXPECT_EQ("% 2 == 0", listener1.str());
2571
2572 const Matcher<const double&> is_zero = Eq(0);
2573 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002574 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002575 EXPECT_EQ("", listener2.str());
2576}
2577
zhanyong.wana862f1d2010-03-15 21:23:04 +00002578MATCHER_P(Really, inner_matcher, "") {
2579 return ExplainMatchResult(inner_matcher, arg, result_listener);
2580}
2581
2582TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
2583 EXPECT_THAT(0, Really(Eq(0)));
2584}
2585
zhanyong.wanbf550852009-06-09 06:09:53 +00002586TEST(AllArgsTest, WorksForTuple) {
2587 EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
2588 EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
2589}
2590
2591TEST(AllArgsTest, WorksForNonTuple) {
2592 EXPECT_THAT(42, AllArgs(Gt(0)));
2593 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
2594}
2595
2596class AllArgsHelper {
2597 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002598 AllArgsHelper() {}
2599
zhanyong.wanbf550852009-06-09 06:09:53 +00002600 MOCK_METHOD2(Helper, int(char x, int y));
zhanyong.wan32de5f52009-12-23 00:13:23 +00002601
2602 private:
2603 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
zhanyong.wanbf550852009-06-09 06:09:53 +00002604};
2605
2606TEST(AllArgsTest, WorksInWithClause) {
2607 AllArgsHelper helper;
2608 ON_CALL(helper, Helper(_, _))
2609 .With(AllArgs(Lt()))
2610 .WillByDefault(Return(1));
2611 EXPECT_CALL(helper, Helper(_, _));
2612 EXPECT_CALL(helper, Helper(_, _))
2613 .With(AllArgs(Gt()))
2614 .WillOnce(Return(2));
2615
2616 EXPECT_EQ(1, helper.Helper('\1', 2));
2617 EXPECT_EQ(2, helper.Helper('a', 1));
2618}
2619
shiqiane35fdd92008-12-10 05:08:54 +00002620// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2621// matches the matcher.
2622TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
2623 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
2624 ASSERT_THAT("Foo", EndsWith("oo"));
2625 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
2626 EXPECT_THAT("Hello", StartsWith("Hell"));
2627}
2628
2629// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2630// doesn't match the matcher.
2631TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
2632 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
2633 // which cannot reference auto variables.
zhanyong.wan736baa82010-09-27 17:44:16 +00002634 static unsigned short n; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00002635 n = 5;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002636
2637 // VC++ prior to version 8.0 SP1 has a bug where it will not see any
2638 // functions declared in the namespace scope from within nested classes.
2639 // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
2640 // namespace-level functions invoked inside them need to be explicitly
2641 // resolved.
2642 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
shiqiane35fdd92008-12-10 05:08:54 +00002643 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002644 "Expected: is > 10\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002645 " Actual: 5" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002646 n = 0;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002647 EXPECT_NONFATAL_FAILURE(
2648 EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
2649 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002650 "Expected: (is <= 7) and (is >= 5)\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002651 " Actual: 0" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002652}
2653
2654// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
2655// has a reference type.
2656TEST(MatcherAssertionTest, WorksForByRefArguments) {
2657 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
2658 // reference auto variables.
2659 static int n;
2660 n = 0;
2661 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002662 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
shiqiane35fdd92008-12-10 05:08:54 +00002663 "Value of: n\n"
2664 "Expected: does not reference the variable @");
2665 // Tests the "Actual" part.
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002666 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
zhanyong.wan736baa82010-09-27 17:44:16 +00002667 "Actual: 0" + OfType("int") + ", which is located @");
shiqiane35fdd92008-12-10 05:08:54 +00002668}
2669
zhanyong.wan95b12332009-09-25 18:55:50 +00002670#if !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002671// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
2672// monomorphic.
zhanyong.wan95b12332009-09-25 18:55:50 +00002673
2674// ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
2675// Symbian compiler: it tries to compile
2676// template<T, U> class MatcherCastImpl { ...
zhanyong.wandb22c222010-01-28 21:52:29 +00002677// virtual bool MatchAndExplain(T x, ...) const {
2678// return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
zhanyong.wan95b12332009-09-25 18:55:50 +00002679// with U == string and T == const char*
2680// With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
2681// the compiler silently crashes with no output.
2682// If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
2683// the code compiles but the converted string is bogus.
shiqiane35fdd92008-12-10 05:08:54 +00002684TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
2685 Matcher<const char*> starts_with_he = StartsWith("he");
2686 ASSERT_THAT("hello", starts_with_he);
2687
Nico Weber09fd5b32017-05-15 17:07:03 -04002688 Matcher<const std::string&> ends_with_ok = EndsWith("ok");
shiqiane35fdd92008-12-10 05:08:54 +00002689 ASSERT_THAT("book", ends_with_ok);
Nico Weber09fd5b32017-05-15 17:07:03 -04002690 const std::string bad = "bad";
zhanyong.wan736baa82010-09-27 17:44:16 +00002691 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
2692 "Value of: bad\n"
2693 "Expected: ends with \"ok\"\n"
2694 " Actual: \"bad\"");
shiqiane35fdd92008-12-10 05:08:54 +00002695 Matcher<int> is_greater_than_5 = Gt(5);
2696 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
2697 "Value of: 5\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002698 "Expected: is > 5\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002699 " Actual: 5" + OfType("int"));
shiqiane35fdd92008-12-10 05:08:54 +00002700}
zhanyong.wan95b12332009-09-25 18:55:50 +00002701#endif // !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002702
2703// Tests floating-point matchers.
2704template <typename RawType>
2705class FloatingPointTest : public testing::Test {
2706 protected:
zhanyong.wan35877b72013-09-18 17:51:08 +00002707 typedef testing::internal::FloatingPoint<RawType> Floating;
shiqiane35fdd92008-12-10 05:08:54 +00002708 typedef typename Floating::Bits Bits;
2709
zhanyong.wan35877b72013-09-18 17:51:08 +00002710 FloatingPointTest()
2711 : max_ulps_(Floating::kMaxUlps),
2712 zero_bits_(Floating(0).bits()),
2713 one_bits_(Floating(1).bits()),
2714 infinity_bits_(Floating(Floating::Infinity()).bits()),
Mark Mentovai4a8e5442015-11-12 10:01:06 -05002715 close_to_positive_zero_(AsBits(zero_bits_ + max_ulps_/2)),
2716 close_to_negative_zero_(AsBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
2717 further_from_negative_zero_(-AsBits(
Mark Mentovaicfe466a2015-11-11 18:26:35 -05002718 zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
Mark Mentovai4a8e5442015-11-12 10:01:06 -05002719 close_to_one_(AsBits(one_bits_ + max_ulps_)),
2720 further_from_one_(AsBits(one_bits_ + max_ulps_ + 1)),
zhanyong.wan35877b72013-09-18 17:51:08 +00002721 infinity_(Floating::Infinity()),
Mark Mentovai4a8e5442015-11-12 10:01:06 -05002722 close_to_infinity_(AsBits(infinity_bits_ - max_ulps_)),
2723 further_from_infinity_(AsBits(infinity_bits_ - max_ulps_ - 1)),
zhanyong.wan35877b72013-09-18 17:51:08 +00002724 max_(Floating::Max()),
Mark Mentovai4a8e5442015-11-12 10:01:06 -05002725 nan1_(AsBits(Floating::kExponentBitMask | 1)),
2726 nan2_(AsBits(Floating::kExponentBitMask | 200)) {
shiqiane35fdd92008-12-10 05:08:54 +00002727 }
2728
2729 void TestSize() {
2730 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2731 }
2732
2733 // A battery of tests for FloatingEqMatcher::Matches.
2734 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2735 void TestMatches(
2736 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
2737 Matcher<RawType> m1 = matcher_maker(0.0);
2738 EXPECT_TRUE(m1.Matches(-0.0));
2739 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
2740 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
2741 EXPECT_FALSE(m1.Matches(1.0));
2742
2743 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
2744 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
2745
2746 Matcher<RawType> m3 = matcher_maker(1.0);
2747 EXPECT_TRUE(m3.Matches(close_to_one_));
2748 EXPECT_FALSE(m3.Matches(further_from_one_));
2749
2750 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
2751 EXPECT_FALSE(m3.Matches(0.0));
2752
2753 Matcher<RawType> m4 = matcher_maker(-infinity_);
2754 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
2755
2756 Matcher<RawType> m5 = matcher_maker(infinity_);
2757 EXPECT_TRUE(m5.Matches(close_to_infinity_));
2758
2759 // This is interesting as the representations of infinity_ and nan1_
2760 // are only 1 DLP apart.
2761 EXPECT_FALSE(m5.Matches(nan1_));
2762
2763 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2764 // some cases.
2765 Matcher<const RawType&> m6 = matcher_maker(0.0);
2766 EXPECT_TRUE(m6.Matches(-0.0));
2767 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
2768 EXPECT_FALSE(m6.Matches(1.0));
2769
2770 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2771 // cases.
2772 Matcher<RawType&> m7 = matcher_maker(0.0);
2773 RawType x = 0.0;
2774 EXPECT_TRUE(m7.Matches(x));
2775 x = 0.01f;
2776 EXPECT_FALSE(m7.Matches(x));
2777 }
2778
2779 // Pre-calculated numbers to be used by the tests.
2780
Mark Mentovaicbce23f2015-11-11 17:44:12 -05002781 const size_t max_ulps_;
shiqiane35fdd92008-12-10 05:08:54 +00002782
zhanyong.wan35877b72013-09-18 17:51:08 +00002783 const Bits zero_bits_; // The bits that represent 0.0.
2784 const Bits one_bits_; // The bits that represent 1.0.
2785 const Bits infinity_bits_; // The bits that represent +infinity.
shiqiane35fdd92008-12-10 05:08:54 +00002786
zhanyong.wan35877b72013-09-18 17:51:08 +00002787 // Some numbers close to 0.0.
2788 const RawType close_to_positive_zero_;
2789 const RawType close_to_negative_zero_;
2790 const RawType further_from_negative_zero_;
shiqiane35fdd92008-12-10 05:08:54 +00002791
zhanyong.wan35877b72013-09-18 17:51:08 +00002792 // Some numbers close to 1.0.
2793 const RawType close_to_one_;
2794 const RawType further_from_one_;
2795
2796 // Some numbers close to +infinity.
2797 const RawType infinity_;
2798 const RawType close_to_infinity_;
2799 const RawType further_from_infinity_;
2800
2801 // Maximum representable value that's not infinity.
2802 const RawType max_;
2803
2804 // Some NaNs.
2805 const RawType nan1_;
2806 const RawType nan2_;
Mark Mentovaicfe466a2015-11-11 18:26:35 -05002807
2808 private:
2809 template <typename T>
Mark Mentovai4a8e5442015-11-12 10:01:06 -05002810 static RawType AsBits(T value) {
Mark Mentovaicfe466a2015-11-11 18:26:35 -05002811 return Floating::ReinterpretBits(static_cast<Bits>(value));
2812 }
shiqiane35fdd92008-12-10 05:08:54 +00002813};
2814
zhanyong.wan616180e2013-06-18 18:49:51 +00002815// Tests floating-point matchers with fixed epsilons.
2816template <typename RawType>
2817class FloatingPointNearTest : public FloatingPointTest<RawType> {
2818 protected:
2819 typedef FloatingPointTest<RawType> ParentType;
2820
2821 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
2822 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2823 void TestNearMatches(
2824 testing::internal::FloatingEqMatcher<RawType>
2825 (*matcher_maker)(RawType, RawType)) {
2826 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
2827 EXPECT_TRUE(m1.Matches(0.0));
2828 EXPECT_TRUE(m1.Matches(-0.0));
2829 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
2830 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
2831 EXPECT_FALSE(m1.Matches(1.0));
2832
2833 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
2834 EXPECT_TRUE(m2.Matches(0.0));
2835 EXPECT_TRUE(m2.Matches(-0.0));
2836 EXPECT_TRUE(m2.Matches(1.0));
2837 EXPECT_TRUE(m2.Matches(-1.0));
2838 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
2839 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
2840
2841 // Check that inf matches inf, regardless of the of the specified max
2842 // absolute error.
2843 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
2844 EXPECT_TRUE(m3.Matches(ParentType::infinity_));
2845 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
2846 EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
2847
2848 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
2849 EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
2850 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
2851 EXPECT_FALSE(m4.Matches(ParentType::infinity_));
2852
2853 // Test various overflow scenarios.
zhanyong.wan35877b72013-09-18 17:51:08 +00002854 Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
2855 EXPECT_TRUE(m5.Matches(ParentType::max_));
2856 EXPECT_FALSE(m5.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002857
zhanyong.wan35877b72013-09-18 17:51:08 +00002858 Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
2859 EXPECT_FALSE(m6.Matches(ParentType::max_));
2860 EXPECT_TRUE(m6.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002861
zhanyong.wan35877b72013-09-18 17:51:08 +00002862 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
2863 EXPECT_TRUE(m7.Matches(ParentType::max_));
2864 EXPECT_FALSE(m7.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002865
zhanyong.wan35877b72013-09-18 17:51:08 +00002866 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
2867 EXPECT_FALSE(m8.Matches(ParentType::max_));
2868 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002869
2870 // The difference between max() and -max() normally overflows to infinity,
2871 // but it should still match if the max_abs_error is also infinity.
2872 Matcher<RawType> m9 = matcher_maker(
zhanyong.wan35877b72013-09-18 17:51:08 +00002873 ParentType::max_, ParentType::infinity_);
2874 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002875
2876 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2877 // some cases.
2878 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
2879 EXPECT_TRUE(m10.Matches(-0.0));
2880 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
2881 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
2882
2883 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2884 // cases.
2885 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
2886 RawType x = 0.0;
2887 EXPECT_TRUE(m11.Matches(x));
2888 x = 1.0f;
2889 EXPECT_TRUE(m11.Matches(x));
2890 x = -1.0f;
2891 EXPECT_TRUE(m11.Matches(x));
2892 x = 1.1f;
2893 EXPECT_FALSE(m11.Matches(x));
2894 x = -1.1f;
2895 EXPECT_FALSE(m11.Matches(x));
2896 }
2897};
2898
shiqiane35fdd92008-12-10 05:08:54 +00002899// Instantiate FloatingPointTest for testing floats.
2900typedef FloatingPointTest<float> FloatTest;
2901
2902TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
2903 TestMatches(&FloatEq);
2904}
2905
2906TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
2907 TestMatches(&NanSensitiveFloatEq);
2908}
2909
2910TEST_F(FloatTest, FloatEqCannotMatchNaN) {
2911 // FloatEq never matches NaN.
2912 Matcher<float> m = FloatEq(nan1_);
2913 EXPECT_FALSE(m.Matches(nan1_));
2914 EXPECT_FALSE(m.Matches(nan2_));
2915 EXPECT_FALSE(m.Matches(1.0));
2916}
2917
2918TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
2919 // NanSensitiveFloatEq will match NaN.
2920 Matcher<float> m = NanSensitiveFloatEq(nan1_);
2921 EXPECT_TRUE(m.Matches(nan1_));
2922 EXPECT_TRUE(m.Matches(nan2_));
2923 EXPECT_FALSE(m.Matches(1.0));
2924}
2925
2926TEST_F(FloatTest, FloatEqCanDescribeSelf) {
2927 Matcher<float> m1 = FloatEq(2.0f);
2928 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002929 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002930
2931 Matcher<float> m2 = FloatEq(0.5f);
2932 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002933 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002934
2935 Matcher<float> m3 = FloatEq(nan1_);
2936 EXPECT_EQ("never matches", Describe(m3));
2937 EXPECT_EQ("is anything", DescribeNegation(m3));
2938}
2939
2940TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
2941 Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
2942 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002943 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002944
2945 Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
2946 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002947 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002948
2949 Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
2950 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002951 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00002952}
2953
zhanyong.wan616180e2013-06-18 18:49:51 +00002954// Instantiate FloatingPointTest for testing floats with a user-specified
2955// max absolute error.
2956typedef FloatingPointNearTest<float> FloatNearTest;
2957
2958TEST_F(FloatNearTest, FloatNearMatches) {
2959 TestNearMatches(&FloatNear);
2960}
2961
2962TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
2963 TestNearMatches(&NanSensitiveFloatNear);
2964}
2965
2966TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
2967 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
2968 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2969 EXPECT_EQ(
2970 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2971
2972 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
2973 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2974 EXPECT_EQ(
2975 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2976
2977 Matcher<float> m3 = FloatNear(nan1_, 0.0);
2978 EXPECT_EQ("never matches", Describe(m3));
2979 EXPECT_EQ("is anything", DescribeNegation(m3));
2980}
2981
2982TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
2983 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
2984 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2985 EXPECT_EQ(
2986 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2987
2988 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
2989 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2990 EXPECT_EQ(
2991 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2992
2993 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
2994 EXPECT_EQ("is NaN", Describe(m3));
2995 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
2996}
2997
2998TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
2999 // FloatNear never matches NaN.
3000 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
3001 EXPECT_FALSE(m.Matches(nan1_));
3002 EXPECT_FALSE(m.Matches(nan2_));
3003 EXPECT_FALSE(m.Matches(1.0));
3004}
3005
3006TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
3007 // NanSensitiveFloatNear will match NaN.
3008 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
3009 EXPECT_TRUE(m.Matches(nan1_));
3010 EXPECT_TRUE(m.Matches(nan2_));
3011 EXPECT_FALSE(m.Matches(1.0));
3012}
3013
shiqiane35fdd92008-12-10 05:08:54 +00003014// Instantiate FloatingPointTest for testing doubles.
3015typedef FloatingPointTest<double> DoubleTest;
3016
3017TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
3018 TestMatches(&DoubleEq);
3019}
3020
3021TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
3022 TestMatches(&NanSensitiveDoubleEq);
3023}
3024
3025TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
3026 // DoubleEq never matches NaN.
3027 Matcher<double> m = DoubleEq(nan1_);
3028 EXPECT_FALSE(m.Matches(nan1_));
3029 EXPECT_FALSE(m.Matches(nan2_));
3030 EXPECT_FALSE(m.Matches(1.0));
3031}
3032
3033TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3034 // NanSensitiveDoubleEq will match NaN.
3035 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
3036 EXPECT_TRUE(m.Matches(nan1_));
3037 EXPECT_TRUE(m.Matches(nan2_));
3038 EXPECT_FALSE(m.Matches(1.0));
3039}
3040
3041TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3042 Matcher<double> m1 = DoubleEq(2.0);
3043 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003044 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003045
3046 Matcher<double> m2 = DoubleEq(0.5);
3047 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003048 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003049
3050 Matcher<double> m3 = DoubleEq(nan1_);
3051 EXPECT_EQ("never matches", Describe(m3));
3052 EXPECT_EQ("is anything", DescribeNegation(m3));
3053}
3054
3055TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3056 Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3057 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003058 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003059
3060 Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3061 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003062 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003063
3064 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3065 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003066 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00003067}
3068
zhanyong.wan616180e2013-06-18 18:49:51 +00003069// Instantiate FloatingPointTest for testing floats with a user-specified
3070// max absolute error.
3071typedef FloatingPointNearTest<double> DoubleNearTest;
3072
3073TEST_F(DoubleNearTest, DoubleNearMatches) {
3074 TestNearMatches(&DoubleNear);
3075}
3076
3077TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3078 TestNearMatches(&NanSensitiveDoubleNear);
3079}
3080
3081TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3082 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3083 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3084 EXPECT_EQ(
3085 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3086
3087 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3088 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3089 EXPECT_EQ(
3090 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3091
3092 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3093 EXPECT_EQ("never matches", Describe(m3));
3094 EXPECT_EQ("is anything", DescribeNegation(m3));
3095}
3096
kosak6b817802015-01-08 02:38:14 +00003097TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
3098 EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
3099 EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
3100 EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
3101
Nico Weber09fd5b32017-05-15 17:07:03 -04003102 const std::string explanation =
3103 Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
kosak6b817802015-01-08 02:38:14 +00003104 // Different C++ implementations may print floating-point numbers
3105 // slightly differently.
3106 EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC
3107 explanation == "which is 1.2e-010 from 2.1") // MSVC
3108 << " where explanation is \"" << explanation << "\".";
3109}
3110
zhanyong.wan616180e2013-06-18 18:49:51 +00003111TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3112 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3113 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3114 EXPECT_EQ(
3115 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3116
3117 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3118 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3119 EXPECT_EQ(
3120 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3121
3122 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3123 EXPECT_EQ("is NaN", Describe(m3));
3124 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3125}
3126
3127TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3128 // DoubleNear never matches NaN.
3129 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3130 EXPECT_FALSE(m.Matches(nan1_));
3131 EXPECT_FALSE(m.Matches(nan2_));
3132 EXPECT_FALSE(m.Matches(1.0));
3133}
3134
3135TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3136 // NanSensitiveDoubleNear will match NaN.
3137 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3138 EXPECT_TRUE(m.Matches(nan1_));
3139 EXPECT_TRUE(m.Matches(nan2_));
3140 EXPECT_FALSE(m.Matches(1.0));
3141}
3142
shiqiane35fdd92008-12-10 05:08:54 +00003143TEST(PointeeTest, RawPointer) {
3144 const Matcher<int*> m = Pointee(Ge(0));
3145
3146 int n = 1;
3147 EXPECT_TRUE(m.Matches(&n));
3148 n = -1;
3149 EXPECT_FALSE(m.Matches(&n));
3150 EXPECT_FALSE(m.Matches(NULL));
3151}
3152
3153TEST(PointeeTest, RawPointerToConst) {
3154 const Matcher<const double*> m = Pointee(Ge(0));
3155
3156 double x = 1;
3157 EXPECT_TRUE(m.Matches(&x));
3158 x = -1;
3159 EXPECT_FALSE(m.Matches(&x));
3160 EXPECT_FALSE(m.Matches(NULL));
3161}
3162
3163TEST(PointeeTest, ReferenceToConstRawPointer) {
3164 const Matcher<int* const &> m = Pointee(Ge(0));
3165
3166 int n = 1;
3167 EXPECT_TRUE(m.Matches(&n));
3168 n = -1;
3169 EXPECT_FALSE(m.Matches(&n));
3170 EXPECT_FALSE(m.Matches(NULL));
3171}
3172
3173TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3174 const Matcher<double* &> m = Pointee(Ge(0));
3175
3176 double x = 1.0;
3177 double* p = &x;
3178 EXPECT_TRUE(m.Matches(p));
3179 x = -1;
3180 EXPECT_FALSE(m.Matches(p));
3181 p = NULL;
3182 EXPECT_FALSE(m.Matches(p));
3183}
3184
billydonahue1f5fdea2014-05-19 17:54:51 +00003185MATCHER_P(FieldIIs, inner_matcher, "") {
3186 return ExplainMatchResult(inner_matcher, arg.i, result_listener);
3187}
3188
Mark Mentovaic8a10502015-10-12 18:01:43 -04003189#if GTEST_HAS_RTTI
3190
billydonahue1f5fdea2014-05-19 17:54:51 +00003191TEST(WhenDynamicCastToTest, SameType) {
3192 Derived derived;
3193 derived.i = 4;
3194
3195 // Right type. A pointer is passed down.
3196 Base* as_base_ptr = &derived;
3197 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
3198 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
3199 EXPECT_THAT(as_base_ptr,
3200 Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
3201}
3202
3203TEST(WhenDynamicCastToTest, WrongTypes) {
3204 Base base;
3205 Derived derived;
3206 OtherDerived other_derived;
3207
3208 // Wrong types. NULL is passed.
3209 EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3210 EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
3211 Base* as_base_ptr = &derived;
3212 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
3213 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
3214 as_base_ptr = &other_derived;
3215 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3216 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3217}
3218
3219TEST(WhenDynamicCastToTest, AlreadyNull) {
3220 // Already NULL.
3221 Base* as_base_ptr = NULL;
3222 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3223}
3224
3225struct AmbiguousCastTypes {
3226 class VirtualDerived : public virtual Base {};
3227 class DerivedSub1 : public VirtualDerived {};
3228 class DerivedSub2 : public VirtualDerived {};
3229 class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
3230};
3231
3232TEST(WhenDynamicCastToTest, AmbiguousCast) {
3233 AmbiguousCastTypes::DerivedSub1 sub1;
3234 AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
3235 // Multiply derived from Base. dynamic_cast<> returns NULL.
3236 Base* as_base_ptr =
3237 static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
3238 EXPECT_THAT(as_base_ptr,
3239 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
3240 as_base_ptr = &sub1;
3241 EXPECT_THAT(
3242 as_base_ptr,
3243 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
3244}
3245
3246TEST(WhenDynamicCastToTest, Describe) {
3247 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
billydonahue1f5fdea2014-05-19 17:54:51 +00003248 const string prefix =
3249 "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
billydonahue1f5fdea2014-05-19 17:54:51 +00003250 EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
3251 EXPECT_EQ(prefix + "does not point to a value that is anything",
3252 DescribeNegation(matcher));
3253}
3254
3255TEST(WhenDynamicCastToTest, Explain) {
3256 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3257 Base* null = NULL;
3258 EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
3259 Derived derived;
3260 EXPECT_TRUE(matcher.Matches(&derived));
3261 EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
3262
3263 // With references, the matcher itself can fail. Test for that one.
3264 Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
3265 EXPECT_THAT(Explain(ref_matcher, derived),
3266 HasSubstr("which cannot be dynamic_cast"));
3267}
3268
3269TEST(WhenDynamicCastToTest, GoodReference) {
3270 Derived derived;
3271 derived.i = 4;
3272 Base& as_base_ref = derived;
3273 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
3274 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
3275}
3276
3277TEST(WhenDynamicCastToTest, BadReference) {
3278 Derived derived;
3279 Base& as_base_ref = derived;
3280 EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
3281}
3282
Mark Mentovaic8a10502015-10-12 18:01:43 -04003283#endif // GTEST_HAS_RTTI
3284
vladlosevada23472012-08-14 15:38:49 +00003285// Minimal const-propagating pointer.
3286template <typename T>
3287class ConstPropagatingPtr {
3288 public:
3289 typedef T element_type;
3290
3291 ConstPropagatingPtr() : val_() {}
3292 explicit ConstPropagatingPtr(T* t) : val_(t) {}
3293 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3294
3295 T* get() { return val_; }
3296 T& operator*() { return *val_; }
3297 // Most smart pointers return non-const T* and T& from the next methods.
3298 const T* get() const { return val_; }
3299 const T& operator*() const { return *val_; }
3300
3301 private:
3302 T* val_;
3303};
3304
3305TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3306 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3307 int three = 3;
3308 const ConstPropagatingPtr<int> co(&three);
3309 ConstPropagatingPtr<int> o(&three);
3310 EXPECT_TRUE(m.Matches(o));
3311 EXPECT_TRUE(m.Matches(co));
3312 *o = 6;
3313 EXPECT_FALSE(m.Matches(o));
3314 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3315}
3316
shiqiane35fdd92008-12-10 05:08:54 +00003317TEST(PointeeTest, NeverMatchesNull) {
3318 const Matcher<const char*> m = Pointee(_);
3319 EXPECT_FALSE(m.Matches(NULL));
3320}
3321
3322// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3323TEST(PointeeTest, MatchesAgainstAValue) {
3324 const Matcher<int*> m = Pointee(5);
3325
3326 int n = 5;
3327 EXPECT_TRUE(m.Matches(&n));
3328 n = -1;
3329 EXPECT_FALSE(m.Matches(&n));
3330 EXPECT_FALSE(m.Matches(NULL));
3331}
3332
3333TEST(PointeeTest, CanDescribeSelf) {
3334 const Matcher<int*> m = Pointee(Gt(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003335 EXPECT_EQ("points to a value that is > 3", Describe(m));
3336 EXPECT_EQ("does not point to a value that is > 3",
shiqiane35fdd92008-12-10 05:08:54 +00003337 DescribeNegation(m));
3338}
3339
shiqiane35fdd92008-12-10 05:08:54 +00003340TEST(PointeeTest, CanExplainMatchResult) {
Nico Weber09fd5b32017-05-15 17:07:03 -04003341 const Matcher<const std::string*> m = Pointee(StartsWith("Hi"));
shiqiane35fdd92008-12-10 05:08:54 +00003342
Nico Weber09fd5b32017-05-15 17:07:03 -04003343 EXPECT_EQ("", Explain(m, static_cast<const std::string*>(NULL)));
shiqiane35fdd92008-12-10 05:08:54 +00003344
zhanyong.wan736baa82010-09-27 17:44:16 +00003345 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
3346 long n = 3; // NOLINT
3347 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003348 Explain(m2, &n));
3349}
3350
3351TEST(PointeeTest, AlwaysExplainsPointee) {
3352 const Matcher<int*> m = Pointee(0);
3353 int n = 42;
zhanyong.wan736baa82010-09-27 17:44:16 +00003354 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
shiqiane35fdd92008-12-10 05:08:54 +00003355}
3356
3357// An uncopyable class.
3358class Uncopyable {
3359 public:
billydonahue1f5fdea2014-05-19 17:54:51 +00003360 Uncopyable() : value_(-1) {}
zhanyong.wan32de5f52009-12-23 00:13:23 +00003361 explicit Uncopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003362
3363 int value() const { return value_; }
billydonahue1f5fdea2014-05-19 17:54:51 +00003364 void set_value(int i) { value_ = i; }
3365
shiqiane35fdd92008-12-10 05:08:54 +00003366 private:
billydonahue1f5fdea2014-05-19 17:54:51 +00003367 int value_;
shiqiane35fdd92008-12-10 05:08:54 +00003368 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3369};
3370
3371// Returns true iff x.value() is positive.
3372bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3373
billydonahue1f5fdea2014-05-19 17:54:51 +00003374MATCHER_P(UncopyableIs, inner_matcher, "") {
3375 return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
3376}
3377
shiqiane35fdd92008-12-10 05:08:54 +00003378// A user-defined struct for testing Field().
3379struct AStruct {
3380 AStruct() : x(0), y(1.0), z(5), p(NULL) {}
3381 AStruct(const AStruct& rhs)
3382 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3383
3384 int x; // A non-const field.
3385 const double y; // A const field.
3386 Uncopyable z; // An uncopyable field.
3387 const char* p; // A pointer field.
zhanyong.wan32de5f52009-12-23 00:13:23 +00003388
3389 private:
3390 GTEST_DISALLOW_ASSIGN_(AStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003391};
3392
3393// A derived struct for testing Field().
3394struct DerivedStruct : public AStruct {
3395 char ch;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003396
3397 private:
3398 GTEST_DISALLOW_ASSIGN_(DerivedStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003399};
3400
3401// Tests that Field(&Foo::field, ...) works when field is non-const.
3402TEST(FieldTest, WorksForNonConstField) {
3403 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
3404
3405 AStruct a;
3406 EXPECT_TRUE(m.Matches(a));
3407 a.x = -1;
3408 EXPECT_FALSE(m.Matches(a));
3409}
3410
3411// Tests that Field(&Foo::field, ...) works when field is const.
3412TEST(FieldTest, WorksForConstField) {
3413 AStruct a;
3414
3415 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
3416 EXPECT_TRUE(m.Matches(a));
3417 m = Field(&AStruct::y, Le(0.0));
3418 EXPECT_FALSE(m.Matches(a));
3419}
3420
3421// Tests that Field(&Foo::field, ...) works when field is not copyable.
3422TEST(FieldTest, WorksForUncopyableField) {
3423 AStruct a;
3424
3425 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3426 EXPECT_TRUE(m.Matches(a));
3427 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3428 EXPECT_FALSE(m.Matches(a));
3429}
3430
3431// Tests that Field(&Foo::field, ...) works when field is a pointer.
3432TEST(FieldTest, WorksForPointerField) {
3433 // Matching against NULL.
3434 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
3435 AStruct a;
3436 EXPECT_TRUE(m.Matches(a));
3437 a.p = "hi";
3438 EXPECT_FALSE(m.Matches(a));
3439
3440 // Matching a pointer that is not NULL.
3441 m = Field(&AStruct::p, StartsWith("hi"));
3442 a.p = "hill";
3443 EXPECT_TRUE(m.Matches(a));
3444 a.p = "hole";
3445 EXPECT_FALSE(m.Matches(a));
3446}
3447
3448// Tests that Field() works when the object is passed by reference.
3449TEST(FieldTest, WorksForByRefArgument) {
3450 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3451
3452 AStruct a;
3453 EXPECT_TRUE(m.Matches(a));
3454 a.x = -1;
3455 EXPECT_FALSE(m.Matches(a));
3456}
3457
3458// Tests that Field(&Foo::field, ...) works when the argument's type
3459// is a sub-type of Foo.
3460TEST(FieldTest, WorksForArgumentOfSubType) {
3461 // Note that the matcher expects DerivedStruct but we say AStruct
3462 // inside Field().
3463 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
3464
3465 DerivedStruct d;
3466 EXPECT_TRUE(m.Matches(d));
3467 d.x = -1;
3468 EXPECT_FALSE(m.Matches(d));
3469}
3470
3471// Tests that Field(&Foo::field, m) works when field's type and m's
3472// argument type are compatible but not the same.
3473TEST(FieldTest, WorksForCompatibleMatcherType) {
3474 // The field is an int, but the inner matcher expects a signed char.
3475 Matcher<const AStruct&> m = Field(&AStruct::x,
3476 Matcher<signed char>(Ge(0)));
3477
3478 AStruct a;
3479 EXPECT_TRUE(m.Matches(a));
3480 a.x = -1;
3481 EXPECT_FALSE(m.Matches(a));
3482}
3483
3484// Tests that Field() can describe itself.
3485TEST(FieldTest, CanDescribeSelf) {
3486 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3487
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003488 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3489 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003490}
3491
3492// Tests that Field() can explain the match result.
3493TEST(FieldTest, CanExplainMatchResult) {
3494 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3495
3496 AStruct a;
3497 a.x = 1;
zhanyong.wan736baa82010-09-27 17:44:16 +00003498 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003499
3500 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003501 EXPECT_EQ(
3502 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
3503 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003504}
3505
3506// Tests that Field() works when the argument is a pointer to const.
3507TEST(FieldForPointerTest, WorksForPointerToConst) {
3508 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3509
3510 AStruct a;
3511 EXPECT_TRUE(m.Matches(&a));
3512 a.x = -1;
3513 EXPECT_FALSE(m.Matches(&a));
3514}
3515
3516// Tests that Field() works when the argument is a pointer to non-const.
3517TEST(FieldForPointerTest, WorksForPointerToNonConst) {
3518 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
3519
3520 AStruct a;
3521 EXPECT_TRUE(m.Matches(&a));
3522 a.x = -1;
3523 EXPECT_FALSE(m.Matches(&a));
3524}
3525
zhanyong.wan6953a722010-01-13 05:15:07 +00003526// Tests that Field() works when the argument is a reference to a const pointer.
3527TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
3528 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
3529
3530 AStruct a;
3531 EXPECT_TRUE(m.Matches(&a));
3532 a.x = -1;
3533 EXPECT_FALSE(m.Matches(&a));
3534}
3535
shiqiane35fdd92008-12-10 05:08:54 +00003536// Tests that Field() does not match the NULL pointer.
3537TEST(FieldForPointerTest, DoesNotMatchNull) {
3538 Matcher<const AStruct*> m = Field(&AStruct::x, _);
3539 EXPECT_FALSE(m.Matches(NULL));
3540}
3541
3542// Tests that Field(&Foo::field, ...) works when the argument's type
3543// is a sub-type of const Foo*.
3544TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
3545 // Note that the matcher expects DerivedStruct but we say AStruct
3546 // inside Field().
3547 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
3548
3549 DerivedStruct d;
3550 EXPECT_TRUE(m.Matches(&d));
3551 d.x = -1;
3552 EXPECT_FALSE(m.Matches(&d));
3553}
3554
3555// Tests that Field() can describe itself when used to match a pointer.
3556TEST(FieldForPointerTest, CanDescribeSelf) {
3557 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3558
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003559 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3560 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003561}
3562
3563// Tests that Field() can explain the result of matching a pointer.
3564TEST(FieldForPointerTest, CanExplainMatchResult) {
3565 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3566
3567 AStruct a;
3568 a.x = 1;
3569 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003570 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
3571 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003572
3573 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003574 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
3575 ", which is 1 more than 0", Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003576}
3577
3578// A user-defined class for testing Property().
3579class AClass {
3580 public:
3581 AClass() : n_(0) {}
3582
3583 // A getter that returns a non-reference.
3584 int n() const { return n_; }
3585
3586 void set_n(int new_n) { n_ = new_n; }
3587
3588 // A getter that returns a reference to const.
Nico Weber09fd5b32017-05-15 17:07:03 -04003589 const std::string& s() const { return s_; }
shiqiane35fdd92008-12-10 05:08:54 +00003590
Nico Weber09fd5b32017-05-15 17:07:03 -04003591 void set_s(const std::string& new_s) { s_ = new_s; }
shiqiane35fdd92008-12-10 05:08:54 +00003592
3593 // A getter that returns a reference to non-const.
3594 double& x() const { return x_; }
3595 private:
3596 int n_;
Nico Weber09fd5b32017-05-15 17:07:03 -04003597 std::string s_;
shiqiane35fdd92008-12-10 05:08:54 +00003598
3599 static double x_;
3600};
3601
3602double AClass::x_ = 0.0;
3603
3604// A derived class for testing Property().
3605class DerivedClass : public AClass {
kosak6414d802013-12-03 23:19:36 +00003606 public:
3607 int k() const { return k_; }
shiqiane35fdd92008-12-10 05:08:54 +00003608 private:
3609 int k_;
3610};
3611
3612// Tests that Property(&Foo::property, ...) works when property()
3613// returns a non-reference.
3614TEST(PropertyTest, WorksForNonReferenceProperty) {
3615 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3616
3617 AClass a;
3618 a.set_n(1);
3619 EXPECT_TRUE(m.Matches(a));
3620
3621 a.set_n(-1);
3622 EXPECT_FALSE(m.Matches(a));
3623}
3624
3625// Tests that Property(&Foo::property, ...) works when property()
3626// returns a reference to const.
3627TEST(PropertyTest, WorksForReferenceToConstProperty) {
3628 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
3629
3630 AClass a;
3631 a.set_s("hill");
3632 EXPECT_TRUE(m.Matches(a));
3633
3634 a.set_s("hole");
3635 EXPECT_FALSE(m.Matches(a));
3636}
3637
3638// Tests that Property(&Foo::property, ...) works when property()
3639// returns a reference to non-const.
3640TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
3641 double x = 0.0;
3642 AClass a;
3643
3644 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
3645 EXPECT_FALSE(m.Matches(a));
3646
3647 m = Property(&AClass::x, Not(Ref(x)));
3648 EXPECT_TRUE(m.Matches(a));
3649}
3650
3651// Tests that Property(&Foo::property, ...) works when the argument is
3652// passed by value.
3653TEST(PropertyTest, WorksForByValueArgument) {
3654 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
3655
3656 AClass a;
3657 a.set_s("hill");
3658 EXPECT_TRUE(m.Matches(a));
3659
3660 a.set_s("hole");
3661 EXPECT_FALSE(m.Matches(a));
3662}
3663
3664// Tests that Property(&Foo::property, ...) works when the argument's
3665// type is a sub-type of Foo.
3666TEST(PropertyTest, WorksForArgumentOfSubType) {
3667 // The matcher expects a DerivedClass, but inside the Property() we
3668 // say AClass.
3669 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
3670
3671 DerivedClass d;
3672 d.set_n(1);
3673 EXPECT_TRUE(m.Matches(d));
3674
3675 d.set_n(-1);
3676 EXPECT_FALSE(m.Matches(d));
3677}
3678
3679// Tests that Property(&Foo::property, m) works when property()'s type
3680// and m's argument type are compatible but different.
3681TEST(PropertyTest, WorksForCompatibleMatcherType) {
3682 // n() returns an int but the inner matcher expects a signed char.
3683 Matcher<const AClass&> m = Property(&AClass::n,
3684 Matcher<signed char>(Ge(0)));
3685
3686 AClass a;
3687 EXPECT_TRUE(m.Matches(a));
3688 a.set_n(-1);
3689 EXPECT_FALSE(m.Matches(a));
3690}
3691
3692// Tests that Property() can describe itself.
3693TEST(PropertyTest, CanDescribeSelf) {
3694 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3695
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003696 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3697 EXPECT_EQ("is an object whose given property isn't >= 0",
3698 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003699}
3700
3701// Tests that Property() can explain the match result.
3702TEST(PropertyTest, CanExplainMatchResult) {
3703 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3704
3705 AClass a;
3706 a.set_n(1);
zhanyong.wan736baa82010-09-27 17:44:16 +00003707 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003708
3709 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003710 EXPECT_EQ(
3711 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
3712 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003713}
3714
3715// Tests that Property() works when the argument is a pointer to const.
3716TEST(PropertyForPointerTest, WorksForPointerToConst) {
3717 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3718
3719 AClass a;
3720 a.set_n(1);
3721 EXPECT_TRUE(m.Matches(&a));
3722
3723 a.set_n(-1);
3724 EXPECT_FALSE(m.Matches(&a));
3725}
3726
3727// Tests that Property() works when the argument is a pointer to non-const.
3728TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
3729 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
3730
3731 AClass a;
3732 a.set_s("hill");
3733 EXPECT_TRUE(m.Matches(&a));
3734
3735 a.set_s("hole");
3736 EXPECT_FALSE(m.Matches(&a));
3737}
3738
zhanyong.wan6953a722010-01-13 05:15:07 +00003739// Tests that Property() works when the argument is a reference to a
3740// const pointer.
3741TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
3742 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
3743
3744 AClass a;
3745 a.set_s("hill");
3746 EXPECT_TRUE(m.Matches(&a));
3747
3748 a.set_s("hole");
3749 EXPECT_FALSE(m.Matches(&a));
3750}
3751
shiqiane35fdd92008-12-10 05:08:54 +00003752// Tests that Property() does not match the NULL pointer.
3753TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
3754 Matcher<const AClass*> m = Property(&AClass::x, _);
3755 EXPECT_FALSE(m.Matches(NULL));
3756}
3757
3758// Tests that Property(&Foo::property, ...) works when the argument's
3759// type is a sub-type of const Foo*.
3760TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
3761 // The matcher expects a DerivedClass, but inside the Property() we
3762 // say AClass.
3763 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
3764
3765 DerivedClass d;
3766 d.set_n(1);
3767 EXPECT_TRUE(m.Matches(&d));
3768
3769 d.set_n(-1);
3770 EXPECT_FALSE(m.Matches(&d));
3771}
3772
3773// Tests that Property() can describe itself when used to match a pointer.
3774TEST(PropertyForPointerTest, CanDescribeSelf) {
3775 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3776
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003777 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3778 EXPECT_EQ("is an object whose given property isn't >= 0",
3779 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003780}
3781
3782// Tests that Property() can explain the result of matching a pointer.
3783TEST(PropertyForPointerTest, CanExplainMatchResult) {
3784 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3785
3786 AClass a;
3787 a.set_n(1);
3788 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003789 EXPECT_EQ(
3790 "which points to an object whose given property is 1" + OfType("int"),
3791 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003792
3793 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003794 EXPECT_EQ("which points to an object whose given property is 1" +
3795 OfType("int") + ", which is 1 more than 0",
3796 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003797}
3798
3799// Tests ResultOf.
3800
3801// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3802// function pointer.
Nico Weber09fd5b32017-05-15 17:07:03 -04003803std::string IntToStringFunction(int input) {
3804 return input == 1 ? "foo" : "bar";
3805}
shiqiane35fdd92008-12-10 05:08:54 +00003806
3807TEST(ResultOfTest, WorksForFunctionPointers) {
Nico Weber09fd5b32017-05-15 17:07:03 -04003808 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo")));
shiqiane35fdd92008-12-10 05:08:54 +00003809
3810 EXPECT_TRUE(matcher.Matches(1));
3811 EXPECT_FALSE(matcher.Matches(2));
3812}
3813
3814// Tests that ResultOf() can describe itself.
3815TEST(ResultOfTest, CanDescribeItself) {
3816 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
3817
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003818 EXPECT_EQ("is mapped by the given callable to a value that "
3819 "is equal to \"foo\"", Describe(matcher));
3820 EXPECT_EQ("is mapped by the given callable to a value that "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003821 "isn't equal to \"foo\"", DescribeNegation(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00003822}
3823
3824// Tests that ResultOf() can explain the match result.
3825int IntFunction(int input) { return input == 42 ? 80 : 90; }
3826
3827TEST(ResultOfTest, CanExplainMatchResult) {
3828 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003829 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003830 Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003831
3832 matcher = ResultOf(&IntFunction, GreaterThan(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003833 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
3834 ", which is 5 more than 85", Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003835}
3836
3837// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3838// returns a non-reference.
3839TEST(ResultOfTest, WorksForNonReferenceResults) {
3840 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
3841
3842 EXPECT_TRUE(matcher.Matches(42));
3843 EXPECT_FALSE(matcher.Matches(36));
3844}
3845
3846// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3847// returns a reference to non-const.
zhanyong.wan736baa82010-09-27 17:44:16 +00003848double& DoubleFunction(double& input) { return input; } // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003849
zhanyong.wan736baa82010-09-27 17:44:16 +00003850Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003851 return obj;
3852}
3853
3854TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
3855 double x = 3.14;
3856 double x2 = x;
3857 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
3858
3859 EXPECT_TRUE(matcher.Matches(x));
3860 EXPECT_FALSE(matcher.Matches(x2));
3861
3862 // Test that ResultOf works with uncopyable objects
3863 Uncopyable obj(0);
3864 Uncopyable obj2(0);
3865 Matcher<Uncopyable&> matcher2 =
3866 ResultOf(&RefUncopyableFunction, Ref(obj));
3867
3868 EXPECT_TRUE(matcher2.Matches(obj));
3869 EXPECT_FALSE(matcher2.Matches(obj2));
3870}
3871
3872// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3873// returns a reference to const.
Nico Weber09fd5b32017-05-15 17:07:03 -04003874const std::string& StringFunction(const std::string& input) { return input; }
shiqiane35fdd92008-12-10 05:08:54 +00003875
3876TEST(ResultOfTest, WorksForReferenceToConstResults) {
Nico Weber09fd5b32017-05-15 17:07:03 -04003877 std::string s = "foo";
3878 std::string s2 = s;
3879 Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));
shiqiane35fdd92008-12-10 05:08:54 +00003880
3881 EXPECT_TRUE(matcher.Matches(s));
3882 EXPECT_FALSE(matcher.Matches(s2));
3883}
3884
3885// Tests that ResultOf(f, m) works when f(x) and m's
3886// argument types are compatible but different.
3887TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
3888 // IntFunction() returns int but the inner matcher expects a signed char.
3889 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
3890
3891 EXPECT_TRUE(matcher.Matches(36));
3892 EXPECT_FALSE(matcher.Matches(42));
3893}
3894
shiqiane35fdd92008-12-10 05:08:54 +00003895// Tests that the program aborts when ResultOf is passed
3896// a NULL function pointer.
3897TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
zhanyong.wan04d6ed82009-09-11 07:01:08 +00003898 EXPECT_DEATH_IF_SUPPORTED(
Nico Weber09fd5b32017-05-15 17:07:03 -04003899 ResultOf(static_cast<std::string (*)(int dummy)>(NULL),
3900 Eq(std::string("foo"))),
3901 "NULL function pointer is passed into ResultOf\\(\\)\\.");
shiqiane35fdd92008-12-10 05:08:54 +00003902}
shiqiane35fdd92008-12-10 05:08:54 +00003903
3904// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3905// function reference.
3906TEST(ResultOfTest, WorksForFunctionReferences) {
3907 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
3908 EXPECT_TRUE(matcher.Matches(1));
3909 EXPECT_FALSE(matcher.Matches(2));
3910}
3911
3912// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3913// function object.
Nico Weber09fd5b32017-05-15 17:07:03 -04003914struct Functor : public ::std::unary_function<int, std::string> {
shiqiane35fdd92008-12-10 05:08:54 +00003915 result_type operator()(argument_type input) const {
3916 return IntToStringFunction(input);
3917 }
3918};
3919
3920TEST(ResultOfTest, WorksForFunctors) {
Nico Weber09fd5b32017-05-15 17:07:03 -04003921 Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo")));
shiqiane35fdd92008-12-10 05:08:54 +00003922
3923 EXPECT_TRUE(matcher.Matches(1));
3924 EXPECT_FALSE(matcher.Matches(2));
3925}
3926
3927// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3928// functor with more then one operator() defined. ResultOf() must work
3929// for each defined operator().
3930struct PolymorphicFunctor {
3931 typedef int result_type;
3932 int operator()(int n) { return n; }
3933 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
3934};
3935
3936TEST(ResultOfTest, WorksForPolymorphicFunctors) {
3937 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
3938
3939 EXPECT_TRUE(matcher_int.Matches(10));
3940 EXPECT_FALSE(matcher_int.Matches(2));
3941
3942 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
3943
3944 EXPECT_TRUE(matcher_string.Matches("long string"));
3945 EXPECT_FALSE(matcher_string.Matches("shrt"));
3946}
3947
3948const int* ReferencingFunction(const int& n) { return &n; }
3949
3950struct ReferencingFunctor {
3951 typedef const int* result_type;
3952 result_type operator()(const int& n) { return &n; }
3953};
3954
3955TEST(ResultOfTest, WorksForReferencingCallables) {
3956 const int n = 1;
3957 const int n2 = 1;
3958 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
3959 EXPECT_TRUE(matcher2.Matches(n));
3960 EXPECT_FALSE(matcher2.Matches(n2));
3961
3962 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
3963 EXPECT_TRUE(matcher3.Matches(n));
3964 EXPECT_FALSE(matcher3.Matches(n2));
3965}
3966
shiqiane35fdd92008-12-10 05:08:54 +00003967class DivisibleByImpl {
3968 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003969 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
shiqiane35fdd92008-12-10 05:08:54 +00003970
zhanyong.wandb22c222010-01-28 21:52:29 +00003971 // For testing using ExplainMatchResultTo() with polymorphic matchers.
shiqiane35fdd92008-12-10 05:08:54 +00003972 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00003973 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003974 *listener << "which is " << (n % divider_) << " modulo "
zhanyong.wandb22c222010-01-28 21:52:29 +00003975 << divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003976 return (n % divider_) == 0;
3977 }
3978
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003979 void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003980 *os << "is divisible by " << divider_;
3981 }
3982
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003983 void DescribeNegationTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003984 *os << "is not divisible by " << divider_;
3985 }
3986
zhanyong.wan32de5f52009-12-23 00:13:23 +00003987 void set_divider(int a_divider) { divider_ = a_divider; }
shiqiane35fdd92008-12-10 05:08:54 +00003988 int divider() const { return divider_; }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003989
shiqiane35fdd92008-12-10 05:08:54 +00003990 private:
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003991 int divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003992};
3993
shiqiane35fdd92008-12-10 05:08:54 +00003994PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
3995 return MakePolymorphicMatcher(DivisibleByImpl(n));
3996}
3997
3998// Tests that when AllOf() fails, only the first failing matcher is
3999// asked to explain why.
4000TEST(ExplainMatchResultTest, AllOf_False_False) {
4001 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004002 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00004003}
4004
4005// Tests that when AllOf() fails, only the first failing matcher is
4006// asked to explain why.
4007TEST(ExplainMatchResultTest, AllOf_False_True) {
4008 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004009 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00004010}
4011
4012// Tests that when AllOf() fails, only the first failing matcher is
4013// asked to explain why.
4014TEST(ExplainMatchResultTest, AllOf_True_False) {
4015 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004016 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00004017}
4018
4019// Tests that when AllOf() succeeds, all matchers are asked to explain
4020// why.
4021TEST(ExplainMatchResultTest, AllOf_True_True) {
4022 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004023 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00004024}
4025
4026TEST(ExplainMatchResultTest, AllOf_True_True_2) {
4027 const Matcher<int> m = AllOf(Ge(2), Le(3));
4028 EXPECT_EQ("", Explain(m, 2));
4029}
4030
4031TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
4032 const Matcher<int> m = GreaterThan(5);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00004033 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00004034}
4035
4036// The following two tests verify that values without a public copy
4037// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
4038// with the help of ByRef().
4039
4040class NotCopyable {
4041 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00004042 explicit NotCopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00004043
4044 int value() const { return value_; }
4045
4046 bool operator==(const NotCopyable& rhs) const {
4047 return value() == rhs.value();
4048 }
4049
4050 bool operator>=(const NotCopyable& rhs) const {
4051 return value() >= rhs.value();
4052 }
4053 private:
4054 int value_;
4055
4056 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
4057};
4058
4059TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
4060 const NotCopyable const_value1(1);
4061 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
4062
4063 const NotCopyable n1(1), n2(2);
4064 EXPECT_TRUE(m.Matches(n1));
4065 EXPECT_FALSE(m.Matches(n2));
4066}
4067
4068TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
4069 NotCopyable value2(2);
4070 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
4071
4072 NotCopyable n1(1), n2(2);
4073 EXPECT_FALSE(m.Matches(n1));
4074 EXPECT_TRUE(m.Matches(n2));
4075}
4076
zhanyong.wan320814a2013-03-01 00:20:30 +00004077TEST(IsEmptyTest, ImplementsIsEmpty) {
4078 vector<int> container;
4079 EXPECT_THAT(container, IsEmpty());
4080 container.push_back(0);
4081 EXPECT_THAT(container, Not(IsEmpty()));
4082 container.push_back(1);
4083 EXPECT_THAT(container, Not(IsEmpty()));
4084}
4085
4086TEST(IsEmptyTest, WorksWithString) {
Nico Weber09fd5b32017-05-15 17:07:03 -04004087 std::string text;
zhanyong.wan320814a2013-03-01 00:20:30 +00004088 EXPECT_THAT(text, IsEmpty());
4089 text = "foo";
4090 EXPECT_THAT(text, Not(IsEmpty()));
Nico Weber09fd5b32017-05-15 17:07:03 -04004091 text = std::string("\0", 1);
zhanyong.wan320814a2013-03-01 00:20:30 +00004092 EXPECT_THAT(text, Not(IsEmpty()));
4093}
4094
4095TEST(IsEmptyTest, CanDescribeSelf) {
4096 Matcher<vector<int> > m = IsEmpty();
4097 EXPECT_EQ("is empty", Describe(m));
4098 EXPECT_EQ("isn't empty", DescribeNegation(m));
4099}
4100
4101TEST(IsEmptyTest, ExplainsResult) {
4102 Matcher<vector<int> > m = IsEmpty();
4103 vector<int> container;
4104 EXPECT_EQ("", Explain(m, container));
4105 container.push_back(0);
4106 EXPECT_EQ("whose size is 1", Explain(m, container));
4107}
4108
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004109TEST(SizeIsTest, ImplementsSizeIs) {
4110 vector<int> container;
4111 EXPECT_THAT(container, SizeIs(0));
4112 EXPECT_THAT(container, Not(SizeIs(1)));
4113 container.push_back(0);
4114 EXPECT_THAT(container, Not(SizeIs(0)));
4115 EXPECT_THAT(container, SizeIs(1));
4116 container.push_back(0);
4117 EXPECT_THAT(container, Not(SizeIs(0)));
4118 EXPECT_THAT(container, SizeIs(2));
4119}
4120
4121TEST(SizeIsTest, WorksWithMap) {
Nico Weber09fd5b32017-05-15 17:07:03 -04004122 map<std::string, int> container;
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004123 EXPECT_THAT(container, SizeIs(0));
4124 EXPECT_THAT(container, Not(SizeIs(1)));
4125 container.insert(make_pair("foo", 1));
4126 EXPECT_THAT(container, Not(SizeIs(0)));
4127 EXPECT_THAT(container, SizeIs(1));
4128 container.insert(make_pair("bar", 2));
4129 EXPECT_THAT(container, Not(SizeIs(0)));
4130 EXPECT_THAT(container, SizeIs(2));
4131}
4132
4133TEST(SizeIsTest, WorksWithReferences) {
4134 vector<int> container;
4135 Matcher<const vector<int>&> m = SizeIs(1);
4136 EXPECT_THAT(container, Not(m));
4137 container.push_back(0);
4138 EXPECT_THAT(container, m);
4139}
4140
4141TEST(SizeIsTest, CanDescribeSelf) {
4142 Matcher<vector<int> > m = SizeIs(2);
4143 EXPECT_EQ("size is equal to 2", Describe(m));
4144 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
4145}
4146
4147TEST(SizeIsTest, ExplainsResult) {
4148 Matcher<vector<int> > m1 = SizeIs(2);
4149 Matcher<vector<int> > m2 = SizeIs(Lt(2u));
4150 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
4151 Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
4152 vector<int> container;
4153 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
4154 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
4155 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
4156 EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
4157 Explain(m4, container));
4158 container.push_back(0);
4159 container.push_back(0);
4160 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
4161 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
4162 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
4163 EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
4164 Explain(m4, container));
4165}
4166
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004167#if GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004168// Tests ContainerEq with different container types, and
4169// different element types.
4170
4171template <typename T>
zhanyong.wanb8243162009-06-04 05:48:20 +00004172class ContainerEqTest : public testing::Test {};
zhanyong.wan6a896b52009-01-16 01:13:50 +00004173
4174typedef testing::Types<
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004175 set<int>,
4176 vector<size_t>,
4177 multiset<size_t>,
4178 list<int> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004179 ContainerEqTestTypes;
4180
4181TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
4182
4183// Tests that the filled container is equal to itself.
4184TYPED_TEST(ContainerEqTest, EqualsSelf) {
4185 static const int vals[] = {1, 1, 2, 3, 5, 8};
4186 TypeParam my_set(vals, vals + 6);
4187 const Matcher<TypeParam> m = ContainerEq(my_set);
4188 EXPECT_TRUE(m.Matches(my_set));
4189 EXPECT_EQ("", Explain(m, my_set));
4190}
4191
4192// Tests that missing values are reported.
4193TYPED_TEST(ContainerEqTest, ValueMissing) {
4194 static const int vals[] = {1, 1, 2, 3, 5, 8};
4195 static const int test_vals[] = {2, 1, 8, 5};
4196 TypeParam my_set(vals, vals + 6);
4197 TypeParam test_set(test_vals, test_vals + 4);
4198 const Matcher<TypeParam> m = ContainerEq(my_set);
4199 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004200 EXPECT_EQ("which doesn't have these expected elements: 3",
4201 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004202}
4203
4204// Tests that added values are reported.
4205TYPED_TEST(ContainerEqTest, ValueAdded) {
4206 static const int vals[] = {1, 1, 2, 3, 5, 8};
4207 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4208 TypeParam my_set(vals, vals + 6);
4209 TypeParam test_set(test_vals, test_vals + 6);
4210 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4211 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004212 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004213}
4214
4215// Tests that added and missing values are reported together.
4216TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4217 static const int vals[] = {1, 1, 2, 3, 5, 8};
4218 static const int test_vals[] = {1, 2, 3, 8, 46};
4219 TypeParam my_set(vals, vals + 6);
4220 TypeParam test_set(test_vals, test_vals + 5);
4221 const Matcher<TypeParam> m = ContainerEq(my_set);
4222 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004223 EXPECT_EQ("which has these unexpected elements: 46,\n"
4224 "and doesn't have these expected elements: 5",
4225 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004226}
4227
4228// Tests duplicated value -- expect no explanation.
4229TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4230 static const int vals[] = {1, 1, 2, 3, 5, 8};
4231 static const int test_vals[] = {1, 2, 3, 5, 8};
4232 TypeParam my_set(vals, vals + 6);
4233 TypeParam test_set(test_vals, test_vals + 5);
4234 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4235 // Depending on the container, match may be true or false
4236 // But in any case there should be no explanation.
4237 EXPECT_EQ("", Explain(m, test_set));
4238}
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004239#endif // GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004240
4241// Tests that mutliple missing values are reported.
4242// Using just vector here, so order is predicatble.
4243TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4244 static const int vals[] = {1, 1, 2, 3, 5, 8};
4245 static const int test_vals[] = {2, 1, 5};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004246 vector<int> my_set(vals, vals + 6);
4247 vector<int> test_set(test_vals, test_vals + 3);
4248 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004249 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004250 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4251 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004252}
4253
4254// Tests that added values are reported.
4255// Using just vector here, so order is predicatble.
4256TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4257 static const int vals[] = {1, 1, 2, 3, 5, 8};
4258 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004259 list<size_t> my_set(vals, vals + 6);
4260 list<size_t> test_set(test_vals, test_vals + 7);
4261 const Matcher<const list<size_t>&> m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004262 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004263 EXPECT_EQ("which has these unexpected elements: 92, 46",
4264 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004265}
4266
4267// Tests that added and missing values are reported together.
4268TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
4269 static const int vals[] = {1, 1, 2, 3, 5, 8};
4270 static const int test_vals[] = {1, 2, 3, 92, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004271 list<size_t> my_set(vals, vals + 6);
4272 list<size_t> test_set(test_vals, test_vals + 5);
4273 const Matcher<const list<size_t> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004274 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004275 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4276 "and doesn't have these expected elements: 5, 8",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004277 Explain(m, test_set));
4278}
4279
4280// Tests to see that duplicate elements are detected,
4281// but (as above) not reported in the explanation.
4282TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
4283 static const int vals[] = {1, 1, 2, 3, 5, 8};
4284 static const int test_vals[] = {1, 2, 3, 5, 8};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004285 vector<int> my_set(vals, vals + 6);
4286 vector<int> test_set(test_vals, test_vals + 5);
4287 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004288 EXPECT_TRUE(m.Matches(my_set));
4289 EXPECT_FALSE(m.Matches(test_set));
4290 // There is nothing to report when both sets contain all the same values.
4291 EXPECT_EQ("", Explain(m, test_set));
4292}
4293
4294// Tests that ContainerEq works for non-trivial associative containers,
4295// like maps.
4296TEST(ContainerEqExtraTest, WorksForMaps) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004297 map<int, std::string> my_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004298 my_map[0] = "a";
4299 my_map[1] = "b";
4300
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004301 map<int, std::string> test_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004302 test_map[0] = "aa";
4303 test_map[1] = "b";
4304
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004305 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004306 EXPECT_TRUE(m.Matches(my_map));
4307 EXPECT_FALSE(m.Matches(test_map));
4308
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004309 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
4310 "and doesn't have these expected elements: (0, \"a\")",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004311 Explain(m, test_map));
4312}
4313
zhanyong.wanb8243162009-06-04 05:48:20 +00004314TEST(ContainerEqExtraTest, WorksForNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00004315 int a1[] = {1, 2, 3};
4316 int a2[] = {1, 2, 3};
4317 int b[] = {1, 2, 4};
zhanyong.wanb8243162009-06-04 05:48:20 +00004318
4319 EXPECT_THAT(a1, ContainerEq(a2));
4320 EXPECT_THAT(a1, Not(ContainerEq(b)));
4321}
4322
4323TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00004324 const char a1[][3] = {"hi", "lo"};
4325 const char a2[][3] = {"hi", "lo"};
4326 const char b[][3] = {"lo", "hi"};
zhanyong.wanb8243162009-06-04 05:48:20 +00004327
4328 // Tests using ContainerEq() in the first dimension.
4329 EXPECT_THAT(a1, ContainerEq(a2));
4330 EXPECT_THAT(a1, Not(ContainerEq(b)));
4331
4332 // Tests using ContainerEq() in the second dimension.
4333 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
4334 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
4335}
4336
4337TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
kosak2336e9c2014-07-28 22:57:30 +00004338 const int a1[] = {1, 2, 3};
4339 const int a2[] = {1, 2, 3};
4340 const int b[] = {1, 2, 3, 4};
zhanyong.wanb8243162009-06-04 05:48:20 +00004341
zhanyong.wan2661c682009-06-09 05:42:12 +00004342 const int* const p1 = a1;
4343 EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
4344 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004345
kosak2336e9c2014-07-28 22:57:30 +00004346 const int c[] = {1, 3, 2};
zhanyong.wan2661c682009-06-09 05:42:12 +00004347 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004348}
4349
4350TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
4351 std::string a1[][3] = {
kosak2336e9c2014-07-28 22:57:30 +00004352 {"hi", "hello", "ciao"},
4353 {"bye", "see you", "ciao"}
zhanyong.wanb8243162009-06-04 05:48:20 +00004354 };
4355
4356 std::string a2[][3] = {
kosak2336e9c2014-07-28 22:57:30 +00004357 {"hi", "hello", "ciao"},
4358 {"bye", "see you", "ciao"}
zhanyong.wanb8243162009-06-04 05:48:20 +00004359 };
4360
4361 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
4362 EXPECT_THAT(a1, m);
4363
4364 a2[0][0] = "ha";
4365 EXPECT_THAT(a1, m);
4366}
4367
zhanyong.wan898725c2011-09-16 16:45:39 +00004368TEST(WhenSortedByTest, WorksForEmptyContainer) {
4369 const vector<int> numbers;
4370 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
4371 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
4372}
4373
4374TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
4375 vector<unsigned> numbers;
4376 numbers.push_back(3);
4377 numbers.push_back(1);
4378 numbers.push_back(2);
4379 numbers.push_back(2);
4380 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
4381 ElementsAre(3, 2, 2, 1)));
4382 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
4383 ElementsAre(1, 2, 2, 3))));
4384}
4385
4386TEST(WhenSortedByTest, WorksForNonVectorContainer) {
Nico Weber09fd5b32017-05-15 17:07:03 -04004387 list<std::string> words;
zhanyong.wan898725c2011-09-16 16:45:39 +00004388 words.push_back("say");
4389 words.push_back("hello");
4390 words.push_back("world");
Nico Weber09fd5b32017-05-15 17:07:03 -04004391 EXPECT_THAT(words, WhenSortedBy(less<std::string>(),
zhanyong.wan898725c2011-09-16 16:45:39 +00004392 ElementsAre("hello", "say", "world")));
Nico Weber09fd5b32017-05-15 17:07:03 -04004393 EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),
zhanyong.wan898725c2011-09-16 16:45:39 +00004394 ElementsAre("say", "hello", "world"))));
4395}
4396
4397TEST(WhenSortedByTest, WorksForNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00004398 const int numbers[] = {1, 3, 2, 4};
4399 const int sorted_numbers[] = {1, 2, 3, 4};
zhanyong.wan898725c2011-09-16 16:45:39 +00004400 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
4401 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
4402 ElementsAreArray(sorted_numbers)));
4403 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
4404}
4405
4406TEST(WhenSortedByTest, CanDescribeSelf) {
4407 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
4408 EXPECT_EQ("(when sorted) has 2 elements where\n"
4409 "element #0 is equal to 1,\n"
4410 "element #1 is equal to 2",
4411 Describe(m));
4412 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
4413 "element #0 isn't equal to 1, or\n"
4414 "element #1 isn't equal to 2",
4415 DescribeNegation(m));
4416}
4417
4418TEST(WhenSortedByTest, ExplainsMatchResult) {
kosak2336e9c2014-07-28 22:57:30 +00004419 const int a[] = {2, 1};
zhanyong.wan898725c2011-09-16 16:45:39 +00004420 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
4421 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
4422 EXPECT_EQ("which is { 1, 2 } when sorted",
4423 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
4424}
4425
4426// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
4427// need to test it as exhaustively as we test the latter.
4428
4429TEST(WhenSortedTest, WorksForEmptyContainer) {
4430 const vector<int> numbers;
4431 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
4432 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
4433}
4434
4435TEST(WhenSortedTest, WorksForNonEmptyContainer) {
Nico Weber09fd5b32017-05-15 17:07:03 -04004436 list<std::string> words;
zhanyong.wan898725c2011-09-16 16:45:39 +00004437 words.push_back("3");
4438 words.push_back("1");
4439 words.push_back("2");
4440 words.push_back("2");
4441 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
4442 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
4443}
4444
zhanyong.wana9a59e02013-03-27 16:14:55 +00004445TEST(WhenSortedTest, WorksForMapTypes) {
Nico Weber09fd5b32017-05-15 17:07:03 -04004446 map<std::string, int> word_counts;
4447 word_counts["and"] = 1;
4448 word_counts["the"] = 1;
4449 word_counts["buffalo"] = 2;
4450 EXPECT_THAT(word_counts,
4451 WhenSorted(ElementsAre(Pair("and", 1), Pair("buffalo", 2),
4452 Pair("the", 1))));
4453 EXPECT_THAT(word_counts,
4454 Not(WhenSorted(ElementsAre(Pair("and", 1), Pair("the", 1),
4455 Pair("buffalo", 2)))));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004456}
4457
4458TEST(WhenSortedTest, WorksForMultiMapTypes) {
4459 multimap<int, int> ifib;
4460 ifib.insert(make_pair(8, 6));
4461 ifib.insert(make_pair(2, 3));
4462 ifib.insert(make_pair(1, 1));
4463 ifib.insert(make_pair(3, 4));
4464 ifib.insert(make_pair(1, 2));
4465 ifib.insert(make_pair(5, 5));
4466 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
4467 Pair(1, 2),
4468 Pair(2, 3),
4469 Pair(3, 4),
4470 Pair(5, 5),
4471 Pair(8, 6))));
4472 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
4473 Pair(2, 3),
4474 Pair(1, 1),
4475 Pair(3, 4),
4476 Pair(1, 2),
4477 Pair(5, 5)))));
4478}
4479
4480TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
4481 std::deque<int> d;
4482 d.push_back(2);
4483 d.push_back(1);
4484 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
4485 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
4486}
4487
4488TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
4489 std::deque<int> d;
4490 d.push_back(2);
4491 d.push_back(1);
4492 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
4493 EXPECT_THAT(d, WhenSorted(vector_match));
4494 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
4495 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
4496}
4497
4498// Deliberately bare pseudo-container.
4499// Offers only begin() and end() accessors, yielding InputIterator.
4500template <typename T>
4501class Streamlike {
4502 private:
4503 class ConstIter;
4504 public:
4505 typedef ConstIter const_iterator;
4506 typedef T value_type;
4507
4508 template <typename InIter>
4509 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
4510
4511 const_iterator begin() const {
4512 return const_iterator(this, remainder_.begin());
4513 }
4514 const_iterator end() const {
4515 return const_iterator(this, remainder_.end());
4516 }
4517
4518 private:
4519 class ConstIter : public std::iterator<std::input_iterator_tag,
4520 value_type,
4521 ptrdiff_t,
kosakcd99eb02014-11-17 02:18:28 +00004522 const value_type*,
4523 const value_type&> {
zhanyong.wana9a59e02013-03-27 16:14:55 +00004524 public:
4525 ConstIter(const Streamlike* s,
4526 typename std::list<value_type>::iterator pos)
4527 : s_(s), pos_(pos) {}
4528
4529 const value_type& operator*() const { return *pos_; }
4530 const value_type* operator->() const { return &*pos_; }
4531 ConstIter& operator++() {
4532 s_->remainder_.erase(pos_++);
4533 return *this;
4534 }
4535
4536 // *iter++ is required to work (see std::istreambuf_iterator).
4537 // (void)iter++ is also required to work.
4538 class PostIncrProxy {
4539 public:
4540 explicit PostIncrProxy(const value_type& value) : value_(value) {}
4541 value_type operator*() const { return value_; }
4542 private:
4543 value_type value_;
4544 };
4545 PostIncrProxy operator++(int) {
4546 PostIncrProxy proxy(**this);
4547 ++(*this);
4548 return proxy;
4549 }
4550
4551 friend bool operator==(const ConstIter& a, const ConstIter& b) {
4552 return a.s_ == b.s_ && a.pos_ == b.pos_;
4553 }
4554 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
4555 return !(a == b);
4556 }
4557
4558 private:
4559 const Streamlike* s_;
4560 typename std::list<value_type>::iterator pos_;
4561 };
4562
4563 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
4564 os << "[";
4565 typedef typename std::list<value_type>::const_iterator Iter;
4566 const char* sep = "";
4567 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
4568 os << sep << *it;
4569 sep = ",";
4570 }
4571 os << "]";
4572 return os;
4573 }
4574
4575 mutable std::list<value_type> remainder_; // modified by iteration
4576};
4577
4578TEST(StreamlikeTest, Iteration) {
kosak2336e9c2014-07-28 22:57:30 +00004579 const int a[5] = {2, 1, 4, 5, 3};
zhanyong.wana9a59e02013-03-27 16:14:55 +00004580 Streamlike<int> s(a, a + 5);
4581 Streamlike<int>::const_iterator it = s.begin();
4582 const int* ip = a;
4583 while (it != s.end()) {
4584 SCOPED_TRACE(ip - a);
4585 EXPECT_EQ(*ip++, *it++);
4586 }
4587}
4588
kosak5b9cbbb2014-11-17 00:28:55 +00004589#if GTEST_HAS_STD_FORWARD_LIST_
kosakb6a34882014-03-12 21:06:46 +00004590TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
4591 std::forward_list<int> container;
4592 EXPECT_THAT(container, BeginEndDistanceIs(0));
4593 EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
4594 container.push_front(0);
4595 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4596 EXPECT_THAT(container, BeginEndDistanceIs(1));
4597 container.push_front(0);
4598 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4599 EXPECT_THAT(container, BeginEndDistanceIs(2));
4600}
kosak5b9cbbb2014-11-17 00:28:55 +00004601#endif // GTEST_HAS_STD_FORWARD_LIST_
kosakb6a34882014-03-12 21:06:46 +00004602
4603TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
kosak2336e9c2014-07-28 22:57:30 +00004604 const int a[5] = {1, 2, 3, 4, 5};
kosakb6a34882014-03-12 21:06:46 +00004605 Streamlike<int> s(a, a + 5);
4606 EXPECT_THAT(s, BeginEndDistanceIs(5));
4607}
4608
4609TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
4610 Matcher<vector<int> > m = BeginEndDistanceIs(2);
4611 EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
4612 EXPECT_EQ("distance between begin() and end() isn't equal to 2",
4613 DescribeNegation(m));
4614}
4615
4616TEST(BeginEndDistanceIsTest, ExplainsResult) {
4617 Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
4618 Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
4619 Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
4620 Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
4621 vector<int> container;
4622 EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
4623 Explain(m1, container));
4624 EXPECT_EQ("whose distance between begin() and end() 0 matches",
4625 Explain(m2, container));
4626 EXPECT_EQ("whose distance between begin() and end() 0 matches",
4627 Explain(m3, container));
4628 EXPECT_EQ(
4629 "whose distance between begin() and end() 0 doesn't match, which is 1 "
4630 "less than 1",
4631 Explain(m4, container));
4632 container.push_back(0);
4633 container.push_back(0);
4634 EXPECT_EQ("whose distance between begin() and end() 2 matches",
4635 Explain(m1, container));
4636 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4637 Explain(m2, container));
4638 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4639 Explain(m3, container));
4640 EXPECT_EQ(
4641 "whose distance between begin() and end() 2 matches, which is 1 more "
4642 "than 1",
4643 Explain(m4, container));
4644}
4645
zhanyong.wana9a59e02013-03-27 16:14:55 +00004646TEST(WhenSortedTest, WorksForStreamlike) {
4647 // Streamlike 'container' provides only minimal iterator support.
4648 // Its iterators are tagged with input_iterator_tag.
kosak2336e9c2014-07-28 22:57:30 +00004649 const int a[5] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00004650 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004651 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
4652 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4653}
4654
4655TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
kosak2336e9c2014-07-28 22:57:30 +00004656 const int a[] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00004657 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004658 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
4659 EXPECT_THAT(s, WhenSorted(vector_match));
4660 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4661}
4662
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004663// Tests using ElementsAre() and ElementsAreArray() with stream-like
4664// "containers".
4665
4666TEST(ElemensAreStreamTest, WorksForStreamlike) {
kosak2336e9c2014-07-28 22:57:30 +00004667 const int a[5] = {1, 2, 3, 4, 5};
kosak6414d802013-12-03 23:19:36 +00004668 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004669 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
4670 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
4671}
4672
4673TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
kosak2336e9c2014-07-28 22:57:30 +00004674 const int a[5] = {1, 2, 3, 4, 5};
kosak6414d802013-12-03 23:19:36 +00004675 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004676
4677 vector<int> expected;
4678 expected.push_back(1);
4679 expected.push_back(2);
4680 expected.push_back(3);
4681 expected.push_back(4);
4682 expected.push_back(5);
4683 EXPECT_THAT(s, ElementsAreArray(expected));
4684
4685 expected[3] = 0;
4686 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
4687}
4688
billydonahue1f5fdea2014-05-19 17:54:51 +00004689TEST(ElementsAreTest, WorksWithUncopyable) {
4690 Uncopyable objs[2];
4691 objs[0].set_value(-3);
4692 objs[1].set_value(1);
4693 EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
4694}
4695
kosak06678922014-07-28 20:01:28 +00004696TEST(ElementsAreTest, TakesStlContainer) {
4697 const int actual[] = {3, 1, 2};
4698
4699 ::std::list<int> expected;
4700 expected.push_back(3);
4701 expected.push_back(1);
4702 expected.push_back(2);
4703 EXPECT_THAT(actual, ElementsAreArray(expected));
4704
4705 expected.push_back(4);
4706 EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
4707}
4708
zhanyong.wanfb25d532013-07-28 08:24:00 +00004709// Tests for UnorderedElementsAreArray()
4710
4711TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
kosak2336e9c2014-07-28 22:57:30 +00004712 const int a[] = {0, 1, 2, 3, 4};
kosak6414d802013-12-03 23:19:36 +00004713 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004714 do {
4715 StringMatchResultListener listener;
4716 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
4717 s, &listener)) << listener.str();
4718 } while (std::next_permutation(s.begin(), s.end()));
4719}
4720
4721TEST(UnorderedElementsAreArrayTest, VectorBool) {
kosak2336e9c2014-07-28 22:57:30 +00004722 const bool a[] = {0, 1, 0, 1, 1};
4723 const bool b[] = {1, 0, 1, 1, 0};
kosak6414d802013-12-03 23:19:36 +00004724 std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a));
4725 std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004726 StringMatchResultListener listener;
4727 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
4728 actual, &listener)) << listener.str();
4729}
4730
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004731TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
4732 // Streamlike 'container' provides only minimal iterator support.
4733 // Its iterators are tagged with input_iterator_tag, and it has no
4734 // size() or empty() methods.
kosak2336e9c2014-07-28 22:57:30 +00004735 const int a[5] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00004736 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004737
4738 ::std::vector<int> expected;
4739 expected.push_back(1);
4740 expected.push_back(2);
4741 expected.push_back(3);
4742 expected.push_back(4);
4743 expected.push_back(5);
4744 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
4745
4746 expected.push_back(6);
4747 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
4748}
4749
kosak06678922014-07-28 20:01:28 +00004750TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
4751 const int actual[] = {3, 1, 2};
4752
4753 ::std::list<int> expected;
4754 expected.push_back(1);
4755 expected.push_back(2);
4756 expected.push_back(3);
4757 EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
4758
4759 expected.push_back(4);
4760 EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
4761}
4762
kosak18489fa2013-12-04 23:49:07 +00004763#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004764
4765TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
kosak2336e9c2014-07-28 22:57:30 +00004766 const int a[5] = {2, 1, 4, 5, 3};
4767 EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
4768 EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004769}
4770
4771TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
Nico Weber09fd5b32017-05-15 17:07:03 -04004772 const std::string a[5] = {"a", "b", "c", "d", "e"};
kosak2336e9c2014-07-28 22:57:30 +00004773 EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
4774 EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004775}
4776
4777TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
kosak2336e9c2014-07-28 22:57:30 +00004778 const int a[5] = {2, 1, 4, 5, 3};
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004779 EXPECT_THAT(a, UnorderedElementsAreArray(
kosak2336e9c2014-07-28 22:57:30 +00004780 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004781 EXPECT_THAT(a, Not(UnorderedElementsAreArray(
kosak2336e9c2014-07-28 22:57:30 +00004782 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004783}
4784
4785TEST(UnorderedElementsAreArrayTest,
4786 TakesInitializerListOfDifferentTypedMatchers) {
kosak2336e9c2014-07-28 22:57:30 +00004787 const int a[5] = {2, 1, 4, 5, 3};
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004788 // The compiler cannot infer the type of the initializer list if its
4789 // elements have different types. We must explicitly specify the
4790 // unified element type in this case.
4791 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
kosak2336e9c2014-07-28 22:57:30 +00004792 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004793 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
kosak2336e9c2014-07-28 22:57:30 +00004794 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004795}
4796
kosak18489fa2013-12-04 23:49:07 +00004797#endif // GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004798
zhanyong.wanfb25d532013-07-28 08:24:00 +00004799class UnorderedElementsAreTest : public testing::Test {
4800 protected:
4801 typedef std::vector<int> IntVec;
4802};
4803
billydonahue1f5fdea2014-05-19 17:54:51 +00004804TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
4805 Uncopyable objs[2];
4806 objs[0].set_value(-3);
4807 objs[1].set_value(1);
4808 EXPECT_THAT(objs,
4809 UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
4810}
4811
zhanyong.wanfb25d532013-07-28 08:24:00 +00004812TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
kosak2336e9c2014-07-28 22:57:30 +00004813 const int a[] = {1, 2, 3};
kosak6414d802013-12-03 23:19:36 +00004814 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004815 do {
4816 StringMatchResultListener listener;
4817 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4818 s, &listener)) << listener.str();
4819 } while (std::next_permutation(s.begin(), s.end()));
4820}
4821
4822TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
kosak2336e9c2014-07-28 22:57:30 +00004823 const int a[] = {1, 2, 3};
kosak6414d802013-12-03 23:19:36 +00004824 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004825 std::vector<Matcher<int> > mv;
4826 mv.push_back(1);
4827 mv.push_back(2);
4828 mv.push_back(2);
4829 // The element with value '3' matches nothing: fail fast.
4830 StringMatchResultListener listener;
4831 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4832 s, &listener)) << listener.str();
4833}
4834
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004835TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
4836 // Streamlike 'container' provides only minimal iterator support.
4837 // Its iterators are tagged with input_iterator_tag, and it has no
4838 // size() or empty() methods.
kosak2336e9c2014-07-28 22:57:30 +00004839 const int a[5] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00004840 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004841
4842 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
4843 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
4844}
4845
zhanyong.wanfb25d532013-07-28 08:24:00 +00004846// One naive implementation of the matcher runs in O(N!) time, which is too
4847// slow for many real-world inputs. This test shows that our matcher can match
4848// 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
4849// iterations and obviously effectively incomputable.
4850// [ RUN ] UnorderedElementsAreTest.Performance
4851// [ OK ] UnorderedElementsAreTest.Performance (4 ms)
4852TEST_F(UnorderedElementsAreTest, Performance) {
4853 std::vector<int> s;
4854 std::vector<Matcher<int> > mv;
4855 for (int i = 0; i < 100; ++i) {
4856 s.push_back(i);
4857 mv.push_back(_);
4858 }
4859 mv[50] = Eq(0);
4860 StringMatchResultListener listener;
4861 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4862 s, &listener)) << listener.str();
4863}
4864
4865// Another variant of 'Performance' with similar expectations.
4866// [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
4867// [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
4868TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
4869 std::vector<int> s;
4870 std::vector<Matcher<int> > mv;
4871 for (int i = 0; i < 100; ++i) {
4872 s.push_back(i);
4873 if (i & 1) {
4874 mv.push_back(_);
4875 } else {
4876 mv.push_back(i);
4877 }
4878 }
4879 StringMatchResultListener listener;
4880 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4881 s, &listener)) << listener.str();
4882}
4883
4884TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
4885 std::vector<int> v;
4886 v.push_back(4);
4887 StringMatchResultListener listener;
4888 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4889 v, &listener)) << listener.str();
4890 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
4891}
4892
4893TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
4894 std::vector<int> v;
4895 StringMatchResultListener listener;
4896 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4897 v, &listener)) << listener.str();
4898 EXPECT_THAT(listener.str(), Eq(""));
4899}
4900
4901TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
4902 std::vector<int> v;
4903 v.push_back(1);
4904 v.push_back(1);
4905 StringMatchResultListener listener;
4906 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4907 v, &listener)) << listener.str();
4908 EXPECT_THAT(
4909 listener.str(),
4910 Eq("where the following matchers don't match any elements:\n"
4911 "matcher #1: is equal to 2"));
4912}
4913
4914TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
4915 std::vector<int> v;
4916 v.push_back(1);
4917 v.push_back(2);
4918 StringMatchResultListener listener;
4919 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
4920 v, &listener)) << listener.str();
4921 EXPECT_THAT(
4922 listener.str(),
4923 Eq("where the following elements don't match any matchers:\n"
4924 "element #1: 2"));
4925}
4926
4927TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
4928 std::vector<int> v;
4929 v.push_back(2);
4930 v.push_back(3);
4931 StringMatchResultListener listener;
4932 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4933 v, &listener)) << listener.str();
4934 EXPECT_THAT(
4935 listener.str(),
4936 Eq("where"
4937 " the following matchers don't match any elements:\n"
4938 "matcher #0: is equal to 1\n"
4939 "and"
4940 " where"
4941 " the following elements don't match any matchers:\n"
4942 "element #1: 3"));
4943}
4944
4945// Test helper for formatting element, matcher index pairs in expectations.
Nico Weber09fd5b32017-05-15 17:07:03 -04004946static std::string EMString(int element, int matcher) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00004947 stringstream ss;
4948 ss << "(element #" << element << ", matcher #" << matcher << ")";
4949 return ss.str();
4950}
4951
4952TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
4953 // A situation where all elements and matchers have a match
4954 // associated with them, but the max matching is not perfect.
Nico Weber09fd5b32017-05-15 17:07:03 -04004955 std::vector<std::string> v;
zhanyong.wanfb25d532013-07-28 08:24:00 +00004956 v.push_back("a");
4957 v.push_back("b");
4958 v.push_back("c");
4959 StringMatchResultListener listener;
4960 EXPECT_FALSE(ExplainMatchResult(
4961 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
4962 << listener.str();
4963
Nico Weber09fd5b32017-05-15 17:07:03 -04004964 std::string prefix =
zhanyong.wanfb25d532013-07-28 08:24:00 +00004965 "where no permutation of the elements can satisfy all matchers, "
4966 "and the closest match is 2 of 3 matchers with the "
4967 "pairings:\n";
4968
4969 // We have to be a bit loose here, because there are 4 valid max matches.
4970 EXPECT_THAT(
4971 listener.str(),
4972 AnyOf(prefix + "{\n " + EMString(0, 0) +
4973 ",\n " + EMString(1, 2) + "\n}",
4974 prefix + "{\n " + EMString(0, 1) +
4975 ",\n " + EMString(1, 2) + "\n}",
4976 prefix + "{\n " + EMString(0, 0) +
4977 ",\n " + EMString(2, 2) + "\n}",
4978 prefix + "{\n " + EMString(0, 1) +
4979 ",\n " + EMString(2, 2) + "\n}"));
4980}
4981
4982TEST_F(UnorderedElementsAreTest, Describe) {
4983 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
4984 Eq("is empty"));
4985 EXPECT_THAT(
4986 Describe<IntVec>(UnorderedElementsAre(345)),
4987 Eq("has 1 element and that element is equal to 345"));
4988 EXPECT_THAT(
4989 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
4990 Eq("has 3 elements and there exists some permutation "
4991 "of elements such that:\n"
4992 " - element #0 is equal to 111, and\n"
4993 " - element #1 is equal to 222, and\n"
4994 " - element #2 is equal to 333"));
4995}
4996
4997TEST_F(UnorderedElementsAreTest, DescribeNegation) {
4998 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
4999 Eq("isn't empty"));
5000 EXPECT_THAT(
5001 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
5002 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
5003 EXPECT_THAT(
5004 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
5005 Eq("doesn't have 3 elements, or there exists no permutation "
5006 "of elements such that:\n"
5007 " - element #0 is equal to 123, and\n"
5008 " - element #1 is equal to 234, and\n"
5009 " - element #2 is equal to 345"));
5010}
5011
5012namespace {
5013
5014// Used as a check on the more complex max flow method used in the
5015// real testing::internal::FindMaxBipartiteMatching. This method is
5016// compatible but runs in worst-case factorial time, so we only
5017// use it in testing for small problem sizes.
5018template <typename Graph>
5019class BacktrackingMaxBPMState {
5020 public:
5021 // Does not take ownership of 'g'.
5022 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
5023
5024 ElementMatcherPairs Compute() {
5025 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
5026 return best_so_far_;
5027 }
5028 lhs_used_.assign(graph_->LhsSize(), kUnused);
5029 rhs_used_.assign(graph_->RhsSize(), kUnused);
5030 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
5031 matches_.clear();
5032 RecurseInto(irhs);
5033 if (best_so_far_.size() == graph_->RhsSize())
5034 break;
5035 }
5036 return best_so_far_;
5037 }
5038
5039 private:
5040 static const size_t kUnused = static_cast<size_t>(-1);
5041
5042 void PushMatch(size_t lhs, size_t rhs) {
5043 matches_.push_back(ElementMatcherPair(lhs, rhs));
5044 lhs_used_[lhs] = rhs;
5045 rhs_used_[rhs] = lhs;
5046 if (matches_.size() > best_so_far_.size()) {
5047 best_so_far_ = matches_;
5048 }
5049 }
5050
5051 void PopMatch() {
5052 const ElementMatcherPair& back = matches_.back();
5053 lhs_used_[back.first] = kUnused;
5054 rhs_used_[back.second] = kUnused;
5055 matches_.pop_back();
5056 }
5057
5058 bool RecurseInto(size_t irhs) {
5059 if (rhs_used_[irhs] != kUnused) {
5060 return true;
5061 }
5062 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
5063 if (lhs_used_[ilhs] != kUnused) {
5064 continue;
5065 }
5066 if (!graph_->HasEdge(ilhs, irhs)) {
5067 continue;
5068 }
5069 PushMatch(ilhs, irhs);
5070 if (best_so_far_.size() == graph_->RhsSize()) {
5071 return false;
5072 }
5073 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
5074 if (!RecurseInto(mi)) return false;
5075 }
5076 PopMatch();
5077 }
5078 return true;
5079 }
5080
5081 const Graph* graph_; // not owned
5082 std::vector<size_t> lhs_used_;
5083 std::vector<size_t> rhs_used_;
5084 ElementMatcherPairs matches_;
5085 ElementMatcherPairs best_so_far_;
5086};
5087
5088template <typename Graph>
5089const size_t BacktrackingMaxBPMState<Graph>::kUnused;
5090
5091} // namespace
5092
5093// Implement a simple backtracking algorithm to determine if it is possible
5094// to find one element per matcher, without reusing elements.
5095template <typename Graph>
5096ElementMatcherPairs
5097FindBacktrackingMaxBPM(const Graph& g) {
5098 return BacktrackingMaxBPMState<Graph>(&g).Compute();
5099}
5100
5101class BacktrackingBPMTest : public ::testing::Test { };
5102
5103// Tests the MaxBipartiteMatching algorithm with square matrices.
5104// The single int param is the # of nodes on each of the left and right sides.
5105class BipartiteTest : public ::testing::TestWithParam<int> { };
5106
5107// Verify all match graphs up to some moderate number of edges.
5108TEST_P(BipartiteTest, Exhaustive) {
5109 int nodes = GetParam();
5110 MatchMatrix graph(nodes, nodes);
5111 do {
5112 ElementMatcherPairs matches =
5113 internal::FindMaxBipartiteMatching(graph);
5114 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
5115 << "graph: " << graph.DebugString();
5116 // Check that all elements of matches are in the graph.
5117 // Check that elements of first and second are unique.
5118 std::vector<bool> seen_element(graph.LhsSize());
5119 std::vector<bool> seen_matcher(graph.RhsSize());
5120 SCOPED_TRACE(PrintToString(matches));
5121 for (size_t i = 0; i < matches.size(); ++i) {
5122 size_t ilhs = matches[i].first;
5123 size_t irhs = matches[i].second;
5124 EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
5125 EXPECT_FALSE(seen_element[ilhs]);
5126 EXPECT_FALSE(seen_matcher[irhs]);
5127 seen_element[ilhs] = true;
5128 seen_matcher[irhs] = true;
5129 }
5130 } while (graph.NextGraph());
5131}
5132
5133INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest,
5134 ::testing::Range(0, 5));
5135
5136// Parameterized by a pair interpreted as (LhsSize, RhsSize).
5137class BipartiteNonSquareTest
5138 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
5139};
5140
5141TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
5142 // .......
5143 // 0:-----\ :
5144 // 1:---\ | :
5145 // 2:---\ | :
5146 // 3:-\ | | :
5147 // :.......:
5148 // 0 1 2
5149 MatchMatrix g(4, 3);
kosak2336e9c2014-07-28 22:57:30 +00005150 static const int kEdges[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}};
kosak6414d802013-12-03 23:19:36 +00005151 for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00005152 g.SetEdge(kEdges[i][0], kEdges[i][1], true);
5153 }
5154 EXPECT_THAT(FindBacktrackingMaxBPM(g),
5155 ElementsAre(Pair(3, 0),
5156 Pair(AnyOf(1, 2), 1),
5157 Pair(0, 2))) << g.DebugString();
5158}
5159
5160// Verify a few nonsquare matrices.
5161TEST_P(BipartiteNonSquareTest, Exhaustive) {
5162 size_t nlhs = GetParam().first;
5163 size_t nrhs = GetParam().second;
5164 MatchMatrix graph(nlhs, nrhs);
5165 do {
5166 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5167 internal::FindMaxBipartiteMatching(graph).size())
5168 << "graph: " << graph.DebugString()
5169 << "\nbacktracking: "
5170 << PrintToString(FindBacktrackingMaxBPM(graph))
5171 << "\nmax flow: "
5172 << PrintToString(internal::FindMaxBipartiteMatching(graph));
5173 } while (graph.NextGraph());
5174}
5175
5176INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest,
5177 testing::Values(
5178 std::make_pair(1, 2),
5179 std::make_pair(2, 1),
5180 std::make_pair(3, 2),
5181 std::make_pair(2, 3),
5182 std::make_pair(4, 1),
5183 std::make_pair(1, 4),
5184 std::make_pair(4, 3),
5185 std::make_pair(3, 4)));
5186
5187class BipartiteRandomTest
5188 : public ::testing::TestWithParam<std::pair<int, int> > {
5189};
5190
5191// Verifies a large sample of larger graphs.
5192TEST_P(BipartiteRandomTest, LargerNets) {
5193 int nodes = GetParam().first;
5194 int iters = GetParam().second;
5195 MatchMatrix graph(nodes, nodes);
5196
5197 testing::internal::Int32 seed = GTEST_FLAG(random_seed);
5198 if (seed == 0) {
5199 seed = static_cast<testing::internal::Int32>(time(NULL));
5200 }
5201
5202 for (; iters > 0; --iters, ++seed) {
5203 srand(static_cast<int>(seed));
5204 graph.Randomize();
5205 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5206 internal::FindMaxBipartiteMatching(graph).size())
5207 << " graph: " << graph.DebugString()
5208 << "\nTo reproduce the failure, rerun the test with the flag"
5209 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
5210 }
5211}
5212
5213// Test argument is a std::pair<int, int> representing (nodes, iters).
5214INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest,
5215 testing::Values(
5216 std::make_pair(5, 10000),
5217 std::make_pair(6, 5000),
5218 std::make_pair(7, 2000),
5219 std::make_pair(8, 500),
5220 std::make_pair(9, 100)));
5221
zhanyong.wan736baa82010-09-27 17:44:16 +00005222// Tests IsReadableTypeName().
5223
5224TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
5225 EXPECT_TRUE(IsReadableTypeName("int"));
5226 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
5227 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
5228 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
5229}
5230
5231TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
5232 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
5233 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
5234 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
5235}
5236
5237TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
5238 EXPECT_FALSE(
5239 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
5240 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
5241}
5242
5243TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
5244 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
5245}
5246
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005247// Tests JoinAsTuple().
5248
5249TEST(JoinAsTupleTest, JoinsEmptyTuple) {
5250 EXPECT_EQ("", JoinAsTuple(Strings()));
5251}
5252
5253TEST(JoinAsTupleTest, JoinsOneTuple) {
kosak2336e9c2014-07-28 22:57:30 +00005254 const char* fields[] = {"1"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005255 EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
5256}
5257
5258TEST(JoinAsTupleTest, JoinsTwoTuple) {
kosak2336e9c2014-07-28 22:57:30 +00005259 const char* fields[] = {"1", "a"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005260 EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
5261}
5262
5263TEST(JoinAsTupleTest, JoinsTenTuple) {
kosak2336e9c2014-07-28 22:57:30 +00005264 const char* fields[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005265 EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
5266 JoinAsTuple(Strings(fields, fields + 10)));
5267}
5268
5269// Tests FormatMatcherDescription().
5270
5271TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
5272 EXPECT_EQ("is even",
zhanyong.wanb4140802010-06-08 22:53:57 +00005273 FormatMatcherDescription(false, "IsEven", Strings()));
5274 EXPECT_EQ("not (is even)",
5275 FormatMatcherDescription(true, "IsEven", Strings()));
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005276
kosak2336e9c2014-07-28 22:57:30 +00005277 const char* params[] = {"5"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005278 EXPECT_EQ("equals 5",
zhanyong.wanb4140802010-06-08 22:53:57 +00005279 FormatMatcherDescription(false, "Equals",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005280 Strings(params, params + 1)));
5281
kosak2336e9c2014-07-28 22:57:30 +00005282 const char* params2[] = {"5", "8"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005283 EXPECT_EQ("is in range (5, 8)",
zhanyong.wanb4140802010-06-08 22:53:57 +00005284 FormatMatcherDescription(false, "IsInRange",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005285 Strings(params2, params2 + 2)));
5286}
5287
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00005288// Tests PolymorphicMatcher::mutable_impl().
5289TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
5290 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5291 DivisibleByImpl& impl = m.mutable_impl();
5292 EXPECT_EQ(42, impl.divider());
5293
5294 impl.set_divider(0);
5295 EXPECT_EQ(0, m.mutable_impl().divider());
5296}
5297
5298// Tests PolymorphicMatcher::impl().
5299TEST(PolymorphicMatcherTest, CanAccessImpl) {
5300 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5301 const DivisibleByImpl& impl = m.impl();
5302 EXPECT_EQ(42, impl.divider());
5303}
5304
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005305TEST(MatcherTupleTest, ExplainsMatchFailure) {
5306 stringstream ss1;
5307 ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
5308 make_tuple('a', 10), &ss1);
5309 EXPECT_EQ("", ss1.str()); // Successful match.
5310
5311 stringstream ss2;
5312 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5313 make_tuple(2, 'b'), &ss2);
5314 EXPECT_EQ(" Expected arg #0: is > 5\n"
5315 " Actual: 2, which is 3 less than 5\n"
zhanyong.wand60c5f42010-07-21 22:21:07 +00005316 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
5317 " Actual: 'b' (98, 0x62)\n",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005318 ss2.str()); // Failed match where both arguments need explanation.
5319
5320 stringstream ss3;
5321 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5322 make_tuple(2, 'a'), &ss3);
5323 EXPECT_EQ(" Expected arg #0: is > 5\n"
5324 " Actual: 2, which is 3 less than 5\n",
5325 ss3.str()); // Failed match where only one argument needs
5326 // explanation.
5327}
5328
zhanyong.wan33605ba2010-04-22 23:37:47 +00005329// Tests Each().
5330
5331TEST(EachTest, ExplainsMatchResultCorrectly) {
5332 set<int> a; // empty
5333
5334 Matcher<set<int> > m = Each(2);
5335 EXPECT_EQ("", Explain(m, a));
5336
zhanyong.wan736baa82010-09-27 17:44:16 +00005337 Matcher<const int(&)[1]> n = Each(1); // NOLINT
zhanyong.wan33605ba2010-04-22 23:37:47 +00005338
kosak2336e9c2014-07-28 22:57:30 +00005339 const int b[1] = {1};
zhanyong.wan33605ba2010-04-22 23:37:47 +00005340 EXPECT_EQ("", Explain(n, b));
5341
5342 n = Each(3);
5343 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
5344
5345 a.insert(1);
5346 a.insert(2);
5347 a.insert(3);
5348 m = Each(GreaterThan(0));
5349 EXPECT_EQ("", Explain(m, a));
5350
5351 m = Each(GreaterThan(10));
5352 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
5353 Explain(m, a));
5354}
5355
5356TEST(EachTest, DescribesItselfCorrectly) {
5357 Matcher<vector<int> > m = Each(1);
5358 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
5359
5360 Matcher<vector<int> > m2 = Not(m);
5361 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
5362}
5363
5364TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
5365 vector<int> some_vector;
5366 EXPECT_THAT(some_vector, Each(1));
5367 some_vector.push_back(3);
5368 EXPECT_THAT(some_vector, Not(Each(1)));
5369 EXPECT_THAT(some_vector, Each(3));
5370 some_vector.push_back(1);
5371 some_vector.push_back(2);
5372 EXPECT_THAT(some_vector, Not(Each(3)));
5373 EXPECT_THAT(some_vector, Each(Lt(3.5)));
5374
Nico Weber09fd5b32017-05-15 17:07:03 -04005375 vector<std::string> another_vector;
zhanyong.wan33605ba2010-04-22 23:37:47 +00005376 another_vector.push_back("fee");
Nico Weber09fd5b32017-05-15 17:07:03 -04005377 EXPECT_THAT(another_vector, Each(std::string("fee")));
zhanyong.wan33605ba2010-04-22 23:37:47 +00005378 another_vector.push_back("fie");
5379 another_vector.push_back("foe");
5380 another_vector.push_back("fum");
Nico Weber09fd5b32017-05-15 17:07:03 -04005381 EXPECT_THAT(another_vector, Not(Each(std::string("fee"))));
zhanyong.wan33605ba2010-04-22 23:37:47 +00005382}
5383
5384TEST(EachTest, MatchesMapWhenAllElementsMatch) {
5385 map<const char*, int> my_map;
5386 const char* bar = "a string";
5387 my_map[bar] = 2;
5388 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
5389
Nico Weber09fd5b32017-05-15 17:07:03 -04005390 map<std::string, int> another_map;
5391 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
zhanyong.wan33605ba2010-04-22 23:37:47 +00005392 another_map["fee"] = 1;
Nico Weber09fd5b32017-05-15 17:07:03 -04005393 EXPECT_THAT(another_map, Each(make_pair(std::string("fee"), 1)));
zhanyong.wan33605ba2010-04-22 23:37:47 +00005394 another_map["fie"] = 2;
5395 another_map["foe"] = 3;
5396 another_map["fum"] = 4;
Nico Weber09fd5b32017-05-15 17:07:03 -04005397 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee"), 1))));
5398 EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum"), 1))));
zhanyong.wan33605ba2010-04-22 23:37:47 +00005399 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
5400}
5401
5402TEST(EachTest, AcceptsMatcher) {
kosak2336e9c2014-07-28 22:57:30 +00005403 const int a[] = {1, 2, 3};
zhanyong.wan33605ba2010-04-22 23:37:47 +00005404 EXPECT_THAT(a, Each(Gt(0)));
5405 EXPECT_THAT(a, Not(Each(Gt(1))));
5406}
5407
5408TEST(EachTest, WorksForNativeArrayAsTuple) {
kosak2336e9c2014-07-28 22:57:30 +00005409 const int a[] = {1, 2};
zhanyong.wan33605ba2010-04-22 23:37:47 +00005410 const int* const pointer = a;
5411 EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
5412 EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
5413}
5414
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005415// For testing Pointwise().
5416class IsHalfOfMatcher {
5417 public:
5418 template <typename T1, typename T2>
5419 bool MatchAndExplain(const tuple<T1, T2>& a_pair,
5420 MatchResultListener* listener) const {
5421 if (get<0>(a_pair) == get<1>(a_pair)/2) {
5422 *listener << "where the second is " << get<1>(a_pair);
5423 return true;
5424 } else {
5425 *listener << "where the second/2 is " << get<1>(a_pair)/2;
5426 return false;
5427 }
5428 }
5429
5430 void DescribeTo(ostream* os) const {
5431 *os << "are a pair where the first is half of the second";
5432 }
5433
5434 void DescribeNegationTo(ostream* os) const {
5435 *os << "are a pair where the first isn't half of the second";
5436 }
5437};
5438
5439PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
5440 return MakePolymorphicMatcher(IsHalfOfMatcher());
5441}
5442
5443TEST(PointwiseTest, DescribesSelf) {
5444 vector<int> rhs;
5445 rhs.push_back(1);
5446 rhs.push_back(2);
5447 rhs.push_back(3);
5448 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
5449 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
5450 "in { 1, 2, 3 } are a pair where the first is half of the second",
5451 Describe(m));
5452 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
5453 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
5454 "where the first isn't half of the second",
5455 DescribeNegation(m));
5456}
5457
5458TEST(PointwiseTest, MakesCopyOfRhs) {
5459 list<signed char> rhs;
5460 rhs.push_back(2);
5461 rhs.push_back(4);
5462
kosak2336e9c2014-07-28 22:57:30 +00005463 int lhs[] = {1, 2};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005464 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
5465 EXPECT_THAT(lhs, m);
5466
5467 // Changing rhs now shouldn't affect m, which made a copy of rhs.
5468 rhs.push_back(6);
5469 EXPECT_THAT(lhs, m);
5470}
5471
5472TEST(PointwiseTest, WorksForLhsNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00005473 const int lhs[] = {1, 2, 3};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005474 vector<int> rhs;
5475 rhs.push_back(2);
5476 rhs.push_back(4);
5477 rhs.push_back(6);
5478 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
5479 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5480}
5481
5482TEST(PointwiseTest, WorksForRhsNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00005483 const int rhs[] = {1, 2, 3};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005484 vector<int> lhs;
5485 lhs.push_back(2);
5486 lhs.push_back(4);
5487 lhs.push_back(6);
5488 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
5489 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
5490}
5491
kosak2336e9c2014-07-28 22:57:30 +00005492#if GTEST_HAS_STD_INITIALIZER_LIST_
5493
5494TEST(PointwiseTest, WorksForRhsInitializerList) {
5495 const vector<int> lhs{2, 4, 6};
5496 EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
5497 EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
5498}
5499
5500#endif // GTEST_HAS_STD_INITIALIZER_LIST_
5501
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005502TEST(PointwiseTest, RejectsWrongSize) {
kosak2336e9c2014-07-28 22:57:30 +00005503 const double lhs[2] = {1, 2};
5504 const int rhs[1] = {0};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005505 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5506 EXPECT_EQ("which contains 2 values",
5507 Explain(Pointwise(Gt(), rhs), lhs));
5508
kosak2336e9c2014-07-28 22:57:30 +00005509 const int rhs2[3] = {0, 1, 2};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005510 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
5511}
5512
5513TEST(PointwiseTest, RejectsWrongContent) {
kosak2336e9c2014-07-28 22:57:30 +00005514 const double lhs[3] = {1, 2, 3};
5515 const int rhs[3] = {2, 6, 4};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005516 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
5517 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
5518 "where the second/2 is 3",
5519 Explain(Pointwise(IsHalfOf(), rhs), lhs));
5520}
5521
5522TEST(PointwiseTest, AcceptsCorrectContent) {
kosak2336e9c2014-07-28 22:57:30 +00005523 const double lhs[3] = {1, 2, 3};
5524 const int rhs[3] = {2, 4, 6};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005525 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
5526 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
5527}
5528
5529TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
kosak2336e9c2014-07-28 22:57:30 +00005530 const double lhs[3] = {1, 2, 3};
5531 const int rhs[3] = {2, 4, 6};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005532 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5533 EXPECT_THAT(lhs, Pointwise(m1, rhs));
5534 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
5535
5536 // This type works as a tuple<const double&, const int&> can be
5537 // implicitly cast to tuple<double, int>.
5538 const Matcher<tuple<double, int> > m2 = IsHalfOf();
5539 EXPECT_THAT(lhs, Pointwise(m2, rhs));
5540 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
5541}
5542
kosak2336e9c2014-07-28 22:57:30 +00005543TEST(UnorderedPointwiseTest, DescribesSelf) {
5544 vector<int> rhs;
5545 rhs.push_back(1);
5546 rhs.push_back(2);
5547 rhs.push_back(3);
5548 const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
5549 EXPECT_EQ(
5550 "has 3 elements and there exists some permutation of elements such "
5551 "that:\n"
5552 " - element #0 and 1 are a pair where the first is half of the second, "
5553 "and\n"
5554 " - element #1 and 2 are a pair where the first is half of the second, "
5555 "and\n"
5556 " - element #2 and 3 are a pair where the first is half of the second",
5557 Describe(m));
5558 EXPECT_EQ(
5559 "doesn't have 3 elements, or there exists no permutation of elements "
5560 "such that:\n"
5561 " - element #0 and 1 are a pair where the first is half of the second, "
5562 "and\n"
5563 " - element #1 and 2 are a pair where the first is half of the second, "
5564 "and\n"
5565 " - element #2 and 3 are a pair where the first is half of the second",
5566 DescribeNegation(m));
5567}
5568
5569TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
5570 list<signed char> rhs;
5571 rhs.push_back(2);
5572 rhs.push_back(4);
5573
5574 int lhs[] = {2, 1};
5575 const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
5576 EXPECT_THAT(lhs, m);
5577
5578 // Changing rhs now shouldn't affect m, which made a copy of rhs.
5579 rhs.push_back(6);
5580 EXPECT_THAT(lhs, m);
5581}
5582
5583TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
5584 const int lhs[] = {1, 2, 3};
5585 vector<int> rhs;
5586 rhs.push_back(4);
5587 rhs.push_back(6);
5588 rhs.push_back(2);
5589 EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
5590 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
5591}
5592
5593TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
5594 const int rhs[] = {1, 2, 3};
5595 vector<int> lhs;
5596 lhs.push_back(4);
5597 lhs.push_back(2);
5598 lhs.push_back(6);
5599 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
5600 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
5601}
5602
5603#if GTEST_HAS_STD_INITIALIZER_LIST_
5604
5605TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
5606 const vector<int> lhs{2, 4, 6};
5607 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
5608 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
5609}
5610
5611#endif // GTEST_HAS_STD_INITIALIZER_LIST_
5612
5613TEST(UnorderedPointwiseTest, RejectsWrongSize) {
5614 const double lhs[2] = {1, 2};
5615 const int rhs[1] = {0};
5616 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
5617 EXPECT_EQ("which has 2 elements",
5618 Explain(UnorderedPointwise(Gt(), rhs), lhs));
5619
5620 const int rhs2[3] = {0, 1, 2};
5621 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
5622}
5623
5624TEST(UnorderedPointwiseTest, RejectsWrongContent) {
5625 const double lhs[3] = {1, 2, 3};
5626 const int rhs[3] = {2, 6, 6};
5627 EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
5628 EXPECT_EQ("where the following elements don't match any matchers:\n"
5629 "element #1: 2",
5630 Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
5631}
5632
5633TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
5634 const double lhs[3] = {1, 2, 3};
5635 const int rhs[3] = {2, 4, 6};
5636 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
5637}
5638
5639TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
5640 const double lhs[3] = {1, 2, 3};
5641 const int rhs[3] = {6, 4, 2};
5642 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
5643}
5644
5645TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
5646 const double lhs[3] = {1, 2, 3};
5647 const int rhs[3] = {4, 6, 2};
5648 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5649 EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
5650
5651 // This type works as a tuple<const double&, const int&> can be
5652 // implicitly cast to tuple<double, int>.
5653 const Matcher<tuple<double, int> > m2 = IsHalfOf();
5654 EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
5655}
5656
shiqiane35fdd92008-12-10 05:08:54 +00005657} // namespace gmock_matchers_test
5658} // namespace testing