blob: 29c9dc2cc730e5ecb463823523a519daaf5656da [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
zhanyong.wan736baa82010-09-27 17:44:16 +0000192string OfType(const string& type_name) {
193#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>
202string Describe(const Matcher<T>& m) {
203 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>
210string DescribeNegation(const Matcher<T>& m) {
211 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>
218string 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
mazong1123531bf5c2016-07-14 13:44:46 +0800874inline bool operator==(const Unprintable&, /* lhs */ const Unprintable& /* rhs */) { return true; }
875
shiqiane35fdd92008-12-10 05:08:54 +0000876TEST(EqTest, CanDescribeSelf) {
877 Matcher<Unprintable> m = Eq(Unprintable());
878 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
879}
880
881// Tests that Eq(v) can be used to match any type that supports
882// comparing with type T, where T is v's type.
883TEST(EqTest, IsPolymorphic) {
884 Matcher<int> m1 = Eq(1);
885 EXPECT_TRUE(m1.Matches(1));
886 EXPECT_FALSE(m1.Matches(2));
887
888 Matcher<char> m2 = Eq(1);
889 EXPECT_TRUE(m2.Matches('\1'));
890 EXPECT_FALSE(m2.Matches('a'));
891}
892
893// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
894TEST(TypedEqTest, ChecksEqualityForGivenType) {
895 Matcher<char> m1 = TypedEq<char>('a');
896 EXPECT_TRUE(m1.Matches('a'));
897 EXPECT_FALSE(m1.Matches('b'));
898
899 Matcher<int> m2 = TypedEq<int>(6);
900 EXPECT_TRUE(m2.Matches(6));
901 EXPECT_FALSE(m2.Matches(7));
902}
903
904// Tests that TypedEq(v) describes itself properly.
905TEST(TypedEqTest, CanDescribeSelf) {
906 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
907}
908
909// Tests that TypedEq<T>(v) has type Matcher<T>.
910
911// Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
912// is a "bare" type (i.e. not in the form of const U or U&). If v's
913// type is not T, the compiler will generate a message about
914// "undefined referece".
915template <typename T>
916struct Type {
zhanyong.wan32de5f52009-12-23 00:13:23 +0000917 static bool IsTypeOf(const T& /* v */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000918
919 template <typename T2>
920 static void IsTypeOf(T2 v);
921};
922
923TEST(TypedEqTest, HasSpecifiedType) {
924 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
925 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
926 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
927}
928
929// Tests that Ge(v) matches anything >= v.
930TEST(GeTest, ImplementsGreaterThanOrEqual) {
931 Matcher<int> m1 = Ge(0);
932 EXPECT_TRUE(m1.Matches(1));
933 EXPECT_TRUE(m1.Matches(0));
934 EXPECT_FALSE(m1.Matches(-1));
935}
936
937// Tests that Ge(v) describes itself properly.
938TEST(GeTest, CanDescribeSelf) {
939 Matcher<int> m = Ge(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000940 EXPECT_EQ("is >= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000941}
942
943// Tests that Gt(v) matches anything > v.
944TEST(GtTest, ImplementsGreaterThan) {
945 Matcher<double> m1 = Gt(0);
946 EXPECT_TRUE(m1.Matches(1.0));
947 EXPECT_FALSE(m1.Matches(0.0));
948 EXPECT_FALSE(m1.Matches(-1.0));
949}
950
951// Tests that Gt(v) describes itself properly.
952TEST(GtTest, CanDescribeSelf) {
953 Matcher<int> m = Gt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000954 EXPECT_EQ("is > 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000955}
956
957// Tests that Le(v) matches anything <= v.
958TEST(LeTest, ImplementsLessThanOrEqual) {
959 Matcher<char> m1 = Le('b');
960 EXPECT_TRUE(m1.Matches('a'));
961 EXPECT_TRUE(m1.Matches('b'));
962 EXPECT_FALSE(m1.Matches('c'));
963}
964
965// Tests that Le(v) describes itself properly.
966TEST(LeTest, CanDescribeSelf) {
967 Matcher<int> m = Le(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000968 EXPECT_EQ("is <= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000969}
970
971// Tests that Lt(v) matches anything < v.
972TEST(LtTest, ImplementsLessThan) {
973 Matcher<const string&> m1 = Lt("Hello");
974 EXPECT_TRUE(m1.Matches("Abc"));
975 EXPECT_FALSE(m1.Matches("Hello"));
976 EXPECT_FALSE(m1.Matches("Hello, world!"));
977}
978
979// Tests that Lt(v) describes itself properly.
980TEST(LtTest, CanDescribeSelf) {
981 Matcher<int> m = Lt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000982 EXPECT_EQ("is < 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000983}
984
985// Tests that Ne(v) matches anything != v.
986TEST(NeTest, ImplementsNotEqual) {
987 Matcher<int> m1 = Ne(0);
988 EXPECT_TRUE(m1.Matches(1));
989 EXPECT_TRUE(m1.Matches(-1));
990 EXPECT_FALSE(m1.Matches(0));
991}
992
993// Tests that Ne(v) describes itself properly.
994TEST(NeTest, CanDescribeSelf) {
995 Matcher<int> m = Ne(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000996 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000997}
998
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000999// Tests that IsNull() matches any NULL pointer of any type.
1000TEST(IsNullTest, MatchesNullPointer) {
1001 Matcher<int*> m1 = IsNull();
1002 int* p1 = NULL;
1003 int n = 0;
1004 EXPECT_TRUE(m1.Matches(p1));
1005 EXPECT_FALSE(m1.Matches(&n));
1006
1007 Matcher<const char*> m2 = IsNull();
1008 const char* p2 = NULL;
1009 EXPECT_TRUE(m2.Matches(p2));
1010 EXPECT_FALSE(m2.Matches("hi"));
1011
zhanyong.wan95b12332009-09-25 18:55:50 +00001012#if !GTEST_OS_SYMBIAN
1013 // Nokia's Symbian compiler generates:
1014 // gmock-matchers.h: ambiguous access to overloaded function
1015 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
1016 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
1017 // MatcherInterface<void *> *)'
1018 // gmock-matchers.h: (point of instantiation: 'testing::
1019 // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
1020 // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001021 Matcher<void*> m3 = IsNull();
1022 void* p3 = NULL;
1023 EXPECT_TRUE(m3.Matches(p3));
1024 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
zhanyong.wan95b12332009-09-25 18:55:50 +00001025#endif
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001026}
1027
vladlosev79b83502009-11-18 00:43:37 +00001028TEST(IsNullTest, LinkedPtr) {
1029 const Matcher<linked_ptr<int> > m = IsNull();
1030 const linked_ptr<int> null_p;
1031 const linked_ptr<int> non_null_p(new int);
1032
1033 EXPECT_TRUE(m.Matches(null_p));
1034 EXPECT_FALSE(m.Matches(non_null_p));
1035}
1036
1037TEST(IsNullTest, ReferenceToConstLinkedPtr) {
1038 const Matcher<const linked_ptr<double>&> m = IsNull();
1039 const linked_ptr<double> null_p;
1040 const linked_ptr<double> non_null_p(new double);
1041
1042 EXPECT_TRUE(m.Matches(null_p));
1043 EXPECT_FALSE(m.Matches(non_null_p));
1044}
1045
Mark Mentovaia0435dc2015-10-12 17:57:51 -04001046#if GTEST_HAS_STD_FUNCTION_
kosak6305ff52015-04-28 22:36:31 +00001047TEST(IsNullTest, StdFunction) {
1048 const Matcher<std::function<void()>> m = IsNull();
1049
1050 EXPECT_TRUE(m.Matches(std::function<void()>()));
1051 EXPECT_FALSE(m.Matches([]{}));
1052}
Mark Mentovaia0435dc2015-10-12 17:57:51 -04001053#endif // GTEST_HAS_STD_FUNCTION_
kosak6305ff52015-04-28 22:36:31 +00001054
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001055// Tests that IsNull() describes itself properly.
1056TEST(IsNullTest, CanDescribeSelf) {
1057 Matcher<int*> m = IsNull();
1058 EXPECT_EQ("is NULL", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001059 EXPECT_EQ("isn't NULL", DescribeNegation(m));
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001060}
1061
shiqiane35fdd92008-12-10 05:08:54 +00001062// Tests that NotNull() matches any non-NULL pointer of any type.
1063TEST(NotNullTest, MatchesNonNullPointer) {
1064 Matcher<int*> m1 = NotNull();
1065 int* p1 = NULL;
1066 int n = 0;
1067 EXPECT_FALSE(m1.Matches(p1));
1068 EXPECT_TRUE(m1.Matches(&n));
1069
1070 Matcher<const char*> m2 = NotNull();
1071 const char* p2 = NULL;
1072 EXPECT_FALSE(m2.Matches(p2));
1073 EXPECT_TRUE(m2.Matches("hi"));
1074}
1075
vladlosev79b83502009-11-18 00:43:37 +00001076TEST(NotNullTest, LinkedPtr) {
1077 const Matcher<linked_ptr<int> > m = NotNull();
1078 const linked_ptr<int> null_p;
1079 const linked_ptr<int> non_null_p(new int);
1080
1081 EXPECT_FALSE(m.Matches(null_p));
1082 EXPECT_TRUE(m.Matches(non_null_p));
1083}
1084
1085TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1086 const Matcher<const linked_ptr<double>&> m = NotNull();
1087 const linked_ptr<double> null_p;
1088 const linked_ptr<double> non_null_p(new double);
1089
1090 EXPECT_FALSE(m.Matches(null_p));
1091 EXPECT_TRUE(m.Matches(non_null_p));
1092}
1093
Mark Mentovaia0435dc2015-10-12 17:57:51 -04001094#if GTEST_HAS_STD_FUNCTION_
kosak6305ff52015-04-28 22:36:31 +00001095TEST(NotNullTest, StdFunction) {
1096 const Matcher<std::function<void()>> m = NotNull();
1097
1098 EXPECT_TRUE(m.Matches([]{}));
1099 EXPECT_FALSE(m.Matches(std::function<void()>()));
1100}
Mark Mentovaia0435dc2015-10-12 17:57:51 -04001101#endif // GTEST_HAS_STD_FUNCTION_
kosak6305ff52015-04-28 22:36:31 +00001102
shiqiane35fdd92008-12-10 05:08:54 +00001103// Tests that NotNull() describes itself properly.
1104TEST(NotNullTest, CanDescribeSelf) {
1105 Matcher<int*> m = NotNull();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001106 EXPECT_EQ("isn't NULL", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001107}
1108
1109// Tests that Ref(variable) matches an argument that references
1110// 'variable'.
1111TEST(RefTest, MatchesSameVariable) {
1112 int a = 0;
1113 int b = 0;
1114 Matcher<int&> m = Ref(a);
1115 EXPECT_TRUE(m.Matches(a));
1116 EXPECT_FALSE(m.Matches(b));
1117}
1118
1119// Tests that Ref(variable) describes itself properly.
1120TEST(RefTest, CanDescribeSelf) {
1121 int n = 5;
1122 Matcher<int&> m = Ref(n);
1123 stringstream ss;
1124 ss << "references the variable @" << &n << " 5";
1125 EXPECT_EQ(string(ss.str()), Describe(m));
1126}
1127
1128// Test that Ref(non_const_varialbe) can be used as a matcher for a
1129// const reference.
1130TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1131 int a = 0;
1132 int b = 0;
1133 Matcher<const int&> m = Ref(a);
1134 EXPECT_TRUE(m.Matches(a));
1135 EXPECT_FALSE(m.Matches(b));
1136}
1137
1138// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1139// used wherever Ref(base) can be used (Ref(derived) is a sub-type
1140// of Ref(base), but not vice versa.
1141
shiqiane35fdd92008-12-10 05:08:54 +00001142TEST(RefTest, IsCovariant) {
1143 Base base, base2;
1144 Derived derived;
1145 Matcher<const Base&> m1 = Ref(base);
1146 EXPECT_TRUE(m1.Matches(base));
1147 EXPECT_FALSE(m1.Matches(base2));
1148 EXPECT_FALSE(m1.Matches(derived));
1149
1150 m1 = Ref(derived);
1151 EXPECT_TRUE(m1.Matches(derived));
1152 EXPECT_FALSE(m1.Matches(base));
1153 EXPECT_FALSE(m1.Matches(base2));
1154}
1155
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001156TEST(RefTest, ExplainsResult) {
1157 int n = 0;
1158 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1159 StartsWith("which is located @"));
1160
1161 int m = 0;
1162 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1163 StartsWith("which is located @"));
1164}
1165
shiqiane35fdd92008-12-10 05:08:54 +00001166// Tests string comparison matchers.
1167
1168TEST(StrEqTest, MatchesEqualString) {
1169 Matcher<const char*> m = StrEq(string("Hello"));
1170 EXPECT_TRUE(m.Matches("Hello"));
1171 EXPECT_FALSE(m.Matches("hello"));
1172 EXPECT_FALSE(m.Matches(NULL));
1173
1174 Matcher<const string&> m2 = StrEq("Hello");
1175 EXPECT_TRUE(m2.Matches("Hello"));
1176 EXPECT_FALSE(m2.Matches("Hi"));
1177}
1178
1179TEST(StrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001180 Matcher<string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1181 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
shiqiane35fdd92008-12-10 05:08:54 +00001182 Describe(m));
1183
1184 string str("01204500800");
1185 str[3] = '\0';
1186 Matcher<string> m2 = StrEq(str);
1187 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1188 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1189 Matcher<string> m3 = StrEq(str);
1190 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1191}
1192
1193TEST(StrNeTest, MatchesUnequalString) {
1194 Matcher<const char*> m = StrNe("Hello");
1195 EXPECT_TRUE(m.Matches(""));
1196 EXPECT_TRUE(m.Matches(NULL));
1197 EXPECT_FALSE(m.Matches("Hello"));
1198
1199 Matcher<string> m2 = StrNe(string("Hello"));
1200 EXPECT_TRUE(m2.Matches("hello"));
1201 EXPECT_FALSE(m2.Matches("Hello"));
1202}
1203
1204TEST(StrNeTest, CanDescribeSelf) {
1205 Matcher<const char*> m = StrNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001206 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001207}
1208
1209TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1210 Matcher<const char*> m = StrCaseEq(string("Hello"));
1211 EXPECT_TRUE(m.Matches("Hello"));
1212 EXPECT_TRUE(m.Matches("hello"));
1213 EXPECT_FALSE(m.Matches("Hi"));
1214 EXPECT_FALSE(m.Matches(NULL));
1215
1216 Matcher<const string&> m2 = StrCaseEq("Hello");
1217 EXPECT_TRUE(m2.Matches("hello"));
1218 EXPECT_FALSE(m2.Matches("Hi"));
1219}
1220
1221TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1222 string str1("oabocdooeoo");
1223 string str2("OABOCDOOEOO");
1224 Matcher<const string&> m0 = StrCaseEq(str1);
1225 EXPECT_FALSE(m0.Matches(str2 + string(1, '\0')));
1226
1227 str1[3] = str2[3] = '\0';
1228 Matcher<const string&> m1 = StrCaseEq(str1);
1229 EXPECT_TRUE(m1.Matches(str2));
1230
1231 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1232 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1233 Matcher<const string&> m2 = StrCaseEq(str1);
1234 str1[9] = str2[9] = '\0';
1235 EXPECT_FALSE(m2.Matches(str2));
1236
1237 Matcher<const string&> m3 = StrCaseEq(str1);
1238 EXPECT_TRUE(m3.Matches(str2));
1239
1240 EXPECT_FALSE(m3.Matches(str2 + "x"));
1241 str2.append(1, '\0');
1242 EXPECT_FALSE(m3.Matches(str2));
1243 EXPECT_FALSE(m3.Matches(string(str2, 0, 9)));
1244}
1245
1246TEST(StrCaseEqTest, CanDescribeSelf) {
1247 Matcher<string> m = StrCaseEq("Hi");
1248 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1249}
1250
1251TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1252 Matcher<const char*> m = StrCaseNe("Hello");
1253 EXPECT_TRUE(m.Matches("Hi"));
1254 EXPECT_TRUE(m.Matches(NULL));
1255 EXPECT_FALSE(m.Matches("Hello"));
1256 EXPECT_FALSE(m.Matches("hello"));
1257
1258 Matcher<string> m2 = StrCaseNe(string("Hello"));
1259 EXPECT_TRUE(m2.Matches(""));
1260 EXPECT_FALSE(m2.Matches("Hello"));
1261}
1262
1263TEST(StrCaseNeTest, CanDescribeSelf) {
1264 Matcher<const char*> m = StrCaseNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001265 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001266}
1267
1268// Tests that HasSubstr() works for matching string-typed values.
1269TEST(HasSubstrTest, WorksForStringClasses) {
1270 const Matcher<string> m1 = HasSubstr("foo");
1271 EXPECT_TRUE(m1.Matches(string("I love food.")));
1272 EXPECT_FALSE(m1.Matches(string("tofo")));
1273
1274 const Matcher<const std::string&> m2 = HasSubstr("foo");
1275 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1276 EXPECT_FALSE(m2.Matches(std::string("tofo")));
1277}
1278
1279// Tests that HasSubstr() works for matching C-string-typed values.
1280TEST(HasSubstrTest, WorksForCStrings) {
1281 const Matcher<char*> m1 = HasSubstr("foo");
1282 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1283 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1284 EXPECT_FALSE(m1.Matches(NULL));
1285
1286 const Matcher<const char*> m2 = HasSubstr("foo");
1287 EXPECT_TRUE(m2.Matches("I love food."));
1288 EXPECT_FALSE(m2.Matches("tofo"));
1289 EXPECT_FALSE(m2.Matches(NULL));
1290}
1291
1292// Tests that HasSubstr(s) describes itself properly.
1293TEST(HasSubstrTest, CanDescribeSelf) {
1294 Matcher<string> m = HasSubstr("foo\n\"");
1295 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1296}
1297
zhanyong.wanb5937da2009-07-16 20:26:41 +00001298TEST(KeyTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001299 Matcher<const pair<std::string, int>&> m = Key("foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001300 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001301 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1302}
1303
1304TEST(KeyTest, ExplainsResult) {
1305 Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1306 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1307 Explain(m, make_pair(5, true)));
1308 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1309 Explain(m, make_pair(15, true)));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001310}
1311
1312TEST(KeyTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001313 pair<int, std::string> p(25, "foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001314 EXPECT_THAT(p, Key(25));
1315 EXPECT_THAT(p, Not(Key(42)));
1316 EXPECT_THAT(p, Key(Ge(20)));
1317 EXPECT_THAT(p, Not(Key(Lt(25))));
1318}
1319
1320TEST(KeyTest, SafelyCastsInnerMatcher) {
1321 Matcher<int> is_positive = Gt(0);
1322 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001323 pair<char, bool> p('a', true);
zhanyong.wanb5937da2009-07-16 20:26:41 +00001324 EXPECT_THAT(p, Key(is_positive));
1325 EXPECT_THAT(p, Not(Key(is_negative)));
1326}
1327
1328TEST(KeyTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001329 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001330 container.insert(make_pair(1, 'a'));
1331 container.insert(make_pair(2, 'b'));
1332 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001333 EXPECT_THAT(container, Contains(Key(1)));
1334 EXPECT_THAT(container, Not(Contains(Key(3))));
1335}
1336
1337TEST(KeyTest, InsideContainsUsingMultimap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001338 multimap<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001339 container.insert(make_pair(1, 'a'));
1340 container.insert(make_pair(2, 'b'));
1341 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001342
1343 EXPECT_THAT(container, Not(Contains(Key(25))));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001344 container.insert(make_pair(25, 'd'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001345 EXPECT_THAT(container, Contains(Key(25)));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001346 container.insert(make_pair(25, 'e'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001347 EXPECT_THAT(container, Contains(Key(25)));
1348
1349 EXPECT_THAT(container, Contains(Key(1)));
1350 EXPECT_THAT(container, Not(Contains(Key(3))));
1351}
1352
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001353TEST(PairTest, Typing) {
1354 // Test verifies the following type conversions can be compiled.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001355 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1356 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1357 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001358
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001359 Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1360 Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001361}
1362
1363TEST(PairTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001364 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001365 EXPECT_EQ("has a first field that is equal to \"foo\""
1366 ", and has a second field that is equal to 42",
1367 Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001368 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1369 ", or has a second field that isn't equal to 42",
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001370 DescribeNegation(m1));
1371 // Double and triple negation (1 or 2 times not and description of negation).
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001372 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1373 EXPECT_EQ("has a first field that isn't equal to 13"
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001374 ", and has a second field that is equal to 42",
1375 DescribeNegation(m2));
1376}
1377
1378TEST(PairTest, CanExplainMatchResultTo) {
zhanyong.wan82113312010-01-08 21:55:40 +00001379 // If neither field matches, Pair() should explain about the first
1380 // field.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001381 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001382 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001383 Explain(m, make_pair(-1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001384
zhanyong.wan82113312010-01-08 21:55:40 +00001385 // If the first field matches but the second doesn't, Pair() should
1386 // explain about the second field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001387 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001388 Explain(m, make_pair(1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001389
zhanyong.wan82113312010-01-08 21:55:40 +00001390 // If the first field doesn't match but the second does, Pair()
1391 // should explain about the first field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001392 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001393 Explain(m, make_pair(-1, 2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001394
zhanyong.wan82113312010-01-08 21:55:40 +00001395 // If both fields match, Pair() should explain about them both.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001396 EXPECT_EQ("whose both fields match, where the first field is a value "
1397 "which is 1 more than 0, and the second field is a value "
1398 "which is 2 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001399 Explain(m, make_pair(1, 2)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001400
1401 // If only the first match has an explanation, only this explanation should
1402 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001403 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001404 EXPECT_EQ("whose both fields match, where the first field is a value "
1405 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001406 Explain(explain_first, make_pair(1, 0)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001407
1408 // If only the second match has an explanation, only this explanation should
1409 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001410 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001411 EXPECT_EQ("whose both fields match, where the second field is a value "
1412 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001413 Explain(explain_second, make_pair(0, 1)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001414}
1415
1416TEST(PairTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001417 pair<int, std::string> p(25, "foo");
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001418
1419 // Both fields match.
1420 EXPECT_THAT(p, Pair(25, "foo"));
1421 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1422
1423 // 'first' doesnt' match, but 'second' matches.
1424 EXPECT_THAT(p, Not(Pair(42, "foo")));
1425 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1426
1427 // 'first' matches, but 'second' doesn't match.
1428 EXPECT_THAT(p, Not(Pair(25, "bar")));
1429 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1430
1431 // Neither field matches.
1432 EXPECT_THAT(p, Not(Pair(13, "bar")));
1433 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1434}
1435
1436TEST(PairTest, SafelyCastsInnerMatchers) {
1437 Matcher<int> is_positive = Gt(0);
1438 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001439 pair<char, bool> p('a', true);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001440 EXPECT_THAT(p, Pair(is_positive, _));
1441 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1442 EXPECT_THAT(p, Pair(_, is_positive));
1443 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1444}
1445
1446TEST(PairTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001447 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001448 container.insert(make_pair(1, 'a'));
1449 container.insert(make_pair(2, 'b'));
1450 container.insert(make_pair(4, 'c'));
zhanyong.wan95b12332009-09-25 18:55:50 +00001451 EXPECT_THAT(container, Contains(Pair(1, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001452 EXPECT_THAT(container, Contains(Pair(1, _)));
zhanyong.wan95b12332009-09-25 18:55:50 +00001453 EXPECT_THAT(container, Contains(Pair(_, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001454 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1455}
1456
shiqiane35fdd92008-12-10 05:08:54 +00001457// Tests StartsWith(s).
1458
1459TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1460 const Matcher<const char*> m1 = StartsWith(string(""));
1461 EXPECT_TRUE(m1.Matches("Hi"));
1462 EXPECT_TRUE(m1.Matches(""));
1463 EXPECT_FALSE(m1.Matches(NULL));
1464
1465 const Matcher<const string&> m2 = StartsWith("Hi");
1466 EXPECT_TRUE(m2.Matches("Hi"));
1467 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1468 EXPECT_TRUE(m2.Matches("High"));
1469 EXPECT_FALSE(m2.Matches("H"));
1470 EXPECT_FALSE(m2.Matches(" Hi"));
1471}
1472
1473TEST(StartsWithTest, CanDescribeSelf) {
1474 Matcher<const std::string> m = StartsWith("Hi");
1475 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1476}
1477
1478// Tests EndsWith(s).
1479
1480TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1481 const Matcher<const char*> m1 = EndsWith("");
1482 EXPECT_TRUE(m1.Matches("Hi"));
1483 EXPECT_TRUE(m1.Matches(""));
1484 EXPECT_FALSE(m1.Matches(NULL));
1485
1486 const Matcher<const string&> m2 = EndsWith(string("Hi"));
1487 EXPECT_TRUE(m2.Matches("Hi"));
1488 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1489 EXPECT_TRUE(m2.Matches("Super Hi"));
1490 EXPECT_FALSE(m2.Matches("i"));
1491 EXPECT_FALSE(m2.Matches("Hi "));
1492}
1493
1494TEST(EndsWithTest, CanDescribeSelf) {
1495 Matcher<const std::string> m = EndsWith("Hi");
1496 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1497}
1498
shiqiane35fdd92008-12-10 05:08:54 +00001499// Tests MatchesRegex().
1500
1501TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1502 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1503 EXPECT_TRUE(m1.Matches("az"));
1504 EXPECT_TRUE(m1.Matches("abcz"));
1505 EXPECT_FALSE(m1.Matches(NULL));
1506
1507 const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z"));
1508 EXPECT_TRUE(m2.Matches("azbz"));
1509 EXPECT_FALSE(m2.Matches("az1"));
1510 EXPECT_FALSE(m2.Matches("1az"));
1511}
1512
1513TEST(MatchesRegexTest, CanDescribeSelf) {
1514 Matcher<const std::string> m1 = MatchesRegex(string("Hi.*"));
1515 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1516
zhanyong.wand14aaed2010-01-14 05:36:32 +00001517 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1518 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001519}
1520
1521// Tests ContainsRegex().
1522
1523TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1524 const Matcher<const char*> m1 = ContainsRegex(string("a.*z"));
1525 EXPECT_TRUE(m1.Matches("az"));
1526 EXPECT_TRUE(m1.Matches("0abcz1"));
1527 EXPECT_FALSE(m1.Matches(NULL));
1528
1529 const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z"));
1530 EXPECT_TRUE(m2.Matches("azbz"));
1531 EXPECT_TRUE(m2.Matches("az1"));
1532 EXPECT_FALSE(m2.Matches("1a"));
1533}
1534
1535TEST(ContainsRegexTest, CanDescribeSelf) {
1536 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1537 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1538
zhanyong.wand14aaed2010-01-14 05:36:32 +00001539 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1540 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001541}
shiqiane35fdd92008-12-10 05:08:54 +00001542
1543// Tests for wide strings.
1544#if GTEST_HAS_STD_WSTRING
1545TEST(StdWideStrEqTest, MatchesEqual) {
1546 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1547 EXPECT_TRUE(m.Matches(L"Hello"));
1548 EXPECT_FALSE(m.Matches(L"hello"));
1549 EXPECT_FALSE(m.Matches(NULL));
1550
1551 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1552 EXPECT_TRUE(m2.Matches(L"Hello"));
1553 EXPECT_FALSE(m2.Matches(L"Hi"));
1554
1555 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1556 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1557 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1558
1559 ::std::wstring str(L"01204500800");
1560 str[3] = L'\0';
1561 Matcher<const ::std::wstring&> m4 = StrEq(str);
1562 EXPECT_TRUE(m4.Matches(str));
1563 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1564 Matcher<const ::std::wstring&> m5 = StrEq(str);
1565 EXPECT_TRUE(m5.Matches(str));
1566}
1567
1568TEST(StdWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001569 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1570 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001571 Describe(m));
1572
1573 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1574 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1575 Describe(m2));
1576
1577 ::std::wstring str(L"01204500800");
1578 str[3] = L'\0';
1579 Matcher<const ::std::wstring&> m4 = StrEq(str);
1580 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1581 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1582 Matcher<const ::std::wstring&> m5 = StrEq(str);
1583 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1584}
1585
1586TEST(StdWideStrNeTest, MatchesUnequalString) {
1587 Matcher<const wchar_t*> m = StrNe(L"Hello");
1588 EXPECT_TRUE(m.Matches(L""));
1589 EXPECT_TRUE(m.Matches(NULL));
1590 EXPECT_FALSE(m.Matches(L"Hello"));
1591
1592 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1593 EXPECT_TRUE(m2.Matches(L"hello"));
1594 EXPECT_FALSE(m2.Matches(L"Hello"));
1595}
1596
1597TEST(StdWideStrNeTest, CanDescribeSelf) {
1598 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001599 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001600}
1601
1602TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1603 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1604 EXPECT_TRUE(m.Matches(L"Hello"));
1605 EXPECT_TRUE(m.Matches(L"hello"));
1606 EXPECT_FALSE(m.Matches(L"Hi"));
1607 EXPECT_FALSE(m.Matches(NULL));
1608
1609 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1610 EXPECT_TRUE(m2.Matches(L"hello"));
1611 EXPECT_FALSE(m2.Matches(L"Hi"));
1612}
1613
1614TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1615 ::std::wstring str1(L"oabocdooeoo");
1616 ::std::wstring str2(L"OABOCDOOEOO");
1617 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1618 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1619
1620 str1[3] = str2[3] = L'\0';
1621 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1622 EXPECT_TRUE(m1.Matches(str2));
1623
1624 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1625 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1626 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1627 str1[9] = str2[9] = L'\0';
1628 EXPECT_FALSE(m2.Matches(str2));
1629
1630 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1631 EXPECT_TRUE(m3.Matches(str2));
1632
1633 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1634 str2.append(1, L'\0');
1635 EXPECT_FALSE(m3.Matches(str2));
1636 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1637}
1638
1639TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1640 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1641 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1642}
1643
1644TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1645 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1646 EXPECT_TRUE(m.Matches(L"Hi"));
1647 EXPECT_TRUE(m.Matches(NULL));
1648 EXPECT_FALSE(m.Matches(L"Hello"));
1649 EXPECT_FALSE(m.Matches(L"hello"));
1650
1651 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1652 EXPECT_TRUE(m2.Matches(L""));
1653 EXPECT_FALSE(m2.Matches(L"Hello"));
1654}
1655
1656TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1657 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001658 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001659}
1660
1661// Tests that HasSubstr() works for matching wstring-typed values.
1662TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1663 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1664 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1665 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1666
1667 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1668 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1669 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1670}
1671
1672// Tests that HasSubstr() works for matching C-wide-string-typed values.
1673TEST(StdWideHasSubstrTest, WorksForCStrings) {
1674 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1675 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1676 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1677 EXPECT_FALSE(m1.Matches(NULL));
1678
1679 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1680 EXPECT_TRUE(m2.Matches(L"I love food."));
1681 EXPECT_FALSE(m2.Matches(L"tofo"));
1682 EXPECT_FALSE(m2.Matches(NULL));
1683}
1684
1685// Tests that HasSubstr(s) describes itself properly.
1686TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1687 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1688 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1689}
1690
1691// Tests StartsWith(s).
1692
1693TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1694 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1695 EXPECT_TRUE(m1.Matches(L"Hi"));
1696 EXPECT_TRUE(m1.Matches(L""));
1697 EXPECT_FALSE(m1.Matches(NULL));
1698
1699 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1700 EXPECT_TRUE(m2.Matches(L"Hi"));
1701 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1702 EXPECT_TRUE(m2.Matches(L"High"));
1703 EXPECT_FALSE(m2.Matches(L"H"));
1704 EXPECT_FALSE(m2.Matches(L" Hi"));
1705}
1706
1707TEST(StdWideStartsWithTest, CanDescribeSelf) {
1708 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
1709 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1710}
1711
1712// Tests EndsWith(s).
1713
1714TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
1715 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1716 EXPECT_TRUE(m1.Matches(L"Hi"));
1717 EXPECT_TRUE(m1.Matches(L""));
1718 EXPECT_FALSE(m1.Matches(NULL));
1719
1720 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
1721 EXPECT_TRUE(m2.Matches(L"Hi"));
1722 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1723 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1724 EXPECT_FALSE(m2.Matches(L"i"));
1725 EXPECT_FALSE(m2.Matches(L"Hi "));
1726}
1727
1728TEST(StdWideEndsWithTest, CanDescribeSelf) {
1729 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
1730 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1731}
1732
1733#endif // GTEST_HAS_STD_WSTRING
1734
1735#if GTEST_HAS_GLOBAL_WSTRING
1736TEST(GlobalWideStrEqTest, MatchesEqual) {
1737 Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
1738 EXPECT_TRUE(m.Matches(L"Hello"));
1739 EXPECT_FALSE(m.Matches(L"hello"));
1740 EXPECT_FALSE(m.Matches(NULL));
1741
1742 Matcher<const ::wstring&> m2 = StrEq(L"Hello");
1743 EXPECT_TRUE(m2.Matches(L"Hello"));
1744 EXPECT_FALSE(m2.Matches(L"Hi"));
1745
1746 Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1747 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1748 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1749
1750 ::wstring str(L"01204500800");
1751 str[3] = L'\0';
1752 Matcher<const ::wstring&> m4 = StrEq(str);
1753 EXPECT_TRUE(m4.Matches(str));
1754 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1755 Matcher<const ::wstring&> m5 = StrEq(str);
1756 EXPECT_TRUE(m5.Matches(str));
1757}
1758
1759TEST(GlobalWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001760 Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1761 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001762 Describe(m));
1763
1764 Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1765 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1766 Describe(m2));
1767
1768 ::wstring str(L"01204500800");
1769 str[3] = L'\0';
1770 Matcher<const ::wstring&> m4 = StrEq(str);
1771 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1772 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1773 Matcher<const ::wstring&> m5 = StrEq(str);
1774 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1775}
1776
1777TEST(GlobalWideStrNeTest, MatchesUnequalString) {
1778 Matcher<const wchar_t*> m = StrNe(L"Hello");
1779 EXPECT_TRUE(m.Matches(L""));
1780 EXPECT_TRUE(m.Matches(NULL));
1781 EXPECT_FALSE(m.Matches(L"Hello"));
1782
1783 Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
1784 EXPECT_TRUE(m2.Matches(L"hello"));
1785 EXPECT_FALSE(m2.Matches(L"Hello"));
1786}
1787
1788TEST(GlobalWideStrNeTest, CanDescribeSelf) {
1789 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001790 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001791}
1792
1793TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1794 Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
1795 EXPECT_TRUE(m.Matches(L"Hello"));
1796 EXPECT_TRUE(m.Matches(L"hello"));
1797 EXPECT_FALSE(m.Matches(L"Hi"));
1798 EXPECT_FALSE(m.Matches(NULL));
1799
1800 Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
1801 EXPECT_TRUE(m2.Matches(L"hello"));
1802 EXPECT_FALSE(m2.Matches(L"Hi"));
1803}
1804
1805TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1806 ::wstring str1(L"oabocdooeoo");
1807 ::wstring str2(L"OABOCDOOEOO");
1808 Matcher<const ::wstring&> m0 = StrCaseEq(str1);
1809 EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
1810
1811 str1[3] = str2[3] = L'\0';
1812 Matcher<const ::wstring&> m1 = StrCaseEq(str1);
1813 EXPECT_TRUE(m1.Matches(str2));
1814
1815 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1816 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1817 Matcher<const ::wstring&> m2 = StrCaseEq(str1);
1818 str1[9] = str2[9] = L'\0';
1819 EXPECT_FALSE(m2.Matches(str2));
1820
1821 Matcher<const ::wstring&> m3 = StrCaseEq(str1);
1822 EXPECT_TRUE(m3.Matches(str2));
1823
1824 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1825 str2.append(1, L'\0');
1826 EXPECT_FALSE(m3.Matches(str2));
1827 EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
1828}
1829
1830TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
1831 Matcher< ::wstring> m = StrCaseEq(L"Hi");
1832 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1833}
1834
1835TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1836 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1837 EXPECT_TRUE(m.Matches(L"Hi"));
1838 EXPECT_TRUE(m.Matches(NULL));
1839 EXPECT_FALSE(m.Matches(L"Hello"));
1840 EXPECT_FALSE(m.Matches(L"hello"));
1841
1842 Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
1843 EXPECT_TRUE(m2.Matches(L""));
1844 EXPECT_FALSE(m2.Matches(L"Hello"));
1845}
1846
1847TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
1848 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001849 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001850}
1851
1852// Tests that HasSubstr() works for matching wstring-typed values.
1853TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
1854 const Matcher< ::wstring> m1 = HasSubstr(L"foo");
1855 EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
1856 EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
1857
1858 const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
1859 EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
1860 EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
1861}
1862
1863// Tests that HasSubstr() works for matching C-wide-string-typed values.
1864TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
1865 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1866 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1867 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1868 EXPECT_FALSE(m1.Matches(NULL));
1869
1870 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1871 EXPECT_TRUE(m2.Matches(L"I love food."));
1872 EXPECT_FALSE(m2.Matches(L"tofo"));
1873 EXPECT_FALSE(m2.Matches(NULL));
1874}
1875
1876// Tests that HasSubstr(s) describes itself properly.
1877TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
1878 Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
1879 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1880}
1881
1882// Tests StartsWith(s).
1883
1884TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
1885 const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
1886 EXPECT_TRUE(m1.Matches(L"Hi"));
1887 EXPECT_TRUE(m1.Matches(L""));
1888 EXPECT_FALSE(m1.Matches(NULL));
1889
1890 const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
1891 EXPECT_TRUE(m2.Matches(L"Hi"));
1892 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1893 EXPECT_TRUE(m2.Matches(L"High"));
1894 EXPECT_FALSE(m2.Matches(L"H"));
1895 EXPECT_FALSE(m2.Matches(L" Hi"));
1896}
1897
1898TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
1899 Matcher<const ::wstring> m = StartsWith(L"Hi");
1900 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1901}
1902
1903// Tests EndsWith(s).
1904
1905TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
1906 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1907 EXPECT_TRUE(m1.Matches(L"Hi"));
1908 EXPECT_TRUE(m1.Matches(L""));
1909 EXPECT_FALSE(m1.Matches(NULL));
1910
1911 const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
1912 EXPECT_TRUE(m2.Matches(L"Hi"));
1913 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1914 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1915 EXPECT_FALSE(m2.Matches(L"i"));
1916 EXPECT_FALSE(m2.Matches(L"Hi "));
1917}
1918
1919TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
1920 Matcher<const ::wstring> m = EndsWith(L"Hi");
1921 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1922}
1923
1924#endif // GTEST_HAS_GLOBAL_WSTRING
1925
1926
kosakbd018832014-04-02 20:30:00 +00001927typedef ::testing::tuple<long, int> Tuple2; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00001928
1929// Tests that Eq() matches a 2-tuple where the first field == the
1930// second field.
1931TEST(Eq2Test, MatchesEqualArguments) {
1932 Matcher<const Tuple2&> m = Eq();
1933 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1934 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1935}
1936
1937// Tests that Eq() describes itself properly.
1938TEST(Eq2Test, CanDescribeSelf) {
1939 Matcher<const Tuple2&> m = Eq();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001940 EXPECT_EQ("are an equal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001941}
1942
1943// Tests that Ge() matches a 2-tuple where the first field >= the
1944// second field.
1945TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
1946 Matcher<const Tuple2&> m = Ge();
1947 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1948 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1949 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1950}
1951
1952// Tests that Ge() describes itself properly.
1953TEST(Ge2Test, CanDescribeSelf) {
1954 Matcher<const Tuple2&> m = Ge();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001955 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001956}
1957
1958// Tests that Gt() matches a 2-tuple where the first field > the
1959// second field.
1960TEST(Gt2Test, MatchesGreaterThanArguments) {
1961 Matcher<const Tuple2&> m = Gt();
1962 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1963 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1964 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1965}
1966
1967// Tests that Gt() describes itself properly.
1968TEST(Gt2Test, CanDescribeSelf) {
1969 Matcher<const Tuple2&> m = Gt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001970 EXPECT_EQ("are a pair where the first > the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001971}
1972
1973// Tests that Le() matches a 2-tuple where the first field <= the
1974// second field.
1975TEST(Le2Test, MatchesLessThanOrEqualArguments) {
1976 Matcher<const Tuple2&> m = Le();
1977 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1978 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1979 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1980}
1981
1982// Tests that Le() describes itself properly.
1983TEST(Le2Test, CanDescribeSelf) {
1984 Matcher<const Tuple2&> m = Le();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001985 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001986}
1987
1988// Tests that Lt() matches a 2-tuple where the first field < the
1989// second field.
1990TEST(Lt2Test, MatchesLessThanArguments) {
1991 Matcher<const Tuple2&> m = Lt();
1992 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1993 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1994 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1995}
1996
1997// Tests that Lt() describes itself properly.
1998TEST(Lt2Test, CanDescribeSelf) {
1999 Matcher<const Tuple2&> m = Lt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002000 EXPECT_EQ("are a pair where the first < the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002001}
2002
2003// Tests that Ne() matches a 2-tuple where the first field != the
2004// second field.
2005TEST(Ne2Test, MatchesUnequalArguments) {
2006 Matcher<const Tuple2&> m = Ne();
2007 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2008 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2009 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2010}
2011
2012// Tests that Ne() describes itself properly.
2013TEST(Ne2Test, CanDescribeSelf) {
2014 Matcher<const Tuple2&> m = Ne();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002015 EXPECT_EQ("are an unequal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002016}
2017
2018// Tests that Not(m) matches any value that doesn't match m.
2019TEST(NotTest, NegatesMatcher) {
2020 Matcher<int> m;
2021 m = Not(Eq(2));
2022 EXPECT_TRUE(m.Matches(3));
2023 EXPECT_FALSE(m.Matches(2));
2024}
2025
2026// Tests that Not(m) describes itself properly.
2027TEST(NotTest, CanDescribeSelf) {
2028 Matcher<int> m = Not(Eq(5));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002029 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002030}
2031
zhanyong.wan18490652009-05-11 18:54:08 +00002032// Tests that monomorphic matchers are safely cast by the Not matcher.
2033TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2034 // greater_than_5 is a monomorphic matcher.
2035 Matcher<int> greater_than_5 = Gt(5);
2036
2037 Matcher<const int&> m = Not(greater_than_5);
2038 Matcher<int&> m2 = Not(greater_than_5);
2039 Matcher<int&> m3 = Not(m);
2040}
2041
zhanyong.wan02c15052010-06-09 19:21:30 +00002042// Helper to allow easy testing of AllOf matchers with num parameters.
2043void AllOfMatches(int num, const Matcher<int>& m) {
2044 SCOPED_TRACE(Describe(m));
2045 EXPECT_TRUE(m.Matches(0));
2046 for (int i = 1; i <= num; ++i) {
2047 EXPECT_FALSE(m.Matches(i));
2048 }
2049 EXPECT_TRUE(m.Matches(num + 1));
2050}
2051
shiqiane35fdd92008-12-10 05:08:54 +00002052// Tests that AllOf(m1, ..., mn) matches any value that matches all of
2053// the given matchers.
2054TEST(AllOfTest, MatchesWhenAllMatch) {
2055 Matcher<int> m;
2056 m = AllOf(Le(2), Ge(1));
2057 EXPECT_TRUE(m.Matches(1));
2058 EXPECT_TRUE(m.Matches(2));
2059 EXPECT_FALSE(m.Matches(0));
2060 EXPECT_FALSE(m.Matches(3));
2061
2062 m = AllOf(Gt(0), Ne(1), Ne(2));
2063 EXPECT_TRUE(m.Matches(3));
2064 EXPECT_FALSE(m.Matches(2));
2065 EXPECT_FALSE(m.Matches(1));
2066 EXPECT_FALSE(m.Matches(0));
2067
2068 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2069 EXPECT_TRUE(m.Matches(4));
2070 EXPECT_FALSE(m.Matches(3));
2071 EXPECT_FALSE(m.Matches(2));
2072 EXPECT_FALSE(m.Matches(1));
2073 EXPECT_FALSE(m.Matches(0));
2074
2075 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2076 EXPECT_TRUE(m.Matches(0));
2077 EXPECT_TRUE(m.Matches(1));
2078 EXPECT_FALSE(m.Matches(3));
zhanyong.wan02c15052010-06-09 19:21:30 +00002079
2080 // The following tests for varying number of sub-matchers. Due to the way
2081 // the sub-matchers are handled it is enough to test every sub-matcher once
2082 // with sub-matchers using the same matcher type. Varying matcher types are
2083 // checked for above.
2084 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2085 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2086 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2087 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2088 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2089 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2090 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2091 Ne(8)));
2092 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2093 Ne(8), Ne(9)));
2094 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2095 Ne(9), Ne(10)));
shiqiane35fdd92008-12-10 05:08:54 +00002096}
2097
zhanyong.wan616180e2013-06-18 18:49:51 +00002098#if GTEST_LANG_CXX11
2099// Tests the variadic version of the AllOfMatcher.
2100TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
2101 // Make sure AllOf is defined in the right namespace and does not depend on
2102 // ADL.
2103 ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2104 Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2105 Ne(9), Ne(10), Ne(11));
2106 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))"));
2107 AllOfMatches(11, m);
2108 AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2109 Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
2110 Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22),
2111 Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29),
2112 Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36),
2113 Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43),
2114 Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2115 Ne(50)));
2116}
2117
2118#endif // GTEST_LANG_CXX11
2119
shiqiane35fdd92008-12-10 05:08:54 +00002120// Tests that AllOf(m1, ..., mn) describes itself properly.
2121TEST(AllOfTest, CanDescribeSelf) {
2122 Matcher<int> m;
2123 m = AllOf(Le(2), Ge(1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002124 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002125
2126 m = AllOf(Gt(0), Ne(1), Ne(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002127 EXPECT_EQ("(is > 0) and "
2128 "((isn't equal to 1) and "
2129 "(isn't equal to 2))",
shiqiane35fdd92008-12-10 05:08:54 +00002130 Describe(m));
2131
2132
2133 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002134 EXPECT_EQ("((is > 0) and "
2135 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002136 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002137 "(isn't equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002138 Describe(m));
2139
2140
2141 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002142 EXPECT_EQ("((is >= 0) and "
2143 "(is < 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002144 "((isn't equal to 3) and "
2145 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002146 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002147 Describe(m));
2148}
2149
2150// Tests that AllOf(m1, ..., mn) describes its negation properly.
2151TEST(AllOfTest, CanDescribeNegation) {
2152 Matcher<int> m;
2153 m = AllOf(Le(2), Ge(1));
2154 EXPECT_EQ("(isn't <= 2) or "
2155 "(isn't >= 1)",
2156 DescribeNegation(m));
2157
2158 m = AllOf(Gt(0), Ne(1), Ne(2));
2159 EXPECT_EQ("(isn't > 0) or "
2160 "((is equal to 1) or "
2161 "(is equal to 2))",
2162 DescribeNegation(m));
2163
2164
2165 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002166 EXPECT_EQ("((isn't > 0) or "
2167 "(is equal to 1)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002168 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002169 "(is equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002170 DescribeNegation(m));
2171
2172
2173 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002174 EXPECT_EQ("((isn't >= 0) or "
2175 "(isn't < 10)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002176 "((is equal to 3) or "
2177 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002178 "(is equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002179 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00002180}
2181
zhanyong.wan18490652009-05-11 18:54:08 +00002182// Tests that monomorphic matchers are safely cast by the AllOf matcher.
2183TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2184 // greater_than_5 and less_than_10 are monomorphic matchers.
2185 Matcher<int> greater_than_5 = Gt(5);
2186 Matcher<int> less_than_10 = Lt(10);
2187
2188 Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2189 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2190 Matcher<int&> m3 = AllOf(greater_than_5, m2);
2191
2192 // Tests that BothOf works when composing itself.
2193 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2194 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2195}
2196
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002197TEST(AllOfTest, ExplainsResult) {
2198 Matcher<int> m;
2199
2200 // Successful match. Both matchers need to explain. The second
2201 // matcher doesn't give an explanation, so only the first matcher's
2202 // explanation is printed.
2203 m = AllOf(GreaterThan(10), Lt(30));
2204 EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2205
2206 // Successful match. Both matchers need to explain.
2207 m = AllOf(GreaterThan(10), GreaterThan(20));
2208 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2209 Explain(m, 30));
2210
2211 // Successful match. All matchers need to explain. The second
2212 // matcher doesn't given an explanation.
2213 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2214 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2215 Explain(m, 25));
2216
2217 // Successful match. All matchers need to explain.
2218 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2219 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2220 "and which is 10 more than 30",
2221 Explain(m, 40));
2222
2223 // Failed match. The first matcher, which failed, needs to
2224 // explain.
2225 m = AllOf(GreaterThan(10), GreaterThan(20));
2226 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2227
2228 // Failed match. The second matcher, which failed, needs to
2229 // explain. Since it doesn't given an explanation, nothing is
2230 // printed.
2231 m = AllOf(GreaterThan(10), Lt(30));
2232 EXPECT_EQ("", Explain(m, 40));
2233
2234 // Failed match. The second matcher, which failed, needs to
2235 // explain.
2236 m = AllOf(GreaterThan(10), GreaterThan(20));
2237 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2238}
2239
zhanyong.wan02c15052010-06-09 19:21:30 +00002240// Helper to allow easy testing of AnyOf matchers with num parameters.
2241void AnyOfMatches(int num, const Matcher<int>& m) {
2242 SCOPED_TRACE(Describe(m));
2243 EXPECT_FALSE(m.Matches(0));
2244 for (int i = 1; i <= num; ++i) {
2245 EXPECT_TRUE(m.Matches(i));
2246 }
2247 EXPECT_FALSE(m.Matches(num + 1));
2248}
2249
shiqiane35fdd92008-12-10 05:08:54 +00002250// Tests that AnyOf(m1, ..., mn) matches any value that matches at
2251// least one of the given matchers.
2252TEST(AnyOfTest, MatchesWhenAnyMatches) {
2253 Matcher<int> m;
2254 m = AnyOf(Le(1), Ge(3));
2255 EXPECT_TRUE(m.Matches(1));
2256 EXPECT_TRUE(m.Matches(4));
2257 EXPECT_FALSE(m.Matches(2));
2258
2259 m = AnyOf(Lt(0), Eq(1), Eq(2));
2260 EXPECT_TRUE(m.Matches(-1));
2261 EXPECT_TRUE(m.Matches(1));
2262 EXPECT_TRUE(m.Matches(2));
2263 EXPECT_FALSE(m.Matches(0));
2264
2265 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2266 EXPECT_TRUE(m.Matches(-1));
2267 EXPECT_TRUE(m.Matches(1));
2268 EXPECT_TRUE(m.Matches(2));
2269 EXPECT_TRUE(m.Matches(3));
2270 EXPECT_FALSE(m.Matches(0));
2271
2272 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2273 EXPECT_TRUE(m.Matches(0));
2274 EXPECT_TRUE(m.Matches(11));
2275 EXPECT_TRUE(m.Matches(3));
2276 EXPECT_FALSE(m.Matches(2));
zhanyong.wan02c15052010-06-09 19:21:30 +00002277
2278 // The following tests for varying number of sub-matchers. Due to the way
2279 // the sub-matchers are handled it is enough to test every sub-matcher once
2280 // with sub-matchers using the same matcher type. Varying matcher types are
2281 // checked for above.
2282 AnyOfMatches(2, AnyOf(1, 2));
2283 AnyOfMatches(3, AnyOf(1, 2, 3));
2284 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2285 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2286 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2287 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2288 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2289 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2290 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
shiqiane35fdd92008-12-10 05:08:54 +00002291}
2292
zhanyong.wan616180e2013-06-18 18:49:51 +00002293#if GTEST_LANG_CXX11
2294// Tests the variadic version of the AnyOfMatcher.
2295TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2296 // Also make sure AnyOf is defined in the right namespace and does not depend
2297 // on ADL.
2298 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2299
2300 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))"));
2301 AnyOfMatches(11, m);
2302 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2303 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2304 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2305 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2306 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2307}
2308
2309#endif // GTEST_LANG_CXX11
2310
shiqiane35fdd92008-12-10 05:08:54 +00002311// Tests that AnyOf(m1, ..., mn) describes itself properly.
2312TEST(AnyOfTest, CanDescribeSelf) {
2313 Matcher<int> m;
2314 m = AnyOf(Le(1), Ge(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002315 EXPECT_EQ("(is <= 1) or (is >= 3)",
shiqiane35fdd92008-12-10 05:08:54 +00002316 Describe(m));
2317
2318 m = AnyOf(Lt(0), Eq(1), Eq(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002319 EXPECT_EQ("(is < 0) or "
shiqiane35fdd92008-12-10 05:08:54 +00002320 "((is equal to 1) or (is equal to 2))",
2321 Describe(m));
2322
2323 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002324 EXPECT_EQ("((is < 0) or "
2325 "(is equal to 1)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002326 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002327 "(is equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002328 Describe(m));
2329
2330 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002331 EXPECT_EQ("((is <= 0) or "
2332 "(is > 10)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002333 "((is equal to 3) or "
2334 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002335 "(is equal to 7)))",
shiqiane35fdd92008-12-10 05:08:54 +00002336 Describe(m));
2337}
2338
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002339// Tests that AnyOf(m1, ..., mn) describes its negation properly.
2340TEST(AnyOfTest, CanDescribeNegation) {
2341 Matcher<int> m;
2342 m = AnyOf(Le(1), Ge(3));
2343 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2344 DescribeNegation(m));
2345
2346 m = AnyOf(Lt(0), Eq(1), Eq(2));
2347 EXPECT_EQ("(isn't < 0) and "
2348 "((isn't equal to 1) and (isn't equal to 2))",
2349 DescribeNegation(m));
2350
2351 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002352 EXPECT_EQ("((isn't < 0) and "
2353 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002354 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002355 "(isn't equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002356 DescribeNegation(m));
2357
2358 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002359 EXPECT_EQ("((isn't <= 0) and "
2360 "(isn't > 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002361 "((isn't equal to 3) and "
2362 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002363 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002364 DescribeNegation(m));
2365}
2366
zhanyong.wan18490652009-05-11 18:54:08 +00002367// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2368TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2369 // greater_than_5 and less_than_10 are monomorphic matchers.
2370 Matcher<int> greater_than_5 = Gt(5);
2371 Matcher<int> less_than_10 = Lt(10);
2372
2373 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2374 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2375 Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2376
2377 // Tests that EitherOf works when composing itself.
2378 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2379 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2380}
2381
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002382TEST(AnyOfTest, ExplainsResult) {
2383 Matcher<int> m;
2384
2385 // Failed match. Both matchers need to explain. The second
2386 // matcher doesn't give an explanation, so only the first matcher's
2387 // explanation is printed.
2388 m = AnyOf(GreaterThan(10), Lt(0));
2389 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2390
2391 // Failed match. Both matchers need to explain.
2392 m = AnyOf(GreaterThan(10), GreaterThan(20));
2393 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2394 Explain(m, 5));
2395
2396 // Failed match. All matchers need to explain. The second
2397 // matcher doesn't given an explanation.
2398 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2399 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2400 Explain(m, 5));
2401
2402 // Failed match. All matchers need to explain.
2403 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2404 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2405 "and which is 25 less than 30",
2406 Explain(m, 5));
2407
2408 // Successful match. The first matcher, which succeeded, needs to
2409 // explain.
2410 m = AnyOf(GreaterThan(10), GreaterThan(20));
2411 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2412
2413 // Successful match. The second matcher, which succeeded, needs to
2414 // explain. Since it doesn't given an explanation, nothing is
2415 // printed.
2416 m = AnyOf(GreaterThan(10), Lt(30));
2417 EXPECT_EQ("", Explain(m, 0));
2418
2419 // Successful match. The second matcher, which succeeded, needs to
2420 // explain.
2421 m = AnyOf(GreaterThan(30), GreaterThan(20));
2422 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2423}
2424
shiqiane35fdd92008-12-10 05:08:54 +00002425// The following predicate function and predicate functor are for
2426// testing the Truly(predicate) matcher.
2427
2428// Returns non-zero if the input is positive. Note that the return
2429// type of this function is not bool. It's OK as Truly() accepts any
2430// unary function or functor whose return type can be implicitly
2431// converted to bool.
2432int IsPositive(double x) {
2433 return x > 0 ? 1 : 0;
2434}
2435
2436// This functor returns true if the input is greater than the given
2437// number.
2438class IsGreaterThan {
2439 public:
2440 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2441
2442 bool operator()(int n) const { return n > threshold_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002443
shiqiane35fdd92008-12-10 05:08:54 +00002444 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002445 int threshold_;
shiqiane35fdd92008-12-10 05:08:54 +00002446};
2447
2448// For testing Truly().
2449const int foo = 0;
2450
2451// This predicate returns true iff the argument references foo and has
2452// a zero value.
2453bool ReferencesFooAndIsZero(const int& n) {
2454 return (&n == &foo) && (n == 0);
2455}
2456
2457// Tests that Truly(predicate) matches what satisfies the given
2458// predicate.
2459TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2460 Matcher<double> m = Truly(IsPositive);
2461 EXPECT_TRUE(m.Matches(2.0));
2462 EXPECT_FALSE(m.Matches(-1.5));
2463}
2464
2465// Tests that Truly(predicate_functor) works too.
2466TEST(TrulyTest, CanBeUsedWithFunctor) {
2467 Matcher<int> m = Truly(IsGreaterThan(5));
2468 EXPECT_TRUE(m.Matches(6));
2469 EXPECT_FALSE(m.Matches(4));
2470}
2471
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00002472// A class that can be implicitly converted to bool.
2473class ConvertibleToBool {
2474 public:
2475 explicit ConvertibleToBool(int number) : number_(number) {}
2476 operator bool() const { return number_ != 0; }
2477
2478 private:
2479 int number_;
2480};
2481
2482ConvertibleToBool IsNotZero(int number) {
2483 return ConvertibleToBool(number);
2484}
2485
2486// Tests that the predicate used in Truly() may return a class that's
2487// implicitly convertible to bool, even when the class has no
2488// operator!().
2489TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2490 Matcher<int> m = Truly(IsNotZero);
2491 EXPECT_TRUE(m.Matches(1));
2492 EXPECT_FALSE(m.Matches(0));
2493}
2494
shiqiane35fdd92008-12-10 05:08:54 +00002495// Tests that Truly(predicate) can describe itself properly.
2496TEST(TrulyTest, CanDescribeSelf) {
2497 Matcher<double> m = Truly(IsPositive);
2498 EXPECT_EQ("satisfies the given predicate",
2499 Describe(m));
2500}
2501
2502// Tests that Truly(predicate) works when the matcher takes its
2503// argument by reference.
2504TEST(TrulyTest, WorksForByRefArguments) {
2505 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2506 EXPECT_TRUE(m.Matches(foo));
2507 int n = 0;
2508 EXPECT_FALSE(m.Matches(n));
2509}
2510
2511// Tests that Matches(m) is a predicate satisfied by whatever that
2512// matches matcher m.
2513TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2514 EXPECT_TRUE(Matches(Ge(0))(1));
2515 EXPECT_FALSE(Matches(Eq('a'))('b'));
2516}
2517
2518// Tests that Matches(m) works when the matcher takes its argument by
2519// reference.
2520TEST(MatchesTest, WorksOnByRefArguments) {
2521 int m = 0, n = 0;
2522 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2523 EXPECT_FALSE(Matches(Ref(m))(n));
2524}
2525
2526// Tests that a Matcher on non-reference type can be used in
2527// Matches().
2528TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
2529 Matcher<int> eq5 = Eq(5);
2530 EXPECT_TRUE(Matches(eq5)(5));
2531 EXPECT_FALSE(Matches(eq5)(2));
2532}
2533
zhanyong.wanb8243162009-06-04 05:48:20 +00002534// Tests Value(value, matcher). Since Value() is a simple wrapper for
2535// Matches(), which has been tested already, we don't spend a lot of
2536// effort on testing Value().
2537TEST(ValueTest, WorksWithPolymorphicMatcher) {
2538 EXPECT_TRUE(Value("hi", StartsWith("h")));
2539 EXPECT_FALSE(Value(5, Gt(10)));
2540}
2541
2542TEST(ValueTest, WorksWithMonomorphicMatcher) {
2543 const Matcher<int> is_zero = Eq(0);
2544 EXPECT_TRUE(Value(0, is_zero));
2545 EXPECT_FALSE(Value('a', is_zero));
2546
2547 int n = 0;
2548 const Matcher<const int&> ref_n = Ref(n);
2549 EXPECT_TRUE(Value(n, ref_n));
2550 EXPECT_FALSE(Value(1, ref_n));
2551}
2552
zhanyong.wana862f1d2010-03-15 21:23:04 +00002553TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002554 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002555 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002556 EXPECT_EQ("% 2 == 0", listener1.str());
2557
2558 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002559 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002560 EXPECT_EQ("", listener2.str());
2561}
2562
zhanyong.wana862f1d2010-03-15 21:23:04 +00002563TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002564 const Matcher<int> is_even = PolymorphicIsEven();
2565 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002566 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002567 EXPECT_EQ("% 2 == 0", listener1.str());
2568
2569 const Matcher<const double&> is_zero = Eq(0);
2570 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002571 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002572 EXPECT_EQ("", listener2.str());
2573}
2574
zhanyong.wana862f1d2010-03-15 21:23:04 +00002575MATCHER_P(Really, inner_matcher, "") {
2576 return ExplainMatchResult(inner_matcher, arg, result_listener);
2577}
2578
2579TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
2580 EXPECT_THAT(0, Really(Eq(0)));
2581}
2582
zhanyong.wanbf550852009-06-09 06:09:53 +00002583TEST(AllArgsTest, WorksForTuple) {
2584 EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
2585 EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
2586}
2587
2588TEST(AllArgsTest, WorksForNonTuple) {
2589 EXPECT_THAT(42, AllArgs(Gt(0)));
2590 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
2591}
2592
2593class AllArgsHelper {
2594 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002595 AllArgsHelper() {}
2596
zhanyong.wanbf550852009-06-09 06:09:53 +00002597 MOCK_METHOD2(Helper, int(char x, int y));
zhanyong.wan32de5f52009-12-23 00:13:23 +00002598
2599 private:
2600 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
zhanyong.wanbf550852009-06-09 06:09:53 +00002601};
2602
2603TEST(AllArgsTest, WorksInWithClause) {
2604 AllArgsHelper helper;
2605 ON_CALL(helper, Helper(_, _))
2606 .With(AllArgs(Lt()))
2607 .WillByDefault(Return(1));
2608 EXPECT_CALL(helper, Helper(_, _));
2609 EXPECT_CALL(helper, Helper(_, _))
2610 .With(AllArgs(Gt()))
2611 .WillOnce(Return(2));
2612
2613 EXPECT_EQ(1, helper.Helper('\1', 2));
2614 EXPECT_EQ(2, helper.Helper('a', 1));
2615}
2616
shiqiane35fdd92008-12-10 05:08:54 +00002617// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2618// matches the matcher.
2619TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
2620 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
2621 ASSERT_THAT("Foo", EndsWith("oo"));
2622 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
2623 EXPECT_THAT("Hello", StartsWith("Hell"));
2624}
2625
2626// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2627// doesn't match the matcher.
2628TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
2629 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
2630 // which cannot reference auto variables.
zhanyong.wan736baa82010-09-27 17:44:16 +00002631 static unsigned short n; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00002632 n = 5;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002633
2634 // VC++ prior to version 8.0 SP1 has a bug where it will not see any
2635 // functions declared in the namespace scope from within nested classes.
2636 // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
2637 // namespace-level functions invoked inside them need to be explicitly
2638 // resolved.
2639 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
shiqiane35fdd92008-12-10 05:08:54 +00002640 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002641 "Expected: is > 10\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002642 " Actual: 5" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002643 n = 0;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002644 EXPECT_NONFATAL_FAILURE(
2645 EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
2646 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002647 "Expected: (is <= 7) and (is >= 5)\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002648 " Actual: 0" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002649}
2650
2651// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
2652// has a reference type.
2653TEST(MatcherAssertionTest, WorksForByRefArguments) {
2654 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
2655 // reference auto variables.
2656 static int n;
2657 n = 0;
2658 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002659 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
shiqiane35fdd92008-12-10 05:08:54 +00002660 "Value of: n\n"
2661 "Expected: does not reference the variable @");
2662 // Tests the "Actual" part.
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002663 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
zhanyong.wan736baa82010-09-27 17:44:16 +00002664 "Actual: 0" + OfType("int") + ", which is located @");
shiqiane35fdd92008-12-10 05:08:54 +00002665}
2666
zhanyong.wan95b12332009-09-25 18:55:50 +00002667#if !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002668// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
2669// monomorphic.
zhanyong.wan95b12332009-09-25 18:55:50 +00002670
2671// ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
2672// Symbian compiler: it tries to compile
2673// template<T, U> class MatcherCastImpl { ...
zhanyong.wandb22c222010-01-28 21:52:29 +00002674// virtual bool MatchAndExplain(T x, ...) const {
2675// return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
zhanyong.wan95b12332009-09-25 18:55:50 +00002676// with U == string and T == const char*
2677// With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
2678// the compiler silently crashes with no output.
2679// If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
2680// the code compiles but the converted string is bogus.
shiqiane35fdd92008-12-10 05:08:54 +00002681TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
2682 Matcher<const char*> starts_with_he = StartsWith("he");
2683 ASSERT_THAT("hello", starts_with_he);
2684
2685 Matcher<const string&> ends_with_ok = EndsWith("ok");
2686 ASSERT_THAT("book", ends_with_ok);
zhanyong.wan736baa82010-09-27 17:44:16 +00002687 const string bad = "bad";
2688 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
2689 "Value of: bad\n"
2690 "Expected: ends with \"ok\"\n"
2691 " Actual: \"bad\"");
shiqiane35fdd92008-12-10 05:08:54 +00002692 Matcher<int> is_greater_than_5 = Gt(5);
2693 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
2694 "Value of: 5\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002695 "Expected: is > 5\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002696 " Actual: 5" + OfType("int"));
shiqiane35fdd92008-12-10 05:08:54 +00002697}
zhanyong.wan95b12332009-09-25 18:55:50 +00002698#endif // !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002699
2700// Tests floating-point matchers.
2701template <typename RawType>
2702class FloatingPointTest : public testing::Test {
2703 protected:
zhanyong.wan35877b72013-09-18 17:51:08 +00002704 typedef testing::internal::FloatingPoint<RawType> Floating;
shiqiane35fdd92008-12-10 05:08:54 +00002705 typedef typename Floating::Bits Bits;
2706
zhanyong.wan35877b72013-09-18 17:51:08 +00002707 FloatingPointTest()
2708 : max_ulps_(Floating::kMaxUlps),
2709 zero_bits_(Floating(0).bits()),
2710 one_bits_(Floating(1).bits()),
2711 infinity_bits_(Floating(Floating::Infinity()).bits()),
Mark Mentovai4a8e5442015-11-12 10:01:06 -05002712 close_to_positive_zero_(AsBits(zero_bits_ + max_ulps_/2)),
2713 close_to_negative_zero_(AsBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
2714 further_from_negative_zero_(-AsBits(
Mark Mentovaicfe466a2015-11-11 18:26:35 -05002715 zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
Mark Mentovai4a8e5442015-11-12 10:01:06 -05002716 close_to_one_(AsBits(one_bits_ + max_ulps_)),
2717 further_from_one_(AsBits(one_bits_ + max_ulps_ + 1)),
zhanyong.wan35877b72013-09-18 17:51:08 +00002718 infinity_(Floating::Infinity()),
Mark Mentovai4a8e5442015-11-12 10:01:06 -05002719 close_to_infinity_(AsBits(infinity_bits_ - max_ulps_)),
2720 further_from_infinity_(AsBits(infinity_bits_ - max_ulps_ - 1)),
zhanyong.wan35877b72013-09-18 17:51:08 +00002721 max_(Floating::Max()),
Mark Mentovai4a8e5442015-11-12 10:01:06 -05002722 nan1_(AsBits(Floating::kExponentBitMask | 1)),
2723 nan2_(AsBits(Floating::kExponentBitMask | 200)) {
shiqiane35fdd92008-12-10 05:08:54 +00002724 }
2725
2726 void TestSize() {
2727 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2728 }
2729
2730 // A battery of tests for FloatingEqMatcher::Matches.
2731 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2732 void TestMatches(
2733 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
2734 Matcher<RawType> m1 = matcher_maker(0.0);
2735 EXPECT_TRUE(m1.Matches(-0.0));
2736 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
2737 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
2738 EXPECT_FALSE(m1.Matches(1.0));
2739
2740 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
2741 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
2742
2743 Matcher<RawType> m3 = matcher_maker(1.0);
2744 EXPECT_TRUE(m3.Matches(close_to_one_));
2745 EXPECT_FALSE(m3.Matches(further_from_one_));
2746
2747 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
2748 EXPECT_FALSE(m3.Matches(0.0));
2749
2750 Matcher<RawType> m4 = matcher_maker(-infinity_);
2751 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
2752
2753 Matcher<RawType> m5 = matcher_maker(infinity_);
2754 EXPECT_TRUE(m5.Matches(close_to_infinity_));
2755
2756 // This is interesting as the representations of infinity_ and nan1_
2757 // are only 1 DLP apart.
2758 EXPECT_FALSE(m5.Matches(nan1_));
2759
2760 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2761 // some cases.
2762 Matcher<const RawType&> m6 = matcher_maker(0.0);
2763 EXPECT_TRUE(m6.Matches(-0.0));
2764 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
2765 EXPECT_FALSE(m6.Matches(1.0));
2766
2767 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2768 // cases.
2769 Matcher<RawType&> m7 = matcher_maker(0.0);
2770 RawType x = 0.0;
2771 EXPECT_TRUE(m7.Matches(x));
2772 x = 0.01f;
2773 EXPECT_FALSE(m7.Matches(x));
2774 }
2775
2776 // Pre-calculated numbers to be used by the tests.
2777
Mark Mentovaicbce23f2015-11-11 17:44:12 -05002778 const size_t max_ulps_;
shiqiane35fdd92008-12-10 05:08:54 +00002779
zhanyong.wan35877b72013-09-18 17:51:08 +00002780 const Bits zero_bits_; // The bits that represent 0.0.
2781 const Bits one_bits_; // The bits that represent 1.0.
2782 const Bits infinity_bits_; // The bits that represent +infinity.
shiqiane35fdd92008-12-10 05:08:54 +00002783
zhanyong.wan35877b72013-09-18 17:51:08 +00002784 // Some numbers close to 0.0.
2785 const RawType close_to_positive_zero_;
2786 const RawType close_to_negative_zero_;
2787 const RawType further_from_negative_zero_;
shiqiane35fdd92008-12-10 05:08:54 +00002788
zhanyong.wan35877b72013-09-18 17:51:08 +00002789 // Some numbers close to 1.0.
2790 const RawType close_to_one_;
2791 const RawType further_from_one_;
2792
2793 // Some numbers close to +infinity.
2794 const RawType infinity_;
2795 const RawType close_to_infinity_;
2796 const RawType further_from_infinity_;
2797
2798 // Maximum representable value that's not infinity.
2799 const RawType max_;
2800
2801 // Some NaNs.
2802 const RawType nan1_;
2803 const RawType nan2_;
Mark Mentovaicfe466a2015-11-11 18:26:35 -05002804
2805 private:
2806 template <typename T>
Mark Mentovai4a8e5442015-11-12 10:01:06 -05002807 static RawType AsBits(T value) {
Mark Mentovaicfe466a2015-11-11 18:26:35 -05002808 return Floating::ReinterpretBits(static_cast<Bits>(value));
2809 }
shiqiane35fdd92008-12-10 05:08:54 +00002810};
2811
zhanyong.wan616180e2013-06-18 18:49:51 +00002812// Tests floating-point matchers with fixed epsilons.
2813template <typename RawType>
2814class FloatingPointNearTest : public FloatingPointTest<RawType> {
2815 protected:
2816 typedef FloatingPointTest<RawType> ParentType;
2817
2818 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
2819 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2820 void TestNearMatches(
2821 testing::internal::FloatingEqMatcher<RawType>
2822 (*matcher_maker)(RawType, RawType)) {
2823 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
2824 EXPECT_TRUE(m1.Matches(0.0));
2825 EXPECT_TRUE(m1.Matches(-0.0));
2826 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
2827 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
2828 EXPECT_FALSE(m1.Matches(1.0));
2829
2830 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
2831 EXPECT_TRUE(m2.Matches(0.0));
2832 EXPECT_TRUE(m2.Matches(-0.0));
2833 EXPECT_TRUE(m2.Matches(1.0));
2834 EXPECT_TRUE(m2.Matches(-1.0));
2835 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
2836 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
2837
2838 // Check that inf matches inf, regardless of the of the specified max
2839 // absolute error.
2840 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
2841 EXPECT_TRUE(m3.Matches(ParentType::infinity_));
2842 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
2843 EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
2844
2845 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
2846 EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
2847 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
2848 EXPECT_FALSE(m4.Matches(ParentType::infinity_));
2849
2850 // Test various overflow scenarios.
zhanyong.wan35877b72013-09-18 17:51:08 +00002851 Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
2852 EXPECT_TRUE(m5.Matches(ParentType::max_));
2853 EXPECT_FALSE(m5.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002854
zhanyong.wan35877b72013-09-18 17:51:08 +00002855 Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
2856 EXPECT_FALSE(m6.Matches(ParentType::max_));
2857 EXPECT_TRUE(m6.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002858
zhanyong.wan35877b72013-09-18 17:51:08 +00002859 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
2860 EXPECT_TRUE(m7.Matches(ParentType::max_));
2861 EXPECT_FALSE(m7.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002862
zhanyong.wan35877b72013-09-18 17:51:08 +00002863 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
2864 EXPECT_FALSE(m8.Matches(ParentType::max_));
2865 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002866
2867 // The difference between max() and -max() normally overflows to infinity,
2868 // but it should still match if the max_abs_error is also infinity.
2869 Matcher<RawType> m9 = matcher_maker(
zhanyong.wan35877b72013-09-18 17:51:08 +00002870 ParentType::max_, ParentType::infinity_);
2871 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002872
2873 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2874 // some cases.
2875 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
2876 EXPECT_TRUE(m10.Matches(-0.0));
2877 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
2878 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
2879
2880 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2881 // cases.
2882 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
2883 RawType x = 0.0;
2884 EXPECT_TRUE(m11.Matches(x));
2885 x = 1.0f;
2886 EXPECT_TRUE(m11.Matches(x));
2887 x = -1.0f;
2888 EXPECT_TRUE(m11.Matches(x));
2889 x = 1.1f;
2890 EXPECT_FALSE(m11.Matches(x));
2891 x = -1.1f;
2892 EXPECT_FALSE(m11.Matches(x));
2893 }
2894};
2895
shiqiane35fdd92008-12-10 05:08:54 +00002896// Instantiate FloatingPointTest for testing floats.
2897typedef FloatingPointTest<float> FloatTest;
2898
2899TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
2900 TestMatches(&FloatEq);
2901}
2902
2903TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
2904 TestMatches(&NanSensitiveFloatEq);
2905}
2906
2907TEST_F(FloatTest, FloatEqCannotMatchNaN) {
2908 // FloatEq never matches NaN.
2909 Matcher<float> m = FloatEq(nan1_);
2910 EXPECT_FALSE(m.Matches(nan1_));
2911 EXPECT_FALSE(m.Matches(nan2_));
2912 EXPECT_FALSE(m.Matches(1.0));
2913}
2914
2915TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
2916 // NanSensitiveFloatEq will match NaN.
2917 Matcher<float> m = NanSensitiveFloatEq(nan1_);
2918 EXPECT_TRUE(m.Matches(nan1_));
2919 EXPECT_TRUE(m.Matches(nan2_));
2920 EXPECT_FALSE(m.Matches(1.0));
2921}
2922
2923TEST_F(FloatTest, FloatEqCanDescribeSelf) {
2924 Matcher<float> m1 = FloatEq(2.0f);
2925 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002926 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002927
2928 Matcher<float> m2 = FloatEq(0.5f);
2929 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002930 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002931
2932 Matcher<float> m3 = FloatEq(nan1_);
2933 EXPECT_EQ("never matches", Describe(m3));
2934 EXPECT_EQ("is anything", DescribeNegation(m3));
2935}
2936
2937TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
2938 Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
2939 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002940 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002941
2942 Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
2943 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002944 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002945
2946 Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
2947 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002948 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00002949}
2950
zhanyong.wan616180e2013-06-18 18:49:51 +00002951// Instantiate FloatingPointTest for testing floats with a user-specified
2952// max absolute error.
2953typedef FloatingPointNearTest<float> FloatNearTest;
2954
2955TEST_F(FloatNearTest, FloatNearMatches) {
2956 TestNearMatches(&FloatNear);
2957}
2958
2959TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
2960 TestNearMatches(&NanSensitiveFloatNear);
2961}
2962
2963TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
2964 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
2965 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2966 EXPECT_EQ(
2967 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2968
2969 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
2970 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2971 EXPECT_EQ(
2972 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2973
2974 Matcher<float> m3 = FloatNear(nan1_, 0.0);
2975 EXPECT_EQ("never matches", Describe(m3));
2976 EXPECT_EQ("is anything", DescribeNegation(m3));
2977}
2978
2979TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
2980 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
2981 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2982 EXPECT_EQ(
2983 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2984
2985 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
2986 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2987 EXPECT_EQ(
2988 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2989
2990 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
2991 EXPECT_EQ("is NaN", Describe(m3));
2992 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
2993}
2994
2995TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
2996 // FloatNear never matches NaN.
2997 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
2998 EXPECT_FALSE(m.Matches(nan1_));
2999 EXPECT_FALSE(m.Matches(nan2_));
3000 EXPECT_FALSE(m.Matches(1.0));
3001}
3002
3003TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
3004 // NanSensitiveFloatNear will match NaN.
3005 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
3006 EXPECT_TRUE(m.Matches(nan1_));
3007 EXPECT_TRUE(m.Matches(nan2_));
3008 EXPECT_FALSE(m.Matches(1.0));
3009}
3010
shiqiane35fdd92008-12-10 05:08:54 +00003011// Instantiate FloatingPointTest for testing doubles.
3012typedef FloatingPointTest<double> DoubleTest;
3013
3014TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
3015 TestMatches(&DoubleEq);
3016}
3017
3018TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
3019 TestMatches(&NanSensitiveDoubleEq);
3020}
3021
3022TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
3023 // DoubleEq never matches NaN.
3024 Matcher<double> m = DoubleEq(nan1_);
3025 EXPECT_FALSE(m.Matches(nan1_));
3026 EXPECT_FALSE(m.Matches(nan2_));
3027 EXPECT_FALSE(m.Matches(1.0));
3028}
3029
3030TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3031 // NanSensitiveDoubleEq will match NaN.
3032 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
3033 EXPECT_TRUE(m.Matches(nan1_));
3034 EXPECT_TRUE(m.Matches(nan2_));
3035 EXPECT_FALSE(m.Matches(1.0));
3036}
3037
3038TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3039 Matcher<double> m1 = DoubleEq(2.0);
3040 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003041 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003042
3043 Matcher<double> m2 = DoubleEq(0.5);
3044 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003045 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003046
3047 Matcher<double> m3 = DoubleEq(nan1_);
3048 EXPECT_EQ("never matches", Describe(m3));
3049 EXPECT_EQ("is anything", DescribeNegation(m3));
3050}
3051
3052TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3053 Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3054 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003055 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003056
3057 Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3058 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003059 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003060
3061 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3062 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003063 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00003064}
3065
zhanyong.wan616180e2013-06-18 18:49:51 +00003066// Instantiate FloatingPointTest for testing floats with a user-specified
3067// max absolute error.
3068typedef FloatingPointNearTest<double> DoubleNearTest;
3069
3070TEST_F(DoubleNearTest, DoubleNearMatches) {
3071 TestNearMatches(&DoubleNear);
3072}
3073
3074TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3075 TestNearMatches(&NanSensitiveDoubleNear);
3076}
3077
3078TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3079 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3080 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3081 EXPECT_EQ(
3082 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3083
3084 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3085 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3086 EXPECT_EQ(
3087 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3088
3089 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3090 EXPECT_EQ("never matches", Describe(m3));
3091 EXPECT_EQ("is anything", DescribeNegation(m3));
3092}
3093
kosak6b817802015-01-08 02:38:14 +00003094TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
3095 EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
3096 EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
3097 EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
3098
3099 const string explanation = Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
3100 // Different C++ implementations may print floating-point numbers
3101 // slightly differently.
3102 EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC
3103 explanation == "which is 1.2e-010 from 2.1") // MSVC
3104 << " where explanation is \"" << explanation << "\".";
3105}
3106
zhanyong.wan616180e2013-06-18 18:49:51 +00003107TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3108 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3109 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3110 EXPECT_EQ(
3111 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3112
3113 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3114 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3115 EXPECT_EQ(
3116 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3117
3118 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3119 EXPECT_EQ("is NaN", Describe(m3));
3120 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3121}
3122
3123TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3124 // DoubleNear never matches NaN.
3125 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3126 EXPECT_FALSE(m.Matches(nan1_));
3127 EXPECT_FALSE(m.Matches(nan2_));
3128 EXPECT_FALSE(m.Matches(1.0));
3129}
3130
3131TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3132 // NanSensitiveDoubleNear will match NaN.
3133 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3134 EXPECT_TRUE(m.Matches(nan1_));
3135 EXPECT_TRUE(m.Matches(nan2_));
3136 EXPECT_FALSE(m.Matches(1.0));
3137}
3138
shiqiane35fdd92008-12-10 05:08:54 +00003139TEST(PointeeTest, RawPointer) {
3140 const Matcher<int*> m = Pointee(Ge(0));
3141
3142 int n = 1;
3143 EXPECT_TRUE(m.Matches(&n));
3144 n = -1;
3145 EXPECT_FALSE(m.Matches(&n));
3146 EXPECT_FALSE(m.Matches(NULL));
3147}
3148
3149TEST(PointeeTest, RawPointerToConst) {
3150 const Matcher<const double*> m = Pointee(Ge(0));
3151
3152 double x = 1;
3153 EXPECT_TRUE(m.Matches(&x));
3154 x = -1;
3155 EXPECT_FALSE(m.Matches(&x));
3156 EXPECT_FALSE(m.Matches(NULL));
3157}
3158
3159TEST(PointeeTest, ReferenceToConstRawPointer) {
3160 const Matcher<int* const &> m = Pointee(Ge(0));
3161
3162 int n = 1;
3163 EXPECT_TRUE(m.Matches(&n));
3164 n = -1;
3165 EXPECT_FALSE(m.Matches(&n));
3166 EXPECT_FALSE(m.Matches(NULL));
3167}
3168
3169TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3170 const Matcher<double* &> m = Pointee(Ge(0));
3171
3172 double x = 1.0;
3173 double* p = &x;
3174 EXPECT_TRUE(m.Matches(p));
3175 x = -1;
3176 EXPECT_FALSE(m.Matches(p));
3177 p = NULL;
3178 EXPECT_FALSE(m.Matches(p));
3179}
3180
billydonahue1f5fdea2014-05-19 17:54:51 +00003181MATCHER_P(FieldIIs, inner_matcher, "") {
3182 return ExplainMatchResult(inner_matcher, arg.i, result_listener);
3183}
3184
Mark Mentovaic8a10502015-10-12 18:01:43 -04003185#if GTEST_HAS_RTTI
3186
billydonahue1f5fdea2014-05-19 17:54:51 +00003187TEST(WhenDynamicCastToTest, SameType) {
3188 Derived derived;
3189 derived.i = 4;
3190
3191 // Right type. A pointer is passed down.
3192 Base* as_base_ptr = &derived;
3193 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
3194 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
3195 EXPECT_THAT(as_base_ptr,
3196 Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
3197}
3198
3199TEST(WhenDynamicCastToTest, WrongTypes) {
3200 Base base;
3201 Derived derived;
3202 OtherDerived other_derived;
3203
3204 // Wrong types. NULL is passed.
3205 EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3206 EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
3207 Base* as_base_ptr = &derived;
3208 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
3209 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
3210 as_base_ptr = &other_derived;
3211 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3212 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3213}
3214
3215TEST(WhenDynamicCastToTest, AlreadyNull) {
3216 // Already NULL.
3217 Base* as_base_ptr = NULL;
3218 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3219}
3220
3221struct AmbiguousCastTypes {
3222 class VirtualDerived : public virtual Base {};
3223 class DerivedSub1 : public VirtualDerived {};
3224 class DerivedSub2 : public VirtualDerived {};
3225 class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
3226};
3227
3228TEST(WhenDynamicCastToTest, AmbiguousCast) {
3229 AmbiguousCastTypes::DerivedSub1 sub1;
3230 AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
3231 // Multiply derived from Base. dynamic_cast<> returns NULL.
3232 Base* as_base_ptr =
3233 static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
3234 EXPECT_THAT(as_base_ptr,
3235 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
3236 as_base_ptr = &sub1;
3237 EXPECT_THAT(
3238 as_base_ptr,
3239 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
3240}
3241
3242TEST(WhenDynamicCastToTest, Describe) {
3243 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
billydonahue1f5fdea2014-05-19 17:54:51 +00003244 const string prefix =
3245 "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
billydonahue1f5fdea2014-05-19 17:54:51 +00003246 EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
3247 EXPECT_EQ(prefix + "does not point to a value that is anything",
3248 DescribeNegation(matcher));
3249}
3250
3251TEST(WhenDynamicCastToTest, Explain) {
3252 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3253 Base* null = NULL;
3254 EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
3255 Derived derived;
3256 EXPECT_TRUE(matcher.Matches(&derived));
3257 EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
3258
3259 // With references, the matcher itself can fail. Test for that one.
3260 Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
3261 EXPECT_THAT(Explain(ref_matcher, derived),
3262 HasSubstr("which cannot be dynamic_cast"));
3263}
3264
3265TEST(WhenDynamicCastToTest, GoodReference) {
3266 Derived derived;
3267 derived.i = 4;
3268 Base& as_base_ref = derived;
3269 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
3270 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
3271}
3272
3273TEST(WhenDynamicCastToTest, BadReference) {
3274 Derived derived;
3275 Base& as_base_ref = derived;
3276 EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
3277}
3278
Mark Mentovaic8a10502015-10-12 18:01:43 -04003279#endif // GTEST_HAS_RTTI
3280
vladlosevada23472012-08-14 15:38:49 +00003281// Minimal const-propagating pointer.
3282template <typename T>
3283class ConstPropagatingPtr {
3284 public:
3285 typedef T element_type;
3286
3287 ConstPropagatingPtr() : val_() {}
3288 explicit ConstPropagatingPtr(T* t) : val_(t) {}
3289 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3290
3291 T* get() { return val_; }
3292 T& operator*() { return *val_; }
3293 // Most smart pointers return non-const T* and T& from the next methods.
3294 const T* get() const { return val_; }
3295 const T& operator*() const { return *val_; }
3296
3297 private:
3298 T* val_;
3299};
3300
3301TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3302 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3303 int three = 3;
3304 const ConstPropagatingPtr<int> co(&three);
3305 ConstPropagatingPtr<int> o(&three);
3306 EXPECT_TRUE(m.Matches(o));
3307 EXPECT_TRUE(m.Matches(co));
3308 *o = 6;
3309 EXPECT_FALSE(m.Matches(o));
3310 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3311}
3312
shiqiane35fdd92008-12-10 05:08:54 +00003313TEST(PointeeTest, NeverMatchesNull) {
3314 const Matcher<const char*> m = Pointee(_);
3315 EXPECT_FALSE(m.Matches(NULL));
3316}
3317
3318// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3319TEST(PointeeTest, MatchesAgainstAValue) {
3320 const Matcher<int*> m = Pointee(5);
3321
3322 int n = 5;
3323 EXPECT_TRUE(m.Matches(&n));
3324 n = -1;
3325 EXPECT_FALSE(m.Matches(&n));
3326 EXPECT_FALSE(m.Matches(NULL));
3327}
3328
3329TEST(PointeeTest, CanDescribeSelf) {
3330 const Matcher<int*> m = Pointee(Gt(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003331 EXPECT_EQ("points to a value that is > 3", Describe(m));
3332 EXPECT_EQ("does not point to a value that is > 3",
shiqiane35fdd92008-12-10 05:08:54 +00003333 DescribeNegation(m));
3334}
3335
shiqiane35fdd92008-12-10 05:08:54 +00003336TEST(PointeeTest, CanExplainMatchResult) {
3337 const Matcher<const string*> m = Pointee(StartsWith("Hi"));
3338
3339 EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL)));
3340
zhanyong.wan736baa82010-09-27 17:44:16 +00003341 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
3342 long n = 3; // NOLINT
3343 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003344 Explain(m2, &n));
3345}
3346
3347TEST(PointeeTest, AlwaysExplainsPointee) {
3348 const Matcher<int*> m = Pointee(0);
3349 int n = 42;
zhanyong.wan736baa82010-09-27 17:44:16 +00003350 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
shiqiane35fdd92008-12-10 05:08:54 +00003351}
3352
3353// An uncopyable class.
3354class Uncopyable {
3355 public:
billydonahue1f5fdea2014-05-19 17:54:51 +00003356 Uncopyable() : value_(-1) {}
zhanyong.wan32de5f52009-12-23 00:13:23 +00003357 explicit Uncopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003358
3359 int value() const { return value_; }
billydonahue1f5fdea2014-05-19 17:54:51 +00003360 void set_value(int i) { value_ = i; }
3361
shiqiane35fdd92008-12-10 05:08:54 +00003362 private:
billydonahue1f5fdea2014-05-19 17:54:51 +00003363 int value_;
shiqiane35fdd92008-12-10 05:08:54 +00003364 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3365};
3366
3367// Returns true iff x.value() is positive.
3368bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3369
billydonahue1f5fdea2014-05-19 17:54:51 +00003370MATCHER_P(UncopyableIs, inner_matcher, "") {
3371 return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
3372}
3373
shiqiane35fdd92008-12-10 05:08:54 +00003374// A user-defined struct for testing Field().
3375struct AStruct {
3376 AStruct() : x(0), y(1.0), z(5), p(NULL) {}
3377 AStruct(const AStruct& rhs)
3378 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3379
3380 int x; // A non-const field.
3381 const double y; // A const field.
3382 Uncopyable z; // An uncopyable field.
3383 const char* p; // A pointer field.
zhanyong.wan32de5f52009-12-23 00:13:23 +00003384
3385 private:
3386 GTEST_DISALLOW_ASSIGN_(AStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003387};
3388
3389// A derived struct for testing Field().
3390struct DerivedStruct : public AStruct {
3391 char ch;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003392
3393 private:
3394 GTEST_DISALLOW_ASSIGN_(DerivedStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003395};
3396
3397// Tests that Field(&Foo::field, ...) works when field is non-const.
3398TEST(FieldTest, WorksForNonConstField) {
3399 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
3400
3401 AStruct a;
3402 EXPECT_TRUE(m.Matches(a));
3403 a.x = -1;
3404 EXPECT_FALSE(m.Matches(a));
3405}
3406
3407// Tests that Field(&Foo::field, ...) works when field is const.
3408TEST(FieldTest, WorksForConstField) {
3409 AStruct a;
3410
3411 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
3412 EXPECT_TRUE(m.Matches(a));
3413 m = Field(&AStruct::y, Le(0.0));
3414 EXPECT_FALSE(m.Matches(a));
3415}
3416
3417// Tests that Field(&Foo::field, ...) works when field is not copyable.
3418TEST(FieldTest, WorksForUncopyableField) {
3419 AStruct a;
3420
3421 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3422 EXPECT_TRUE(m.Matches(a));
3423 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3424 EXPECT_FALSE(m.Matches(a));
3425}
3426
3427// Tests that Field(&Foo::field, ...) works when field is a pointer.
3428TEST(FieldTest, WorksForPointerField) {
3429 // Matching against NULL.
3430 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
3431 AStruct a;
3432 EXPECT_TRUE(m.Matches(a));
3433 a.p = "hi";
3434 EXPECT_FALSE(m.Matches(a));
3435
3436 // Matching a pointer that is not NULL.
3437 m = Field(&AStruct::p, StartsWith("hi"));
3438 a.p = "hill";
3439 EXPECT_TRUE(m.Matches(a));
3440 a.p = "hole";
3441 EXPECT_FALSE(m.Matches(a));
3442}
3443
3444// Tests that Field() works when the object is passed by reference.
3445TEST(FieldTest, WorksForByRefArgument) {
3446 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3447
3448 AStruct a;
3449 EXPECT_TRUE(m.Matches(a));
3450 a.x = -1;
3451 EXPECT_FALSE(m.Matches(a));
3452}
3453
3454// Tests that Field(&Foo::field, ...) works when the argument's type
3455// is a sub-type of Foo.
3456TEST(FieldTest, WorksForArgumentOfSubType) {
3457 // Note that the matcher expects DerivedStruct but we say AStruct
3458 // inside Field().
3459 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
3460
3461 DerivedStruct d;
3462 EXPECT_TRUE(m.Matches(d));
3463 d.x = -1;
3464 EXPECT_FALSE(m.Matches(d));
3465}
3466
3467// Tests that Field(&Foo::field, m) works when field's type and m's
3468// argument type are compatible but not the same.
3469TEST(FieldTest, WorksForCompatibleMatcherType) {
3470 // The field is an int, but the inner matcher expects a signed char.
3471 Matcher<const AStruct&> m = Field(&AStruct::x,
3472 Matcher<signed char>(Ge(0)));
3473
3474 AStruct a;
3475 EXPECT_TRUE(m.Matches(a));
3476 a.x = -1;
3477 EXPECT_FALSE(m.Matches(a));
3478}
3479
3480// Tests that Field() can describe itself.
3481TEST(FieldTest, CanDescribeSelf) {
3482 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3483
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003484 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3485 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003486}
3487
3488// Tests that Field() can explain the match result.
3489TEST(FieldTest, CanExplainMatchResult) {
3490 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3491
3492 AStruct a;
3493 a.x = 1;
zhanyong.wan736baa82010-09-27 17:44:16 +00003494 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003495
3496 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003497 EXPECT_EQ(
3498 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
3499 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003500}
3501
3502// Tests that Field() works when the argument is a pointer to const.
3503TEST(FieldForPointerTest, WorksForPointerToConst) {
3504 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3505
3506 AStruct a;
3507 EXPECT_TRUE(m.Matches(&a));
3508 a.x = -1;
3509 EXPECT_FALSE(m.Matches(&a));
3510}
3511
3512// Tests that Field() works when the argument is a pointer to non-const.
3513TEST(FieldForPointerTest, WorksForPointerToNonConst) {
3514 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
3515
3516 AStruct a;
3517 EXPECT_TRUE(m.Matches(&a));
3518 a.x = -1;
3519 EXPECT_FALSE(m.Matches(&a));
3520}
3521
zhanyong.wan6953a722010-01-13 05:15:07 +00003522// Tests that Field() works when the argument is a reference to a const pointer.
3523TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
3524 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
3525
3526 AStruct a;
3527 EXPECT_TRUE(m.Matches(&a));
3528 a.x = -1;
3529 EXPECT_FALSE(m.Matches(&a));
3530}
3531
shiqiane35fdd92008-12-10 05:08:54 +00003532// Tests that Field() does not match the NULL pointer.
3533TEST(FieldForPointerTest, DoesNotMatchNull) {
3534 Matcher<const AStruct*> m = Field(&AStruct::x, _);
3535 EXPECT_FALSE(m.Matches(NULL));
3536}
3537
3538// Tests that Field(&Foo::field, ...) works when the argument's type
3539// is a sub-type of const Foo*.
3540TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
3541 // Note that the matcher expects DerivedStruct but we say AStruct
3542 // inside Field().
3543 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
3544
3545 DerivedStruct d;
3546 EXPECT_TRUE(m.Matches(&d));
3547 d.x = -1;
3548 EXPECT_FALSE(m.Matches(&d));
3549}
3550
3551// Tests that Field() can describe itself when used to match a pointer.
3552TEST(FieldForPointerTest, CanDescribeSelf) {
3553 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3554
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003555 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3556 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003557}
3558
3559// Tests that Field() can explain the result of matching a pointer.
3560TEST(FieldForPointerTest, CanExplainMatchResult) {
3561 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3562
3563 AStruct a;
3564 a.x = 1;
3565 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003566 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
3567 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003568
3569 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003570 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
3571 ", which is 1 more than 0", Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003572}
3573
3574// A user-defined class for testing Property().
3575class AClass {
3576 public:
3577 AClass() : n_(0) {}
3578
3579 // A getter that returns a non-reference.
3580 int n() const { return n_; }
3581
3582 void set_n(int new_n) { n_ = new_n; }
3583
3584 // A getter that returns a reference to const.
3585 const string& s() const { return s_; }
3586
3587 void set_s(const string& new_s) { s_ = new_s; }
3588
3589 // A getter that returns a reference to non-const.
3590 double& x() const { return x_; }
3591 private:
3592 int n_;
3593 string s_;
3594
3595 static double x_;
3596};
3597
3598double AClass::x_ = 0.0;
3599
3600// A derived class for testing Property().
3601class DerivedClass : public AClass {
kosak6414d802013-12-03 23:19:36 +00003602 public:
3603 int k() const { return k_; }
shiqiane35fdd92008-12-10 05:08:54 +00003604 private:
3605 int k_;
3606};
3607
3608// Tests that Property(&Foo::property, ...) works when property()
3609// returns a non-reference.
3610TEST(PropertyTest, WorksForNonReferenceProperty) {
3611 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3612
3613 AClass a;
3614 a.set_n(1);
3615 EXPECT_TRUE(m.Matches(a));
3616
3617 a.set_n(-1);
3618 EXPECT_FALSE(m.Matches(a));
3619}
3620
3621// Tests that Property(&Foo::property, ...) works when property()
3622// returns a reference to const.
3623TEST(PropertyTest, WorksForReferenceToConstProperty) {
3624 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
3625
3626 AClass a;
3627 a.set_s("hill");
3628 EXPECT_TRUE(m.Matches(a));
3629
3630 a.set_s("hole");
3631 EXPECT_FALSE(m.Matches(a));
3632}
3633
3634// Tests that Property(&Foo::property, ...) works when property()
3635// returns a reference to non-const.
3636TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
3637 double x = 0.0;
3638 AClass a;
3639
3640 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
3641 EXPECT_FALSE(m.Matches(a));
3642
3643 m = Property(&AClass::x, Not(Ref(x)));
3644 EXPECT_TRUE(m.Matches(a));
3645}
3646
3647// Tests that Property(&Foo::property, ...) works when the argument is
3648// passed by value.
3649TEST(PropertyTest, WorksForByValueArgument) {
3650 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
3651
3652 AClass a;
3653 a.set_s("hill");
3654 EXPECT_TRUE(m.Matches(a));
3655
3656 a.set_s("hole");
3657 EXPECT_FALSE(m.Matches(a));
3658}
3659
3660// Tests that Property(&Foo::property, ...) works when the argument's
3661// type is a sub-type of Foo.
3662TEST(PropertyTest, WorksForArgumentOfSubType) {
3663 // The matcher expects a DerivedClass, but inside the Property() we
3664 // say AClass.
3665 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
3666
3667 DerivedClass d;
3668 d.set_n(1);
3669 EXPECT_TRUE(m.Matches(d));
3670
3671 d.set_n(-1);
3672 EXPECT_FALSE(m.Matches(d));
3673}
3674
3675// Tests that Property(&Foo::property, m) works when property()'s type
3676// and m's argument type are compatible but different.
3677TEST(PropertyTest, WorksForCompatibleMatcherType) {
3678 // n() returns an int but the inner matcher expects a signed char.
3679 Matcher<const AClass&> m = Property(&AClass::n,
3680 Matcher<signed char>(Ge(0)));
3681
3682 AClass a;
3683 EXPECT_TRUE(m.Matches(a));
3684 a.set_n(-1);
3685 EXPECT_FALSE(m.Matches(a));
3686}
3687
3688// Tests that Property() can describe itself.
3689TEST(PropertyTest, CanDescribeSelf) {
3690 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3691
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003692 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3693 EXPECT_EQ("is an object whose given property isn't >= 0",
3694 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003695}
3696
3697// Tests that Property() can explain the match result.
3698TEST(PropertyTest, CanExplainMatchResult) {
3699 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3700
3701 AClass a;
3702 a.set_n(1);
zhanyong.wan736baa82010-09-27 17:44:16 +00003703 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003704
3705 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003706 EXPECT_EQ(
3707 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
3708 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003709}
3710
3711// Tests that Property() works when the argument is a pointer to const.
3712TEST(PropertyForPointerTest, WorksForPointerToConst) {
3713 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3714
3715 AClass a;
3716 a.set_n(1);
3717 EXPECT_TRUE(m.Matches(&a));
3718
3719 a.set_n(-1);
3720 EXPECT_FALSE(m.Matches(&a));
3721}
3722
3723// Tests that Property() works when the argument is a pointer to non-const.
3724TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
3725 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
3726
3727 AClass a;
3728 a.set_s("hill");
3729 EXPECT_TRUE(m.Matches(&a));
3730
3731 a.set_s("hole");
3732 EXPECT_FALSE(m.Matches(&a));
3733}
3734
zhanyong.wan6953a722010-01-13 05:15:07 +00003735// Tests that Property() works when the argument is a reference to a
3736// const pointer.
3737TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
3738 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
3739
3740 AClass a;
3741 a.set_s("hill");
3742 EXPECT_TRUE(m.Matches(&a));
3743
3744 a.set_s("hole");
3745 EXPECT_FALSE(m.Matches(&a));
3746}
3747
shiqiane35fdd92008-12-10 05:08:54 +00003748// Tests that Property() does not match the NULL pointer.
3749TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
3750 Matcher<const AClass*> m = Property(&AClass::x, _);
3751 EXPECT_FALSE(m.Matches(NULL));
3752}
3753
3754// Tests that Property(&Foo::property, ...) works when the argument's
3755// type is a sub-type of const Foo*.
3756TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
3757 // The matcher expects a DerivedClass, but inside the Property() we
3758 // say AClass.
3759 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
3760
3761 DerivedClass d;
3762 d.set_n(1);
3763 EXPECT_TRUE(m.Matches(&d));
3764
3765 d.set_n(-1);
3766 EXPECT_FALSE(m.Matches(&d));
3767}
3768
3769// Tests that Property() can describe itself when used to match a pointer.
3770TEST(PropertyForPointerTest, CanDescribeSelf) {
3771 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3772
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003773 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3774 EXPECT_EQ("is an object whose given property isn't >= 0",
3775 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003776}
3777
3778// Tests that Property() can explain the result of matching a pointer.
3779TEST(PropertyForPointerTest, CanExplainMatchResult) {
3780 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3781
3782 AClass a;
3783 a.set_n(1);
3784 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003785 EXPECT_EQ(
3786 "which points to an object whose given property is 1" + OfType("int"),
3787 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003788
3789 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003790 EXPECT_EQ("which points to an object whose given property is 1" +
3791 OfType("int") + ", which is 1 more than 0",
3792 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003793}
3794
3795// Tests ResultOf.
3796
3797// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3798// function pointer.
3799string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; }
3800
3801TEST(ResultOfTest, WorksForFunctionPointers) {
3802 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo")));
3803
3804 EXPECT_TRUE(matcher.Matches(1));
3805 EXPECT_FALSE(matcher.Matches(2));
3806}
3807
3808// Tests that ResultOf() can describe itself.
3809TEST(ResultOfTest, CanDescribeItself) {
3810 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
3811
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003812 EXPECT_EQ("is mapped by the given callable to a value that "
3813 "is equal to \"foo\"", Describe(matcher));
3814 EXPECT_EQ("is mapped by the given callable to a value that "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003815 "isn't equal to \"foo\"", DescribeNegation(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00003816}
3817
3818// Tests that ResultOf() can explain the match result.
3819int IntFunction(int input) { return input == 42 ? 80 : 90; }
3820
3821TEST(ResultOfTest, CanExplainMatchResult) {
3822 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003823 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003824 Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003825
3826 matcher = ResultOf(&IntFunction, GreaterThan(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003827 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
3828 ", which is 5 more than 85", Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003829}
3830
3831// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3832// returns a non-reference.
3833TEST(ResultOfTest, WorksForNonReferenceResults) {
3834 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
3835
3836 EXPECT_TRUE(matcher.Matches(42));
3837 EXPECT_FALSE(matcher.Matches(36));
3838}
3839
3840// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3841// returns a reference to non-const.
zhanyong.wan736baa82010-09-27 17:44:16 +00003842double& DoubleFunction(double& input) { return input; } // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003843
zhanyong.wan736baa82010-09-27 17:44:16 +00003844Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003845 return obj;
3846}
3847
3848TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
3849 double x = 3.14;
3850 double x2 = x;
3851 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
3852
3853 EXPECT_TRUE(matcher.Matches(x));
3854 EXPECT_FALSE(matcher.Matches(x2));
3855
3856 // Test that ResultOf works with uncopyable objects
3857 Uncopyable obj(0);
3858 Uncopyable obj2(0);
3859 Matcher<Uncopyable&> matcher2 =
3860 ResultOf(&RefUncopyableFunction, Ref(obj));
3861
3862 EXPECT_TRUE(matcher2.Matches(obj));
3863 EXPECT_FALSE(matcher2.Matches(obj2));
3864}
3865
3866// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3867// returns a reference to const.
3868const string& StringFunction(const string& input) { return input; }
3869
3870TEST(ResultOfTest, WorksForReferenceToConstResults) {
3871 string s = "foo";
3872 string s2 = s;
3873 Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s));
3874
3875 EXPECT_TRUE(matcher.Matches(s));
3876 EXPECT_FALSE(matcher.Matches(s2));
3877}
3878
3879// Tests that ResultOf(f, m) works when f(x) and m's
3880// argument types are compatible but different.
3881TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
3882 // IntFunction() returns int but the inner matcher expects a signed char.
3883 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
3884
3885 EXPECT_TRUE(matcher.Matches(36));
3886 EXPECT_FALSE(matcher.Matches(42));
3887}
3888
shiqiane35fdd92008-12-10 05:08:54 +00003889// Tests that the program aborts when ResultOf is passed
3890// a NULL function pointer.
3891TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
zhanyong.wan04d6ed82009-09-11 07:01:08 +00003892 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan736baa82010-09-27 17:44:16 +00003893 ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))),
shiqiane35fdd92008-12-10 05:08:54 +00003894 "NULL function pointer is passed into ResultOf\\(\\)\\.");
3895}
shiqiane35fdd92008-12-10 05:08:54 +00003896
3897// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3898// function reference.
3899TEST(ResultOfTest, WorksForFunctionReferences) {
3900 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
3901 EXPECT_TRUE(matcher.Matches(1));
3902 EXPECT_FALSE(matcher.Matches(2));
3903}
3904
3905// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3906// function object.
3907struct Functor : public ::std::unary_function<int, string> {
3908 result_type operator()(argument_type input) const {
3909 return IntToStringFunction(input);
3910 }
3911};
3912
3913TEST(ResultOfTest, WorksForFunctors) {
3914 Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo")));
3915
3916 EXPECT_TRUE(matcher.Matches(1));
3917 EXPECT_FALSE(matcher.Matches(2));
3918}
3919
3920// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3921// functor with more then one operator() defined. ResultOf() must work
3922// for each defined operator().
3923struct PolymorphicFunctor {
3924 typedef int result_type;
3925 int operator()(int n) { return n; }
3926 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
3927};
3928
3929TEST(ResultOfTest, WorksForPolymorphicFunctors) {
3930 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
3931
3932 EXPECT_TRUE(matcher_int.Matches(10));
3933 EXPECT_FALSE(matcher_int.Matches(2));
3934
3935 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
3936
3937 EXPECT_TRUE(matcher_string.Matches("long string"));
3938 EXPECT_FALSE(matcher_string.Matches("shrt"));
3939}
3940
3941const int* ReferencingFunction(const int& n) { return &n; }
3942
3943struct ReferencingFunctor {
3944 typedef const int* result_type;
3945 result_type operator()(const int& n) { return &n; }
3946};
3947
3948TEST(ResultOfTest, WorksForReferencingCallables) {
3949 const int n = 1;
3950 const int n2 = 1;
3951 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
3952 EXPECT_TRUE(matcher2.Matches(n));
3953 EXPECT_FALSE(matcher2.Matches(n2));
3954
3955 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
3956 EXPECT_TRUE(matcher3.Matches(n));
3957 EXPECT_FALSE(matcher3.Matches(n2));
3958}
3959
shiqiane35fdd92008-12-10 05:08:54 +00003960class DivisibleByImpl {
3961 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003962 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
shiqiane35fdd92008-12-10 05:08:54 +00003963
zhanyong.wandb22c222010-01-28 21:52:29 +00003964 // For testing using ExplainMatchResultTo() with polymorphic matchers.
shiqiane35fdd92008-12-10 05:08:54 +00003965 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00003966 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003967 *listener << "which is " << (n % divider_) << " modulo "
zhanyong.wandb22c222010-01-28 21:52:29 +00003968 << divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003969 return (n % divider_) == 0;
3970 }
3971
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003972 void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003973 *os << "is divisible by " << divider_;
3974 }
3975
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003976 void DescribeNegationTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003977 *os << "is not divisible by " << divider_;
3978 }
3979
zhanyong.wan32de5f52009-12-23 00:13:23 +00003980 void set_divider(int a_divider) { divider_ = a_divider; }
shiqiane35fdd92008-12-10 05:08:54 +00003981 int divider() const { return divider_; }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003982
shiqiane35fdd92008-12-10 05:08:54 +00003983 private:
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003984 int divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003985};
3986
shiqiane35fdd92008-12-10 05:08:54 +00003987PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
3988 return MakePolymorphicMatcher(DivisibleByImpl(n));
3989}
3990
3991// Tests that when AllOf() fails, only the first failing matcher is
3992// asked to explain why.
3993TEST(ExplainMatchResultTest, AllOf_False_False) {
3994 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003995 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00003996}
3997
3998// Tests that when AllOf() fails, only the first failing matcher is
3999// asked to explain why.
4000TEST(ExplainMatchResultTest, AllOf_False_True) {
4001 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004002 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
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_True_False) {
4008 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004009 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00004010}
4011
4012// Tests that when AllOf() succeeds, all matchers are asked to explain
4013// why.
4014TEST(ExplainMatchResultTest, AllOf_True_True) {
4015 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004016 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00004017}
4018
4019TEST(ExplainMatchResultTest, AllOf_True_True_2) {
4020 const Matcher<int> m = AllOf(Ge(2), Le(3));
4021 EXPECT_EQ("", Explain(m, 2));
4022}
4023
4024TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
4025 const Matcher<int> m = GreaterThan(5);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00004026 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00004027}
4028
4029// The following two tests verify that values without a public copy
4030// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
4031// with the help of ByRef().
4032
4033class NotCopyable {
4034 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00004035 explicit NotCopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00004036
4037 int value() const { return value_; }
4038
4039 bool operator==(const NotCopyable& rhs) const {
4040 return value() == rhs.value();
4041 }
4042
4043 bool operator>=(const NotCopyable& rhs) const {
4044 return value() >= rhs.value();
4045 }
4046 private:
4047 int value_;
4048
4049 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
4050};
4051
4052TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
4053 const NotCopyable const_value1(1);
4054 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
4055
4056 const NotCopyable n1(1), n2(2);
4057 EXPECT_TRUE(m.Matches(n1));
4058 EXPECT_FALSE(m.Matches(n2));
4059}
4060
4061TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
4062 NotCopyable value2(2);
4063 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
4064
4065 NotCopyable n1(1), n2(2);
4066 EXPECT_FALSE(m.Matches(n1));
4067 EXPECT_TRUE(m.Matches(n2));
4068}
4069
zhanyong.wan320814a2013-03-01 00:20:30 +00004070TEST(IsEmptyTest, ImplementsIsEmpty) {
4071 vector<int> container;
4072 EXPECT_THAT(container, IsEmpty());
4073 container.push_back(0);
4074 EXPECT_THAT(container, Not(IsEmpty()));
4075 container.push_back(1);
4076 EXPECT_THAT(container, Not(IsEmpty()));
4077}
4078
4079TEST(IsEmptyTest, WorksWithString) {
4080 string text;
4081 EXPECT_THAT(text, IsEmpty());
4082 text = "foo";
4083 EXPECT_THAT(text, Not(IsEmpty()));
4084 text = string("\0", 1);
4085 EXPECT_THAT(text, Not(IsEmpty()));
4086}
4087
4088TEST(IsEmptyTest, CanDescribeSelf) {
4089 Matcher<vector<int> > m = IsEmpty();
4090 EXPECT_EQ("is empty", Describe(m));
4091 EXPECT_EQ("isn't empty", DescribeNegation(m));
4092}
4093
4094TEST(IsEmptyTest, ExplainsResult) {
4095 Matcher<vector<int> > m = IsEmpty();
4096 vector<int> container;
4097 EXPECT_EQ("", Explain(m, container));
4098 container.push_back(0);
4099 EXPECT_EQ("whose size is 1", Explain(m, container));
4100}
4101
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004102TEST(SizeIsTest, ImplementsSizeIs) {
4103 vector<int> container;
4104 EXPECT_THAT(container, SizeIs(0));
4105 EXPECT_THAT(container, Not(SizeIs(1)));
4106 container.push_back(0);
4107 EXPECT_THAT(container, Not(SizeIs(0)));
4108 EXPECT_THAT(container, SizeIs(1));
4109 container.push_back(0);
4110 EXPECT_THAT(container, Not(SizeIs(0)));
4111 EXPECT_THAT(container, SizeIs(2));
4112}
4113
4114TEST(SizeIsTest, WorksWithMap) {
4115 map<string, int> container;
4116 EXPECT_THAT(container, SizeIs(0));
4117 EXPECT_THAT(container, Not(SizeIs(1)));
4118 container.insert(make_pair("foo", 1));
4119 EXPECT_THAT(container, Not(SizeIs(0)));
4120 EXPECT_THAT(container, SizeIs(1));
4121 container.insert(make_pair("bar", 2));
4122 EXPECT_THAT(container, Not(SizeIs(0)));
4123 EXPECT_THAT(container, SizeIs(2));
4124}
4125
4126TEST(SizeIsTest, WorksWithReferences) {
4127 vector<int> container;
4128 Matcher<const vector<int>&> m = SizeIs(1);
4129 EXPECT_THAT(container, Not(m));
4130 container.push_back(0);
4131 EXPECT_THAT(container, m);
4132}
4133
4134TEST(SizeIsTest, CanDescribeSelf) {
4135 Matcher<vector<int> > m = SizeIs(2);
4136 EXPECT_EQ("size is equal to 2", Describe(m));
4137 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
4138}
4139
4140TEST(SizeIsTest, ExplainsResult) {
4141 Matcher<vector<int> > m1 = SizeIs(2);
4142 Matcher<vector<int> > m2 = SizeIs(Lt(2u));
4143 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
4144 Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
4145 vector<int> container;
4146 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
4147 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
4148 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
4149 EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
4150 Explain(m4, container));
4151 container.push_back(0);
4152 container.push_back(0);
4153 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
4154 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
4155 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
4156 EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
4157 Explain(m4, container));
4158}
4159
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004160#if GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004161// Tests ContainerEq with different container types, and
4162// different element types.
4163
4164template <typename T>
zhanyong.wanb8243162009-06-04 05:48:20 +00004165class ContainerEqTest : public testing::Test {};
zhanyong.wan6a896b52009-01-16 01:13:50 +00004166
4167typedef testing::Types<
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004168 set<int>,
4169 vector<size_t>,
4170 multiset<size_t>,
4171 list<int> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004172 ContainerEqTestTypes;
4173
4174TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
4175
4176// Tests that the filled container is equal to itself.
4177TYPED_TEST(ContainerEqTest, EqualsSelf) {
4178 static const int vals[] = {1, 1, 2, 3, 5, 8};
4179 TypeParam my_set(vals, vals + 6);
4180 const Matcher<TypeParam> m = ContainerEq(my_set);
4181 EXPECT_TRUE(m.Matches(my_set));
4182 EXPECT_EQ("", Explain(m, my_set));
4183}
4184
4185// Tests that missing values are reported.
4186TYPED_TEST(ContainerEqTest, ValueMissing) {
4187 static const int vals[] = {1, 1, 2, 3, 5, 8};
4188 static const int test_vals[] = {2, 1, 8, 5};
4189 TypeParam my_set(vals, vals + 6);
4190 TypeParam test_set(test_vals, test_vals + 4);
4191 const Matcher<TypeParam> m = ContainerEq(my_set);
4192 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004193 EXPECT_EQ("which doesn't have these expected elements: 3",
4194 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004195}
4196
4197// Tests that added values are reported.
4198TYPED_TEST(ContainerEqTest, ValueAdded) {
4199 static const int vals[] = {1, 1, 2, 3, 5, 8};
4200 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4201 TypeParam my_set(vals, vals + 6);
4202 TypeParam test_set(test_vals, test_vals + 6);
4203 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4204 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004205 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004206}
4207
4208// Tests that added and missing values are reported together.
4209TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4210 static const int vals[] = {1, 1, 2, 3, 5, 8};
4211 static const int test_vals[] = {1, 2, 3, 8, 46};
4212 TypeParam my_set(vals, vals + 6);
4213 TypeParam test_set(test_vals, test_vals + 5);
4214 const Matcher<TypeParam> m = ContainerEq(my_set);
4215 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004216 EXPECT_EQ("which has these unexpected elements: 46,\n"
4217 "and doesn't have these expected elements: 5",
4218 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004219}
4220
4221// Tests duplicated value -- expect no explanation.
4222TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4223 static const int vals[] = {1, 1, 2, 3, 5, 8};
4224 static const int test_vals[] = {1, 2, 3, 5, 8};
4225 TypeParam my_set(vals, vals + 6);
4226 TypeParam test_set(test_vals, test_vals + 5);
4227 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4228 // Depending on the container, match may be true or false
4229 // But in any case there should be no explanation.
4230 EXPECT_EQ("", Explain(m, test_set));
4231}
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004232#endif // GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004233
4234// Tests that mutliple missing values are reported.
4235// Using just vector here, so order is predicatble.
4236TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4237 static const int vals[] = {1, 1, 2, 3, 5, 8};
4238 static const int test_vals[] = {2, 1, 5};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004239 vector<int> my_set(vals, vals + 6);
4240 vector<int> test_set(test_vals, test_vals + 3);
4241 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004242 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004243 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4244 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004245}
4246
4247// Tests that added values are reported.
4248// Using just vector here, so order is predicatble.
4249TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4250 static const int vals[] = {1, 1, 2, 3, 5, 8};
4251 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004252 list<size_t> my_set(vals, vals + 6);
4253 list<size_t> test_set(test_vals, test_vals + 7);
4254 const Matcher<const list<size_t>&> m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004255 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004256 EXPECT_EQ("which has these unexpected elements: 92, 46",
4257 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004258}
4259
4260// Tests that added and missing values are reported together.
4261TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
4262 static const int vals[] = {1, 1, 2, 3, 5, 8};
4263 static const int test_vals[] = {1, 2, 3, 92, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004264 list<size_t> my_set(vals, vals + 6);
4265 list<size_t> test_set(test_vals, test_vals + 5);
4266 const Matcher<const list<size_t> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004267 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004268 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4269 "and doesn't have these expected elements: 5, 8",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004270 Explain(m, test_set));
4271}
4272
4273// Tests to see that duplicate elements are detected,
4274// but (as above) not reported in the explanation.
4275TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
4276 static const int vals[] = {1, 1, 2, 3, 5, 8};
4277 static const int test_vals[] = {1, 2, 3, 5, 8};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004278 vector<int> my_set(vals, vals + 6);
4279 vector<int> test_set(test_vals, test_vals + 5);
4280 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004281 EXPECT_TRUE(m.Matches(my_set));
4282 EXPECT_FALSE(m.Matches(test_set));
4283 // There is nothing to report when both sets contain all the same values.
4284 EXPECT_EQ("", Explain(m, test_set));
4285}
4286
4287// Tests that ContainerEq works for non-trivial associative containers,
4288// like maps.
4289TEST(ContainerEqExtraTest, WorksForMaps) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004290 map<int, std::string> my_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004291 my_map[0] = "a";
4292 my_map[1] = "b";
4293
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004294 map<int, std::string> test_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004295 test_map[0] = "aa";
4296 test_map[1] = "b";
4297
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004298 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004299 EXPECT_TRUE(m.Matches(my_map));
4300 EXPECT_FALSE(m.Matches(test_map));
4301
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004302 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
4303 "and doesn't have these expected elements: (0, \"a\")",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004304 Explain(m, test_map));
4305}
4306
zhanyong.wanb8243162009-06-04 05:48:20 +00004307TEST(ContainerEqExtraTest, WorksForNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00004308 int a1[] = {1, 2, 3};
4309 int a2[] = {1, 2, 3};
4310 int b[] = {1, 2, 4};
zhanyong.wanb8243162009-06-04 05:48:20 +00004311
4312 EXPECT_THAT(a1, ContainerEq(a2));
4313 EXPECT_THAT(a1, Not(ContainerEq(b)));
4314}
4315
4316TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00004317 const char a1[][3] = {"hi", "lo"};
4318 const char a2[][3] = {"hi", "lo"};
4319 const char b[][3] = {"lo", "hi"};
zhanyong.wanb8243162009-06-04 05:48:20 +00004320
4321 // Tests using ContainerEq() in the first dimension.
4322 EXPECT_THAT(a1, ContainerEq(a2));
4323 EXPECT_THAT(a1, Not(ContainerEq(b)));
4324
4325 // Tests using ContainerEq() in the second dimension.
4326 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
4327 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
4328}
4329
4330TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
kosak2336e9c2014-07-28 22:57:30 +00004331 const int a1[] = {1, 2, 3};
4332 const int a2[] = {1, 2, 3};
4333 const int b[] = {1, 2, 3, 4};
zhanyong.wanb8243162009-06-04 05:48:20 +00004334
zhanyong.wan2661c682009-06-09 05:42:12 +00004335 const int* const p1 = a1;
4336 EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
4337 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004338
kosak2336e9c2014-07-28 22:57:30 +00004339 const int c[] = {1, 3, 2};
zhanyong.wan2661c682009-06-09 05:42:12 +00004340 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004341}
4342
4343TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
4344 std::string a1[][3] = {
kosak2336e9c2014-07-28 22:57:30 +00004345 {"hi", "hello", "ciao"},
4346 {"bye", "see you", "ciao"}
zhanyong.wanb8243162009-06-04 05:48:20 +00004347 };
4348
4349 std::string a2[][3] = {
kosak2336e9c2014-07-28 22:57:30 +00004350 {"hi", "hello", "ciao"},
4351 {"bye", "see you", "ciao"}
zhanyong.wanb8243162009-06-04 05:48:20 +00004352 };
4353
4354 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
4355 EXPECT_THAT(a1, m);
4356
4357 a2[0][0] = "ha";
4358 EXPECT_THAT(a1, m);
4359}
4360
zhanyong.wan898725c2011-09-16 16:45:39 +00004361TEST(WhenSortedByTest, WorksForEmptyContainer) {
4362 const vector<int> numbers;
4363 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
4364 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
4365}
4366
4367TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
4368 vector<unsigned> numbers;
4369 numbers.push_back(3);
4370 numbers.push_back(1);
4371 numbers.push_back(2);
4372 numbers.push_back(2);
4373 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
4374 ElementsAre(3, 2, 2, 1)));
4375 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
4376 ElementsAre(1, 2, 2, 3))));
4377}
4378
4379TEST(WhenSortedByTest, WorksForNonVectorContainer) {
4380 list<string> words;
4381 words.push_back("say");
4382 words.push_back("hello");
4383 words.push_back("world");
4384 EXPECT_THAT(words, WhenSortedBy(less<string>(),
4385 ElementsAre("hello", "say", "world")));
4386 EXPECT_THAT(words, Not(WhenSortedBy(less<string>(),
4387 ElementsAre("say", "hello", "world"))));
4388}
4389
4390TEST(WhenSortedByTest, WorksForNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00004391 const int numbers[] = {1, 3, 2, 4};
4392 const int sorted_numbers[] = {1, 2, 3, 4};
zhanyong.wan898725c2011-09-16 16:45:39 +00004393 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
4394 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
4395 ElementsAreArray(sorted_numbers)));
4396 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
4397}
4398
4399TEST(WhenSortedByTest, CanDescribeSelf) {
4400 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
4401 EXPECT_EQ("(when sorted) has 2 elements where\n"
4402 "element #0 is equal to 1,\n"
4403 "element #1 is equal to 2",
4404 Describe(m));
4405 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
4406 "element #0 isn't equal to 1, or\n"
4407 "element #1 isn't equal to 2",
4408 DescribeNegation(m));
4409}
4410
4411TEST(WhenSortedByTest, ExplainsMatchResult) {
kosak2336e9c2014-07-28 22:57:30 +00004412 const int a[] = {2, 1};
zhanyong.wan898725c2011-09-16 16:45:39 +00004413 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
4414 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
4415 EXPECT_EQ("which is { 1, 2 } when sorted",
4416 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
4417}
4418
4419// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
4420// need to test it as exhaustively as we test the latter.
4421
4422TEST(WhenSortedTest, WorksForEmptyContainer) {
4423 const vector<int> numbers;
4424 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
4425 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
4426}
4427
4428TEST(WhenSortedTest, WorksForNonEmptyContainer) {
4429 list<string> words;
4430 words.push_back("3");
4431 words.push_back("1");
4432 words.push_back("2");
4433 words.push_back("2");
4434 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
4435 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
4436}
4437
zhanyong.wana9a59e02013-03-27 16:14:55 +00004438TEST(WhenSortedTest, WorksForMapTypes) {
4439 map<string, int> word_counts;
4440 word_counts["and"] = 1;
4441 word_counts["the"] = 1;
4442 word_counts["buffalo"] = 2;
4443 EXPECT_THAT(word_counts, WhenSorted(ElementsAre(
4444 Pair("and", 1), Pair("buffalo", 2), Pair("the", 1))));
4445 EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre(
4446 Pair("and", 1), Pair("the", 1), Pair("buffalo", 2)))));
4447}
4448
4449TEST(WhenSortedTest, WorksForMultiMapTypes) {
4450 multimap<int, int> ifib;
4451 ifib.insert(make_pair(8, 6));
4452 ifib.insert(make_pair(2, 3));
4453 ifib.insert(make_pair(1, 1));
4454 ifib.insert(make_pair(3, 4));
4455 ifib.insert(make_pair(1, 2));
4456 ifib.insert(make_pair(5, 5));
4457 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
4458 Pair(1, 2),
4459 Pair(2, 3),
4460 Pair(3, 4),
4461 Pair(5, 5),
4462 Pair(8, 6))));
4463 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
4464 Pair(2, 3),
4465 Pair(1, 1),
4466 Pair(3, 4),
4467 Pair(1, 2),
4468 Pair(5, 5)))));
4469}
4470
4471TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
4472 std::deque<int> d;
4473 d.push_back(2);
4474 d.push_back(1);
4475 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
4476 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
4477}
4478
4479TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
4480 std::deque<int> d;
4481 d.push_back(2);
4482 d.push_back(1);
4483 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
4484 EXPECT_THAT(d, WhenSorted(vector_match));
4485 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
4486 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
4487}
4488
4489// Deliberately bare pseudo-container.
4490// Offers only begin() and end() accessors, yielding InputIterator.
4491template <typename T>
4492class Streamlike {
4493 private:
4494 class ConstIter;
4495 public:
4496 typedef ConstIter const_iterator;
4497 typedef T value_type;
4498
4499 template <typename InIter>
4500 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
4501
4502 const_iterator begin() const {
4503 return const_iterator(this, remainder_.begin());
4504 }
4505 const_iterator end() const {
4506 return const_iterator(this, remainder_.end());
4507 }
4508
4509 private:
4510 class ConstIter : public std::iterator<std::input_iterator_tag,
4511 value_type,
4512 ptrdiff_t,
kosakcd99eb02014-11-17 02:18:28 +00004513 const value_type*,
4514 const value_type&> {
zhanyong.wana9a59e02013-03-27 16:14:55 +00004515 public:
4516 ConstIter(const Streamlike* s,
4517 typename std::list<value_type>::iterator pos)
4518 : s_(s), pos_(pos) {}
4519
4520 const value_type& operator*() const { return *pos_; }
4521 const value_type* operator->() const { return &*pos_; }
4522 ConstIter& operator++() {
4523 s_->remainder_.erase(pos_++);
4524 return *this;
4525 }
4526
4527 // *iter++ is required to work (see std::istreambuf_iterator).
4528 // (void)iter++ is also required to work.
4529 class PostIncrProxy {
4530 public:
4531 explicit PostIncrProxy(const value_type& value) : value_(value) {}
4532 value_type operator*() const { return value_; }
4533 private:
4534 value_type value_;
4535 };
4536 PostIncrProxy operator++(int) {
4537 PostIncrProxy proxy(**this);
4538 ++(*this);
4539 return proxy;
4540 }
4541
4542 friend bool operator==(const ConstIter& a, const ConstIter& b) {
4543 return a.s_ == b.s_ && a.pos_ == b.pos_;
4544 }
4545 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
4546 return !(a == b);
4547 }
4548
4549 private:
4550 const Streamlike* s_;
4551 typename std::list<value_type>::iterator pos_;
4552 };
4553
4554 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
4555 os << "[";
4556 typedef typename std::list<value_type>::const_iterator Iter;
4557 const char* sep = "";
4558 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
4559 os << sep << *it;
4560 sep = ",";
4561 }
4562 os << "]";
4563 return os;
4564 }
4565
4566 mutable std::list<value_type> remainder_; // modified by iteration
4567};
4568
4569TEST(StreamlikeTest, Iteration) {
kosak2336e9c2014-07-28 22:57:30 +00004570 const int a[5] = {2, 1, 4, 5, 3};
zhanyong.wana9a59e02013-03-27 16:14:55 +00004571 Streamlike<int> s(a, a + 5);
4572 Streamlike<int>::const_iterator it = s.begin();
4573 const int* ip = a;
4574 while (it != s.end()) {
4575 SCOPED_TRACE(ip - a);
4576 EXPECT_EQ(*ip++, *it++);
4577 }
4578}
4579
kosak5b9cbbb2014-11-17 00:28:55 +00004580#if GTEST_HAS_STD_FORWARD_LIST_
kosakb6a34882014-03-12 21:06:46 +00004581TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
4582 std::forward_list<int> container;
4583 EXPECT_THAT(container, BeginEndDistanceIs(0));
4584 EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
4585 container.push_front(0);
4586 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4587 EXPECT_THAT(container, BeginEndDistanceIs(1));
4588 container.push_front(0);
4589 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4590 EXPECT_THAT(container, BeginEndDistanceIs(2));
4591}
kosak5b9cbbb2014-11-17 00:28:55 +00004592#endif // GTEST_HAS_STD_FORWARD_LIST_
kosakb6a34882014-03-12 21:06:46 +00004593
4594TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
kosak2336e9c2014-07-28 22:57:30 +00004595 const int a[5] = {1, 2, 3, 4, 5};
kosakb6a34882014-03-12 21:06:46 +00004596 Streamlike<int> s(a, a + 5);
4597 EXPECT_THAT(s, BeginEndDistanceIs(5));
4598}
4599
4600TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
4601 Matcher<vector<int> > m = BeginEndDistanceIs(2);
4602 EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
4603 EXPECT_EQ("distance between begin() and end() isn't equal to 2",
4604 DescribeNegation(m));
4605}
4606
4607TEST(BeginEndDistanceIsTest, ExplainsResult) {
4608 Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
4609 Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
4610 Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
4611 Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
4612 vector<int> container;
4613 EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
4614 Explain(m1, container));
4615 EXPECT_EQ("whose distance between begin() and end() 0 matches",
4616 Explain(m2, container));
4617 EXPECT_EQ("whose distance between begin() and end() 0 matches",
4618 Explain(m3, container));
4619 EXPECT_EQ(
4620 "whose distance between begin() and end() 0 doesn't match, which is 1 "
4621 "less than 1",
4622 Explain(m4, container));
4623 container.push_back(0);
4624 container.push_back(0);
4625 EXPECT_EQ("whose distance between begin() and end() 2 matches",
4626 Explain(m1, container));
4627 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4628 Explain(m2, container));
4629 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4630 Explain(m3, container));
4631 EXPECT_EQ(
4632 "whose distance between begin() and end() 2 matches, which is 1 more "
4633 "than 1",
4634 Explain(m4, container));
4635}
4636
zhanyong.wana9a59e02013-03-27 16:14:55 +00004637TEST(WhenSortedTest, WorksForStreamlike) {
4638 // Streamlike 'container' provides only minimal iterator support.
4639 // Its iterators are tagged with input_iterator_tag.
kosak2336e9c2014-07-28 22:57:30 +00004640 const int a[5] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00004641 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004642 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
4643 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4644}
4645
4646TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
kosak2336e9c2014-07-28 22:57:30 +00004647 const int a[] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00004648 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004649 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
4650 EXPECT_THAT(s, WhenSorted(vector_match));
4651 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4652}
4653
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004654// Tests using ElementsAre() and ElementsAreArray() with stream-like
4655// "containers".
4656
4657TEST(ElemensAreStreamTest, WorksForStreamlike) {
kosak2336e9c2014-07-28 22:57:30 +00004658 const int a[5] = {1, 2, 3, 4, 5};
kosak6414d802013-12-03 23:19:36 +00004659 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004660 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
4661 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
4662}
4663
4664TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
kosak2336e9c2014-07-28 22:57:30 +00004665 const int a[5] = {1, 2, 3, 4, 5};
kosak6414d802013-12-03 23:19:36 +00004666 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004667
4668 vector<int> expected;
4669 expected.push_back(1);
4670 expected.push_back(2);
4671 expected.push_back(3);
4672 expected.push_back(4);
4673 expected.push_back(5);
4674 EXPECT_THAT(s, ElementsAreArray(expected));
4675
4676 expected[3] = 0;
4677 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
4678}
4679
billydonahue1f5fdea2014-05-19 17:54:51 +00004680TEST(ElementsAreTest, WorksWithUncopyable) {
4681 Uncopyable objs[2];
4682 objs[0].set_value(-3);
4683 objs[1].set_value(1);
4684 EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
4685}
4686
kosak06678922014-07-28 20:01:28 +00004687TEST(ElementsAreTest, TakesStlContainer) {
4688 const int actual[] = {3, 1, 2};
4689
4690 ::std::list<int> expected;
4691 expected.push_back(3);
4692 expected.push_back(1);
4693 expected.push_back(2);
4694 EXPECT_THAT(actual, ElementsAreArray(expected));
4695
4696 expected.push_back(4);
4697 EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
4698}
4699
zhanyong.wanfb25d532013-07-28 08:24:00 +00004700// Tests for UnorderedElementsAreArray()
4701
4702TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
kosak2336e9c2014-07-28 22:57:30 +00004703 const int a[] = {0, 1, 2, 3, 4};
kosak6414d802013-12-03 23:19:36 +00004704 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004705 do {
4706 StringMatchResultListener listener;
4707 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
4708 s, &listener)) << listener.str();
4709 } while (std::next_permutation(s.begin(), s.end()));
4710}
4711
4712TEST(UnorderedElementsAreArrayTest, VectorBool) {
kosak2336e9c2014-07-28 22:57:30 +00004713 const bool a[] = {0, 1, 0, 1, 1};
4714 const bool b[] = {1, 0, 1, 1, 0};
kosak6414d802013-12-03 23:19:36 +00004715 std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a));
4716 std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004717 StringMatchResultListener listener;
4718 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
4719 actual, &listener)) << listener.str();
4720}
4721
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004722TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
4723 // Streamlike 'container' provides only minimal iterator support.
4724 // Its iterators are tagged with input_iterator_tag, and it has no
4725 // size() or empty() methods.
kosak2336e9c2014-07-28 22:57:30 +00004726 const int a[5] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00004727 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004728
4729 ::std::vector<int> expected;
4730 expected.push_back(1);
4731 expected.push_back(2);
4732 expected.push_back(3);
4733 expected.push_back(4);
4734 expected.push_back(5);
4735 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
4736
4737 expected.push_back(6);
4738 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
4739}
4740
kosak06678922014-07-28 20:01:28 +00004741TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
4742 const int actual[] = {3, 1, 2};
4743
4744 ::std::list<int> expected;
4745 expected.push_back(1);
4746 expected.push_back(2);
4747 expected.push_back(3);
4748 EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
4749
4750 expected.push_back(4);
4751 EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
4752}
4753
kosak18489fa2013-12-04 23:49:07 +00004754#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004755
4756TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
kosak2336e9c2014-07-28 22:57:30 +00004757 const int a[5] = {2, 1, 4, 5, 3};
4758 EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
4759 EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004760}
4761
4762TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
kosak2336e9c2014-07-28 22:57:30 +00004763 const string a[5] = {"a", "b", "c", "d", "e"};
4764 EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
4765 EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004766}
4767
4768TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
kosak2336e9c2014-07-28 22:57:30 +00004769 const int a[5] = {2, 1, 4, 5, 3};
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004770 EXPECT_THAT(a, UnorderedElementsAreArray(
kosak2336e9c2014-07-28 22:57:30 +00004771 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004772 EXPECT_THAT(a, Not(UnorderedElementsAreArray(
kosak2336e9c2014-07-28 22:57:30 +00004773 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004774}
4775
4776TEST(UnorderedElementsAreArrayTest,
4777 TakesInitializerListOfDifferentTypedMatchers) {
kosak2336e9c2014-07-28 22:57:30 +00004778 const int a[5] = {2, 1, 4, 5, 3};
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004779 // The compiler cannot infer the type of the initializer list if its
4780 // elements have different types. We must explicitly specify the
4781 // unified element type in this case.
4782 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
kosak2336e9c2014-07-28 22:57:30 +00004783 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004784 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
kosak2336e9c2014-07-28 22:57:30 +00004785 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004786}
4787
kosak18489fa2013-12-04 23:49:07 +00004788#endif // GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004789
zhanyong.wanfb25d532013-07-28 08:24:00 +00004790class UnorderedElementsAreTest : public testing::Test {
4791 protected:
4792 typedef std::vector<int> IntVec;
4793};
4794
billydonahue1f5fdea2014-05-19 17:54:51 +00004795TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
4796 Uncopyable objs[2];
4797 objs[0].set_value(-3);
4798 objs[1].set_value(1);
4799 EXPECT_THAT(objs,
4800 UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
4801}
4802
zhanyong.wanfb25d532013-07-28 08:24:00 +00004803TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
kosak2336e9c2014-07-28 22:57:30 +00004804 const int a[] = {1, 2, 3};
kosak6414d802013-12-03 23:19:36 +00004805 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004806 do {
4807 StringMatchResultListener listener;
4808 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4809 s, &listener)) << listener.str();
4810 } while (std::next_permutation(s.begin(), s.end()));
4811}
4812
4813TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
kosak2336e9c2014-07-28 22:57:30 +00004814 const int a[] = {1, 2, 3};
kosak6414d802013-12-03 23:19:36 +00004815 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004816 std::vector<Matcher<int> > mv;
4817 mv.push_back(1);
4818 mv.push_back(2);
4819 mv.push_back(2);
4820 // The element with value '3' matches nothing: fail fast.
4821 StringMatchResultListener listener;
4822 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4823 s, &listener)) << listener.str();
4824}
4825
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004826TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
4827 // Streamlike 'container' provides only minimal iterator support.
4828 // Its iterators are tagged with input_iterator_tag, and it has no
4829 // size() or empty() methods.
kosak2336e9c2014-07-28 22:57:30 +00004830 const int a[5] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00004831 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004832
4833 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
4834 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
4835}
4836
zhanyong.wanfb25d532013-07-28 08:24:00 +00004837// One naive implementation of the matcher runs in O(N!) time, which is too
4838// slow for many real-world inputs. This test shows that our matcher can match
4839// 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
4840// iterations and obviously effectively incomputable.
4841// [ RUN ] UnorderedElementsAreTest.Performance
4842// [ OK ] UnorderedElementsAreTest.Performance (4 ms)
4843TEST_F(UnorderedElementsAreTest, Performance) {
4844 std::vector<int> s;
4845 std::vector<Matcher<int> > mv;
4846 for (int i = 0; i < 100; ++i) {
4847 s.push_back(i);
4848 mv.push_back(_);
4849 }
4850 mv[50] = Eq(0);
4851 StringMatchResultListener listener;
4852 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4853 s, &listener)) << listener.str();
4854}
4855
4856// Another variant of 'Performance' with similar expectations.
4857// [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
4858// [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
4859TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
4860 std::vector<int> s;
4861 std::vector<Matcher<int> > mv;
4862 for (int i = 0; i < 100; ++i) {
4863 s.push_back(i);
4864 if (i & 1) {
4865 mv.push_back(_);
4866 } else {
4867 mv.push_back(i);
4868 }
4869 }
4870 StringMatchResultListener listener;
4871 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4872 s, &listener)) << listener.str();
4873}
4874
4875TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
4876 std::vector<int> v;
4877 v.push_back(4);
4878 StringMatchResultListener listener;
4879 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4880 v, &listener)) << listener.str();
4881 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
4882}
4883
4884TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
4885 std::vector<int> v;
4886 StringMatchResultListener listener;
4887 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4888 v, &listener)) << listener.str();
4889 EXPECT_THAT(listener.str(), Eq(""));
4890}
4891
4892TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
4893 std::vector<int> v;
4894 v.push_back(1);
4895 v.push_back(1);
4896 StringMatchResultListener listener;
4897 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4898 v, &listener)) << listener.str();
4899 EXPECT_THAT(
4900 listener.str(),
4901 Eq("where the following matchers don't match any elements:\n"
4902 "matcher #1: is equal to 2"));
4903}
4904
4905TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
4906 std::vector<int> v;
4907 v.push_back(1);
4908 v.push_back(2);
4909 StringMatchResultListener listener;
4910 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
4911 v, &listener)) << listener.str();
4912 EXPECT_THAT(
4913 listener.str(),
4914 Eq("where the following elements don't match any matchers:\n"
4915 "element #1: 2"));
4916}
4917
4918TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
4919 std::vector<int> v;
4920 v.push_back(2);
4921 v.push_back(3);
4922 StringMatchResultListener listener;
4923 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4924 v, &listener)) << listener.str();
4925 EXPECT_THAT(
4926 listener.str(),
4927 Eq("where"
4928 " the following matchers don't match any elements:\n"
4929 "matcher #0: is equal to 1\n"
4930 "and"
4931 " where"
4932 " the following elements don't match any matchers:\n"
4933 "element #1: 3"));
4934}
4935
4936// Test helper for formatting element, matcher index pairs in expectations.
4937static string EMString(int element, int matcher) {
4938 stringstream ss;
4939 ss << "(element #" << element << ", matcher #" << matcher << ")";
4940 return ss.str();
4941}
4942
4943TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
4944 // A situation where all elements and matchers have a match
4945 // associated with them, but the max matching is not perfect.
4946 std::vector<string> v;
4947 v.push_back("a");
4948 v.push_back("b");
4949 v.push_back("c");
4950 StringMatchResultListener listener;
4951 EXPECT_FALSE(ExplainMatchResult(
4952 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
4953 << listener.str();
4954
4955 string prefix =
4956 "where no permutation of the elements can satisfy all matchers, "
4957 "and the closest match is 2 of 3 matchers with the "
4958 "pairings:\n";
4959
4960 // We have to be a bit loose here, because there are 4 valid max matches.
4961 EXPECT_THAT(
4962 listener.str(),
4963 AnyOf(prefix + "{\n " + EMString(0, 0) +
4964 ",\n " + EMString(1, 2) + "\n}",
4965 prefix + "{\n " + EMString(0, 1) +
4966 ",\n " + EMString(1, 2) + "\n}",
4967 prefix + "{\n " + EMString(0, 0) +
4968 ",\n " + EMString(2, 2) + "\n}",
4969 prefix + "{\n " + EMString(0, 1) +
4970 ",\n " + EMString(2, 2) + "\n}"));
4971}
4972
4973TEST_F(UnorderedElementsAreTest, Describe) {
4974 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
4975 Eq("is empty"));
4976 EXPECT_THAT(
4977 Describe<IntVec>(UnorderedElementsAre(345)),
4978 Eq("has 1 element and that element is equal to 345"));
4979 EXPECT_THAT(
4980 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
4981 Eq("has 3 elements and there exists some permutation "
4982 "of elements such that:\n"
4983 " - element #0 is equal to 111, and\n"
4984 " - element #1 is equal to 222, and\n"
4985 " - element #2 is equal to 333"));
4986}
4987
4988TEST_F(UnorderedElementsAreTest, DescribeNegation) {
4989 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
4990 Eq("isn't empty"));
4991 EXPECT_THAT(
4992 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
4993 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
4994 EXPECT_THAT(
4995 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
4996 Eq("doesn't have 3 elements, or there exists no permutation "
4997 "of elements such that:\n"
4998 " - element #0 is equal to 123, and\n"
4999 " - element #1 is equal to 234, and\n"
5000 " - element #2 is equal to 345"));
5001}
5002
5003namespace {
5004
5005// Used as a check on the more complex max flow method used in the
5006// real testing::internal::FindMaxBipartiteMatching. This method is
5007// compatible but runs in worst-case factorial time, so we only
5008// use it in testing for small problem sizes.
5009template <typename Graph>
5010class BacktrackingMaxBPMState {
5011 public:
5012 // Does not take ownership of 'g'.
5013 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
5014
5015 ElementMatcherPairs Compute() {
5016 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
5017 return best_so_far_;
5018 }
5019 lhs_used_.assign(graph_->LhsSize(), kUnused);
5020 rhs_used_.assign(graph_->RhsSize(), kUnused);
5021 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
5022 matches_.clear();
5023 RecurseInto(irhs);
5024 if (best_so_far_.size() == graph_->RhsSize())
5025 break;
5026 }
5027 return best_so_far_;
5028 }
5029
5030 private:
5031 static const size_t kUnused = static_cast<size_t>(-1);
5032
5033 void PushMatch(size_t lhs, size_t rhs) {
5034 matches_.push_back(ElementMatcherPair(lhs, rhs));
5035 lhs_used_[lhs] = rhs;
5036 rhs_used_[rhs] = lhs;
5037 if (matches_.size() > best_so_far_.size()) {
5038 best_so_far_ = matches_;
5039 }
5040 }
5041
5042 void PopMatch() {
5043 const ElementMatcherPair& back = matches_.back();
5044 lhs_used_[back.first] = kUnused;
5045 rhs_used_[back.second] = kUnused;
5046 matches_.pop_back();
5047 }
5048
5049 bool RecurseInto(size_t irhs) {
5050 if (rhs_used_[irhs] != kUnused) {
5051 return true;
5052 }
5053 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
5054 if (lhs_used_[ilhs] != kUnused) {
5055 continue;
5056 }
5057 if (!graph_->HasEdge(ilhs, irhs)) {
5058 continue;
5059 }
5060 PushMatch(ilhs, irhs);
5061 if (best_so_far_.size() == graph_->RhsSize()) {
5062 return false;
5063 }
5064 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
5065 if (!RecurseInto(mi)) return false;
5066 }
5067 PopMatch();
5068 }
5069 return true;
5070 }
5071
5072 const Graph* graph_; // not owned
5073 std::vector<size_t> lhs_used_;
5074 std::vector<size_t> rhs_used_;
5075 ElementMatcherPairs matches_;
5076 ElementMatcherPairs best_so_far_;
5077};
5078
5079template <typename Graph>
5080const size_t BacktrackingMaxBPMState<Graph>::kUnused;
5081
5082} // namespace
5083
5084// Implement a simple backtracking algorithm to determine if it is possible
5085// to find one element per matcher, without reusing elements.
5086template <typename Graph>
5087ElementMatcherPairs
5088FindBacktrackingMaxBPM(const Graph& g) {
5089 return BacktrackingMaxBPMState<Graph>(&g).Compute();
5090}
5091
5092class BacktrackingBPMTest : public ::testing::Test { };
5093
5094// Tests the MaxBipartiteMatching algorithm with square matrices.
5095// The single int param is the # of nodes on each of the left and right sides.
5096class BipartiteTest : public ::testing::TestWithParam<int> { };
5097
5098// Verify all match graphs up to some moderate number of edges.
5099TEST_P(BipartiteTest, Exhaustive) {
5100 int nodes = GetParam();
5101 MatchMatrix graph(nodes, nodes);
5102 do {
5103 ElementMatcherPairs matches =
5104 internal::FindMaxBipartiteMatching(graph);
5105 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
5106 << "graph: " << graph.DebugString();
5107 // Check that all elements of matches are in the graph.
5108 // Check that elements of first and second are unique.
5109 std::vector<bool> seen_element(graph.LhsSize());
5110 std::vector<bool> seen_matcher(graph.RhsSize());
5111 SCOPED_TRACE(PrintToString(matches));
5112 for (size_t i = 0; i < matches.size(); ++i) {
5113 size_t ilhs = matches[i].first;
5114 size_t irhs = matches[i].second;
5115 EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
5116 EXPECT_FALSE(seen_element[ilhs]);
5117 EXPECT_FALSE(seen_matcher[irhs]);
5118 seen_element[ilhs] = true;
5119 seen_matcher[irhs] = true;
5120 }
5121 } while (graph.NextGraph());
5122}
5123
5124INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest,
5125 ::testing::Range(0, 5));
5126
5127// Parameterized by a pair interpreted as (LhsSize, RhsSize).
5128class BipartiteNonSquareTest
5129 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
5130};
5131
5132TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
5133 // .......
5134 // 0:-----\ :
5135 // 1:---\ | :
5136 // 2:---\ | :
5137 // 3:-\ | | :
5138 // :.......:
5139 // 0 1 2
5140 MatchMatrix g(4, 3);
kosak2336e9c2014-07-28 22:57:30 +00005141 static const int kEdges[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}};
kosak6414d802013-12-03 23:19:36 +00005142 for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00005143 g.SetEdge(kEdges[i][0], kEdges[i][1], true);
5144 }
5145 EXPECT_THAT(FindBacktrackingMaxBPM(g),
5146 ElementsAre(Pair(3, 0),
5147 Pair(AnyOf(1, 2), 1),
5148 Pair(0, 2))) << g.DebugString();
5149}
5150
5151// Verify a few nonsquare matrices.
5152TEST_P(BipartiteNonSquareTest, Exhaustive) {
5153 size_t nlhs = GetParam().first;
5154 size_t nrhs = GetParam().second;
5155 MatchMatrix graph(nlhs, nrhs);
5156 do {
5157 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5158 internal::FindMaxBipartiteMatching(graph).size())
5159 << "graph: " << graph.DebugString()
5160 << "\nbacktracking: "
5161 << PrintToString(FindBacktrackingMaxBPM(graph))
5162 << "\nmax flow: "
5163 << PrintToString(internal::FindMaxBipartiteMatching(graph));
5164 } while (graph.NextGraph());
5165}
5166
5167INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest,
5168 testing::Values(
5169 std::make_pair(1, 2),
5170 std::make_pair(2, 1),
5171 std::make_pair(3, 2),
5172 std::make_pair(2, 3),
5173 std::make_pair(4, 1),
5174 std::make_pair(1, 4),
5175 std::make_pair(4, 3),
5176 std::make_pair(3, 4)));
5177
5178class BipartiteRandomTest
5179 : public ::testing::TestWithParam<std::pair<int, int> > {
5180};
5181
5182// Verifies a large sample of larger graphs.
5183TEST_P(BipartiteRandomTest, LargerNets) {
5184 int nodes = GetParam().first;
5185 int iters = GetParam().second;
5186 MatchMatrix graph(nodes, nodes);
5187
5188 testing::internal::Int32 seed = GTEST_FLAG(random_seed);
5189 if (seed == 0) {
5190 seed = static_cast<testing::internal::Int32>(time(NULL));
5191 }
5192
5193 for (; iters > 0; --iters, ++seed) {
5194 srand(static_cast<int>(seed));
5195 graph.Randomize();
5196 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5197 internal::FindMaxBipartiteMatching(graph).size())
5198 << " graph: " << graph.DebugString()
5199 << "\nTo reproduce the failure, rerun the test with the flag"
5200 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
5201 }
5202}
5203
5204// Test argument is a std::pair<int, int> representing (nodes, iters).
5205INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest,
5206 testing::Values(
5207 std::make_pair(5, 10000),
5208 std::make_pair(6, 5000),
5209 std::make_pair(7, 2000),
5210 std::make_pair(8, 500),
5211 std::make_pair(9, 100)));
5212
zhanyong.wan736baa82010-09-27 17:44:16 +00005213// Tests IsReadableTypeName().
5214
5215TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
5216 EXPECT_TRUE(IsReadableTypeName("int"));
5217 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
5218 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
5219 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
5220}
5221
5222TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
5223 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
5224 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
5225 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
5226}
5227
5228TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
5229 EXPECT_FALSE(
5230 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
5231 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
5232}
5233
5234TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
5235 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
5236}
5237
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005238// Tests JoinAsTuple().
5239
5240TEST(JoinAsTupleTest, JoinsEmptyTuple) {
5241 EXPECT_EQ("", JoinAsTuple(Strings()));
5242}
5243
5244TEST(JoinAsTupleTest, JoinsOneTuple) {
kosak2336e9c2014-07-28 22:57:30 +00005245 const char* fields[] = {"1"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005246 EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
5247}
5248
5249TEST(JoinAsTupleTest, JoinsTwoTuple) {
kosak2336e9c2014-07-28 22:57:30 +00005250 const char* fields[] = {"1", "a"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005251 EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
5252}
5253
5254TEST(JoinAsTupleTest, JoinsTenTuple) {
kosak2336e9c2014-07-28 22:57:30 +00005255 const char* fields[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005256 EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
5257 JoinAsTuple(Strings(fields, fields + 10)));
5258}
5259
5260// Tests FormatMatcherDescription().
5261
5262TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
5263 EXPECT_EQ("is even",
zhanyong.wanb4140802010-06-08 22:53:57 +00005264 FormatMatcherDescription(false, "IsEven", Strings()));
5265 EXPECT_EQ("not (is even)",
5266 FormatMatcherDescription(true, "IsEven", Strings()));
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005267
kosak2336e9c2014-07-28 22:57:30 +00005268 const char* params[] = {"5"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005269 EXPECT_EQ("equals 5",
zhanyong.wanb4140802010-06-08 22:53:57 +00005270 FormatMatcherDescription(false, "Equals",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005271 Strings(params, params + 1)));
5272
kosak2336e9c2014-07-28 22:57:30 +00005273 const char* params2[] = {"5", "8"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005274 EXPECT_EQ("is in range (5, 8)",
zhanyong.wanb4140802010-06-08 22:53:57 +00005275 FormatMatcherDescription(false, "IsInRange",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005276 Strings(params2, params2 + 2)));
5277}
5278
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00005279// Tests PolymorphicMatcher::mutable_impl().
5280TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
5281 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5282 DivisibleByImpl& impl = m.mutable_impl();
5283 EXPECT_EQ(42, impl.divider());
5284
5285 impl.set_divider(0);
5286 EXPECT_EQ(0, m.mutable_impl().divider());
5287}
5288
5289// Tests PolymorphicMatcher::impl().
5290TEST(PolymorphicMatcherTest, CanAccessImpl) {
5291 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5292 const DivisibleByImpl& impl = m.impl();
5293 EXPECT_EQ(42, impl.divider());
5294}
5295
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005296TEST(MatcherTupleTest, ExplainsMatchFailure) {
5297 stringstream ss1;
5298 ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
5299 make_tuple('a', 10), &ss1);
5300 EXPECT_EQ("", ss1.str()); // Successful match.
5301
5302 stringstream ss2;
5303 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5304 make_tuple(2, 'b'), &ss2);
5305 EXPECT_EQ(" Expected arg #0: is > 5\n"
5306 " Actual: 2, which is 3 less than 5\n"
zhanyong.wand60c5f42010-07-21 22:21:07 +00005307 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
5308 " Actual: 'b' (98, 0x62)\n",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005309 ss2.str()); // Failed match where both arguments need explanation.
5310
5311 stringstream ss3;
5312 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5313 make_tuple(2, 'a'), &ss3);
5314 EXPECT_EQ(" Expected arg #0: is > 5\n"
5315 " Actual: 2, which is 3 less than 5\n",
5316 ss3.str()); // Failed match where only one argument needs
5317 // explanation.
5318}
5319
zhanyong.wan33605ba2010-04-22 23:37:47 +00005320// Tests Each().
5321
5322TEST(EachTest, ExplainsMatchResultCorrectly) {
5323 set<int> a; // empty
5324
5325 Matcher<set<int> > m = Each(2);
5326 EXPECT_EQ("", Explain(m, a));
5327
zhanyong.wan736baa82010-09-27 17:44:16 +00005328 Matcher<const int(&)[1]> n = Each(1); // NOLINT
zhanyong.wan33605ba2010-04-22 23:37:47 +00005329
kosak2336e9c2014-07-28 22:57:30 +00005330 const int b[1] = {1};
zhanyong.wan33605ba2010-04-22 23:37:47 +00005331 EXPECT_EQ("", Explain(n, b));
5332
5333 n = Each(3);
5334 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
5335
5336 a.insert(1);
5337 a.insert(2);
5338 a.insert(3);
5339 m = Each(GreaterThan(0));
5340 EXPECT_EQ("", Explain(m, a));
5341
5342 m = Each(GreaterThan(10));
5343 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
5344 Explain(m, a));
5345}
5346
5347TEST(EachTest, DescribesItselfCorrectly) {
5348 Matcher<vector<int> > m = Each(1);
5349 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
5350
5351 Matcher<vector<int> > m2 = Not(m);
5352 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
5353}
5354
5355TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
5356 vector<int> some_vector;
5357 EXPECT_THAT(some_vector, Each(1));
5358 some_vector.push_back(3);
5359 EXPECT_THAT(some_vector, Not(Each(1)));
5360 EXPECT_THAT(some_vector, Each(3));
5361 some_vector.push_back(1);
5362 some_vector.push_back(2);
5363 EXPECT_THAT(some_vector, Not(Each(3)));
5364 EXPECT_THAT(some_vector, Each(Lt(3.5)));
5365
5366 vector<string> another_vector;
5367 another_vector.push_back("fee");
5368 EXPECT_THAT(another_vector, Each(string("fee")));
5369 another_vector.push_back("fie");
5370 another_vector.push_back("foe");
5371 another_vector.push_back("fum");
5372 EXPECT_THAT(another_vector, Not(Each(string("fee"))));
5373}
5374
5375TEST(EachTest, MatchesMapWhenAllElementsMatch) {
5376 map<const char*, int> my_map;
5377 const char* bar = "a string";
5378 my_map[bar] = 2;
5379 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
5380
5381 map<string, int> another_map;
5382 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5383 another_map["fee"] = 1;
5384 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5385 another_map["fie"] = 2;
5386 another_map["foe"] = 3;
5387 another_map["fum"] = 4;
5388 EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1))));
5389 EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1))));
5390 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
5391}
5392
5393TEST(EachTest, AcceptsMatcher) {
kosak2336e9c2014-07-28 22:57:30 +00005394 const int a[] = {1, 2, 3};
zhanyong.wan33605ba2010-04-22 23:37:47 +00005395 EXPECT_THAT(a, Each(Gt(0)));
5396 EXPECT_THAT(a, Not(Each(Gt(1))));
5397}
5398
5399TEST(EachTest, WorksForNativeArrayAsTuple) {
kosak2336e9c2014-07-28 22:57:30 +00005400 const int a[] = {1, 2};
zhanyong.wan33605ba2010-04-22 23:37:47 +00005401 const int* const pointer = a;
5402 EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
5403 EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
5404}
5405
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005406// For testing Pointwise().
5407class IsHalfOfMatcher {
5408 public:
5409 template <typename T1, typename T2>
5410 bool MatchAndExplain(const tuple<T1, T2>& a_pair,
5411 MatchResultListener* listener) const {
5412 if (get<0>(a_pair) == get<1>(a_pair)/2) {
5413 *listener << "where the second is " << get<1>(a_pair);
5414 return true;
5415 } else {
5416 *listener << "where the second/2 is " << get<1>(a_pair)/2;
5417 return false;
5418 }
5419 }
5420
5421 void DescribeTo(ostream* os) const {
5422 *os << "are a pair where the first is half of the second";
5423 }
5424
5425 void DescribeNegationTo(ostream* os) const {
5426 *os << "are a pair where the first isn't half of the second";
5427 }
5428};
5429
5430PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
5431 return MakePolymorphicMatcher(IsHalfOfMatcher());
5432}
5433
5434TEST(PointwiseTest, DescribesSelf) {
5435 vector<int> rhs;
5436 rhs.push_back(1);
5437 rhs.push_back(2);
5438 rhs.push_back(3);
5439 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
5440 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
5441 "in { 1, 2, 3 } are a pair where the first is half of the second",
5442 Describe(m));
5443 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
5444 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
5445 "where the first isn't half of the second",
5446 DescribeNegation(m));
5447}
5448
5449TEST(PointwiseTest, MakesCopyOfRhs) {
5450 list<signed char> rhs;
5451 rhs.push_back(2);
5452 rhs.push_back(4);
5453
kosak2336e9c2014-07-28 22:57:30 +00005454 int lhs[] = {1, 2};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005455 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
5456 EXPECT_THAT(lhs, m);
5457
5458 // Changing rhs now shouldn't affect m, which made a copy of rhs.
5459 rhs.push_back(6);
5460 EXPECT_THAT(lhs, m);
5461}
5462
5463TEST(PointwiseTest, WorksForLhsNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00005464 const int lhs[] = {1, 2, 3};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005465 vector<int> rhs;
5466 rhs.push_back(2);
5467 rhs.push_back(4);
5468 rhs.push_back(6);
5469 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
5470 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5471}
5472
5473TEST(PointwiseTest, WorksForRhsNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00005474 const int rhs[] = {1, 2, 3};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005475 vector<int> lhs;
5476 lhs.push_back(2);
5477 lhs.push_back(4);
5478 lhs.push_back(6);
5479 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
5480 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
5481}
5482
kosak2336e9c2014-07-28 22:57:30 +00005483#if GTEST_HAS_STD_INITIALIZER_LIST_
5484
5485TEST(PointwiseTest, WorksForRhsInitializerList) {
5486 const vector<int> lhs{2, 4, 6};
5487 EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
5488 EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
5489}
5490
5491#endif // GTEST_HAS_STD_INITIALIZER_LIST_
5492
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005493TEST(PointwiseTest, RejectsWrongSize) {
kosak2336e9c2014-07-28 22:57:30 +00005494 const double lhs[2] = {1, 2};
5495 const int rhs[1] = {0};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005496 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5497 EXPECT_EQ("which contains 2 values",
5498 Explain(Pointwise(Gt(), rhs), lhs));
5499
kosak2336e9c2014-07-28 22:57:30 +00005500 const int rhs2[3] = {0, 1, 2};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005501 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
5502}
5503
5504TEST(PointwiseTest, RejectsWrongContent) {
kosak2336e9c2014-07-28 22:57:30 +00005505 const double lhs[3] = {1, 2, 3};
5506 const int rhs[3] = {2, 6, 4};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005507 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
5508 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
5509 "where the second/2 is 3",
5510 Explain(Pointwise(IsHalfOf(), rhs), lhs));
5511}
5512
5513TEST(PointwiseTest, AcceptsCorrectContent) {
kosak2336e9c2014-07-28 22:57:30 +00005514 const double lhs[3] = {1, 2, 3};
5515 const int rhs[3] = {2, 4, 6};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005516 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
5517 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
5518}
5519
5520TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
kosak2336e9c2014-07-28 22:57:30 +00005521 const double lhs[3] = {1, 2, 3};
5522 const int rhs[3] = {2, 4, 6};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005523 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5524 EXPECT_THAT(lhs, Pointwise(m1, rhs));
5525 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
5526
5527 // This type works as a tuple<const double&, const int&> can be
5528 // implicitly cast to tuple<double, int>.
5529 const Matcher<tuple<double, int> > m2 = IsHalfOf();
5530 EXPECT_THAT(lhs, Pointwise(m2, rhs));
5531 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
5532}
5533
kosak2336e9c2014-07-28 22:57:30 +00005534TEST(UnorderedPointwiseTest, DescribesSelf) {
5535 vector<int> rhs;
5536 rhs.push_back(1);
5537 rhs.push_back(2);
5538 rhs.push_back(3);
5539 const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
5540 EXPECT_EQ(
5541 "has 3 elements and there exists some permutation of elements such "
5542 "that:\n"
5543 " - element #0 and 1 are a pair where the first is half of the second, "
5544 "and\n"
5545 " - element #1 and 2 are a pair where the first is half of the second, "
5546 "and\n"
5547 " - element #2 and 3 are a pair where the first is half of the second",
5548 Describe(m));
5549 EXPECT_EQ(
5550 "doesn't have 3 elements, or there exists no permutation of elements "
5551 "such 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 DescribeNegation(m));
5558}
5559
5560TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
5561 list<signed char> rhs;
5562 rhs.push_back(2);
5563 rhs.push_back(4);
5564
5565 int lhs[] = {2, 1};
5566 const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
5567 EXPECT_THAT(lhs, m);
5568
5569 // Changing rhs now shouldn't affect m, which made a copy of rhs.
5570 rhs.push_back(6);
5571 EXPECT_THAT(lhs, m);
5572}
5573
5574TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
5575 const int lhs[] = {1, 2, 3};
5576 vector<int> rhs;
5577 rhs.push_back(4);
5578 rhs.push_back(6);
5579 rhs.push_back(2);
5580 EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
5581 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
5582}
5583
5584TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
5585 const int rhs[] = {1, 2, 3};
5586 vector<int> lhs;
5587 lhs.push_back(4);
5588 lhs.push_back(2);
5589 lhs.push_back(6);
5590 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
5591 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
5592}
5593
5594#if GTEST_HAS_STD_INITIALIZER_LIST_
5595
5596TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
5597 const vector<int> lhs{2, 4, 6};
5598 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
5599 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
5600}
5601
5602#endif // GTEST_HAS_STD_INITIALIZER_LIST_
5603
5604TEST(UnorderedPointwiseTest, RejectsWrongSize) {
5605 const double lhs[2] = {1, 2};
5606 const int rhs[1] = {0};
5607 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
5608 EXPECT_EQ("which has 2 elements",
5609 Explain(UnorderedPointwise(Gt(), rhs), lhs));
5610
5611 const int rhs2[3] = {0, 1, 2};
5612 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
5613}
5614
5615TEST(UnorderedPointwiseTest, RejectsWrongContent) {
5616 const double lhs[3] = {1, 2, 3};
5617 const int rhs[3] = {2, 6, 6};
5618 EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
5619 EXPECT_EQ("where the following elements don't match any matchers:\n"
5620 "element #1: 2",
5621 Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
5622}
5623
5624TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
5625 const double lhs[3] = {1, 2, 3};
5626 const int rhs[3] = {2, 4, 6};
5627 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
5628}
5629
5630TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
5631 const double lhs[3] = {1, 2, 3};
5632 const int rhs[3] = {6, 4, 2};
5633 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
5634}
5635
5636TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
5637 const double lhs[3] = {1, 2, 3};
5638 const int rhs[3] = {4, 6, 2};
5639 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5640 EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
5641
5642 // This type works as a tuple<const double&, const int&> can be
5643 // implicitly cast to tuple<double, int>.
5644 const Matcher<tuple<double, int> > m2 = IsHalfOf();
5645 EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
5646}
5647
shiqiane35fdd92008-12-10 05:08:54 +00005648} // namespace gmock_matchers_test
5649} // namespace testing