blob: be2e9009ee73cc29f13260a87109a4a836487f10 [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file tests some commonly used argument matchers.
35
zhanyong.wan53e08c42010-09-14 05:38:21 +000036#include "gmock/gmock-matchers.h"
zhanyong.wan320814a2013-03-01 00:20:30 +000037#include "gmock/gmock-more-matchers.h"
shiqiane35fdd92008-12-10 05:08:54 +000038
39#include <string.h>
zhanyong.wanfb25d532013-07-28 08:24:00 +000040#include <time.h>
zhanyong.wana9a59e02013-03-27 16:14:55 +000041#include <deque>
shiqiane35fdd92008-12-10 05:08:54 +000042#include <functional>
zhanyong.wana862f1d2010-03-15 21:23:04 +000043#include <iostream>
zhanyong.wana9a59e02013-03-27 16:14:55 +000044#include <iterator>
zhanyong.wan616180e2013-06-18 18:49:51 +000045#include <limits>
zhanyong.wan6a896b52009-01-16 01:13:50 +000046#include <list>
47#include <map>
48#include <set>
shiqiane35fdd92008-12-10 05:08:54 +000049#include <sstream>
zhanyong.wan6a896b52009-01-16 01:13:50 +000050#include <string>
zhanyong.wanf5e1ce52009-09-16 07:02:02 +000051#include <utility>
zhanyong.wan6a896b52009-01-16 01:13:50 +000052#include <vector>
zhanyong.wan53e08c42010-09-14 05:38:21 +000053#include "gmock/gmock.h"
54#include "gtest/gtest.h"
55#include "gtest/gtest-spi.h"
shiqiane35fdd92008-12-10 05:08:54 +000056
kosak5b9cbbb2014-11-17 00:28:55 +000057#if GTEST_HAS_STD_FORWARD_LIST_
kosakb6a34882014-03-12 21:06:46 +000058# include <forward_list> // NOLINT
59#endif
60
shiqiane35fdd92008-12-10 05:08:54 +000061namespace testing {
zhanyong.wan4a5330d2009-02-19 00:36:44 +000062
63namespace internal {
vladlosev587c1b32011-05-20 00:42:22 +000064GTEST_API_ string JoinAsTuple(const Strings& fields);
zhanyong.wan4a5330d2009-02-19 00:36:44 +000065} // namespace internal
66
shiqiane35fdd92008-12-10 05:08:54 +000067namespace gmock_matchers_test {
68
zhanyong.wan898725c2011-09-16 16:45:39 +000069using std::greater;
70using std::less;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000071using std::list;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000072using std::make_pair;
zhanyong.wanb5937da2009-07-16 20:26:41 +000073using std::map;
74using std::multimap;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000075using std::multiset;
76using std::ostream;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000077using std::pair;
zhanyong.wan33605ba2010-04-22 23:37:47 +000078using std::set;
shiqiane35fdd92008-12-10 05:08:54 +000079using std::stringstream;
zhanyong.wan33605ba2010-04-22 23:37:47 +000080using std::vector;
shiqiane35fdd92008-12-10 05:08:54 +000081using testing::A;
zhanyong.wanbf550852009-06-09 06:09:53 +000082using testing::AllArgs;
shiqiane35fdd92008-12-10 05:08:54 +000083using testing::AllOf;
84using testing::An;
85using testing::AnyOf;
86using testing::ByRef;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000087using testing::ContainsRegex;
shiqiane35fdd92008-12-10 05:08:54 +000088using testing::DoubleEq;
zhanyong.wan616180e2013-06-18 18:49:51 +000089using testing::DoubleNear;
shiqiane35fdd92008-12-10 05:08:54 +000090using testing::EndsWith;
91using testing::Eq;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000092using testing::ExplainMatchResult;
shiqiane35fdd92008-12-10 05:08:54 +000093using testing::Field;
94using testing::FloatEq;
zhanyong.wan616180e2013-06-18 18:49:51 +000095using testing::FloatNear;
shiqiane35fdd92008-12-10 05:08:54 +000096using testing::Ge;
97using testing::Gt;
98using testing::HasSubstr;
zhanyong.wan320814a2013-03-01 00:20:30 +000099using testing::IsEmpty;
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000100using testing::IsNull;
zhanyong.wanb5937da2009-07-16 20:26:41 +0000101using testing::Key;
shiqiane35fdd92008-12-10 05:08:54 +0000102using testing::Le;
103using testing::Lt;
104using testing::MakeMatcher;
105using testing::MakePolymorphicMatcher;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000106using testing::MatchResultListener;
shiqiane35fdd92008-12-10 05:08:54 +0000107using testing::Matcher;
108using testing::MatcherCast;
109using testing::MatcherInterface;
110using testing::Matches;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000111using testing::MatchesRegex;
shiqiane35fdd92008-12-10 05:08:54 +0000112using testing::NanSensitiveDoubleEq;
zhanyong.wan616180e2013-06-18 18:49:51 +0000113using testing::NanSensitiveDoubleNear;
shiqiane35fdd92008-12-10 05:08:54 +0000114using testing::NanSensitiveFloatEq;
zhanyong.wan616180e2013-06-18 18:49:51 +0000115using testing::NanSensitiveFloatNear;
shiqiane35fdd92008-12-10 05:08:54 +0000116using testing::Ne;
117using testing::Not;
118using testing::NotNull;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000119using testing::Pair;
shiqiane35fdd92008-12-10 05:08:54 +0000120using testing::Pointee;
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000121using testing::Pointwise;
shiqiane35fdd92008-12-10 05:08:54 +0000122using testing::PolymorphicMatcher;
123using testing::Property;
124using testing::Ref;
125using testing::ResultOf;
zhanyong.wana31d9ce2013-03-01 01:50:17 +0000126using testing::SizeIs;
shiqiane35fdd92008-12-10 05:08:54 +0000127using testing::StartsWith;
128using testing::StrCaseEq;
129using testing::StrCaseNe;
130using testing::StrEq;
131using testing::StrNe;
kosak2336e9c2014-07-28 22:57:30 +0000132using testing::StringMatchResultListener;
shiqiane35fdd92008-12-10 05:08:54 +0000133using testing::Truly;
134using testing::TypedEq;
kosak2336e9c2014-07-28 22:57:30 +0000135using testing::UnorderedPointwise;
zhanyong.wanb8243162009-06-04 05:48:20 +0000136using testing::Value;
zhanyong.wan898725c2011-09-16 16:45:39 +0000137using testing::WhenSorted;
138using testing::WhenSortedBy;
shiqiane35fdd92008-12-10 05:08:54 +0000139using testing::_;
kosak2336e9c2014-07-28 22:57:30 +0000140using testing::get;
zhanyong.wana862f1d2010-03-15 21:23:04 +0000141using testing::internal::DummyMatchResultListener;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000142using testing::internal::ElementMatcherPair;
143using testing::internal::ElementMatcherPairs;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000144using testing::internal::ExplainMatchFailureTupleTo;
shiqiane35fdd92008-12-10 05:08:54 +0000145using testing::internal::FloatingEqMatcher;
zhanyong.wanb4140802010-06-08 22:53:57 +0000146using testing::internal::FormatMatcherDescription;
zhanyong.wan736baa82010-09-27 17:44:16 +0000147using testing::internal::IsReadableTypeName;
zhanyong.wan4a5330d2009-02-19 00:36:44 +0000148using testing::internal::JoinAsTuple;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000149using testing::internal::MatchMatrix;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000150using testing::internal::RE;
zhanyong.wana862f1d2010-03-15 21:23:04 +0000151using testing::internal::StreamMatchResultListener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000152using testing::internal::Strings;
vladlosev79b83502009-11-18 00:43:37 +0000153using testing::internal::linked_ptr;
vladloseve56daa72009-11-18 01:08:08 +0000154using testing::internal::scoped_ptr;
shiqiane35fdd92008-12-10 05:08:54 +0000155using testing::internal::string;
kosak2336e9c2014-07-28 22:57:30 +0000156using testing::make_tuple;
157using testing::tuple;
shiqiane35fdd92008-12-10 05:08:54 +0000158
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000159// For testing ExplainMatchResultTo().
160class GreaterThanMatcher : public MatcherInterface<int> {
161 public:
162 explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
163
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000164 virtual void DescribeTo(ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000165 *os << "is > " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000166 }
167
zhanyong.wandb22c222010-01-28 21:52:29 +0000168 virtual bool MatchAndExplain(int lhs,
169 MatchResultListener* listener) const {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000170 const int diff = lhs - rhs_;
171 if (diff > 0) {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000172 *listener << "which is " << diff << " more than " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000173 } else if (diff == 0) {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000174 *listener << "which is the same as " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000175 } else {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000176 *listener << "which is " << -diff << " less than " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000177 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000178
179 return lhs > rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000180 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000181
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000182 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000183 int rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000184};
185
186Matcher<int> GreaterThan(int n) {
187 return MakeMatcher(new GreaterThanMatcher(n));
188}
189
zhanyong.wan736baa82010-09-27 17:44:16 +0000190string OfType(const string& type_name) {
191#if GTEST_HAS_RTTI
192 return " (of type " + type_name + ")";
193#else
194 return "";
195#endif
196}
197
shiqiane35fdd92008-12-10 05:08:54 +0000198// Returns the description of the given matcher.
199template <typename T>
200string Describe(const Matcher<T>& m) {
201 stringstream ss;
202 m.DescribeTo(&ss);
203 return ss.str();
204}
205
206// Returns the description of the negation of the given matcher.
207template <typename T>
208string DescribeNegation(const Matcher<T>& m) {
209 stringstream ss;
210 m.DescribeNegationTo(&ss);
211 return ss.str();
212}
213
214// Returns the reason why x matches, or doesn't match, m.
215template <typename MatcherType, typename Value>
216string Explain(const MatcherType& m, const Value& x) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000217 StringMatchResultListener listener;
218 ExplainMatchResult(m, x, &listener);
219 return listener.str();
shiqiane35fdd92008-12-10 05:08:54 +0000220}
221
zhanyong.wana862f1d2010-03-15 21:23:04 +0000222TEST(MatchResultListenerTest, StreamingWorks) {
223 StringMatchResultListener listener;
224 listener << "hi" << 5;
225 EXPECT_EQ("hi5", listener.str());
226
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000227 listener.Clear();
228 EXPECT_EQ("", listener.str());
229
230 listener << 42;
231 EXPECT_EQ("42", listener.str());
232
zhanyong.wana862f1d2010-03-15 21:23:04 +0000233 // Streaming shouldn't crash when the underlying ostream is NULL.
234 DummyMatchResultListener dummy;
235 dummy << "hi" << 5;
236}
237
238TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
239 EXPECT_TRUE(DummyMatchResultListener().stream() == NULL);
240 EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL);
241
242 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
243}
244
245TEST(MatchResultListenerTest, IsInterestedWorks) {
246 EXPECT_TRUE(StringMatchResultListener().IsInterested());
247 EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
248
249 EXPECT_FALSE(DummyMatchResultListener().IsInterested());
250 EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested());
251}
252
shiqiane35fdd92008-12-10 05:08:54 +0000253// Makes sure that the MatcherInterface<T> interface doesn't
254// change.
255class EvenMatcherImpl : public MatcherInterface<int> {
256 public:
zhanyong.wandb22c222010-01-28 21:52:29 +0000257 virtual bool MatchAndExplain(int x,
258 MatchResultListener* /* listener */) const {
259 return x % 2 == 0;
260 }
shiqiane35fdd92008-12-10 05:08:54 +0000261
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000262 virtual void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +0000263 *os << "is an even number";
264 }
265
266 // We deliberately don't define DescribeNegationTo() and
267 // ExplainMatchResultTo() here, to make sure the definition of these
268 // two methods is optional.
269};
270
zhanyong.wana862f1d2010-03-15 21:23:04 +0000271// Makes sure that the MatcherInterface API doesn't change.
272TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
shiqiane35fdd92008-12-10 05:08:54 +0000273 EvenMatcherImpl m;
274}
275
zhanyong.wan82113312010-01-08 21:55:40 +0000276// Tests implementing a monomorphic matcher using MatchAndExplain().
277
278class NewEvenMatcherImpl : public MatcherInterface<int> {
279 public:
280 virtual bool MatchAndExplain(int x, MatchResultListener* listener) const {
281 const bool match = x % 2 == 0;
282 // Verifies that we can stream to a listener directly.
283 *listener << "value % " << 2;
284 if (listener->stream() != NULL) {
285 // Verifies that we can stream to a listener's underlying stream
286 // too.
287 *listener->stream() << " == " << (x % 2);
288 }
289 return match;
290 }
291
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000292 virtual void DescribeTo(ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000293 *os << "is an even number";
294 }
295};
296
297TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
298 Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
299 EXPECT_TRUE(m.Matches(2));
300 EXPECT_FALSE(m.Matches(3));
301 EXPECT_EQ("value % 2 == 0", Explain(m, 2));
302 EXPECT_EQ("value % 2 == 1", Explain(m, 3));
303}
304
shiqiane35fdd92008-12-10 05:08:54 +0000305// Tests default-constructing a matcher.
306TEST(MatcherTest, CanBeDefaultConstructed) {
307 Matcher<double> m;
308}
309
310// Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
311TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
312 const MatcherInterface<int>* impl = new EvenMatcherImpl;
313 Matcher<int> m(impl);
314 EXPECT_TRUE(m.Matches(4));
315 EXPECT_FALSE(m.Matches(5));
316}
317
318// Tests that value can be used in place of Eq(value).
319TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
320 Matcher<int> m1 = 5;
321 EXPECT_TRUE(m1.Matches(5));
322 EXPECT_FALSE(m1.Matches(6));
323}
324
325// Tests that NULL can be used in place of Eq(NULL).
326TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
327 Matcher<int*> m1 = NULL;
328 EXPECT_TRUE(m1.Matches(NULL));
329 int n = 0;
330 EXPECT_FALSE(m1.Matches(&n));
331}
332
333// Tests that matchers are copyable.
334TEST(MatcherTest, IsCopyable) {
335 // Tests the copy constructor.
336 Matcher<bool> m1 = Eq(false);
337 EXPECT_TRUE(m1.Matches(false));
338 EXPECT_FALSE(m1.Matches(true));
339
340 // Tests the assignment operator.
341 m1 = Eq(true);
342 EXPECT_TRUE(m1.Matches(true));
343 EXPECT_FALSE(m1.Matches(false));
344}
345
346// Tests that Matcher<T>::DescribeTo() calls
347// MatcherInterface<T>::DescribeTo().
348TEST(MatcherTest, CanDescribeItself) {
349 EXPECT_EQ("is an even number",
350 Describe(Matcher<int>(new EvenMatcherImpl)));
351}
352
zhanyong.wan82113312010-01-08 21:55:40 +0000353// Tests Matcher<T>::MatchAndExplain().
354TEST(MatcherTest, MatchAndExplain) {
355 Matcher<int> m = GreaterThan(0);
zhanyong.wan34b034c2010-03-05 21:23:23 +0000356 StringMatchResultListener listener1;
zhanyong.wan82113312010-01-08 21:55:40 +0000357 EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000358 EXPECT_EQ("which is 42 more than 0", listener1.str());
zhanyong.wan82113312010-01-08 21:55:40 +0000359
zhanyong.wan34b034c2010-03-05 21:23:23 +0000360 StringMatchResultListener listener2;
zhanyong.wan82113312010-01-08 21:55:40 +0000361 EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000362 EXPECT_EQ("which is 9 less than 0", listener2.str());
zhanyong.wan82113312010-01-08 21:55:40 +0000363}
364
shiqiane35fdd92008-12-10 05:08:54 +0000365// Tests that a C-string literal can be implicitly converted to a
366// Matcher<string> or Matcher<const string&>.
367TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
368 Matcher<string> m1 = "hi";
369 EXPECT_TRUE(m1.Matches("hi"));
370 EXPECT_FALSE(m1.Matches("hello"));
371
372 Matcher<const string&> m2 = "hi";
373 EXPECT_TRUE(m2.Matches("hi"));
374 EXPECT_FALSE(m2.Matches("hello"));
375}
376
377// Tests that a string object can be implicitly converted to a
378// Matcher<string> or Matcher<const string&>.
379TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
380 Matcher<string> m1 = string("hi");
381 EXPECT_TRUE(m1.Matches("hi"));
382 EXPECT_FALSE(m1.Matches("hello"));
383
384 Matcher<const string&> m2 = string("hi");
385 EXPECT_TRUE(m2.Matches("hi"));
386 EXPECT_FALSE(m2.Matches("hello"));
387}
388
zhanyong.wan1f122a02013-03-25 16:27:03 +0000389#if GTEST_HAS_STRING_PIECE_
390// Tests that a C-string literal can be implicitly converted to a
391// Matcher<StringPiece> or Matcher<const StringPiece&>.
392TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
393 Matcher<StringPiece> m1 = "cats";
394 EXPECT_TRUE(m1.Matches("cats"));
395 EXPECT_FALSE(m1.Matches("dogs"));
396
397 Matcher<const StringPiece&> m2 = "cats";
398 EXPECT_TRUE(m2.Matches("cats"));
399 EXPECT_FALSE(m2.Matches("dogs"));
400}
401
402// Tests that a string object can be implicitly converted to a
403// Matcher<StringPiece> or Matcher<const StringPiece&>.
404TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromString) {
405 Matcher<StringPiece> m1 = string("cats");
406 EXPECT_TRUE(m1.Matches("cats"));
407 EXPECT_FALSE(m1.Matches("dogs"));
408
409 Matcher<const StringPiece&> m2 = string("cats");
410 EXPECT_TRUE(m2.Matches("cats"));
411 EXPECT_FALSE(m2.Matches("dogs"));
412}
413
414// Tests that a StringPiece object can be implicitly converted to a
415// Matcher<StringPiece> or Matcher<const StringPiece&>.
416TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromStringPiece) {
417 Matcher<StringPiece> m1 = StringPiece("cats");
418 EXPECT_TRUE(m1.Matches("cats"));
419 EXPECT_FALSE(m1.Matches("dogs"));
420
421 Matcher<const StringPiece&> m2 = StringPiece("cats");
422 EXPECT_TRUE(m2.Matches("cats"));
423 EXPECT_FALSE(m2.Matches("dogs"));
424}
425#endif // GTEST_HAS_STRING_PIECE_
426
shiqiane35fdd92008-12-10 05:08:54 +0000427// Tests that MakeMatcher() constructs a Matcher<T> from a
428// MatcherInterface* without requiring the user to explicitly
429// write the type.
430TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
431 const MatcherInterface<int>* dummy_impl = NULL;
432 Matcher<int> m = MakeMatcher(dummy_impl);
433}
434
zhanyong.wan82113312010-01-08 21:55:40 +0000435// Tests that MakePolymorphicMatcher() can construct a polymorphic
436// matcher from its implementation using the old API.
zhanyong.wan33605ba2010-04-22 23:37:47 +0000437const int g_bar = 1;
shiqiane35fdd92008-12-10 05:08:54 +0000438class ReferencesBarOrIsZeroImpl {
439 public:
440 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +0000441 bool MatchAndExplain(const T& x,
442 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000443 const void* p = &x;
zhanyong.wan33605ba2010-04-22 23:37:47 +0000444 return p == &g_bar || x == 0;
shiqiane35fdd92008-12-10 05:08:54 +0000445 }
446
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000447 void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
shiqiane35fdd92008-12-10 05:08:54 +0000448
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000449 void DescribeNegationTo(ostream* os) const {
zhanyong.wan33605ba2010-04-22 23:37:47 +0000450 *os << "doesn't reference g_bar and is not zero";
shiqiane35fdd92008-12-10 05:08:54 +0000451 }
452};
453
454// This function verifies that MakePolymorphicMatcher() returns a
455// PolymorphicMatcher<T> where T is the argument's type.
456PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
457 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
458}
459
zhanyong.wan82113312010-01-08 21:55:40 +0000460TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
shiqiane35fdd92008-12-10 05:08:54 +0000461 // Using a polymorphic matcher to match a reference type.
462 Matcher<const int&> m1 = ReferencesBarOrIsZero();
463 EXPECT_TRUE(m1.Matches(0));
464 // Verifies that the identity of a by-reference argument is preserved.
zhanyong.wan33605ba2010-04-22 23:37:47 +0000465 EXPECT_TRUE(m1.Matches(g_bar));
shiqiane35fdd92008-12-10 05:08:54 +0000466 EXPECT_FALSE(m1.Matches(1));
zhanyong.wan33605ba2010-04-22 23:37:47 +0000467 EXPECT_EQ("g_bar or zero", Describe(m1));
shiqiane35fdd92008-12-10 05:08:54 +0000468
469 // Using a polymorphic matcher to match a value type.
470 Matcher<double> m2 = ReferencesBarOrIsZero();
471 EXPECT_TRUE(m2.Matches(0.0));
472 EXPECT_FALSE(m2.Matches(0.1));
zhanyong.wan33605ba2010-04-22 23:37:47 +0000473 EXPECT_EQ("g_bar or zero", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +0000474}
475
zhanyong.wan82113312010-01-08 21:55:40 +0000476// Tests implementing a polymorphic matcher using MatchAndExplain().
477
478class PolymorphicIsEvenImpl {
479 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000480 void DescribeTo(ostream* os) const { *os << "is even"; }
zhanyong.wan82113312010-01-08 21:55:40 +0000481
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000482 void DescribeNegationTo(ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000483 *os << "is odd";
484 }
zhanyong.wan82113312010-01-08 21:55:40 +0000485
zhanyong.wandb22c222010-01-28 21:52:29 +0000486 template <typename T>
487 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
488 // Verifies that we can stream to the listener directly.
489 *listener << "% " << 2;
490 if (listener->stream() != NULL) {
491 // Verifies that we can stream to the listener's underlying stream
492 // too.
493 *listener->stream() << " == " << (x % 2);
494 }
495 return (x % 2) == 0;
zhanyong.wan82113312010-01-08 21:55:40 +0000496 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000497};
zhanyong.wan82113312010-01-08 21:55:40 +0000498
499PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
500 return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
501}
502
503TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
504 // Using PolymorphicIsEven() as a Matcher<int>.
505 const Matcher<int> m1 = PolymorphicIsEven();
506 EXPECT_TRUE(m1.Matches(42));
507 EXPECT_FALSE(m1.Matches(43));
508 EXPECT_EQ("is even", Describe(m1));
509
510 const Matcher<int> not_m1 = Not(m1);
511 EXPECT_EQ("is odd", Describe(not_m1));
512
513 EXPECT_EQ("% 2 == 0", Explain(m1, 42));
514
515 // Using PolymorphicIsEven() as a Matcher<char>.
516 const Matcher<char> m2 = PolymorphicIsEven();
517 EXPECT_TRUE(m2.Matches('\x42'));
518 EXPECT_FALSE(m2.Matches('\x43'));
519 EXPECT_EQ("is even", Describe(m2));
520
521 const Matcher<char> not_m2 = Not(m2);
522 EXPECT_EQ("is odd", Describe(not_m2));
523
524 EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
525}
526
shiqiane35fdd92008-12-10 05:08:54 +0000527// Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
528TEST(MatcherCastTest, FromPolymorphicMatcher) {
529 Matcher<int> m = MatcherCast<int>(Eq(5));
530 EXPECT_TRUE(m.Matches(5));
531 EXPECT_FALSE(m.Matches(6));
532}
533
534// For testing casting matchers between compatible types.
535class IntValue {
536 public:
537 // An int can be statically (although not implicitly) cast to a
538 // IntValue.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000539 explicit IntValue(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +0000540
541 int value() const { return value_; }
542 private:
543 int value_;
544};
545
546// For testing casting matchers between compatible types.
547bool IsPositiveIntValue(const IntValue& foo) {
548 return foo.value() > 0;
549}
550
551// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
552// can be statically converted to U.
553TEST(MatcherCastTest, FromCompatibleType) {
554 Matcher<double> m1 = Eq(2.0);
555 Matcher<int> m2 = MatcherCast<int>(m1);
556 EXPECT_TRUE(m2.Matches(2));
557 EXPECT_FALSE(m2.Matches(3));
558
559 Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
560 Matcher<int> m4 = MatcherCast<int>(m3);
561 // In the following, the arguments 1 and 0 are statically converted
562 // to IntValue objects, and then tested by the IsPositiveIntValue()
563 // predicate.
564 EXPECT_TRUE(m4.Matches(1));
565 EXPECT_FALSE(m4.Matches(0));
566}
567
568// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
569TEST(MatcherCastTest, FromConstReferenceToNonReference) {
570 Matcher<const int&> m1 = Eq(0);
571 Matcher<int> m2 = MatcherCast<int>(m1);
572 EXPECT_TRUE(m2.Matches(0));
573 EXPECT_FALSE(m2.Matches(1));
574}
575
576// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
577TEST(MatcherCastTest, FromReferenceToNonReference) {
578 Matcher<int&> m1 = Eq(0);
579 Matcher<int> m2 = MatcherCast<int>(m1);
580 EXPECT_TRUE(m2.Matches(0));
581 EXPECT_FALSE(m2.Matches(1));
582}
583
584// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
585TEST(MatcherCastTest, FromNonReferenceToConstReference) {
586 Matcher<int> m1 = Eq(0);
587 Matcher<const int&> m2 = MatcherCast<const int&>(m1);
588 EXPECT_TRUE(m2.Matches(0));
589 EXPECT_FALSE(m2.Matches(1));
590}
591
592// Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
593TEST(MatcherCastTest, FromNonReferenceToReference) {
594 Matcher<int> m1 = Eq(0);
595 Matcher<int&> m2 = MatcherCast<int&>(m1);
596 int n = 0;
597 EXPECT_TRUE(m2.Matches(n));
598 n = 1;
599 EXPECT_FALSE(m2.Matches(n));
600}
601
602// Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
603TEST(MatcherCastTest, FromSameType) {
604 Matcher<int> m1 = Eq(0);
605 Matcher<int> m2 = MatcherCast<int>(m1);
606 EXPECT_TRUE(m2.Matches(0));
607 EXPECT_FALSE(m2.Matches(1));
608}
609
kosak506340a2014-11-17 01:47:54 +0000610// Implicitly convertible from any type.
jgm79a367e2012-04-10 16:02:11 +0000611struct ConvertibleFromAny {
612 ConvertibleFromAny(int a_value) : value(a_value) {}
613 template <typename T>
kosak506340a2014-11-17 01:47:54 +0000614 ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
jgm79a367e2012-04-10 16:02:11 +0000615 ADD_FAILURE() << "Conversion constructor called";
616 }
617 int value;
618};
619
620bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
621 return a.value == b.value;
622}
623
624ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
625 return os << a.value;
626}
627
628TEST(MatcherCastTest, ConversionConstructorIsUsed) {
629 Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
630 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
631 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
632}
633
634TEST(MatcherCastTest, FromConvertibleFromAny) {
635 Matcher<ConvertibleFromAny> m =
636 MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
637 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
638 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
639}
640
kosak5f2a6ca2013-12-03 01:43:07 +0000641struct IntReferenceWrapper {
642 IntReferenceWrapper(const int& a_value) : value(&a_value) {}
643 const int* value;
644};
645
646bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
647 return a.value == b.value;
648}
649
650TEST(MatcherCastTest, ValueIsNotCopied) {
651 int n = 42;
652 Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
653 // Verify that the matcher holds a reference to n, not to its temporary copy.
654 EXPECT_TRUE(m.Matches(n));
655}
656
billydonahue1f5fdea2014-05-19 17:54:51 +0000657class Base {
658 public:
659 virtual ~Base() {}
660 Base() {}
661 private:
662 GTEST_DISALLOW_COPY_AND_ASSIGN_(Base);
663};
664
665class Derived : public Base {
666 public:
667 Derived() : Base() {}
668 int i;
669};
670
671class OtherDerived : public Base {};
zhanyong.wan18490652009-05-11 18:54:08 +0000672
673// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
674TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
675 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
676 EXPECT_TRUE(m2.Matches(' '));
677 EXPECT_FALSE(m2.Matches('\n'));
678}
679
zhanyong.wan16cf4732009-05-14 20:55:30 +0000680// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
681// T and U are arithmetic types and T can be losslessly converted to
682// U.
683TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
zhanyong.wan18490652009-05-11 18:54:08 +0000684 Matcher<double> m1 = DoubleEq(1.0);
zhanyong.wan16cf4732009-05-14 20:55:30 +0000685 Matcher<float> m2 = SafeMatcherCast<float>(m1);
686 EXPECT_TRUE(m2.Matches(1.0f));
687 EXPECT_FALSE(m2.Matches(2.0f));
688
689 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
690 EXPECT_TRUE(m3.Matches('a'));
691 EXPECT_FALSE(m3.Matches('b'));
zhanyong.wan18490652009-05-11 18:54:08 +0000692}
693
694// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
695// are pointers or references to a derived and a base class, correspondingly.
696TEST(SafeMatcherCastTest, FromBaseClass) {
697 Derived d, d2;
698 Matcher<Base*> m1 = Eq(&d);
699 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
700 EXPECT_TRUE(m2.Matches(&d));
701 EXPECT_FALSE(m2.Matches(&d2));
702
703 Matcher<Base&> m3 = Ref(d);
704 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
705 EXPECT_TRUE(m4.Matches(d));
706 EXPECT_FALSE(m4.Matches(d2));
707}
708
709// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
710TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
711 int n = 0;
712 Matcher<const int&> m1 = Ref(n);
713 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
714 int n1 = 0;
715 EXPECT_TRUE(m2.Matches(n));
716 EXPECT_FALSE(m2.Matches(n1));
717}
718
719// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
720TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
721 Matcher<int> m1 = Eq(0);
722 Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
723 EXPECT_TRUE(m2.Matches(0));
724 EXPECT_FALSE(m2.Matches(1));
725}
726
727// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
728TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
729 Matcher<int> m1 = Eq(0);
730 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
731 int n = 0;
732 EXPECT_TRUE(m2.Matches(n));
733 n = 1;
734 EXPECT_FALSE(m2.Matches(n));
735}
736
737// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
738TEST(SafeMatcherCastTest, FromSameType) {
739 Matcher<int> m1 = Eq(0);
740 Matcher<int> m2 = SafeMatcherCast<int>(m1);
741 EXPECT_TRUE(m2.Matches(0));
742 EXPECT_FALSE(m2.Matches(1));
743}
744
jgm79a367e2012-04-10 16:02:11 +0000745TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
746 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
747 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
748 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
749}
750
751TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
752 Matcher<ConvertibleFromAny> m =
753 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
754 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
755 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
756}
757
kosak5f2a6ca2013-12-03 01:43:07 +0000758TEST(SafeMatcherCastTest, ValueIsNotCopied) {
759 int n = 42;
760 Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
761 // Verify that the matcher holds a reference to n, not to its temporary copy.
762 EXPECT_TRUE(m.Matches(n));
763}
764
shiqiane35fdd92008-12-10 05:08:54 +0000765// Tests that A<T>() matches any value of type T.
766TEST(ATest, MatchesAnyValue) {
767 // Tests a matcher for a value type.
768 Matcher<double> m1 = A<double>();
769 EXPECT_TRUE(m1.Matches(91.43));
770 EXPECT_TRUE(m1.Matches(-15.32));
771
772 // Tests a matcher for a reference type.
773 int a = 2;
774 int b = -6;
775 Matcher<int&> m2 = A<int&>();
776 EXPECT_TRUE(m2.Matches(a));
777 EXPECT_TRUE(m2.Matches(b));
778}
779
zhanyong.wanf4274522013-04-24 02:49:43 +0000780TEST(ATest, WorksForDerivedClass) {
781 Base base;
782 Derived derived;
783 EXPECT_THAT(&base, A<Base*>());
784 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
785 EXPECT_THAT(&derived, A<Base*>());
786 EXPECT_THAT(&derived, A<Derived*>());
787}
788
shiqiane35fdd92008-12-10 05:08:54 +0000789// Tests that A<T>() describes itself properly.
790TEST(ATest, CanDescribeSelf) {
791 EXPECT_EQ("is anything", Describe(A<bool>()));
792}
793
794// Tests that An<T>() matches any value of type T.
795TEST(AnTest, MatchesAnyValue) {
796 // Tests a matcher for a value type.
797 Matcher<int> m1 = An<int>();
798 EXPECT_TRUE(m1.Matches(9143));
799 EXPECT_TRUE(m1.Matches(-1532));
800
801 // Tests a matcher for a reference type.
802 int a = 2;
803 int b = -6;
804 Matcher<int&> m2 = An<int&>();
805 EXPECT_TRUE(m2.Matches(a));
806 EXPECT_TRUE(m2.Matches(b));
807}
808
809// Tests that An<T>() describes itself properly.
810TEST(AnTest, CanDescribeSelf) {
811 EXPECT_EQ("is anything", Describe(An<int>()));
812}
813
814// Tests that _ can be used as a matcher for any type and matches any
815// value of that type.
816TEST(UnderscoreTest, MatchesAnyValue) {
817 // Uses _ as a matcher for a value type.
818 Matcher<int> m1 = _;
819 EXPECT_TRUE(m1.Matches(123));
820 EXPECT_TRUE(m1.Matches(-242));
821
822 // Uses _ as a matcher for a reference type.
823 bool a = false;
824 const bool b = true;
825 Matcher<const bool&> m2 = _;
826 EXPECT_TRUE(m2.Matches(a));
827 EXPECT_TRUE(m2.Matches(b));
828}
829
830// Tests that _ describes itself properly.
831TEST(UnderscoreTest, CanDescribeSelf) {
832 Matcher<int> m = _;
833 EXPECT_EQ("is anything", Describe(m));
834}
835
836// Tests that Eq(x) matches any value equal to x.
837TEST(EqTest, MatchesEqualValue) {
838 // 2 C-strings with same content but different addresses.
839 const char a1[] = "hi";
840 const char a2[] = "hi";
841
842 Matcher<const char*> m1 = Eq(a1);
843 EXPECT_TRUE(m1.Matches(a1));
844 EXPECT_FALSE(m1.Matches(a2));
845}
846
847// Tests that Eq(v) describes itself properly.
848
849class Unprintable {
850 public:
851 Unprintable() : c_('a') {}
852
zhanyong.wan32de5f52009-12-23 00:13:23 +0000853 bool operator==(const Unprintable& /* rhs */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000854 private:
855 char c_;
856};
857
858TEST(EqTest, CanDescribeSelf) {
859 Matcher<Unprintable> m = Eq(Unprintable());
860 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
861}
862
863// Tests that Eq(v) can be used to match any type that supports
864// comparing with type T, where T is v's type.
865TEST(EqTest, IsPolymorphic) {
866 Matcher<int> m1 = Eq(1);
867 EXPECT_TRUE(m1.Matches(1));
868 EXPECT_FALSE(m1.Matches(2));
869
870 Matcher<char> m2 = Eq(1);
871 EXPECT_TRUE(m2.Matches('\1'));
872 EXPECT_FALSE(m2.Matches('a'));
873}
874
875// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
876TEST(TypedEqTest, ChecksEqualityForGivenType) {
877 Matcher<char> m1 = TypedEq<char>('a');
878 EXPECT_TRUE(m1.Matches('a'));
879 EXPECT_FALSE(m1.Matches('b'));
880
881 Matcher<int> m2 = TypedEq<int>(6);
882 EXPECT_TRUE(m2.Matches(6));
883 EXPECT_FALSE(m2.Matches(7));
884}
885
886// Tests that TypedEq(v) describes itself properly.
887TEST(TypedEqTest, CanDescribeSelf) {
888 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
889}
890
891// Tests that TypedEq<T>(v) has type Matcher<T>.
892
893// Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
894// is a "bare" type (i.e. not in the form of const U or U&). If v's
895// type is not T, the compiler will generate a message about
896// "undefined referece".
897template <typename T>
898struct Type {
zhanyong.wan32de5f52009-12-23 00:13:23 +0000899 static bool IsTypeOf(const T& /* v */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000900
901 template <typename T2>
902 static void IsTypeOf(T2 v);
903};
904
905TEST(TypedEqTest, HasSpecifiedType) {
906 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
907 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
908 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
909}
910
911// Tests that Ge(v) matches anything >= v.
912TEST(GeTest, ImplementsGreaterThanOrEqual) {
913 Matcher<int> m1 = Ge(0);
914 EXPECT_TRUE(m1.Matches(1));
915 EXPECT_TRUE(m1.Matches(0));
916 EXPECT_FALSE(m1.Matches(-1));
917}
918
919// Tests that Ge(v) describes itself properly.
920TEST(GeTest, CanDescribeSelf) {
921 Matcher<int> m = Ge(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000922 EXPECT_EQ("is >= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000923}
924
925// Tests that Gt(v) matches anything > v.
926TEST(GtTest, ImplementsGreaterThan) {
927 Matcher<double> m1 = Gt(0);
928 EXPECT_TRUE(m1.Matches(1.0));
929 EXPECT_FALSE(m1.Matches(0.0));
930 EXPECT_FALSE(m1.Matches(-1.0));
931}
932
933// Tests that Gt(v) describes itself properly.
934TEST(GtTest, CanDescribeSelf) {
935 Matcher<int> m = Gt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000936 EXPECT_EQ("is > 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000937}
938
939// Tests that Le(v) matches anything <= v.
940TEST(LeTest, ImplementsLessThanOrEqual) {
941 Matcher<char> m1 = Le('b');
942 EXPECT_TRUE(m1.Matches('a'));
943 EXPECT_TRUE(m1.Matches('b'));
944 EXPECT_FALSE(m1.Matches('c'));
945}
946
947// Tests that Le(v) describes itself properly.
948TEST(LeTest, CanDescribeSelf) {
949 Matcher<int> m = Le(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000950 EXPECT_EQ("is <= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000951}
952
953// Tests that Lt(v) matches anything < v.
954TEST(LtTest, ImplementsLessThan) {
955 Matcher<const string&> m1 = Lt("Hello");
956 EXPECT_TRUE(m1.Matches("Abc"));
957 EXPECT_FALSE(m1.Matches("Hello"));
958 EXPECT_FALSE(m1.Matches("Hello, world!"));
959}
960
961// Tests that Lt(v) describes itself properly.
962TEST(LtTest, CanDescribeSelf) {
963 Matcher<int> m = Lt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000964 EXPECT_EQ("is < 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000965}
966
967// Tests that Ne(v) matches anything != v.
968TEST(NeTest, ImplementsNotEqual) {
969 Matcher<int> m1 = Ne(0);
970 EXPECT_TRUE(m1.Matches(1));
971 EXPECT_TRUE(m1.Matches(-1));
972 EXPECT_FALSE(m1.Matches(0));
973}
974
975// Tests that Ne(v) describes itself properly.
976TEST(NeTest, CanDescribeSelf) {
977 Matcher<int> m = Ne(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000978 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000979}
980
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000981// Tests that IsNull() matches any NULL pointer of any type.
982TEST(IsNullTest, MatchesNullPointer) {
983 Matcher<int*> m1 = IsNull();
984 int* p1 = NULL;
985 int n = 0;
986 EXPECT_TRUE(m1.Matches(p1));
987 EXPECT_FALSE(m1.Matches(&n));
988
989 Matcher<const char*> m2 = IsNull();
990 const char* p2 = NULL;
991 EXPECT_TRUE(m2.Matches(p2));
992 EXPECT_FALSE(m2.Matches("hi"));
993
zhanyong.wan95b12332009-09-25 18:55:50 +0000994#if !GTEST_OS_SYMBIAN
995 // Nokia's Symbian compiler generates:
996 // gmock-matchers.h: ambiguous access to overloaded function
997 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
998 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
999 // MatcherInterface<void *> *)'
1000 // gmock-matchers.h: (point of instantiation: 'testing::
1001 // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
1002 // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001003 Matcher<void*> m3 = IsNull();
1004 void* p3 = NULL;
1005 EXPECT_TRUE(m3.Matches(p3));
1006 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
zhanyong.wan95b12332009-09-25 18:55:50 +00001007#endif
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001008}
1009
vladlosev79b83502009-11-18 00:43:37 +00001010TEST(IsNullTest, LinkedPtr) {
1011 const Matcher<linked_ptr<int> > m = IsNull();
1012 const linked_ptr<int> null_p;
1013 const linked_ptr<int> non_null_p(new int);
1014
1015 EXPECT_TRUE(m.Matches(null_p));
1016 EXPECT_FALSE(m.Matches(non_null_p));
1017}
1018
1019TEST(IsNullTest, ReferenceToConstLinkedPtr) {
1020 const Matcher<const linked_ptr<double>&> m = IsNull();
1021 const linked_ptr<double> null_p;
1022 const linked_ptr<double> non_null_p(new double);
1023
1024 EXPECT_TRUE(m.Matches(null_p));
1025 EXPECT_FALSE(m.Matches(non_null_p));
1026}
1027
vladloseve56daa72009-11-18 01:08:08 +00001028TEST(IsNullTest, ReferenceToConstScopedPtr) {
1029 const Matcher<const scoped_ptr<double>&> m = IsNull();
1030 const scoped_ptr<double> null_p;
1031 const scoped_ptr<double> non_null_p(new double);
1032
1033 EXPECT_TRUE(m.Matches(null_p));
1034 EXPECT_FALSE(m.Matches(non_null_p));
1035}
1036
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001037// Tests that IsNull() describes itself properly.
1038TEST(IsNullTest, CanDescribeSelf) {
1039 Matcher<int*> m = IsNull();
1040 EXPECT_EQ("is NULL", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001041 EXPECT_EQ("isn't NULL", DescribeNegation(m));
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001042}
1043
shiqiane35fdd92008-12-10 05:08:54 +00001044// Tests that NotNull() matches any non-NULL pointer of any type.
1045TEST(NotNullTest, MatchesNonNullPointer) {
1046 Matcher<int*> m1 = NotNull();
1047 int* p1 = NULL;
1048 int n = 0;
1049 EXPECT_FALSE(m1.Matches(p1));
1050 EXPECT_TRUE(m1.Matches(&n));
1051
1052 Matcher<const char*> m2 = NotNull();
1053 const char* p2 = NULL;
1054 EXPECT_FALSE(m2.Matches(p2));
1055 EXPECT_TRUE(m2.Matches("hi"));
1056}
1057
vladlosev79b83502009-11-18 00:43:37 +00001058TEST(NotNullTest, LinkedPtr) {
1059 const Matcher<linked_ptr<int> > m = NotNull();
1060 const linked_ptr<int> null_p;
1061 const linked_ptr<int> non_null_p(new int);
1062
1063 EXPECT_FALSE(m.Matches(null_p));
1064 EXPECT_TRUE(m.Matches(non_null_p));
1065}
1066
1067TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1068 const Matcher<const linked_ptr<double>&> m = NotNull();
1069 const linked_ptr<double> null_p;
1070 const linked_ptr<double> non_null_p(new double);
1071
1072 EXPECT_FALSE(m.Matches(null_p));
1073 EXPECT_TRUE(m.Matches(non_null_p));
1074}
1075
vladloseve56daa72009-11-18 01:08:08 +00001076TEST(NotNullTest, ReferenceToConstScopedPtr) {
1077 const Matcher<const scoped_ptr<double>&> m = NotNull();
1078 const scoped_ptr<double> null_p;
1079 const scoped_ptr<double> non_null_p(new double);
1080
1081 EXPECT_FALSE(m.Matches(null_p));
1082 EXPECT_TRUE(m.Matches(non_null_p));
1083}
1084
shiqiane35fdd92008-12-10 05:08:54 +00001085// Tests that NotNull() describes itself properly.
1086TEST(NotNullTest, CanDescribeSelf) {
1087 Matcher<int*> m = NotNull();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001088 EXPECT_EQ("isn't NULL", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001089}
1090
1091// Tests that Ref(variable) matches an argument that references
1092// 'variable'.
1093TEST(RefTest, MatchesSameVariable) {
1094 int a = 0;
1095 int b = 0;
1096 Matcher<int&> m = Ref(a);
1097 EXPECT_TRUE(m.Matches(a));
1098 EXPECT_FALSE(m.Matches(b));
1099}
1100
1101// Tests that Ref(variable) describes itself properly.
1102TEST(RefTest, CanDescribeSelf) {
1103 int n = 5;
1104 Matcher<int&> m = Ref(n);
1105 stringstream ss;
1106 ss << "references the variable @" << &n << " 5";
1107 EXPECT_EQ(string(ss.str()), Describe(m));
1108}
1109
1110// Test that Ref(non_const_varialbe) can be used as a matcher for a
1111// const reference.
1112TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1113 int a = 0;
1114 int b = 0;
1115 Matcher<const int&> m = Ref(a);
1116 EXPECT_TRUE(m.Matches(a));
1117 EXPECT_FALSE(m.Matches(b));
1118}
1119
1120// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1121// used wherever Ref(base) can be used (Ref(derived) is a sub-type
1122// of Ref(base), but not vice versa.
1123
shiqiane35fdd92008-12-10 05:08:54 +00001124TEST(RefTest, IsCovariant) {
1125 Base base, base2;
1126 Derived derived;
1127 Matcher<const Base&> m1 = Ref(base);
1128 EXPECT_TRUE(m1.Matches(base));
1129 EXPECT_FALSE(m1.Matches(base2));
1130 EXPECT_FALSE(m1.Matches(derived));
1131
1132 m1 = Ref(derived);
1133 EXPECT_TRUE(m1.Matches(derived));
1134 EXPECT_FALSE(m1.Matches(base));
1135 EXPECT_FALSE(m1.Matches(base2));
1136}
1137
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001138TEST(RefTest, ExplainsResult) {
1139 int n = 0;
1140 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1141 StartsWith("which is located @"));
1142
1143 int m = 0;
1144 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1145 StartsWith("which is located @"));
1146}
1147
shiqiane35fdd92008-12-10 05:08:54 +00001148// Tests string comparison matchers.
1149
1150TEST(StrEqTest, MatchesEqualString) {
1151 Matcher<const char*> m = StrEq(string("Hello"));
1152 EXPECT_TRUE(m.Matches("Hello"));
1153 EXPECT_FALSE(m.Matches("hello"));
1154 EXPECT_FALSE(m.Matches(NULL));
1155
1156 Matcher<const string&> m2 = StrEq("Hello");
1157 EXPECT_TRUE(m2.Matches("Hello"));
1158 EXPECT_FALSE(m2.Matches("Hi"));
1159}
1160
1161TEST(StrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001162 Matcher<string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1163 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
shiqiane35fdd92008-12-10 05:08:54 +00001164 Describe(m));
1165
1166 string str("01204500800");
1167 str[3] = '\0';
1168 Matcher<string> m2 = StrEq(str);
1169 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1170 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1171 Matcher<string> m3 = StrEq(str);
1172 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1173}
1174
1175TEST(StrNeTest, MatchesUnequalString) {
1176 Matcher<const char*> m = StrNe("Hello");
1177 EXPECT_TRUE(m.Matches(""));
1178 EXPECT_TRUE(m.Matches(NULL));
1179 EXPECT_FALSE(m.Matches("Hello"));
1180
1181 Matcher<string> m2 = StrNe(string("Hello"));
1182 EXPECT_TRUE(m2.Matches("hello"));
1183 EXPECT_FALSE(m2.Matches("Hello"));
1184}
1185
1186TEST(StrNeTest, CanDescribeSelf) {
1187 Matcher<const char*> m = StrNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001188 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001189}
1190
1191TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1192 Matcher<const char*> m = StrCaseEq(string("Hello"));
1193 EXPECT_TRUE(m.Matches("Hello"));
1194 EXPECT_TRUE(m.Matches("hello"));
1195 EXPECT_FALSE(m.Matches("Hi"));
1196 EXPECT_FALSE(m.Matches(NULL));
1197
1198 Matcher<const string&> m2 = StrCaseEq("Hello");
1199 EXPECT_TRUE(m2.Matches("hello"));
1200 EXPECT_FALSE(m2.Matches("Hi"));
1201}
1202
1203TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1204 string str1("oabocdooeoo");
1205 string str2("OABOCDOOEOO");
1206 Matcher<const string&> m0 = StrCaseEq(str1);
1207 EXPECT_FALSE(m0.Matches(str2 + string(1, '\0')));
1208
1209 str1[3] = str2[3] = '\0';
1210 Matcher<const string&> m1 = StrCaseEq(str1);
1211 EXPECT_TRUE(m1.Matches(str2));
1212
1213 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1214 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1215 Matcher<const string&> m2 = StrCaseEq(str1);
1216 str1[9] = str2[9] = '\0';
1217 EXPECT_FALSE(m2.Matches(str2));
1218
1219 Matcher<const string&> m3 = StrCaseEq(str1);
1220 EXPECT_TRUE(m3.Matches(str2));
1221
1222 EXPECT_FALSE(m3.Matches(str2 + "x"));
1223 str2.append(1, '\0');
1224 EXPECT_FALSE(m3.Matches(str2));
1225 EXPECT_FALSE(m3.Matches(string(str2, 0, 9)));
1226}
1227
1228TEST(StrCaseEqTest, CanDescribeSelf) {
1229 Matcher<string> m = StrCaseEq("Hi");
1230 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1231}
1232
1233TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1234 Matcher<const char*> m = StrCaseNe("Hello");
1235 EXPECT_TRUE(m.Matches("Hi"));
1236 EXPECT_TRUE(m.Matches(NULL));
1237 EXPECT_FALSE(m.Matches("Hello"));
1238 EXPECT_FALSE(m.Matches("hello"));
1239
1240 Matcher<string> m2 = StrCaseNe(string("Hello"));
1241 EXPECT_TRUE(m2.Matches(""));
1242 EXPECT_FALSE(m2.Matches("Hello"));
1243}
1244
1245TEST(StrCaseNeTest, CanDescribeSelf) {
1246 Matcher<const char*> m = StrCaseNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001247 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001248}
1249
1250// Tests that HasSubstr() works for matching string-typed values.
1251TEST(HasSubstrTest, WorksForStringClasses) {
1252 const Matcher<string> m1 = HasSubstr("foo");
1253 EXPECT_TRUE(m1.Matches(string("I love food.")));
1254 EXPECT_FALSE(m1.Matches(string("tofo")));
1255
1256 const Matcher<const std::string&> m2 = HasSubstr("foo");
1257 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1258 EXPECT_FALSE(m2.Matches(std::string("tofo")));
1259}
1260
1261// Tests that HasSubstr() works for matching C-string-typed values.
1262TEST(HasSubstrTest, WorksForCStrings) {
1263 const Matcher<char*> m1 = HasSubstr("foo");
1264 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1265 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1266 EXPECT_FALSE(m1.Matches(NULL));
1267
1268 const Matcher<const char*> m2 = HasSubstr("foo");
1269 EXPECT_TRUE(m2.Matches("I love food."));
1270 EXPECT_FALSE(m2.Matches("tofo"));
1271 EXPECT_FALSE(m2.Matches(NULL));
1272}
1273
1274// Tests that HasSubstr(s) describes itself properly.
1275TEST(HasSubstrTest, CanDescribeSelf) {
1276 Matcher<string> m = HasSubstr("foo\n\"");
1277 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1278}
1279
zhanyong.wanb5937da2009-07-16 20:26:41 +00001280TEST(KeyTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001281 Matcher<const pair<std::string, int>&> m = Key("foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001282 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001283 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1284}
1285
1286TEST(KeyTest, ExplainsResult) {
1287 Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1288 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1289 Explain(m, make_pair(5, true)));
1290 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1291 Explain(m, make_pair(15, true)));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001292}
1293
1294TEST(KeyTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001295 pair<int, std::string> p(25, "foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001296 EXPECT_THAT(p, Key(25));
1297 EXPECT_THAT(p, Not(Key(42)));
1298 EXPECT_THAT(p, Key(Ge(20)));
1299 EXPECT_THAT(p, Not(Key(Lt(25))));
1300}
1301
1302TEST(KeyTest, SafelyCastsInnerMatcher) {
1303 Matcher<int> is_positive = Gt(0);
1304 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001305 pair<char, bool> p('a', true);
zhanyong.wanb5937da2009-07-16 20:26:41 +00001306 EXPECT_THAT(p, Key(is_positive));
1307 EXPECT_THAT(p, Not(Key(is_negative)));
1308}
1309
1310TEST(KeyTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001311 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001312 container.insert(make_pair(1, 'a'));
1313 container.insert(make_pair(2, 'b'));
1314 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001315 EXPECT_THAT(container, Contains(Key(1)));
1316 EXPECT_THAT(container, Not(Contains(Key(3))));
1317}
1318
1319TEST(KeyTest, InsideContainsUsingMultimap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001320 multimap<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001321 container.insert(make_pair(1, 'a'));
1322 container.insert(make_pair(2, 'b'));
1323 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001324
1325 EXPECT_THAT(container, Not(Contains(Key(25))));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001326 container.insert(make_pair(25, 'd'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001327 EXPECT_THAT(container, Contains(Key(25)));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001328 container.insert(make_pair(25, 'e'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001329 EXPECT_THAT(container, Contains(Key(25)));
1330
1331 EXPECT_THAT(container, Contains(Key(1)));
1332 EXPECT_THAT(container, Not(Contains(Key(3))));
1333}
1334
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001335TEST(PairTest, Typing) {
1336 // Test verifies the following type conversions can be compiled.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001337 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1338 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1339 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001340
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001341 Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1342 Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001343}
1344
1345TEST(PairTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001346 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001347 EXPECT_EQ("has a first field that is equal to \"foo\""
1348 ", and has a second field that is equal to 42",
1349 Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001350 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1351 ", or has a second field that isn't equal to 42",
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001352 DescribeNegation(m1));
1353 // Double and triple negation (1 or 2 times not and description of negation).
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001354 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1355 EXPECT_EQ("has a first field that isn't equal to 13"
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001356 ", and has a second field that is equal to 42",
1357 DescribeNegation(m2));
1358}
1359
1360TEST(PairTest, CanExplainMatchResultTo) {
zhanyong.wan82113312010-01-08 21:55:40 +00001361 // If neither field matches, Pair() should explain about the first
1362 // field.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001363 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001364 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001365 Explain(m, make_pair(-1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001366
zhanyong.wan82113312010-01-08 21:55:40 +00001367 // If the first field matches but the second doesn't, Pair() should
1368 // explain about the second field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001369 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001370 Explain(m, make_pair(1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001371
zhanyong.wan82113312010-01-08 21:55:40 +00001372 // If the first field doesn't match but the second does, Pair()
1373 // should explain about the first field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001374 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001375 Explain(m, make_pair(-1, 2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001376
zhanyong.wan82113312010-01-08 21:55:40 +00001377 // If both fields match, Pair() should explain about them both.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001378 EXPECT_EQ("whose both fields match, where the first field is a value "
1379 "which is 1 more than 0, and the second field is a value "
1380 "which is 2 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001381 Explain(m, make_pair(1, 2)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001382
1383 // If only the first match has an explanation, only this explanation should
1384 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001385 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001386 EXPECT_EQ("whose both fields match, where the first field is a value "
1387 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001388 Explain(explain_first, make_pair(1, 0)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001389
1390 // If only the second match has an explanation, only this explanation should
1391 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001392 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001393 EXPECT_EQ("whose both fields match, where the second field is a value "
1394 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001395 Explain(explain_second, make_pair(0, 1)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001396}
1397
1398TEST(PairTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001399 pair<int, std::string> p(25, "foo");
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001400
1401 // Both fields match.
1402 EXPECT_THAT(p, Pair(25, "foo"));
1403 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1404
1405 // 'first' doesnt' match, but 'second' matches.
1406 EXPECT_THAT(p, Not(Pair(42, "foo")));
1407 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1408
1409 // 'first' matches, but 'second' doesn't match.
1410 EXPECT_THAT(p, Not(Pair(25, "bar")));
1411 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1412
1413 // Neither field matches.
1414 EXPECT_THAT(p, Not(Pair(13, "bar")));
1415 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1416}
1417
1418TEST(PairTest, SafelyCastsInnerMatchers) {
1419 Matcher<int> is_positive = Gt(0);
1420 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001421 pair<char, bool> p('a', true);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001422 EXPECT_THAT(p, Pair(is_positive, _));
1423 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1424 EXPECT_THAT(p, Pair(_, is_positive));
1425 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1426}
1427
1428TEST(PairTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001429 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001430 container.insert(make_pair(1, 'a'));
1431 container.insert(make_pair(2, 'b'));
1432 container.insert(make_pair(4, 'c'));
zhanyong.wan95b12332009-09-25 18:55:50 +00001433 EXPECT_THAT(container, Contains(Pair(1, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001434 EXPECT_THAT(container, Contains(Pair(1, _)));
zhanyong.wan95b12332009-09-25 18:55:50 +00001435 EXPECT_THAT(container, Contains(Pair(_, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001436 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1437}
1438
shiqiane35fdd92008-12-10 05:08:54 +00001439// Tests StartsWith(s).
1440
1441TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1442 const Matcher<const char*> m1 = StartsWith(string(""));
1443 EXPECT_TRUE(m1.Matches("Hi"));
1444 EXPECT_TRUE(m1.Matches(""));
1445 EXPECT_FALSE(m1.Matches(NULL));
1446
1447 const Matcher<const string&> m2 = StartsWith("Hi");
1448 EXPECT_TRUE(m2.Matches("Hi"));
1449 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1450 EXPECT_TRUE(m2.Matches("High"));
1451 EXPECT_FALSE(m2.Matches("H"));
1452 EXPECT_FALSE(m2.Matches(" Hi"));
1453}
1454
1455TEST(StartsWithTest, CanDescribeSelf) {
1456 Matcher<const std::string> m = StartsWith("Hi");
1457 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1458}
1459
1460// Tests EndsWith(s).
1461
1462TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1463 const Matcher<const char*> m1 = EndsWith("");
1464 EXPECT_TRUE(m1.Matches("Hi"));
1465 EXPECT_TRUE(m1.Matches(""));
1466 EXPECT_FALSE(m1.Matches(NULL));
1467
1468 const Matcher<const string&> m2 = EndsWith(string("Hi"));
1469 EXPECT_TRUE(m2.Matches("Hi"));
1470 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1471 EXPECT_TRUE(m2.Matches("Super Hi"));
1472 EXPECT_FALSE(m2.Matches("i"));
1473 EXPECT_FALSE(m2.Matches("Hi "));
1474}
1475
1476TEST(EndsWithTest, CanDescribeSelf) {
1477 Matcher<const std::string> m = EndsWith("Hi");
1478 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1479}
1480
shiqiane35fdd92008-12-10 05:08:54 +00001481// Tests MatchesRegex().
1482
1483TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1484 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1485 EXPECT_TRUE(m1.Matches("az"));
1486 EXPECT_TRUE(m1.Matches("abcz"));
1487 EXPECT_FALSE(m1.Matches(NULL));
1488
1489 const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z"));
1490 EXPECT_TRUE(m2.Matches("azbz"));
1491 EXPECT_FALSE(m2.Matches("az1"));
1492 EXPECT_FALSE(m2.Matches("1az"));
1493}
1494
1495TEST(MatchesRegexTest, CanDescribeSelf) {
1496 Matcher<const std::string> m1 = MatchesRegex(string("Hi.*"));
1497 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1498
zhanyong.wand14aaed2010-01-14 05:36:32 +00001499 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1500 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001501}
1502
1503// Tests ContainsRegex().
1504
1505TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1506 const Matcher<const char*> m1 = ContainsRegex(string("a.*z"));
1507 EXPECT_TRUE(m1.Matches("az"));
1508 EXPECT_TRUE(m1.Matches("0abcz1"));
1509 EXPECT_FALSE(m1.Matches(NULL));
1510
1511 const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z"));
1512 EXPECT_TRUE(m2.Matches("azbz"));
1513 EXPECT_TRUE(m2.Matches("az1"));
1514 EXPECT_FALSE(m2.Matches("1a"));
1515}
1516
1517TEST(ContainsRegexTest, CanDescribeSelf) {
1518 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1519 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1520
zhanyong.wand14aaed2010-01-14 05:36:32 +00001521 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1522 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001523}
shiqiane35fdd92008-12-10 05:08:54 +00001524
1525// Tests for wide strings.
1526#if GTEST_HAS_STD_WSTRING
1527TEST(StdWideStrEqTest, MatchesEqual) {
1528 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1529 EXPECT_TRUE(m.Matches(L"Hello"));
1530 EXPECT_FALSE(m.Matches(L"hello"));
1531 EXPECT_FALSE(m.Matches(NULL));
1532
1533 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1534 EXPECT_TRUE(m2.Matches(L"Hello"));
1535 EXPECT_FALSE(m2.Matches(L"Hi"));
1536
1537 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1538 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1539 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1540
1541 ::std::wstring str(L"01204500800");
1542 str[3] = L'\0';
1543 Matcher<const ::std::wstring&> m4 = StrEq(str);
1544 EXPECT_TRUE(m4.Matches(str));
1545 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1546 Matcher<const ::std::wstring&> m5 = StrEq(str);
1547 EXPECT_TRUE(m5.Matches(str));
1548}
1549
1550TEST(StdWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001551 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1552 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001553 Describe(m));
1554
1555 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1556 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1557 Describe(m2));
1558
1559 ::std::wstring str(L"01204500800");
1560 str[3] = L'\0';
1561 Matcher<const ::std::wstring&> m4 = StrEq(str);
1562 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1563 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1564 Matcher<const ::std::wstring&> m5 = StrEq(str);
1565 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1566}
1567
1568TEST(StdWideStrNeTest, MatchesUnequalString) {
1569 Matcher<const wchar_t*> m = StrNe(L"Hello");
1570 EXPECT_TRUE(m.Matches(L""));
1571 EXPECT_TRUE(m.Matches(NULL));
1572 EXPECT_FALSE(m.Matches(L"Hello"));
1573
1574 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1575 EXPECT_TRUE(m2.Matches(L"hello"));
1576 EXPECT_FALSE(m2.Matches(L"Hello"));
1577}
1578
1579TEST(StdWideStrNeTest, CanDescribeSelf) {
1580 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001581 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001582}
1583
1584TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1585 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1586 EXPECT_TRUE(m.Matches(L"Hello"));
1587 EXPECT_TRUE(m.Matches(L"hello"));
1588 EXPECT_FALSE(m.Matches(L"Hi"));
1589 EXPECT_FALSE(m.Matches(NULL));
1590
1591 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1592 EXPECT_TRUE(m2.Matches(L"hello"));
1593 EXPECT_FALSE(m2.Matches(L"Hi"));
1594}
1595
1596TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1597 ::std::wstring str1(L"oabocdooeoo");
1598 ::std::wstring str2(L"OABOCDOOEOO");
1599 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1600 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1601
1602 str1[3] = str2[3] = L'\0';
1603 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1604 EXPECT_TRUE(m1.Matches(str2));
1605
1606 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1607 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1608 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1609 str1[9] = str2[9] = L'\0';
1610 EXPECT_FALSE(m2.Matches(str2));
1611
1612 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1613 EXPECT_TRUE(m3.Matches(str2));
1614
1615 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1616 str2.append(1, L'\0');
1617 EXPECT_FALSE(m3.Matches(str2));
1618 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1619}
1620
1621TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1622 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1623 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1624}
1625
1626TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1627 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1628 EXPECT_TRUE(m.Matches(L"Hi"));
1629 EXPECT_TRUE(m.Matches(NULL));
1630 EXPECT_FALSE(m.Matches(L"Hello"));
1631 EXPECT_FALSE(m.Matches(L"hello"));
1632
1633 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1634 EXPECT_TRUE(m2.Matches(L""));
1635 EXPECT_FALSE(m2.Matches(L"Hello"));
1636}
1637
1638TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1639 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001640 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001641}
1642
1643// Tests that HasSubstr() works for matching wstring-typed values.
1644TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1645 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1646 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1647 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1648
1649 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1650 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1651 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1652}
1653
1654// Tests that HasSubstr() works for matching C-wide-string-typed values.
1655TEST(StdWideHasSubstrTest, WorksForCStrings) {
1656 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1657 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1658 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1659 EXPECT_FALSE(m1.Matches(NULL));
1660
1661 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1662 EXPECT_TRUE(m2.Matches(L"I love food."));
1663 EXPECT_FALSE(m2.Matches(L"tofo"));
1664 EXPECT_FALSE(m2.Matches(NULL));
1665}
1666
1667// Tests that HasSubstr(s) describes itself properly.
1668TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1669 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1670 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1671}
1672
1673// Tests StartsWith(s).
1674
1675TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1676 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1677 EXPECT_TRUE(m1.Matches(L"Hi"));
1678 EXPECT_TRUE(m1.Matches(L""));
1679 EXPECT_FALSE(m1.Matches(NULL));
1680
1681 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1682 EXPECT_TRUE(m2.Matches(L"Hi"));
1683 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1684 EXPECT_TRUE(m2.Matches(L"High"));
1685 EXPECT_FALSE(m2.Matches(L"H"));
1686 EXPECT_FALSE(m2.Matches(L" Hi"));
1687}
1688
1689TEST(StdWideStartsWithTest, CanDescribeSelf) {
1690 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
1691 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1692}
1693
1694// Tests EndsWith(s).
1695
1696TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
1697 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1698 EXPECT_TRUE(m1.Matches(L"Hi"));
1699 EXPECT_TRUE(m1.Matches(L""));
1700 EXPECT_FALSE(m1.Matches(NULL));
1701
1702 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
1703 EXPECT_TRUE(m2.Matches(L"Hi"));
1704 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1705 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1706 EXPECT_FALSE(m2.Matches(L"i"));
1707 EXPECT_FALSE(m2.Matches(L"Hi "));
1708}
1709
1710TEST(StdWideEndsWithTest, CanDescribeSelf) {
1711 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
1712 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1713}
1714
1715#endif // GTEST_HAS_STD_WSTRING
1716
1717#if GTEST_HAS_GLOBAL_WSTRING
1718TEST(GlobalWideStrEqTest, MatchesEqual) {
1719 Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
1720 EXPECT_TRUE(m.Matches(L"Hello"));
1721 EXPECT_FALSE(m.Matches(L"hello"));
1722 EXPECT_FALSE(m.Matches(NULL));
1723
1724 Matcher<const ::wstring&> m2 = StrEq(L"Hello");
1725 EXPECT_TRUE(m2.Matches(L"Hello"));
1726 EXPECT_FALSE(m2.Matches(L"Hi"));
1727
1728 Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1729 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1730 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1731
1732 ::wstring str(L"01204500800");
1733 str[3] = L'\0';
1734 Matcher<const ::wstring&> m4 = StrEq(str);
1735 EXPECT_TRUE(m4.Matches(str));
1736 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1737 Matcher<const ::wstring&> m5 = StrEq(str);
1738 EXPECT_TRUE(m5.Matches(str));
1739}
1740
1741TEST(GlobalWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001742 Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1743 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001744 Describe(m));
1745
1746 Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1747 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1748 Describe(m2));
1749
1750 ::wstring str(L"01204500800");
1751 str[3] = L'\0';
1752 Matcher<const ::wstring&> m4 = StrEq(str);
1753 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1754 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1755 Matcher<const ::wstring&> m5 = StrEq(str);
1756 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1757}
1758
1759TEST(GlobalWideStrNeTest, MatchesUnequalString) {
1760 Matcher<const wchar_t*> m = StrNe(L"Hello");
1761 EXPECT_TRUE(m.Matches(L""));
1762 EXPECT_TRUE(m.Matches(NULL));
1763 EXPECT_FALSE(m.Matches(L"Hello"));
1764
1765 Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
1766 EXPECT_TRUE(m2.Matches(L"hello"));
1767 EXPECT_FALSE(m2.Matches(L"Hello"));
1768}
1769
1770TEST(GlobalWideStrNeTest, CanDescribeSelf) {
1771 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001772 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001773}
1774
1775TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1776 Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
1777 EXPECT_TRUE(m.Matches(L"Hello"));
1778 EXPECT_TRUE(m.Matches(L"hello"));
1779 EXPECT_FALSE(m.Matches(L"Hi"));
1780 EXPECT_FALSE(m.Matches(NULL));
1781
1782 Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
1783 EXPECT_TRUE(m2.Matches(L"hello"));
1784 EXPECT_FALSE(m2.Matches(L"Hi"));
1785}
1786
1787TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1788 ::wstring str1(L"oabocdooeoo");
1789 ::wstring str2(L"OABOCDOOEOO");
1790 Matcher<const ::wstring&> m0 = StrCaseEq(str1);
1791 EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
1792
1793 str1[3] = str2[3] = L'\0';
1794 Matcher<const ::wstring&> m1 = StrCaseEq(str1);
1795 EXPECT_TRUE(m1.Matches(str2));
1796
1797 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1798 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1799 Matcher<const ::wstring&> m2 = StrCaseEq(str1);
1800 str1[9] = str2[9] = L'\0';
1801 EXPECT_FALSE(m2.Matches(str2));
1802
1803 Matcher<const ::wstring&> m3 = StrCaseEq(str1);
1804 EXPECT_TRUE(m3.Matches(str2));
1805
1806 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1807 str2.append(1, L'\0');
1808 EXPECT_FALSE(m3.Matches(str2));
1809 EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
1810}
1811
1812TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
1813 Matcher< ::wstring> m = StrCaseEq(L"Hi");
1814 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1815}
1816
1817TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1818 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1819 EXPECT_TRUE(m.Matches(L"Hi"));
1820 EXPECT_TRUE(m.Matches(NULL));
1821 EXPECT_FALSE(m.Matches(L"Hello"));
1822 EXPECT_FALSE(m.Matches(L"hello"));
1823
1824 Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
1825 EXPECT_TRUE(m2.Matches(L""));
1826 EXPECT_FALSE(m2.Matches(L"Hello"));
1827}
1828
1829TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
1830 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001831 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001832}
1833
1834// Tests that HasSubstr() works for matching wstring-typed values.
1835TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
1836 const Matcher< ::wstring> m1 = HasSubstr(L"foo");
1837 EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
1838 EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
1839
1840 const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
1841 EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
1842 EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
1843}
1844
1845// Tests that HasSubstr() works for matching C-wide-string-typed values.
1846TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
1847 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1848 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1849 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1850 EXPECT_FALSE(m1.Matches(NULL));
1851
1852 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1853 EXPECT_TRUE(m2.Matches(L"I love food."));
1854 EXPECT_FALSE(m2.Matches(L"tofo"));
1855 EXPECT_FALSE(m2.Matches(NULL));
1856}
1857
1858// Tests that HasSubstr(s) describes itself properly.
1859TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
1860 Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
1861 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1862}
1863
1864// Tests StartsWith(s).
1865
1866TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
1867 const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
1868 EXPECT_TRUE(m1.Matches(L"Hi"));
1869 EXPECT_TRUE(m1.Matches(L""));
1870 EXPECT_FALSE(m1.Matches(NULL));
1871
1872 const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
1873 EXPECT_TRUE(m2.Matches(L"Hi"));
1874 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1875 EXPECT_TRUE(m2.Matches(L"High"));
1876 EXPECT_FALSE(m2.Matches(L"H"));
1877 EXPECT_FALSE(m2.Matches(L" Hi"));
1878}
1879
1880TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
1881 Matcher<const ::wstring> m = StartsWith(L"Hi");
1882 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1883}
1884
1885// Tests EndsWith(s).
1886
1887TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
1888 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1889 EXPECT_TRUE(m1.Matches(L"Hi"));
1890 EXPECT_TRUE(m1.Matches(L""));
1891 EXPECT_FALSE(m1.Matches(NULL));
1892
1893 const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
1894 EXPECT_TRUE(m2.Matches(L"Hi"));
1895 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1896 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1897 EXPECT_FALSE(m2.Matches(L"i"));
1898 EXPECT_FALSE(m2.Matches(L"Hi "));
1899}
1900
1901TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
1902 Matcher<const ::wstring> m = EndsWith(L"Hi");
1903 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1904}
1905
1906#endif // GTEST_HAS_GLOBAL_WSTRING
1907
1908
kosakbd018832014-04-02 20:30:00 +00001909typedef ::testing::tuple<long, int> Tuple2; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00001910
1911// Tests that Eq() matches a 2-tuple where the first field == the
1912// second field.
1913TEST(Eq2Test, MatchesEqualArguments) {
1914 Matcher<const Tuple2&> m = Eq();
1915 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1916 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1917}
1918
1919// Tests that Eq() describes itself properly.
1920TEST(Eq2Test, CanDescribeSelf) {
1921 Matcher<const Tuple2&> m = Eq();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001922 EXPECT_EQ("are an equal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001923}
1924
1925// Tests that Ge() matches a 2-tuple where the first field >= the
1926// second field.
1927TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
1928 Matcher<const Tuple2&> m = Ge();
1929 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1930 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1931 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1932}
1933
1934// Tests that Ge() describes itself properly.
1935TEST(Ge2Test, CanDescribeSelf) {
1936 Matcher<const Tuple2&> m = Ge();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001937 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001938}
1939
1940// Tests that Gt() matches a 2-tuple where the first field > the
1941// second field.
1942TEST(Gt2Test, MatchesGreaterThanArguments) {
1943 Matcher<const Tuple2&> m = Gt();
1944 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1945 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1946 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1947}
1948
1949// Tests that Gt() describes itself properly.
1950TEST(Gt2Test, CanDescribeSelf) {
1951 Matcher<const Tuple2&> m = Gt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001952 EXPECT_EQ("are a pair where the first > the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001953}
1954
1955// Tests that Le() matches a 2-tuple where the first field <= the
1956// second field.
1957TEST(Le2Test, MatchesLessThanOrEqualArguments) {
1958 Matcher<const Tuple2&> m = Le();
1959 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1960 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1961 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1962}
1963
1964// Tests that Le() describes itself properly.
1965TEST(Le2Test, CanDescribeSelf) {
1966 Matcher<const Tuple2&> m = Le();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001967 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001968}
1969
1970// Tests that Lt() matches a 2-tuple where the first field < the
1971// second field.
1972TEST(Lt2Test, MatchesLessThanArguments) {
1973 Matcher<const Tuple2&> m = Lt();
1974 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1975 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1976 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1977}
1978
1979// Tests that Lt() describes itself properly.
1980TEST(Lt2Test, CanDescribeSelf) {
1981 Matcher<const Tuple2&> m = Lt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001982 EXPECT_EQ("are a pair where the first < the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001983}
1984
1985// Tests that Ne() matches a 2-tuple where the first field != the
1986// second field.
1987TEST(Ne2Test, MatchesUnequalArguments) {
1988 Matcher<const Tuple2&> m = Ne();
1989 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1990 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1991 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1992}
1993
1994// Tests that Ne() describes itself properly.
1995TEST(Ne2Test, CanDescribeSelf) {
1996 Matcher<const Tuple2&> m = Ne();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001997 EXPECT_EQ("are an unequal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001998}
1999
2000// Tests that Not(m) matches any value that doesn't match m.
2001TEST(NotTest, NegatesMatcher) {
2002 Matcher<int> m;
2003 m = Not(Eq(2));
2004 EXPECT_TRUE(m.Matches(3));
2005 EXPECT_FALSE(m.Matches(2));
2006}
2007
2008// Tests that Not(m) describes itself properly.
2009TEST(NotTest, CanDescribeSelf) {
2010 Matcher<int> m = Not(Eq(5));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002011 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002012}
2013
zhanyong.wan18490652009-05-11 18:54:08 +00002014// Tests that monomorphic matchers are safely cast by the Not matcher.
2015TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2016 // greater_than_5 is a monomorphic matcher.
2017 Matcher<int> greater_than_5 = Gt(5);
2018
2019 Matcher<const int&> m = Not(greater_than_5);
2020 Matcher<int&> m2 = Not(greater_than_5);
2021 Matcher<int&> m3 = Not(m);
2022}
2023
zhanyong.wan02c15052010-06-09 19:21:30 +00002024// Helper to allow easy testing of AllOf matchers with num parameters.
2025void AllOfMatches(int num, const Matcher<int>& m) {
2026 SCOPED_TRACE(Describe(m));
2027 EXPECT_TRUE(m.Matches(0));
2028 for (int i = 1; i <= num; ++i) {
2029 EXPECT_FALSE(m.Matches(i));
2030 }
2031 EXPECT_TRUE(m.Matches(num + 1));
2032}
2033
shiqiane35fdd92008-12-10 05:08:54 +00002034// Tests that AllOf(m1, ..., mn) matches any value that matches all of
2035// the given matchers.
2036TEST(AllOfTest, MatchesWhenAllMatch) {
2037 Matcher<int> m;
2038 m = AllOf(Le(2), Ge(1));
2039 EXPECT_TRUE(m.Matches(1));
2040 EXPECT_TRUE(m.Matches(2));
2041 EXPECT_FALSE(m.Matches(0));
2042 EXPECT_FALSE(m.Matches(3));
2043
2044 m = AllOf(Gt(0), Ne(1), Ne(2));
2045 EXPECT_TRUE(m.Matches(3));
2046 EXPECT_FALSE(m.Matches(2));
2047 EXPECT_FALSE(m.Matches(1));
2048 EXPECT_FALSE(m.Matches(0));
2049
2050 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2051 EXPECT_TRUE(m.Matches(4));
2052 EXPECT_FALSE(m.Matches(3));
2053 EXPECT_FALSE(m.Matches(2));
2054 EXPECT_FALSE(m.Matches(1));
2055 EXPECT_FALSE(m.Matches(0));
2056
2057 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2058 EXPECT_TRUE(m.Matches(0));
2059 EXPECT_TRUE(m.Matches(1));
2060 EXPECT_FALSE(m.Matches(3));
zhanyong.wan02c15052010-06-09 19:21:30 +00002061
2062 // The following tests for varying number of sub-matchers. Due to the way
2063 // the sub-matchers are handled it is enough to test every sub-matcher once
2064 // with sub-matchers using the same matcher type. Varying matcher types are
2065 // checked for above.
2066 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2067 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2068 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2069 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2070 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2071 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2072 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2073 Ne(8)));
2074 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2075 Ne(8), Ne(9)));
2076 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2077 Ne(9), Ne(10)));
shiqiane35fdd92008-12-10 05:08:54 +00002078}
2079
zhanyong.wan616180e2013-06-18 18:49:51 +00002080#if GTEST_LANG_CXX11
2081// Tests the variadic version of the AllOfMatcher.
2082TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
2083 // Make sure AllOf is defined in the right namespace and does not depend on
2084 // ADL.
2085 ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2086 Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2087 Ne(9), Ne(10), Ne(11));
2088 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))"));
2089 AllOfMatches(11, m);
2090 AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2091 Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
2092 Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22),
2093 Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29),
2094 Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36),
2095 Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43),
2096 Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2097 Ne(50)));
2098}
2099
2100#endif // GTEST_LANG_CXX11
2101
shiqiane35fdd92008-12-10 05:08:54 +00002102// Tests that AllOf(m1, ..., mn) describes itself properly.
2103TEST(AllOfTest, CanDescribeSelf) {
2104 Matcher<int> m;
2105 m = AllOf(Le(2), Ge(1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002106 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002107
2108 m = AllOf(Gt(0), Ne(1), Ne(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002109 EXPECT_EQ("(is > 0) and "
2110 "((isn't equal to 1) and "
2111 "(isn't equal to 2))",
shiqiane35fdd92008-12-10 05:08:54 +00002112 Describe(m));
2113
2114
2115 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002116 EXPECT_EQ("((is > 0) and "
2117 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002118 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002119 "(isn't equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002120 Describe(m));
2121
2122
2123 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002124 EXPECT_EQ("((is >= 0) and "
2125 "(is < 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002126 "((isn't equal to 3) and "
2127 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002128 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002129 Describe(m));
2130}
2131
2132// Tests that AllOf(m1, ..., mn) describes its negation properly.
2133TEST(AllOfTest, CanDescribeNegation) {
2134 Matcher<int> m;
2135 m = AllOf(Le(2), Ge(1));
2136 EXPECT_EQ("(isn't <= 2) or "
2137 "(isn't >= 1)",
2138 DescribeNegation(m));
2139
2140 m = AllOf(Gt(0), Ne(1), Ne(2));
2141 EXPECT_EQ("(isn't > 0) or "
2142 "((is equal to 1) or "
2143 "(is equal to 2))",
2144 DescribeNegation(m));
2145
2146
2147 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002148 EXPECT_EQ("((isn't > 0) or "
2149 "(is equal to 1)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002150 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002151 "(is equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002152 DescribeNegation(m));
2153
2154
2155 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002156 EXPECT_EQ("((isn't >= 0) or "
2157 "(isn't < 10)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002158 "((is equal to 3) or "
2159 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002160 "(is equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002161 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00002162}
2163
zhanyong.wan18490652009-05-11 18:54:08 +00002164// Tests that monomorphic matchers are safely cast by the AllOf matcher.
2165TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2166 // greater_than_5 and less_than_10 are monomorphic matchers.
2167 Matcher<int> greater_than_5 = Gt(5);
2168 Matcher<int> less_than_10 = Lt(10);
2169
2170 Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2171 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2172 Matcher<int&> m3 = AllOf(greater_than_5, m2);
2173
2174 // Tests that BothOf works when composing itself.
2175 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2176 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2177}
2178
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002179TEST(AllOfTest, ExplainsResult) {
2180 Matcher<int> m;
2181
2182 // Successful match. Both matchers need to explain. The second
2183 // matcher doesn't give an explanation, so only the first matcher's
2184 // explanation is printed.
2185 m = AllOf(GreaterThan(10), Lt(30));
2186 EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2187
2188 // Successful match. Both matchers need to explain.
2189 m = AllOf(GreaterThan(10), GreaterThan(20));
2190 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2191 Explain(m, 30));
2192
2193 // Successful match. All matchers need to explain. The second
2194 // matcher doesn't given an explanation.
2195 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2196 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2197 Explain(m, 25));
2198
2199 // Successful match. All matchers need to explain.
2200 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2201 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2202 "and which is 10 more than 30",
2203 Explain(m, 40));
2204
2205 // Failed match. The first matcher, which failed, needs to
2206 // explain.
2207 m = AllOf(GreaterThan(10), GreaterThan(20));
2208 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2209
2210 // Failed match. The second matcher, which failed, needs to
2211 // explain. Since it doesn't given an explanation, nothing is
2212 // printed.
2213 m = AllOf(GreaterThan(10), Lt(30));
2214 EXPECT_EQ("", Explain(m, 40));
2215
2216 // Failed match. The second matcher, which failed, needs to
2217 // explain.
2218 m = AllOf(GreaterThan(10), GreaterThan(20));
2219 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2220}
2221
zhanyong.wan02c15052010-06-09 19:21:30 +00002222// Helper to allow easy testing of AnyOf matchers with num parameters.
2223void AnyOfMatches(int num, const Matcher<int>& m) {
2224 SCOPED_TRACE(Describe(m));
2225 EXPECT_FALSE(m.Matches(0));
2226 for (int i = 1; i <= num; ++i) {
2227 EXPECT_TRUE(m.Matches(i));
2228 }
2229 EXPECT_FALSE(m.Matches(num + 1));
2230}
2231
shiqiane35fdd92008-12-10 05:08:54 +00002232// Tests that AnyOf(m1, ..., mn) matches any value that matches at
2233// least one of the given matchers.
2234TEST(AnyOfTest, MatchesWhenAnyMatches) {
2235 Matcher<int> m;
2236 m = AnyOf(Le(1), Ge(3));
2237 EXPECT_TRUE(m.Matches(1));
2238 EXPECT_TRUE(m.Matches(4));
2239 EXPECT_FALSE(m.Matches(2));
2240
2241 m = AnyOf(Lt(0), Eq(1), Eq(2));
2242 EXPECT_TRUE(m.Matches(-1));
2243 EXPECT_TRUE(m.Matches(1));
2244 EXPECT_TRUE(m.Matches(2));
2245 EXPECT_FALSE(m.Matches(0));
2246
2247 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2248 EXPECT_TRUE(m.Matches(-1));
2249 EXPECT_TRUE(m.Matches(1));
2250 EXPECT_TRUE(m.Matches(2));
2251 EXPECT_TRUE(m.Matches(3));
2252 EXPECT_FALSE(m.Matches(0));
2253
2254 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2255 EXPECT_TRUE(m.Matches(0));
2256 EXPECT_TRUE(m.Matches(11));
2257 EXPECT_TRUE(m.Matches(3));
2258 EXPECT_FALSE(m.Matches(2));
zhanyong.wan02c15052010-06-09 19:21:30 +00002259
2260 // The following tests for varying number of sub-matchers. Due to the way
2261 // the sub-matchers are handled it is enough to test every sub-matcher once
2262 // with sub-matchers using the same matcher type. Varying matcher types are
2263 // checked for above.
2264 AnyOfMatches(2, AnyOf(1, 2));
2265 AnyOfMatches(3, AnyOf(1, 2, 3));
2266 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2267 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2268 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2269 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2270 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2271 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2272 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
shiqiane35fdd92008-12-10 05:08:54 +00002273}
2274
zhanyong.wan616180e2013-06-18 18:49:51 +00002275#if GTEST_LANG_CXX11
2276// Tests the variadic version of the AnyOfMatcher.
2277TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2278 // Also make sure AnyOf is defined in the right namespace and does not depend
2279 // on ADL.
2280 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2281
2282 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))"));
2283 AnyOfMatches(11, m);
2284 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2285 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2286 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2287 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2288 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2289}
2290
2291#endif // GTEST_LANG_CXX11
2292
shiqiane35fdd92008-12-10 05:08:54 +00002293// Tests that AnyOf(m1, ..., mn) describes itself properly.
2294TEST(AnyOfTest, CanDescribeSelf) {
2295 Matcher<int> m;
2296 m = AnyOf(Le(1), Ge(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002297 EXPECT_EQ("(is <= 1) or (is >= 3)",
shiqiane35fdd92008-12-10 05:08:54 +00002298 Describe(m));
2299
2300 m = AnyOf(Lt(0), Eq(1), Eq(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002301 EXPECT_EQ("(is < 0) or "
shiqiane35fdd92008-12-10 05:08:54 +00002302 "((is equal to 1) or (is equal to 2))",
2303 Describe(m));
2304
2305 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002306 EXPECT_EQ("((is < 0) or "
2307 "(is equal to 1)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002308 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002309 "(is equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002310 Describe(m));
2311
2312 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002313 EXPECT_EQ("((is <= 0) or "
2314 "(is > 10)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002315 "((is equal to 3) or "
2316 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002317 "(is equal to 7)))",
shiqiane35fdd92008-12-10 05:08:54 +00002318 Describe(m));
2319}
2320
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002321// Tests that AnyOf(m1, ..., mn) describes its negation properly.
2322TEST(AnyOfTest, CanDescribeNegation) {
2323 Matcher<int> m;
2324 m = AnyOf(Le(1), Ge(3));
2325 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2326 DescribeNegation(m));
2327
2328 m = AnyOf(Lt(0), Eq(1), Eq(2));
2329 EXPECT_EQ("(isn't < 0) and "
2330 "((isn't equal to 1) and (isn't equal to 2))",
2331 DescribeNegation(m));
2332
2333 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002334 EXPECT_EQ("((isn't < 0) and "
2335 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002336 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002337 "(isn't equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002338 DescribeNegation(m));
2339
2340 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002341 EXPECT_EQ("((isn't <= 0) and "
2342 "(isn't > 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002343 "((isn't equal to 3) and "
2344 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002345 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002346 DescribeNegation(m));
2347}
2348
zhanyong.wan18490652009-05-11 18:54:08 +00002349// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2350TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2351 // greater_than_5 and less_than_10 are monomorphic matchers.
2352 Matcher<int> greater_than_5 = Gt(5);
2353 Matcher<int> less_than_10 = Lt(10);
2354
2355 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2356 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2357 Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2358
2359 // Tests that EitherOf works when composing itself.
2360 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2361 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2362}
2363
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002364TEST(AnyOfTest, ExplainsResult) {
2365 Matcher<int> m;
2366
2367 // Failed match. Both matchers need to explain. The second
2368 // matcher doesn't give an explanation, so only the first matcher's
2369 // explanation is printed.
2370 m = AnyOf(GreaterThan(10), Lt(0));
2371 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2372
2373 // Failed match. Both matchers need to explain.
2374 m = AnyOf(GreaterThan(10), GreaterThan(20));
2375 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2376 Explain(m, 5));
2377
2378 // Failed match. All matchers need to explain. The second
2379 // matcher doesn't given an explanation.
2380 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2381 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2382 Explain(m, 5));
2383
2384 // Failed match. All matchers need to explain.
2385 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2386 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2387 "and which is 25 less than 30",
2388 Explain(m, 5));
2389
2390 // Successful match. The first matcher, which succeeded, needs to
2391 // explain.
2392 m = AnyOf(GreaterThan(10), GreaterThan(20));
2393 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2394
2395 // Successful match. The second matcher, which succeeded, needs to
2396 // explain. Since it doesn't given an explanation, nothing is
2397 // printed.
2398 m = AnyOf(GreaterThan(10), Lt(30));
2399 EXPECT_EQ("", Explain(m, 0));
2400
2401 // Successful match. The second matcher, which succeeded, needs to
2402 // explain.
2403 m = AnyOf(GreaterThan(30), GreaterThan(20));
2404 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2405}
2406
shiqiane35fdd92008-12-10 05:08:54 +00002407// The following predicate function and predicate functor are for
2408// testing the Truly(predicate) matcher.
2409
2410// Returns non-zero if the input is positive. Note that the return
2411// type of this function is not bool. It's OK as Truly() accepts any
2412// unary function or functor whose return type can be implicitly
2413// converted to bool.
2414int IsPositive(double x) {
2415 return x > 0 ? 1 : 0;
2416}
2417
2418// This functor returns true if the input is greater than the given
2419// number.
2420class IsGreaterThan {
2421 public:
2422 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2423
2424 bool operator()(int n) const { return n > threshold_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002425
shiqiane35fdd92008-12-10 05:08:54 +00002426 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002427 int threshold_;
shiqiane35fdd92008-12-10 05:08:54 +00002428};
2429
2430// For testing Truly().
2431const int foo = 0;
2432
2433// This predicate returns true iff the argument references foo and has
2434// a zero value.
2435bool ReferencesFooAndIsZero(const int& n) {
2436 return (&n == &foo) && (n == 0);
2437}
2438
2439// Tests that Truly(predicate) matches what satisfies the given
2440// predicate.
2441TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2442 Matcher<double> m = Truly(IsPositive);
2443 EXPECT_TRUE(m.Matches(2.0));
2444 EXPECT_FALSE(m.Matches(-1.5));
2445}
2446
2447// Tests that Truly(predicate_functor) works too.
2448TEST(TrulyTest, CanBeUsedWithFunctor) {
2449 Matcher<int> m = Truly(IsGreaterThan(5));
2450 EXPECT_TRUE(m.Matches(6));
2451 EXPECT_FALSE(m.Matches(4));
2452}
2453
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00002454// A class that can be implicitly converted to bool.
2455class ConvertibleToBool {
2456 public:
2457 explicit ConvertibleToBool(int number) : number_(number) {}
2458 operator bool() const { return number_ != 0; }
2459
2460 private:
2461 int number_;
2462};
2463
2464ConvertibleToBool IsNotZero(int number) {
2465 return ConvertibleToBool(number);
2466}
2467
2468// Tests that the predicate used in Truly() may return a class that's
2469// implicitly convertible to bool, even when the class has no
2470// operator!().
2471TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2472 Matcher<int> m = Truly(IsNotZero);
2473 EXPECT_TRUE(m.Matches(1));
2474 EXPECT_FALSE(m.Matches(0));
2475}
2476
shiqiane35fdd92008-12-10 05:08:54 +00002477// Tests that Truly(predicate) can describe itself properly.
2478TEST(TrulyTest, CanDescribeSelf) {
2479 Matcher<double> m = Truly(IsPositive);
2480 EXPECT_EQ("satisfies the given predicate",
2481 Describe(m));
2482}
2483
2484// Tests that Truly(predicate) works when the matcher takes its
2485// argument by reference.
2486TEST(TrulyTest, WorksForByRefArguments) {
2487 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2488 EXPECT_TRUE(m.Matches(foo));
2489 int n = 0;
2490 EXPECT_FALSE(m.Matches(n));
2491}
2492
2493// Tests that Matches(m) is a predicate satisfied by whatever that
2494// matches matcher m.
2495TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2496 EXPECT_TRUE(Matches(Ge(0))(1));
2497 EXPECT_FALSE(Matches(Eq('a'))('b'));
2498}
2499
2500// Tests that Matches(m) works when the matcher takes its argument by
2501// reference.
2502TEST(MatchesTest, WorksOnByRefArguments) {
2503 int m = 0, n = 0;
2504 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2505 EXPECT_FALSE(Matches(Ref(m))(n));
2506}
2507
2508// Tests that a Matcher on non-reference type can be used in
2509// Matches().
2510TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
2511 Matcher<int> eq5 = Eq(5);
2512 EXPECT_TRUE(Matches(eq5)(5));
2513 EXPECT_FALSE(Matches(eq5)(2));
2514}
2515
zhanyong.wanb8243162009-06-04 05:48:20 +00002516// Tests Value(value, matcher). Since Value() is a simple wrapper for
2517// Matches(), which has been tested already, we don't spend a lot of
2518// effort on testing Value().
2519TEST(ValueTest, WorksWithPolymorphicMatcher) {
2520 EXPECT_TRUE(Value("hi", StartsWith("h")));
2521 EXPECT_FALSE(Value(5, Gt(10)));
2522}
2523
2524TEST(ValueTest, WorksWithMonomorphicMatcher) {
2525 const Matcher<int> is_zero = Eq(0);
2526 EXPECT_TRUE(Value(0, is_zero));
2527 EXPECT_FALSE(Value('a', is_zero));
2528
2529 int n = 0;
2530 const Matcher<const int&> ref_n = Ref(n);
2531 EXPECT_TRUE(Value(n, ref_n));
2532 EXPECT_FALSE(Value(1, ref_n));
2533}
2534
zhanyong.wana862f1d2010-03-15 21:23:04 +00002535TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002536 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002537 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002538 EXPECT_EQ("% 2 == 0", listener1.str());
2539
2540 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002541 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002542 EXPECT_EQ("", listener2.str());
2543}
2544
zhanyong.wana862f1d2010-03-15 21:23:04 +00002545TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002546 const Matcher<int> is_even = PolymorphicIsEven();
2547 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002548 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002549 EXPECT_EQ("% 2 == 0", listener1.str());
2550
2551 const Matcher<const double&> is_zero = Eq(0);
2552 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002553 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002554 EXPECT_EQ("", listener2.str());
2555}
2556
zhanyong.wana862f1d2010-03-15 21:23:04 +00002557MATCHER_P(Really, inner_matcher, "") {
2558 return ExplainMatchResult(inner_matcher, arg, result_listener);
2559}
2560
2561TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
2562 EXPECT_THAT(0, Really(Eq(0)));
2563}
2564
zhanyong.wanbf550852009-06-09 06:09:53 +00002565TEST(AllArgsTest, WorksForTuple) {
2566 EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
2567 EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
2568}
2569
2570TEST(AllArgsTest, WorksForNonTuple) {
2571 EXPECT_THAT(42, AllArgs(Gt(0)));
2572 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
2573}
2574
2575class AllArgsHelper {
2576 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002577 AllArgsHelper() {}
2578
zhanyong.wanbf550852009-06-09 06:09:53 +00002579 MOCK_METHOD2(Helper, int(char x, int y));
zhanyong.wan32de5f52009-12-23 00:13:23 +00002580
2581 private:
2582 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
zhanyong.wanbf550852009-06-09 06:09:53 +00002583};
2584
2585TEST(AllArgsTest, WorksInWithClause) {
2586 AllArgsHelper helper;
2587 ON_CALL(helper, Helper(_, _))
2588 .With(AllArgs(Lt()))
2589 .WillByDefault(Return(1));
2590 EXPECT_CALL(helper, Helper(_, _));
2591 EXPECT_CALL(helper, Helper(_, _))
2592 .With(AllArgs(Gt()))
2593 .WillOnce(Return(2));
2594
2595 EXPECT_EQ(1, helper.Helper('\1', 2));
2596 EXPECT_EQ(2, helper.Helper('a', 1));
2597}
2598
shiqiane35fdd92008-12-10 05:08:54 +00002599// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2600// matches the matcher.
2601TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
2602 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
2603 ASSERT_THAT("Foo", EndsWith("oo"));
2604 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
2605 EXPECT_THAT("Hello", StartsWith("Hell"));
2606}
2607
2608// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2609// doesn't match the matcher.
2610TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
2611 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
2612 // which cannot reference auto variables.
zhanyong.wan736baa82010-09-27 17:44:16 +00002613 static unsigned short n; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00002614 n = 5;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002615
2616 // VC++ prior to version 8.0 SP1 has a bug where it will not see any
2617 // functions declared in the namespace scope from within nested classes.
2618 // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
2619 // namespace-level functions invoked inside them need to be explicitly
2620 // resolved.
2621 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
shiqiane35fdd92008-12-10 05:08:54 +00002622 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002623 "Expected: is > 10\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002624 " Actual: 5" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002625 n = 0;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002626 EXPECT_NONFATAL_FAILURE(
2627 EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
2628 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002629 "Expected: (is <= 7) and (is >= 5)\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002630 " Actual: 0" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002631}
2632
2633// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
2634// has a reference type.
2635TEST(MatcherAssertionTest, WorksForByRefArguments) {
2636 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
2637 // reference auto variables.
2638 static int n;
2639 n = 0;
2640 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002641 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
shiqiane35fdd92008-12-10 05:08:54 +00002642 "Value of: n\n"
2643 "Expected: does not reference the variable @");
2644 // Tests the "Actual" part.
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002645 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
zhanyong.wan736baa82010-09-27 17:44:16 +00002646 "Actual: 0" + OfType("int") + ", which is located @");
shiqiane35fdd92008-12-10 05:08:54 +00002647}
2648
zhanyong.wan95b12332009-09-25 18:55:50 +00002649#if !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002650// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
2651// monomorphic.
zhanyong.wan95b12332009-09-25 18:55:50 +00002652
2653// ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
2654// Symbian compiler: it tries to compile
2655// template<T, U> class MatcherCastImpl { ...
zhanyong.wandb22c222010-01-28 21:52:29 +00002656// virtual bool MatchAndExplain(T x, ...) const {
2657// return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
zhanyong.wan95b12332009-09-25 18:55:50 +00002658// with U == string and T == const char*
2659// With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
2660// the compiler silently crashes with no output.
2661// If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
2662// the code compiles but the converted string is bogus.
shiqiane35fdd92008-12-10 05:08:54 +00002663TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
2664 Matcher<const char*> starts_with_he = StartsWith("he");
2665 ASSERT_THAT("hello", starts_with_he);
2666
2667 Matcher<const string&> ends_with_ok = EndsWith("ok");
2668 ASSERT_THAT("book", ends_with_ok);
zhanyong.wan736baa82010-09-27 17:44:16 +00002669 const string bad = "bad";
2670 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
2671 "Value of: bad\n"
2672 "Expected: ends with \"ok\"\n"
2673 " Actual: \"bad\"");
shiqiane35fdd92008-12-10 05:08:54 +00002674 Matcher<int> is_greater_than_5 = Gt(5);
2675 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
2676 "Value of: 5\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002677 "Expected: is > 5\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002678 " Actual: 5" + OfType("int"));
shiqiane35fdd92008-12-10 05:08:54 +00002679}
zhanyong.wan95b12332009-09-25 18:55:50 +00002680#endif // !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002681
2682// Tests floating-point matchers.
2683template <typename RawType>
2684class FloatingPointTest : public testing::Test {
2685 protected:
zhanyong.wan35877b72013-09-18 17:51:08 +00002686 typedef testing::internal::FloatingPoint<RawType> Floating;
shiqiane35fdd92008-12-10 05:08:54 +00002687 typedef typename Floating::Bits Bits;
2688
zhanyong.wan35877b72013-09-18 17:51:08 +00002689 FloatingPointTest()
2690 : max_ulps_(Floating::kMaxUlps),
2691 zero_bits_(Floating(0).bits()),
2692 one_bits_(Floating(1).bits()),
2693 infinity_bits_(Floating(Floating::Infinity()).bits()),
2694 close_to_positive_zero_(
2695 Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
2696 close_to_negative_zero_(
2697 -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
2698 further_from_negative_zero_(-Floating::ReinterpretBits(
2699 zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
2700 close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
2701 further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
2702 infinity_(Floating::Infinity()),
2703 close_to_infinity_(
2704 Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
2705 further_from_infinity_(
2706 Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
2707 max_(Floating::Max()),
2708 nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
2709 nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
shiqiane35fdd92008-12-10 05:08:54 +00002710 }
2711
2712 void TestSize() {
2713 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2714 }
2715
2716 // A battery of tests for FloatingEqMatcher::Matches.
2717 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2718 void TestMatches(
2719 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
2720 Matcher<RawType> m1 = matcher_maker(0.0);
2721 EXPECT_TRUE(m1.Matches(-0.0));
2722 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
2723 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
2724 EXPECT_FALSE(m1.Matches(1.0));
2725
2726 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
2727 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
2728
2729 Matcher<RawType> m3 = matcher_maker(1.0);
2730 EXPECT_TRUE(m3.Matches(close_to_one_));
2731 EXPECT_FALSE(m3.Matches(further_from_one_));
2732
2733 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
2734 EXPECT_FALSE(m3.Matches(0.0));
2735
2736 Matcher<RawType> m4 = matcher_maker(-infinity_);
2737 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
2738
2739 Matcher<RawType> m5 = matcher_maker(infinity_);
2740 EXPECT_TRUE(m5.Matches(close_to_infinity_));
2741
2742 // This is interesting as the representations of infinity_ and nan1_
2743 // are only 1 DLP apart.
2744 EXPECT_FALSE(m5.Matches(nan1_));
2745
2746 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2747 // some cases.
2748 Matcher<const RawType&> m6 = matcher_maker(0.0);
2749 EXPECT_TRUE(m6.Matches(-0.0));
2750 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
2751 EXPECT_FALSE(m6.Matches(1.0));
2752
2753 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2754 // cases.
2755 Matcher<RawType&> m7 = matcher_maker(0.0);
2756 RawType x = 0.0;
2757 EXPECT_TRUE(m7.Matches(x));
2758 x = 0.01f;
2759 EXPECT_FALSE(m7.Matches(x));
2760 }
2761
2762 // Pre-calculated numbers to be used by the tests.
2763
zhanyong.wan35877b72013-09-18 17:51:08 +00002764 const size_t max_ulps_;
shiqiane35fdd92008-12-10 05:08:54 +00002765
zhanyong.wan35877b72013-09-18 17:51:08 +00002766 const Bits zero_bits_; // The bits that represent 0.0.
2767 const Bits one_bits_; // The bits that represent 1.0.
2768 const Bits infinity_bits_; // The bits that represent +infinity.
shiqiane35fdd92008-12-10 05:08:54 +00002769
zhanyong.wan35877b72013-09-18 17:51:08 +00002770 // Some numbers close to 0.0.
2771 const RawType close_to_positive_zero_;
2772 const RawType close_to_negative_zero_;
2773 const RawType further_from_negative_zero_;
shiqiane35fdd92008-12-10 05:08:54 +00002774
zhanyong.wan35877b72013-09-18 17:51:08 +00002775 // Some numbers close to 1.0.
2776 const RawType close_to_one_;
2777 const RawType further_from_one_;
2778
2779 // Some numbers close to +infinity.
2780 const RawType infinity_;
2781 const RawType close_to_infinity_;
2782 const RawType further_from_infinity_;
2783
2784 // Maximum representable value that's not infinity.
2785 const RawType max_;
2786
2787 // Some NaNs.
2788 const RawType nan1_;
2789 const RawType nan2_;
shiqiane35fdd92008-12-10 05:08:54 +00002790};
2791
zhanyong.wan616180e2013-06-18 18:49:51 +00002792// Tests floating-point matchers with fixed epsilons.
2793template <typename RawType>
2794class FloatingPointNearTest : public FloatingPointTest<RawType> {
2795 protected:
2796 typedef FloatingPointTest<RawType> ParentType;
2797
2798 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
2799 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2800 void TestNearMatches(
2801 testing::internal::FloatingEqMatcher<RawType>
2802 (*matcher_maker)(RawType, RawType)) {
2803 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
2804 EXPECT_TRUE(m1.Matches(0.0));
2805 EXPECT_TRUE(m1.Matches(-0.0));
2806 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
2807 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
2808 EXPECT_FALSE(m1.Matches(1.0));
2809
2810 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
2811 EXPECT_TRUE(m2.Matches(0.0));
2812 EXPECT_TRUE(m2.Matches(-0.0));
2813 EXPECT_TRUE(m2.Matches(1.0));
2814 EXPECT_TRUE(m2.Matches(-1.0));
2815 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
2816 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
2817
2818 // Check that inf matches inf, regardless of the of the specified max
2819 // absolute error.
2820 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
2821 EXPECT_TRUE(m3.Matches(ParentType::infinity_));
2822 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
2823 EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
2824
2825 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
2826 EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
2827 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
2828 EXPECT_FALSE(m4.Matches(ParentType::infinity_));
2829
2830 // Test various overflow scenarios.
zhanyong.wan35877b72013-09-18 17:51:08 +00002831 Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
2832 EXPECT_TRUE(m5.Matches(ParentType::max_));
2833 EXPECT_FALSE(m5.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002834
zhanyong.wan35877b72013-09-18 17:51:08 +00002835 Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
2836 EXPECT_FALSE(m6.Matches(ParentType::max_));
2837 EXPECT_TRUE(m6.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002838
zhanyong.wan35877b72013-09-18 17:51:08 +00002839 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
2840 EXPECT_TRUE(m7.Matches(ParentType::max_));
2841 EXPECT_FALSE(m7.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002842
zhanyong.wan35877b72013-09-18 17:51:08 +00002843 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
2844 EXPECT_FALSE(m8.Matches(ParentType::max_));
2845 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002846
2847 // The difference between max() and -max() normally overflows to infinity,
2848 // but it should still match if the max_abs_error is also infinity.
2849 Matcher<RawType> m9 = matcher_maker(
zhanyong.wan35877b72013-09-18 17:51:08 +00002850 ParentType::max_, ParentType::infinity_);
2851 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002852
2853 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2854 // some cases.
2855 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
2856 EXPECT_TRUE(m10.Matches(-0.0));
2857 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
2858 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
2859
2860 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2861 // cases.
2862 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
2863 RawType x = 0.0;
2864 EXPECT_TRUE(m11.Matches(x));
2865 x = 1.0f;
2866 EXPECT_TRUE(m11.Matches(x));
2867 x = -1.0f;
2868 EXPECT_TRUE(m11.Matches(x));
2869 x = 1.1f;
2870 EXPECT_FALSE(m11.Matches(x));
2871 x = -1.1f;
2872 EXPECT_FALSE(m11.Matches(x));
2873 }
2874};
2875
shiqiane35fdd92008-12-10 05:08:54 +00002876// Instantiate FloatingPointTest for testing floats.
2877typedef FloatingPointTest<float> FloatTest;
2878
2879TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
2880 TestMatches(&FloatEq);
2881}
2882
2883TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
2884 TestMatches(&NanSensitiveFloatEq);
2885}
2886
2887TEST_F(FloatTest, FloatEqCannotMatchNaN) {
2888 // FloatEq never matches NaN.
2889 Matcher<float> m = FloatEq(nan1_);
2890 EXPECT_FALSE(m.Matches(nan1_));
2891 EXPECT_FALSE(m.Matches(nan2_));
2892 EXPECT_FALSE(m.Matches(1.0));
2893}
2894
2895TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
2896 // NanSensitiveFloatEq will match NaN.
2897 Matcher<float> m = NanSensitiveFloatEq(nan1_);
2898 EXPECT_TRUE(m.Matches(nan1_));
2899 EXPECT_TRUE(m.Matches(nan2_));
2900 EXPECT_FALSE(m.Matches(1.0));
2901}
2902
2903TEST_F(FloatTest, FloatEqCanDescribeSelf) {
2904 Matcher<float> m1 = FloatEq(2.0f);
2905 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002906 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002907
2908 Matcher<float> m2 = FloatEq(0.5f);
2909 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002910 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002911
2912 Matcher<float> m3 = FloatEq(nan1_);
2913 EXPECT_EQ("never matches", Describe(m3));
2914 EXPECT_EQ("is anything", DescribeNegation(m3));
2915}
2916
2917TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
2918 Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
2919 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002920 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002921
2922 Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
2923 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002924 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002925
2926 Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
2927 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002928 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00002929}
2930
zhanyong.wan616180e2013-06-18 18:49:51 +00002931// Instantiate FloatingPointTest for testing floats with a user-specified
2932// max absolute error.
2933typedef FloatingPointNearTest<float> FloatNearTest;
2934
2935TEST_F(FloatNearTest, FloatNearMatches) {
2936 TestNearMatches(&FloatNear);
2937}
2938
2939TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
2940 TestNearMatches(&NanSensitiveFloatNear);
2941}
2942
2943TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
2944 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
2945 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2946 EXPECT_EQ(
2947 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2948
2949 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
2950 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2951 EXPECT_EQ(
2952 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2953
2954 Matcher<float> m3 = FloatNear(nan1_, 0.0);
2955 EXPECT_EQ("never matches", Describe(m3));
2956 EXPECT_EQ("is anything", DescribeNegation(m3));
2957}
2958
2959TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
2960 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
2961 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2962 EXPECT_EQ(
2963 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2964
2965 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
2966 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2967 EXPECT_EQ(
2968 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2969
2970 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
2971 EXPECT_EQ("is NaN", Describe(m3));
2972 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
2973}
2974
2975TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
2976 // FloatNear never matches NaN.
2977 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
2978 EXPECT_FALSE(m.Matches(nan1_));
2979 EXPECT_FALSE(m.Matches(nan2_));
2980 EXPECT_FALSE(m.Matches(1.0));
2981}
2982
2983TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
2984 // NanSensitiveFloatNear will match NaN.
2985 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
2986 EXPECT_TRUE(m.Matches(nan1_));
2987 EXPECT_TRUE(m.Matches(nan2_));
2988 EXPECT_FALSE(m.Matches(1.0));
2989}
2990
shiqiane35fdd92008-12-10 05:08:54 +00002991// Instantiate FloatingPointTest for testing doubles.
2992typedef FloatingPointTest<double> DoubleTest;
2993
2994TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
2995 TestMatches(&DoubleEq);
2996}
2997
2998TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
2999 TestMatches(&NanSensitiveDoubleEq);
3000}
3001
3002TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
3003 // DoubleEq never matches NaN.
3004 Matcher<double> m = DoubleEq(nan1_);
3005 EXPECT_FALSE(m.Matches(nan1_));
3006 EXPECT_FALSE(m.Matches(nan2_));
3007 EXPECT_FALSE(m.Matches(1.0));
3008}
3009
3010TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3011 // NanSensitiveDoubleEq will match NaN.
3012 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
3013 EXPECT_TRUE(m.Matches(nan1_));
3014 EXPECT_TRUE(m.Matches(nan2_));
3015 EXPECT_FALSE(m.Matches(1.0));
3016}
3017
3018TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3019 Matcher<double> m1 = DoubleEq(2.0);
3020 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003021 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003022
3023 Matcher<double> m2 = DoubleEq(0.5);
3024 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003025 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003026
3027 Matcher<double> m3 = DoubleEq(nan1_);
3028 EXPECT_EQ("never matches", Describe(m3));
3029 EXPECT_EQ("is anything", DescribeNegation(m3));
3030}
3031
3032TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3033 Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3034 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003035 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003036
3037 Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3038 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003039 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003040
3041 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3042 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003043 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00003044}
3045
zhanyong.wan616180e2013-06-18 18:49:51 +00003046// Instantiate FloatingPointTest for testing floats with a user-specified
3047// max absolute error.
3048typedef FloatingPointNearTest<double> DoubleNearTest;
3049
3050TEST_F(DoubleNearTest, DoubleNearMatches) {
3051 TestNearMatches(&DoubleNear);
3052}
3053
3054TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3055 TestNearMatches(&NanSensitiveDoubleNear);
3056}
3057
3058TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3059 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3060 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3061 EXPECT_EQ(
3062 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3063
3064 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3065 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3066 EXPECT_EQ(
3067 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3068
3069 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3070 EXPECT_EQ("never matches", Describe(m3));
3071 EXPECT_EQ("is anything", DescribeNegation(m3));
3072}
3073
kosak6b817802015-01-08 02:38:14 +00003074TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
3075 EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
3076 EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
3077 EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
3078
3079 const string explanation = Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
3080 // Different C++ implementations may print floating-point numbers
3081 // slightly differently.
3082 EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC
3083 explanation == "which is 1.2e-010 from 2.1") // MSVC
3084 << " where explanation is \"" << explanation << "\".";
3085}
3086
zhanyong.wan616180e2013-06-18 18:49:51 +00003087TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3088 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3089 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3090 EXPECT_EQ(
3091 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3092
3093 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3094 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3095 EXPECT_EQ(
3096 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3097
3098 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3099 EXPECT_EQ("is NaN", Describe(m3));
3100 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3101}
3102
3103TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3104 // DoubleNear never matches NaN.
3105 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3106 EXPECT_FALSE(m.Matches(nan1_));
3107 EXPECT_FALSE(m.Matches(nan2_));
3108 EXPECT_FALSE(m.Matches(1.0));
3109}
3110
3111TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3112 // NanSensitiveDoubleNear will match NaN.
3113 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3114 EXPECT_TRUE(m.Matches(nan1_));
3115 EXPECT_TRUE(m.Matches(nan2_));
3116 EXPECT_FALSE(m.Matches(1.0));
3117}
3118
shiqiane35fdd92008-12-10 05:08:54 +00003119TEST(PointeeTest, RawPointer) {
3120 const Matcher<int*> m = Pointee(Ge(0));
3121
3122 int n = 1;
3123 EXPECT_TRUE(m.Matches(&n));
3124 n = -1;
3125 EXPECT_FALSE(m.Matches(&n));
3126 EXPECT_FALSE(m.Matches(NULL));
3127}
3128
3129TEST(PointeeTest, RawPointerToConst) {
3130 const Matcher<const double*> m = Pointee(Ge(0));
3131
3132 double x = 1;
3133 EXPECT_TRUE(m.Matches(&x));
3134 x = -1;
3135 EXPECT_FALSE(m.Matches(&x));
3136 EXPECT_FALSE(m.Matches(NULL));
3137}
3138
3139TEST(PointeeTest, ReferenceToConstRawPointer) {
3140 const Matcher<int* const &> m = Pointee(Ge(0));
3141
3142 int n = 1;
3143 EXPECT_TRUE(m.Matches(&n));
3144 n = -1;
3145 EXPECT_FALSE(m.Matches(&n));
3146 EXPECT_FALSE(m.Matches(NULL));
3147}
3148
3149TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3150 const Matcher<double* &> m = Pointee(Ge(0));
3151
3152 double x = 1.0;
3153 double* p = &x;
3154 EXPECT_TRUE(m.Matches(p));
3155 x = -1;
3156 EXPECT_FALSE(m.Matches(p));
3157 p = NULL;
3158 EXPECT_FALSE(m.Matches(p));
3159}
3160
billydonahue1f5fdea2014-05-19 17:54:51 +00003161
3162MATCHER_P(FieldIIs, inner_matcher, "") {
3163 return ExplainMatchResult(inner_matcher, arg.i, result_listener);
3164}
3165
3166TEST(WhenDynamicCastToTest, SameType) {
3167 Derived derived;
3168 derived.i = 4;
3169
3170 // Right type. A pointer is passed down.
3171 Base* as_base_ptr = &derived;
3172 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
3173 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
3174 EXPECT_THAT(as_base_ptr,
3175 Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
3176}
3177
3178TEST(WhenDynamicCastToTest, WrongTypes) {
3179 Base base;
3180 Derived derived;
3181 OtherDerived other_derived;
3182
3183 // Wrong types. NULL is passed.
3184 EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3185 EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
3186 Base* as_base_ptr = &derived;
3187 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
3188 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
3189 as_base_ptr = &other_derived;
3190 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3191 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3192}
3193
3194TEST(WhenDynamicCastToTest, AlreadyNull) {
3195 // Already NULL.
3196 Base* as_base_ptr = NULL;
3197 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3198}
3199
3200struct AmbiguousCastTypes {
3201 class VirtualDerived : public virtual Base {};
3202 class DerivedSub1 : public VirtualDerived {};
3203 class DerivedSub2 : public VirtualDerived {};
3204 class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
3205};
3206
3207TEST(WhenDynamicCastToTest, AmbiguousCast) {
3208 AmbiguousCastTypes::DerivedSub1 sub1;
3209 AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
3210 // Multiply derived from Base. dynamic_cast<> returns NULL.
3211 Base* as_base_ptr =
3212 static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
3213 EXPECT_THAT(as_base_ptr,
3214 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
3215 as_base_ptr = &sub1;
3216 EXPECT_THAT(
3217 as_base_ptr,
3218 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
3219}
3220
3221TEST(WhenDynamicCastToTest, Describe) {
3222 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3223#if GTEST_HAS_RTTI
3224 const string prefix =
3225 "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
3226#else // GTEST_HAS_RTTI
3227 const string prefix = "when dynamic_cast, ";
3228#endif // GTEST_HAS_RTTI
3229 EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
3230 EXPECT_EQ(prefix + "does not point to a value that is anything",
3231 DescribeNegation(matcher));
3232}
3233
3234TEST(WhenDynamicCastToTest, Explain) {
3235 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3236 Base* null = NULL;
3237 EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
3238 Derived derived;
3239 EXPECT_TRUE(matcher.Matches(&derived));
3240 EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
3241
3242 // With references, the matcher itself can fail. Test for that one.
3243 Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
3244 EXPECT_THAT(Explain(ref_matcher, derived),
3245 HasSubstr("which cannot be dynamic_cast"));
3246}
3247
3248TEST(WhenDynamicCastToTest, GoodReference) {
3249 Derived derived;
3250 derived.i = 4;
3251 Base& as_base_ref = derived;
3252 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
3253 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
3254}
3255
3256TEST(WhenDynamicCastToTest, BadReference) {
3257 Derived derived;
3258 Base& as_base_ref = derived;
3259 EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
3260}
3261
vladlosevada23472012-08-14 15:38:49 +00003262// Minimal const-propagating pointer.
3263template <typename T>
3264class ConstPropagatingPtr {
3265 public:
3266 typedef T element_type;
3267
3268 ConstPropagatingPtr() : val_() {}
3269 explicit ConstPropagatingPtr(T* t) : val_(t) {}
3270 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3271
3272 T* get() { return val_; }
3273 T& operator*() { return *val_; }
3274 // Most smart pointers return non-const T* and T& from the next methods.
3275 const T* get() const { return val_; }
3276 const T& operator*() const { return *val_; }
3277
3278 private:
3279 T* val_;
3280};
3281
3282TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3283 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3284 int three = 3;
3285 const ConstPropagatingPtr<int> co(&three);
3286 ConstPropagatingPtr<int> o(&three);
3287 EXPECT_TRUE(m.Matches(o));
3288 EXPECT_TRUE(m.Matches(co));
3289 *o = 6;
3290 EXPECT_FALSE(m.Matches(o));
3291 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3292}
3293
shiqiane35fdd92008-12-10 05:08:54 +00003294TEST(PointeeTest, NeverMatchesNull) {
3295 const Matcher<const char*> m = Pointee(_);
3296 EXPECT_FALSE(m.Matches(NULL));
3297}
3298
3299// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3300TEST(PointeeTest, MatchesAgainstAValue) {
3301 const Matcher<int*> m = Pointee(5);
3302
3303 int n = 5;
3304 EXPECT_TRUE(m.Matches(&n));
3305 n = -1;
3306 EXPECT_FALSE(m.Matches(&n));
3307 EXPECT_FALSE(m.Matches(NULL));
3308}
3309
3310TEST(PointeeTest, CanDescribeSelf) {
3311 const Matcher<int*> m = Pointee(Gt(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003312 EXPECT_EQ("points to a value that is > 3", Describe(m));
3313 EXPECT_EQ("does not point to a value that is > 3",
shiqiane35fdd92008-12-10 05:08:54 +00003314 DescribeNegation(m));
3315}
3316
shiqiane35fdd92008-12-10 05:08:54 +00003317TEST(PointeeTest, CanExplainMatchResult) {
3318 const Matcher<const string*> m = Pointee(StartsWith("Hi"));
3319
3320 EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL)));
3321
zhanyong.wan736baa82010-09-27 17:44:16 +00003322 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
3323 long n = 3; // NOLINT
3324 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003325 Explain(m2, &n));
3326}
3327
3328TEST(PointeeTest, AlwaysExplainsPointee) {
3329 const Matcher<int*> m = Pointee(0);
3330 int n = 42;
zhanyong.wan736baa82010-09-27 17:44:16 +00003331 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
shiqiane35fdd92008-12-10 05:08:54 +00003332}
3333
3334// An uncopyable class.
3335class Uncopyable {
3336 public:
billydonahue1f5fdea2014-05-19 17:54:51 +00003337 Uncopyable() : value_(-1) {}
zhanyong.wan32de5f52009-12-23 00:13:23 +00003338 explicit Uncopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003339
3340 int value() const { return value_; }
billydonahue1f5fdea2014-05-19 17:54:51 +00003341 void set_value(int i) { value_ = i; }
3342
shiqiane35fdd92008-12-10 05:08:54 +00003343 private:
billydonahue1f5fdea2014-05-19 17:54:51 +00003344 int value_;
shiqiane35fdd92008-12-10 05:08:54 +00003345 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3346};
3347
3348// Returns true iff x.value() is positive.
3349bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3350
billydonahue1f5fdea2014-05-19 17:54:51 +00003351MATCHER_P(UncopyableIs, inner_matcher, "") {
3352 return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
3353}
3354
shiqiane35fdd92008-12-10 05:08:54 +00003355// A user-defined struct for testing Field().
3356struct AStruct {
3357 AStruct() : x(0), y(1.0), z(5), p(NULL) {}
3358 AStruct(const AStruct& rhs)
3359 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3360
3361 int x; // A non-const field.
3362 const double y; // A const field.
3363 Uncopyable z; // An uncopyable field.
3364 const char* p; // A pointer field.
zhanyong.wan32de5f52009-12-23 00:13:23 +00003365
3366 private:
3367 GTEST_DISALLOW_ASSIGN_(AStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003368};
3369
3370// A derived struct for testing Field().
3371struct DerivedStruct : public AStruct {
3372 char ch;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003373
3374 private:
3375 GTEST_DISALLOW_ASSIGN_(DerivedStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003376};
3377
3378// Tests that Field(&Foo::field, ...) works when field is non-const.
3379TEST(FieldTest, WorksForNonConstField) {
3380 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
3381
3382 AStruct a;
3383 EXPECT_TRUE(m.Matches(a));
3384 a.x = -1;
3385 EXPECT_FALSE(m.Matches(a));
3386}
3387
3388// Tests that Field(&Foo::field, ...) works when field is const.
3389TEST(FieldTest, WorksForConstField) {
3390 AStruct a;
3391
3392 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
3393 EXPECT_TRUE(m.Matches(a));
3394 m = Field(&AStruct::y, Le(0.0));
3395 EXPECT_FALSE(m.Matches(a));
3396}
3397
3398// Tests that Field(&Foo::field, ...) works when field is not copyable.
3399TEST(FieldTest, WorksForUncopyableField) {
3400 AStruct a;
3401
3402 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3403 EXPECT_TRUE(m.Matches(a));
3404 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3405 EXPECT_FALSE(m.Matches(a));
3406}
3407
3408// Tests that Field(&Foo::field, ...) works when field is a pointer.
3409TEST(FieldTest, WorksForPointerField) {
3410 // Matching against NULL.
3411 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
3412 AStruct a;
3413 EXPECT_TRUE(m.Matches(a));
3414 a.p = "hi";
3415 EXPECT_FALSE(m.Matches(a));
3416
3417 // Matching a pointer that is not NULL.
3418 m = Field(&AStruct::p, StartsWith("hi"));
3419 a.p = "hill";
3420 EXPECT_TRUE(m.Matches(a));
3421 a.p = "hole";
3422 EXPECT_FALSE(m.Matches(a));
3423}
3424
3425// Tests that Field() works when the object is passed by reference.
3426TEST(FieldTest, WorksForByRefArgument) {
3427 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3428
3429 AStruct a;
3430 EXPECT_TRUE(m.Matches(a));
3431 a.x = -1;
3432 EXPECT_FALSE(m.Matches(a));
3433}
3434
3435// Tests that Field(&Foo::field, ...) works when the argument's type
3436// is a sub-type of Foo.
3437TEST(FieldTest, WorksForArgumentOfSubType) {
3438 // Note that the matcher expects DerivedStruct but we say AStruct
3439 // inside Field().
3440 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
3441
3442 DerivedStruct d;
3443 EXPECT_TRUE(m.Matches(d));
3444 d.x = -1;
3445 EXPECT_FALSE(m.Matches(d));
3446}
3447
3448// Tests that Field(&Foo::field, m) works when field's type and m's
3449// argument type are compatible but not the same.
3450TEST(FieldTest, WorksForCompatibleMatcherType) {
3451 // The field is an int, but the inner matcher expects a signed char.
3452 Matcher<const AStruct&> m = Field(&AStruct::x,
3453 Matcher<signed char>(Ge(0)));
3454
3455 AStruct a;
3456 EXPECT_TRUE(m.Matches(a));
3457 a.x = -1;
3458 EXPECT_FALSE(m.Matches(a));
3459}
3460
3461// Tests that Field() can describe itself.
3462TEST(FieldTest, CanDescribeSelf) {
3463 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3464
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003465 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3466 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003467}
3468
3469// Tests that Field() can explain the match result.
3470TEST(FieldTest, CanExplainMatchResult) {
3471 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3472
3473 AStruct a;
3474 a.x = 1;
zhanyong.wan736baa82010-09-27 17:44:16 +00003475 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003476
3477 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003478 EXPECT_EQ(
3479 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
3480 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003481}
3482
3483// Tests that Field() works when the argument is a pointer to const.
3484TEST(FieldForPointerTest, WorksForPointerToConst) {
3485 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3486
3487 AStruct a;
3488 EXPECT_TRUE(m.Matches(&a));
3489 a.x = -1;
3490 EXPECT_FALSE(m.Matches(&a));
3491}
3492
3493// Tests that Field() works when the argument is a pointer to non-const.
3494TEST(FieldForPointerTest, WorksForPointerToNonConst) {
3495 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
3496
3497 AStruct a;
3498 EXPECT_TRUE(m.Matches(&a));
3499 a.x = -1;
3500 EXPECT_FALSE(m.Matches(&a));
3501}
3502
zhanyong.wan6953a722010-01-13 05:15:07 +00003503// Tests that Field() works when the argument is a reference to a const pointer.
3504TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
3505 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
3506
3507 AStruct a;
3508 EXPECT_TRUE(m.Matches(&a));
3509 a.x = -1;
3510 EXPECT_FALSE(m.Matches(&a));
3511}
3512
shiqiane35fdd92008-12-10 05:08:54 +00003513// Tests that Field() does not match the NULL pointer.
3514TEST(FieldForPointerTest, DoesNotMatchNull) {
3515 Matcher<const AStruct*> m = Field(&AStruct::x, _);
3516 EXPECT_FALSE(m.Matches(NULL));
3517}
3518
3519// Tests that Field(&Foo::field, ...) works when the argument's type
3520// is a sub-type of const Foo*.
3521TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
3522 // Note that the matcher expects DerivedStruct but we say AStruct
3523 // inside Field().
3524 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
3525
3526 DerivedStruct d;
3527 EXPECT_TRUE(m.Matches(&d));
3528 d.x = -1;
3529 EXPECT_FALSE(m.Matches(&d));
3530}
3531
3532// Tests that Field() can describe itself when used to match a pointer.
3533TEST(FieldForPointerTest, CanDescribeSelf) {
3534 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3535
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003536 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3537 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003538}
3539
3540// Tests that Field() can explain the result of matching a pointer.
3541TEST(FieldForPointerTest, CanExplainMatchResult) {
3542 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3543
3544 AStruct a;
3545 a.x = 1;
3546 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003547 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
3548 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003549
3550 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003551 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
3552 ", which is 1 more than 0", Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003553}
3554
3555// A user-defined class for testing Property().
3556class AClass {
3557 public:
3558 AClass() : n_(0) {}
3559
3560 // A getter that returns a non-reference.
3561 int n() const { return n_; }
3562
3563 void set_n(int new_n) { n_ = new_n; }
3564
3565 // A getter that returns a reference to const.
3566 const string& s() const { return s_; }
3567
3568 void set_s(const string& new_s) { s_ = new_s; }
3569
3570 // A getter that returns a reference to non-const.
3571 double& x() const { return x_; }
3572 private:
3573 int n_;
3574 string s_;
3575
3576 static double x_;
3577};
3578
3579double AClass::x_ = 0.0;
3580
3581// A derived class for testing Property().
3582class DerivedClass : public AClass {
kosak6414d802013-12-03 23:19:36 +00003583 public:
3584 int k() const { return k_; }
shiqiane35fdd92008-12-10 05:08:54 +00003585 private:
3586 int k_;
3587};
3588
3589// Tests that Property(&Foo::property, ...) works when property()
3590// returns a non-reference.
3591TEST(PropertyTest, WorksForNonReferenceProperty) {
3592 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3593
3594 AClass a;
3595 a.set_n(1);
3596 EXPECT_TRUE(m.Matches(a));
3597
3598 a.set_n(-1);
3599 EXPECT_FALSE(m.Matches(a));
3600}
3601
3602// Tests that Property(&Foo::property, ...) works when property()
3603// returns a reference to const.
3604TEST(PropertyTest, WorksForReferenceToConstProperty) {
3605 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
3606
3607 AClass a;
3608 a.set_s("hill");
3609 EXPECT_TRUE(m.Matches(a));
3610
3611 a.set_s("hole");
3612 EXPECT_FALSE(m.Matches(a));
3613}
3614
3615// Tests that Property(&Foo::property, ...) works when property()
3616// returns a reference to non-const.
3617TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
3618 double x = 0.0;
3619 AClass a;
3620
3621 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
3622 EXPECT_FALSE(m.Matches(a));
3623
3624 m = Property(&AClass::x, Not(Ref(x)));
3625 EXPECT_TRUE(m.Matches(a));
3626}
3627
3628// Tests that Property(&Foo::property, ...) works when the argument is
3629// passed by value.
3630TEST(PropertyTest, WorksForByValueArgument) {
3631 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
3632
3633 AClass a;
3634 a.set_s("hill");
3635 EXPECT_TRUE(m.Matches(a));
3636
3637 a.set_s("hole");
3638 EXPECT_FALSE(m.Matches(a));
3639}
3640
3641// Tests that Property(&Foo::property, ...) works when the argument's
3642// type is a sub-type of Foo.
3643TEST(PropertyTest, WorksForArgumentOfSubType) {
3644 // The matcher expects a DerivedClass, but inside the Property() we
3645 // say AClass.
3646 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
3647
3648 DerivedClass d;
3649 d.set_n(1);
3650 EXPECT_TRUE(m.Matches(d));
3651
3652 d.set_n(-1);
3653 EXPECT_FALSE(m.Matches(d));
3654}
3655
3656// Tests that Property(&Foo::property, m) works when property()'s type
3657// and m's argument type are compatible but different.
3658TEST(PropertyTest, WorksForCompatibleMatcherType) {
3659 // n() returns an int but the inner matcher expects a signed char.
3660 Matcher<const AClass&> m = Property(&AClass::n,
3661 Matcher<signed char>(Ge(0)));
3662
3663 AClass a;
3664 EXPECT_TRUE(m.Matches(a));
3665 a.set_n(-1);
3666 EXPECT_FALSE(m.Matches(a));
3667}
3668
3669// Tests that Property() can describe itself.
3670TEST(PropertyTest, CanDescribeSelf) {
3671 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3672
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003673 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3674 EXPECT_EQ("is an object whose given property isn't >= 0",
3675 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003676}
3677
3678// Tests that Property() can explain the match result.
3679TEST(PropertyTest, CanExplainMatchResult) {
3680 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3681
3682 AClass a;
3683 a.set_n(1);
zhanyong.wan736baa82010-09-27 17:44:16 +00003684 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003685
3686 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003687 EXPECT_EQ(
3688 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
3689 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003690}
3691
3692// Tests that Property() works when the argument is a pointer to const.
3693TEST(PropertyForPointerTest, WorksForPointerToConst) {
3694 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3695
3696 AClass a;
3697 a.set_n(1);
3698 EXPECT_TRUE(m.Matches(&a));
3699
3700 a.set_n(-1);
3701 EXPECT_FALSE(m.Matches(&a));
3702}
3703
3704// Tests that Property() works when the argument is a pointer to non-const.
3705TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
3706 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
3707
3708 AClass a;
3709 a.set_s("hill");
3710 EXPECT_TRUE(m.Matches(&a));
3711
3712 a.set_s("hole");
3713 EXPECT_FALSE(m.Matches(&a));
3714}
3715
zhanyong.wan6953a722010-01-13 05:15:07 +00003716// Tests that Property() works when the argument is a reference to a
3717// const pointer.
3718TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
3719 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
3720
3721 AClass a;
3722 a.set_s("hill");
3723 EXPECT_TRUE(m.Matches(&a));
3724
3725 a.set_s("hole");
3726 EXPECT_FALSE(m.Matches(&a));
3727}
3728
shiqiane35fdd92008-12-10 05:08:54 +00003729// Tests that Property() does not match the NULL pointer.
3730TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
3731 Matcher<const AClass*> m = Property(&AClass::x, _);
3732 EXPECT_FALSE(m.Matches(NULL));
3733}
3734
3735// Tests that Property(&Foo::property, ...) works when the argument's
3736// type is a sub-type of const Foo*.
3737TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
3738 // The matcher expects a DerivedClass, but inside the Property() we
3739 // say AClass.
3740 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
3741
3742 DerivedClass d;
3743 d.set_n(1);
3744 EXPECT_TRUE(m.Matches(&d));
3745
3746 d.set_n(-1);
3747 EXPECT_FALSE(m.Matches(&d));
3748}
3749
3750// Tests that Property() can describe itself when used to match a pointer.
3751TEST(PropertyForPointerTest, CanDescribeSelf) {
3752 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3753
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003754 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3755 EXPECT_EQ("is an object whose given property isn't >= 0",
3756 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003757}
3758
3759// Tests that Property() can explain the result of matching a pointer.
3760TEST(PropertyForPointerTest, CanExplainMatchResult) {
3761 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3762
3763 AClass a;
3764 a.set_n(1);
3765 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003766 EXPECT_EQ(
3767 "which points to an object whose given property is 1" + OfType("int"),
3768 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003769
3770 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003771 EXPECT_EQ("which points to an object whose given property is 1" +
3772 OfType("int") + ", which is 1 more than 0",
3773 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003774}
3775
3776// Tests ResultOf.
3777
3778// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3779// function pointer.
3780string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; }
3781
3782TEST(ResultOfTest, WorksForFunctionPointers) {
3783 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo")));
3784
3785 EXPECT_TRUE(matcher.Matches(1));
3786 EXPECT_FALSE(matcher.Matches(2));
3787}
3788
3789// Tests that ResultOf() can describe itself.
3790TEST(ResultOfTest, CanDescribeItself) {
3791 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
3792
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003793 EXPECT_EQ("is mapped by the given callable to a value that "
3794 "is equal to \"foo\"", Describe(matcher));
3795 EXPECT_EQ("is mapped by the given callable to a value that "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003796 "isn't equal to \"foo\"", DescribeNegation(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00003797}
3798
3799// Tests that ResultOf() can explain the match result.
3800int IntFunction(int input) { return input == 42 ? 80 : 90; }
3801
3802TEST(ResultOfTest, CanExplainMatchResult) {
3803 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003804 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003805 Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003806
3807 matcher = ResultOf(&IntFunction, GreaterThan(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003808 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
3809 ", which is 5 more than 85", Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003810}
3811
3812// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3813// returns a non-reference.
3814TEST(ResultOfTest, WorksForNonReferenceResults) {
3815 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
3816
3817 EXPECT_TRUE(matcher.Matches(42));
3818 EXPECT_FALSE(matcher.Matches(36));
3819}
3820
3821// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3822// returns a reference to non-const.
zhanyong.wan736baa82010-09-27 17:44:16 +00003823double& DoubleFunction(double& input) { return input; } // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003824
zhanyong.wan736baa82010-09-27 17:44:16 +00003825Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003826 return obj;
3827}
3828
3829TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
3830 double x = 3.14;
3831 double x2 = x;
3832 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
3833
3834 EXPECT_TRUE(matcher.Matches(x));
3835 EXPECT_FALSE(matcher.Matches(x2));
3836
3837 // Test that ResultOf works with uncopyable objects
3838 Uncopyable obj(0);
3839 Uncopyable obj2(0);
3840 Matcher<Uncopyable&> matcher2 =
3841 ResultOf(&RefUncopyableFunction, Ref(obj));
3842
3843 EXPECT_TRUE(matcher2.Matches(obj));
3844 EXPECT_FALSE(matcher2.Matches(obj2));
3845}
3846
3847// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3848// returns a reference to const.
3849const string& StringFunction(const string& input) { return input; }
3850
3851TEST(ResultOfTest, WorksForReferenceToConstResults) {
3852 string s = "foo";
3853 string s2 = s;
3854 Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s));
3855
3856 EXPECT_TRUE(matcher.Matches(s));
3857 EXPECT_FALSE(matcher.Matches(s2));
3858}
3859
3860// Tests that ResultOf(f, m) works when f(x) and m's
3861// argument types are compatible but different.
3862TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
3863 // IntFunction() returns int but the inner matcher expects a signed char.
3864 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
3865
3866 EXPECT_TRUE(matcher.Matches(36));
3867 EXPECT_FALSE(matcher.Matches(42));
3868}
3869
shiqiane35fdd92008-12-10 05:08:54 +00003870// Tests that the program aborts when ResultOf is passed
3871// a NULL function pointer.
3872TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
zhanyong.wan04d6ed82009-09-11 07:01:08 +00003873 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan736baa82010-09-27 17:44:16 +00003874 ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))),
shiqiane35fdd92008-12-10 05:08:54 +00003875 "NULL function pointer is passed into ResultOf\\(\\)\\.");
3876}
shiqiane35fdd92008-12-10 05:08:54 +00003877
3878// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3879// function reference.
3880TEST(ResultOfTest, WorksForFunctionReferences) {
3881 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
3882 EXPECT_TRUE(matcher.Matches(1));
3883 EXPECT_FALSE(matcher.Matches(2));
3884}
3885
3886// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3887// function object.
3888struct Functor : public ::std::unary_function<int, string> {
3889 result_type operator()(argument_type input) const {
3890 return IntToStringFunction(input);
3891 }
3892};
3893
3894TEST(ResultOfTest, WorksForFunctors) {
3895 Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo")));
3896
3897 EXPECT_TRUE(matcher.Matches(1));
3898 EXPECT_FALSE(matcher.Matches(2));
3899}
3900
3901// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3902// functor with more then one operator() defined. ResultOf() must work
3903// for each defined operator().
3904struct PolymorphicFunctor {
3905 typedef int result_type;
3906 int operator()(int n) { return n; }
3907 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
3908};
3909
3910TEST(ResultOfTest, WorksForPolymorphicFunctors) {
3911 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
3912
3913 EXPECT_TRUE(matcher_int.Matches(10));
3914 EXPECT_FALSE(matcher_int.Matches(2));
3915
3916 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
3917
3918 EXPECT_TRUE(matcher_string.Matches("long string"));
3919 EXPECT_FALSE(matcher_string.Matches("shrt"));
3920}
3921
3922const int* ReferencingFunction(const int& n) { return &n; }
3923
3924struct ReferencingFunctor {
3925 typedef const int* result_type;
3926 result_type operator()(const int& n) { return &n; }
3927};
3928
3929TEST(ResultOfTest, WorksForReferencingCallables) {
3930 const int n = 1;
3931 const int n2 = 1;
3932 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
3933 EXPECT_TRUE(matcher2.Matches(n));
3934 EXPECT_FALSE(matcher2.Matches(n2));
3935
3936 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
3937 EXPECT_TRUE(matcher3.Matches(n));
3938 EXPECT_FALSE(matcher3.Matches(n2));
3939}
3940
shiqiane35fdd92008-12-10 05:08:54 +00003941class DivisibleByImpl {
3942 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003943 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
shiqiane35fdd92008-12-10 05:08:54 +00003944
zhanyong.wandb22c222010-01-28 21:52:29 +00003945 // For testing using ExplainMatchResultTo() with polymorphic matchers.
shiqiane35fdd92008-12-10 05:08:54 +00003946 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00003947 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003948 *listener << "which is " << (n % divider_) << " modulo "
zhanyong.wandb22c222010-01-28 21:52:29 +00003949 << divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003950 return (n % divider_) == 0;
3951 }
3952
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003953 void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003954 *os << "is divisible by " << divider_;
3955 }
3956
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003957 void DescribeNegationTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003958 *os << "is not divisible by " << divider_;
3959 }
3960
zhanyong.wan32de5f52009-12-23 00:13:23 +00003961 void set_divider(int a_divider) { divider_ = a_divider; }
shiqiane35fdd92008-12-10 05:08:54 +00003962 int divider() const { return divider_; }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003963
shiqiane35fdd92008-12-10 05:08:54 +00003964 private:
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003965 int divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003966};
3967
shiqiane35fdd92008-12-10 05:08:54 +00003968PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
3969 return MakePolymorphicMatcher(DivisibleByImpl(n));
3970}
3971
3972// Tests that when AllOf() fails, only the first failing matcher is
3973// asked to explain why.
3974TEST(ExplainMatchResultTest, AllOf_False_False) {
3975 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003976 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00003977}
3978
3979// Tests that when AllOf() fails, only the first failing matcher is
3980// asked to explain why.
3981TEST(ExplainMatchResultTest, AllOf_False_True) {
3982 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003983 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003984}
3985
3986// Tests that when AllOf() fails, only the first failing matcher is
3987// asked to explain why.
3988TEST(ExplainMatchResultTest, AllOf_True_False) {
3989 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003990 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00003991}
3992
3993// Tests that when AllOf() succeeds, all matchers are asked to explain
3994// why.
3995TEST(ExplainMatchResultTest, AllOf_True_True) {
3996 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003997 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003998}
3999
4000TEST(ExplainMatchResultTest, AllOf_True_True_2) {
4001 const Matcher<int> m = AllOf(Ge(2), Le(3));
4002 EXPECT_EQ("", Explain(m, 2));
4003}
4004
4005TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
4006 const Matcher<int> m = GreaterThan(5);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00004007 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00004008}
4009
4010// The following two tests verify that values without a public copy
4011// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
4012// with the help of ByRef().
4013
4014class NotCopyable {
4015 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00004016 explicit NotCopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00004017
4018 int value() const { return value_; }
4019
4020 bool operator==(const NotCopyable& rhs) const {
4021 return value() == rhs.value();
4022 }
4023
4024 bool operator>=(const NotCopyable& rhs) const {
4025 return value() >= rhs.value();
4026 }
4027 private:
4028 int value_;
4029
4030 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
4031};
4032
4033TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
4034 const NotCopyable const_value1(1);
4035 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
4036
4037 const NotCopyable n1(1), n2(2);
4038 EXPECT_TRUE(m.Matches(n1));
4039 EXPECT_FALSE(m.Matches(n2));
4040}
4041
4042TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
4043 NotCopyable value2(2);
4044 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
4045
4046 NotCopyable n1(1), n2(2);
4047 EXPECT_FALSE(m.Matches(n1));
4048 EXPECT_TRUE(m.Matches(n2));
4049}
4050
zhanyong.wan320814a2013-03-01 00:20:30 +00004051TEST(IsEmptyTest, ImplementsIsEmpty) {
4052 vector<int> container;
4053 EXPECT_THAT(container, IsEmpty());
4054 container.push_back(0);
4055 EXPECT_THAT(container, Not(IsEmpty()));
4056 container.push_back(1);
4057 EXPECT_THAT(container, Not(IsEmpty()));
4058}
4059
4060TEST(IsEmptyTest, WorksWithString) {
4061 string text;
4062 EXPECT_THAT(text, IsEmpty());
4063 text = "foo";
4064 EXPECT_THAT(text, Not(IsEmpty()));
4065 text = string("\0", 1);
4066 EXPECT_THAT(text, Not(IsEmpty()));
4067}
4068
4069TEST(IsEmptyTest, CanDescribeSelf) {
4070 Matcher<vector<int> > m = IsEmpty();
4071 EXPECT_EQ("is empty", Describe(m));
4072 EXPECT_EQ("isn't empty", DescribeNegation(m));
4073}
4074
4075TEST(IsEmptyTest, ExplainsResult) {
4076 Matcher<vector<int> > m = IsEmpty();
4077 vector<int> container;
4078 EXPECT_EQ("", Explain(m, container));
4079 container.push_back(0);
4080 EXPECT_EQ("whose size is 1", Explain(m, container));
4081}
4082
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004083TEST(SizeIsTest, ImplementsSizeIs) {
4084 vector<int> container;
4085 EXPECT_THAT(container, SizeIs(0));
4086 EXPECT_THAT(container, Not(SizeIs(1)));
4087 container.push_back(0);
4088 EXPECT_THAT(container, Not(SizeIs(0)));
4089 EXPECT_THAT(container, SizeIs(1));
4090 container.push_back(0);
4091 EXPECT_THAT(container, Not(SizeIs(0)));
4092 EXPECT_THAT(container, SizeIs(2));
4093}
4094
4095TEST(SizeIsTest, WorksWithMap) {
4096 map<string, int> container;
4097 EXPECT_THAT(container, SizeIs(0));
4098 EXPECT_THAT(container, Not(SizeIs(1)));
4099 container.insert(make_pair("foo", 1));
4100 EXPECT_THAT(container, Not(SizeIs(0)));
4101 EXPECT_THAT(container, SizeIs(1));
4102 container.insert(make_pair("bar", 2));
4103 EXPECT_THAT(container, Not(SizeIs(0)));
4104 EXPECT_THAT(container, SizeIs(2));
4105}
4106
4107TEST(SizeIsTest, WorksWithReferences) {
4108 vector<int> container;
4109 Matcher<const vector<int>&> m = SizeIs(1);
4110 EXPECT_THAT(container, Not(m));
4111 container.push_back(0);
4112 EXPECT_THAT(container, m);
4113}
4114
4115TEST(SizeIsTest, CanDescribeSelf) {
4116 Matcher<vector<int> > m = SizeIs(2);
4117 EXPECT_EQ("size is equal to 2", Describe(m));
4118 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
4119}
4120
4121TEST(SizeIsTest, ExplainsResult) {
4122 Matcher<vector<int> > m1 = SizeIs(2);
4123 Matcher<vector<int> > m2 = SizeIs(Lt(2u));
4124 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
4125 Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
4126 vector<int> container;
4127 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
4128 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
4129 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
4130 EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
4131 Explain(m4, container));
4132 container.push_back(0);
4133 container.push_back(0);
4134 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
4135 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
4136 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
4137 EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
4138 Explain(m4, container));
4139}
4140
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004141#if GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004142// Tests ContainerEq with different container types, and
4143// different element types.
4144
4145template <typename T>
zhanyong.wanb8243162009-06-04 05:48:20 +00004146class ContainerEqTest : public testing::Test {};
zhanyong.wan6a896b52009-01-16 01:13:50 +00004147
4148typedef testing::Types<
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004149 set<int>,
4150 vector<size_t>,
4151 multiset<size_t>,
4152 list<int> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004153 ContainerEqTestTypes;
4154
4155TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
4156
4157// Tests that the filled container is equal to itself.
4158TYPED_TEST(ContainerEqTest, EqualsSelf) {
4159 static const int vals[] = {1, 1, 2, 3, 5, 8};
4160 TypeParam my_set(vals, vals + 6);
4161 const Matcher<TypeParam> m = ContainerEq(my_set);
4162 EXPECT_TRUE(m.Matches(my_set));
4163 EXPECT_EQ("", Explain(m, my_set));
4164}
4165
4166// Tests that missing values are reported.
4167TYPED_TEST(ContainerEqTest, ValueMissing) {
4168 static const int vals[] = {1, 1, 2, 3, 5, 8};
4169 static const int test_vals[] = {2, 1, 8, 5};
4170 TypeParam my_set(vals, vals + 6);
4171 TypeParam test_set(test_vals, test_vals + 4);
4172 const Matcher<TypeParam> m = ContainerEq(my_set);
4173 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004174 EXPECT_EQ("which doesn't have these expected elements: 3",
4175 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004176}
4177
4178// Tests that added values are reported.
4179TYPED_TEST(ContainerEqTest, ValueAdded) {
4180 static const int vals[] = {1, 1, 2, 3, 5, 8};
4181 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4182 TypeParam my_set(vals, vals + 6);
4183 TypeParam test_set(test_vals, test_vals + 6);
4184 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4185 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004186 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004187}
4188
4189// Tests that added and missing values are reported together.
4190TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4191 static const int vals[] = {1, 1, 2, 3, 5, 8};
4192 static const int test_vals[] = {1, 2, 3, 8, 46};
4193 TypeParam my_set(vals, vals + 6);
4194 TypeParam test_set(test_vals, test_vals + 5);
4195 const Matcher<TypeParam> m = ContainerEq(my_set);
4196 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004197 EXPECT_EQ("which has these unexpected elements: 46,\n"
4198 "and doesn't have these expected elements: 5",
4199 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004200}
4201
4202// Tests duplicated value -- expect no explanation.
4203TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4204 static const int vals[] = {1, 1, 2, 3, 5, 8};
4205 static const int test_vals[] = {1, 2, 3, 5, 8};
4206 TypeParam my_set(vals, vals + 6);
4207 TypeParam test_set(test_vals, test_vals + 5);
4208 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4209 // Depending on the container, match may be true or false
4210 // But in any case there should be no explanation.
4211 EXPECT_EQ("", Explain(m, test_set));
4212}
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004213#endif // GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004214
4215// Tests that mutliple missing values are reported.
4216// Using just vector here, so order is predicatble.
4217TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4218 static const int vals[] = {1, 1, 2, 3, 5, 8};
4219 static const int test_vals[] = {2, 1, 5};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004220 vector<int> my_set(vals, vals + 6);
4221 vector<int> test_set(test_vals, test_vals + 3);
4222 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004223 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004224 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4225 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004226}
4227
4228// Tests that added values are reported.
4229// Using just vector here, so order is predicatble.
4230TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4231 static const int vals[] = {1, 1, 2, 3, 5, 8};
4232 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004233 list<size_t> my_set(vals, vals + 6);
4234 list<size_t> test_set(test_vals, test_vals + 7);
4235 const Matcher<const list<size_t>&> m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004236 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004237 EXPECT_EQ("which has these unexpected elements: 92, 46",
4238 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004239}
4240
4241// Tests that added and missing values are reported together.
4242TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
4243 static const int vals[] = {1, 1, 2, 3, 5, 8};
4244 static const int test_vals[] = {1, 2, 3, 92, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004245 list<size_t> my_set(vals, vals + 6);
4246 list<size_t> test_set(test_vals, test_vals + 5);
4247 const Matcher<const list<size_t> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004248 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004249 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4250 "and doesn't have these expected elements: 5, 8",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004251 Explain(m, test_set));
4252}
4253
4254// Tests to see that duplicate elements are detected,
4255// but (as above) not reported in the explanation.
4256TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
4257 static const int vals[] = {1, 1, 2, 3, 5, 8};
4258 static const int test_vals[] = {1, 2, 3, 5, 8};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004259 vector<int> my_set(vals, vals + 6);
4260 vector<int> test_set(test_vals, test_vals + 5);
4261 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004262 EXPECT_TRUE(m.Matches(my_set));
4263 EXPECT_FALSE(m.Matches(test_set));
4264 // There is nothing to report when both sets contain all the same values.
4265 EXPECT_EQ("", Explain(m, test_set));
4266}
4267
4268// Tests that ContainerEq works for non-trivial associative containers,
4269// like maps.
4270TEST(ContainerEqExtraTest, WorksForMaps) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004271 map<int, std::string> my_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004272 my_map[0] = "a";
4273 my_map[1] = "b";
4274
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004275 map<int, std::string> test_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004276 test_map[0] = "aa";
4277 test_map[1] = "b";
4278
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004279 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004280 EXPECT_TRUE(m.Matches(my_map));
4281 EXPECT_FALSE(m.Matches(test_map));
4282
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004283 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
4284 "and doesn't have these expected elements: (0, \"a\")",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004285 Explain(m, test_map));
4286}
4287
zhanyong.wanb8243162009-06-04 05:48:20 +00004288TEST(ContainerEqExtraTest, WorksForNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00004289 int a1[] = {1, 2, 3};
4290 int a2[] = {1, 2, 3};
4291 int b[] = {1, 2, 4};
zhanyong.wanb8243162009-06-04 05:48:20 +00004292
4293 EXPECT_THAT(a1, ContainerEq(a2));
4294 EXPECT_THAT(a1, Not(ContainerEq(b)));
4295}
4296
4297TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00004298 const char a1[][3] = {"hi", "lo"};
4299 const char a2[][3] = {"hi", "lo"};
4300 const char b[][3] = {"lo", "hi"};
zhanyong.wanb8243162009-06-04 05:48:20 +00004301
4302 // Tests using ContainerEq() in the first dimension.
4303 EXPECT_THAT(a1, ContainerEq(a2));
4304 EXPECT_THAT(a1, Not(ContainerEq(b)));
4305
4306 // Tests using ContainerEq() in the second dimension.
4307 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
4308 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
4309}
4310
4311TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
kosak2336e9c2014-07-28 22:57:30 +00004312 const int a1[] = {1, 2, 3};
4313 const int a2[] = {1, 2, 3};
4314 const int b[] = {1, 2, 3, 4};
zhanyong.wanb8243162009-06-04 05:48:20 +00004315
zhanyong.wan2661c682009-06-09 05:42:12 +00004316 const int* const p1 = a1;
4317 EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
4318 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004319
kosak2336e9c2014-07-28 22:57:30 +00004320 const int c[] = {1, 3, 2};
zhanyong.wan2661c682009-06-09 05:42:12 +00004321 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004322}
4323
4324TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
4325 std::string a1[][3] = {
kosak2336e9c2014-07-28 22:57:30 +00004326 {"hi", "hello", "ciao"},
4327 {"bye", "see you", "ciao"}
zhanyong.wanb8243162009-06-04 05:48:20 +00004328 };
4329
4330 std::string a2[][3] = {
kosak2336e9c2014-07-28 22:57:30 +00004331 {"hi", "hello", "ciao"},
4332 {"bye", "see you", "ciao"}
zhanyong.wanb8243162009-06-04 05:48:20 +00004333 };
4334
4335 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
4336 EXPECT_THAT(a1, m);
4337
4338 a2[0][0] = "ha";
4339 EXPECT_THAT(a1, m);
4340}
4341
zhanyong.wan898725c2011-09-16 16:45:39 +00004342TEST(WhenSortedByTest, WorksForEmptyContainer) {
4343 const vector<int> numbers;
4344 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
4345 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
4346}
4347
4348TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
4349 vector<unsigned> numbers;
4350 numbers.push_back(3);
4351 numbers.push_back(1);
4352 numbers.push_back(2);
4353 numbers.push_back(2);
4354 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
4355 ElementsAre(3, 2, 2, 1)));
4356 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
4357 ElementsAre(1, 2, 2, 3))));
4358}
4359
4360TEST(WhenSortedByTest, WorksForNonVectorContainer) {
4361 list<string> words;
4362 words.push_back("say");
4363 words.push_back("hello");
4364 words.push_back("world");
4365 EXPECT_THAT(words, WhenSortedBy(less<string>(),
4366 ElementsAre("hello", "say", "world")));
4367 EXPECT_THAT(words, Not(WhenSortedBy(less<string>(),
4368 ElementsAre("say", "hello", "world"))));
4369}
4370
4371TEST(WhenSortedByTest, WorksForNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00004372 const int numbers[] = {1, 3, 2, 4};
4373 const int sorted_numbers[] = {1, 2, 3, 4};
zhanyong.wan898725c2011-09-16 16:45:39 +00004374 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
4375 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
4376 ElementsAreArray(sorted_numbers)));
4377 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
4378}
4379
4380TEST(WhenSortedByTest, CanDescribeSelf) {
4381 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
4382 EXPECT_EQ("(when sorted) has 2 elements where\n"
4383 "element #0 is equal to 1,\n"
4384 "element #1 is equal to 2",
4385 Describe(m));
4386 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
4387 "element #0 isn't equal to 1, or\n"
4388 "element #1 isn't equal to 2",
4389 DescribeNegation(m));
4390}
4391
4392TEST(WhenSortedByTest, ExplainsMatchResult) {
kosak2336e9c2014-07-28 22:57:30 +00004393 const int a[] = {2, 1};
zhanyong.wan898725c2011-09-16 16:45:39 +00004394 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
4395 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
4396 EXPECT_EQ("which is { 1, 2 } when sorted",
4397 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
4398}
4399
4400// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
4401// need to test it as exhaustively as we test the latter.
4402
4403TEST(WhenSortedTest, WorksForEmptyContainer) {
4404 const vector<int> numbers;
4405 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
4406 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
4407}
4408
4409TEST(WhenSortedTest, WorksForNonEmptyContainer) {
4410 list<string> words;
4411 words.push_back("3");
4412 words.push_back("1");
4413 words.push_back("2");
4414 words.push_back("2");
4415 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
4416 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
4417}
4418
zhanyong.wana9a59e02013-03-27 16:14:55 +00004419TEST(WhenSortedTest, WorksForMapTypes) {
4420 map<string, int> word_counts;
4421 word_counts["and"] = 1;
4422 word_counts["the"] = 1;
4423 word_counts["buffalo"] = 2;
4424 EXPECT_THAT(word_counts, WhenSorted(ElementsAre(
4425 Pair("and", 1), Pair("buffalo", 2), Pair("the", 1))));
4426 EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre(
4427 Pair("and", 1), Pair("the", 1), Pair("buffalo", 2)))));
4428}
4429
4430TEST(WhenSortedTest, WorksForMultiMapTypes) {
4431 multimap<int, int> ifib;
4432 ifib.insert(make_pair(8, 6));
4433 ifib.insert(make_pair(2, 3));
4434 ifib.insert(make_pair(1, 1));
4435 ifib.insert(make_pair(3, 4));
4436 ifib.insert(make_pair(1, 2));
4437 ifib.insert(make_pair(5, 5));
4438 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
4439 Pair(1, 2),
4440 Pair(2, 3),
4441 Pair(3, 4),
4442 Pair(5, 5),
4443 Pair(8, 6))));
4444 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
4445 Pair(2, 3),
4446 Pair(1, 1),
4447 Pair(3, 4),
4448 Pair(1, 2),
4449 Pair(5, 5)))));
4450}
4451
4452TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
4453 std::deque<int> d;
4454 d.push_back(2);
4455 d.push_back(1);
4456 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
4457 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
4458}
4459
4460TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
4461 std::deque<int> d;
4462 d.push_back(2);
4463 d.push_back(1);
4464 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
4465 EXPECT_THAT(d, WhenSorted(vector_match));
4466 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
4467 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
4468}
4469
4470// Deliberately bare pseudo-container.
4471// Offers only begin() and end() accessors, yielding InputIterator.
4472template <typename T>
4473class Streamlike {
4474 private:
4475 class ConstIter;
4476 public:
4477 typedef ConstIter const_iterator;
4478 typedef T value_type;
4479
4480 template <typename InIter>
4481 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
4482
4483 const_iterator begin() const {
4484 return const_iterator(this, remainder_.begin());
4485 }
4486 const_iterator end() const {
4487 return const_iterator(this, remainder_.end());
4488 }
4489
4490 private:
4491 class ConstIter : public std::iterator<std::input_iterator_tag,
4492 value_type,
4493 ptrdiff_t,
kosakcd99eb02014-11-17 02:18:28 +00004494 const value_type*,
4495 const value_type&> {
zhanyong.wana9a59e02013-03-27 16:14:55 +00004496 public:
4497 ConstIter(const Streamlike* s,
4498 typename std::list<value_type>::iterator pos)
4499 : s_(s), pos_(pos) {}
4500
4501 const value_type& operator*() const { return *pos_; }
4502 const value_type* operator->() const { return &*pos_; }
4503 ConstIter& operator++() {
4504 s_->remainder_.erase(pos_++);
4505 return *this;
4506 }
4507
4508 // *iter++ is required to work (see std::istreambuf_iterator).
4509 // (void)iter++ is also required to work.
4510 class PostIncrProxy {
4511 public:
4512 explicit PostIncrProxy(const value_type& value) : value_(value) {}
4513 value_type operator*() const { return value_; }
4514 private:
4515 value_type value_;
4516 };
4517 PostIncrProxy operator++(int) {
4518 PostIncrProxy proxy(**this);
4519 ++(*this);
4520 return proxy;
4521 }
4522
4523 friend bool operator==(const ConstIter& a, const ConstIter& b) {
4524 return a.s_ == b.s_ && a.pos_ == b.pos_;
4525 }
4526 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
4527 return !(a == b);
4528 }
4529
4530 private:
4531 const Streamlike* s_;
4532 typename std::list<value_type>::iterator pos_;
4533 };
4534
4535 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
4536 os << "[";
4537 typedef typename std::list<value_type>::const_iterator Iter;
4538 const char* sep = "";
4539 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
4540 os << sep << *it;
4541 sep = ",";
4542 }
4543 os << "]";
4544 return os;
4545 }
4546
4547 mutable std::list<value_type> remainder_; // modified by iteration
4548};
4549
4550TEST(StreamlikeTest, Iteration) {
kosak2336e9c2014-07-28 22:57:30 +00004551 const int a[5] = {2, 1, 4, 5, 3};
zhanyong.wana9a59e02013-03-27 16:14:55 +00004552 Streamlike<int> s(a, a + 5);
4553 Streamlike<int>::const_iterator it = s.begin();
4554 const int* ip = a;
4555 while (it != s.end()) {
4556 SCOPED_TRACE(ip - a);
4557 EXPECT_EQ(*ip++, *it++);
4558 }
4559}
4560
kosak5b9cbbb2014-11-17 00:28:55 +00004561#if GTEST_HAS_STD_FORWARD_LIST_
kosakb6a34882014-03-12 21:06:46 +00004562TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
4563 std::forward_list<int> container;
4564 EXPECT_THAT(container, BeginEndDistanceIs(0));
4565 EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
4566 container.push_front(0);
4567 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4568 EXPECT_THAT(container, BeginEndDistanceIs(1));
4569 container.push_front(0);
4570 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4571 EXPECT_THAT(container, BeginEndDistanceIs(2));
4572}
kosak5b9cbbb2014-11-17 00:28:55 +00004573#endif // GTEST_HAS_STD_FORWARD_LIST_
kosakb6a34882014-03-12 21:06:46 +00004574
4575TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
kosak2336e9c2014-07-28 22:57:30 +00004576 const int a[5] = {1, 2, 3, 4, 5};
kosakb6a34882014-03-12 21:06:46 +00004577 Streamlike<int> s(a, a + 5);
4578 EXPECT_THAT(s, BeginEndDistanceIs(5));
4579}
4580
4581TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
4582 Matcher<vector<int> > m = BeginEndDistanceIs(2);
4583 EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
4584 EXPECT_EQ("distance between begin() and end() isn't equal to 2",
4585 DescribeNegation(m));
4586}
4587
4588TEST(BeginEndDistanceIsTest, ExplainsResult) {
4589 Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
4590 Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
4591 Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
4592 Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
4593 vector<int> container;
4594 EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
4595 Explain(m1, container));
4596 EXPECT_EQ("whose distance between begin() and end() 0 matches",
4597 Explain(m2, container));
4598 EXPECT_EQ("whose distance between begin() and end() 0 matches",
4599 Explain(m3, container));
4600 EXPECT_EQ(
4601 "whose distance between begin() and end() 0 doesn't match, which is 1 "
4602 "less than 1",
4603 Explain(m4, container));
4604 container.push_back(0);
4605 container.push_back(0);
4606 EXPECT_EQ("whose distance between begin() and end() 2 matches",
4607 Explain(m1, container));
4608 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4609 Explain(m2, container));
4610 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4611 Explain(m3, container));
4612 EXPECT_EQ(
4613 "whose distance between begin() and end() 2 matches, which is 1 more "
4614 "than 1",
4615 Explain(m4, container));
4616}
4617
zhanyong.wana9a59e02013-03-27 16:14:55 +00004618TEST(WhenSortedTest, WorksForStreamlike) {
4619 // Streamlike 'container' provides only minimal iterator support.
4620 // Its iterators are tagged with input_iterator_tag.
kosak2336e9c2014-07-28 22:57:30 +00004621 const int a[5] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00004622 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004623 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
4624 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4625}
4626
4627TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
kosak2336e9c2014-07-28 22:57:30 +00004628 const int a[] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00004629 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004630 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
4631 EXPECT_THAT(s, WhenSorted(vector_match));
4632 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4633}
4634
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004635// Tests using ElementsAre() and ElementsAreArray() with stream-like
4636// "containers".
4637
4638TEST(ElemensAreStreamTest, WorksForStreamlike) {
kosak2336e9c2014-07-28 22:57:30 +00004639 const int a[5] = {1, 2, 3, 4, 5};
kosak6414d802013-12-03 23:19:36 +00004640 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004641 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
4642 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
4643}
4644
4645TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
kosak2336e9c2014-07-28 22:57:30 +00004646 const int a[5] = {1, 2, 3, 4, 5};
kosak6414d802013-12-03 23:19:36 +00004647 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004648
4649 vector<int> expected;
4650 expected.push_back(1);
4651 expected.push_back(2);
4652 expected.push_back(3);
4653 expected.push_back(4);
4654 expected.push_back(5);
4655 EXPECT_THAT(s, ElementsAreArray(expected));
4656
4657 expected[3] = 0;
4658 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
4659}
4660
billydonahue1f5fdea2014-05-19 17:54:51 +00004661TEST(ElementsAreTest, WorksWithUncopyable) {
4662 Uncopyable objs[2];
4663 objs[0].set_value(-3);
4664 objs[1].set_value(1);
4665 EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
4666}
4667
kosak06678922014-07-28 20:01:28 +00004668TEST(ElementsAreTest, TakesStlContainer) {
4669 const int actual[] = {3, 1, 2};
4670
4671 ::std::list<int> expected;
4672 expected.push_back(3);
4673 expected.push_back(1);
4674 expected.push_back(2);
4675 EXPECT_THAT(actual, ElementsAreArray(expected));
4676
4677 expected.push_back(4);
4678 EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
4679}
4680
zhanyong.wanfb25d532013-07-28 08:24:00 +00004681// Tests for UnorderedElementsAreArray()
4682
4683TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
kosak2336e9c2014-07-28 22:57:30 +00004684 const int a[] = {0, 1, 2, 3, 4};
kosak6414d802013-12-03 23:19:36 +00004685 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004686 do {
4687 StringMatchResultListener listener;
4688 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
4689 s, &listener)) << listener.str();
4690 } while (std::next_permutation(s.begin(), s.end()));
4691}
4692
4693TEST(UnorderedElementsAreArrayTest, VectorBool) {
kosak2336e9c2014-07-28 22:57:30 +00004694 const bool a[] = {0, 1, 0, 1, 1};
4695 const bool b[] = {1, 0, 1, 1, 0};
kosak6414d802013-12-03 23:19:36 +00004696 std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a));
4697 std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004698 StringMatchResultListener listener;
4699 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
4700 actual, &listener)) << listener.str();
4701}
4702
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004703TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
4704 // Streamlike 'container' provides only minimal iterator support.
4705 // Its iterators are tagged with input_iterator_tag, and it has no
4706 // size() or empty() methods.
kosak2336e9c2014-07-28 22:57:30 +00004707 const int a[5] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00004708 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004709
4710 ::std::vector<int> expected;
4711 expected.push_back(1);
4712 expected.push_back(2);
4713 expected.push_back(3);
4714 expected.push_back(4);
4715 expected.push_back(5);
4716 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
4717
4718 expected.push_back(6);
4719 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
4720}
4721
kosak06678922014-07-28 20:01:28 +00004722TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
4723 const int actual[] = {3, 1, 2};
4724
4725 ::std::list<int> expected;
4726 expected.push_back(1);
4727 expected.push_back(2);
4728 expected.push_back(3);
4729 EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
4730
4731 expected.push_back(4);
4732 EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
4733}
4734
kosak18489fa2013-12-04 23:49:07 +00004735#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004736
4737TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
kosak2336e9c2014-07-28 22:57:30 +00004738 const int a[5] = {2, 1, 4, 5, 3};
4739 EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
4740 EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004741}
4742
4743TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
kosak2336e9c2014-07-28 22:57:30 +00004744 const string a[5] = {"a", "b", "c", "d", "e"};
4745 EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
4746 EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004747}
4748
4749TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
kosak2336e9c2014-07-28 22:57:30 +00004750 const int a[5] = {2, 1, 4, 5, 3};
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004751 EXPECT_THAT(a, UnorderedElementsAreArray(
kosak2336e9c2014-07-28 22:57:30 +00004752 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004753 EXPECT_THAT(a, Not(UnorderedElementsAreArray(
kosak2336e9c2014-07-28 22:57:30 +00004754 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004755}
4756
4757TEST(UnorderedElementsAreArrayTest,
4758 TakesInitializerListOfDifferentTypedMatchers) {
kosak2336e9c2014-07-28 22:57:30 +00004759 const int a[5] = {2, 1, 4, 5, 3};
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004760 // The compiler cannot infer the type of the initializer list if its
4761 // elements have different types. We must explicitly specify the
4762 // unified element type in this case.
4763 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
kosak2336e9c2014-07-28 22:57:30 +00004764 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004765 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
kosak2336e9c2014-07-28 22:57:30 +00004766 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004767}
4768
kosak18489fa2013-12-04 23:49:07 +00004769#endif // GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004770
zhanyong.wanfb25d532013-07-28 08:24:00 +00004771class UnorderedElementsAreTest : public testing::Test {
4772 protected:
4773 typedef std::vector<int> IntVec;
4774};
4775
billydonahue1f5fdea2014-05-19 17:54:51 +00004776TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
4777 Uncopyable objs[2];
4778 objs[0].set_value(-3);
4779 objs[1].set_value(1);
4780 EXPECT_THAT(objs,
4781 UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
4782}
4783
zhanyong.wanfb25d532013-07-28 08:24:00 +00004784TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
kosak2336e9c2014-07-28 22:57:30 +00004785 const int a[] = {1, 2, 3};
kosak6414d802013-12-03 23:19:36 +00004786 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004787 do {
4788 StringMatchResultListener listener;
4789 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4790 s, &listener)) << listener.str();
4791 } while (std::next_permutation(s.begin(), s.end()));
4792}
4793
4794TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
kosak2336e9c2014-07-28 22:57:30 +00004795 const int a[] = {1, 2, 3};
kosak6414d802013-12-03 23:19:36 +00004796 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004797 std::vector<Matcher<int> > mv;
4798 mv.push_back(1);
4799 mv.push_back(2);
4800 mv.push_back(2);
4801 // The element with value '3' matches nothing: fail fast.
4802 StringMatchResultListener listener;
4803 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4804 s, &listener)) << listener.str();
4805}
4806
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004807TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
4808 // Streamlike 'container' provides only minimal iterator support.
4809 // Its iterators are tagged with input_iterator_tag, and it has no
4810 // size() or empty() methods.
kosak2336e9c2014-07-28 22:57:30 +00004811 const int a[5] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00004812 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004813
4814 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
4815 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
4816}
4817
zhanyong.wanfb25d532013-07-28 08:24:00 +00004818// One naive implementation of the matcher runs in O(N!) time, which is too
4819// slow for many real-world inputs. This test shows that our matcher can match
4820// 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
4821// iterations and obviously effectively incomputable.
4822// [ RUN ] UnorderedElementsAreTest.Performance
4823// [ OK ] UnorderedElementsAreTest.Performance (4 ms)
4824TEST_F(UnorderedElementsAreTest, Performance) {
4825 std::vector<int> s;
4826 std::vector<Matcher<int> > mv;
4827 for (int i = 0; i < 100; ++i) {
4828 s.push_back(i);
4829 mv.push_back(_);
4830 }
4831 mv[50] = Eq(0);
4832 StringMatchResultListener listener;
4833 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4834 s, &listener)) << listener.str();
4835}
4836
4837// Another variant of 'Performance' with similar expectations.
4838// [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
4839// [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
4840TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
4841 std::vector<int> s;
4842 std::vector<Matcher<int> > mv;
4843 for (int i = 0; i < 100; ++i) {
4844 s.push_back(i);
4845 if (i & 1) {
4846 mv.push_back(_);
4847 } else {
4848 mv.push_back(i);
4849 }
4850 }
4851 StringMatchResultListener listener;
4852 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4853 s, &listener)) << listener.str();
4854}
4855
4856TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
4857 std::vector<int> v;
4858 v.push_back(4);
4859 StringMatchResultListener listener;
4860 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4861 v, &listener)) << listener.str();
4862 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
4863}
4864
4865TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
4866 std::vector<int> v;
4867 StringMatchResultListener listener;
4868 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4869 v, &listener)) << listener.str();
4870 EXPECT_THAT(listener.str(), Eq(""));
4871}
4872
4873TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
4874 std::vector<int> v;
4875 v.push_back(1);
4876 v.push_back(1);
4877 StringMatchResultListener listener;
4878 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4879 v, &listener)) << listener.str();
4880 EXPECT_THAT(
4881 listener.str(),
4882 Eq("where the following matchers don't match any elements:\n"
4883 "matcher #1: is equal to 2"));
4884}
4885
4886TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
4887 std::vector<int> v;
4888 v.push_back(1);
4889 v.push_back(2);
4890 StringMatchResultListener listener;
4891 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
4892 v, &listener)) << listener.str();
4893 EXPECT_THAT(
4894 listener.str(),
4895 Eq("where the following elements don't match any matchers:\n"
4896 "element #1: 2"));
4897}
4898
4899TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
4900 std::vector<int> v;
4901 v.push_back(2);
4902 v.push_back(3);
4903 StringMatchResultListener listener;
4904 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4905 v, &listener)) << listener.str();
4906 EXPECT_THAT(
4907 listener.str(),
4908 Eq("where"
4909 " the following matchers don't match any elements:\n"
4910 "matcher #0: is equal to 1\n"
4911 "and"
4912 " where"
4913 " the following elements don't match any matchers:\n"
4914 "element #1: 3"));
4915}
4916
4917// Test helper for formatting element, matcher index pairs in expectations.
4918static string EMString(int element, int matcher) {
4919 stringstream ss;
4920 ss << "(element #" << element << ", matcher #" << matcher << ")";
4921 return ss.str();
4922}
4923
4924TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
4925 // A situation where all elements and matchers have a match
4926 // associated with them, but the max matching is not perfect.
4927 std::vector<string> v;
4928 v.push_back("a");
4929 v.push_back("b");
4930 v.push_back("c");
4931 StringMatchResultListener listener;
4932 EXPECT_FALSE(ExplainMatchResult(
4933 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
4934 << listener.str();
4935
4936 string prefix =
4937 "where no permutation of the elements can satisfy all matchers, "
4938 "and the closest match is 2 of 3 matchers with the "
4939 "pairings:\n";
4940
4941 // We have to be a bit loose here, because there are 4 valid max matches.
4942 EXPECT_THAT(
4943 listener.str(),
4944 AnyOf(prefix + "{\n " + EMString(0, 0) +
4945 ",\n " + EMString(1, 2) + "\n}",
4946 prefix + "{\n " + EMString(0, 1) +
4947 ",\n " + EMString(1, 2) + "\n}",
4948 prefix + "{\n " + EMString(0, 0) +
4949 ",\n " + EMString(2, 2) + "\n}",
4950 prefix + "{\n " + EMString(0, 1) +
4951 ",\n " + EMString(2, 2) + "\n}"));
4952}
4953
4954TEST_F(UnorderedElementsAreTest, Describe) {
4955 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
4956 Eq("is empty"));
4957 EXPECT_THAT(
4958 Describe<IntVec>(UnorderedElementsAre(345)),
4959 Eq("has 1 element and that element is equal to 345"));
4960 EXPECT_THAT(
4961 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
4962 Eq("has 3 elements and there exists some permutation "
4963 "of elements such that:\n"
4964 " - element #0 is equal to 111, and\n"
4965 " - element #1 is equal to 222, and\n"
4966 " - element #2 is equal to 333"));
4967}
4968
4969TEST_F(UnorderedElementsAreTest, DescribeNegation) {
4970 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
4971 Eq("isn't empty"));
4972 EXPECT_THAT(
4973 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
4974 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
4975 EXPECT_THAT(
4976 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
4977 Eq("doesn't have 3 elements, or there exists no permutation "
4978 "of elements such that:\n"
4979 " - element #0 is equal to 123, and\n"
4980 " - element #1 is equal to 234, and\n"
4981 " - element #2 is equal to 345"));
4982}
4983
4984namespace {
4985
4986// Used as a check on the more complex max flow method used in the
4987// real testing::internal::FindMaxBipartiteMatching. This method is
4988// compatible but runs in worst-case factorial time, so we only
4989// use it in testing for small problem sizes.
4990template <typename Graph>
4991class BacktrackingMaxBPMState {
4992 public:
4993 // Does not take ownership of 'g'.
4994 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
4995
4996 ElementMatcherPairs Compute() {
4997 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
4998 return best_so_far_;
4999 }
5000 lhs_used_.assign(graph_->LhsSize(), kUnused);
5001 rhs_used_.assign(graph_->RhsSize(), kUnused);
5002 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
5003 matches_.clear();
5004 RecurseInto(irhs);
5005 if (best_so_far_.size() == graph_->RhsSize())
5006 break;
5007 }
5008 return best_so_far_;
5009 }
5010
5011 private:
5012 static const size_t kUnused = static_cast<size_t>(-1);
5013
5014 void PushMatch(size_t lhs, size_t rhs) {
5015 matches_.push_back(ElementMatcherPair(lhs, rhs));
5016 lhs_used_[lhs] = rhs;
5017 rhs_used_[rhs] = lhs;
5018 if (matches_.size() > best_so_far_.size()) {
5019 best_so_far_ = matches_;
5020 }
5021 }
5022
5023 void PopMatch() {
5024 const ElementMatcherPair& back = matches_.back();
5025 lhs_used_[back.first] = kUnused;
5026 rhs_used_[back.second] = kUnused;
5027 matches_.pop_back();
5028 }
5029
5030 bool RecurseInto(size_t irhs) {
5031 if (rhs_used_[irhs] != kUnused) {
5032 return true;
5033 }
5034 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
5035 if (lhs_used_[ilhs] != kUnused) {
5036 continue;
5037 }
5038 if (!graph_->HasEdge(ilhs, irhs)) {
5039 continue;
5040 }
5041 PushMatch(ilhs, irhs);
5042 if (best_so_far_.size() == graph_->RhsSize()) {
5043 return false;
5044 }
5045 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
5046 if (!RecurseInto(mi)) return false;
5047 }
5048 PopMatch();
5049 }
5050 return true;
5051 }
5052
5053 const Graph* graph_; // not owned
5054 std::vector<size_t> lhs_used_;
5055 std::vector<size_t> rhs_used_;
5056 ElementMatcherPairs matches_;
5057 ElementMatcherPairs best_so_far_;
5058};
5059
5060template <typename Graph>
5061const size_t BacktrackingMaxBPMState<Graph>::kUnused;
5062
5063} // namespace
5064
5065// Implement a simple backtracking algorithm to determine if it is possible
5066// to find one element per matcher, without reusing elements.
5067template <typename Graph>
5068ElementMatcherPairs
5069FindBacktrackingMaxBPM(const Graph& g) {
5070 return BacktrackingMaxBPMState<Graph>(&g).Compute();
5071}
5072
5073class BacktrackingBPMTest : public ::testing::Test { };
5074
5075// Tests the MaxBipartiteMatching algorithm with square matrices.
5076// The single int param is the # of nodes on each of the left and right sides.
5077class BipartiteTest : public ::testing::TestWithParam<int> { };
5078
5079// Verify all match graphs up to some moderate number of edges.
5080TEST_P(BipartiteTest, Exhaustive) {
5081 int nodes = GetParam();
5082 MatchMatrix graph(nodes, nodes);
5083 do {
5084 ElementMatcherPairs matches =
5085 internal::FindMaxBipartiteMatching(graph);
5086 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
5087 << "graph: " << graph.DebugString();
5088 // Check that all elements of matches are in the graph.
5089 // Check that elements of first and second are unique.
5090 std::vector<bool> seen_element(graph.LhsSize());
5091 std::vector<bool> seen_matcher(graph.RhsSize());
5092 SCOPED_TRACE(PrintToString(matches));
5093 for (size_t i = 0; i < matches.size(); ++i) {
5094 size_t ilhs = matches[i].first;
5095 size_t irhs = matches[i].second;
5096 EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
5097 EXPECT_FALSE(seen_element[ilhs]);
5098 EXPECT_FALSE(seen_matcher[irhs]);
5099 seen_element[ilhs] = true;
5100 seen_matcher[irhs] = true;
5101 }
5102 } while (graph.NextGraph());
5103}
5104
5105INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest,
5106 ::testing::Range(0, 5));
5107
5108// Parameterized by a pair interpreted as (LhsSize, RhsSize).
5109class BipartiteNonSquareTest
5110 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
5111};
5112
5113TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
5114 // .......
5115 // 0:-----\ :
5116 // 1:---\ | :
5117 // 2:---\ | :
5118 // 3:-\ | | :
5119 // :.......:
5120 // 0 1 2
5121 MatchMatrix g(4, 3);
kosak2336e9c2014-07-28 22:57:30 +00005122 static const int kEdges[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}};
kosak6414d802013-12-03 23:19:36 +00005123 for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00005124 g.SetEdge(kEdges[i][0], kEdges[i][1], true);
5125 }
5126 EXPECT_THAT(FindBacktrackingMaxBPM(g),
5127 ElementsAre(Pair(3, 0),
5128 Pair(AnyOf(1, 2), 1),
5129 Pair(0, 2))) << g.DebugString();
5130}
5131
5132// Verify a few nonsquare matrices.
5133TEST_P(BipartiteNonSquareTest, Exhaustive) {
5134 size_t nlhs = GetParam().first;
5135 size_t nrhs = GetParam().second;
5136 MatchMatrix graph(nlhs, nrhs);
5137 do {
5138 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5139 internal::FindMaxBipartiteMatching(graph).size())
5140 << "graph: " << graph.DebugString()
5141 << "\nbacktracking: "
5142 << PrintToString(FindBacktrackingMaxBPM(graph))
5143 << "\nmax flow: "
5144 << PrintToString(internal::FindMaxBipartiteMatching(graph));
5145 } while (graph.NextGraph());
5146}
5147
5148INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest,
5149 testing::Values(
5150 std::make_pair(1, 2),
5151 std::make_pair(2, 1),
5152 std::make_pair(3, 2),
5153 std::make_pair(2, 3),
5154 std::make_pair(4, 1),
5155 std::make_pair(1, 4),
5156 std::make_pair(4, 3),
5157 std::make_pair(3, 4)));
5158
5159class BipartiteRandomTest
5160 : public ::testing::TestWithParam<std::pair<int, int> > {
5161};
5162
5163// Verifies a large sample of larger graphs.
5164TEST_P(BipartiteRandomTest, LargerNets) {
5165 int nodes = GetParam().first;
5166 int iters = GetParam().second;
5167 MatchMatrix graph(nodes, nodes);
5168
5169 testing::internal::Int32 seed = GTEST_FLAG(random_seed);
5170 if (seed == 0) {
5171 seed = static_cast<testing::internal::Int32>(time(NULL));
5172 }
5173
5174 for (; iters > 0; --iters, ++seed) {
5175 srand(static_cast<int>(seed));
5176 graph.Randomize();
5177 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5178 internal::FindMaxBipartiteMatching(graph).size())
5179 << " graph: " << graph.DebugString()
5180 << "\nTo reproduce the failure, rerun the test with the flag"
5181 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
5182 }
5183}
5184
5185// Test argument is a std::pair<int, int> representing (nodes, iters).
5186INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest,
5187 testing::Values(
5188 std::make_pair(5, 10000),
5189 std::make_pair(6, 5000),
5190 std::make_pair(7, 2000),
5191 std::make_pair(8, 500),
5192 std::make_pair(9, 100)));
5193
zhanyong.wan736baa82010-09-27 17:44:16 +00005194// Tests IsReadableTypeName().
5195
5196TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
5197 EXPECT_TRUE(IsReadableTypeName("int"));
5198 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
5199 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
5200 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
5201}
5202
5203TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
5204 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
5205 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
5206 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
5207}
5208
5209TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
5210 EXPECT_FALSE(
5211 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
5212 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
5213}
5214
5215TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
5216 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
5217}
5218
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005219// Tests JoinAsTuple().
5220
5221TEST(JoinAsTupleTest, JoinsEmptyTuple) {
5222 EXPECT_EQ("", JoinAsTuple(Strings()));
5223}
5224
5225TEST(JoinAsTupleTest, JoinsOneTuple) {
kosak2336e9c2014-07-28 22:57:30 +00005226 const char* fields[] = {"1"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005227 EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
5228}
5229
5230TEST(JoinAsTupleTest, JoinsTwoTuple) {
kosak2336e9c2014-07-28 22:57:30 +00005231 const char* fields[] = {"1", "a"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005232 EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
5233}
5234
5235TEST(JoinAsTupleTest, JoinsTenTuple) {
kosak2336e9c2014-07-28 22:57:30 +00005236 const char* fields[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005237 EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
5238 JoinAsTuple(Strings(fields, fields + 10)));
5239}
5240
5241// Tests FormatMatcherDescription().
5242
5243TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
5244 EXPECT_EQ("is even",
zhanyong.wanb4140802010-06-08 22:53:57 +00005245 FormatMatcherDescription(false, "IsEven", Strings()));
5246 EXPECT_EQ("not (is even)",
5247 FormatMatcherDescription(true, "IsEven", Strings()));
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005248
kosak2336e9c2014-07-28 22:57:30 +00005249 const char* params[] = {"5"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005250 EXPECT_EQ("equals 5",
zhanyong.wanb4140802010-06-08 22:53:57 +00005251 FormatMatcherDescription(false, "Equals",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005252 Strings(params, params + 1)));
5253
kosak2336e9c2014-07-28 22:57:30 +00005254 const char* params2[] = {"5", "8"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005255 EXPECT_EQ("is in range (5, 8)",
zhanyong.wanb4140802010-06-08 22:53:57 +00005256 FormatMatcherDescription(false, "IsInRange",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005257 Strings(params2, params2 + 2)));
5258}
5259
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00005260// Tests PolymorphicMatcher::mutable_impl().
5261TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
5262 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5263 DivisibleByImpl& impl = m.mutable_impl();
5264 EXPECT_EQ(42, impl.divider());
5265
5266 impl.set_divider(0);
5267 EXPECT_EQ(0, m.mutable_impl().divider());
5268}
5269
5270// Tests PolymorphicMatcher::impl().
5271TEST(PolymorphicMatcherTest, CanAccessImpl) {
5272 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5273 const DivisibleByImpl& impl = m.impl();
5274 EXPECT_EQ(42, impl.divider());
5275}
5276
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005277TEST(MatcherTupleTest, ExplainsMatchFailure) {
5278 stringstream ss1;
5279 ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
5280 make_tuple('a', 10), &ss1);
5281 EXPECT_EQ("", ss1.str()); // Successful match.
5282
5283 stringstream ss2;
5284 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5285 make_tuple(2, 'b'), &ss2);
5286 EXPECT_EQ(" Expected arg #0: is > 5\n"
5287 " Actual: 2, which is 3 less than 5\n"
zhanyong.wand60c5f42010-07-21 22:21:07 +00005288 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
5289 " Actual: 'b' (98, 0x62)\n",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005290 ss2.str()); // Failed match where both arguments need explanation.
5291
5292 stringstream ss3;
5293 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5294 make_tuple(2, 'a'), &ss3);
5295 EXPECT_EQ(" Expected arg #0: is > 5\n"
5296 " Actual: 2, which is 3 less than 5\n",
5297 ss3.str()); // Failed match where only one argument needs
5298 // explanation.
5299}
5300
zhanyong.wan33605ba2010-04-22 23:37:47 +00005301// Tests Each().
5302
5303TEST(EachTest, ExplainsMatchResultCorrectly) {
5304 set<int> a; // empty
5305
5306 Matcher<set<int> > m = Each(2);
5307 EXPECT_EQ("", Explain(m, a));
5308
zhanyong.wan736baa82010-09-27 17:44:16 +00005309 Matcher<const int(&)[1]> n = Each(1); // NOLINT
zhanyong.wan33605ba2010-04-22 23:37:47 +00005310
kosak2336e9c2014-07-28 22:57:30 +00005311 const int b[1] = {1};
zhanyong.wan33605ba2010-04-22 23:37:47 +00005312 EXPECT_EQ("", Explain(n, b));
5313
5314 n = Each(3);
5315 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
5316
5317 a.insert(1);
5318 a.insert(2);
5319 a.insert(3);
5320 m = Each(GreaterThan(0));
5321 EXPECT_EQ("", Explain(m, a));
5322
5323 m = Each(GreaterThan(10));
5324 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
5325 Explain(m, a));
5326}
5327
5328TEST(EachTest, DescribesItselfCorrectly) {
5329 Matcher<vector<int> > m = Each(1);
5330 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
5331
5332 Matcher<vector<int> > m2 = Not(m);
5333 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
5334}
5335
5336TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
5337 vector<int> some_vector;
5338 EXPECT_THAT(some_vector, Each(1));
5339 some_vector.push_back(3);
5340 EXPECT_THAT(some_vector, Not(Each(1)));
5341 EXPECT_THAT(some_vector, Each(3));
5342 some_vector.push_back(1);
5343 some_vector.push_back(2);
5344 EXPECT_THAT(some_vector, Not(Each(3)));
5345 EXPECT_THAT(some_vector, Each(Lt(3.5)));
5346
5347 vector<string> another_vector;
5348 another_vector.push_back("fee");
5349 EXPECT_THAT(another_vector, Each(string("fee")));
5350 another_vector.push_back("fie");
5351 another_vector.push_back("foe");
5352 another_vector.push_back("fum");
5353 EXPECT_THAT(another_vector, Not(Each(string("fee"))));
5354}
5355
5356TEST(EachTest, MatchesMapWhenAllElementsMatch) {
5357 map<const char*, int> my_map;
5358 const char* bar = "a string";
5359 my_map[bar] = 2;
5360 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
5361
5362 map<string, int> another_map;
5363 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5364 another_map["fee"] = 1;
5365 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5366 another_map["fie"] = 2;
5367 another_map["foe"] = 3;
5368 another_map["fum"] = 4;
5369 EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1))));
5370 EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1))));
5371 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
5372}
5373
5374TEST(EachTest, AcceptsMatcher) {
kosak2336e9c2014-07-28 22:57:30 +00005375 const int a[] = {1, 2, 3};
zhanyong.wan33605ba2010-04-22 23:37:47 +00005376 EXPECT_THAT(a, Each(Gt(0)));
5377 EXPECT_THAT(a, Not(Each(Gt(1))));
5378}
5379
5380TEST(EachTest, WorksForNativeArrayAsTuple) {
kosak2336e9c2014-07-28 22:57:30 +00005381 const int a[] = {1, 2};
zhanyong.wan33605ba2010-04-22 23:37:47 +00005382 const int* const pointer = a;
5383 EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
5384 EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
5385}
5386
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005387// For testing Pointwise().
5388class IsHalfOfMatcher {
5389 public:
5390 template <typename T1, typename T2>
5391 bool MatchAndExplain(const tuple<T1, T2>& a_pair,
5392 MatchResultListener* listener) const {
5393 if (get<0>(a_pair) == get<1>(a_pair)/2) {
5394 *listener << "where the second is " << get<1>(a_pair);
5395 return true;
5396 } else {
5397 *listener << "where the second/2 is " << get<1>(a_pair)/2;
5398 return false;
5399 }
5400 }
5401
5402 void DescribeTo(ostream* os) const {
5403 *os << "are a pair where the first is half of the second";
5404 }
5405
5406 void DescribeNegationTo(ostream* os) const {
5407 *os << "are a pair where the first isn't half of the second";
5408 }
5409};
5410
5411PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
5412 return MakePolymorphicMatcher(IsHalfOfMatcher());
5413}
5414
5415TEST(PointwiseTest, DescribesSelf) {
5416 vector<int> rhs;
5417 rhs.push_back(1);
5418 rhs.push_back(2);
5419 rhs.push_back(3);
5420 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
5421 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
5422 "in { 1, 2, 3 } are a pair where the first is half of the second",
5423 Describe(m));
5424 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
5425 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
5426 "where the first isn't half of the second",
5427 DescribeNegation(m));
5428}
5429
5430TEST(PointwiseTest, MakesCopyOfRhs) {
5431 list<signed char> rhs;
5432 rhs.push_back(2);
5433 rhs.push_back(4);
5434
kosak2336e9c2014-07-28 22:57:30 +00005435 int lhs[] = {1, 2};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005436 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
5437 EXPECT_THAT(lhs, m);
5438
5439 // Changing rhs now shouldn't affect m, which made a copy of rhs.
5440 rhs.push_back(6);
5441 EXPECT_THAT(lhs, m);
5442}
5443
5444TEST(PointwiseTest, WorksForLhsNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00005445 const int lhs[] = {1, 2, 3};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005446 vector<int> rhs;
5447 rhs.push_back(2);
5448 rhs.push_back(4);
5449 rhs.push_back(6);
5450 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
5451 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5452}
5453
5454TEST(PointwiseTest, WorksForRhsNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00005455 const int rhs[] = {1, 2, 3};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005456 vector<int> lhs;
5457 lhs.push_back(2);
5458 lhs.push_back(4);
5459 lhs.push_back(6);
5460 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
5461 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
5462}
5463
kosak2336e9c2014-07-28 22:57:30 +00005464#if GTEST_HAS_STD_INITIALIZER_LIST_
5465
5466TEST(PointwiseTest, WorksForRhsInitializerList) {
5467 const vector<int> lhs{2, 4, 6};
5468 EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
5469 EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
5470}
5471
5472#endif // GTEST_HAS_STD_INITIALIZER_LIST_
5473
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005474TEST(PointwiseTest, RejectsWrongSize) {
kosak2336e9c2014-07-28 22:57:30 +00005475 const double lhs[2] = {1, 2};
5476 const int rhs[1] = {0};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005477 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5478 EXPECT_EQ("which contains 2 values",
5479 Explain(Pointwise(Gt(), rhs), lhs));
5480
kosak2336e9c2014-07-28 22:57:30 +00005481 const int rhs2[3] = {0, 1, 2};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005482 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
5483}
5484
5485TEST(PointwiseTest, RejectsWrongContent) {
kosak2336e9c2014-07-28 22:57:30 +00005486 const double lhs[3] = {1, 2, 3};
5487 const int rhs[3] = {2, 6, 4};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005488 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
5489 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
5490 "where the second/2 is 3",
5491 Explain(Pointwise(IsHalfOf(), rhs), lhs));
5492}
5493
5494TEST(PointwiseTest, AcceptsCorrectContent) {
kosak2336e9c2014-07-28 22:57:30 +00005495 const double lhs[3] = {1, 2, 3};
5496 const int rhs[3] = {2, 4, 6};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005497 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
5498 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
5499}
5500
5501TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
kosak2336e9c2014-07-28 22:57:30 +00005502 const double lhs[3] = {1, 2, 3};
5503 const int rhs[3] = {2, 4, 6};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005504 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5505 EXPECT_THAT(lhs, Pointwise(m1, rhs));
5506 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
5507
5508 // This type works as a tuple<const double&, const int&> can be
5509 // implicitly cast to tuple<double, int>.
5510 const Matcher<tuple<double, int> > m2 = IsHalfOf();
5511 EXPECT_THAT(lhs, Pointwise(m2, rhs));
5512 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
5513}
5514
kosak2336e9c2014-07-28 22:57:30 +00005515TEST(UnorderedPointwiseTest, DescribesSelf) {
5516 vector<int> rhs;
5517 rhs.push_back(1);
5518 rhs.push_back(2);
5519 rhs.push_back(3);
5520 const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
5521 EXPECT_EQ(
5522 "has 3 elements and there exists some permutation of elements such "
5523 "that:\n"
5524 " - element #0 and 1 are a pair where the first is half of the second, "
5525 "and\n"
5526 " - element #1 and 2 are a pair where the first is half of the second, "
5527 "and\n"
5528 " - element #2 and 3 are a pair where the first is half of the second",
5529 Describe(m));
5530 EXPECT_EQ(
5531 "doesn't have 3 elements, or there exists no permutation of elements "
5532 "such that:\n"
5533 " - element #0 and 1 are a pair where the first is half of the second, "
5534 "and\n"
5535 " - element #1 and 2 are a pair where the first is half of the second, "
5536 "and\n"
5537 " - element #2 and 3 are a pair where the first is half of the second",
5538 DescribeNegation(m));
5539}
5540
5541TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
5542 list<signed char> rhs;
5543 rhs.push_back(2);
5544 rhs.push_back(4);
5545
5546 int lhs[] = {2, 1};
5547 const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
5548 EXPECT_THAT(lhs, m);
5549
5550 // Changing rhs now shouldn't affect m, which made a copy of rhs.
5551 rhs.push_back(6);
5552 EXPECT_THAT(lhs, m);
5553}
5554
5555TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
5556 const int lhs[] = {1, 2, 3};
5557 vector<int> rhs;
5558 rhs.push_back(4);
5559 rhs.push_back(6);
5560 rhs.push_back(2);
5561 EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
5562 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
5563}
5564
5565TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
5566 const int rhs[] = {1, 2, 3};
5567 vector<int> lhs;
5568 lhs.push_back(4);
5569 lhs.push_back(2);
5570 lhs.push_back(6);
5571 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
5572 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
5573}
5574
5575#if GTEST_HAS_STD_INITIALIZER_LIST_
5576
5577TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
5578 const vector<int> lhs{2, 4, 6};
5579 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
5580 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
5581}
5582
5583#endif // GTEST_HAS_STD_INITIALIZER_LIST_
5584
5585TEST(UnorderedPointwiseTest, RejectsWrongSize) {
5586 const double lhs[2] = {1, 2};
5587 const int rhs[1] = {0};
5588 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
5589 EXPECT_EQ("which has 2 elements",
5590 Explain(UnorderedPointwise(Gt(), rhs), lhs));
5591
5592 const int rhs2[3] = {0, 1, 2};
5593 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
5594}
5595
5596TEST(UnorderedPointwiseTest, RejectsWrongContent) {
5597 const double lhs[3] = {1, 2, 3};
5598 const int rhs[3] = {2, 6, 6};
5599 EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
5600 EXPECT_EQ("where the following elements don't match any matchers:\n"
5601 "element #1: 2",
5602 Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
5603}
5604
5605TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
5606 const double lhs[3] = {1, 2, 3};
5607 const int rhs[3] = {2, 4, 6};
5608 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
5609}
5610
5611TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
5612 const double lhs[3] = {1, 2, 3};
5613 const int rhs[3] = {6, 4, 2};
5614 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
5615}
5616
5617TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
5618 const double lhs[3] = {1, 2, 3};
5619 const int rhs[3] = {4, 6, 2};
5620 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5621 EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
5622
5623 // This type works as a tuple<const double&, const int&> can be
5624 // implicitly cast to tuple<double, int>.
5625 const Matcher<tuple<double, int> > m2 = IsHalfOf();
5626 EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
5627}
5628
shiqiane35fdd92008-12-10 05:08:54 +00005629} // namespace gmock_matchers_test
5630} // namespace testing