blob: 2a5cf908ecd2688e0cb2a2455a7ca3cbdd101220 [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
57namespace testing {
zhanyong.wan4a5330d2009-02-19 00:36:44 +000058
59namespace internal {
vladlosev587c1b32011-05-20 00:42:22 +000060GTEST_API_ string JoinAsTuple(const Strings& fields);
zhanyong.wan4a5330d2009-02-19 00:36:44 +000061} // namespace internal
62
shiqiane35fdd92008-12-10 05:08:54 +000063namespace gmock_matchers_test {
64
zhanyong.wan898725c2011-09-16 16:45:39 +000065using std::greater;
66using std::less;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000067using std::list;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000068using std::make_pair;
zhanyong.wanb5937da2009-07-16 20:26:41 +000069using std::map;
70using std::multimap;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000071using std::multiset;
72using std::ostream;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000073using std::pair;
zhanyong.wan33605ba2010-04-22 23:37:47 +000074using std::set;
shiqiane35fdd92008-12-10 05:08:54 +000075using std::stringstream;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000076using std::tr1::get;
zhanyong.wanb8243162009-06-04 05:48:20 +000077using std::tr1::make_tuple;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000078using std::tr1::tuple;
zhanyong.wan33605ba2010-04-22 23:37:47 +000079using std::vector;
shiqiane35fdd92008-12-10 05:08:54 +000080using testing::A;
zhanyong.wanbf550852009-06-09 06:09:53 +000081using testing::AllArgs;
shiqiane35fdd92008-12-10 05:08:54 +000082using testing::AllOf;
83using testing::An;
84using testing::AnyOf;
85using testing::ByRef;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000086using testing::ContainsRegex;
shiqiane35fdd92008-12-10 05:08:54 +000087using testing::DoubleEq;
zhanyong.wan616180e2013-06-18 18:49:51 +000088using testing::DoubleNear;
shiqiane35fdd92008-12-10 05:08:54 +000089using testing::EndsWith;
90using testing::Eq;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000091using testing::ExplainMatchResult;
shiqiane35fdd92008-12-10 05:08:54 +000092using testing::Field;
93using testing::FloatEq;
zhanyong.wan616180e2013-06-18 18:49:51 +000094using testing::FloatNear;
shiqiane35fdd92008-12-10 05:08:54 +000095using testing::Ge;
96using testing::Gt;
97using testing::HasSubstr;
zhanyong.wan320814a2013-03-01 00:20:30 +000098using testing::IsEmpty;
zhanyong.wan2d970ee2009-09-24 21:41:36 +000099using testing::IsNull;
zhanyong.wanb5937da2009-07-16 20:26:41 +0000100using testing::Key;
shiqiane35fdd92008-12-10 05:08:54 +0000101using testing::Le;
102using testing::Lt;
103using testing::MakeMatcher;
104using testing::MakePolymorphicMatcher;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000105using testing::MatchResultListener;
shiqiane35fdd92008-12-10 05:08:54 +0000106using testing::Matcher;
107using testing::MatcherCast;
108using testing::MatcherInterface;
109using testing::Matches;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000110using testing::MatchesRegex;
shiqiane35fdd92008-12-10 05:08:54 +0000111using testing::NanSensitiveDoubleEq;
zhanyong.wan616180e2013-06-18 18:49:51 +0000112using testing::NanSensitiveDoubleNear;
shiqiane35fdd92008-12-10 05:08:54 +0000113using testing::NanSensitiveFloatEq;
zhanyong.wan616180e2013-06-18 18:49:51 +0000114using testing::NanSensitiveFloatNear;
shiqiane35fdd92008-12-10 05:08:54 +0000115using testing::Ne;
116using testing::Not;
117using testing::NotNull;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000118using testing::Pair;
shiqiane35fdd92008-12-10 05:08:54 +0000119using testing::Pointee;
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000120using testing::Pointwise;
shiqiane35fdd92008-12-10 05:08:54 +0000121using testing::PolymorphicMatcher;
122using testing::Property;
123using testing::Ref;
124using testing::ResultOf;
zhanyong.wana31d9ce2013-03-01 01:50:17 +0000125using testing::SizeIs;
shiqiane35fdd92008-12-10 05:08:54 +0000126using testing::StartsWith;
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000127using testing::StringMatchResultListener;
shiqiane35fdd92008-12-10 05:08:54 +0000128using testing::StrCaseEq;
129using testing::StrCaseNe;
130using testing::StrEq;
131using testing::StrNe;
132using testing::Truly;
133using testing::TypedEq;
zhanyong.wanb8243162009-06-04 05:48:20 +0000134using testing::Value;
zhanyong.wan898725c2011-09-16 16:45:39 +0000135using testing::WhenSorted;
136using testing::WhenSortedBy;
shiqiane35fdd92008-12-10 05:08:54 +0000137using testing::_;
zhanyong.wana862f1d2010-03-15 21:23:04 +0000138using testing::internal::DummyMatchResultListener;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000139using testing::internal::ElementMatcherPair;
140using testing::internal::ElementMatcherPairs;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000141using testing::internal::ExplainMatchFailureTupleTo;
shiqiane35fdd92008-12-10 05:08:54 +0000142using testing::internal::FloatingEqMatcher;
zhanyong.wanb4140802010-06-08 22:53:57 +0000143using testing::internal::FormatMatcherDescription;
zhanyong.wan736baa82010-09-27 17:44:16 +0000144using testing::internal::IsReadableTypeName;
zhanyong.wan4a5330d2009-02-19 00:36:44 +0000145using testing::internal::JoinAsTuple;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000146using testing::internal::MatchMatrix;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000147using testing::internal::RE;
zhanyong.wana862f1d2010-03-15 21:23:04 +0000148using testing::internal::StreamMatchResultListener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000149using testing::internal::Strings;
vladlosev79b83502009-11-18 00:43:37 +0000150using testing::internal::linked_ptr;
vladloseve56daa72009-11-18 01:08:08 +0000151using testing::internal::scoped_ptr;
shiqiane35fdd92008-12-10 05:08:54 +0000152using testing::internal::string;
153
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000154// For testing ExplainMatchResultTo().
155class GreaterThanMatcher : public MatcherInterface<int> {
156 public:
157 explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
158
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000159 virtual void DescribeTo(ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000160 *os << "is > " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000161 }
162
zhanyong.wandb22c222010-01-28 21:52:29 +0000163 virtual bool MatchAndExplain(int lhs,
164 MatchResultListener* listener) const {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000165 const int diff = lhs - rhs_;
166 if (diff > 0) {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000167 *listener << "which is " << diff << " more than " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000168 } else if (diff == 0) {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000169 *listener << "which is the same as " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000170 } else {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000171 *listener << "which is " << -diff << " less than " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000172 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000173
174 return lhs > rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000175 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000176
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000177 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000178 int rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000179};
180
181Matcher<int> GreaterThan(int n) {
182 return MakeMatcher(new GreaterThanMatcher(n));
183}
184
zhanyong.wan736baa82010-09-27 17:44:16 +0000185string OfType(const string& type_name) {
186#if GTEST_HAS_RTTI
187 return " (of type " + type_name + ")";
188#else
189 return "";
190#endif
191}
192
shiqiane35fdd92008-12-10 05:08:54 +0000193// Returns the description of the given matcher.
194template <typename T>
195string Describe(const Matcher<T>& m) {
196 stringstream ss;
197 m.DescribeTo(&ss);
198 return ss.str();
199}
200
201// Returns the description of the negation of the given matcher.
202template <typename T>
203string DescribeNegation(const Matcher<T>& m) {
204 stringstream ss;
205 m.DescribeNegationTo(&ss);
206 return ss.str();
207}
208
209// Returns the reason why x matches, or doesn't match, m.
210template <typename MatcherType, typename Value>
211string Explain(const MatcherType& m, const Value& x) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000212 StringMatchResultListener listener;
213 ExplainMatchResult(m, x, &listener);
214 return listener.str();
shiqiane35fdd92008-12-10 05:08:54 +0000215}
216
zhanyong.wana862f1d2010-03-15 21:23:04 +0000217TEST(MatchResultListenerTest, StreamingWorks) {
218 StringMatchResultListener listener;
219 listener << "hi" << 5;
220 EXPECT_EQ("hi5", listener.str());
221
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000222 listener.Clear();
223 EXPECT_EQ("", listener.str());
224
225 listener << 42;
226 EXPECT_EQ("42", listener.str());
227
zhanyong.wana862f1d2010-03-15 21:23:04 +0000228 // Streaming shouldn't crash when the underlying ostream is NULL.
229 DummyMatchResultListener dummy;
230 dummy << "hi" << 5;
231}
232
233TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
234 EXPECT_TRUE(DummyMatchResultListener().stream() == NULL);
235 EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL);
236
237 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
238}
239
240TEST(MatchResultListenerTest, IsInterestedWorks) {
241 EXPECT_TRUE(StringMatchResultListener().IsInterested());
242 EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
243
244 EXPECT_FALSE(DummyMatchResultListener().IsInterested());
245 EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested());
246}
247
shiqiane35fdd92008-12-10 05:08:54 +0000248// Makes sure that the MatcherInterface<T> interface doesn't
249// change.
250class EvenMatcherImpl : public MatcherInterface<int> {
251 public:
zhanyong.wandb22c222010-01-28 21:52:29 +0000252 virtual bool MatchAndExplain(int x,
253 MatchResultListener* /* listener */) const {
254 return x % 2 == 0;
255 }
shiqiane35fdd92008-12-10 05:08:54 +0000256
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000257 virtual void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +0000258 *os << "is an even number";
259 }
260
261 // We deliberately don't define DescribeNegationTo() and
262 // ExplainMatchResultTo() here, to make sure the definition of these
263 // two methods is optional.
264};
265
zhanyong.wana862f1d2010-03-15 21:23:04 +0000266// Makes sure that the MatcherInterface API doesn't change.
267TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
shiqiane35fdd92008-12-10 05:08:54 +0000268 EvenMatcherImpl m;
269}
270
zhanyong.wan82113312010-01-08 21:55:40 +0000271// Tests implementing a monomorphic matcher using MatchAndExplain().
272
273class NewEvenMatcherImpl : public MatcherInterface<int> {
274 public:
275 virtual bool MatchAndExplain(int x, MatchResultListener* listener) const {
276 const bool match = x % 2 == 0;
277 // Verifies that we can stream to a listener directly.
278 *listener << "value % " << 2;
279 if (listener->stream() != NULL) {
280 // Verifies that we can stream to a listener's underlying stream
281 // too.
282 *listener->stream() << " == " << (x % 2);
283 }
284 return match;
285 }
286
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000287 virtual void DescribeTo(ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000288 *os << "is an even number";
289 }
290};
291
292TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
293 Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
294 EXPECT_TRUE(m.Matches(2));
295 EXPECT_FALSE(m.Matches(3));
296 EXPECT_EQ("value % 2 == 0", Explain(m, 2));
297 EXPECT_EQ("value % 2 == 1", Explain(m, 3));
298}
299
shiqiane35fdd92008-12-10 05:08:54 +0000300// Tests default-constructing a matcher.
301TEST(MatcherTest, CanBeDefaultConstructed) {
302 Matcher<double> m;
303}
304
305// Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
306TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
307 const MatcherInterface<int>* impl = new EvenMatcherImpl;
308 Matcher<int> m(impl);
309 EXPECT_TRUE(m.Matches(4));
310 EXPECT_FALSE(m.Matches(5));
311}
312
313// Tests that value can be used in place of Eq(value).
314TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
315 Matcher<int> m1 = 5;
316 EXPECT_TRUE(m1.Matches(5));
317 EXPECT_FALSE(m1.Matches(6));
318}
319
320// Tests that NULL can be used in place of Eq(NULL).
321TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
322 Matcher<int*> m1 = NULL;
323 EXPECT_TRUE(m1.Matches(NULL));
324 int n = 0;
325 EXPECT_FALSE(m1.Matches(&n));
326}
327
328// Tests that matchers are copyable.
329TEST(MatcherTest, IsCopyable) {
330 // Tests the copy constructor.
331 Matcher<bool> m1 = Eq(false);
332 EXPECT_TRUE(m1.Matches(false));
333 EXPECT_FALSE(m1.Matches(true));
334
335 // Tests the assignment operator.
336 m1 = Eq(true);
337 EXPECT_TRUE(m1.Matches(true));
338 EXPECT_FALSE(m1.Matches(false));
339}
340
341// Tests that Matcher<T>::DescribeTo() calls
342// MatcherInterface<T>::DescribeTo().
343TEST(MatcherTest, CanDescribeItself) {
344 EXPECT_EQ("is an even number",
345 Describe(Matcher<int>(new EvenMatcherImpl)));
346}
347
zhanyong.wan82113312010-01-08 21:55:40 +0000348// Tests Matcher<T>::MatchAndExplain().
349TEST(MatcherTest, MatchAndExplain) {
350 Matcher<int> m = GreaterThan(0);
zhanyong.wan34b034c2010-03-05 21:23:23 +0000351 StringMatchResultListener listener1;
zhanyong.wan82113312010-01-08 21:55:40 +0000352 EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000353 EXPECT_EQ("which is 42 more than 0", listener1.str());
zhanyong.wan82113312010-01-08 21:55:40 +0000354
zhanyong.wan34b034c2010-03-05 21:23:23 +0000355 StringMatchResultListener listener2;
zhanyong.wan82113312010-01-08 21:55:40 +0000356 EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000357 EXPECT_EQ("which is 9 less than 0", listener2.str());
zhanyong.wan82113312010-01-08 21:55:40 +0000358}
359
shiqiane35fdd92008-12-10 05:08:54 +0000360// Tests that a C-string literal can be implicitly converted to a
361// Matcher<string> or Matcher<const string&>.
362TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
363 Matcher<string> m1 = "hi";
364 EXPECT_TRUE(m1.Matches("hi"));
365 EXPECT_FALSE(m1.Matches("hello"));
366
367 Matcher<const string&> m2 = "hi";
368 EXPECT_TRUE(m2.Matches("hi"));
369 EXPECT_FALSE(m2.Matches("hello"));
370}
371
372// Tests that a string object can be implicitly converted to a
373// Matcher<string> or Matcher<const string&>.
374TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
375 Matcher<string> m1 = string("hi");
376 EXPECT_TRUE(m1.Matches("hi"));
377 EXPECT_FALSE(m1.Matches("hello"));
378
379 Matcher<const string&> m2 = string("hi");
380 EXPECT_TRUE(m2.Matches("hi"));
381 EXPECT_FALSE(m2.Matches("hello"));
382}
383
zhanyong.wan1f122a02013-03-25 16:27:03 +0000384#if GTEST_HAS_STRING_PIECE_
385// Tests that a C-string literal can be implicitly converted to a
386// Matcher<StringPiece> or Matcher<const StringPiece&>.
387TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
388 Matcher<StringPiece> m1 = "cats";
389 EXPECT_TRUE(m1.Matches("cats"));
390 EXPECT_FALSE(m1.Matches("dogs"));
391
392 Matcher<const StringPiece&> m2 = "cats";
393 EXPECT_TRUE(m2.Matches("cats"));
394 EXPECT_FALSE(m2.Matches("dogs"));
395}
396
397// Tests that a string object can be implicitly converted to a
398// Matcher<StringPiece> or Matcher<const StringPiece&>.
399TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromString) {
400 Matcher<StringPiece> m1 = string("cats");
401 EXPECT_TRUE(m1.Matches("cats"));
402 EXPECT_FALSE(m1.Matches("dogs"));
403
404 Matcher<const StringPiece&> m2 = string("cats");
405 EXPECT_TRUE(m2.Matches("cats"));
406 EXPECT_FALSE(m2.Matches("dogs"));
407}
408
409// Tests that a StringPiece object can be implicitly converted to a
410// Matcher<StringPiece> or Matcher<const StringPiece&>.
411TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromStringPiece) {
412 Matcher<StringPiece> m1 = StringPiece("cats");
413 EXPECT_TRUE(m1.Matches("cats"));
414 EXPECT_FALSE(m1.Matches("dogs"));
415
416 Matcher<const StringPiece&> m2 = StringPiece("cats");
417 EXPECT_TRUE(m2.Matches("cats"));
418 EXPECT_FALSE(m2.Matches("dogs"));
419}
420#endif // GTEST_HAS_STRING_PIECE_
421
shiqiane35fdd92008-12-10 05:08:54 +0000422// Tests that MakeMatcher() constructs a Matcher<T> from a
423// MatcherInterface* without requiring the user to explicitly
424// write the type.
425TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
426 const MatcherInterface<int>* dummy_impl = NULL;
427 Matcher<int> m = MakeMatcher(dummy_impl);
428}
429
zhanyong.wan82113312010-01-08 21:55:40 +0000430// Tests that MakePolymorphicMatcher() can construct a polymorphic
431// matcher from its implementation using the old API.
zhanyong.wan33605ba2010-04-22 23:37:47 +0000432const int g_bar = 1;
shiqiane35fdd92008-12-10 05:08:54 +0000433class ReferencesBarOrIsZeroImpl {
434 public:
435 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +0000436 bool MatchAndExplain(const T& x,
437 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000438 const void* p = &x;
zhanyong.wan33605ba2010-04-22 23:37:47 +0000439 return p == &g_bar || x == 0;
shiqiane35fdd92008-12-10 05:08:54 +0000440 }
441
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000442 void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
shiqiane35fdd92008-12-10 05:08:54 +0000443
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000444 void DescribeNegationTo(ostream* os) const {
zhanyong.wan33605ba2010-04-22 23:37:47 +0000445 *os << "doesn't reference g_bar and is not zero";
shiqiane35fdd92008-12-10 05:08:54 +0000446 }
447};
448
449// This function verifies that MakePolymorphicMatcher() returns a
450// PolymorphicMatcher<T> where T is the argument's type.
451PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
452 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
453}
454
zhanyong.wan82113312010-01-08 21:55:40 +0000455TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
shiqiane35fdd92008-12-10 05:08:54 +0000456 // Using a polymorphic matcher to match a reference type.
457 Matcher<const int&> m1 = ReferencesBarOrIsZero();
458 EXPECT_TRUE(m1.Matches(0));
459 // Verifies that the identity of a by-reference argument is preserved.
zhanyong.wan33605ba2010-04-22 23:37:47 +0000460 EXPECT_TRUE(m1.Matches(g_bar));
shiqiane35fdd92008-12-10 05:08:54 +0000461 EXPECT_FALSE(m1.Matches(1));
zhanyong.wan33605ba2010-04-22 23:37:47 +0000462 EXPECT_EQ("g_bar or zero", Describe(m1));
shiqiane35fdd92008-12-10 05:08:54 +0000463
464 // Using a polymorphic matcher to match a value type.
465 Matcher<double> m2 = ReferencesBarOrIsZero();
466 EXPECT_TRUE(m2.Matches(0.0));
467 EXPECT_FALSE(m2.Matches(0.1));
zhanyong.wan33605ba2010-04-22 23:37:47 +0000468 EXPECT_EQ("g_bar or zero", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +0000469}
470
zhanyong.wan82113312010-01-08 21:55:40 +0000471// Tests implementing a polymorphic matcher using MatchAndExplain().
472
473class PolymorphicIsEvenImpl {
474 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000475 void DescribeTo(ostream* os) const { *os << "is even"; }
zhanyong.wan82113312010-01-08 21:55:40 +0000476
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000477 void DescribeNegationTo(ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000478 *os << "is odd";
479 }
zhanyong.wan82113312010-01-08 21:55:40 +0000480
zhanyong.wandb22c222010-01-28 21:52:29 +0000481 template <typename T>
482 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
483 // Verifies that we can stream to the listener directly.
484 *listener << "% " << 2;
485 if (listener->stream() != NULL) {
486 // Verifies that we can stream to the listener's underlying stream
487 // too.
488 *listener->stream() << " == " << (x % 2);
489 }
490 return (x % 2) == 0;
zhanyong.wan82113312010-01-08 21:55:40 +0000491 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000492};
zhanyong.wan82113312010-01-08 21:55:40 +0000493
494PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
495 return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
496}
497
498TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
499 // Using PolymorphicIsEven() as a Matcher<int>.
500 const Matcher<int> m1 = PolymorphicIsEven();
501 EXPECT_TRUE(m1.Matches(42));
502 EXPECT_FALSE(m1.Matches(43));
503 EXPECT_EQ("is even", Describe(m1));
504
505 const Matcher<int> not_m1 = Not(m1);
506 EXPECT_EQ("is odd", Describe(not_m1));
507
508 EXPECT_EQ("% 2 == 0", Explain(m1, 42));
509
510 // Using PolymorphicIsEven() as a Matcher<char>.
511 const Matcher<char> m2 = PolymorphicIsEven();
512 EXPECT_TRUE(m2.Matches('\x42'));
513 EXPECT_FALSE(m2.Matches('\x43'));
514 EXPECT_EQ("is even", Describe(m2));
515
516 const Matcher<char> not_m2 = Not(m2);
517 EXPECT_EQ("is odd", Describe(not_m2));
518
519 EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
520}
521
shiqiane35fdd92008-12-10 05:08:54 +0000522// Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
523TEST(MatcherCastTest, FromPolymorphicMatcher) {
524 Matcher<int> m = MatcherCast<int>(Eq(5));
525 EXPECT_TRUE(m.Matches(5));
526 EXPECT_FALSE(m.Matches(6));
527}
528
529// For testing casting matchers between compatible types.
530class IntValue {
531 public:
532 // An int can be statically (although not implicitly) cast to a
533 // IntValue.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000534 explicit IntValue(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +0000535
536 int value() const { return value_; }
537 private:
538 int value_;
539};
540
541// For testing casting matchers between compatible types.
542bool IsPositiveIntValue(const IntValue& foo) {
543 return foo.value() > 0;
544}
545
546// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
547// can be statically converted to U.
548TEST(MatcherCastTest, FromCompatibleType) {
549 Matcher<double> m1 = Eq(2.0);
550 Matcher<int> m2 = MatcherCast<int>(m1);
551 EXPECT_TRUE(m2.Matches(2));
552 EXPECT_FALSE(m2.Matches(3));
553
554 Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
555 Matcher<int> m4 = MatcherCast<int>(m3);
556 // In the following, the arguments 1 and 0 are statically converted
557 // to IntValue objects, and then tested by the IsPositiveIntValue()
558 // predicate.
559 EXPECT_TRUE(m4.Matches(1));
560 EXPECT_FALSE(m4.Matches(0));
561}
562
563// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
564TEST(MatcherCastTest, FromConstReferenceToNonReference) {
565 Matcher<const int&> m1 = Eq(0);
566 Matcher<int> m2 = MatcherCast<int>(m1);
567 EXPECT_TRUE(m2.Matches(0));
568 EXPECT_FALSE(m2.Matches(1));
569}
570
571// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
572TEST(MatcherCastTest, FromReferenceToNonReference) {
573 Matcher<int&> m1 = Eq(0);
574 Matcher<int> m2 = MatcherCast<int>(m1);
575 EXPECT_TRUE(m2.Matches(0));
576 EXPECT_FALSE(m2.Matches(1));
577}
578
579// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
580TEST(MatcherCastTest, FromNonReferenceToConstReference) {
581 Matcher<int> m1 = Eq(0);
582 Matcher<const int&> m2 = MatcherCast<const int&>(m1);
583 EXPECT_TRUE(m2.Matches(0));
584 EXPECT_FALSE(m2.Matches(1));
585}
586
587// Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
588TEST(MatcherCastTest, FromNonReferenceToReference) {
589 Matcher<int> m1 = Eq(0);
590 Matcher<int&> m2 = MatcherCast<int&>(m1);
591 int n = 0;
592 EXPECT_TRUE(m2.Matches(n));
593 n = 1;
594 EXPECT_FALSE(m2.Matches(n));
595}
596
597// Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
598TEST(MatcherCastTest, FromSameType) {
599 Matcher<int> m1 = Eq(0);
600 Matcher<int> m2 = MatcherCast<int>(m1);
601 EXPECT_TRUE(m2.Matches(0));
602 EXPECT_FALSE(m2.Matches(1));
603}
604
jgm79a367e2012-04-10 16:02:11 +0000605// Implicitly convertible form any type.
606struct ConvertibleFromAny {
607 ConvertibleFromAny(int a_value) : value(a_value) {}
608 template <typename T>
609 ConvertibleFromAny(const T& a_value) : value(-1) {
610 ADD_FAILURE() << "Conversion constructor called";
611 }
612 int value;
613};
614
615bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
616 return a.value == b.value;
617}
618
619ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
620 return os << a.value;
621}
622
623TEST(MatcherCastTest, ConversionConstructorIsUsed) {
624 Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
625 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
626 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
627}
628
629TEST(MatcherCastTest, FromConvertibleFromAny) {
630 Matcher<ConvertibleFromAny> m =
631 MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
632 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
633 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
634}
635
kosak5f2a6ca2013-12-03 01:43:07 +0000636struct IntReferenceWrapper {
637 IntReferenceWrapper(const int& a_value) : value(&a_value) {}
638 const int* value;
639};
640
641bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
642 return a.value == b.value;
643}
644
645TEST(MatcherCastTest, ValueIsNotCopied) {
646 int n = 42;
647 Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
648 // Verify that the matcher holds a reference to n, not to its temporary copy.
649 EXPECT_TRUE(m.Matches(n));
650}
651
zhanyong.wan18490652009-05-11 18:54:08 +0000652class Base {};
653class Derived : public Base {};
654
655// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
656TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
657 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
658 EXPECT_TRUE(m2.Matches(' '));
659 EXPECT_FALSE(m2.Matches('\n'));
660}
661
zhanyong.wan16cf4732009-05-14 20:55:30 +0000662// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
663// T and U are arithmetic types and T can be losslessly converted to
664// U.
665TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
zhanyong.wan18490652009-05-11 18:54:08 +0000666 Matcher<double> m1 = DoubleEq(1.0);
zhanyong.wan16cf4732009-05-14 20:55:30 +0000667 Matcher<float> m2 = SafeMatcherCast<float>(m1);
668 EXPECT_TRUE(m2.Matches(1.0f));
669 EXPECT_FALSE(m2.Matches(2.0f));
670
671 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
672 EXPECT_TRUE(m3.Matches('a'));
673 EXPECT_FALSE(m3.Matches('b'));
zhanyong.wan18490652009-05-11 18:54:08 +0000674}
675
676// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
677// are pointers or references to a derived and a base class, correspondingly.
678TEST(SafeMatcherCastTest, FromBaseClass) {
679 Derived d, d2;
680 Matcher<Base*> m1 = Eq(&d);
681 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
682 EXPECT_TRUE(m2.Matches(&d));
683 EXPECT_FALSE(m2.Matches(&d2));
684
685 Matcher<Base&> m3 = Ref(d);
686 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
687 EXPECT_TRUE(m4.Matches(d));
688 EXPECT_FALSE(m4.Matches(d2));
689}
690
691// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
692TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
693 int n = 0;
694 Matcher<const int&> m1 = Ref(n);
695 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
696 int n1 = 0;
697 EXPECT_TRUE(m2.Matches(n));
698 EXPECT_FALSE(m2.Matches(n1));
699}
700
701// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
702TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
703 Matcher<int> m1 = Eq(0);
704 Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
705 EXPECT_TRUE(m2.Matches(0));
706 EXPECT_FALSE(m2.Matches(1));
707}
708
709// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
710TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
711 Matcher<int> m1 = Eq(0);
712 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
713 int n = 0;
714 EXPECT_TRUE(m2.Matches(n));
715 n = 1;
716 EXPECT_FALSE(m2.Matches(n));
717}
718
719// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
720TEST(SafeMatcherCastTest, FromSameType) {
721 Matcher<int> m1 = Eq(0);
722 Matcher<int> m2 = SafeMatcherCast<int>(m1);
723 EXPECT_TRUE(m2.Matches(0));
724 EXPECT_FALSE(m2.Matches(1));
725}
726
jgm79a367e2012-04-10 16:02:11 +0000727TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
728 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
729 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
730 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
731}
732
733TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
734 Matcher<ConvertibleFromAny> m =
735 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
736 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
737 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
738}
739
kosak5f2a6ca2013-12-03 01:43:07 +0000740TEST(SafeMatcherCastTest, ValueIsNotCopied) {
741 int n = 42;
742 Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
743 // Verify that the matcher holds a reference to n, not to its temporary copy.
744 EXPECT_TRUE(m.Matches(n));
745}
746
shiqiane35fdd92008-12-10 05:08:54 +0000747// Tests that A<T>() matches any value of type T.
748TEST(ATest, MatchesAnyValue) {
749 // Tests a matcher for a value type.
750 Matcher<double> m1 = A<double>();
751 EXPECT_TRUE(m1.Matches(91.43));
752 EXPECT_TRUE(m1.Matches(-15.32));
753
754 // Tests a matcher for a reference type.
755 int a = 2;
756 int b = -6;
757 Matcher<int&> m2 = A<int&>();
758 EXPECT_TRUE(m2.Matches(a));
759 EXPECT_TRUE(m2.Matches(b));
760}
761
zhanyong.wanf4274522013-04-24 02:49:43 +0000762TEST(ATest, WorksForDerivedClass) {
763 Base base;
764 Derived derived;
765 EXPECT_THAT(&base, A<Base*>());
766 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
767 EXPECT_THAT(&derived, A<Base*>());
768 EXPECT_THAT(&derived, A<Derived*>());
769}
770
shiqiane35fdd92008-12-10 05:08:54 +0000771// Tests that A<T>() describes itself properly.
772TEST(ATest, CanDescribeSelf) {
773 EXPECT_EQ("is anything", Describe(A<bool>()));
774}
775
776// Tests that An<T>() matches any value of type T.
777TEST(AnTest, MatchesAnyValue) {
778 // Tests a matcher for a value type.
779 Matcher<int> m1 = An<int>();
780 EXPECT_TRUE(m1.Matches(9143));
781 EXPECT_TRUE(m1.Matches(-1532));
782
783 // Tests a matcher for a reference type.
784 int a = 2;
785 int b = -6;
786 Matcher<int&> m2 = An<int&>();
787 EXPECT_TRUE(m2.Matches(a));
788 EXPECT_TRUE(m2.Matches(b));
789}
790
791// Tests that An<T>() describes itself properly.
792TEST(AnTest, CanDescribeSelf) {
793 EXPECT_EQ("is anything", Describe(An<int>()));
794}
795
796// Tests that _ can be used as a matcher for any type and matches any
797// value of that type.
798TEST(UnderscoreTest, MatchesAnyValue) {
799 // Uses _ as a matcher for a value type.
800 Matcher<int> m1 = _;
801 EXPECT_TRUE(m1.Matches(123));
802 EXPECT_TRUE(m1.Matches(-242));
803
804 // Uses _ as a matcher for a reference type.
805 bool a = false;
806 const bool b = true;
807 Matcher<const bool&> m2 = _;
808 EXPECT_TRUE(m2.Matches(a));
809 EXPECT_TRUE(m2.Matches(b));
810}
811
812// Tests that _ describes itself properly.
813TEST(UnderscoreTest, CanDescribeSelf) {
814 Matcher<int> m = _;
815 EXPECT_EQ("is anything", Describe(m));
816}
817
818// Tests that Eq(x) matches any value equal to x.
819TEST(EqTest, MatchesEqualValue) {
820 // 2 C-strings with same content but different addresses.
821 const char a1[] = "hi";
822 const char a2[] = "hi";
823
824 Matcher<const char*> m1 = Eq(a1);
825 EXPECT_TRUE(m1.Matches(a1));
826 EXPECT_FALSE(m1.Matches(a2));
827}
828
829// Tests that Eq(v) describes itself properly.
830
831class Unprintable {
832 public:
833 Unprintable() : c_('a') {}
834
zhanyong.wan32de5f52009-12-23 00:13:23 +0000835 bool operator==(const Unprintable& /* rhs */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000836 private:
837 char c_;
838};
839
840TEST(EqTest, CanDescribeSelf) {
841 Matcher<Unprintable> m = Eq(Unprintable());
842 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
843}
844
845// Tests that Eq(v) can be used to match any type that supports
846// comparing with type T, where T is v's type.
847TEST(EqTest, IsPolymorphic) {
848 Matcher<int> m1 = Eq(1);
849 EXPECT_TRUE(m1.Matches(1));
850 EXPECT_FALSE(m1.Matches(2));
851
852 Matcher<char> m2 = Eq(1);
853 EXPECT_TRUE(m2.Matches('\1'));
854 EXPECT_FALSE(m2.Matches('a'));
855}
856
857// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
858TEST(TypedEqTest, ChecksEqualityForGivenType) {
859 Matcher<char> m1 = TypedEq<char>('a');
860 EXPECT_TRUE(m1.Matches('a'));
861 EXPECT_FALSE(m1.Matches('b'));
862
863 Matcher<int> m2 = TypedEq<int>(6);
864 EXPECT_TRUE(m2.Matches(6));
865 EXPECT_FALSE(m2.Matches(7));
866}
867
868// Tests that TypedEq(v) describes itself properly.
869TEST(TypedEqTest, CanDescribeSelf) {
870 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
871}
872
873// Tests that TypedEq<T>(v) has type Matcher<T>.
874
875// Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
876// is a "bare" type (i.e. not in the form of const U or U&). If v's
877// type is not T, the compiler will generate a message about
878// "undefined referece".
879template <typename T>
880struct Type {
zhanyong.wan32de5f52009-12-23 00:13:23 +0000881 static bool IsTypeOf(const T& /* v */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000882
883 template <typename T2>
884 static void IsTypeOf(T2 v);
885};
886
887TEST(TypedEqTest, HasSpecifiedType) {
888 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
889 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
890 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
891}
892
893// Tests that Ge(v) matches anything >= v.
894TEST(GeTest, ImplementsGreaterThanOrEqual) {
895 Matcher<int> m1 = Ge(0);
896 EXPECT_TRUE(m1.Matches(1));
897 EXPECT_TRUE(m1.Matches(0));
898 EXPECT_FALSE(m1.Matches(-1));
899}
900
901// Tests that Ge(v) describes itself properly.
902TEST(GeTest, CanDescribeSelf) {
903 Matcher<int> m = Ge(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000904 EXPECT_EQ("is >= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000905}
906
907// Tests that Gt(v) matches anything > v.
908TEST(GtTest, ImplementsGreaterThan) {
909 Matcher<double> m1 = Gt(0);
910 EXPECT_TRUE(m1.Matches(1.0));
911 EXPECT_FALSE(m1.Matches(0.0));
912 EXPECT_FALSE(m1.Matches(-1.0));
913}
914
915// Tests that Gt(v) describes itself properly.
916TEST(GtTest, CanDescribeSelf) {
917 Matcher<int> m = Gt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000918 EXPECT_EQ("is > 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000919}
920
921// Tests that Le(v) matches anything <= v.
922TEST(LeTest, ImplementsLessThanOrEqual) {
923 Matcher<char> m1 = Le('b');
924 EXPECT_TRUE(m1.Matches('a'));
925 EXPECT_TRUE(m1.Matches('b'));
926 EXPECT_FALSE(m1.Matches('c'));
927}
928
929// Tests that Le(v) describes itself properly.
930TEST(LeTest, CanDescribeSelf) {
931 Matcher<int> m = Le(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000932 EXPECT_EQ("is <= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000933}
934
935// Tests that Lt(v) matches anything < v.
936TEST(LtTest, ImplementsLessThan) {
937 Matcher<const string&> m1 = Lt("Hello");
938 EXPECT_TRUE(m1.Matches("Abc"));
939 EXPECT_FALSE(m1.Matches("Hello"));
940 EXPECT_FALSE(m1.Matches("Hello, world!"));
941}
942
943// Tests that Lt(v) describes itself properly.
944TEST(LtTest, CanDescribeSelf) {
945 Matcher<int> m = Lt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000946 EXPECT_EQ("is < 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000947}
948
949// Tests that Ne(v) matches anything != v.
950TEST(NeTest, ImplementsNotEqual) {
951 Matcher<int> m1 = Ne(0);
952 EXPECT_TRUE(m1.Matches(1));
953 EXPECT_TRUE(m1.Matches(-1));
954 EXPECT_FALSE(m1.Matches(0));
955}
956
957// Tests that Ne(v) describes itself properly.
958TEST(NeTest, CanDescribeSelf) {
959 Matcher<int> m = Ne(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000960 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000961}
962
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000963// Tests that IsNull() matches any NULL pointer of any type.
964TEST(IsNullTest, MatchesNullPointer) {
965 Matcher<int*> m1 = IsNull();
966 int* p1 = NULL;
967 int n = 0;
968 EXPECT_TRUE(m1.Matches(p1));
969 EXPECT_FALSE(m1.Matches(&n));
970
971 Matcher<const char*> m2 = IsNull();
972 const char* p2 = NULL;
973 EXPECT_TRUE(m2.Matches(p2));
974 EXPECT_FALSE(m2.Matches("hi"));
975
zhanyong.wan95b12332009-09-25 18:55:50 +0000976#if !GTEST_OS_SYMBIAN
977 // Nokia's Symbian compiler generates:
978 // gmock-matchers.h: ambiguous access to overloaded function
979 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
980 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
981 // MatcherInterface<void *> *)'
982 // gmock-matchers.h: (point of instantiation: 'testing::
983 // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
984 // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000985 Matcher<void*> m3 = IsNull();
986 void* p3 = NULL;
987 EXPECT_TRUE(m3.Matches(p3));
988 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
zhanyong.wan95b12332009-09-25 18:55:50 +0000989#endif
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000990}
991
vladlosev79b83502009-11-18 00:43:37 +0000992TEST(IsNullTest, LinkedPtr) {
993 const Matcher<linked_ptr<int> > m = IsNull();
994 const linked_ptr<int> null_p;
995 const linked_ptr<int> non_null_p(new int);
996
997 EXPECT_TRUE(m.Matches(null_p));
998 EXPECT_FALSE(m.Matches(non_null_p));
999}
1000
1001TEST(IsNullTest, ReferenceToConstLinkedPtr) {
1002 const Matcher<const linked_ptr<double>&> m = IsNull();
1003 const linked_ptr<double> null_p;
1004 const linked_ptr<double> non_null_p(new double);
1005
1006 EXPECT_TRUE(m.Matches(null_p));
1007 EXPECT_FALSE(m.Matches(non_null_p));
1008}
1009
vladloseve56daa72009-11-18 01:08:08 +00001010TEST(IsNullTest, ReferenceToConstScopedPtr) {
1011 const Matcher<const scoped_ptr<double>&> m = IsNull();
1012 const scoped_ptr<double> null_p;
1013 const scoped_ptr<double> non_null_p(new double);
1014
1015 EXPECT_TRUE(m.Matches(null_p));
1016 EXPECT_FALSE(m.Matches(non_null_p));
1017}
1018
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001019// Tests that IsNull() describes itself properly.
1020TEST(IsNullTest, CanDescribeSelf) {
1021 Matcher<int*> m = IsNull();
1022 EXPECT_EQ("is NULL", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001023 EXPECT_EQ("isn't NULL", DescribeNegation(m));
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001024}
1025
shiqiane35fdd92008-12-10 05:08:54 +00001026// Tests that NotNull() matches any non-NULL pointer of any type.
1027TEST(NotNullTest, MatchesNonNullPointer) {
1028 Matcher<int*> m1 = NotNull();
1029 int* p1 = NULL;
1030 int n = 0;
1031 EXPECT_FALSE(m1.Matches(p1));
1032 EXPECT_TRUE(m1.Matches(&n));
1033
1034 Matcher<const char*> m2 = NotNull();
1035 const char* p2 = NULL;
1036 EXPECT_FALSE(m2.Matches(p2));
1037 EXPECT_TRUE(m2.Matches("hi"));
1038}
1039
vladlosev79b83502009-11-18 00:43:37 +00001040TEST(NotNullTest, LinkedPtr) {
1041 const Matcher<linked_ptr<int> > m = NotNull();
1042 const linked_ptr<int> null_p;
1043 const linked_ptr<int> non_null_p(new int);
1044
1045 EXPECT_FALSE(m.Matches(null_p));
1046 EXPECT_TRUE(m.Matches(non_null_p));
1047}
1048
1049TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1050 const Matcher<const linked_ptr<double>&> m = NotNull();
1051 const linked_ptr<double> null_p;
1052 const linked_ptr<double> non_null_p(new double);
1053
1054 EXPECT_FALSE(m.Matches(null_p));
1055 EXPECT_TRUE(m.Matches(non_null_p));
1056}
1057
vladloseve56daa72009-11-18 01:08:08 +00001058TEST(NotNullTest, ReferenceToConstScopedPtr) {
1059 const Matcher<const scoped_ptr<double>&> m = NotNull();
1060 const scoped_ptr<double> null_p;
1061 const scoped_ptr<double> non_null_p(new double);
1062
1063 EXPECT_FALSE(m.Matches(null_p));
1064 EXPECT_TRUE(m.Matches(non_null_p));
1065}
1066
shiqiane35fdd92008-12-10 05:08:54 +00001067// Tests that NotNull() describes itself properly.
1068TEST(NotNullTest, CanDescribeSelf) {
1069 Matcher<int*> m = NotNull();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001070 EXPECT_EQ("isn't NULL", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001071}
1072
1073// Tests that Ref(variable) matches an argument that references
1074// 'variable'.
1075TEST(RefTest, MatchesSameVariable) {
1076 int a = 0;
1077 int b = 0;
1078 Matcher<int&> m = Ref(a);
1079 EXPECT_TRUE(m.Matches(a));
1080 EXPECT_FALSE(m.Matches(b));
1081}
1082
1083// Tests that Ref(variable) describes itself properly.
1084TEST(RefTest, CanDescribeSelf) {
1085 int n = 5;
1086 Matcher<int&> m = Ref(n);
1087 stringstream ss;
1088 ss << "references the variable @" << &n << " 5";
1089 EXPECT_EQ(string(ss.str()), Describe(m));
1090}
1091
1092// Test that Ref(non_const_varialbe) can be used as a matcher for a
1093// const reference.
1094TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1095 int a = 0;
1096 int b = 0;
1097 Matcher<const int&> m = Ref(a);
1098 EXPECT_TRUE(m.Matches(a));
1099 EXPECT_FALSE(m.Matches(b));
1100}
1101
1102// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1103// used wherever Ref(base) can be used (Ref(derived) is a sub-type
1104// of Ref(base), but not vice versa.
1105
shiqiane35fdd92008-12-10 05:08:54 +00001106TEST(RefTest, IsCovariant) {
1107 Base base, base2;
1108 Derived derived;
1109 Matcher<const Base&> m1 = Ref(base);
1110 EXPECT_TRUE(m1.Matches(base));
1111 EXPECT_FALSE(m1.Matches(base2));
1112 EXPECT_FALSE(m1.Matches(derived));
1113
1114 m1 = Ref(derived);
1115 EXPECT_TRUE(m1.Matches(derived));
1116 EXPECT_FALSE(m1.Matches(base));
1117 EXPECT_FALSE(m1.Matches(base2));
1118}
1119
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001120TEST(RefTest, ExplainsResult) {
1121 int n = 0;
1122 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1123 StartsWith("which is located @"));
1124
1125 int m = 0;
1126 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1127 StartsWith("which is located @"));
1128}
1129
shiqiane35fdd92008-12-10 05:08:54 +00001130// Tests string comparison matchers.
1131
1132TEST(StrEqTest, MatchesEqualString) {
1133 Matcher<const char*> m = StrEq(string("Hello"));
1134 EXPECT_TRUE(m.Matches("Hello"));
1135 EXPECT_FALSE(m.Matches("hello"));
1136 EXPECT_FALSE(m.Matches(NULL));
1137
1138 Matcher<const string&> m2 = StrEq("Hello");
1139 EXPECT_TRUE(m2.Matches("Hello"));
1140 EXPECT_FALSE(m2.Matches("Hi"));
1141}
1142
1143TEST(StrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001144 Matcher<string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1145 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
shiqiane35fdd92008-12-10 05:08:54 +00001146 Describe(m));
1147
1148 string str("01204500800");
1149 str[3] = '\0';
1150 Matcher<string> m2 = StrEq(str);
1151 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1152 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1153 Matcher<string> m3 = StrEq(str);
1154 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1155}
1156
1157TEST(StrNeTest, MatchesUnequalString) {
1158 Matcher<const char*> m = StrNe("Hello");
1159 EXPECT_TRUE(m.Matches(""));
1160 EXPECT_TRUE(m.Matches(NULL));
1161 EXPECT_FALSE(m.Matches("Hello"));
1162
1163 Matcher<string> m2 = StrNe(string("Hello"));
1164 EXPECT_TRUE(m2.Matches("hello"));
1165 EXPECT_FALSE(m2.Matches("Hello"));
1166}
1167
1168TEST(StrNeTest, CanDescribeSelf) {
1169 Matcher<const char*> m = StrNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001170 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001171}
1172
1173TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1174 Matcher<const char*> m = StrCaseEq(string("Hello"));
1175 EXPECT_TRUE(m.Matches("Hello"));
1176 EXPECT_TRUE(m.Matches("hello"));
1177 EXPECT_FALSE(m.Matches("Hi"));
1178 EXPECT_FALSE(m.Matches(NULL));
1179
1180 Matcher<const string&> m2 = StrCaseEq("Hello");
1181 EXPECT_TRUE(m2.Matches("hello"));
1182 EXPECT_FALSE(m2.Matches("Hi"));
1183}
1184
1185TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1186 string str1("oabocdooeoo");
1187 string str2("OABOCDOOEOO");
1188 Matcher<const string&> m0 = StrCaseEq(str1);
1189 EXPECT_FALSE(m0.Matches(str2 + string(1, '\0')));
1190
1191 str1[3] = str2[3] = '\0';
1192 Matcher<const string&> m1 = StrCaseEq(str1);
1193 EXPECT_TRUE(m1.Matches(str2));
1194
1195 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1196 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1197 Matcher<const string&> m2 = StrCaseEq(str1);
1198 str1[9] = str2[9] = '\0';
1199 EXPECT_FALSE(m2.Matches(str2));
1200
1201 Matcher<const string&> m3 = StrCaseEq(str1);
1202 EXPECT_TRUE(m3.Matches(str2));
1203
1204 EXPECT_FALSE(m3.Matches(str2 + "x"));
1205 str2.append(1, '\0');
1206 EXPECT_FALSE(m3.Matches(str2));
1207 EXPECT_FALSE(m3.Matches(string(str2, 0, 9)));
1208}
1209
1210TEST(StrCaseEqTest, CanDescribeSelf) {
1211 Matcher<string> m = StrCaseEq("Hi");
1212 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1213}
1214
1215TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1216 Matcher<const char*> m = StrCaseNe("Hello");
1217 EXPECT_TRUE(m.Matches("Hi"));
1218 EXPECT_TRUE(m.Matches(NULL));
1219 EXPECT_FALSE(m.Matches("Hello"));
1220 EXPECT_FALSE(m.Matches("hello"));
1221
1222 Matcher<string> m2 = StrCaseNe(string("Hello"));
1223 EXPECT_TRUE(m2.Matches(""));
1224 EXPECT_FALSE(m2.Matches("Hello"));
1225}
1226
1227TEST(StrCaseNeTest, CanDescribeSelf) {
1228 Matcher<const char*> m = StrCaseNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001229 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001230}
1231
1232// Tests that HasSubstr() works for matching string-typed values.
1233TEST(HasSubstrTest, WorksForStringClasses) {
1234 const Matcher<string> m1 = HasSubstr("foo");
1235 EXPECT_TRUE(m1.Matches(string("I love food.")));
1236 EXPECT_FALSE(m1.Matches(string("tofo")));
1237
1238 const Matcher<const std::string&> m2 = HasSubstr("foo");
1239 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1240 EXPECT_FALSE(m2.Matches(std::string("tofo")));
1241}
1242
1243// Tests that HasSubstr() works for matching C-string-typed values.
1244TEST(HasSubstrTest, WorksForCStrings) {
1245 const Matcher<char*> m1 = HasSubstr("foo");
1246 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1247 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1248 EXPECT_FALSE(m1.Matches(NULL));
1249
1250 const Matcher<const char*> m2 = HasSubstr("foo");
1251 EXPECT_TRUE(m2.Matches("I love food."));
1252 EXPECT_FALSE(m2.Matches("tofo"));
1253 EXPECT_FALSE(m2.Matches(NULL));
1254}
1255
1256// Tests that HasSubstr(s) describes itself properly.
1257TEST(HasSubstrTest, CanDescribeSelf) {
1258 Matcher<string> m = HasSubstr("foo\n\"");
1259 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1260}
1261
zhanyong.wanb5937da2009-07-16 20:26:41 +00001262TEST(KeyTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001263 Matcher<const pair<std::string, int>&> m = Key("foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001264 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001265 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1266}
1267
1268TEST(KeyTest, ExplainsResult) {
1269 Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1270 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1271 Explain(m, make_pair(5, true)));
1272 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1273 Explain(m, make_pair(15, true)));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001274}
1275
1276TEST(KeyTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001277 pair<int, std::string> p(25, "foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001278 EXPECT_THAT(p, Key(25));
1279 EXPECT_THAT(p, Not(Key(42)));
1280 EXPECT_THAT(p, Key(Ge(20)));
1281 EXPECT_THAT(p, Not(Key(Lt(25))));
1282}
1283
1284TEST(KeyTest, SafelyCastsInnerMatcher) {
1285 Matcher<int> is_positive = Gt(0);
1286 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001287 pair<char, bool> p('a', true);
zhanyong.wanb5937da2009-07-16 20:26:41 +00001288 EXPECT_THAT(p, Key(is_positive));
1289 EXPECT_THAT(p, Not(Key(is_negative)));
1290}
1291
1292TEST(KeyTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001293 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001294 container.insert(make_pair(1, 'a'));
1295 container.insert(make_pair(2, 'b'));
1296 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001297 EXPECT_THAT(container, Contains(Key(1)));
1298 EXPECT_THAT(container, Not(Contains(Key(3))));
1299}
1300
1301TEST(KeyTest, InsideContainsUsingMultimap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001302 multimap<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001303 container.insert(make_pair(1, 'a'));
1304 container.insert(make_pair(2, 'b'));
1305 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001306
1307 EXPECT_THAT(container, Not(Contains(Key(25))));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001308 container.insert(make_pair(25, 'd'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001309 EXPECT_THAT(container, Contains(Key(25)));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001310 container.insert(make_pair(25, 'e'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001311 EXPECT_THAT(container, Contains(Key(25)));
1312
1313 EXPECT_THAT(container, Contains(Key(1)));
1314 EXPECT_THAT(container, Not(Contains(Key(3))));
1315}
1316
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001317TEST(PairTest, Typing) {
1318 // Test verifies the following type conversions can be compiled.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001319 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1320 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1321 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001322
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001323 Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1324 Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001325}
1326
1327TEST(PairTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001328 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001329 EXPECT_EQ("has a first field that is equal to \"foo\""
1330 ", and has a second field that is equal to 42",
1331 Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001332 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1333 ", or has a second field that isn't equal to 42",
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001334 DescribeNegation(m1));
1335 // Double and triple negation (1 or 2 times not and description of negation).
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001336 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1337 EXPECT_EQ("has a first field that isn't equal to 13"
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001338 ", and has a second field that is equal to 42",
1339 DescribeNegation(m2));
1340}
1341
1342TEST(PairTest, CanExplainMatchResultTo) {
zhanyong.wan82113312010-01-08 21:55:40 +00001343 // If neither field matches, Pair() should explain about the first
1344 // field.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001345 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001346 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001347 Explain(m, make_pair(-1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001348
zhanyong.wan82113312010-01-08 21:55:40 +00001349 // If the first field matches but the second doesn't, Pair() should
1350 // explain about the second field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001351 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001352 Explain(m, make_pair(1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001353
zhanyong.wan82113312010-01-08 21:55:40 +00001354 // If the first field doesn't match but the second does, Pair()
1355 // should explain about the first field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001356 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001357 Explain(m, make_pair(-1, 2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001358
zhanyong.wan82113312010-01-08 21:55:40 +00001359 // If both fields match, Pair() should explain about them both.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001360 EXPECT_EQ("whose both fields match, where the first field is a value "
1361 "which is 1 more than 0, and the second field is a value "
1362 "which is 2 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001363 Explain(m, make_pair(1, 2)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001364
1365 // If only the first match has an explanation, only this explanation should
1366 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001367 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001368 EXPECT_EQ("whose both fields match, where the first field is a value "
1369 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001370 Explain(explain_first, make_pair(1, 0)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001371
1372 // If only the second match has an explanation, only this explanation should
1373 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001374 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001375 EXPECT_EQ("whose both fields match, where the second field is a value "
1376 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001377 Explain(explain_second, make_pair(0, 1)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001378}
1379
1380TEST(PairTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001381 pair<int, std::string> p(25, "foo");
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001382
1383 // Both fields match.
1384 EXPECT_THAT(p, Pair(25, "foo"));
1385 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1386
1387 // 'first' doesnt' match, but 'second' matches.
1388 EXPECT_THAT(p, Not(Pair(42, "foo")));
1389 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1390
1391 // 'first' matches, but 'second' doesn't match.
1392 EXPECT_THAT(p, Not(Pair(25, "bar")));
1393 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1394
1395 // Neither field matches.
1396 EXPECT_THAT(p, Not(Pair(13, "bar")));
1397 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1398}
1399
1400TEST(PairTest, SafelyCastsInnerMatchers) {
1401 Matcher<int> is_positive = Gt(0);
1402 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001403 pair<char, bool> p('a', true);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001404 EXPECT_THAT(p, Pair(is_positive, _));
1405 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1406 EXPECT_THAT(p, Pair(_, is_positive));
1407 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1408}
1409
1410TEST(PairTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001411 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001412 container.insert(make_pair(1, 'a'));
1413 container.insert(make_pair(2, 'b'));
1414 container.insert(make_pair(4, 'c'));
zhanyong.wan95b12332009-09-25 18:55:50 +00001415 EXPECT_THAT(container, Contains(Pair(1, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001416 EXPECT_THAT(container, Contains(Pair(1, _)));
zhanyong.wan95b12332009-09-25 18:55:50 +00001417 EXPECT_THAT(container, Contains(Pair(_, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001418 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1419}
1420
shiqiane35fdd92008-12-10 05:08:54 +00001421// Tests StartsWith(s).
1422
1423TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1424 const Matcher<const char*> m1 = StartsWith(string(""));
1425 EXPECT_TRUE(m1.Matches("Hi"));
1426 EXPECT_TRUE(m1.Matches(""));
1427 EXPECT_FALSE(m1.Matches(NULL));
1428
1429 const Matcher<const string&> m2 = StartsWith("Hi");
1430 EXPECT_TRUE(m2.Matches("Hi"));
1431 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1432 EXPECT_TRUE(m2.Matches("High"));
1433 EXPECT_FALSE(m2.Matches("H"));
1434 EXPECT_FALSE(m2.Matches(" Hi"));
1435}
1436
1437TEST(StartsWithTest, CanDescribeSelf) {
1438 Matcher<const std::string> m = StartsWith("Hi");
1439 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1440}
1441
1442// Tests EndsWith(s).
1443
1444TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1445 const Matcher<const char*> m1 = EndsWith("");
1446 EXPECT_TRUE(m1.Matches("Hi"));
1447 EXPECT_TRUE(m1.Matches(""));
1448 EXPECT_FALSE(m1.Matches(NULL));
1449
1450 const Matcher<const string&> m2 = EndsWith(string("Hi"));
1451 EXPECT_TRUE(m2.Matches("Hi"));
1452 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1453 EXPECT_TRUE(m2.Matches("Super Hi"));
1454 EXPECT_FALSE(m2.Matches("i"));
1455 EXPECT_FALSE(m2.Matches("Hi "));
1456}
1457
1458TEST(EndsWithTest, CanDescribeSelf) {
1459 Matcher<const std::string> m = EndsWith("Hi");
1460 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1461}
1462
shiqiane35fdd92008-12-10 05:08:54 +00001463// Tests MatchesRegex().
1464
1465TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1466 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1467 EXPECT_TRUE(m1.Matches("az"));
1468 EXPECT_TRUE(m1.Matches("abcz"));
1469 EXPECT_FALSE(m1.Matches(NULL));
1470
1471 const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z"));
1472 EXPECT_TRUE(m2.Matches("azbz"));
1473 EXPECT_FALSE(m2.Matches("az1"));
1474 EXPECT_FALSE(m2.Matches("1az"));
1475}
1476
1477TEST(MatchesRegexTest, CanDescribeSelf) {
1478 Matcher<const std::string> m1 = MatchesRegex(string("Hi.*"));
1479 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1480
zhanyong.wand14aaed2010-01-14 05:36:32 +00001481 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1482 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001483}
1484
1485// Tests ContainsRegex().
1486
1487TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1488 const Matcher<const char*> m1 = ContainsRegex(string("a.*z"));
1489 EXPECT_TRUE(m1.Matches("az"));
1490 EXPECT_TRUE(m1.Matches("0abcz1"));
1491 EXPECT_FALSE(m1.Matches(NULL));
1492
1493 const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z"));
1494 EXPECT_TRUE(m2.Matches("azbz"));
1495 EXPECT_TRUE(m2.Matches("az1"));
1496 EXPECT_FALSE(m2.Matches("1a"));
1497}
1498
1499TEST(ContainsRegexTest, CanDescribeSelf) {
1500 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1501 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1502
zhanyong.wand14aaed2010-01-14 05:36:32 +00001503 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1504 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001505}
shiqiane35fdd92008-12-10 05:08:54 +00001506
1507// Tests for wide strings.
1508#if GTEST_HAS_STD_WSTRING
1509TEST(StdWideStrEqTest, MatchesEqual) {
1510 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1511 EXPECT_TRUE(m.Matches(L"Hello"));
1512 EXPECT_FALSE(m.Matches(L"hello"));
1513 EXPECT_FALSE(m.Matches(NULL));
1514
1515 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1516 EXPECT_TRUE(m2.Matches(L"Hello"));
1517 EXPECT_FALSE(m2.Matches(L"Hi"));
1518
1519 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1520 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1521 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1522
1523 ::std::wstring str(L"01204500800");
1524 str[3] = L'\0';
1525 Matcher<const ::std::wstring&> m4 = StrEq(str);
1526 EXPECT_TRUE(m4.Matches(str));
1527 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1528 Matcher<const ::std::wstring&> m5 = StrEq(str);
1529 EXPECT_TRUE(m5.Matches(str));
1530}
1531
1532TEST(StdWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001533 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1534 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001535 Describe(m));
1536
1537 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1538 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1539 Describe(m2));
1540
1541 ::std::wstring str(L"01204500800");
1542 str[3] = L'\0';
1543 Matcher<const ::std::wstring&> m4 = StrEq(str);
1544 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1545 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1546 Matcher<const ::std::wstring&> m5 = StrEq(str);
1547 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1548}
1549
1550TEST(StdWideStrNeTest, MatchesUnequalString) {
1551 Matcher<const wchar_t*> m = StrNe(L"Hello");
1552 EXPECT_TRUE(m.Matches(L""));
1553 EXPECT_TRUE(m.Matches(NULL));
1554 EXPECT_FALSE(m.Matches(L"Hello"));
1555
1556 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1557 EXPECT_TRUE(m2.Matches(L"hello"));
1558 EXPECT_FALSE(m2.Matches(L"Hello"));
1559}
1560
1561TEST(StdWideStrNeTest, CanDescribeSelf) {
1562 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001563 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001564}
1565
1566TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1567 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1568 EXPECT_TRUE(m.Matches(L"Hello"));
1569 EXPECT_TRUE(m.Matches(L"hello"));
1570 EXPECT_FALSE(m.Matches(L"Hi"));
1571 EXPECT_FALSE(m.Matches(NULL));
1572
1573 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1574 EXPECT_TRUE(m2.Matches(L"hello"));
1575 EXPECT_FALSE(m2.Matches(L"Hi"));
1576}
1577
1578TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1579 ::std::wstring str1(L"oabocdooeoo");
1580 ::std::wstring str2(L"OABOCDOOEOO");
1581 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1582 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1583
1584 str1[3] = str2[3] = L'\0';
1585 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1586 EXPECT_TRUE(m1.Matches(str2));
1587
1588 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1589 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1590 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1591 str1[9] = str2[9] = L'\0';
1592 EXPECT_FALSE(m2.Matches(str2));
1593
1594 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1595 EXPECT_TRUE(m3.Matches(str2));
1596
1597 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1598 str2.append(1, L'\0');
1599 EXPECT_FALSE(m3.Matches(str2));
1600 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1601}
1602
1603TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1604 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1605 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1606}
1607
1608TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1609 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1610 EXPECT_TRUE(m.Matches(L"Hi"));
1611 EXPECT_TRUE(m.Matches(NULL));
1612 EXPECT_FALSE(m.Matches(L"Hello"));
1613 EXPECT_FALSE(m.Matches(L"hello"));
1614
1615 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1616 EXPECT_TRUE(m2.Matches(L""));
1617 EXPECT_FALSE(m2.Matches(L"Hello"));
1618}
1619
1620TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1621 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001622 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001623}
1624
1625// Tests that HasSubstr() works for matching wstring-typed values.
1626TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1627 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1628 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1629 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1630
1631 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1632 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1633 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1634}
1635
1636// Tests that HasSubstr() works for matching C-wide-string-typed values.
1637TEST(StdWideHasSubstrTest, WorksForCStrings) {
1638 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1639 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1640 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1641 EXPECT_FALSE(m1.Matches(NULL));
1642
1643 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1644 EXPECT_TRUE(m2.Matches(L"I love food."));
1645 EXPECT_FALSE(m2.Matches(L"tofo"));
1646 EXPECT_FALSE(m2.Matches(NULL));
1647}
1648
1649// Tests that HasSubstr(s) describes itself properly.
1650TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1651 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1652 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1653}
1654
1655// Tests StartsWith(s).
1656
1657TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1658 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1659 EXPECT_TRUE(m1.Matches(L"Hi"));
1660 EXPECT_TRUE(m1.Matches(L""));
1661 EXPECT_FALSE(m1.Matches(NULL));
1662
1663 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1664 EXPECT_TRUE(m2.Matches(L"Hi"));
1665 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1666 EXPECT_TRUE(m2.Matches(L"High"));
1667 EXPECT_FALSE(m2.Matches(L"H"));
1668 EXPECT_FALSE(m2.Matches(L" Hi"));
1669}
1670
1671TEST(StdWideStartsWithTest, CanDescribeSelf) {
1672 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
1673 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1674}
1675
1676// Tests EndsWith(s).
1677
1678TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
1679 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1680 EXPECT_TRUE(m1.Matches(L"Hi"));
1681 EXPECT_TRUE(m1.Matches(L""));
1682 EXPECT_FALSE(m1.Matches(NULL));
1683
1684 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
1685 EXPECT_TRUE(m2.Matches(L"Hi"));
1686 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1687 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1688 EXPECT_FALSE(m2.Matches(L"i"));
1689 EXPECT_FALSE(m2.Matches(L"Hi "));
1690}
1691
1692TEST(StdWideEndsWithTest, CanDescribeSelf) {
1693 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
1694 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1695}
1696
1697#endif // GTEST_HAS_STD_WSTRING
1698
1699#if GTEST_HAS_GLOBAL_WSTRING
1700TEST(GlobalWideStrEqTest, MatchesEqual) {
1701 Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
1702 EXPECT_TRUE(m.Matches(L"Hello"));
1703 EXPECT_FALSE(m.Matches(L"hello"));
1704 EXPECT_FALSE(m.Matches(NULL));
1705
1706 Matcher<const ::wstring&> m2 = StrEq(L"Hello");
1707 EXPECT_TRUE(m2.Matches(L"Hello"));
1708 EXPECT_FALSE(m2.Matches(L"Hi"));
1709
1710 Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1711 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1712 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1713
1714 ::wstring str(L"01204500800");
1715 str[3] = L'\0';
1716 Matcher<const ::wstring&> m4 = StrEq(str);
1717 EXPECT_TRUE(m4.Matches(str));
1718 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1719 Matcher<const ::wstring&> m5 = StrEq(str);
1720 EXPECT_TRUE(m5.Matches(str));
1721}
1722
1723TEST(GlobalWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001724 Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1725 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001726 Describe(m));
1727
1728 Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1729 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1730 Describe(m2));
1731
1732 ::wstring str(L"01204500800");
1733 str[3] = L'\0';
1734 Matcher<const ::wstring&> m4 = StrEq(str);
1735 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1736 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1737 Matcher<const ::wstring&> m5 = StrEq(str);
1738 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1739}
1740
1741TEST(GlobalWideStrNeTest, MatchesUnequalString) {
1742 Matcher<const wchar_t*> m = StrNe(L"Hello");
1743 EXPECT_TRUE(m.Matches(L""));
1744 EXPECT_TRUE(m.Matches(NULL));
1745 EXPECT_FALSE(m.Matches(L"Hello"));
1746
1747 Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
1748 EXPECT_TRUE(m2.Matches(L"hello"));
1749 EXPECT_FALSE(m2.Matches(L"Hello"));
1750}
1751
1752TEST(GlobalWideStrNeTest, CanDescribeSelf) {
1753 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001754 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001755}
1756
1757TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1758 Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
1759 EXPECT_TRUE(m.Matches(L"Hello"));
1760 EXPECT_TRUE(m.Matches(L"hello"));
1761 EXPECT_FALSE(m.Matches(L"Hi"));
1762 EXPECT_FALSE(m.Matches(NULL));
1763
1764 Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
1765 EXPECT_TRUE(m2.Matches(L"hello"));
1766 EXPECT_FALSE(m2.Matches(L"Hi"));
1767}
1768
1769TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1770 ::wstring str1(L"oabocdooeoo");
1771 ::wstring str2(L"OABOCDOOEOO");
1772 Matcher<const ::wstring&> m0 = StrCaseEq(str1);
1773 EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
1774
1775 str1[3] = str2[3] = L'\0';
1776 Matcher<const ::wstring&> m1 = StrCaseEq(str1);
1777 EXPECT_TRUE(m1.Matches(str2));
1778
1779 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1780 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1781 Matcher<const ::wstring&> m2 = StrCaseEq(str1);
1782 str1[9] = str2[9] = L'\0';
1783 EXPECT_FALSE(m2.Matches(str2));
1784
1785 Matcher<const ::wstring&> m3 = StrCaseEq(str1);
1786 EXPECT_TRUE(m3.Matches(str2));
1787
1788 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1789 str2.append(1, L'\0');
1790 EXPECT_FALSE(m3.Matches(str2));
1791 EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
1792}
1793
1794TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
1795 Matcher< ::wstring> m = StrCaseEq(L"Hi");
1796 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1797}
1798
1799TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1800 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1801 EXPECT_TRUE(m.Matches(L"Hi"));
1802 EXPECT_TRUE(m.Matches(NULL));
1803 EXPECT_FALSE(m.Matches(L"Hello"));
1804 EXPECT_FALSE(m.Matches(L"hello"));
1805
1806 Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
1807 EXPECT_TRUE(m2.Matches(L""));
1808 EXPECT_FALSE(m2.Matches(L"Hello"));
1809}
1810
1811TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
1812 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001813 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001814}
1815
1816// Tests that HasSubstr() works for matching wstring-typed values.
1817TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
1818 const Matcher< ::wstring> m1 = HasSubstr(L"foo");
1819 EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
1820 EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
1821
1822 const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
1823 EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
1824 EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
1825}
1826
1827// Tests that HasSubstr() works for matching C-wide-string-typed values.
1828TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
1829 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1830 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1831 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1832 EXPECT_FALSE(m1.Matches(NULL));
1833
1834 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1835 EXPECT_TRUE(m2.Matches(L"I love food."));
1836 EXPECT_FALSE(m2.Matches(L"tofo"));
1837 EXPECT_FALSE(m2.Matches(NULL));
1838}
1839
1840// Tests that HasSubstr(s) describes itself properly.
1841TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
1842 Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
1843 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1844}
1845
1846// Tests StartsWith(s).
1847
1848TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
1849 const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
1850 EXPECT_TRUE(m1.Matches(L"Hi"));
1851 EXPECT_TRUE(m1.Matches(L""));
1852 EXPECT_FALSE(m1.Matches(NULL));
1853
1854 const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
1855 EXPECT_TRUE(m2.Matches(L"Hi"));
1856 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1857 EXPECT_TRUE(m2.Matches(L"High"));
1858 EXPECT_FALSE(m2.Matches(L"H"));
1859 EXPECT_FALSE(m2.Matches(L" Hi"));
1860}
1861
1862TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
1863 Matcher<const ::wstring> m = StartsWith(L"Hi");
1864 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1865}
1866
1867// Tests EndsWith(s).
1868
1869TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
1870 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1871 EXPECT_TRUE(m1.Matches(L"Hi"));
1872 EXPECT_TRUE(m1.Matches(L""));
1873 EXPECT_FALSE(m1.Matches(NULL));
1874
1875 const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
1876 EXPECT_TRUE(m2.Matches(L"Hi"));
1877 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1878 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1879 EXPECT_FALSE(m2.Matches(L"i"));
1880 EXPECT_FALSE(m2.Matches(L"Hi "));
1881}
1882
1883TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
1884 Matcher<const ::wstring> m = EndsWith(L"Hi");
1885 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1886}
1887
1888#endif // GTEST_HAS_GLOBAL_WSTRING
1889
1890
1891typedef ::std::tr1::tuple<long, int> Tuple2; // NOLINT
1892
1893// Tests that Eq() matches a 2-tuple where the first field == the
1894// second field.
1895TEST(Eq2Test, MatchesEqualArguments) {
1896 Matcher<const Tuple2&> m = Eq();
1897 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1898 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1899}
1900
1901// Tests that Eq() describes itself properly.
1902TEST(Eq2Test, CanDescribeSelf) {
1903 Matcher<const Tuple2&> m = Eq();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001904 EXPECT_EQ("are an equal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001905}
1906
1907// Tests that Ge() matches a 2-tuple where the first field >= the
1908// second field.
1909TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
1910 Matcher<const Tuple2&> m = Ge();
1911 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1912 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1913 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1914}
1915
1916// Tests that Ge() describes itself properly.
1917TEST(Ge2Test, CanDescribeSelf) {
1918 Matcher<const Tuple2&> m = Ge();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001919 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001920}
1921
1922// Tests that Gt() matches a 2-tuple where the first field > the
1923// second field.
1924TEST(Gt2Test, MatchesGreaterThanArguments) {
1925 Matcher<const Tuple2&> m = Gt();
1926 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1927 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1928 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1929}
1930
1931// Tests that Gt() describes itself properly.
1932TEST(Gt2Test, CanDescribeSelf) {
1933 Matcher<const Tuple2&> m = Gt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001934 EXPECT_EQ("are a pair where the first > the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001935}
1936
1937// Tests that Le() matches a 2-tuple where the first field <= the
1938// second field.
1939TEST(Le2Test, MatchesLessThanOrEqualArguments) {
1940 Matcher<const Tuple2&> m = Le();
1941 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1942 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1943 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1944}
1945
1946// Tests that Le() describes itself properly.
1947TEST(Le2Test, CanDescribeSelf) {
1948 Matcher<const Tuple2&> m = Le();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001949 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001950}
1951
1952// Tests that Lt() matches a 2-tuple where the first field < the
1953// second field.
1954TEST(Lt2Test, MatchesLessThanArguments) {
1955 Matcher<const Tuple2&> m = Lt();
1956 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1957 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1958 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1959}
1960
1961// Tests that Lt() describes itself properly.
1962TEST(Lt2Test, CanDescribeSelf) {
1963 Matcher<const Tuple2&> m = Lt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001964 EXPECT_EQ("are a pair where the first < the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001965}
1966
1967// Tests that Ne() matches a 2-tuple where the first field != the
1968// second field.
1969TEST(Ne2Test, MatchesUnequalArguments) {
1970 Matcher<const Tuple2&> m = Ne();
1971 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1972 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1973 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1974}
1975
1976// Tests that Ne() describes itself properly.
1977TEST(Ne2Test, CanDescribeSelf) {
1978 Matcher<const Tuple2&> m = Ne();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001979 EXPECT_EQ("are an unequal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001980}
1981
1982// Tests that Not(m) matches any value that doesn't match m.
1983TEST(NotTest, NegatesMatcher) {
1984 Matcher<int> m;
1985 m = Not(Eq(2));
1986 EXPECT_TRUE(m.Matches(3));
1987 EXPECT_FALSE(m.Matches(2));
1988}
1989
1990// Tests that Not(m) describes itself properly.
1991TEST(NotTest, CanDescribeSelf) {
1992 Matcher<int> m = Not(Eq(5));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001993 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001994}
1995
zhanyong.wan18490652009-05-11 18:54:08 +00001996// Tests that monomorphic matchers are safely cast by the Not matcher.
1997TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
1998 // greater_than_5 is a monomorphic matcher.
1999 Matcher<int> greater_than_5 = Gt(5);
2000
2001 Matcher<const int&> m = Not(greater_than_5);
2002 Matcher<int&> m2 = Not(greater_than_5);
2003 Matcher<int&> m3 = Not(m);
2004}
2005
zhanyong.wan02c15052010-06-09 19:21:30 +00002006// Helper to allow easy testing of AllOf matchers with num parameters.
2007void AllOfMatches(int num, const Matcher<int>& m) {
2008 SCOPED_TRACE(Describe(m));
2009 EXPECT_TRUE(m.Matches(0));
2010 for (int i = 1; i <= num; ++i) {
2011 EXPECT_FALSE(m.Matches(i));
2012 }
2013 EXPECT_TRUE(m.Matches(num + 1));
2014}
2015
shiqiane35fdd92008-12-10 05:08:54 +00002016// Tests that AllOf(m1, ..., mn) matches any value that matches all of
2017// the given matchers.
2018TEST(AllOfTest, MatchesWhenAllMatch) {
2019 Matcher<int> m;
2020 m = AllOf(Le(2), Ge(1));
2021 EXPECT_TRUE(m.Matches(1));
2022 EXPECT_TRUE(m.Matches(2));
2023 EXPECT_FALSE(m.Matches(0));
2024 EXPECT_FALSE(m.Matches(3));
2025
2026 m = AllOf(Gt(0), Ne(1), Ne(2));
2027 EXPECT_TRUE(m.Matches(3));
2028 EXPECT_FALSE(m.Matches(2));
2029 EXPECT_FALSE(m.Matches(1));
2030 EXPECT_FALSE(m.Matches(0));
2031
2032 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2033 EXPECT_TRUE(m.Matches(4));
2034 EXPECT_FALSE(m.Matches(3));
2035 EXPECT_FALSE(m.Matches(2));
2036 EXPECT_FALSE(m.Matches(1));
2037 EXPECT_FALSE(m.Matches(0));
2038
2039 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2040 EXPECT_TRUE(m.Matches(0));
2041 EXPECT_TRUE(m.Matches(1));
2042 EXPECT_FALSE(m.Matches(3));
zhanyong.wan02c15052010-06-09 19:21:30 +00002043
2044 // The following tests for varying number of sub-matchers. Due to the way
2045 // the sub-matchers are handled it is enough to test every sub-matcher once
2046 // with sub-matchers using the same matcher type. Varying matcher types are
2047 // checked for above.
2048 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2049 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2050 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2051 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2052 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2053 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2054 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2055 Ne(8)));
2056 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2057 Ne(8), Ne(9)));
2058 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2059 Ne(9), Ne(10)));
shiqiane35fdd92008-12-10 05:08:54 +00002060}
2061
zhanyong.wan616180e2013-06-18 18:49:51 +00002062#if GTEST_LANG_CXX11
2063// Tests the variadic version of the AllOfMatcher.
2064TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
2065 // Make sure AllOf is defined in the right namespace and does not depend on
2066 // ADL.
2067 ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2068 Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2069 Ne(9), Ne(10), Ne(11));
2070 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))"));
2071 AllOfMatches(11, m);
2072 AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2073 Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
2074 Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22),
2075 Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29),
2076 Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36),
2077 Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43),
2078 Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2079 Ne(50)));
2080}
2081
2082#endif // GTEST_LANG_CXX11
2083
shiqiane35fdd92008-12-10 05:08:54 +00002084// Tests that AllOf(m1, ..., mn) describes itself properly.
2085TEST(AllOfTest, CanDescribeSelf) {
2086 Matcher<int> m;
2087 m = AllOf(Le(2), Ge(1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002088 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002089
2090 m = AllOf(Gt(0), Ne(1), Ne(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002091 EXPECT_EQ("(is > 0) and "
2092 "((isn't equal to 1) and "
2093 "(isn't equal to 2))",
shiqiane35fdd92008-12-10 05:08:54 +00002094 Describe(m));
2095
2096
2097 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002098 EXPECT_EQ("((is > 0) and "
2099 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002100 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002101 "(isn't equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002102 Describe(m));
2103
2104
2105 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002106 EXPECT_EQ("((is >= 0) and "
2107 "(is < 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002108 "((isn't equal to 3) and "
2109 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002110 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002111 Describe(m));
2112}
2113
2114// Tests that AllOf(m1, ..., mn) describes its negation properly.
2115TEST(AllOfTest, CanDescribeNegation) {
2116 Matcher<int> m;
2117 m = AllOf(Le(2), Ge(1));
2118 EXPECT_EQ("(isn't <= 2) or "
2119 "(isn't >= 1)",
2120 DescribeNegation(m));
2121
2122 m = AllOf(Gt(0), Ne(1), Ne(2));
2123 EXPECT_EQ("(isn't > 0) or "
2124 "((is equal to 1) or "
2125 "(is equal to 2))",
2126 DescribeNegation(m));
2127
2128
2129 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002130 EXPECT_EQ("((isn't > 0) or "
2131 "(is equal to 1)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002132 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002133 "(is equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002134 DescribeNegation(m));
2135
2136
2137 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002138 EXPECT_EQ("((isn't >= 0) or "
2139 "(isn't < 10)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002140 "((is equal to 3) or "
2141 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002142 "(is equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002143 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00002144}
2145
zhanyong.wan18490652009-05-11 18:54:08 +00002146// Tests that monomorphic matchers are safely cast by the AllOf matcher.
2147TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2148 // greater_than_5 and less_than_10 are monomorphic matchers.
2149 Matcher<int> greater_than_5 = Gt(5);
2150 Matcher<int> less_than_10 = Lt(10);
2151
2152 Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2153 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2154 Matcher<int&> m3 = AllOf(greater_than_5, m2);
2155
2156 // Tests that BothOf works when composing itself.
2157 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2158 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2159}
2160
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002161TEST(AllOfTest, ExplainsResult) {
2162 Matcher<int> m;
2163
2164 // Successful match. Both matchers need to explain. The second
2165 // matcher doesn't give an explanation, so only the first matcher's
2166 // explanation is printed.
2167 m = AllOf(GreaterThan(10), Lt(30));
2168 EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2169
2170 // Successful match. Both matchers need to explain.
2171 m = AllOf(GreaterThan(10), GreaterThan(20));
2172 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2173 Explain(m, 30));
2174
2175 // Successful match. All matchers need to explain. The second
2176 // matcher doesn't given an explanation.
2177 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2178 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2179 Explain(m, 25));
2180
2181 // Successful match. All matchers need to explain.
2182 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2183 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2184 "and which is 10 more than 30",
2185 Explain(m, 40));
2186
2187 // Failed match. The first matcher, which failed, needs to
2188 // explain.
2189 m = AllOf(GreaterThan(10), GreaterThan(20));
2190 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2191
2192 // Failed match. The second matcher, which failed, needs to
2193 // explain. Since it doesn't given an explanation, nothing is
2194 // printed.
2195 m = AllOf(GreaterThan(10), Lt(30));
2196 EXPECT_EQ("", Explain(m, 40));
2197
2198 // Failed match. The second matcher, which failed, needs to
2199 // explain.
2200 m = AllOf(GreaterThan(10), GreaterThan(20));
2201 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2202}
2203
zhanyong.wan02c15052010-06-09 19:21:30 +00002204// Helper to allow easy testing of AnyOf matchers with num parameters.
2205void AnyOfMatches(int num, const Matcher<int>& m) {
2206 SCOPED_TRACE(Describe(m));
2207 EXPECT_FALSE(m.Matches(0));
2208 for (int i = 1; i <= num; ++i) {
2209 EXPECT_TRUE(m.Matches(i));
2210 }
2211 EXPECT_FALSE(m.Matches(num + 1));
2212}
2213
shiqiane35fdd92008-12-10 05:08:54 +00002214// Tests that AnyOf(m1, ..., mn) matches any value that matches at
2215// least one of the given matchers.
2216TEST(AnyOfTest, MatchesWhenAnyMatches) {
2217 Matcher<int> m;
2218 m = AnyOf(Le(1), Ge(3));
2219 EXPECT_TRUE(m.Matches(1));
2220 EXPECT_TRUE(m.Matches(4));
2221 EXPECT_FALSE(m.Matches(2));
2222
2223 m = AnyOf(Lt(0), Eq(1), Eq(2));
2224 EXPECT_TRUE(m.Matches(-1));
2225 EXPECT_TRUE(m.Matches(1));
2226 EXPECT_TRUE(m.Matches(2));
2227 EXPECT_FALSE(m.Matches(0));
2228
2229 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2230 EXPECT_TRUE(m.Matches(-1));
2231 EXPECT_TRUE(m.Matches(1));
2232 EXPECT_TRUE(m.Matches(2));
2233 EXPECT_TRUE(m.Matches(3));
2234 EXPECT_FALSE(m.Matches(0));
2235
2236 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2237 EXPECT_TRUE(m.Matches(0));
2238 EXPECT_TRUE(m.Matches(11));
2239 EXPECT_TRUE(m.Matches(3));
2240 EXPECT_FALSE(m.Matches(2));
zhanyong.wan02c15052010-06-09 19:21:30 +00002241
2242 // The following tests for varying number of sub-matchers. Due to the way
2243 // the sub-matchers are handled it is enough to test every sub-matcher once
2244 // with sub-matchers using the same matcher type. Varying matcher types are
2245 // checked for above.
2246 AnyOfMatches(2, AnyOf(1, 2));
2247 AnyOfMatches(3, AnyOf(1, 2, 3));
2248 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2249 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2250 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2251 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2252 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2253 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2254 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
shiqiane35fdd92008-12-10 05:08:54 +00002255}
2256
zhanyong.wan616180e2013-06-18 18:49:51 +00002257#if GTEST_LANG_CXX11
2258// Tests the variadic version of the AnyOfMatcher.
2259TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2260 // Also make sure AnyOf is defined in the right namespace and does not depend
2261 // on ADL.
2262 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2263
2264 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))"));
2265 AnyOfMatches(11, m);
2266 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2267 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2268 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2269 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2270 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2271}
2272
2273#endif // GTEST_LANG_CXX11
2274
shiqiane35fdd92008-12-10 05:08:54 +00002275// Tests that AnyOf(m1, ..., mn) describes itself properly.
2276TEST(AnyOfTest, CanDescribeSelf) {
2277 Matcher<int> m;
2278 m = AnyOf(Le(1), Ge(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002279 EXPECT_EQ("(is <= 1) or (is >= 3)",
shiqiane35fdd92008-12-10 05:08:54 +00002280 Describe(m));
2281
2282 m = AnyOf(Lt(0), Eq(1), Eq(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002283 EXPECT_EQ("(is < 0) or "
shiqiane35fdd92008-12-10 05:08:54 +00002284 "((is equal to 1) or (is equal to 2))",
2285 Describe(m));
2286
2287 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002288 EXPECT_EQ("((is < 0) or "
2289 "(is equal to 1)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002290 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002291 "(is equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002292 Describe(m));
2293
2294 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002295 EXPECT_EQ("((is <= 0) or "
2296 "(is > 10)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002297 "((is equal to 3) or "
2298 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002299 "(is equal to 7)))",
shiqiane35fdd92008-12-10 05:08:54 +00002300 Describe(m));
2301}
2302
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002303// Tests that AnyOf(m1, ..., mn) describes its negation properly.
2304TEST(AnyOfTest, CanDescribeNegation) {
2305 Matcher<int> m;
2306 m = AnyOf(Le(1), Ge(3));
2307 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2308 DescribeNegation(m));
2309
2310 m = AnyOf(Lt(0), Eq(1), Eq(2));
2311 EXPECT_EQ("(isn't < 0) and "
2312 "((isn't equal to 1) and (isn't equal to 2))",
2313 DescribeNegation(m));
2314
2315 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002316 EXPECT_EQ("((isn't < 0) and "
2317 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002318 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002319 "(isn't equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002320 DescribeNegation(m));
2321
2322 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002323 EXPECT_EQ("((isn't <= 0) and "
2324 "(isn't > 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002325 "((isn't equal to 3) and "
2326 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002327 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002328 DescribeNegation(m));
2329}
2330
zhanyong.wan18490652009-05-11 18:54:08 +00002331// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2332TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2333 // greater_than_5 and less_than_10 are monomorphic matchers.
2334 Matcher<int> greater_than_5 = Gt(5);
2335 Matcher<int> less_than_10 = Lt(10);
2336
2337 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2338 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2339 Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2340
2341 // Tests that EitherOf works when composing itself.
2342 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2343 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2344}
2345
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002346TEST(AnyOfTest, ExplainsResult) {
2347 Matcher<int> m;
2348
2349 // Failed match. Both matchers need to explain. The second
2350 // matcher doesn't give an explanation, so only the first matcher's
2351 // explanation is printed.
2352 m = AnyOf(GreaterThan(10), Lt(0));
2353 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2354
2355 // Failed match. Both matchers need to explain.
2356 m = AnyOf(GreaterThan(10), GreaterThan(20));
2357 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2358 Explain(m, 5));
2359
2360 // Failed match. All matchers need to explain. The second
2361 // matcher doesn't given an explanation.
2362 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2363 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2364 Explain(m, 5));
2365
2366 // Failed match. All matchers need to explain.
2367 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2368 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2369 "and which is 25 less than 30",
2370 Explain(m, 5));
2371
2372 // Successful match. The first matcher, which succeeded, needs to
2373 // explain.
2374 m = AnyOf(GreaterThan(10), GreaterThan(20));
2375 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2376
2377 // Successful match. The second matcher, which succeeded, needs to
2378 // explain. Since it doesn't given an explanation, nothing is
2379 // printed.
2380 m = AnyOf(GreaterThan(10), Lt(30));
2381 EXPECT_EQ("", Explain(m, 0));
2382
2383 // Successful match. The second matcher, which succeeded, needs to
2384 // explain.
2385 m = AnyOf(GreaterThan(30), GreaterThan(20));
2386 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2387}
2388
shiqiane35fdd92008-12-10 05:08:54 +00002389// The following predicate function and predicate functor are for
2390// testing the Truly(predicate) matcher.
2391
2392// Returns non-zero if the input is positive. Note that the return
2393// type of this function is not bool. It's OK as Truly() accepts any
2394// unary function or functor whose return type can be implicitly
2395// converted to bool.
2396int IsPositive(double x) {
2397 return x > 0 ? 1 : 0;
2398}
2399
2400// This functor returns true if the input is greater than the given
2401// number.
2402class IsGreaterThan {
2403 public:
2404 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2405
2406 bool operator()(int n) const { return n > threshold_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002407
shiqiane35fdd92008-12-10 05:08:54 +00002408 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002409 int threshold_;
shiqiane35fdd92008-12-10 05:08:54 +00002410};
2411
2412// For testing Truly().
2413const int foo = 0;
2414
2415// This predicate returns true iff the argument references foo and has
2416// a zero value.
2417bool ReferencesFooAndIsZero(const int& n) {
2418 return (&n == &foo) && (n == 0);
2419}
2420
2421// Tests that Truly(predicate) matches what satisfies the given
2422// predicate.
2423TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2424 Matcher<double> m = Truly(IsPositive);
2425 EXPECT_TRUE(m.Matches(2.0));
2426 EXPECT_FALSE(m.Matches(-1.5));
2427}
2428
2429// Tests that Truly(predicate_functor) works too.
2430TEST(TrulyTest, CanBeUsedWithFunctor) {
2431 Matcher<int> m = Truly(IsGreaterThan(5));
2432 EXPECT_TRUE(m.Matches(6));
2433 EXPECT_FALSE(m.Matches(4));
2434}
2435
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00002436// A class that can be implicitly converted to bool.
2437class ConvertibleToBool {
2438 public:
2439 explicit ConvertibleToBool(int number) : number_(number) {}
2440 operator bool() const { return number_ != 0; }
2441
2442 private:
2443 int number_;
2444};
2445
2446ConvertibleToBool IsNotZero(int number) {
2447 return ConvertibleToBool(number);
2448}
2449
2450// Tests that the predicate used in Truly() may return a class that's
2451// implicitly convertible to bool, even when the class has no
2452// operator!().
2453TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2454 Matcher<int> m = Truly(IsNotZero);
2455 EXPECT_TRUE(m.Matches(1));
2456 EXPECT_FALSE(m.Matches(0));
2457}
2458
shiqiane35fdd92008-12-10 05:08:54 +00002459// Tests that Truly(predicate) can describe itself properly.
2460TEST(TrulyTest, CanDescribeSelf) {
2461 Matcher<double> m = Truly(IsPositive);
2462 EXPECT_EQ("satisfies the given predicate",
2463 Describe(m));
2464}
2465
2466// Tests that Truly(predicate) works when the matcher takes its
2467// argument by reference.
2468TEST(TrulyTest, WorksForByRefArguments) {
2469 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2470 EXPECT_TRUE(m.Matches(foo));
2471 int n = 0;
2472 EXPECT_FALSE(m.Matches(n));
2473}
2474
2475// Tests that Matches(m) is a predicate satisfied by whatever that
2476// matches matcher m.
2477TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2478 EXPECT_TRUE(Matches(Ge(0))(1));
2479 EXPECT_FALSE(Matches(Eq('a'))('b'));
2480}
2481
2482// Tests that Matches(m) works when the matcher takes its argument by
2483// reference.
2484TEST(MatchesTest, WorksOnByRefArguments) {
2485 int m = 0, n = 0;
2486 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2487 EXPECT_FALSE(Matches(Ref(m))(n));
2488}
2489
2490// Tests that a Matcher on non-reference type can be used in
2491// Matches().
2492TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
2493 Matcher<int> eq5 = Eq(5);
2494 EXPECT_TRUE(Matches(eq5)(5));
2495 EXPECT_FALSE(Matches(eq5)(2));
2496}
2497
zhanyong.wanb8243162009-06-04 05:48:20 +00002498// Tests Value(value, matcher). Since Value() is a simple wrapper for
2499// Matches(), which has been tested already, we don't spend a lot of
2500// effort on testing Value().
2501TEST(ValueTest, WorksWithPolymorphicMatcher) {
2502 EXPECT_TRUE(Value("hi", StartsWith("h")));
2503 EXPECT_FALSE(Value(5, Gt(10)));
2504}
2505
2506TEST(ValueTest, WorksWithMonomorphicMatcher) {
2507 const Matcher<int> is_zero = Eq(0);
2508 EXPECT_TRUE(Value(0, is_zero));
2509 EXPECT_FALSE(Value('a', is_zero));
2510
2511 int n = 0;
2512 const Matcher<const int&> ref_n = Ref(n);
2513 EXPECT_TRUE(Value(n, ref_n));
2514 EXPECT_FALSE(Value(1, ref_n));
2515}
2516
zhanyong.wana862f1d2010-03-15 21:23:04 +00002517TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002518 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002519 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002520 EXPECT_EQ("% 2 == 0", listener1.str());
2521
2522 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002523 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002524 EXPECT_EQ("", listener2.str());
2525}
2526
zhanyong.wana862f1d2010-03-15 21:23:04 +00002527TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002528 const Matcher<int> is_even = PolymorphicIsEven();
2529 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002530 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002531 EXPECT_EQ("% 2 == 0", listener1.str());
2532
2533 const Matcher<const double&> is_zero = Eq(0);
2534 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002535 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002536 EXPECT_EQ("", listener2.str());
2537}
2538
zhanyong.wana862f1d2010-03-15 21:23:04 +00002539MATCHER_P(Really, inner_matcher, "") {
2540 return ExplainMatchResult(inner_matcher, arg, result_listener);
2541}
2542
2543TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
2544 EXPECT_THAT(0, Really(Eq(0)));
2545}
2546
zhanyong.wanbf550852009-06-09 06:09:53 +00002547TEST(AllArgsTest, WorksForTuple) {
2548 EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
2549 EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
2550}
2551
2552TEST(AllArgsTest, WorksForNonTuple) {
2553 EXPECT_THAT(42, AllArgs(Gt(0)));
2554 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
2555}
2556
2557class AllArgsHelper {
2558 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002559 AllArgsHelper() {}
2560
zhanyong.wanbf550852009-06-09 06:09:53 +00002561 MOCK_METHOD2(Helper, int(char x, int y));
zhanyong.wan32de5f52009-12-23 00:13:23 +00002562
2563 private:
2564 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
zhanyong.wanbf550852009-06-09 06:09:53 +00002565};
2566
2567TEST(AllArgsTest, WorksInWithClause) {
2568 AllArgsHelper helper;
2569 ON_CALL(helper, Helper(_, _))
2570 .With(AllArgs(Lt()))
2571 .WillByDefault(Return(1));
2572 EXPECT_CALL(helper, Helper(_, _));
2573 EXPECT_CALL(helper, Helper(_, _))
2574 .With(AllArgs(Gt()))
2575 .WillOnce(Return(2));
2576
2577 EXPECT_EQ(1, helper.Helper('\1', 2));
2578 EXPECT_EQ(2, helper.Helper('a', 1));
2579}
2580
shiqiane35fdd92008-12-10 05:08:54 +00002581// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2582// matches the matcher.
2583TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
2584 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
2585 ASSERT_THAT("Foo", EndsWith("oo"));
2586 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
2587 EXPECT_THAT("Hello", StartsWith("Hell"));
2588}
2589
2590// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2591// doesn't match the matcher.
2592TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
2593 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
2594 // which cannot reference auto variables.
zhanyong.wan736baa82010-09-27 17:44:16 +00002595 static unsigned short n; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00002596 n = 5;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002597
2598 // VC++ prior to version 8.0 SP1 has a bug where it will not see any
2599 // functions declared in the namespace scope from within nested classes.
2600 // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
2601 // namespace-level functions invoked inside them need to be explicitly
2602 // resolved.
2603 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
shiqiane35fdd92008-12-10 05:08:54 +00002604 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002605 "Expected: is > 10\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002606 " Actual: 5" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002607 n = 0;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002608 EXPECT_NONFATAL_FAILURE(
2609 EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
2610 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002611 "Expected: (is <= 7) and (is >= 5)\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002612 " Actual: 0" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002613}
2614
2615// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
2616// has a reference type.
2617TEST(MatcherAssertionTest, WorksForByRefArguments) {
2618 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
2619 // reference auto variables.
2620 static int n;
2621 n = 0;
2622 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002623 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
shiqiane35fdd92008-12-10 05:08:54 +00002624 "Value of: n\n"
2625 "Expected: does not reference the variable @");
2626 // Tests the "Actual" part.
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002627 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
zhanyong.wan736baa82010-09-27 17:44:16 +00002628 "Actual: 0" + OfType("int") + ", which is located @");
shiqiane35fdd92008-12-10 05:08:54 +00002629}
2630
zhanyong.wan95b12332009-09-25 18:55:50 +00002631#if !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002632// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
2633// monomorphic.
zhanyong.wan95b12332009-09-25 18:55:50 +00002634
2635// ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
2636// Symbian compiler: it tries to compile
2637// template<T, U> class MatcherCastImpl { ...
zhanyong.wandb22c222010-01-28 21:52:29 +00002638// virtual bool MatchAndExplain(T x, ...) const {
2639// return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
zhanyong.wan95b12332009-09-25 18:55:50 +00002640// with U == string and T == const char*
2641// With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
2642// the compiler silently crashes with no output.
2643// If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
2644// the code compiles but the converted string is bogus.
shiqiane35fdd92008-12-10 05:08:54 +00002645TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
2646 Matcher<const char*> starts_with_he = StartsWith("he");
2647 ASSERT_THAT("hello", starts_with_he);
2648
2649 Matcher<const string&> ends_with_ok = EndsWith("ok");
2650 ASSERT_THAT("book", ends_with_ok);
zhanyong.wan736baa82010-09-27 17:44:16 +00002651 const string bad = "bad";
2652 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
2653 "Value of: bad\n"
2654 "Expected: ends with \"ok\"\n"
2655 " Actual: \"bad\"");
shiqiane35fdd92008-12-10 05:08:54 +00002656 Matcher<int> is_greater_than_5 = Gt(5);
2657 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
2658 "Value of: 5\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002659 "Expected: is > 5\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002660 " Actual: 5" + OfType("int"));
shiqiane35fdd92008-12-10 05:08:54 +00002661}
zhanyong.wan95b12332009-09-25 18:55:50 +00002662#endif // !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002663
2664// Tests floating-point matchers.
2665template <typename RawType>
2666class FloatingPointTest : public testing::Test {
2667 protected:
zhanyong.wan35877b72013-09-18 17:51:08 +00002668 typedef testing::internal::FloatingPoint<RawType> Floating;
shiqiane35fdd92008-12-10 05:08:54 +00002669 typedef typename Floating::Bits Bits;
2670
zhanyong.wan35877b72013-09-18 17:51:08 +00002671 FloatingPointTest()
2672 : max_ulps_(Floating::kMaxUlps),
2673 zero_bits_(Floating(0).bits()),
2674 one_bits_(Floating(1).bits()),
2675 infinity_bits_(Floating(Floating::Infinity()).bits()),
2676 close_to_positive_zero_(
2677 Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
2678 close_to_negative_zero_(
2679 -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
2680 further_from_negative_zero_(-Floating::ReinterpretBits(
2681 zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
2682 close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
2683 further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
2684 infinity_(Floating::Infinity()),
2685 close_to_infinity_(
2686 Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
2687 further_from_infinity_(
2688 Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
2689 max_(Floating::Max()),
2690 nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
2691 nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
shiqiane35fdd92008-12-10 05:08:54 +00002692 }
2693
2694 void TestSize() {
2695 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2696 }
2697
2698 // A battery of tests for FloatingEqMatcher::Matches.
2699 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2700 void TestMatches(
2701 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
2702 Matcher<RawType> m1 = matcher_maker(0.0);
2703 EXPECT_TRUE(m1.Matches(-0.0));
2704 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
2705 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
2706 EXPECT_FALSE(m1.Matches(1.0));
2707
2708 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
2709 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
2710
2711 Matcher<RawType> m3 = matcher_maker(1.0);
2712 EXPECT_TRUE(m3.Matches(close_to_one_));
2713 EXPECT_FALSE(m3.Matches(further_from_one_));
2714
2715 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
2716 EXPECT_FALSE(m3.Matches(0.0));
2717
2718 Matcher<RawType> m4 = matcher_maker(-infinity_);
2719 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
2720
2721 Matcher<RawType> m5 = matcher_maker(infinity_);
2722 EXPECT_TRUE(m5.Matches(close_to_infinity_));
2723
2724 // This is interesting as the representations of infinity_ and nan1_
2725 // are only 1 DLP apart.
2726 EXPECT_FALSE(m5.Matches(nan1_));
2727
2728 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2729 // some cases.
2730 Matcher<const RawType&> m6 = matcher_maker(0.0);
2731 EXPECT_TRUE(m6.Matches(-0.0));
2732 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
2733 EXPECT_FALSE(m6.Matches(1.0));
2734
2735 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2736 // cases.
2737 Matcher<RawType&> m7 = matcher_maker(0.0);
2738 RawType x = 0.0;
2739 EXPECT_TRUE(m7.Matches(x));
2740 x = 0.01f;
2741 EXPECT_FALSE(m7.Matches(x));
2742 }
2743
2744 // Pre-calculated numbers to be used by the tests.
2745
zhanyong.wan35877b72013-09-18 17:51:08 +00002746 const size_t max_ulps_;
shiqiane35fdd92008-12-10 05:08:54 +00002747
zhanyong.wan35877b72013-09-18 17:51:08 +00002748 const Bits zero_bits_; // The bits that represent 0.0.
2749 const Bits one_bits_; // The bits that represent 1.0.
2750 const Bits infinity_bits_; // The bits that represent +infinity.
shiqiane35fdd92008-12-10 05:08:54 +00002751
zhanyong.wan35877b72013-09-18 17:51:08 +00002752 // Some numbers close to 0.0.
2753 const RawType close_to_positive_zero_;
2754 const RawType close_to_negative_zero_;
2755 const RawType further_from_negative_zero_;
shiqiane35fdd92008-12-10 05:08:54 +00002756
zhanyong.wan35877b72013-09-18 17:51:08 +00002757 // Some numbers close to 1.0.
2758 const RawType close_to_one_;
2759 const RawType further_from_one_;
2760
2761 // Some numbers close to +infinity.
2762 const RawType infinity_;
2763 const RawType close_to_infinity_;
2764 const RawType further_from_infinity_;
2765
2766 // Maximum representable value that's not infinity.
2767 const RawType max_;
2768
2769 // Some NaNs.
2770 const RawType nan1_;
2771 const RawType nan2_;
shiqiane35fdd92008-12-10 05:08:54 +00002772};
2773
zhanyong.wan616180e2013-06-18 18:49:51 +00002774// Tests floating-point matchers with fixed epsilons.
2775template <typename RawType>
2776class FloatingPointNearTest : public FloatingPointTest<RawType> {
2777 protected:
2778 typedef FloatingPointTest<RawType> ParentType;
2779
2780 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
2781 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2782 void TestNearMatches(
2783 testing::internal::FloatingEqMatcher<RawType>
2784 (*matcher_maker)(RawType, RawType)) {
2785 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
2786 EXPECT_TRUE(m1.Matches(0.0));
2787 EXPECT_TRUE(m1.Matches(-0.0));
2788 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
2789 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
2790 EXPECT_FALSE(m1.Matches(1.0));
2791
2792 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
2793 EXPECT_TRUE(m2.Matches(0.0));
2794 EXPECT_TRUE(m2.Matches(-0.0));
2795 EXPECT_TRUE(m2.Matches(1.0));
2796 EXPECT_TRUE(m2.Matches(-1.0));
2797 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
2798 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
2799
2800 // Check that inf matches inf, regardless of the of the specified max
2801 // absolute error.
2802 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
2803 EXPECT_TRUE(m3.Matches(ParentType::infinity_));
2804 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
2805 EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
2806
2807 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
2808 EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
2809 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
2810 EXPECT_FALSE(m4.Matches(ParentType::infinity_));
2811
2812 // Test various overflow scenarios.
zhanyong.wan35877b72013-09-18 17:51:08 +00002813 Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
2814 EXPECT_TRUE(m5.Matches(ParentType::max_));
2815 EXPECT_FALSE(m5.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002816
zhanyong.wan35877b72013-09-18 17:51:08 +00002817 Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
2818 EXPECT_FALSE(m6.Matches(ParentType::max_));
2819 EXPECT_TRUE(m6.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002820
zhanyong.wan35877b72013-09-18 17:51:08 +00002821 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
2822 EXPECT_TRUE(m7.Matches(ParentType::max_));
2823 EXPECT_FALSE(m7.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002824
zhanyong.wan35877b72013-09-18 17:51:08 +00002825 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
2826 EXPECT_FALSE(m8.Matches(ParentType::max_));
2827 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002828
2829 // The difference between max() and -max() normally overflows to infinity,
2830 // but it should still match if the max_abs_error is also infinity.
2831 Matcher<RawType> m9 = matcher_maker(
zhanyong.wan35877b72013-09-18 17:51:08 +00002832 ParentType::max_, ParentType::infinity_);
2833 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002834
2835 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2836 // some cases.
2837 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
2838 EXPECT_TRUE(m10.Matches(-0.0));
2839 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
2840 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
2841
2842 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2843 // cases.
2844 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
2845 RawType x = 0.0;
2846 EXPECT_TRUE(m11.Matches(x));
2847 x = 1.0f;
2848 EXPECT_TRUE(m11.Matches(x));
2849 x = -1.0f;
2850 EXPECT_TRUE(m11.Matches(x));
2851 x = 1.1f;
2852 EXPECT_FALSE(m11.Matches(x));
2853 x = -1.1f;
2854 EXPECT_FALSE(m11.Matches(x));
2855 }
2856};
2857
shiqiane35fdd92008-12-10 05:08:54 +00002858// Instantiate FloatingPointTest for testing floats.
2859typedef FloatingPointTest<float> FloatTest;
2860
2861TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
2862 TestMatches(&FloatEq);
2863}
2864
2865TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
2866 TestMatches(&NanSensitiveFloatEq);
2867}
2868
2869TEST_F(FloatTest, FloatEqCannotMatchNaN) {
2870 // FloatEq never matches NaN.
2871 Matcher<float> m = FloatEq(nan1_);
2872 EXPECT_FALSE(m.Matches(nan1_));
2873 EXPECT_FALSE(m.Matches(nan2_));
2874 EXPECT_FALSE(m.Matches(1.0));
2875}
2876
2877TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
2878 // NanSensitiveFloatEq will match NaN.
2879 Matcher<float> m = NanSensitiveFloatEq(nan1_);
2880 EXPECT_TRUE(m.Matches(nan1_));
2881 EXPECT_TRUE(m.Matches(nan2_));
2882 EXPECT_FALSE(m.Matches(1.0));
2883}
2884
2885TEST_F(FloatTest, FloatEqCanDescribeSelf) {
2886 Matcher<float> m1 = FloatEq(2.0f);
2887 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002888 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002889
2890 Matcher<float> m2 = FloatEq(0.5f);
2891 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002892 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002893
2894 Matcher<float> m3 = FloatEq(nan1_);
2895 EXPECT_EQ("never matches", Describe(m3));
2896 EXPECT_EQ("is anything", DescribeNegation(m3));
2897}
2898
2899TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
2900 Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
2901 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002902 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002903
2904 Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
2905 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002906 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002907
2908 Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
2909 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002910 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00002911}
2912
zhanyong.wan616180e2013-06-18 18:49:51 +00002913// Instantiate FloatingPointTest for testing floats with a user-specified
2914// max absolute error.
2915typedef FloatingPointNearTest<float> FloatNearTest;
2916
2917TEST_F(FloatNearTest, FloatNearMatches) {
2918 TestNearMatches(&FloatNear);
2919}
2920
2921TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
2922 TestNearMatches(&NanSensitiveFloatNear);
2923}
2924
2925TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
2926 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
2927 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2928 EXPECT_EQ(
2929 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2930
2931 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
2932 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2933 EXPECT_EQ(
2934 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2935
2936 Matcher<float> m3 = FloatNear(nan1_, 0.0);
2937 EXPECT_EQ("never matches", Describe(m3));
2938 EXPECT_EQ("is anything", DescribeNegation(m3));
2939}
2940
2941TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
2942 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
2943 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2944 EXPECT_EQ(
2945 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2946
2947 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
2948 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2949 EXPECT_EQ(
2950 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2951
2952 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
2953 EXPECT_EQ("is NaN", Describe(m3));
2954 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
2955}
2956
2957TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
2958 // FloatNear never matches NaN.
2959 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
2960 EXPECT_FALSE(m.Matches(nan1_));
2961 EXPECT_FALSE(m.Matches(nan2_));
2962 EXPECT_FALSE(m.Matches(1.0));
2963}
2964
2965TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
2966 // NanSensitiveFloatNear will match NaN.
2967 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
2968 EXPECT_TRUE(m.Matches(nan1_));
2969 EXPECT_TRUE(m.Matches(nan2_));
2970 EXPECT_FALSE(m.Matches(1.0));
2971}
2972
shiqiane35fdd92008-12-10 05:08:54 +00002973// Instantiate FloatingPointTest for testing doubles.
2974typedef FloatingPointTest<double> DoubleTest;
2975
2976TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
2977 TestMatches(&DoubleEq);
2978}
2979
2980TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
2981 TestMatches(&NanSensitiveDoubleEq);
2982}
2983
2984TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
2985 // DoubleEq never matches NaN.
2986 Matcher<double> m = DoubleEq(nan1_);
2987 EXPECT_FALSE(m.Matches(nan1_));
2988 EXPECT_FALSE(m.Matches(nan2_));
2989 EXPECT_FALSE(m.Matches(1.0));
2990}
2991
2992TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
2993 // NanSensitiveDoubleEq will match NaN.
2994 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
2995 EXPECT_TRUE(m.Matches(nan1_));
2996 EXPECT_TRUE(m.Matches(nan2_));
2997 EXPECT_FALSE(m.Matches(1.0));
2998}
2999
3000TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3001 Matcher<double> m1 = DoubleEq(2.0);
3002 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003003 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003004
3005 Matcher<double> m2 = DoubleEq(0.5);
3006 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003007 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003008
3009 Matcher<double> m3 = DoubleEq(nan1_);
3010 EXPECT_EQ("never matches", Describe(m3));
3011 EXPECT_EQ("is anything", DescribeNegation(m3));
3012}
3013
3014TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3015 Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3016 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003017 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003018
3019 Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3020 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003021 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003022
3023 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3024 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003025 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00003026}
3027
zhanyong.wan616180e2013-06-18 18:49:51 +00003028// Instantiate FloatingPointTest for testing floats with a user-specified
3029// max absolute error.
3030typedef FloatingPointNearTest<double> DoubleNearTest;
3031
3032TEST_F(DoubleNearTest, DoubleNearMatches) {
3033 TestNearMatches(&DoubleNear);
3034}
3035
3036TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3037 TestNearMatches(&NanSensitiveDoubleNear);
3038}
3039
3040TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3041 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3042 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3043 EXPECT_EQ(
3044 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3045
3046 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3047 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3048 EXPECT_EQ(
3049 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3050
3051 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3052 EXPECT_EQ("never matches", Describe(m3));
3053 EXPECT_EQ("is anything", DescribeNegation(m3));
3054}
3055
3056TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3057 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3058 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3059 EXPECT_EQ(
3060 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3061
3062 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3063 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3064 EXPECT_EQ(
3065 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3066
3067 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3068 EXPECT_EQ("is NaN", Describe(m3));
3069 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3070}
3071
3072TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3073 // DoubleNear never matches NaN.
3074 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3075 EXPECT_FALSE(m.Matches(nan1_));
3076 EXPECT_FALSE(m.Matches(nan2_));
3077 EXPECT_FALSE(m.Matches(1.0));
3078}
3079
3080TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3081 // NanSensitiveDoubleNear will match NaN.
3082 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3083 EXPECT_TRUE(m.Matches(nan1_));
3084 EXPECT_TRUE(m.Matches(nan2_));
3085 EXPECT_FALSE(m.Matches(1.0));
3086}
3087
shiqiane35fdd92008-12-10 05:08:54 +00003088TEST(PointeeTest, RawPointer) {
3089 const Matcher<int*> m = Pointee(Ge(0));
3090
3091 int n = 1;
3092 EXPECT_TRUE(m.Matches(&n));
3093 n = -1;
3094 EXPECT_FALSE(m.Matches(&n));
3095 EXPECT_FALSE(m.Matches(NULL));
3096}
3097
3098TEST(PointeeTest, RawPointerToConst) {
3099 const Matcher<const double*> m = Pointee(Ge(0));
3100
3101 double x = 1;
3102 EXPECT_TRUE(m.Matches(&x));
3103 x = -1;
3104 EXPECT_FALSE(m.Matches(&x));
3105 EXPECT_FALSE(m.Matches(NULL));
3106}
3107
3108TEST(PointeeTest, ReferenceToConstRawPointer) {
3109 const Matcher<int* const &> m = Pointee(Ge(0));
3110
3111 int n = 1;
3112 EXPECT_TRUE(m.Matches(&n));
3113 n = -1;
3114 EXPECT_FALSE(m.Matches(&n));
3115 EXPECT_FALSE(m.Matches(NULL));
3116}
3117
3118TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3119 const Matcher<double* &> m = Pointee(Ge(0));
3120
3121 double x = 1.0;
3122 double* p = &x;
3123 EXPECT_TRUE(m.Matches(p));
3124 x = -1;
3125 EXPECT_FALSE(m.Matches(p));
3126 p = NULL;
3127 EXPECT_FALSE(m.Matches(p));
3128}
3129
vladlosevada23472012-08-14 15:38:49 +00003130// Minimal const-propagating pointer.
3131template <typename T>
3132class ConstPropagatingPtr {
3133 public:
3134 typedef T element_type;
3135
3136 ConstPropagatingPtr() : val_() {}
3137 explicit ConstPropagatingPtr(T* t) : val_(t) {}
3138 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3139
3140 T* get() { return val_; }
3141 T& operator*() { return *val_; }
3142 // Most smart pointers return non-const T* and T& from the next methods.
3143 const T* get() const { return val_; }
3144 const T& operator*() const { return *val_; }
3145
3146 private:
3147 T* val_;
3148};
3149
3150TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3151 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3152 int three = 3;
3153 const ConstPropagatingPtr<int> co(&three);
3154 ConstPropagatingPtr<int> o(&three);
3155 EXPECT_TRUE(m.Matches(o));
3156 EXPECT_TRUE(m.Matches(co));
3157 *o = 6;
3158 EXPECT_FALSE(m.Matches(o));
3159 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3160}
3161
shiqiane35fdd92008-12-10 05:08:54 +00003162TEST(PointeeTest, NeverMatchesNull) {
3163 const Matcher<const char*> m = Pointee(_);
3164 EXPECT_FALSE(m.Matches(NULL));
3165}
3166
3167// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3168TEST(PointeeTest, MatchesAgainstAValue) {
3169 const Matcher<int*> m = Pointee(5);
3170
3171 int n = 5;
3172 EXPECT_TRUE(m.Matches(&n));
3173 n = -1;
3174 EXPECT_FALSE(m.Matches(&n));
3175 EXPECT_FALSE(m.Matches(NULL));
3176}
3177
3178TEST(PointeeTest, CanDescribeSelf) {
3179 const Matcher<int*> m = Pointee(Gt(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003180 EXPECT_EQ("points to a value that is > 3", Describe(m));
3181 EXPECT_EQ("does not point to a value that is > 3",
shiqiane35fdd92008-12-10 05:08:54 +00003182 DescribeNegation(m));
3183}
3184
shiqiane35fdd92008-12-10 05:08:54 +00003185TEST(PointeeTest, CanExplainMatchResult) {
3186 const Matcher<const string*> m = Pointee(StartsWith("Hi"));
3187
3188 EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL)));
3189
zhanyong.wan736baa82010-09-27 17:44:16 +00003190 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
3191 long n = 3; // NOLINT
3192 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003193 Explain(m2, &n));
3194}
3195
3196TEST(PointeeTest, AlwaysExplainsPointee) {
3197 const Matcher<int*> m = Pointee(0);
3198 int n = 42;
zhanyong.wan736baa82010-09-27 17:44:16 +00003199 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
shiqiane35fdd92008-12-10 05:08:54 +00003200}
3201
3202// An uncopyable class.
3203class Uncopyable {
3204 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003205 explicit Uncopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003206
3207 int value() const { return value_; }
3208 private:
3209 const int value_;
3210 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3211};
3212
3213// Returns true iff x.value() is positive.
3214bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3215
3216// A user-defined struct for testing Field().
3217struct AStruct {
3218 AStruct() : x(0), y(1.0), z(5), p(NULL) {}
3219 AStruct(const AStruct& rhs)
3220 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3221
3222 int x; // A non-const field.
3223 const double y; // A const field.
3224 Uncopyable z; // An uncopyable field.
3225 const char* p; // A pointer field.
zhanyong.wan32de5f52009-12-23 00:13:23 +00003226
3227 private:
3228 GTEST_DISALLOW_ASSIGN_(AStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003229};
3230
3231// A derived struct for testing Field().
3232struct DerivedStruct : public AStruct {
3233 char ch;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003234
3235 private:
3236 GTEST_DISALLOW_ASSIGN_(DerivedStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003237};
3238
3239// Tests that Field(&Foo::field, ...) works when field is non-const.
3240TEST(FieldTest, WorksForNonConstField) {
3241 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
3242
3243 AStruct a;
3244 EXPECT_TRUE(m.Matches(a));
3245 a.x = -1;
3246 EXPECT_FALSE(m.Matches(a));
3247}
3248
3249// Tests that Field(&Foo::field, ...) works when field is const.
3250TEST(FieldTest, WorksForConstField) {
3251 AStruct a;
3252
3253 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
3254 EXPECT_TRUE(m.Matches(a));
3255 m = Field(&AStruct::y, Le(0.0));
3256 EXPECT_FALSE(m.Matches(a));
3257}
3258
3259// Tests that Field(&Foo::field, ...) works when field is not copyable.
3260TEST(FieldTest, WorksForUncopyableField) {
3261 AStruct a;
3262
3263 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3264 EXPECT_TRUE(m.Matches(a));
3265 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3266 EXPECT_FALSE(m.Matches(a));
3267}
3268
3269// Tests that Field(&Foo::field, ...) works when field is a pointer.
3270TEST(FieldTest, WorksForPointerField) {
3271 // Matching against NULL.
3272 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
3273 AStruct a;
3274 EXPECT_TRUE(m.Matches(a));
3275 a.p = "hi";
3276 EXPECT_FALSE(m.Matches(a));
3277
3278 // Matching a pointer that is not NULL.
3279 m = Field(&AStruct::p, StartsWith("hi"));
3280 a.p = "hill";
3281 EXPECT_TRUE(m.Matches(a));
3282 a.p = "hole";
3283 EXPECT_FALSE(m.Matches(a));
3284}
3285
3286// Tests that Field() works when the object is passed by reference.
3287TEST(FieldTest, WorksForByRefArgument) {
3288 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3289
3290 AStruct a;
3291 EXPECT_TRUE(m.Matches(a));
3292 a.x = -1;
3293 EXPECT_FALSE(m.Matches(a));
3294}
3295
3296// Tests that Field(&Foo::field, ...) works when the argument's type
3297// is a sub-type of Foo.
3298TEST(FieldTest, WorksForArgumentOfSubType) {
3299 // Note that the matcher expects DerivedStruct but we say AStruct
3300 // inside Field().
3301 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
3302
3303 DerivedStruct d;
3304 EXPECT_TRUE(m.Matches(d));
3305 d.x = -1;
3306 EXPECT_FALSE(m.Matches(d));
3307}
3308
3309// Tests that Field(&Foo::field, m) works when field's type and m's
3310// argument type are compatible but not the same.
3311TEST(FieldTest, WorksForCompatibleMatcherType) {
3312 // The field is an int, but the inner matcher expects a signed char.
3313 Matcher<const AStruct&> m = Field(&AStruct::x,
3314 Matcher<signed char>(Ge(0)));
3315
3316 AStruct a;
3317 EXPECT_TRUE(m.Matches(a));
3318 a.x = -1;
3319 EXPECT_FALSE(m.Matches(a));
3320}
3321
3322// Tests that Field() can describe itself.
3323TEST(FieldTest, CanDescribeSelf) {
3324 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3325
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003326 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3327 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003328}
3329
3330// Tests that Field() can explain the match result.
3331TEST(FieldTest, CanExplainMatchResult) {
3332 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3333
3334 AStruct a;
3335 a.x = 1;
zhanyong.wan736baa82010-09-27 17:44:16 +00003336 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003337
3338 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003339 EXPECT_EQ(
3340 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
3341 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003342}
3343
3344// Tests that Field() works when the argument is a pointer to const.
3345TEST(FieldForPointerTest, WorksForPointerToConst) {
3346 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3347
3348 AStruct a;
3349 EXPECT_TRUE(m.Matches(&a));
3350 a.x = -1;
3351 EXPECT_FALSE(m.Matches(&a));
3352}
3353
3354// Tests that Field() works when the argument is a pointer to non-const.
3355TEST(FieldForPointerTest, WorksForPointerToNonConst) {
3356 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
3357
3358 AStruct a;
3359 EXPECT_TRUE(m.Matches(&a));
3360 a.x = -1;
3361 EXPECT_FALSE(m.Matches(&a));
3362}
3363
zhanyong.wan6953a722010-01-13 05:15:07 +00003364// Tests that Field() works when the argument is a reference to a const pointer.
3365TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
3366 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
3367
3368 AStruct a;
3369 EXPECT_TRUE(m.Matches(&a));
3370 a.x = -1;
3371 EXPECT_FALSE(m.Matches(&a));
3372}
3373
shiqiane35fdd92008-12-10 05:08:54 +00003374// Tests that Field() does not match the NULL pointer.
3375TEST(FieldForPointerTest, DoesNotMatchNull) {
3376 Matcher<const AStruct*> m = Field(&AStruct::x, _);
3377 EXPECT_FALSE(m.Matches(NULL));
3378}
3379
3380// Tests that Field(&Foo::field, ...) works when the argument's type
3381// is a sub-type of const Foo*.
3382TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
3383 // Note that the matcher expects DerivedStruct but we say AStruct
3384 // inside Field().
3385 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
3386
3387 DerivedStruct d;
3388 EXPECT_TRUE(m.Matches(&d));
3389 d.x = -1;
3390 EXPECT_FALSE(m.Matches(&d));
3391}
3392
3393// Tests that Field() can describe itself when used to match a pointer.
3394TEST(FieldForPointerTest, CanDescribeSelf) {
3395 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3396
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003397 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3398 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003399}
3400
3401// Tests that Field() can explain the result of matching a pointer.
3402TEST(FieldForPointerTest, CanExplainMatchResult) {
3403 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3404
3405 AStruct a;
3406 a.x = 1;
3407 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003408 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
3409 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003410
3411 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003412 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
3413 ", which is 1 more than 0", Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003414}
3415
3416// A user-defined class for testing Property().
3417class AClass {
3418 public:
3419 AClass() : n_(0) {}
3420
3421 // A getter that returns a non-reference.
3422 int n() const { return n_; }
3423
3424 void set_n(int new_n) { n_ = new_n; }
3425
3426 // A getter that returns a reference to const.
3427 const string& s() const { return s_; }
3428
3429 void set_s(const string& new_s) { s_ = new_s; }
3430
3431 // A getter that returns a reference to non-const.
3432 double& x() const { return x_; }
3433 private:
3434 int n_;
3435 string s_;
3436
3437 static double x_;
3438};
3439
3440double AClass::x_ = 0.0;
3441
3442// A derived class for testing Property().
3443class DerivedClass : public AClass {
kosak6414d802013-12-03 23:19:36 +00003444 public:
3445 int k() const { return k_; }
shiqiane35fdd92008-12-10 05:08:54 +00003446 private:
3447 int k_;
3448};
3449
3450// Tests that Property(&Foo::property, ...) works when property()
3451// returns a non-reference.
3452TEST(PropertyTest, WorksForNonReferenceProperty) {
3453 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3454
3455 AClass a;
3456 a.set_n(1);
3457 EXPECT_TRUE(m.Matches(a));
3458
3459 a.set_n(-1);
3460 EXPECT_FALSE(m.Matches(a));
3461}
3462
3463// Tests that Property(&Foo::property, ...) works when property()
3464// returns a reference to const.
3465TEST(PropertyTest, WorksForReferenceToConstProperty) {
3466 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
3467
3468 AClass a;
3469 a.set_s("hill");
3470 EXPECT_TRUE(m.Matches(a));
3471
3472 a.set_s("hole");
3473 EXPECT_FALSE(m.Matches(a));
3474}
3475
3476// Tests that Property(&Foo::property, ...) works when property()
3477// returns a reference to non-const.
3478TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
3479 double x = 0.0;
3480 AClass a;
3481
3482 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
3483 EXPECT_FALSE(m.Matches(a));
3484
3485 m = Property(&AClass::x, Not(Ref(x)));
3486 EXPECT_TRUE(m.Matches(a));
3487}
3488
3489// Tests that Property(&Foo::property, ...) works when the argument is
3490// passed by value.
3491TEST(PropertyTest, WorksForByValueArgument) {
3492 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
3493
3494 AClass a;
3495 a.set_s("hill");
3496 EXPECT_TRUE(m.Matches(a));
3497
3498 a.set_s("hole");
3499 EXPECT_FALSE(m.Matches(a));
3500}
3501
3502// Tests that Property(&Foo::property, ...) works when the argument's
3503// type is a sub-type of Foo.
3504TEST(PropertyTest, WorksForArgumentOfSubType) {
3505 // The matcher expects a DerivedClass, but inside the Property() we
3506 // say AClass.
3507 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
3508
3509 DerivedClass d;
3510 d.set_n(1);
3511 EXPECT_TRUE(m.Matches(d));
3512
3513 d.set_n(-1);
3514 EXPECT_FALSE(m.Matches(d));
3515}
3516
3517// Tests that Property(&Foo::property, m) works when property()'s type
3518// and m's argument type are compatible but different.
3519TEST(PropertyTest, WorksForCompatibleMatcherType) {
3520 // n() returns an int but the inner matcher expects a signed char.
3521 Matcher<const AClass&> m = Property(&AClass::n,
3522 Matcher<signed char>(Ge(0)));
3523
3524 AClass a;
3525 EXPECT_TRUE(m.Matches(a));
3526 a.set_n(-1);
3527 EXPECT_FALSE(m.Matches(a));
3528}
3529
3530// Tests that Property() can describe itself.
3531TEST(PropertyTest, CanDescribeSelf) {
3532 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3533
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003534 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3535 EXPECT_EQ("is an object whose given property isn't >= 0",
3536 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003537}
3538
3539// Tests that Property() can explain the match result.
3540TEST(PropertyTest, CanExplainMatchResult) {
3541 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3542
3543 AClass a;
3544 a.set_n(1);
zhanyong.wan736baa82010-09-27 17:44:16 +00003545 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003546
3547 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003548 EXPECT_EQ(
3549 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
3550 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003551}
3552
3553// Tests that Property() works when the argument is a pointer to const.
3554TEST(PropertyForPointerTest, WorksForPointerToConst) {
3555 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3556
3557 AClass a;
3558 a.set_n(1);
3559 EXPECT_TRUE(m.Matches(&a));
3560
3561 a.set_n(-1);
3562 EXPECT_FALSE(m.Matches(&a));
3563}
3564
3565// Tests that Property() works when the argument is a pointer to non-const.
3566TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
3567 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
3568
3569 AClass a;
3570 a.set_s("hill");
3571 EXPECT_TRUE(m.Matches(&a));
3572
3573 a.set_s("hole");
3574 EXPECT_FALSE(m.Matches(&a));
3575}
3576
zhanyong.wan6953a722010-01-13 05:15:07 +00003577// Tests that Property() works when the argument is a reference to a
3578// const pointer.
3579TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
3580 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
3581
3582 AClass a;
3583 a.set_s("hill");
3584 EXPECT_TRUE(m.Matches(&a));
3585
3586 a.set_s("hole");
3587 EXPECT_FALSE(m.Matches(&a));
3588}
3589
shiqiane35fdd92008-12-10 05:08:54 +00003590// Tests that Property() does not match the NULL pointer.
3591TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
3592 Matcher<const AClass*> m = Property(&AClass::x, _);
3593 EXPECT_FALSE(m.Matches(NULL));
3594}
3595
3596// Tests that Property(&Foo::property, ...) works when the argument's
3597// type is a sub-type of const Foo*.
3598TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
3599 // The matcher expects a DerivedClass, but inside the Property() we
3600 // say AClass.
3601 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
3602
3603 DerivedClass d;
3604 d.set_n(1);
3605 EXPECT_TRUE(m.Matches(&d));
3606
3607 d.set_n(-1);
3608 EXPECT_FALSE(m.Matches(&d));
3609}
3610
3611// Tests that Property() can describe itself when used to match a pointer.
3612TEST(PropertyForPointerTest, CanDescribeSelf) {
3613 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3614
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003615 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3616 EXPECT_EQ("is an object whose given property isn't >= 0",
3617 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003618}
3619
3620// Tests that Property() can explain the result of matching a pointer.
3621TEST(PropertyForPointerTest, CanExplainMatchResult) {
3622 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3623
3624 AClass a;
3625 a.set_n(1);
3626 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003627 EXPECT_EQ(
3628 "which points to an object whose given property is 1" + OfType("int"),
3629 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003630
3631 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003632 EXPECT_EQ("which points to an object whose given property is 1" +
3633 OfType("int") + ", which is 1 more than 0",
3634 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003635}
3636
3637// Tests ResultOf.
3638
3639// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3640// function pointer.
3641string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; }
3642
3643TEST(ResultOfTest, WorksForFunctionPointers) {
3644 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo")));
3645
3646 EXPECT_TRUE(matcher.Matches(1));
3647 EXPECT_FALSE(matcher.Matches(2));
3648}
3649
3650// Tests that ResultOf() can describe itself.
3651TEST(ResultOfTest, CanDescribeItself) {
3652 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
3653
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003654 EXPECT_EQ("is mapped by the given callable to a value that "
3655 "is equal to \"foo\"", Describe(matcher));
3656 EXPECT_EQ("is mapped by the given callable to a value that "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003657 "isn't equal to \"foo\"", DescribeNegation(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00003658}
3659
3660// Tests that ResultOf() can explain the match result.
3661int IntFunction(int input) { return input == 42 ? 80 : 90; }
3662
3663TEST(ResultOfTest, CanExplainMatchResult) {
3664 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003665 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003666 Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003667
3668 matcher = ResultOf(&IntFunction, GreaterThan(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003669 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
3670 ", which is 5 more than 85", Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003671}
3672
3673// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3674// returns a non-reference.
3675TEST(ResultOfTest, WorksForNonReferenceResults) {
3676 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
3677
3678 EXPECT_TRUE(matcher.Matches(42));
3679 EXPECT_FALSE(matcher.Matches(36));
3680}
3681
3682// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3683// returns a reference to non-const.
zhanyong.wan736baa82010-09-27 17:44:16 +00003684double& DoubleFunction(double& input) { return input; } // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003685
zhanyong.wan736baa82010-09-27 17:44:16 +00003686Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003687 return obj;
3688}
3689
3690TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
3691 double x = 3.14;
3692 double x2 = x;
3693 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
3694
3695 EXPECT_TRUE(matcher.Matches(x));
3696 EXPECT_FALSE(matcher.Matches(x2));
3697
3698 // Test that ResultOf works with uncopyable objects
3699 Uncopyable obj(0);
3700 Uncopyable obj2(0);
3701 Matcher<Uncopyable&> matcher2 =
3702 ResultOf(&RefUncopyableFunction, Ref(obj));
3703
3704 EXPECT_TRUE(matcher2.Matches(obj));
3705 EXPECT_FALSE(matcher2.Matches(obj2));
3706}
3707
3708// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3709// returns a reference to const.
3710const string& StringFunction(const string& input) { return input; }
3711
3712TEST(ResultOfTest, WorksForReferenceToConstResults) {
3713 string s = "foo";
3714 string s2 = s;
3715 Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s));
3716
3717 EXPECT_TRUE(matcher.Matches(s));
3718 EXPECT_FALSE(matcher.Matches(s2));
3719}
3720
3721// Tests that ResultOf(f, m) works when f(x) and m's
3722// argument types are compatible but different.
3723TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
3724 // IntFunction() returns int but the inner matcher expects a signed char.
3725 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
3726
3727 EXPECT_TRUE(matcher.Matches(36));
3728 EXPECT_FALSE(matcher.Matches(42));
3729}
3730
shiqiane35fdd92008-12-10 05:08:54 +00003731// Tests that the program aborts when ResultOf is passed
3732// a NULL function pointer.
3733TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
zhanyong.wan04d6ed82009-09-11 07:01:08 +00003734 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan736baa82010-09-27 17:44:16 +00003735 ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))),
shiqiane35fdd92008-12-10 05:08:54 +00003736 "NULL function pointer is passed into ResultOf\\(\\)\\.");
3737}
shiqiane35fdd92008-12-10 05:08:54 +00003738
3739// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3740// function reference.
3741TEST(ResultOfTest, WorksForFunctionReferences) {
3742 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
3743 EXPECT_TRUE(matcher.Matches(1));
3744 EXPECT_FALSE(matcher.Matches(2));
3745}
3746
3747// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3748// function object.
3749struct Functor : public ::std::unary_function<int, string> {
3750 result_type operator()(argument_type input) const {
3751 return IntToStringFunction(input);
3752 }
3753};
3754
3755TEST(ResultOfTest, WorksForFunctors) {
3756 Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo")));
3757
3758 EXPECT_TRUE(matcher.Matches(1));
3759 EXPECT_FALSE(matcher.Matches(2));
3760}
3761
3762// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3763// functor with more then one operator() defined. ResultOf() must work
3764// for each defined operator().
3765struct PolymorphicFunctor {
3766 typedef int result_type;
3767 int operator()(int n) { return n; }
3768 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
3769};
3770
3771TEST(ResultOfTest, WorksForPolymorphicFunctors) {
3772 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
3773
3774 EXPECT_TRUE(matcher_int.Matches(10));
3775 EXPECT_FALSE(matcher_int.Matches(2));
3776
3777 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
3778
3779 EXPECT_TRUE(matcher_string.Matches("long string"));
3780 EXPECT_FALSE(matcher_string.Matches("shrt"));
3781}
3782
3783const int* ReferencingFunction(const int& n) { return &n; }
3784
3785struct ReferencingFunctor {
3786 typedef const int* result_type;
3787 result_type operator()(const int& n) { return &n; }
3788};
3789
3790TEST(ResultOfTest, WorksForReferencingCallables) {
3791 const int n = 1;
3792 const int n2 = 1;
3793 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
3794 EXPECT_TRUE(matcher2.Matches(n));
3795 EXPECT_FALSE(matcher2.Matches(n2));
3796
3797 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
3798 EXPECT_TRUE(matcher3.Matches(n));
3799 EXPECT_FALSE(matcher3.Matches(n2));
3800}
3801
shiqiane35fdd92008-12-10 05:08:54 +00003802class DivisibleByImpl {
3803 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003804 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
shiqiane35fdd92008-12-10 05:08:54 +00003805
zhanyong.wandb22c222010-01-28 21:52:29 +00003806 // For testing using ExplainMatchResultTo() with polymorphic matchers.
shiqiane35fdd92008-12-10 05:08:54 +00003807 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00003808 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003809 *listener << "which is " << (n % divider_) << " modulo "
zhanyong.wandb22c222010-01-28 21:52:29 +00003810 << divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003811 return (n % divider_) == 0;
3812 }
3813
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003814 void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003815 *os << "is divisible by " << divider_;
3816 }
3817
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003818 void DescribeNegationTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003819 *os << "is not divisible by " << divider_;
3820 }
3821
zhanyong.wan32de5f52009-12-23 00:13:23 +00003822 void set_divider(int a_divider) { divider_ = a_divider; }
shiqiane35fdd92008-12-10 05:08:54 +00003823 int divider() const { return divider_; }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003824
shiqiane35fdd92008-12-10 05:08:54 +00003825 private:
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003826 int divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003827};
3828
shiqiane35fdd92008-12-10 05:08:54 +00003829PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
3830 return MakePolymorphicMatcher(DivisibleByImpl(n));
3831}
3832
3833// Tests that when AllOf() fails, only the first failing matcher is
3834// asked to explain why.
3835TEST(ExplainMatchResultTest, AllOf_False_False) {
3836 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003837 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00003838}
3839
3840// Tests that when AllOf() fails, only the first failing matcher is
3841// asked to explain why.
3842TEST(ExplainMatchResultTest, AllOf_False_True) {
3843 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003844 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003845}
3846
3847// Tests that when AllOf() fails, only the first failing matcher is
3848// asked to explain why.
3849TEST(ExplainMatchResultTest, AllOf_True_False) {
3850 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003851 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00003852}
3853
3854// Tests that when AllOf() succeeds, all matchers are asked to explain
3855// why.
3856TEST(ExplainMatchResultTest, AllOf_True_True) {
3857 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003858 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003859}
3860
3861TEST(ExplainMatchResultTest, AllOf_True_True_2) {
3862 const Matcher<int> m = AllOf(Ge(2), Le(3));
3863 EXPECT_EQ("", Explain(m, 2));
3864}
3865
3866TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
3867 const Matcher<int> m = GreaterThan(5);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003868 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003869}
3870
3871// The following two tests verify that values without a public copy
3872// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
3873// with the help of ByRef().
3874
3875class NotCopyable {
3876 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003877 explicit NotCopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003878
3879 int value() const { return value_; }
3880
3881 bool operator==(const NotCopyable& rhs) const {
3882 return value() == rhs.value();
3883 }
3884
3885 bool operator>=(const NotCopyable& rhs) const {
3886 return value() >= rhs.value();
3887 }
3888 private:
3889 int value_;
3890
3891 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
3892};
3893
3894TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
3895 const NotCopyable const_value1(1);
3896 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
3897
3898 const NotCopyable n1(1), n2(2);
3899 EXPECT_TRUE(m.Matches(n1));
3900 EXPECT_FALSE(m.Matches(n2));
3901}
3902
3903TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
3904 NotCopyable value2(2);
3905 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
3906
3907 NotCopyable n1(1), n2(2);
3908 EXPECT_FALSE(m.Matches(n1));
3909 EXPECT_TRUE(m.Matches(n2));
3910}
3911
zhanyong.wan320814a2013-03-01 00:20:30 +00003912TEST(IsEmptyTest, ImplementsIsEmpty) {
3913 vector<int> container;
3914 EXPECT_THAT(container, IsEmpty());
3915 container.push_back(0);
3916 EXPECT_THAT(container, Not(IsEmpty()));
3917 container.push_back(1);
3918 EXPECT_THAT(container, Not(IsEmpty()));
3919}
3920
3921TEST(IsEmptyTest, WorksWithString) {
3922 string text;
3923 EXPECT_THAT(text, IsEmpty());
3924 text = "foo";
3925 EXPECT_THAT(text, Not(IsEmpty()));
3926 text = string("\0", 1);
3927 EXPECT_THAT(text, Not(IsEmpty()));
3928}
3929
3930TEST(IsEmptyTest, CanDescribeSelf) {
3931 Matcher<vector<int> > m = IsEmpty();
3932 EXPECT_EQ("is empty", Describe(m));
3933 EXPECT_EQ("isn't empty", DescribeNegation(m));
3934}
3935
3936TEST(IsEmptyTest, ExplainsResult) {
3937 Matcher<vector<int> > m = IsEmpty();
3938 vector<int> container;
3939 EXPECT_EQ("", Explain(m, container));
3940 container.push_back(0);
3941 EXPECT_EQ("whose size is 1", Explain(m, container));
3942}
3943
zhanyong.wana31d9ce2013-03-01 01:50:17 +00003944TEST(SizeIsTest, ImplementsSizeIs) {
3945 vector<int> container;
3946 EXPECT_THAT(container, SizeIs(0));
3947 EXPECT_THAT(container, Not(SizeIs(1)));
3948 container.push_back(0);
3949 EXPECT_THAT(container, Not(SizeIs(0)));
3950 EXPECT_THAT(container, SizeIs(1));
3951 container.push_back(0);
3952 EXPECT_THAT(container, Not(SizeIs(0)));
3953 EXPECT_THAT(container, SizeIs(2));
3954}
3955
3956TEST(SizeIsTest, WorksWithMap) {
3957 map<string, int> container;
3958 EXPECT_THAT(container, SizeIs(0));
3959 EXPECT_THAT(container, Not(SizeIs(1)));
3960 container.insert(make_pair("foo", 1));
3961 EXPECT_THAT(container, Not(SizeIs(0)));
3962 EXPECT_THAT(container, SizeIs(1));
3963 container.insert(make_pair("bar", 2));
3964 EXPECT_THAT(container, Not(SizeIs(0)));
3965 EXPECT_THAT(container, SizeIs(2));
3966}
3967
3968TEST(SizeIsTest, WorksWithReferences) {
3969 vector<int> container;
3970 Matcher<const vector<int>&> m = SizeIs(1);
3971 EXPECT_THAT(container, Not(m));
3972 container.push_back(0);
3973 EXPECT_THAT(container, m);
3974}
3975
3976TEST(SizeIsTest, CanDescribeSelf) {
3977 Matcher<vector<int> > m = SizeIs(2);
3978 EXPECT_EQ("size is equal to 2", Describe(m));
3979 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
3980}
3981
3982TEST(SizeIsTest, ExplainsResult) {
3983 Matcher<vector<int> > m1 = SizeIs(2);
3984 Matcher<vector<int> > m2 = SizeIs(Lt(2u));
3985 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
3986 Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
3987 vector<int> container;
3988 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
3989 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
3990 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
3991 EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
3992 Explain(m4, container));
3993 container.push_back(0);
3994 container.push_back(0);
3995 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
3996 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
3997 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
3998 EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
3999 Explain(m4, container));
4000}
4001
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004002#if GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004003// Tests ContainerEq with different container types, and
4004// different element types.
4005
4006template <typename T>
zhanyong.wanb8243162009-06-04 05:48:20 +00004007class ContainerEqTest : public testing::Test {};
zhanyong.wan6a896b52009-01-16 01:13:50 +00004008
4009typedef testing::Types<
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004010 set<int>,
4011 vector<size_t>,
4012 multiset<size_t>,
4013 list<int> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004014 ContainerEqTestTypes;
4015
4016TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
4017
4018// Tests that the filled container is equal to itself.
4019TYPED_TEST(ContainerEqTest, EqualsSelf) {
4020 static const int vals[] = {1, 1, 2, 3, 5, 8};
4021 TypeParam my_set(vals, vals + 6);
4022 const Matcher<TypeParam> m = ContainerEq(my_set);
4023 EXPECT_TRUE(m.Matches(my_set));
4024 EXPECT_EQ("", Explain(m, my_set));
4025}
4026
4027// Tests that missing values are reported.
4028TYPED_TEST(ContainerEqTest, ValueMissing) {
4029 static const int vals[] = {1, 1, 2, 3, 5, 8};
4030 static const int test_vals[] = {2, 1, 8, 5};
4031 TypeParam my_set(vals, vals + 6);
4032 TypeParam test_set(test_vals, test_vals + 4);
4033 const Matcher<TypeParam> m = ContainerEq(my_set);
4034 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004035 EXPECT_EQ("which doesn't have these expected elements: 3",
4036 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004037}
4038
4039// Tests that added values are reported.
4040TYPED_TEST(ContainerEqTest, ValueAdded) {
4041 static const int vals[] = {1, 1, 2, 3, 5, 8};
4042 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4043 TypeParam my_set(vals, vals + 6);
4044 TypeParam test_set(test_vals, test_vals + 6);
4045 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4046 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004047 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004048}
4049
4050// Tests that added and missing values are reported together.
4051TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4052 static const int vals[] = {1, 1, 2, 3, 5, 8};
4053 static const int test_vals[] = {1, 2, 3, 8, 46};
4054 TypeParam my_set(vals, vals + 6);
4055 TypeParam test_set(test_vals, test_vals + 5);
4056 const Matcher<TypeParam> m = ContainerEq(my_set);
4057 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004058 EXPECT_EQ("which has these unexpected elements: 46,\n"
4059 "and doesn't have these expected elements: 5",
4060 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004061}
4062
4063// Tests duplicated value -- expect no explanation.
4064TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4065 static const int vals[] = {1, 1, 2, 3, 5, 8};
4066 static const int test_vals[] = {1, 2, 3, 5, 8};
4067 TypeParam my_set(vals, vals + 6);
4068 TypeParam test_set(test_vals, test_vals + 5);
4069 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4070 // Depending on the container, match may be true or false
4071 // But in any case there should be no explanation.
4072 EXPECT_EQ("", Explain(m, test_set));
4073}
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004074#endif // GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004075
4076// Tests that mutliple missing values are reported.
4077// Using just vector here, so order is predicatble.
4078TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4079 static const int vals[] = {1, 1, 2, 3, 5, 8};
4080 static const int test_vals[] = {2, 1, 5};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004081 vector<int> my_set(vals, vals + 6);
4082 vector<int> test_set(test_vals, test_vals + 3);
4083 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004084 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004085 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4086 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004087}
4088
4089// Tests that added values are reported.
4090// Using just vector here, so order is predicatble.
4091TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4092 static const int vals[] = {1, 1, 2, 3, 5, 8};
4093 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004094 list<size_t> my_set(vals, vals + 6);
4095 list<size_t> test_set(test_vals, test_vals + 7);
4096 const Matcher<const list<size_t>&> m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004097 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004098 EXPECT_EQ("which has these unexpected elements: 92, 46",
4099 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004100}
4101
4102// Tests that added and missing values are reported together.
4103TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
4104 static const int vals[] = {1, 1, 2, 3, 5, 8};
4105 static const int test_vals[] = {1, 2, 3, 92, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004106 list<size_t> my_set(vals, vals + 6);
4107 list<size_t> test_set(test_vals, test_vals + 5);
4108 const Matcher<const list<size_t> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004109 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004110 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4111 "and doesn't have these expected elements: 5, 8",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004112 Explain(m, test_set));
4113}
4114
4115// Tests to see that duplicate elements are detected,
4116// but (as above) not reported in the explanation.
4117TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
4118 static const int vals[] = {1, 1, 2, 3, 5, 8};
4119 static const int test_vals[] = {1, 2, 3, 5, 8};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004120 vector<int> my_set(vals, vals + 6);
4121 vector<int> test_set(test_vals, test_vals + 5);
4122 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004123 EXPECT_TRUE(m.Matches(my_set));
4124 EXPECT_FALSE(m.Matches(test_set));
4125 // There is nothing to report when both sets contain all the same values.
4126 EXPECT_EQ("", Explain(m, test_set));
4127}
4128
4129// Tests that ContainerEq works for non-trivial associative containers,
4130// like maps.
4131TEST(ContainerEqExtraTest, WorksForMaps) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004132 map<int, std::string> my_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004133 my_map[0] = "a";
4134 my_map[1] = "b";
4135
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004136 map<int, std::string> test_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004137 test_map[0] = "aa";
4138 test_map[1] = "b";
4139
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004140 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004141 EXPECT_TRUE(m.Matches(my_map));
4142 EXPECT_FALSE(m.Matches(test_map));
4143
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004144 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
4145 "and doesn't have these expected elements: (0, \"a\")",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004146 Explain(m, test_map));
4147}
4148
zhanyong.wanb8243162009-06-04 05:48:20 +00004149TEST(ContainerEqExtraTest, WorksForNativeArray) {
4150 int a1[] = { 1, 2, 3 };
4151 int a2[] = { 1, 2, 3 };
4152 int b[] = { 1, 2, 4 };
4153
4154 EXPECT_THAT(a1, ContainerEq(a2));
4155 EXPECT_THAT(a1, Not(ContainerEq(b)));
4156}
4157
4158TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
4159 const char a1[][3] = { "hi", "lo" };
4160 const char a2[][3] = { "hi", "lo" };
4161 const char b[][3] = { "lo", "hi" };
4162
4163 // Tests using ContainerEq() in the first dimension.
4164 EXPECT_THAT(a1, ContainerEq(a2));
4165 EXPECT_THAT(a1, Not(ContainerEq(b)));
4166
4167 // Tests using ContainerEq() in the second dimension.
4168 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
4169 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
4170}
4171
4172TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
4173 const int a1[] = { 1, 2, 3 };
4174 const int a2[] = { 1, 2, 3 };
4175 const int b[] = { 1, 2, 3, 4 };
4176
zhanyong.wan2661c682009-06-09 05:42:12 +00004177 const int* const p1 = a1;
4178 EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
4179 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004180
4181 const int c[] = { 1, 3, 2 };
zhanyong.wan2661c682009-06-09 05:42:12 +00004182 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004183}
4184
4185TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
4186 std::string a1[][3] = {
4187 { "hi", "hello", "ciao" },
4188 { "bye", "see you", "ciao" }
4189 };
4190
4191 std::string a2[][3] = {
4192 { "hi", "hello", "ciao" },
4193 { "bye", "see you", "ciao" }
4194 };
4195
4196 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
4197 EXPECT_THAT(a1, m);
4198
4199 a2[0][0] = "ha";
4200 EXPECT_THAT(a1, m);
4201}
4202
zhanyong.wan898725c2011-09-16 16:45:39 +00004203TEST(WhenSortedByTest, WorksForEmptyContainer) {
4204 const vector<int> numbers;
4205 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
4206 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
4207}
4208
4209TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
4210 vector<unsigned> numbers;
4211 numbers.push_back(3);
4212 numbers.push_back(1);
4213 numbers.push_back(2);
4214 numbers.push_back(2);
4215 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
4216 ElementsAre(3, 2, 2, 1)));
4217 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
4218 ElementsAre(1, 2, 2, 3))));
4219}
4220
4221TEST(WhenSortedByTest, WorksForNonVectorContainer) {
4222 list<string> words;
4223 words.push_back("say");
4224 words.push_back("hello");
4225 words.push_back("world");
4226 EXPECT_THAT(words, WhenSortedBy(less<string>(),
4227 ElementsAre("hello", "say", "world")));
4228 EXPECT_THAT(words, Not(WhenSortedBy(less<string>(),
4229 ElementsAre("say", "hello", "world"))));
4230}
4231
4232TEST(WhenSortedByTest, WorksForNativeArray) {
4233 const int numbers[] = { 1, 3, 2, 4 };
4234 const int sorted_numbers[] = { 1, 2, 3, 4 };
4235 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
4236 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
4237 ElementsAreArray(sorted_numbers)));
4238 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
4239}
4240
4241TEST(WhenSortedByTest, CanDescribeSelf) {
4242 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
4243 EXPECT_EQ("(when sorted) has 2 elements where\n"
4244 "element #0 is equal to 1,\n"
4245 "element #1 is equal to 2",
4246 Describe(m));
4247 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
4248 "element #0 isn't equal to 1, or\n"
4249 "element #1 isn't equal to 2",
4250 DescribeNegation(m));
4251}
4252
4253TEST(WhenSortedByTest, ExplainsMatchResult) {
4254 const int a[] = { 2, 1 };
4255 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
4256 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
4257 EXPECT_EQ("which is { 1, 2 } when sorted",
4258 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
4259}
4260
4261// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
4262// need to test it as exhaustively as we test the latter.
4263
4264TEST(WhenSortedTest, WorksForEmptyContainer) {
4265 const vector<int> numbers;
4266 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
4267 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
4268}
4269
4270TEST(WhenSortedTest, WorksForNonEmptyContainer) {
4271 list<string> words;
4272 words.push_back("3");
4273 words.push_back("1");
4274 words.push_back("2");
4275 words.push_back("2");
4276 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
4277 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
4278}
4279
zhanyong.wana9a59e02013-03-27 16:14:55 +00004280TEST(WhenSortedTest, WorksForMapTypes) {
4281 map<string, int> word_counts;
4282 word_counts["and"] = 1;
4283 word_counts["the"] = 1;
4284 word_counts["buffalo"] = 2;
4285 EXPECT_THAT(word_counts, WhenSorted(ElementsAre(
4286 Pair("and", 1), Pair("buffalo", 2), Pair("the", 1))));
4287 EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre(
4288 Pair("and", 1), Pair("the", 1), Pair("buffalo", 2)))));
4289}
4290
4291TEST(WhenSortedTest, WorksForMultiMapTypes) {
4292 multimap<int, int> ifib;
4293 ifib.insert(make_pair(8, 6));
4294 ifib.insert(make_pair(2, 3));
4295 ifib.insert(make_pair(1, 1));
4296 ifib.insert(make_pair(3, 4));
4297 ifib.insert(make_pair(1, 2));
4298 ifib.insert(make_pair(5, 5));
4299 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
4300 Pair(1, 2),
4301 Pair(2, 3),
4302 Pair(3, 4),
4303 Pair(5, 5),
4304 Pair(8, 6))));
4305 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
4306 Pair(2, 3),
4307 Pair(1, 1),
4308 Pair(3, 4),
4309 Pair(1, 2),
4310 Pair(5, 5)))));
4311}
4312
4313TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
4314 std::deque<int> d;
4315 d.push_back(2);
4316 d.push_back(1);
4317 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
4318 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
4319}
4320
4321TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
4322 std::deque<int> d;
4323 d.push_back(2);
4324 d.push_back(1);
4325 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
4326 EXPECT_THAT(d, WhenSorted(vector_match));
4327 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
4328 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
4329}
4330
4331// Deliberately bare pseudo-container.
4332// Offers only begin() and end() accessors, yielding InputIterator.
4333template <typename T>
4334class Streamlike {
4335 private:
4336 class ConstIter;
4337 public:
4338 typedef ConstIter const_iterator;
4339 typedef T value_type;
4340
4341 template <typename InIter>
4342 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
4343
4344 const_iterator begin() const {
4345 return const_iterator(this, remainder_.begin());
4346 }
4347 const_iterator end() const {
4348 return const_iterator(this, remainder_.end());
4349 }
4350
4351 private:
4352 class ConstIter : public std::iterator<std::input_iterator_tag,
4353 value_type,
4354 ptrdiff_t,
4355 const value_type&,
4356 const value_type*> {
4357 public:
4358 ConstIter(const Streamlike* s,
4359 typename std::list<value_type>::iterator pos)
4360 : s_(s), pos_(pos) {}
4361
4362 const value_type& operator*() const { return *pos_; }
4363 const value_type* operator->() const { return &*pos_; }
4364 ConstIter& operator++() {
4365 s_->remainder_.erase(pos_++);
4366 return *this;
4367 }
4368
4369 // *iter++ is required to work (see std::istreambuf_iterator).
4370 // (void)iter++ is also required to work.
4371 class PostIncrProxy {
4372 public:
4373 explicit PostIncrProxy(const value_type& value) : value_(value) {}
4374 value_type operator*() const { return value_; }
4375 private:
4376 value_type value_;
4377 };
4378 PostIncrProxy operator++(int) {
4379 PostIncrProxy proxy(**this);
4380 ++(*this);
4381 return proxy;
4382 }
4383
4384 friend bool operator==(const ConstIter& a, const ConstIter& b) {
4385 return a.s_ == b.s_ && a.pos_ == b.pos_;
4386 }
4387 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
4388 return !(a == b);
4389 }
4390
4391 private:
4392 const Streamlike* s_;
4393 typename std::list<value_type>::iterator pos_;
4394 };
4395
4396 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
4397 os << "[";
4398 typedef typename std::list<value_type>::const_iterator Iter;
4399 const char* sep = "";
4400 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
4401 os << sep << *it;
4402 sep = ",";
4403 }
4404 os << "]";
4405 return os;
4406 }
4407
4408 mutable std::list<value_type> remainder_; // modified by iteration
4409};
4410
4411TEST(StreamlikeTest, Iteration) {
4412 const int a[5] = { 2, 1, 4, 5, 3 };
4413 Streamlike<int> s(a, a + 5);
4414 Streamlike<int>::const_iterator it = s.begin();
4415 const int* ip = a;
4416 while (it != s.end()) {
4417 SCOPED_TRACE(ip - a);
4418 EXPECT_EQ(*ip++, *it++);
4419 }
4420}
4421
4422TEST(WhenSortedTest, WorksForStreamlike) {
4423 // Streamlike 'container' provides only minimal iterator support.
4424 // Its iterators are tagged with input_iterator_tag.
4425 const int a[5] = { 2, 1, 4, 5, 3 };
kosak6414d802013-12-03 23:19:36 +00004426 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004427 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
4428 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4429}
4430
4431TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00004432 const int a[] = { 2, 1, 4, 5, 3 };
kosak6414d802013-12-03 23:19:36 +00004433 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004434 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
4435 EXPECT_THAT(s, WhenSorted(vector_match));
4436 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4437}
4438
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004439// Tests using ElementsAre() and ElementsAreArray() with stream-like
4440// "containers".
4441
4442TEST(ElemensAreStreamTest, WorksForStreamlike) {
4443 const int a[5] = { 1, 2, 3, 4, 5 };
kosak6414d802013-12-03 23:19:36 +00004444 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004445 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
4446 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
4447}
4448
4449TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
4450 const int a[5] = { 1, 2, 3, 4, 5 };
kosak6414d802013-12-03 23:19:36 +00004451 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004452
4453 vector<int> expected;
4454 expected.push_back(1);
4455 expected.push_back(2);
4456 expected.push_back(3);
4457 expected.push_back(4);
4458 expected.push_back(5);
4459 EXPECT_THAT(s, ElementsAreArray(expected));
4460
4461 expected[3] = 0;
4462 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
4463}
4464
zhanyong.wanfb25d532013-07-28 08:24:00 +00004465// Tests for UnorderedElementsAreArray()
4466
4467TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
4468 const int a[] = { 0, 1, 2, 3, 4 };
kosak6414d802013-12-03 23:19:36 +00004469 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004470 do {
4471 StringMatchResultListener listener;
4472 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
4473 s, &listener)) << listener.str();
4474 } while (std::next_permutation(s.begin(), s.end()));
4475}
4476
4477TEST(UnorderedElementsAreArrayTest, VectorBool) {
4478 const bool a[] = { 0, 1, 0, 1, 1 };
4479 const bool b[] = { 1, 0, 1, 1, 0 };
kosak6414d802013-12-03 23:19:36 +00004480 std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a));
4481 std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004482 StringMatchResultListener listener;
4483 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
4484 actual, &listener)) << listener.str();
4485}
4486
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004487TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
4488 // Streamlike 'container' provides only minimal iterator support.
4489 // Its iterators are tagged with input_iterator_tag, and it has no
4490 // size() or empty() methods.
4491 const int a[5] = { 2, 1, 4, 5, 3 };
kosak6414d802013-12-03 23:19:36 +00004492 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004493
4494 ::std::vector<int> expected;
4495 expected.push_back(1);
4496 expected.push_back(2);
4497 expected.push_back(3);
4498 expected.push_back(4);
4499 expected.push_back(5);
4500 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
4501
4502 expected.push_back(6);
4503 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
4504}
4505
kosak18489fa2013-12-04 23:49:07 +00004506#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004507
4508TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
4509 const int a[5] = { 2, 1, 4, 5, 3 };
4510 EXPECT_THAT(a, UnorderedElementsAreArray({ 1, 2, 3, 4, 5 }));
4511 EXPECT_THAT(a, Not(UnorderedElementsAreArray({ 1, 2, 3, 4, 6 })));
4512}
4513
4514TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
4515 const string a[5] = { "a", "b", "c", "d", "e" };
4516 EXPECT_THAT(a, UnorderedElementsAreArray({ "a", "b", "c", "d", "e" }));
4517 EXPECT_THAT(a, Not(UnorderedElementsAreArray({ "a", "b", "c", "d", "ef" })));
4518}
4519
4520TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
4521 const int a[5] = { 2, 1, 4, 5, 3 };
4522 EXPECT_THAT(a, UnorderedElementsAreArray(
4523 { Eq(1), Eq(2), Eq(3), Eq(4), Eq(5) }));
4524 EXPECT_THAT(a, Not(UnorderedElementsAreArray(
4525 { Eq(1), Eq(2), Eq(3), Eq(4), Eq(6) })));
4526}
4527
4528TEST(UnorderedElementsAreArrayTest,
4529 TakesInitializerListOfDifferentTypedMatchers) {
4530 const int a[5] = { 2, 1, 4, 5, 3 };
4531 // The compiler cannot infer the type of the initializer list if its
4532 // elements have different types. We must explicitly specify the
4533 // unified element type in this case.
4534 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
4535 { Eq(1), Ne(-2), Ge(3), Le(4), Eq(5) }));
4536 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
4537 { Eq(1), Ne(-2), Ge(3), Le(4), Eq(6) })));
4538}
4539
kosak18489fa2013-12-04 23:49:07 +00004540#endif // GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004541
zhanyong.wanfb25d532013-07-28 08:24:00 +00004542class UnorderedElementsAreTest : public testing::Test {
4543 protected:
4544 typedef std::vector<int> IntVec;
4545};
4546
4547TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
4548 const int a[] = { 1, 2, 3 };
kosak6414d802013-12-03 23:19:36 +00004549 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004550 do {
4551 StringMatchResultListener listener;
4552 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4553 s, &listener)) << listener.str();
4554 } while (std::next_permutation(s.begin(), s.end()));
4555}
4556
4557TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
4558 const int a[] = { 1, 2, 3 };
kosak6414d802013-12-03 23:19:36 +00004559 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004560 std::vector<Matcher<int> > mv;
4561 mv.push_back(1);
4562 mv.push_back(2);
4563 mv.push_back(2);
4564 // The element with value '3' matches nothing: fail fast.
4565 StringMatchResultListener listener;
4566 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4567 s, &listener)) << listener.str();
4568}
4569
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004570TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
4571 // Streamlike 'container' provides only minimal iterator support.
4572 // Its iterators are tagged with input_iterator_tag, and it has no
4573 // size() or empty() methods.
4574 const int a[5] = { 2, 1, 4, 5, 3 };
kosak6414d802013-12-03 23:19:36 +00004575 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004576
4577 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
4578 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
4579}
4580
zhanyong.wanfb25d532013-07-28 08:24:00 +00004581// One naive implementation of the matcher runs in O(N!) time, which is too
4582// slow for many real-world inputs. This test shows that our matcher can match
4583// 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
4584// iterations and obviously effectively incomputable.
4585// [ RUN ] UnorderedElementsAreTest.Performance
4586// [ OK ] UnorderedElementsAreTest.Performance (4 ms)
4587TEST_F(UnorderedElementsAreTest, Performance) {
4588 std::vector<int> s;
4589 std::vector<Matcher<int> > mv;
4590 for (int i = 0; i < 100; ++i) {
4591 s.push_back(i);
4592 mv.push_back(_);
4593 }
4594 mv[50] = Eq(0);
4595 StringMatchResultListener listener;
4596 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4597 s, &listener)) << listener.str();
4598}
4599
4600// Another variant of 'Performance' with similar expectations.
4601// [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
4602// [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
4603TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
4604 std::vector<int> s;
4605 std::vector<Matcher<int> > mv;
4606 for (int i = 0; i < 100; ++i) {
4607 s.push_back(i);
4608 if (i & 1) {
4609 mv.push_back(_);
4610 } else {
4611 mv.push_back(i);
4612 }
4613 }
4614 StringMatchResultListener listener;
4615 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4616 s, &listener)) << listener.str();
4617}
4618
4619TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
4620 std::vector<int> v;
4621 v.push_back(4);
4622 StringMatchResultListener listener;
4623 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4624 v, &listener)) << listener.str();
4625 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
4626}
4627
4628TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
4629 std::vector<int> v;
4630 StringMatchResultListener listener;
4631 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4632 v, &listener)) << listener.str();
4633 EXPECT_THAT(listener.str(), Eq(""));
4634}
4635
4636TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
4637 std::vector<int> v;
4638 v.push_back(1);
4639 v.push_back(1);
4640 StringMatchResultListener listener;
4641 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4642 v, &listener)) << listener.str();
4643 EXPECT_THAT(
4644 listener.str(),
4645 Eq("where the following matchers don't match any elements:\n"
4646 "matcher #1: is equal to 2"));
4647}
4648
4649TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
4650 std::vector<int> v;
4651 v.push_back(1);
4652 v.push_back(2);
4653 StringMatchResultListener listener;
4654 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
4655 v, &listener)) << listener.str();
4656 EXPECT_THAT(
4657 listener.str(),
4658 Eq("where the following elements don't match any matchers:\n"
4659 "element #1: 2"));
4660}
4661
4662TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
4663 std::vector<int> v;
4664 v.push_back(2);
4665 v.push_back(3);
4666 StringMatchResultListener listener;
4667 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4668 v, &listener)) << listener.str();
4669 EXPECT_THAT(
4670 listener.str(),
4671 Eq("where"
4672 " the following matchers don't match any elements:\n"
4673 "matcher #0: is equal to 1\n"
4674 "and"
4675 " where"
4676 " the following elements don't match any matchers:\n"
4677 "element #1: 3"));
4678}
4679
4680// Test helper for formatting element, matcher index pairs in expectations.
4681static string EMString(int element, int matcher) {
4682 stringstream ss;
4683 ss << "(element #" << element << ", matcher #" << matcher << ")";
4684 return ss.str();
4685}
4686
4687TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
4688 // A situation where all elements and matchers have a match
4689 // associated with them, but the max matching is not perfect.
4690 std::vector<string> v;
4691 v.push_back("a");
4692 v.push_back("b");
4693 v.push_back("c");
4694 StringMatchResultListener listener;
4695 EXPECT_FALSE(ExplainMatchResult(
4696 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
4697 << listener.str();
4698
4699 string prefix =
4700 "where no permutation of the elements can satisfy all matchers, "
4701 "and the closest match is 2 of 3 matchers with the "
4702 "pairings:\n";
4703
4704 // We have to be a bit loose here, because there are 4 valid max matches.
4705 EXPECT_THAT(
4706 listener.str(),
4707 AnyOf(prefix + "{\n " + EMString(0, 0) +
4708 ",\n " + EMString(1, 2) + "\n}",
4709 prefix + "{\n " + EMString(0, 1) +
4710 ",\n " + EMString(1, 2) + "\n}",
4711 prefix + "{\n " + EMString(0, 0) +
4712 ",\n " + EMString(2, 2) + "\n}",
4713 prefix + "{\n " + EMString(0, 1) +
4714 ",\n " + EMString(2, 2) + "\n}"));
4715}
4716
4717TEST_F(UnorderedElementsAreTest, Describe) {
4718 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
4719 Eq("is empty"));
4720 EXPECT_THAT(
4721 Describe<IntVec>(UnorderedElementsAre(345)),
4722 Eq("has 1 element and that element is equal to 345"));
4723 EXPECT_THAT(
4724 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
4725 Eq("has 3 elements and there exists some permutation "
4726 "of elements such that:\n"
4727 " - element #0 is equal to 111, and\n"
4728 " - element #1 is equal to 222, and\n"
4729 " - element #2 is equal to 333"));
4730}
4731
4732TEST_F(UnorderedElementsAreTest, DescribeNegation) {
4733 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
4734 Eq("isn't empty"));
4735 EXPECT_THAT(
4736 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
4737 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
4738 EXPECT_THAT(
4739 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
4740 Eq("doesn't have 3 elements, or there exists no permutation "
4741 "of elements such that:\n"
4742 " - element #0 is equal to 123, and\n"
4743 " - element #1 is equal to 234, and\n"
4744 " - element #2 is equal to 345"));
4745}
4746
4747namespace {
4748
4749// Used as a check on the more complex max flow method used in the
4750// real testing::internal::FindMaxBipartiteMatching. This method is
4751// compatible but runs in worst-case factorial time, so we only
4752// use it in testing for small problem sizes.
4753template <typename Graph>
4754class BacktrackingMaxBPMState {
4755 public:
4756 // Does not take ownership of 'g'.
4757 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
4758
4759 ElementMatcherPairs Compute() {
4760 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
4761 return best_so_far_;
4762 }
4763 lhs_used_.assign(graph_->LhsSize(), kUnused);
4764 rhs_used_.assign(graph_->RhsSize(), kUnused);
4765 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
4766 matches_.clear();
4767 RecurseInto(irhs);
4768 if (best_so_far_.size() == graph_->RhsSize())
4769 break;
4770 }
4771 return best_so_far_;
4772 }
4773
4774 private:
4775 static const size_t kUnused = static_cast<size_t>(-1);
4776
4777 void PushMatch(size_t lhs, size_t rhs) {
4778 matches_.push_back(ElementMatcherPair(lhs, rhs));
4779 lhs_used_[lhs] = rhs;
4780 rhs_used_[rhs] = lhs;
4781 if (matches_.size() > best_so_far_.size()) {
4782 best_so_far_ = matches_;
4783 }
4784 }
4785
4786 void PopMatch() {
4787 const ElementMatcherPair& back = matches_.back();
4788 lhs_used_[back.first] = kUnused;
4789 rhs_used_[back.second] = kUnused;
4790 matches_.pop_back();
4791 }
4792
4793 bool RecurseInto(size_t irhs) {
4794 if (rhs_used_[irhs] != kUnused) {
4795 return true;
4796 }
4797 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
4798 if (lhs_used_[ilhs] != kUnused) {
4799 continue;
4800 }
4801 if (!graph_->HasEdge(ilhs, irhs)) {
4802 continue;
4803 }
4804 PushMatch(ilhs, irhs);
4805 if (best_so_far_.size() == graph_->RhsSize()) {
4806 return false;
4807 }
4808 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
4809 if (!RecurseInto(mi)) return false;
4810 }
4811 PopMatch();
4812 }
4813 return true;
4814 }
4815
4816 const Graph* graph_; // not owned
4817 std::vector<size_t> lhs_used_;
4818 std::vector<size_t> rhs_used_;
4819 ElementMatcherPairs matches_;
4820 ElementMatcherPairs best_so_far_;
4821};
4822
4823template <typename Graph>
4824const size_t BacktrackingMaxBPMState<Graph>::kUnused;
4825
4826} // namespace
4827
4828// Implement a simple backtracking algorithm to determine if it is possible
4829// to find one element per matcher, without reusing elements.
4830template <typename Graph>
4831ElementMatcherPairs
4832FindBacktrackingMaxBPM(const Graph& g) {
4833 return BacktrackingMaxBPMState<Graph>(&g).Compute();
4834}
4835
4836class BacktrackingBPMTest : public ::testing::Test { };
4837
4838// Tests the MaxBipartiteMatching algorithm with square matrices.
4839// The single int param is the # of nodes on each of the left and right sides.
4840class BipartiteTest : public ::testing::TestWithParam<int> { };
4841
4842// Verify all match graphs up to some moderate number of edges.
4843TEST_P(BipartiteTest, Exhaustive) {
4844 int nodes = GetParam();
4845 MatchMatrix graph(nodes, nodes);
4846 do {
4847 ElementMatcherPairs matches =
4848 internal::FindMaxBipartiteMatching(graph);
4849 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
4850 << "graph: " << graph.DebugString();
4851 // Check that all elements of matches are in the graph.
4852 // Check that elements of first and second are unique.
4853 std::vector<bool> seen_element(graph.LhsSize());
4854 std::vector<bool> seen_matcher(graph.RhsSize());
4855 SCOPED_TRACE(PrintToString(matches));
4856 for (size_t i = 0; i < matches.size(); ++i) {
4857 size_t ilhs = matches[i].first;
4858 size_t irhs = matches[i].second;
4859 EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
4860 EXPECT_FALSE(seen_element[ilhs]);
4861 EXPECT_FALSE(seen_matcher[irhs]);
4862 seen_element[ilhs] = true;
4863 seen_matcher[irhs] = true;
4864 }
4865 } while (graph.NextGraph());
4866}
4867
4868INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest,
4869 ::testing::Range(0, 5));
4870
4871// Parameterized by a pair interpreted as (LhsSize, RhsSize).
4872class BipartiteNonSquareTest
4873 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
4874};
4875
4876TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
4877 // .......
4878 // 0:-----\ :
4879 // 1:---\ | :
4880 // 2:---\ | :
4881 // 3:-\ | | :
4882 // :.......:
4883 // 0 1 2
4884 MatchMatrix g(4, 3);
4885 static const int kEdges[][2] = { {0, 2}, {1, 1}, {2, 1}, {3, 0} };
kosak6414d802013-12-03 23:19:36 +00004886 for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00004887 g.SetEdge(kEdges[i][0], kEdges[i][1], true);
4888 }
4889 EXPECT_THAT(FindBacktrackingMaxBPM(g),
4890 ElementsAre(Pair(3, 0),
4891 Pair(AnyOf(1, 2), 1),
4892 Pair(0, 2))) << g.DebugString();
4893}
4894
4895// Verify a few nonsquare matrices.
4896TEST_P(BipartiteNonSquareTest, Exhaustive) {
4897 size_t nlhs = GetParam().first;
4898 size_t nrhs = GetParam().second;
4899 MatchMatrix graph(nlhs, nrhs);
4900 do {
4901 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
4902 internal::FindMaxBipartiteMatching(graph).size())
4903 << "graph: " << graph.DebugString()
4904 << "\nbacktracking: "
4905 << PrintToString(FindBacktrackingMaxBPM(graph))
4906 << "\nmax flow: "
4907 << PrintToString(internal::FindMaxBipartiteMatching(graph));
4908 } while (graph.NextGraph());
4909}
4910
4911INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest,
4912 testing::Values(
4913 std::make_pair(1, 2),
4914 std::make_pair(2, 1),
4915 std::make_pair(3, 2),
4916 std::make_pair(2, 3),
4917 std::make_pair(4, 1),
4918 std::make_pair(1, 4),
4919 std::make_pair(4, 3),
4920 std::make_pair(3, 4)));
4921
4922class BipartiteRandomTest
4923 : public ::testing::TestWithParam<std::pair<int, int> > {
4924};
4925
4926// Verifies a large sample of larger graphs.
4927TEST_P(BipartiteRandomTest, LargerNets) {
4928 int nodes = GetParam().first;
4929 int iters = GetParam().second;
4930 MatchMatrix graph(nodes, nodes);
4931
4932 testing::internal::Int32 seed = GTEST_FLAG(random_seed);
4933 if (seed == 0) {
4934 seed = static_cast<testing::internal::Int32>(time(NULL));
4935 }
4936
4937 for (; iters > 0; --iters, ++seed) {
4938 srand(static_cast<int>(seed));
4939 graph.Randomize();
4940 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
4941 internal::FindMaxBipartiteMatching(graph).size())
4942 << " graph: " << graph.DebugString()
4943 << "\nTo reproduce the failure, rerun the test with the flag"
4944 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
4945 }
4946}
4947
4948// Test argument is a std::pair<int, int> representing (nodes, iters).
4949INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest,
4950 testing::Values(
4951 std::make_pair(5, 10000),
4952 std::make_pair(6, 5000),
4953 std::make_pair(7, 2000),
4954 std::make_pair(8, 500),
4955 std::make_pair(9, 100)));
4956
zhanyong.wan736baa82010-09-27 17:44:16 +00004957// Tests IsReadableTypeName().
4958
4959TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
4960 EXPECT_TRUE(IsReadableTypeName("int"));
4961 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
4962 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
4963 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
4964}
4965
4966TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
4967 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
4968 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
4969 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
4970}
4971
4972TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
4973 EXPECT_FALSE(
4974 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
4975 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
4976}
4977
4978TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
4979 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
4980}
4981
zhanyong.wan4a5330d2009-02-19 00:36:44 +00004982// Tests JoinAsTuple().
4983
4984TEST(JoinAsTupleTest, JoinsEmptyTuple) {
4985 EXPECT_EQ("", JoinAsTuple(Strings()));
4986}
4987
4988TEST(JoinAsTupleTest, JoinsOneTuple) {
4989 const char* fields[] = { "1" };
4990 EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
4991}
4992
4993TEST(JoinAsTupleTest, JoinsTwoTuple) {
4994 const char* fields[] = { "1", "a" };
4995 EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
4996}
4997
4998TEST(JoinAsTupleTest, JoinsTenTuple) {
4999 const char* fields[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
5000 EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
5001 JoinAsTuple(Strings(fields, fields + 10)));
5002}
5003
5004// Tests FormatMatcherDescription().
5005
5006TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
5007 EXPECT_EQ("is even",
zhanyong.wanb4140802010-06-08 22:53:57 +00005008 FormatMatcherDescription(false, "IsEven", Strings()));
5009 EXPECT_EQ("not (is even)",
5010 FormatMatcherDescription(true, "IsEven", Strings()));
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005011
5012 const char* params[] = { "5" };
5013 EXPECT_EQ("equals 5",
zhanyong.wanb4140802010-06-08 22:53:57 +00005014 FormatMatcherDescription(false, "Equals",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005015 Strings(params, params + 1)));
5016
5017 const char* params2[] = { "5", "8" };
5018 EXPECT_EQ("is in range (5, 8)",
zhanyong.wanb4140802010-06-08 22:53:57 +00005019 FormatMatcherDescription(false, "IsInRange",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005020 Strings(params2, params2 + 2)));
5021}
5022
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00005023// Tests PolymorphicMatcher::mutable_impl().
5024TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
5025 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5026 DivisibleByImpl& impl = m.mutable_impl();
5027 EXPECT_EQ(42, impl.divider());
5028
5029 impl.set_divider(0);
5030 EXPECT_EQ(0, m.mutable_impl().divider());
5031}
5032
5033// Tests PolymorphicMatcher::impl().
5034TEST(PolymorphicMatcherTest, CanAccessImpl) {
5035 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5036 const DivisibleByImpl& impl = m.impl();
5037 EXPECT_EQ(42, impl.divider());
5038}
5039
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005040TEST(MatcherTupleTest, ExplainsMatchFailure) {
5041 stringstream ss1;
5042 ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
5043 make_tuple('a', 10), &ss1);
5044 EXPECT_EQ("", ss1.str()); // Successful match.
5045
5046 stringstream ss2;
5047 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5048 make_tuple(2, 'b'), &ss2);
5049 EXPECT_EQ(" Expected arg #0: is > 5\n"
5050 " Actual: 2, which is 3 less than 5\n"
zhanyong.wand60c5f42010-07-21 22:21:07 +00005051 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
5052 " Actual: 'b' (98, 0x62)\n",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005053 ss2.str()); // Failed match where both arguments need explanation.
5054
5055 stringstream ss3;
5056 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5057 make_tuple(2, 'a'), &ss3);
5058 EXPECT_EQ(" Expected arg #0: is > 5\n"
5059 " Actual: 2, which is 3 less than 5\n",
5060 ss3.str()); // Failed match where only one argument needs
5061 // explanation.
5062}
5063
zhanyong.wan33605ba2010-04-22 23:37:47 +00005064// Tests Each().
5065
5066TEST(EachTest, ExplainsMatchResultCorrectly) {
5067 set<int> a; // empty
5068
5069 Matcher<set<int> > m = Each(2);
5070 EXPECT_EQ("", Explain(m, a));
5071
zhanyong.wan736baa82010-09-27 17:44:16 +00005072 Matcher<const int(&)[1]> n = Each(1); // NOLINT
zhanyong.wan33605ba2010-04-22 23:37:47 +00005073
5074 const int b[1] = { 1 };
5075 EXPECT_EQ("", Explain(n, b));
5076
5077 n = Each(3);
5078 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
5079
5080 a.insert(1);
5081 a.insert(2);
5082 a.insert(3);
5083 m = Each(GreaterThan(0));
5084 EXPECT_EQ("", Explain(m, a));
5085
5086 m = Each(GreaterThan(10));
5087 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
5088 Explain(m, a));
5089}
5090
5091TEST(EachTest, DescribesItselfCorrectly) {
5092 Matcher<vector<int> > m = Each(1);
5093 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
5094
5095 Matcher<vector<int> > m2 = Not(m);
5096 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
5097}
5098
5099TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
5100 vector<int> some_vector;
5101 EXPECT_THAT(some_vector, Each(1));
5102 some_vector.push_back(3);
5103 EXPECT_THAT(some_vector, Not(Each(1)));
5104 EXPECT_THAT(some_vector, Each(3));
5105 some_vector.push_back(1);
5106 some_vector.push_back(2);
5107 EXPECT_THAT(some_vector, Not(Each(3)));
5108 EXPECT_THAT(some_vector, Each(Lt(3.5)));
5109
5110 vector<string> another_vector;
5111 another_vector.push_back("fee");
5112 EXPECT_THAT(another_vector, Each(string("fee")));
5113 another_vector.push_back("fie");
5114 another_vector.push_back("foe");
5115 another_vector.push_back("fum");
5116 EXPECT_THAT(another_vector, Not(Each(string("fee"))));
5117}
5118
5119TEST(EachTest, MatchesMapWhenAllElementsMatch) {
5120 map<const char*, int> my_map;
5121 const char* bar = "a string";
5122 my_map[bar] = 2;
5123 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
5124
5125 map<string, int> another_map;
5126 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5127 another_map["fee"] = 1;
5128 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5129 another_map["fie"] = 2;
5130 another_map["foe"] = 3;
5131 another_map["fum"] = 4;
5132 EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1))));
5133 EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1))));
5134 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
5135}
5136
5137TEST(EachTest, AcceptsMatcher) {
5138 const int a[] = { 1, 2, 3 };
5139 EXPECT_THAT(a, Each(Gt(0)));
5140 EXPECT_THAT(a, Not(Each(Gt(1))));
5141}
5142
5143TEST(EachTest, WorksForNativeArrayAsTuple) {
5144 const int a[] = { 1, 2 };
5145 const int* const pointer = a;
5146 EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
5147 EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
5148}
5149
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005150// For testing Pointwise().
5151class IsHalfOfMatcher {
5152 public:
5153 template <typename T1, typename T2>
5154 bool MatchAndExplain(const tuple<T1, T2>& a_pair,
5155 MatchResultListener* listener) const {
5156 if (get<0>(a_pair) == get<1>(a_pair)/2) {
5157 *listener << "where the second is " << get<1>(a_pair);
5158 return true;
5159 } else {
5160 *listener << "where the second/2 is " << get<1>(a_pair)/2;
5161 return false;
5162 }
5163 }
5164
5165 void DescribeTo(ostream* os) const {
5166 *os << "are a pair where the first is half of the second";
5167 }
5168
5169 void DescribeNegationTo(ostream* os) const {
5170 *os << "are a pair where the first isn't half of the second";
5171 }
5172};
5173
5174PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
5175 return MakePolymorphicMatcher(IsHalfOfMatcher());
5176}
5177
5178TEST(PointwiseTest, DescribesSelf) {
5179 vector<int> rhs;
5180 rhs.push_back(1);
5181 rhs.push_back(2);
5182 rhs.push_back(3);
5183 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
5184 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
5185 "in { 1, 2, 3 } are a pair where the first is half of the second",
5186 Describe(m));
5187 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
5188 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
5189 "where the first isn't half of the second",
5190 DescribeNegation(m));
5191}
5192
5193TEST(PointwiseTest, MakesCopyOfRhs) {
5194 list<signed char> rhs;
5195 rhs.push_back(2);
5196 rhs.push_back(4);
5197
5198 int lhs[] = { 1, 2 };
5199 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
5200 EXPECT_THAT(lhs, m);
5201
5202 // Changing rhs now shouldn't affect m, which made a copy of rhs.
5203 rhs.push_back(6);
5204 EXPECT_THAT(lhs, m);
5205}
5206
5207TEST(PointwiseTest, WorksForLhsNativeArray) {
5208 const int lhs[] = { 1, 2, 3 };
5209 vector<int> rhs;
5210 rhs.push_back(2);
5211 rhs.push_back(4);
5212 rhs.push_back(6);
5213 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
5214 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5215}
5216
5217TEST(PointwiseTest, WorksForRhsNativeArray) {
5218 const int rhs[] = { 1, 2, 3 };
5219 vector<int> lhs;
5220 lhs.push_back(2);
5221 lhs.push_back(4);
5222 lhs.push_back(6);
5223 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
5224 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
5225}
5226
5227TEST(PointwiseTest, RejectsWrongSize) {
5228 const double lhs[2] = { 1, 2 };
5229 const int rhs[1] = { 0 };
5230 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5231 EXPECT_EQ("which contains 2 values",
5232 Explain(Pointwise(Gt(), rhs), lhs));
5233
5234 const int rhs2[3] = { 0, 1, 2 };
5235 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
5236}
5237
5238TEST(PointwiseTest, RejectsWrongContent) {
5239 const double lhs[3] = { 1, 2, 3 };
5240 const int rhs[3] = { 2, 6, 4 };
5241 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
5242 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
5243 "where the second/2 is 3",
5244 Explain(Pointwise(IsHalfOf(), rhs), lhs));
5245}
5246
5247TEST(PointwiseTest, AcceptsCorrectContent) {
5248 const double lhs[3] = { 1, 2, 3 };
5249 const int rhs[3] = { 2, 4, 6 };
5250 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
5251 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
5252}
5253
5254TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
5255 const double lhs[3] = { 1, 2, 3 };
5256 const int rhs[3] = { 2, 4, 6 };
5257 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5258 EXPECT_THAT(lhs, Pointwise(m1, rhs));
5259 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
5260
5261 // This type works as a tuple<const double&, const int&> can be
5262 // implicitly cast to tuple<double, int>.
5263 const Matcher<tuple<double, int> > m2 = IsHalfOf();
5264 EXPECT_THAT(lhs, Pointwise(m2, rhs));
5265 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
5266}
5267
shiqiane35fdd92008-12-10 05:08:54 +00005268} // namespace gmock_matchers_test
5269} // namespace testing