blob: ceb20022276e391fb7ca0e75c265e40e362ed103 [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
kosak9b1a9442015-04-28 23:06:58 +0000765TEST(ExpectThat, TakesLiterals) {
766 EXPECT_THAT(1, 1);
767 EXPECT_THAT(1.0, 1.0);
768 EXPECT_THAT(string(), "");
769}
770
771TEST(ExpectThat, TakesFunctions) {
772 struct Helper {
773 static void Func() {}
774 };
775 void (*func)() = Helper::Func;
776 EXPECT_THAT(func, Helper::Func);
777 EXPECT_THAT(func, &Helper::Func);
778}
779
shiqiane35fdd92008-12-10 05:08:54 +0000780// Tests that A<T>() matches any value of type T.
781TEST(ATest, MatchesAnyValue) {
782 // Tests a matcher for a value type.
783 Matcher<double> m1 = A<double>();
784 EXPECT_TRUE(m1.Matches(91.43));
785 EXPECT_TRUE(m1.Matches(-15.32));
786
787 // Tests a matcher for a reference type.
788 int a = 2;
789 int b = -6;
790 Matcher<int&> m2 = A<int&>();
791 EXPECT_TRUE(m2.Matches(a));
792 EXPECT_TRUE(m2.Matches(b));
793}
794
zhanyong.wanf4274522013-04-24 02:49:43 +0000795TEST(ATest, WorksForDerivedClass) {
796 Base base;
797 Derived derived;
798 EXPECT_THAT(&base, A<Base*>());
799 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
800 EXPECT_THAT(&derived, A<Base*>());
801 EXPECT_THAT(&derived, A<Derived*>());
802}
803
shiqiane35fdd92008-12-10 05:08:54 +0000804// Tests that A<T>() describes itself properly.
805TEST(ATest, CanDescribeSelf) {
806 EXPECT_EQ("is anything", Describe(A<bool>()));
807}
808
809// Tests that An<T>() matches any value of type T.
810TEST(AnTest, MatchesAnyValue) {
811 // Tests a matcher for a value type.
812 Matcher<int> m1 = An<int>();
813 EXPECT_TRUE(m1.Matches(9143));
814 EXPECT_TRUE(m1.Matches(-1532));
815
816 // Tests a matcher for a reference type.
817 int a = 2;
818 int b = -6;
819 Matcher<int&> m2 = An<int&>();
820 EXPECT_TRUE(m2.Matches(a));
821 EXPECT_TRUE(m2.Matches(b));
822}
823
824// Tests that An<T>() describes itself properly.
825TEST(AnTest, CanDescribeSelf) {
826 EXPECT_EQ("is anything", Describe(An<int>()));
827}
828
829// Tests that _ can be used as a matcher for any type and matches any
830// value of that type.
831TEST(UnderscoreTest, MatchesAnyValue) {
832 // Uses _ as a matcher for a value type.
833 Matcher<int> m1 = _;
834 EXPECT_TRUE(m1.Matches(123));
835 EXPECT_TRUE(m1.Matches(-242));
836
837 // Uses _ as a matcher for a reference type.
838 bool a = false;
839 const bool b = true;
840 Matcher<const bool&> m2 = _;
841 EXPECT_TRUE(m2.Matches(a));
842 EXPECT_TRUE(m2.Matches(b));
843}
844
845// Tests that _ describes itself properly.
846TEST(UnderscoreTest, CanDescribeSelf) {
847 Matcher<int> m = _;
848 EXPECT_EQ("is anything", Describe(m));
849}
850
851// Tests that Eq(x) matches any value equal to x.
852TEST(EqTest, MatchesEqualValue) {
853 // 2 C-strings with same content but different addresses.
854 const char a1[] = "hi";
855 const char a2[] = "hi";
856
857 Matcher<const char*> m1 = Eq(a1);
858 EXPECT_TRUE(m1.Matches(a1));
859 EXPECT_FALSE(m1.Matches(a2));
860}
861
862// Tests that Eq(v) describes itself properly.
863
864class Unprintable {
865 public:
866 Unprintable() : c_('a') {}
867
zhanyong.wan32de5f52009-12-23 00:13:23 +0000868 bool operator==(const Unprintable& /* rhs */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000869 private:
870 char c_;
871};
872
873TEST(EqTest, CanDescribeSelf) {
874 Matcher<Unprintable> m = Eq(Unprintable());
875 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
876}
877
878// Tests that Eq(v) can be used to match any type that supports
879// comparing with type T, where T is v's type.
880TEST(EqTest, IsPolymorphic) {
881 Matcher<int> m1 = Eq(1);
882 EXPECT_TRUE(m1.Matches(1));
883 EXPECT_FALSE(m1.Matches(2));
884
885 Matcher<char> m2 = Eq(1);
886 EXPECT_TRUE(m2.Matches('\1'));
887 EXPECT_FALSE(m2.Matches('a'));
888}
889
890// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
891TEST(TypedEqTest, ChecksEqualityForGivenType) {
892 Matcher<char> m1 = TypedEq<char>('a');
893 EXPECT_TRUE(m1.Matches('a'));
894 EXPECT_FALSE(m1.Matches('b'));
895
896 Matcher<int> m2 = TypedEq<int>(6);
897 EXPECT_TRUE(m2.Matches(6));
898 EXPECT_FALSE(m2.Matches(7));
899}
900
901// Tests that TypedEq(v) describes itself properly.
902TEST(TypedEqTest, CanDescribeSelf) {
903 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
904}
905
906// Tests that TypedEq<T>(v) has type Matcher<T>.
907
908// Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
909// is a "bare" type (i.e. not in the form of const U or U&). If v's
910// type is not T, the compiler will generate a message about
911// "undefined referece".
912template <typename T>
913struct Type {
zhanyong.wan32de5f52009-12-23 00:13:23 +0000914 static bool IsTypeOf(const T& /* v */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000915
916 template <typename T2>
917 static void IsTypeOf(T2 v);
918};
919
920TEST(TypedEqTest, HasSpecifiedType) {
921 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
922 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
923 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
924}
925
926// Tests that Ge(v) matches anything >= v.
927TEST(GeTest, ImplementsGreaterThanOrEqual) {
928 Matcher<int> m1 = Ge(0);
929 EXPECT_TRUE(m1.Matches(1));
930 EXPECT_TRUE(m1.Matches(0));
931 EXPECT_FALSE(m1.Matches(-1));
932}
933
934// Tests that Ge(v) describes itself properly.
935TEST(GeTest, CanDescribeSelf) {
936 Matcher<int> m = Ge(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000937 EXPECT_EQ("is >= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000938}
939
940// Tests that Gt(v) matches anything > v.
941TEST(GtTest, ImplementsGreaterThan) {
942 Matcher<double> m1 = Gt(0);
943 EXPECT_TRUE(m1.Matches(1.0));
944 EXPECT_FALSE(m1.Matches(0.0));
945 EXPECT_FALSE(m1.Matches(-1.0));
946}
947
948// Tests that Gt(v) describes itself properly.
949TEST(GtTest, CanDescribeSelf) {
950 Matcher<int> m = Gt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000951 EXPECT_EQ("is > 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000952}
953
954// Tests that Le(v) matches anything <= v.
955TEST(LeTest, ImplementsLessThanOrEqual) {
956 Matcher<char> m1 = Le('b');
957 EXPECT_TRUE(m1.Matches('a'));
958 EXPECT_TRUE(m1.Matches('b'));
959 EXPECT_FALSE(m1.Matches('c'));
960}
961
962// Tests that Le(v) describes itself properly.
963TEST(LeTest, CanDescribeSelf) {
964 Matcher<int> m = Le(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000965 EXPECT_EQ("is <= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000966}
967
968// Tests that Lt(v) matches anything < v.
969TEST(LtTest, ImplementsLessThan) {
970 Matcher<const string&> m1 = Lt("Hello");
971 EXPECT_TRUE(m1.Matches("Abc"));
972 EXPECT_FALSE(m1.Matches("Hello"));
973 EXPECT_FALSE(m1.Matches("Hello, world!"));
974}
975
976// Tests that Lt(v) describes itself properly.
977TEST(LtTest, CanDescribeSelf) {
978 Matcher<int> m = Lt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000979 EXPECT_EQ("is < 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000980}
981
982// Tests that Ne(v) matches anything != v.
983TEST(NeTest, ImplementsNotEqual) {
984 Matcher<int> m1 = Ne(0);
985 EXPECT_TRUE(m1.Matches(1));
986 EXPECT_TRUE(m1.Matches(-1));
987 EXPECT_FALSE(m1.Matches(0));
988}
989
990// Tests that Ne(v) describes itself properly.
991TEST(NeTest, CanDescribeSelf) {
992 Matcher<int> m = Ne(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000993 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000994}
995
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000996// Tests that IsNull() matches any NULL pointer of any type.
997TEST(IsNullTest, MatchesNullPointer) {
998 Matcher<int*> m1 = IsNull();
999 int* p1 = NULL;
1000 int n = 0;
1001 EXPECT_TRUE(m1.Matches(p1));
1002 EXPECT_FALSE(m1.Matches(&n));
1003
1004 Matcher<const char*> m2 = IsNull();
1005 const char* p2 = NULL;
1006 EXPECT_TRUE(m2.Matches(p2));
1007 EXPECT_FALSE(m2.Matches("hi"));
1008
zhanyong.wan95b12332009-09-25 18:55:50 +00001009#if !GTEST_OS_SYMBIAN
1010 // Nokia's Symbian compiler generates:
1011 // gmock-matchers.h: ambiguous access to overloaded function
1012 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
1013 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
1014 // MatcherInterface<void *> *)'
1015 // gmock-matchers.h: (point of instantiation: 'testing::
1016 // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
1017 // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001018 Matcher<void*> m3 = IsNull();
1019 void* p3 = NULL;
1020 EXPECT_TRUE(m3.Matches(p3));
1021 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
zhanyong.wan95b12332009-09-25 18:55:50 +00001022#endif
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001023}
1024
vladlosev79b83502009-11-18 00:43:37 +00001025TEST(IsNullTest, LinkedPtr) {
1026 const Matcher<linked_ptr<int> > m = IsNull();
1027 const linked_ptr<int> null_p;
1028 const linked_ptr<int> non_null_p(new int);
1029
1030 EXPECT_TRUE(m.Matches(null_p));
1031 EXPECT_FALSE(m.Matches(non_null_p));
1032}
1033
1034TEST(IsNullTest, ReferenceToConstLinkedPtr) {
1035 const Matcher<const linked_ptr<double>&> m = IsNull();
1036 const linked_ptr<double> null_p;
1037 const linked_ptr<double> non_null_p(new double);
1038
1039 EXPECT_TRUE(m.Matches(null_p));
1040 EXPECT_FALSE(m.Matches(non_null_p));
1041}
1042
kosak6305ff52015-04-28 22:36:31 +00001043#if GTEST_LANG_CXX11
1044TEST(IsNullTest, StdFunction) {
1045 const Matcher<std::function<void()>> m = IsNull();
1046
1047 EXPECT_TRUE(m.Matches(std::function<void()>()));
1048 EXPECT_FALSE(m.Matches([]{}));
1049}
1050#endif // GTEST_LANG_CXX11
1051
vladloseve56daa72009-11-18 01:08:08 +00001052TEST(IsNullTest, ReferenceToConstScopedPtr) {
1053 const Matcher<const scoped_ptr<double>&> m = IsNull();
1054 const scoped_ptr<double> null_p;
1055 const scoped_ptr<double> non_null_p(new double);
1056
1057 EXPECT_TRUE(m.Matches(null_p));
1058 EXPECT_FALSE(m.Matches(non_null_p));
1059}
1060
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001061// Tests that IsNull() describes itself properly.
1062TEST(IsNullTest, CanDescribeSelf) {
1063 Matcher<int*> m = IsNull();
1064 EXPECT_EQ("is NULL", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001065 EXPECT_EQ("isn't NULL", DescribeNegation(m));
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001066}
1067
shiqiane35fdd92008-12-10 05:08:54 +00001068// Tests that NotNull() matches any non-NULL pointer of any type.
1069TEST(NotNullTest, MatchesNonNullPointer) {
1070 Matcher<int*> m1 = NotNull();
1071 int* p1 = NULL;
1072 int n = 0;
1073 EXPECT_FALSE(m1.Matches(p1));
1074 EXPECT_TRUE(m1.Matches(&n));
1075
1076 Matcher<const char*> m2 = NotNull();
1077 const char* p2 = NULL;
1078 EXPECT_FALSE(m2.Matches(p2));
1079 EXPECT_TRUE(m2.Matches("hi"));
1080}
1081
vladlosev79b83502009-11-18 00:43:37 +00001082TEST(NotNullTest, LinkedPtr) {
1083 const Matcher<linked_ptr<int> > m = NotNull();
1084 const linked_ptr<int> null_p;
1085 const linked_ptr<int> non_null_p(new int);
1086
1087 EXPECT_FALSE(m.Matches(null_p));
1088 EXPECT_TRUE(m.Matches(non_null_p));
1089}
1090
1091TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1092 const Matcher<const linked_ptr<double>&> m = NotNull();
1093 const linked_ptr<double> null_p;
1094 const linked_ptr<double> non_null_p(new double);
1095
1096 EXPECT_FALSE(m.Matches(null_p));
1097 EXPECT_TRUE(m.Matches(non_null_p));
1098}
1099
kosak6305ff52015-04-28 22:36:31 +00001100#if GTEST_LANG_CXX11
1101TEST(NotNullTest, StdFunction) {
1102 const Matcher<std::function<void()>> m = NotNull();
1103
1104 EXPECT_TRUE(m.Matches([]{}));
1105 EXPECT_FALSE(m.Matches(std::function<void()>()));
1106}
1107#endif // GTEST_LANG_CXX11
1108
vladloseve56daa72009-11-18 01:08:08 +00001109TEST(NotNullTest, ReferenceToConstScopedPtr) {
1110 const Matcher<const scoped_ptr<double>&> m = NotNull();
1111 const scoped_ptr<double> null_p;
1112 const scoped_ptr<double> non_null_p(new double);
1113
1114 EXPECT_FALSE(m.Matches(null_p));
1115 EXPECT_TRUE(m.Matches(non_null_p));
1116}
1117
shiqiane35fdd92008-12-10 05:08:54 +00001118// Tests that NotNull() describes itself properly.
1119TEST(NotNullTest, CanDescribeSelf) {
1120 Matcher<int*> m = NotNull();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001121 EXPECT_EQ("isn't NULL", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001122}
1123
1124// Tests that Ref(variable) matches an argument that references
1125// 'variable'.
1126TEST(RefTest, MatchesSameVariable) {
1127 int a = 0;
1128 int b = 0;
1129 Matcher<int&> m = Ref(a);
1130 EXPECT_TRUE(m.Matches(a));
1131 EXPECT_FALSE(m.Matches(b));
1132}
1133
1134// Tests that Ref(variable) describes itself properly.
1135TEST(RefTest, CanDescribeSelf) {
1136 int n = 5;
1137 Matcher<int&> m = Ref(n);
1138 stringstream ss;
1139 ss << "references the variable @" << &n << " 5";
1140 EXPECT_EQ(string(ss.str()), Describe(m));
1141}
1142
1143// Test that Ref(non_const_varialbe) can be used as a matcher for a
1144// const reference.
1145TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1146 int a = 0;
1147 int b = 0;
1148 Matcher<const int&> m = Ref(a);
1149 EXPECT_TRUE(m.Matches(a));
1150 EXPECT_FALSE(m.Matches(b));
1151}
1152
1153// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1154// used wherever Ref(base) can be used (Ref(derived) is a sub-type
1155// of Ref(base), but not vice versa.
1156
shiqiane35fdd92008-12-10 05:08:54 +00001157TEST(RefTest, IsCovariant) {
1158 Base base, base2;
1159 Derived derived;
1160 Matcher<const Base&> m1 = Ref(base);
1161 EXPECT_TRUE(m1.Matches(base));
1162 EXPECT_FALSE(m1.Matches(base2));
1163 EXPECT_FALSE(m1.Matches(derived));
1164
1165 m1 = Ref(derived);
1166 EXPECT_TRUE(m1.Matches(derived));
1167 EXPECT_FALSE(m1.Matches(base));
1168 EXPECT_FALSE(m1.Matches(base2));
1169}
1170
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001171TEST(RefTest, ExplainsResult) {
1172 int n = 0;
1173 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1174 StartsWith("which is located @"));
1175
1176 int m = 0;
1177 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1178 StartsWith("which is located @"));
1179}
1180
shiqiane35fdd92008-12-10 05:08:54 +00001181// Tests string comparison matchers.
1182
1183TEST(StrEqTest, MatchesEqualString) {
1184 Matcher<const char*> m = StrEq(string("Hello"));
1185 EXPECT_TRUE(m.Matches("Hello"));
1186 EXPECT_FALSE(m.Matches("hello"));
1187 EXPECT_FALSE(m.Matches(NULL));
1188
1189 Matcher<const string&> m2 = StrEq("Hello");
1190 EXPECT_TRUE(m2.Matches("Hello"));
1191 EXPECT_FALSE(m2.Matches("Hi"));
1192}
1193
1194TEST(StrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001195 Matcher<string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1196 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
shiqiane35fdd92008-12-10 05:08:54 +00001197 Describe(m));
1198
1199 string str("01204500800");
1200 str[3] = '\0';
1201 Matcher<string> m2 = StrEq(str);
1202 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1203 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1204 Matcher<string> m3 = StrEq(str);
1205 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1206}
1207
1208TEST(StrNeTest, MatchesUnequalString) {
1209 Matcher<const char*> m = StrNe("Hello");
1210 EXPECT_TRUE(m.Matches(""));
1211 EXPECT_TRUE(m.Matches(NULL));
1212 EXPECT_FALSE(m.Matches("Hello"));
1213
1214 Matcher<string> m2 = StrNe(string("Hello"));
1215 EXPECT_TRUE(m2.Matches("hello"));
1216 EXPECT_FALSE(m2.Matches("Hello"));
1217}
1218
1219TEST(StrNeTest, CanDescribeSelf) {
1220 Matcher<const char*> m = StrNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001221 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001222}
1223
1224TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1225 Matcher<const char*> m = StrCaseEq(string("Hello"));
1226 EXPECT_TRUE(m.Matches("Hello"));
1227 EXPECT_TRUE(m.Matches("hello"));
1228 EXPECT_FALSE(m.Matches("Hi"));
1229 EXPECT_FALSE(m.Matches(NULL));
1230
1231 Matcher<const string&> m2 = StrCaseEq("Hello");
1232 EXPECT_TRUE(m2.Matches("hello"));
1233 EXPECT_FALSE(m2.Matches("Hi"));
1234}
1235
1236TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1237 string str1("oabocdooeoo");
1238 string str2("OABOCDOOEOO");
1239 Matcher<const string&> m0 = StrCaseEq(str1);
1240 EXPECT_FALSE(m0.Matches(str2 + string(1, '\0')));
1241
1242 str1[3] = str2[3] = '\0';
1243 Matcher<const string&> m1 = StrCaseEq(str1);
1244 EXPECT_TRUE(m1.Matches(str2));
1245
1246 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1247 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1248 Matcher<const string&> m2 = StrCaseEq(str1);
1249 str1[9] = str2[9] = '\0';
1250 EXPECT_FALSE(m2.Matches(str2));
1251
1252 Matcher<const string&> m3 = StrCaseEq(str1);
1253 EXPECT_TRUE(m3.Matches(str2));
1254
1255 EXPECT_FALSE(m3.Matches(str2 + "x"));
1256 str2.append(1, '\0');
1257 EXPECT_FALSE(m3.Matches(str2));
1258 EXPECT_FALSE(m3.Matches(string(str2, 0, 9)));
1259}
1260
1261TEST(StrCaseEqTest, CanDescribeSelf) {
1262 Matcher<string> m = StrCaseEq("Hi");
1263 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1264}
1265
1266TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1267 Matcher<const char*> m = StrCaseNe("Hello");
1268 EXPECT_TRUE(m.Matches("Hi"));
1269 EXPECT_TRUE(m.Matches(NULL));
1270 EXPECT_FALSE(m.Matches("Hello"));
1271 EXPECT_FALSE(m.Matches("hello"));
1272
1273 Matcher<string> m2 = StrCaseNe(string("Hello"));
1274 EXPECT_TRUE(m2.Matches(""));
1275 EXPECT_FALSE(m2.Matches("Hello"));
1276}
1277
1278TEST(StrCaseNeTest, CanDescribeSelf) {
1279 Matcher<const char*> m = StrCaseNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001280 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001281}
1282
1283// Tests that HasSubstr() works for matching string-typed values.
1284TEST(HasSubstrTest, WorksForStringClasses) {
1285 const Matcher<string> m1 = HasSubstr("foo");
1286 EXPECT_TRUE(m1.Matches(string("I love food.")));
1287 EXPECT_FALSE(m1.Matches(string("tofo")));
1288
1289 const Matcher<const std::string&> m2 = HasSubstr("foo");
1290 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1291 EXPECT_FALSE(m2.Matches(std::string("tofo")));
1292}
1293
1294// Tests that HasSubstr() works for matching C-string-typed values.
1295TEST(HasSubstrTest, WorksForCStrings) {
1296 const Matcher<char*> m1 = HasSubstr("foo");
1297 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1298 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1299 EXPECT_FALSE(m1.Matches(NULL));
1300
1301 const Matcher<const char*> m2 = HasSubstr("foo");
1302 EXPECT_TRUE(m2.Matches("I love food."));
1303 EXPECT_FALSE(m2.Matches("tofo"));
1304 EXPECT_FALSE(m2.Matches(NULL));
1305}
1306
1307// Tests that HasSubstr(s) describes itself properly.
1308TEST(HasSubstrTest, CanDescribeSelf) {
1309 Matcher<string> m = HasSubstr("foo\n\"");
1310 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1311}
1312
zhanyong.wanb5937da2009-07-16 20:26:41 +00001313TEST(KeyTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001314 Matcher<const pair<std::string, int>&> m = Key("foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001315 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001316 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1317}
1318
1319TEST(KeyTest, ExplainsResult) {
1320 Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1321 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1322 Explain(m, make_pair(5, true)));
1323 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1324 Explain(m, make_pair(15, true)));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001325}
1326
1327TEST(KeyTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001328 pair<int, std::string> p(25, "foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001329 EXPECT_THAT(p, Key(25));
1330 EXPECT_THAT(p, Not(Key(42)));
1331 EXPECT_THAT(p, Key(Ge(20)));
1332 EXPECT_THAT(p, Not(Key(Lt(25))));
1333}
1334
1335TEST(KeyTest, SafelyCastsInnerMatcher) {
1336 Matcher<int> is_positive = Gt(0);
1337 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001338 pair<char, bool> p('a', true);
zhanyong.wanb5937da2009-07-16 20:26:41 +00001339 EXPECT_THAT(p, Key(is_positive));
1340 EXPECT_THAT(p, Not(Key(is_negative)));
1341}
1342
1343TEST(KeyTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001344 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001345 container.insert(make_pair(1, 'a'));
1346 container.insert(make_pair(2, 'b'));
1347 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001348 EXPECT_THAT(container, Contains(Key(1)));
1349 EXPECT_THAT(container, Not(Contains(Key(3))));
1350}
1351
1352TEST(KeyTest, InsideContainsUsingMultimap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001353 multimap<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001354 container.insert(make_pair(1, 'a'));
1355 container.insert(make_pair(2, 'b'));
1356 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001357
1358 EXPECT_THAT(container, Not(Contains(Key(25))));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001359 container.insert(make_pair(25, 'd'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001360 EXPECT_THAT(container, Contains(Key(25)));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001361 container.insert(make_pair(25, 'e'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001362 EXPECT_THAT(container, Contains(Key(25)));
1363
1364 EXPECT_THAT(container, Contains(Key(1)));
1365 EXPECT_THAT(container, Not(Contains(Key(3))));
1366}
1367
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001368TEST(PairTest, Typing) {
1369 // Test verifies the following type conversions can be compiled.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001370 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1371 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1372 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001373
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001374 Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1375 Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001376}
1377
1378TEST(PairTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001379 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001380 EXPECT_EQ("has a first field that is equal to \"foo\""
1381 ", and has a second field that is equal to 42",
1382 Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001383 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1384 ", or has a second field that isn't equal to 42",
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001385 DescribeNegation(m1));
1386 // Double and triple negation (1 or 2 times not and description of negation).
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001387 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1388 EXPECT_EQ("has a first field that isn't equal to 13"
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001389 ", and has a second field that is equal to 42",
1390 DescribeNegation(m2));
1391}
1392
1393TEST(PairTest, CanExplainMatchResultTo) {
zhanyong.wan82113312010-01-08 21:55:40 +00001394 // If neither field matches, Pair() should explain about the first
1395 // field.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001396 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001397 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001398 Explain(m, make_pair(-1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001399
zhanyong.wan82113312010-01-08 21:55:40 +00001400 // If the first field matches but the second doesn't, Pair() should
1401 // explain about the second field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001402 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001403 Explain(m, make_pair(1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001404
zhanyong.wan82113312010-01-08 21:55:40 +00001405 // If the first field doesn't match but the second does, Pair()
1406 // should explain about the first field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001407 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001408 Explain(m, make_pair(-1, 2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001409
zhanyong.wan82113312010-01-08 21:55:40 +00001410 // If both fields match, Pair() should explain about them both.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001411 EXPECT_EQ("whose both fields match, where the first field is a value "
1412 "which is 1 more than 0, and the second field is a value "
1413 "which is 2 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001414 Explain(m, make_pair(1, 2)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001415
1416 // If only the first match has an explanation, only this explanation should
1417 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001418 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001419 EXPECT_EQ("whose both fields match, where the first field is a value "
1420 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001421 Explain(explain_first, make_pair(1, 0)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001422
1423 // If only the second match has an explanation, only this explanation should
1424 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001425 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001426 EXPECT_EQ("whose both fields match, where the second field is a value "
1427 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001428 Explain(explain_second, make_pair(0, 1)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001429}
1430
1431TEST(PairTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001432 pair<int, std::string> p(25, "foo");
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001433
1434 // Both fields match.
1435 EXPECT_THAT(p, Pair(25, "foo"));
1436 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1437
1438 // 'first' doesnt' match, but 'second' matches.
1439 EXPECT_THAT(p, Not(Pair(42, "foo")));
1440 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1441
1442 // 'first' matches, but 'second' doesn't match.
1443 EXPECT_THAT(p, Not(Pair(25, "bar")));
1444 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1445
1446 // Neither field matches.
1447 EXPECT_THAT(p, Not(Pair(13, "bar")));
1448 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1449}
1450
1451TEST(PairTest, SafelyCastsInnerMatchers) {
1452 Matcher<int> is_positive = Gt(0);
1453 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001454 pair<char, bool> p('a', true);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001455 EXPECT_THAT(p, Pair(is_positive, _));
1456 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1457 EXPECT_THAT(p, Pair(_, is_positive));
1458 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1459}
1460
1461TEST(PairTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001462 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001463 container.insert(make_pair(1, 'a'));
1464 container.insert(make_pair(2, 'b'));
1465 container.insert(make_pair(4, 'c'));
zhanyong.wan95b12332009-09-25 18:55:50 +00001466 EXPECT_THAT(container, Contains(Pair(1, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001467 EXPECT_THAT(container, Contains(Pair(1, _)));
zhanyong.wan95b12332009-09-25 18:55:50 +00001468 EXPECT_THAT(container, Contains(Pair(_, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001469 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1470}
1471
shiqiane35fdd92008-12-10 05:08:54 +00001472// Tests StartsWith(s).
1473
1474TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1475 const Matcher<const char*> m1 = StartsWith(string(""));
1476 EXPECT_TRUE(m1.Matches("Hi"));
1477 EXPECT_TRUE(m1.Matches(""));
1478 EXPECT_FALSE(m1.Matches(NULL));
1479
1480 const Matcher<const string&> m2 = StartsWith("Hi");
1481 EXPECT_TRUE(m2.Matches("Hi"));
1482 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1483 EXPECT_TRUE(m2.Matches("High"));
1484 EXPECT_FALSE(m2.Matches("H"));
1485 EXPECT_FALSE(m2.Matches(" Hi"));
1486}
1487
1488TEST(StartsWithTest, CanDescribeSelf) {
1489 Matcher<const std::string> m = StartsWith("Hi");
1490 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1491}
1492
1493// Tests EndsWith(s).
1494
1495TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1496 const Matcher<const char*> m1 = EndsWith("");
1497 EXPECT_TRUE(m1.Matches("Hi"));
1498 EXPECT_TRUE(m1.Matches(""));
1499 EXPECT_FALSE(m1.Matches(NULL));
1500
1501 const Matcher<const string&> m2 = EndsWith(string("Hi"));
1502 EXPECT_TRUE(m2.Matches("Hi"));
1503 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1504 EXPECT_TRUE(m2.Matches("Super Hi"));
1505 EXPECT_FALSE(m2.Matches("i"));
1506 EXPECT_FALSE(m2.Matches("Hi "));
1507}
1508
1509TEST(EndsWithTest, CanDescribeSelf) {
1510 Matcher<const std::string> m = EndsWith("Hi");
1511 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1512}
1513
shiqiane35fdd92008-12-10 05:08:54 +00001514// Tests MatchesRegex().
1515
1516TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1517 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1518 EXPECT_TRUE(m1.Matches("az"));
1519 EXPECT_TRUE(m1.Matches("abcz"));
1520 EXPECT_FALSE(m1.Matches(NULL));
1521
1522 const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z"));
1523 EXPECT_TRUE(m2.Matches("azbz"));
1524 EXPECT_FALSE(m2.Matches("az1"));
1525 EXPECT_FALSE(m2.Matches("1az"));
1526}
1527
1528TEST(MatchesRegexTest, CanDescribeSelf) {
1529 Matcher<const std::string> m1 = MatchesRegex(string("Hi.*"));
1530 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1531
zhanyong.wand14aaed2010-01-14 05:36:32 +00001532 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1533 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001534}
1535
1536// Tests ContainsRegex().
1537
1538TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1539 const Matcher<const char*> m1 = ContainsRegex(string("a.*z"));
1540 EXPECT_TRUE(m1.Matches("az"));
1541 EXPECT_TRUE(m1.Matches("0abcz1"));
1542 EXPECT_FALSE(m1.Matches(NULL));
1543
1544 const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z"));
1545 EXPECT_TRUE(m2.Matches("azbz"));
1546 EXPECT_TRUE(m2.Matches("az1"));
1547 EXPECT_FALSE(m2.Matches("1a"));
1548}
1549
1550TEST(ContainsRegexTest, CanDescribeSelf) {
1551 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1552 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1553
zhanyong.wand14aaed2010-01-14 05:36:32 +00001554 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1555 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001556}
shiqiane35fdd92008-12-10 05:08:54 +00001557
1558// Tests for wide strings.
1559#if GTEST_HAS_STD_WSTRING
1560TEST(StdWideStrEqTest, MatchesEqual) {
1561 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1562 EXPECT_TRUE(m.Matches(L"Hello"));
1563 EXPECT_FALSE(m.Matches(L"hello"));
1564 EXPECT_FALSE(m.Matches(NULL));
1565
1566 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1567 EXPECT_TRUE(m2.Matches(L"Hello"));
1568 EXPECT_FALSE(m2.Matches(L"Hi"));
1569
1570 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1571 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1572 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1573
1574 ::std::wstring str(L"01204500800");
1575 str[3] = L'\0';
1576 Matcher<const ::std::wstring&> m4 = StrEq(str);
1577 EXPECT_TRUE(m4.Matches(str));
1578 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1579 Matcher<const ::std::wstring&> m5 = StrEq(str);
1580 EXPECT_TRUE(m5.Matches(str));
1581}
1582
1583TEST(StdWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001584 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1585 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001586 Describe(m));
1587
1588 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1589 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1590 Describe(m2));
1591
1592 ::std::wstring str(L"01204500800");
1593 str[3] = L'\0';
1594 Matcher<const ::std::wstring&> m4 = StrEq(str);
1595 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1596 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1597 Matcher<const ::std::wstring&> m5 = StrEq(str);
1598 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1599}
1600
1601TEST(StdWideStrNeTest, MatchesUnequalString) {
1602 Matcher<const wchar_t*> m = StrNe(L"Hello");
1603 EXPECT_TRUE(m.Matches(L""));
1604 EXPECT_TRUE(m.Matches(NULL));
1605 EXPECT_FALSE(m.Matches(L"Hello"));
1606
1607 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1608 EXPECT_TRUE(m2.Matches(L"hello"));
1609 EXPECT_FALSE(m2.Matches(L"Hello"));
1610}
1611
1612TEST(StdWideStrNeTest, CanDescribeSelf) {
1613 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001614 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001615}
1616
1617TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1618 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1619 EXPECT_TRUE(m.Matches(L"Hello"));
1620 EXPECT_TRUE(m.Matches(L"hello"));
1621 EXPECT_FALSE(m.Matches(L"Hi"));
1622 EXPECT_FALSE(m.Matches(NULL));
1623
1624 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1625 EXPECT_TRUE(m2.Matches(L"hello"));
1626 EXPECT_FALSE(m2.Matches(L"Hi"));
1627}
1628
1629TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1630 ::std::wstring str1(L"oabocdooeoo");
1631 ::std::wstring str2(L"OABOCDOOEOO");
1632 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1633 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1634
1635 str1[3] = str2[3] = L'\0';
1636 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1637 EXPECT_TRUE(m1.Matches(str2));
1638
1639 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1640 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1641 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1642 str1[9] = str2[9] = L'\0';
1643 EXPECT_FALSE(m2.Matches(str2));
1644
1645 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1646 EXPECT_TRUE(m3.Matches(str2));
1647
1648 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1649 str2.append(1, L'\0');
1650 EXPECT_FALSE(m3.Matches(str2));
1651 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1652}
1653
1654TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1655 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1656 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1657}
1658
1659TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1660 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1661 EXPECT_TRUE(m.Matches(L"Hi"));
1662 EXPECT_TRUE(m.Matches(NULL));
1663 EXPECT_FALSE(m.Matches(L"Hello"));
1664 EXPECT_FALSE(m.Matches(L"hello"));
1665
1666 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1667 EXPECT_TRUE(m2.Matches(L""));
1668 EXPECT_FALSE(m2.Matches(L"Hello"));
1669}
1670
1671TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1672 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001673 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001674}
1675
1676// Tests that HasSubstr() works for matching wstring-typed values.
1677TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1678 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1679 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1680 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1681
1682 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1683 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1684 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1685}
1686
1687// Tests that HasSubstr() works for matching C-wide-string-typed values.
1688TEST(StdWideHasSubstrTest, WorksForCStrings) {
1689 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1690 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1691 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1692 EXPECT_FALSE(m1.Matches(NULL));
1693
1694 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1695 EXPECT_TRUE(m2.Matches(L"I love food."));
1696 EXPECT_FALSE(m2.Matches(L"tofo"));
1697 EXPECT_FALSE(m2.Matches(NULL));
1698}
1699
1700// Tests that HasSubstr(s) describes itself properly.
1701TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1702 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1703 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1704}
1705
1706// Tests StartsWith(s).
1707
1708TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1709 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1710 EXPECT_TRUE(m1.Matches(L"Hi"));
1711 EXPECT_TRUE(m1.Matches(L""));
1712 EXPECT_FALSE(m1.Matches(NULL));
1713
1714 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1715 EXPECT_TRUE(m2.Matches(L"Hi"));
1716 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1717 EXPECT_TRUE(m2.Matches(L"High"));
1718 EXPECT_FALSE(m2.Matches(L"H"));
1719 EXPECT_FALSE(m2.Matches(L" Hi"));
1720}
1721
1722TEST(StdWideStartsWithTest, CanDescribeSelf) {
1723 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
1724 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1725}
1726
1727// Tests EndsWith(s).
1728
1729TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
1730 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1731 EXPECT_TRUE(m1.Matches(L"Hi"));
1732 EXPECT_TRUE(m1.Matches(L""));
1733 EXPECT_FALSE(m1.Matches(NULL));
1734
1735 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
1736 EXPECT_TRUE(m2.Matches(L"Hi"));
1737 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1738 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1739 EXPECT_FALSE(m2.Matches(L"i"));
1740 EXPECT_FALSE(m2.Matches(L"Hi "));
1741}
1742
1743TEST(StdWideEndsWithTest, CanDescribeSelf) {
1744 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
1745 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1746}
1747
1748#endif // GTEST_HAS_STD_WSTRING
1749
1750#if GTEST_HAS_GLOBAL_WSTRING
1751TEST(GlobalWideStrEqTest, MatchesEqual) {
1752 Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
1753 EXPECT_TRUE(m.Matches(L"Hello"));
1754 EXPECT_FALSE(m.Matches(L"hello"));
1755 EXPECT_FALSE(m.Matches(NULL));
1756
1757 Matcher<const ::wstring&> m2 = StrEq(L"Hello");
1758 EXPECT_TRUE(m2.Matches(L"Hello"));
1759 EXPECT_FALSE(m2.Matches(L"Hi"));
1760
1761 Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1762 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1763 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1764
1765 ::wstring str(L"01204500800");
1766 str[3] = L'\0';
1767 Matcher<const ::wstring&> m4 = StrEq(str);
1768 EXPECT_TRUE(m4.Matches(str));
1769 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1770 Matcher<const ::wstring&> m5 = StrEq(str);
1771 EXPECT_TRUE(m5.Matches(str));
1772}
1773
1774TEST(GlobalWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001775 Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1776 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001777 Describe(m));
1778
1779 Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1780 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1781 Describe(m2));
1782
1783 ::wstring str(L"01204500800");
1784 str[3] = L'\0';
1785 Matcher<const ::wstring&> m4 = StrEq(str);
1786 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1787 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1788 Matcher<const ::wstring&> m5 = StrEq(str);
1789 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1790}
1791
1792TEST(GlobalWideStrNeTest, MatchesUnequalString) {
1793 Matcher<const wchar_t*> m = StrNe(L"Hello");
1794 EXPECT_TRUE(m.Matches(L""));
1795 EXPECT_TRUE(m.Matches(NULL));
1796 EXPECT_FALSE(m.Matches(L"Hello"));
1797
1798 Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
1799 EXPECT_TRUE(m2.Matches(L"hello"));
1800 EXPECT_FALSE(m2.Matches(L"Hello"));
1801}
1802
1803TEST(GlobalWideStrNeTest, CanDescribeSelf) {
1804 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001805 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001806}
1807
1808TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1809 Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
1810 EXPECT_TRUE(m.Matches(L"Hello"));
1811 EXPECT_TRUE(m.Matches(L"hello"));
1812 EXPECT_FALSE(m.Matches(L"Hi"));
1813 EXPECT_FALSE(m.Matches(NULL));
1814
1815 Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
1816 EXPECT_TRUE(m2.Matches(L"hello"));
1817 EXPECT_FALSE(m2.Matches(L"Hi"));
1818}
1819
1820TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1821 ::wstring str1(L"oabocdooeoo");
1822 ::wstring str2(L"OABOCDOOEOO");
1823 Matcher<const ::wstring&> m0 = StrCaseEq(str1);
1824 EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
1825
1826 str1[3] = str2[3] = L'\0';
1827 Matcher<const ::wstring&> m1 = StrCaseEq(str1);
1828 EXPECT_TRUE(m1.Matches(str2));
1829
1830 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1831 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1832 Matcher<const ::wstring&> m2 = StrCaseEq(str1);
1833 str1[9] = str2[9] = L'\0';
1834 EXPECT_FALSE(m2.Matches(str2));
1835
1836 Matcher<const ::wstring&> m3 = StrCaseEq(str1);
1837 EXPECT_TRUE(m3.Matches(str2));
1838
1839 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1840 str2.append(1, L'\0');
1841 EXPECT_FALSE(m3.Matches(str2));
1842 EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
1843}
1844
1845TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
1846 Matcher< ::wstring> m = StrCaseEq(L"Hi");
1847 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1848}
1849
1850TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1851 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1852 EXPECT_TRUE(m.Matches(L"Hi"));
1853 EXPECT_TRUE(m.Matches(NULL));
1854 EXPECT_FALSE(m.Matches(L"Hello"));
1855 EXPECT_FALSE(m.Matches(L"hello"));
1856
1857 Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
1858 EXPECT_TRUE(m2.Matches(L""));
1859 EXPECT_FALSE(m2.Matches(L"Hello"));
1860}
1861
1862TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
1863 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001864 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001865}
1866
1867// Tests that HasSubstr() works for matching wstring-typed values.
1868TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
1869 const Matcher< ::wstring> m1 = HasSubstr(L"foo");
1870 EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
1871 EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
1872
1873 const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
1874 EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
1875 EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
1876}
1877
1878// Tests that HasSubstr() works for matching C-wide-string-typed values.
1879TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
1880 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1881 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1882 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1883 EXPECT_FALSE(m1.Matches(NULL));
1884
1885 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1886 EXPECT_TRUE(m2.Matches(L"I love food."));
1887 EXPECT_FALSE(m2.Matches(L"tofo"));
1888 EXPECT_FALSE(m2.Matches(NULL));
1889}
1890
1891// Tests that HasSubstr(s) describes itself properly.
1892TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
1893 Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
1894 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1895}
1896
1897// Tests StartsWith(s).
1898
1899TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
1900 const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
1901 EXPECT_TRUE(m1.Matches(L"Hi"));
1902 EXPECT_TRUE(m1.Matches(L""));
1903 EXPECT_FALSE(m1.Matches(NULL));
1904
1905 const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
1906 EXPECT_TRUE(m2.Matches(L"Hi"));
1907 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1908 EXPECT_TRUE(m2.Matches(L"High"));
1909 EXPECT_FALSE(m2.Matches(L"H"));
1910 EXPECT_FALSE(m2.Matches(L" Hi"));
1911}
1912
1913TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
1914 Matcher<const ::wstring> m = StartsWith(L"Hi");
1915 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1916}
1917
1918// Tests EndsWith(s).
1919
1920TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
1921 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1922 EXPECT_TRUE(m1.Matches(L"Hi"));
1923 EXPECT_TRUE(m1.Matches(L""));
1924 EXPECT_FALSE(m1.Matches(NULL));
1925
1926 const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
1927 EXPECT_TRUE(m2.Matches(L"Hi"));
1928 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1929 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1930 EXPECT_FALSE(m2.Matches(L"i"));
1931 EXPECT_FALSE(m2.Matches(L"Hi "));
1932}
1933
1934TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
1935 Matcher<const ::wstring> m = EndsWith(L"Hi");
1936 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1937}
1938
1939#endif // GTEST_HAS_GLOBAL_WSTRING
1940
1941
kosakbd018832014-04-02 20:30:00 +00001942typedef ::testing::tuple<long, int> Tuple2; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00001943
1944// Tests that Eq() matches a 2-tuple where the first field == the
1945// second field.
1946TEST(Eq2Test, MatchesEqualArguments) {
1947 Matcher<const Tuple2&> m = Eq();
1948 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1949 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1950}
1951
1952// Tests that Eq() describes itself properly.
1953TEST(Eq2Test, CanDescribeSelf) {
1954 Matcher<const Tuple2&> m = Eq();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001955 EXPECT_EQ("are an equal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001956}
1957
1958// Tests that Ge() matches a 2-tuple where the first field >= the
1959// second field.
1960TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
1961 Matcher<const Tuple2&> m = Ge();
1962 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1963 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1964 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1965}
1966
1967// Tests that Ge() describes itself properly.
1968TEST(Ge2Test, CanDescribeSelf) {
1969 Matcher<const Tuple2&> m = Ge();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001970 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001971}
1972
1973// Tests that Gt() matches a 2-tuple where the first field > the
1974// second field.
1975TEST(Gt2Test, MatchesGreaterThanArguments) {
1976 Matcher<const Tuple2&> m = Gt();
1977 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1978 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1979 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1980}
1981
1982// Tests that Gt() describes itself properly.
1983TEST(Gt2Test, CanDescribeSelf) {
1984 Matcher<const Tuple2&> m = Gt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001985 EXPECT_EQ("are a pair where the first > the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001986}
1987
1988// Tests that Le() matches a 2-tuple where the first field <= the
1989// second field.
1990TEST(Le2Test, MatchesLessThanOrEqualArguments) {
1991 Matcher<const Tuple2&> m = Le();
1992 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1993 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1994 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1995}
1996
1997// Tests that Le() describes itself properly.
1998TEST(Le2Test, CanDescribeSelf) {
1999 Matcher<const Tuple2&> m = Le();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002000 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002001}
2002
2003// Tests that Lt() matches a 2-tuple where the first field < the
2004// second field.
2005TEST(Lt2Test, MatchesLessThanArguments) {
2006 Matcher<const Tuple2&> m = Lt();
2007 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2008 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2009 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
2010}
2011
2012// Tests that Lt() describes itself properly.
2013TEST(Lt2Test, CanDescribeSelf) {
2014 Matcher<const Tuple2&> m = Lt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002015 EXPECT_EQ("are a pair where the first < the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002016}
2017
2018// Tests that Ne() matches a 2-tuple where the first field != the
2019// second field.
2020TEST(Ne2Test, MatchesUnequalArguments) {
2021 Matcher<const Tuple2&> m = Ne();
2022 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2023 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2024 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2025}
2026
2027// Tests that Ne() describes itself properly.
2028TEST(Ne2Test, CanDescribeSelf) {
2029 Matcher<const Tuple2&> m = Ne();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002030 EXPECT_EQ("are an unequal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002031}
2032
2033// Tests that Not(m) matches any value that doesn't match m.
2034TEST(NotTest, NegatesMatcher) {
2035 Matcher<int> m;
2036 m = Not(Eq(2));
2037 EXPECT_TRUE(m.Matches(3));
2038 EXPECT_FALSE(m.Matches(2));
2039}
2040
2041// Tests that Not(m) describes itself properly.
2042TEST(NotTest, CanDescribeSelf) {
2043 Matcher<int> m = Not(Eq(5));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002044 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002045}
2046
zhanyong.wan18490652009-05-11 18:54:08 +00002047// Tests that monomorphic matchers are safely cast by the Not matcher.
2048TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2049 // greater_than_5 is a monomorphic matcher.
2050 Matcher<int> greater_than_5 = Gt(5);
2051
2052 Matcher<const int&> m = Not(greater_than_5);
2053 Matcher<int&> m2 = Not(greater_than_5);
2054 Matcher<int&> m3 = Not(m);
2055}
2056
zhanyong.wan02c15052010-06-09 19:21:30 +00002057// Helper to allow easy testing of AllOf matchers with num parameters.
2058void AllOfMatches(int num, const Matcher<int>& m) {
2059 SCOPED_TRACE(Describe(m));
2060 EXPECT_TRUE(m.Matches(0));
2061 for (int i = 1; i <= num; ++i) {
2062 EXPECT_FALSE(m.Matches(i));
2063 }
2064 EXPECT_TRUE(m.Matches(num + 1));
2065}
2066
shiqiane35fdd92008-12-10 05:08:54 +00002067// Tests that AllOf(m1, ..., mn) matches any value that matches all of
2068// the given matchers.
2069TEST(AllOfTest, MatchesWhenAllMatch) {
2070 Matcher<int> m;
2071 m = AllOf(Le(2), Ge(1));
2072 EXPECT_TRUE(m.Matches(1));
2073 EXPECT_TRUE(m.Matches(2));
2074 EXPECT_FALSE(m.Matches(0));
2075 EXPECT_FALSE(m.Matches(3));
2076
2077 m = AllOf(Gt(0), Ne(1), Ne(2));
2078 EXPECT_TRUE(m.Matches(3));
2079 EXPECT_FALSE(m.Matches(2));
2080 EXPECT_FALSE(m.Matches(1));
2081 EXPECT_FALSE(m.Matches(0));
2082
2083 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2084 EXPECT_TRUE(m.Matches(4));
2085 EXPECT_FALSE(m.Matches(3));
2086 EXPECT_FALSE(m.Matches(2));
2087 EXPECT_FALSE(m.Matches(1));
2088 EXPECT_FALSE(m.Matches(0));
2089
2090 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2091 EXPECT_TRUE(m.Matches(0));
2092 EXPECT_TRUE(m.Matches(1));
2093 EXPECT_FALSE(m.Matches(3));
zhanyong.wan02c15052010-06-09 19:21:30 +00002094
2095 // The following tests for varying number of sub-matchers. Due to the way
2096 // the sub-matchers are handled it is enough to test every sub-matcher once
2097 // with sub-matchers using the same matcher type. Varying matcher types are
2098 // checked for above.
2099 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2100 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2101 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2102 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2103 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2104 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2105 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2106 Ne(8)));
2107 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2108 Ne(8), Ne(9)));
2109 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2110 Ne(9), Ne(10)));
shiqiane35fdd92008-12-10 05:08:54 +00002111}
2112
zhanyong.wan616180e2013-06-18 18:49:51 +00002113#if GTEST_LANG_CXX11
2114// Tests the variadic version of the AllOfMatcher.
2115TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
2116 // Make sure AllOf is defined in the right namespace and does not depend on
2117 // ADL.
2118 ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2119 Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2120 Ne(9), Ne(10), Ne(11));
2121 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))"));
2122 AllOfMatches(11, m);
2123 AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2124 Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
2125 Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22),
2126 Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29),
2127 Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36),
2128 Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43),
2129 Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2130 Ne(50)));
2131}
2132
2133#endif // GTEST_LANG_CXX11
2134
shiqiane35fdd92008-12-10 05:08:54 +00002135// Tests that AllOf(m1, ..., mn) describes itself properly.
2136TEST(AllOfTest, CanDescribeSelf) {
2137 Matcher<int> m;
2138 m = AllOf(Le(2), Ge(1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002139 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002140
2141 m = AllOf(Gt(0), Ne(1), Ne(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002142 EXPECT_EQ("(is > 0) and "
2143 "((isn't equal to 1) and "
2144 "(isn't equal to 2))",
shiqiane35fdd92008-12-10 05:08:54 +00002145 Describe(m));
2146
2147
2148 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002149 EXPECT_EQ("((is > 0) and "
2150 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002151 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002152 "(isn't equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002153 Describe(m));
2154
2155
2156 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002157 EXPECT_EQ("((is >= 0) and "
2158 "(is < 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002159 "((isn't equal to 3) and "
2160 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002161 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002162 Describe(m));
2163}
2164
2165// Tests that AllOf(m1, ..., mn) describes its negation properly.
2166TEST(AllOfTest, CanDescribeNegation) {
2167 Matcher<int> m;
2168 m = AllOf(Le(2), Ge(1));
2169 EXPECT_EQ("(isn't <= 2) or "
2170 "(isn't >= 1)",
2171 DescribeNegation(m));
2172
2173 m = AllOf(Gt(0), Ne(1), Ne(2));
2174 EXPECT_EQ("(isn't > 0) or "
2175 "((is equal to 1) or "
2176 "(is equal to 2))",
2177 DescribeNegation(m));
2178
2179
2180 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002181 EXPECT_EQ("((isn't > 0) or "
2182 "(is equal to 1)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002183 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002184 "(is equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002185 DescribeNegation(m));
2186
2187
2188 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002189 EXPECT_EQ("((isn't >= 0) or "
2190 "(isn't < 10)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002191 "((is equal to 3) or "
2192 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002193 "(is equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002194 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00002195}
2196
zhanyong.wan18490652009-05-11 18:54:08 +00002197// Tests that monomorphic matchers are safely cast by the AllOf matcher.
2198TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2199 // greater_than_5 and less_than_10 are monomorphic matchers.
2200 Matcher<int> greater_than_5 = Gt(5);
2201 Matcher<int> less_than_10 = Lt(10);
2202
2203 Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2204 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2205 Matcher<int&> m3 = AllOf(greater_than_5, m2);
2206
2207 // Tests that BothOf works when composing itself.
2208 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2209 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2210}
2211
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002212TEST(AllOfTest, ExplainsResult) {
2213 Matcher<int> m;
2214
2215 // Successful match. Both matchers need to explain. The second
2216 // matcher doesn't give an explanation, so only the first matcher's
2217 // explanation is printed.
2218 m = AllOf(GreaterThan(10), Lt(30));
2219 EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2220
2221 // Successful match. Both matchers need to explain.
2222 m = AllOf(GreaterThan(10), GreaterThan(20));
2223 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2224 Explain(m, 30));
2225
2226 // Successful match. All matchers need to explain. The second
2227 // matcher doesn't given an explanation.
2228 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2229 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2230 Explain(m, 25));
2231
2232 // Successful match. All matchers need to explain.
2233 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2234 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2235 "and which is 10 more than 30",
2236 Explain(m, 40));
2237
2238 // Failed match. The first matcher, which failed, needs to
2239 // explain.
2240 m = AllOf(GreaterThan(10), GreaterThan(20));
2241 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2242
2243 // Failed match. The second matcher, which failed, needs to
2244 // explain. Since it doesn't given an explanation, nothing is
2245 // printed.
2246 m = AllOf(GreaterThan(10), Lt(30));
2247 EXPECT_EQ("", Explain(m, 40));
2248
2249 // Failed match. The second matcher, which failed, needs to
2250 // explain.
2251 m = AllOf(GreaterThan(10), GreaterThan(20));
2252 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2253}
2254
zhanyong.wan02c15052010-06-09 19:21:30 +00002255// Helper to allow easy testing of AnyOf matchers with num parameters.
2256void AnyOfMatches(int num, const Matcher<int>& m) {
2257 SCOPED_TRACE(Describe(m));
2258 EXPECT_FALSE(m.Matches(0));
2259 for (int i = 1; i <= num; ++i) {
2260 EXPECT_TRUE(m.Matches(i));
2261 }
2262 EXPECT_FALSE(m.Matches(num + 1));
2263}
2264
shiqiane35fdd92008-12-10 05:08:54 +00002265// Tests that AnyOf(m1, ..., mn) matches any value that matches at
2266// least one of the given matchers.
2267TEST(AnyOfTest, MatchesWhenAnyMatches) {
2268 Matcher<int> m;
2269 m = AnyOf(Le(1), Ge(3));
2270 EXPECT_TRUE(m.Matches(1));
2271 EXPECT_TRUE(m.Matches(4));
2272 EXPECT_FALSE(m.Matches(2));
2273
2274 m = AnyOf(Lt(0), Eq(1), Eq(2));
2275 EXPECT_TRUE(m.Matches(-1));
2276 EXPECT_TRUE(m.Matches(1));
2277 EXPECT_TRUE(m.Matches(2));
2278 EXPECT_FALSE(m.Matches(0));
2279
2280 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2281 EXPECT_TRUE(m.Matches(-1));
2282 EXPECT_TRUE(m.Matches(1));
2283 EXPECT_TRUE(m.Matches(2));
2284 EXPECT_TRUE(m.Matches(3));
2285 EXPECT_FALSE(m.Matches(0));
2286
2287 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2288 EXPECT_TRUE(m.Matches(0));
2289 EXPECT_TRUE(m.Matches(11));
2290 EXPECT_TRUE(m.Matches(3));
2291 EXPECT_FALSE(m.Matches(2));
zhanyong.wan02c15052010-06-09 19:21:30 +00002292
2293 // The following tests for varying number of sub-matchers. Due to the way
2294 // the sub-matchers are handled it is enough to test every sub-matcher once
2295 // with sub-matchers using the same matcher type. Varying matcher types are
2296 // checked for above.
2297 AnyOfMatches(2, AnyOf(1, 2));
2298 AnyOfMatches(3, AnyOf(1, 2, 3));
2299 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2300 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2301 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2302 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2303 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2304 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2305 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
shiqiane35fdd92008-12-10 05:08:54 +00002306}
2307
zhanyong.wan616180e2013-06-18 18:49:51 +00002308#if GTEST_LANG_CXX11
2309// Tests the variadic version of the AnyOfMatcher.
2310TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2311 // Also make sure AnyOf is defined in the right namespace and does not depend
2312 // on ADL.
2313 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2314
2315 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))"));
2316 AnyOfMatches(11, m);
2317 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2318 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2319 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2320 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2321 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2322}
2323
2324#endif // GTEST_LANG_CXX11
2325
shiqiane35fdd92008-12-10 05:08:54 +00002326// Tests that AnyOf(m1, ..., mn) describes itself properly.
2327TEST(AnyOfTest, CanDescribeSelf) {
2328 Matcher<int> m;
2329 m = AnyOf(Le(1), Ge(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002330 EXPECT_EQ("(is <= 1) or (is >= 3)",
shiqiane35fdd92008-12-10 05:08:54 +00002331 Describe(m));
2332
2333 m = AnyOf(Lt(0), Eq(1), Eq(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002334 EXPECT_EQ("(is < 0) or "
shiqiane35fdd92008-12-10 05:08:54 +00002335 "((is equal to 1) or (is equal to 2))",
2336 Describe(m));
2337
2338 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002339 EXPECT_EQ("((is < 0) or "
2340 "(is equal to 1)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002341 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002342 "(is equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002343 Describe(m));
2344
2345 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002346 EXPECT_EQ("((is <= 0) or "
2347 "(is > 10)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002348 "((is equal to 3) or "
2349 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002350 "(is equal to 7)))",
shiqiane35fdd92008-12-10 05:08:54 +00002351 Describe(m));
2352}
2353
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002354// Tests that AnyOf(m1, ..., mn) describes its negation properly.
2355TEST(AnyOfTest, CanDescribeNegation) {
2356 Matcher<int> m;
2357 m = AnyOf(Le(1), Ge(3));
2358 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2359 DescribeNegation(m));
2360
2361 m = AnyOf(Lt(0), Eq(1), Eq(2));
2362 EXPECT_EQ("(isn't < 0) and "
2363 "((isn't equal to 1) and (isn't equal to 2))",
2364 DescribeNegation(m));
2365
2366 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002367 EXPECT_EQ("((isn't < 0) and "
2368 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002369 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002370 "(isn't equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002371 DescribeNegation(m));
2372
2373 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002374 EXPECT_EQ("((isn't <= 0) and "
2375 "(isn't > 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002376 "((isn't equal to 3) and "
2377 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002378 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002379 DescribeNegation(m));
2380}
2381
zhanyong.wan18490652009-05-11 18:54:08 +00002382// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2383TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2384 // greater_than_5 and less_than_10 are monomorphic matchers.
2385 Matcher<int> greater_than_5 = Gt(5);
2386 Matcher<int> less_than_10 = Lt(10);
2387
2388 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2389 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2390 Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2391
2392 // Tests that EitherOf works when composing itself.
2393 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2394 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2395}
2396
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002397TEST(AnyOfTest, ExplainsResult) {
2398 Matcher<int> m;
2399
2400 // Failed match. Both matchers need to explain. The second
2401 // matcher doesn't give an explanation, so only the first matcher's
2402 // explanation is printed.
2403 m = AnyOf(GreaterThan(10), Lt(0));
2404 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2405
2406 // Failed match. Both matchers need to explain.
2407 m = AnyOf(GreaterThan(10), GreaterThan(20));
2408 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2409 Explain(m, 5));
2410
2411 // Failed match. All matchers need to explain. The second
2412 // matcher doesn't given an explanation.
2413 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2414 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2415 Explain(m, 5));
2416
2417 // Failed match. All matchers need to explain.
2418 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2419 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2420 "and which is 25 less than 30",
2421 Explain(m, 5));
2422
2423 // Successful match. The first matcher, which succeeded, needs to
2424 // explain.
2425 m = AnyOf(GreaterThan(10), GreaterThan(20));
2426 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2427
2428 // Successful match. The second matcher, which succeeded, needs to
2429 // explain. Since it doesn't given an explanation, nothing is
2430 // printed.
2431 m = AnyOf(GreaterThan(10), Lt(30));
2432 EXPECT_EQ("", Explain(m, 0));
2433
2434 // Successful match. The second matcher, which succeeded, needs to
2435 // explain.
2436 m = AnyOf(GreaterThan(30), GreaterThan(20));
2437 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2438}
2439
shiqiane35fdd92008-12-10 05:08:54 +00002440// The following predicate function and predicate functor are for
2441// testing the Truly(predicate) matcher.
2442
2443// Returns non-zero if the input is positive. Note that the return
2444// type of this function is not bool. It's OK as Truly() accepts any
2445// unary function or functor whose return type can be implicitly
2446// converted to bool.
2447int IsPositive(double x) {
2448 return x > 0 ? 1 : 0;
2449}
2450
2451// This functor returns true if the input is greater than the given
2452// number.
2453class IsGreaterThan {
2454 public:
2455 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2456
2457 bool operator()(int n) const { return n > threshold_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002458
shiqiane35fdd92008-12-10 05:08:54 +00002459 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002460 int threshold_;
shiqiane35fdd92008-12-10 05:08:54 +00002461};
2462
2463// For testing Truly().
2464const int foo = 0;
2465
2466// This predicate returns true iff the argument references foo and has
2467// a zero value.
2468bool ReferencesFooAndIsZero(const int& n) {
2469 return (&n == &foo) && (n == 0);
2470}
2471
2472// Tests that Truly(predicate) matches what satisfies the given
2473// predicate.
2474TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2475 Matcher<double> m = Truly(IsPositive);
2476 EXPECT_TRUE(m.Matches(2.0));
2477 EXPECT_FALSE(m.Matches(-1.5));
2478}
2479
2480// Tests that Truly(predicate_functor) works too.
2481TEST(TrulyTest, CanBeUsedWithFunctor) {
2482 Matcher<int> m = Truly(IsGreaterThan(5));
2483 EXPECT_TRUE(m.Matches(6));
2484 EXPECT_FALSE(m.Matches(4));
2485}
2486
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00002487// A class that can be implicitly converted to bool.
2488class ConvertibleToBool {
2489 public:
2490 explicit ConvertibleToBool(int number) : number_(number) {}
2491 operator bool() const { return number_ != 0; }
2492
2493 private:
2494 int number_;
2495};
2496
2497ConvertibleToBool IsNotZero(int number) {
2498 return ConvertibleToBool(number);
2499}
2500
2501// Tests that the predicate used in Truly() may return a class that's
2502// implicitly convertible to bool, even when the class has no
2503// operator!().
2504TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2505 Matcher<int> m = Truly(IsNotZero);
2506 EXPECT_TRUE(m.Matches(1));
2507 EXPECT_FALSE(m.Matches(0));
2508}
2509
shiqiane35fdd92008-12-10 05:08:54 +00002510// Tests that Truly(predicate) can describe itself properly.
2511TEST(TrulyTest, CanDescribeSelf) {
2512 Matcher<double> m = Truly(IsPositive);
2513 EXPECT_EQ("satisfies the given predicate",
2514 Describe(m));
2515}
2516
2517// Tests that Truly(predicate) works when the matcher takes its
2518// argument by reference.
2519TEST(TrulyTest, WorksForByRefArguments) {
2520 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2521 EXPECT_TRUE(m.Matches(foo));
2522 int n = 0;
2523 EXPECT_FALSE(m.Matches(n));
2524}
2525
2526// Tests that Matches(m) is a predicate satisfied by whatever that
2527// matches matcher m.
2528TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2529 EXPECT_TRUE(Matches(Ge(0))(1));
2530 EXPECT_FALSE(Matches(Eq('a'))('b'));
2531}
2532
2533// Tests that Matches(m) works when the matcher takes its argument by
2534// reference.
2535TEST(MatchesTest, WorksOnByRefArguments) {
2536 int m = 0, n = 0;
2537 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2538 EXPECT_FALSE(Matches(Ref(m))(n));
2539}
2540
2541// Tests that a Matcher on non-reference type can be used in
2542// Matches().
2543TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
2544 Matcher<int> eq5 = Eq(5);
2545 EXPECT_TRUE(Matches(eq5)(5));
2546 EXPECT_FALSE(Matches(eq5)(2));
2547}
2548
zhanyong.wanb8243162009-06-04 05:48:20 +00002549// Tests Value(value, matcher). Since Value() is a simple wrapper for
2550// Matches(), which has been tested already, we don't spend a lot of
2551// effort on testing Value().
2552TEST(ValueTest, WorksWithPolymorphicMatcher) {
2553 EXPECT_TRUE(Value("hi", StartsWith("h")));
2554 EXPECT_FALSE(Value(5, Gt(10)));
2555}
2556
2557TEST(ValueTest, WorksWithMonomorphicMatcher) {
2558 const Matcher<int> is_zero = Eq(0);
2559 EXPECT_TRUE(Value(0, is_zero));
2560 EXPECT_FALSE(Value('a', is_zero));
2561
2562 int n = 0;
2563 const Matcher<const int&> ref_n = Ref(n);
2564 EXPECT_TRUE(Value(n, ref_n));
2565 EXPECT_FALSE(Value(1, ref_n));
2566}
2567
zhanyong.wana862f1d2010-03-15 21:23:04 +00002568TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002569 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002570 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002571 EXPECT_EQ("% 2 == 0", listener1.str());
2572
2573 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002574 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002575 EXPECT_EQ("", listener2.str());
2576}
2577
zhanyong.wana862f1d2010-03-15 21:23:04 +00002578TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002579 const Matcher<int> is_even = PolymorphicIsEven();
2580 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002581 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002582 EXPECT_EQ("% 2 == 0", listener1.str());
2583
2584 const Matcher<const double&> is_zero = Eq(0);
2585 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002586 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002587 EXPECT_EQ("", listener2.str());
2588}
2589
zhanyong.wana862f1d2010-03-15 21:23:04 +00002590MATCHER_P(Really, inner_matcher, "") {
2591 return ExplainMatchResult(inner_matcher, arg, result_listener);
2592}
2593
2594TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
2595 EXPECT_THAT(0, Really(Eq(0)));
2596}
2597
zhanyong.wanbf550852009-06-09 06:09:53 +00002598TEST(AllArgsTest, WorksForTuple) {
2599 EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
2600 EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
2601}
2602
2603TEST(AllArgsTest, WorksForNonTuple) {
2604 EXPECT_THAT(42, AllArgs(Gt(0)));
2605 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
2606}
2607
2608class AllArgsHelper {
2609 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002610 AllArgsHelper() {}
2611
zhanyong.wanbf550852009-06-09 06:09:53 +00002612 MOCK_METHOD2(Helper, int(char x, int y));
zhanyong.wan32de5f52009-12-23 00:13:23 +00002613
2614 private:
2615 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
zhanyong.wanbf550852009-06-09 06:09:53 +00002616};
2617
2618TEST(AllArgsTest, WorksInWithClause) {
2619 AllArgsHelper helper;
2620 ON_CALL(helper, Helper(_, _))
2621 .With(AllArgs(Lt()))
2622 .WillByDefault(Return(1));
2623 EXPECT_CALL(helper, Helper(_, _));
2624 EXPECT_CALL(helper, Helper(_, _))
2625 .With(AllArgs(Gt()))
2626 .WillOnce(Return(2));
2627
2628 EXPECT_EQ(1, helper.Helper('\1', 2));
2629 EXPECT_EQ(2, helper.Helper('a', 1));
2630}
2631
shiqiane35fdd92008-12-10 05:08:54 +00002632// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2633// matches the matcher.
2634TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
2635 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
2636 ASSERT_THAT("Foo", EndsWith("oo"));
2637 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
2638 EXPECT_THAT("Hello", StartsWith("Hell"));
2639}
2640
2641// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2642// doesn't match the matcher.
2643TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
2644 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
2645 // which cannot reference auto variables.
zhanyong.wan736baa82010-09-27 17:44:16 +00002646 static unsigned short n; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00002647 n = 5;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002648
2649 // VC++ prior to version 8.0 SP1 has a bug where it will not see any
2650 // functions declared in the namespace scope from within nested classes.
2651 // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
2652 // namespace-level functions invoked inside them need to be explicitly
2653 // resolved.
2654 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
shiqiane35fdd92008-12-10 05:08:54 +00002655 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002656 "Expected: is > 10\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002657 " Actual: 5" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002658 n = 0;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002659 EXPECT_NONFATAL_FAILURE(
2660 EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
2661 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002662 "Expected: (is <= 7) and (is >= 5)\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002663 " Actual: 0" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002664}
2665
2666// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
2667// has a reference type.
2668TEST(MatcherAssertionTest, WorksForByRefArguments) {
2669 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
2670 // reference auto variables.
2671 static int n;
2672 n = 0;
2673 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002674 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
shiqiane35fdd92008-12-10 05:08:54 +00002675 "Value of: n\n"
2676 "Expected: does not reference the variable @");
2677 // Tests the "Actual" part.
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002678 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
zhanyong.wan736baa82010-09-27 17:44:16 +00002679 "Actual: 0" + OfType("int") + ", which is located @");
shiqiane35fdd92008-12-10 05:08:54 +00002680}
2681
zhanyong.wan95b12332009-09-25 18:55:50 +00002682#if !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002683// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
2684// monomorphic.
zhanyong.wan95b12332009-09-25 18:55:50 +00002685
2686// ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
2687// Symbian compiler: it tries to compile
2688// template<T, U> class MatcherCastImpl { ...
zhanyong.wandb22c222010-01-28 21:52:29 +00002689// virtual bool MatchAndExplain(T x, ...) const {
2690// return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
zhanyong.wan95b12332009-09-25 18:55:50 +00002691// with U == string and T == const char*
2692// With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
2693// the compiler silently crashes with no output.
2694// If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
2695// the code compiles but the converted string is bogus.
shiqiane35fdd92008-12-10 05:08:54 +00002696TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
2697 Matcher<const char*> starts_with_he = StartsWith("he");
2698 ASSERT_THAT("hello", starts_with_he);
2699
2700 Matcher<const string&> ends_with_ok = EndsWith("ok");
2701 ASSERT_THAT("book", ends_with_ok);
zhanyong.wan736baa82010-09-27 17:44:16 +00002702 const string bad = "bad";
2703 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
2704 "Value of: bad\n"
2705 "Expected: ends with \"ok\"\n"
2706 " Actual: \"bad\"");
shiqiane35fdd92008-12-10 05:08:54 +00002707 Matcher<int> is_greater_than_5 = Gt(5);
2708 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
2709 "Value of: 5\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002710 "Expected: is > 5\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002711 " Actual: 5" + OfType("int"));
shiqiane35fdd92008-12-10 05:08:54 +00002712}
zhanyong.wan95b12332009-09-25 18:55:50 +00002713#endif // !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002714
2715// Tests floating-point matchers.
2716template <typename RawType>
2717class FloatingPointTest : public testing::Test {
2718 protected:
zhanyong.wan35877b72013-09-18 17:51:08 +00002719 typedef testing::internal::FloatingPoint<RawType> Floating;
shiqiane35fdd92008-12-10 05:08:54 +00002720 typedef typename Floating::Bits Bits;
2721
zhanyong.wan35877b72013-09-18 17:51:08 +00002722 FloatingPointTest()
2723 : max_ulps_(Floating::kMaxUlps),
2724 zero_bits_(Floating(0).bits()),
2725 one_bits_(Floating(1).bits()),
2726 infinity_bits_(Floating(Floating::Infinity()).bits()),
2727 close_to_positive_zero_(
2728 Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
2729 close_to_negative_zero_(
2730 -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
2731 further_from_negative_zero_(-Floating::ReinterpretBits(
2732 zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
2733 close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
2734 further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
2735 infinity_(Floating::Infinity()),
2736 close_to_infinity_(
2737 Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
2738 further_from_infinity_(
2739 Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
2740 max_(Floating::Max()),
2741 nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
2742 nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
shiqiane35fdd92008-12-10 05:08:54 +00002743 }
2744
2745 void TestSize() {
2746 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2747 }
2748
2749 // A battery of tests for FloatingEqMatcher::Matches.
2750 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2751 void TestMatches(
2752 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
2753 Matcher<RawType> m1 = matcher_maker(0.0);
2754 EXPECT_TRUE(m1.Matches(-0.0));
2755 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
2756 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
2757 EXPECT_FALSE(m1.Matches(1.0));
2758
2759 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
2760 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
2761
2762 Matcher<RawType> m3 = matcher_maker(1.0);
2763 EXPECT_TRUE(m3.Matches(close_to_one_));
2764 EXPECT_FALSE(m3.Matches(further_from_one_));
2765
2766 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
2767 EXPECT_FALSE(m3.Matches(0.0));
2768
2769 Matcher<RawType> m4 = matcher_maker(-infinity_);
2770 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
2771
2772 Matcher<RawType> m5 = matcher_maker(infinity_);
2773 EXPECT_TRUE(m5.Matches(close_to_infinity_));
2774
2775 // This is interesting as the representations of infinity_ and nan1_
2776 // are only 1 DLP apart.
2777 EXPECT_FALSE(m5.Matches(nan1_));
2778
2779 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2780 // some cases.
2781 Matcher<const RawType&> m6 = matcher_maker(0.0);
2782 EXPECT_TRUE(m6.Matches(-0.0));
2783 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
2784 EXPECT_FALSE(m6.Matches(1.0));
2785
2786 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2787 // cases.
2788 Matcher<RawType&> m7 = matcher_maker(0.0);
2789 RawType x = 0.0;
2790 EXPECT_TRUE(m7.Matches(x));
2791 x = 0.01f;
2792 EXPECT_FALSE(m7.Matches(x));
2793 }
2794
2795 // Pre-calculated numbers to be used by the tests.
2796
zhanyong.wan35877b72013-09-18 17:51:08 +00002797 const size_t max_ulps_;
shiqiane35fdd92008-12-10 05:08:54 +00002798
zhanyong.wan35877b72013-09-18 17:51:08 +00002799 const Bits zero_bits_; // The bits that represent 0.0.
2800 const Bits one_bits_; // The bits that represent 1.0.
2801 const Bits infinity_bits_; // The bits that represent +infinity.
shiqiane35fdd92008-12-10 05:08:54 +00002802
zhanyong.wan35877b72013-09-18 17:51:08 +00002803 // Some numbers close to 0.0.
2804 const RawType close_to_positive_zero_;
2805 const RawType close_to_negative_zero_;
2806 const RawType further_from_negative_zero_;
shiqiane35fdd92008-12-10 05:08:54 +00002807
zhanyong.wan35877b72013-09-18 17:51:08 +00002808 // Some numbers close to 1.0.
2809 const RawType close_to_one_;
2810 const RawType further_from_one_;
2811
2812 // Some numbers close to +infinity.
2813 const RawType infinity_;
2814 const RawType close_to_infinity_;
2815 const RawType further_from_infinity_;
2816
2817 // Maximum representable value that's not infinity.
2818 const RawType max_;
2819
2820 // Some NaNs.
2821 const RawType nan1_;
2822 const RawType nan2_;
shiqiane35fdd92008-12-10 05:08:54 +00002823};
2824
zhanyong.wan616180e2013-06-18 18:49:51 +00002825// Tests floating-point matchers with fixed epsilons.
2826template <typename RawType>
2827class FloatingPointNearTest : public FloatingPointTest<RawType> {
2828 protected:
2829 typedef FloatingPointTest<RawType> ParentType;
2830
2831 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
2832 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2833 void TestNearMatches(
2834 testing::internal::FloatingEqMatcher<RawType>
2835 (*matcher_maker)(RawType, RawType)) {
2836 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
2837 EXPECT_TRUE(m1.Matches(0.0));
2838 EXPECT_TRUE(m1.Matches(-0.0));
2839 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
2840 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
2841 EXPECT_FALSE(m1.Matches(1.0));
2842
2843 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
2844 EXPECT_TRUE(m2.Matches(0.0));
2845 EXPECT_TRUE(m2.Matches(-0.0));
2846 EXPECT_TRUE(m2.Matches(1.0));
2847 EXPECT_TRUE(m2.Matches(-1.0));
2848 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
2849 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
2850
2851 // Check that inf matches inf, regardless of the of the specified max
2852 // absolute error.
2853 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
2854 EXPECT_TRUE(m3.Matches(ParentType::infinity_));
2855 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
2856 EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
2857
2858 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
2859 EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
2860 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
2861 EXPECT_FALSE(m4.Matches(ParentType::infinity_));
2862
2863 // Test various overflow scenarios.
zhanyong.wan35877b72013-09-18 17:51:08 +00002864 Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
2865 EXPECT_TRUE(m5.Matches(ParentType::max_));
2866 EXPECT_FALSE(m5.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002867
zhanyong.wan35877b72013-09-18 17:51:08 +00002868 Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
2869 EXPECT_FALSE(m6.Matches(ParentType::max_));
2870 EXPECT_TRUE(m6.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002871
zhanyong.wan35877b72013-09-18 17:51:08 +00002872 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
2873 EXPECT_TRUE(m7.Matches(ParentType::max_));
2874 EXPECT_FALSE(m7.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002875
zhanyong.wan35877b72013-09-18 17:51:08 +00002876 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
2877 EXPECT_FALSE(m8.Matches(ParentType::max_));
2878 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002879
2880 // The difference between max() and -max() normally overflows to infinity,
2881 // but it should still match if the max_abs_error is also infinity.
2882 Matcher<RawType> m9 = matcher_maker(
zhanyong.wan35877b72013-09-18 17:51:08 +00002883 ParentType::max_, ParentType::infinity_);
2884 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002885
2886 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2887 // some cases.
2888 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
2889 EXPECT_TRUE(m10.Matches(-0.0));
2890 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
2891 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
2892
2893 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2894 // cases.
2895 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
2896 RawType x = 0.0;
2897 EXPECT_TRUE(m11.Matches(x));
2898 x = 1.0f;
2899 EXPECT_TRUE(m11.Matches(x));
2900 x = -1.0f;
2901 EXPECT_TRUE(m11.Matches(x));
2902 x = 1.1f;
2903 EXPECT_FALSE(m11.Matches(x));
2904 x = -1.1f;
2905 EXPECT_FALSE(m11.Matches(x));
2906 }
2907};
2908
shiqiane35fdd92008-12-10 05:08:54 +00002909// Instantiate FloatingPointTest for testing floats.
2910typedef FloatingPointTest<float> FloatTest;
2911
2912TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
2913 TestMatches(&FloatEq);
2914}
2915
2916TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
2917 TestMatches(&NanSensitiveFloatEq);
2918}
2919
2920TEST_F(FloatTest, FloatEqCannotMatchNaN) {
2921 // FloatEq never matches NaN.
2922 Matcher<float> m = FloatEq(nan1_);
2923 EXPECT_FALSE(m.Matches(nan1_));
2924 EXPECT_FALSE(m.Matches(nan2_));
2925 EXPECT_FALSE(m.Matches(1.0));
2926}
2927
2928TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
2929 // NanSensitiveFloatEq will match NaN.
2930 Matcher<float> m = NanSensitiveFloatEq(nan1_);
2931 EXPECT_TRUE(m.Matches(nan1_));
2932 EXPECT_TRUE(m.Matches(nan2_));
2933 EXPECT_FALSE(m.Matches(1.0));
2934}
2935
2936TEST_F(FloatTest, FloatEqCanDescribeSelf) {
2937 Matcher<float> m1 = FloatEq(2.0f);
2938 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002939 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002940
2941 Matcher<float> m2 = FloatEq(0.5f);
2942 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002943 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002944
2945 Matcher<float> m3 = FloatEq(nan1_);
2946 EXPECT_EQ("never matches", Describe(m3));
2947 EXPECT_EQ("is anything", DescribeNegation(m3));
2948}
2949
2950TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
2951 Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
2952 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002953 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002954
2955 Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
2956 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002957 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002958
2959 Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
2960 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002961 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00002962}
2963
zhanyong.wan616180e2013-06-18 18:49:51 +00002964// Instantiate FloatingPointTest for testing floats with a user-specified
2965// max absolute error.
2966typedef FloatingPointNearTest<float> FloatNearTest;
2967
2968TEST_F(FloatNearTest, FloatNearMatches) {
2969 TestNearMatches(&FloatNear);
2970}
2971
2972TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
2973 TestNearMatches(&NanSensitiveFloatNear);
2974}
2975
2976TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
2977 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
2978 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2979 EXPECT_EQ(
2980 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2981
2982 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
2983 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2984 EXPECT_EQ(
2985 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2986
2987 Matcher<float> m3 = FloatNear(nan1_, 0.0);
2988 EXPECT_EQ("never matches", Describe(m3));
2989 EXPECT_EQ("is anything", DescribeNegation(m3));
2990}
2991
2992TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
2993 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
2994 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2995 EXPECT_EQ(
2996 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2997
2998 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
2999 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3000 EXPECT_EQ(
3001 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3002
3003 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
3004 EXPECT_EQ("is NaN", Describe(m3));
3005 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3006}
3007
3008TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
3009 // FloatNear never matches NaN.
3010 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
3011 EXPECT_FALSE(m.Matches(nan1_));
3012 EXPECT_FALSE(m.Matches(nan2_));
3013 EXPECT_FALSE(m.Matches(1.0));
3014}
3015
3016TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
3017 // NanSensitiveFloatNear will match NaN.
3018 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
3019 EXPECT_TRUE(m.Matches(nan1_));
3020 EXPECT_TRUE(m.Matches(nan2_));
3021 EXPECT_FALSE(m.Matches(1.0));
3022}
3023
shiqiane35fdd92008-12-10 05:08:54 +00003024// Instantiate FloatingPointTest for testing doubles.
3025typedef FloatingPointTest<double> DoubleTest;
3026
3027TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
3028 TestMatches(&DoubleEq);
3029}
3030
3031TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
3032 TestMatches(&NanSensitiveDoubleEq);
3033}
3034
3035TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
3036 // DoubleEq never matches NaN.
3037 Matcher<double> m = DoubleEq(nan1_);
3038 EXPECT_FALSE(m.Matches(nan1_));
3039 EXPECT_FALSE(m.Matches(nan2_));
3040 EXPECT_FALSE(m.Matches(1.0));
3041}
3042
3043TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3044 // NanSensitiveDoubleEq will match NaN.
3045 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
3046 EXPECT_TRUE(m.Matches(nan1_));
3047 EXPECT_TRUE(m.Matches(nan2_));
3048 EXPECT_FALSE(m.Matches(1.0));
3049}
3050
3051TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3052 Matcher<double> m1 = DoubleEq(2.0);
3053 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003054 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003055
3056 Matcher<double> m2 = DoubleEq(0.5);
3057 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003058 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003059
3060 Matcher<double> m3 = DoubleEq(nan1_);
3061 EXPECT_EQ("never matches", Describe(m3));
3062 EXPECT_EQ("is anything", DescribeNegation(m3));
3063}
3064
3065TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3066 Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3067 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003068 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003069
3070 Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3071 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003072 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003073
3074 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3075 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003076 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00003077}
3078
zhanyong.wan616180e2013-06-18 18:49:51 +00003079// Instantiate FloatingPointTest for testing floats with a user-specified
3080// max absolute error.
3081typedef FloatingPointNearTest<double> DoubleNearTest;
3082
3083TEST_F(DoubleNearTest, DoubleNearMatches) {
3084 TestNearMatches(&DoubleNear);
3085}
3086
3087TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3088 TestNearMatches(&NanSensitiveDoubleNear);
3089}
3090
3091TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3092 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3093 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3094 EXPECT_EQ(
3095 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3096
3097 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3098 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3099 EXPECT_EQ(
3100 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3101
3102 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3103 EXPECT_EQ("never matches", Describe(m3));
3104 EXPECT_EQ("is anything", DescribeNegation(m3));
3105}
3106
kosak6b817802015-01-08 02:38:14 +00003107TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
3108 EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
3109 EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
3110 EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
3111
3112 const string explanation = Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
3113 // Different C++ implementations may print floating-point numbers
3114 // slightly differently.
3115 EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC
3116 explanation == "which is 1.2e-010 from 2.1") // MSVC
3117 << " where explanation is \"" << explanation << "\".";
3118}
3119
zhanyong.wan616180e2013-06-18 18:49:51 +00003120TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3121 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3122 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3123 EXPECT_EQ(
3124 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3125
3126 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3127 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3128 EXPECT_EQ(
3129 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3130
3131 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3132 EXPECT_EQ("is NaN", Describe(m3));
3133 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3134}
3135
3136TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3137 // DoubleNear never matches NaN.
3138 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3139 EXPECT_FALSE(m.Matches(nan1_));
3140 EXPECT_FALSE(m.Matches(nan2_));
3141 EXPECT_FALSE(m.Matches(1.0));
3142}
3143
3144TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3145 // NanSensitiveDoubleNear will match NaN.
3146 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3147 EXPECT_TRUE(m.Matches(nan1_));
3148 EXPECT_TRUE(m.Matches(nan2_));
3149 EXPECT_FALSE(m.Matches(1.0));
3150}
3151
shiqiane35fdd92008-12-10 05:08:54 +00003152TEST(PointeeTest, RawPointer) {
3153 const Matcher<int*> m = Pointee(Ge(0));
3154
3155 int n = 1;
3156 EXPECT_TRUE(m.Matches(&n));
3157 n = -1;
3158 EXPECT_FALSE(m.Matches(&n));
3159 EXPECT_FALSE(m.Matches(NULL));
3160}
3161
3162TEST(PointeeTest, RawPointerToConst) {
3163 const Matcher<const double*> m = Pointee(Ge(0));
3164
3165 double x = 1;
3166 EXPECT_TRUE(m.Matches(&x));
3167 x = -1;
3168 EXPECT_FALSE(m.Matches(&x));
3169 EXPECT_FALSE(m.Matches(NULL));
3170}
3171
3172TEST(PointeeTest, ReferenceToConstRawPointer) {
3173 const Matcher<int* const &> m = Pointee(Ge(0));
3174
3175 int n = 1;
3176 EXPECT_TRUE(m.Matches(&n));
3177 n = -1;
3178 EXPECT_FALSE(m.Matches(&n));
3179 EXPECT_FALSE(m.Matches(NULL));
3180}
3181
3182TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3183 const Matcher<double* &> m = Pointee(Ge(0));
3184
3185 double x = 1.0;
3186 double* p = &x;
3187 EXPECT_TRUE(m.Matches(p));
3188 x = -1;
3189 EXPECT_FALSE(m.Matches(p));
3190 p = NULL;
3191 EXPECT_FALSE(m.Matches(p));
3192}
3193
billydonahue1f5fdea2014-05-19 17:54:51 +00003194
3195MATCHER_P(FieldIIs, inner_matcher, "") {
3196 return ExplainMatchResult(inner_matcher, arg.i, result_listener);
3197}
3198
3199TEST(WhenDynamicCastToTest, SameType) {
3200 Derived derived;
3201 derived.i = 4;
3202
3203 // Right type. A pointer is passed down.
3204 Base* as_base_ptr = &derived;
3205 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
3206 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
3207 EXPECT_THAT(as_base_ptr,
3208 Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
3209}
3210
3211TEST(WhenDynamicCastToTest, WrongTypes) {
3212 Base base;
3213 Derived derived;
3214 OtherDerived other_derived;
3215
3216 // Wrong types. NULL is passed.
3217 EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3218 EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
3219 Base* as_base_ptr = &derived;
3220 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
3221 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
3222 as_base_ptr = &other_derived;
3223 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3224 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3225}
3226
3227TEST(WhenDynamicCastToTest, AlreadyNull) {
3228 // Already NULL.
3229 Base* as_base_ptr = NULL;
3230 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3231}
3232
3233struct AmbiguousCastTypes {
3234 class VirtualDerived : public virtual Base {};
3235 class DerivedSub1 : public VirtualDerived {};
3236 class DerivedSub2 : public VirtualDerived {};
3237 class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
3238};
3239
3240TEST(WhenDynamicCastToTest, AmbiguousCast) {
3241 AmbiguousCastTypes::DerivedSub1 sub1;
3242 AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
3243 // Multiply derived from Base. dynamic_cast<> returns NULL.
3244 Base* as_base_ptr =
3245 static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
3246 EXPECT_THAT(as_base_ptr,
3247 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
3248 as_base_ptr = &sub1;
3249 EXPECT_THAT(
3250 as_base_ptr,
3251 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
3252}
3253
3254TEST(WhenDynamicCastToTest, Describe) {
3255 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3256#if GTEST_HAS_RTTI
3257 const string prefix =
3258 "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
3259#else // GTEST_HAS_RTTI
3260 const string prefix = "when dynamic_cast, ";
3261#endif // GTEST_HAS_RTTI
3262 EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
3263 EXPECT_EQ(prefix + "does not point to a value that is anything",
3264 DescribeNegation(matcher));
3265}
3266
3267TEST(WhenDynamicCastToTest, Explain) {
3268 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3269 Base* null = NULL;
3270 EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
3271 Derived derived;
3272 EXPECT_TRUE(matcher.Matches(&derived));
3273 EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
3274
3275 // With references, the matcher itself can fail. Test for that one.
3276 Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
3277 EXPECT_THAT(Explain(ref_matcher, derived),
3278 HasSubstr("which cannot be dynamic_cast"));
3279}
3280
3281TEST(WhenDynamicCastToTest, GoodReference) {
3282 Derived derived;
3283 derived.i = 4;
3284 Base& as_base_ref = derived;
3285 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
3286 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
3287}
3288
3289TEST(WhenDynamicCastToTest, BadReference) {
3290 Derived derived;
3291 Base& as_base_ref = derived;
3292 EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
3293}
3294
vladlosevada23472012-08-14 15:38:49 +00003295// Minimal const-propagating pointer.
3296template <typename T>
3297class ConstPropagatingPtr {
3298 public:
3299 typedef T element_type;
3300
3301 ConstPropagatingPtr() : val_() {}
3302 explicit ConstPropagatingPtr(T* t) : val_(t) {}
3303 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3304
3305 T* get() { return val_; }
3306 T& operator*() { return *val_; }
3307 // Most smart pointers return non-const T* and T& from the next methods.
3308 const T* get() const { return val_; }
3309 const T& operator*() const { return *val_; }
3310
3311 private:
3312 T* val_;
3313};
3314
3315TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3316 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3317 int three = 3;
3318 const ConstPropagatingPtr<int> co(&three);
3319 ConstPropagatingPtr<int> o(&three);
3320 EXPECT_TRUE(m.Matches(o));
3321 EXPECT_TRUE(m.Matches(co));
3322 *o = 6;
3323 EXPECT_FALSE(m.Matches(o));
3324 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3325}
3326
shiqiane35fdd92008-12-10 05:08:54 +00003327TEST(PointeeTest, NeverMatchesNull) {
3328 const Matcher<const char*> m = Pointee(_);
3329 EXPECT_FALSE(m.Matches(NULL));
3330}
3331
3332// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3333TEST(PointeeTest, MatchesAgainstAValue) {
3334 const Matcher<int*> m = Pointee(5);
3335
3336 int n = 5;
3337 EXPECT_TRUE(m.Matches(&n));
3338 n = -1;
3339 EXPECT_FALSE(m.Matches(&n));
3340 EXPECT_FALSE(m.Matches(NULL));
3341}
3342
3343TEST(PointeeTest, CanDescribeSelf) {
3344 const Matcher<int*> m = Pointee(Gt(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003345 EXPECT_EQ("points to a value that is > 3", Describe(m));
3346 EXPECT_EQ("does not point to a value that is > 3",
shiqiane35fdd92008-12-10 05:08:54 +00003347 DescribeNegation(m));
3348}
3349
shiqiane35fdd92008-12-10 05:08:54 +00003350TEST(PointeeTest, CanExplainMatchResult) {
3351 const Matcher<const string*> m = Pointee(StartsWith("Hi"));
3352
3353 EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL)));
3354
zhanyong.wan736baa82010-09-27 17:44:16 +00003355 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
3356 long n = 3; // NOLINT
3357 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003358 Explain(m2, &n));
3359}
3360
3361TEST(PointeeTest, AlwaysExplainsPointee) {
3362 const Matcher<int*> m = Pointee(0);
3363 int n = 42;
zhanyong.wan736baa82010-09-27 17:44:16 +00003364 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
shiqiane35fdd92008-12-10 05:08:54 +00003365}
3366
3367// An uncopyable class.
3368class Uncopyable {
3369 public:
billydonahue1f5fdea2014-05-19 17:54:51 +00003370 Uncopyable() : value_(-1) {}
zhanyong.wan32de5f52009-12-23 00:13:23 +00003371 explicit Uncopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003372
3373 int value() const { return value_; }
billydonahue1f5fdea2014-05-19 17:54:51 +00003374 void set_value(int i) { value_ = i; }
3375
shiqiane35fdd92008-12-10 05:08:54 +00003376 private:
billydonahue1f5fdea2014-05-19 17:54:51 +00003377 int value_;
shiqiane35fdd92008-12-10 05:08:54 +00003378 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3379};
3380
3381// Returns true iff x.value() is positive.
3382bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3383
billydonahue1f5fdea2014-05-19 17:54:51 +00003384MATCHER_P(UncopyableIs, inner_matcher, "") {
3385 return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
3386}
3387
shiqiane35fdd92008-12-10 05:08:54 +00003388// A user-defined struct for testing Field().
3389struct AStruct {
3390 AStruct() : x(0), y(1.0), z(5), p(NULL) {}
3391 AStruct(const AStruct& rhs)
3392 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3393
3394 int x; // A non-const field.
3395 const double y; // A const field.
3396 Uncopyable z; // An uncopyable field.
3397 const char* p; // A pointer field.
zhanyong.wan32de5f52009-12-23 00:13:23 +00003398
3399 private:
3400 GTEST_DISALLOW_ASSIGN_(AStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003401};
3402
3403// A derived struct for testing Field().
3404struct DerivedStruct : public AStruct {
3405 char ch;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003406
3407 private:
3408 GTEST_DISALLOW_ASSIGN_(DerivedStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003409};
3410
3411// Tests that Field(&Foo::field, ...) works when field is non-const.
3412TEST(FieldTest, WorksForNonConstField) {
3413 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
3414
3415 AStruct a;
3416 EXPECT_TRUE(m.Matches(a));
3417 a.x = -1;
3418 EXPECT_FALSE(m.Matches(a));
3419}
3420
3421// Tests that Field(&Foo::field, ...) works when field is const.
3422TEST(FieldTest, WorksForConstField) {
3423 AStruct a;
3424
3425 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
3426 EXPECT_TRUE(m.Matches(a));
3427 m = Field(&AStruct::y, Le(0.0));
3428 EXPECT_FALSE(m.Matches(a));
3429}
3430
3431// Tests that Field(&Foo::field, ...) works when field is not copyable.
3432TEST(FieldTest, WorksForUncopyableField) {
3433 AStruct a;
3434
3435 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3436 EXPECT_TRUE(m.Matches(a));
3437 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3438 EXPECT_FALSE(m.Matches(a));
3439}
3440
3441// Tests that Field(&Foo::field, ...) works when field is a pointer.
3442TEST(FieldTest, WorksForPointerField) {
3443 // Matching against NULL.
3444 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
3445 AStruct a;
3446 EXPECT_TRUE(m.Matches(a));
3447 a.p = "hi";
3448 EXPECT_FALSE(m.Matches(a));
3449
3450 // Matching a pointer that is not NULL.
3451 m = Field(&AStruct::p, StartsWith("hi"));
3452 a.p = "hill";
3453 EXPECT_TRUE(m.Matches(a));
3454 a.p = "hole";
3455 EXPECT_FALSE(m.Matches(a));
3456}
3457
3458// Tests that Field() works when the object is passed by reference.
3459TEST(FieldTest, WorksForByRefArgument) {
3460 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3461
3462 AStruct a;
3463 EXPECT_TRUE(m.Matches(a));
3464 a.x = -1;
3465 EXPECT_FALSE(m.Matches(a));
3466}
3467
3468// Tests that Field(&Foo::field, ...) works when the argument's type
3469// is a sub-type of Foo.
3470TEST(FieldTest, WorksForArgumentOfSubType) {
3471 // Note that the matcher expects DerivedStruct but we say AStruct
3472 // inside Field().
3473 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
3474
3475 DerivedStruct d;
3476 EXPECT_TRUE(m.Matches(d));
3477 d.x = -1;
3478 EXPECT_FALSE(m.Matches(d));
3479}
3480
3481// Tests that Field(&Foo::field, m) works when field's type and m's
3482// argument type are compatible but not the same.
3483TEST(FieldTest, WorksForCompatibleMatcherType) {
3484 // The field is an int, but the inner matcher expects a signed char.
3485 Matcher<const AStruct&> m = Field(&AStruct::x,
3486 Matcher<signed char>(Ge(0)));
3487
3488 AStruct a;
3489 EXPECT_TRUE(m.Matches(a));
3490 a.x = -1;
3491 EXPECT_FALSE(m.Matches(a));
3492}
3493
3494// Tests that Field() can describe itself.
3495TEST(FieldTest, CanDescribeSelf) {
3496 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3497
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003498 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3499 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003500}
3501
3502// Tests that Field() can explain the match result.
3503TEST(FieldTest, CanExplainMatchResult) {
3504 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3505
3506 AStruct a;
3507 a.x = 1;
zhanyong.wan736baa82010-09-27 17:44:16 +00003508 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003509
3510 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003511 EXPECT_EQ(
3512 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
3513 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003514}
3515
3516// Tests that Field() works when the argument is a pointer to const.
3517TEST(FieldForPointerTest, WorksForPointerToConst) {
3518 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3519
3520 AStruct a;
3521 EXPECT_TRUE(m.Matches(&a));
3522 a.x = -1;
3523 EXPECT_FALSE(m.Matches(&a));
3524}
3525
3526// Tests that Field() works when the argument is a pointer to non-const.
3527TEST(FieldForPointerTest, WorksForPointerToNonConst) {
3528 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
3529
3530 AStruct a;
3531 EXPECT_TRUE(m.Matches(&a));
3532 a.x = -1;
3533 EXPECT_FALSE(m.Matches(&a));
3534}
3535
zhanyong.wan6953a722010-01-13 05:15:07 +00003536// Tests that Field() works when the argument is a reference to a const pointer.
3537TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
3538 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
3539
3540 AStruct a;
3541 EXPECT_TRUE(m.Matches(&a));
3542 a.x = -1;
3543 EXPECT_FALSE(m.Matches(&a));
3544}
3545
shiqiane35fdd92008-12-10 05:08:54 +00003546// Tests that Field() does not match the NULL pointer.
3547TEST(FieldForPointerTest, DoesNotMatchNull) {
3548 Matcher<const AStruct*> m = Field(&AStruct::x, _);
3549 EXPECT_FALSE(m.Matches(NULL));
3550}
3551
3552// Tests that Field(&Foo::field, ...) works when the argument's type
3553// is a sub-type of const Foo*.
3554TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
3555 // Note that the matcher expects DerivedStruct but we say AStruct
3556 // inside Field().
3557 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
3558
3559 DerivedStruct d;
3560 EXPECT_TRUE(m.Matches(&d));
3561 d.x = -1;
3562 EXPECT_FALSE(m.Matches(&d));
3563}
3564
3565// Tests that Field() can describe itself when used to match a pointer.
3566TEST(FieldForPointerTest, CanDescribeSelf) {
3567 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3568
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003569 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3570 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003571}
3572
3573// Tests that Field() can explain the result of matching a pointer.
3574TEST(FieldForPointerTest, CanExplainMatchResult) {
3575 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3576
3577 AStruct a;
3578 a.x = 1;
3579 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003580 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
3581 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003582
3583 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003584 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
3585 ", which is 1 more than 0", Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003586}
3587
3588// A user-defined class for testing Property().
3589class AClass {
3590 public:
3591 AClass() : n_(0) {}
3592
3593 // A getter that returns a non-reference.
3594 int n() const { return n_; }
3595
3596 void set_n(int new_n) { n_ = new_n; }
3597
3598 // A getter that returns a reference to const.
3599 const string& s() const { return s_; }
3600
3601 void set_s(const string& new_s) { s_ = new_s; }
3602
3603 // A getter that returns a reference to non-const.
3604 double& x() const { return x_; }
3605 private:
3606 int n_;
3607 string s_;
3608
3609 static double x_;
3610};
3611
3612double AClass::x_ = 0.0;
3613
3614// A derived class for testing Property().
3615class DerivedClass : public AClass {
kosak6414d802013-12-03 23:19:36 +00003616 public:
3617 int k() const { return k_; }
shiqiane35fdd92008-12-10 05:08:54 +00003618 private:
3619 int k_;
3620};
3621
3622// Tests that Property(&Foo::property, ...) works when property()
3623// returns a non-reference.
3624TEST(PropertyTest, WorksForNonReferenceProperty) {
3625 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3626
3627 AClass a;
3628 a.set_n(1);
3629 EXPECT_TRUE(m.Matches(a));
3630
3631 a.set_n(-1);
3632 EXPECT_FALSE(m.Matches(a));
3633}
3634
3635// Tests that Property(&Foo::property, ...) works when property()
3636// returns a reference to const.
3637TEST(PropertyTest, WorksForReferenceToConstProperty) {
3638 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
3639
3640 AClass a;
3641 a.set_s("hill");
3642 EXPECT_TRUE(m.Matches(a));
3643
3644 a.set_s("hole");
3645 EXPECT_FALSE(m.Matches(a));
3646}
3647
3648// Tests that Property(&Foo::property, ...) works when property()
3649// returns a reference to non-const.
3650TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
3651 double x = 0.0;
3652 AClass a;
3653
3654 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
3655 EXPECT_FALSE(m.Matches(a));
3656
3657 m = Property(&AClass::x, Not(Ref(x)));
3658 EXPECT_TRUE(m.Matches(a));
3659}
3660
3661// Tests that Property(&Foo::property, ...) works when the argument is
3662// passed by value.
3663TEST(PropertyTest, WorksForByValueArgument) {
3664 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
3665
3666 AClass a;
3667 a.set_s("hill");
3668 EXPECT_TRUE(m.Matches(a));
3669
3670 a.set_s("hole");
3671 EXPECT_FALSE(m.Matches(a));
3672}
3673
3674// Tests that Property(&Foo::property, ...) works when the argument's
3675// type is a sub-type of Foo.
3676TEST(PropertyTest, WorksForArgumentOfSubType) {
3677 // The matcher expects a DerivedClass, but inside the Property() we
3678 // say AClass.
3679 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
3680
3681 DerivedClass d;
3682 d.set_n(1);
3683 EXPECT_TRUE(m.Matches(d));
3684
3685 d.set_n(-1);
3686 EXPECT_FALSE(m.Matches(d));
3687}
3688
3689// Tests that Property(&Foo::property, m) works when property()'s type
3690// and m's argument type are compatible but different.
3691TEST(PropertyTest, WorksForCompatibleMatcherType) {
3692 // n() returns an int but the inner matcher expects a signed char.
3693 Matcher<const AClass&> m = Property(&AClass::n,
3694 Matcher<signed char>(Ge(0)));
3695
3696 AClass a;
3697 EXPECT_TRUE(m.Matches(a));
3698 a.set_n(-1);
3699 EXPECT_FALSE(m.Matches(a));
3700}
3701
3702// Tests that Property() can describe itself.
3703TEST(PropertyTest, CanDescribeSelf) {
3704 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3705
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003706 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3707 EXPECT_EQ("is an object whose given property isn't >= 0",
3708 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003709}
3710
3711// Tests that Property() can explain the match result.
3712TEST(PropertyTest, CanExplainMatchResult) {
3713 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3714
3715 AClass a;
3716 a.set_n(1);
zhanyong.wan736baa82010-09-27 17:44:16 +00003717 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003718
3719 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003720 EXPECT_EQ(
3721 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
3722 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003723}
3724
3725// Tests that Property() works when the argument is a pointer to const.
3726TEST(PropertyForPointerTest, WorksForPointerToConst) {
3727 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3728
3729 AClass a;
3730 a.set_n(1);
3731 EXPECT_TRUE(m.Matches(&a));
3732
3733 a.set_n(-1);
3734 EXPECT_FALSE(m.Matches(&a));
3735}
3736
3737// Tests that Property() works when the argument is a pointer to non-const.
3738TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
3739 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
3740
3741 AClass a;
3742 a.set_s("hill");
3743 EXPECT_TRUE(m.Matches(&a));
3744
3745 a.set_s("hole");
3746 EXPECT_FALSE(m.Matches(&a));
3747}
3748
zhanyong.wan6953a722010-01-13 05:15:07 +00003749// Tests that Property() works when the argument is a reference to a
3750// const pointer.
3751TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
3752 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
3753
3754 AClass a;
3755 a.set_s("hill");
3756 EXPECT_TRUE(m.Matches(&a));
3757
3758 a.set_s("hole");
3759 EXPECT_FALSE(m.Matches(&a));
3760}
3761
shiqiane35fdd92008-12-10 05:08:54 +00003762// Tests that Property() does not match the NULL pointer.
3763TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
3764 Matcher<const AClass*> m = Property(&AClass::x, _);
3765 EXPECT_FALSE(m.Matches(NULL));
3766}
3767
3768// Tests that Property(&Foo::property, ...) works when the argument's
3769// type is a sub-type of const Foo*.
3770TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
3771 // The matcher expects a DerivedClass, but inside the Property() we
3772 // say AClass.
3773 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
3774
3775 DerivedClass d;
3776 d.set_n(1);
3777 EXPECT_TRUE(m.Matches(&d));
3778
3779 d.set_n(-1);
3780 EXPECT_FALSE(m.Matches(&d));
3781}
3782
3783// Tests that Property() can describe itself when used to match a pointer.
3784TEST(PropertyForPointerTest, CanDescribeSelf) {
3785 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3786
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003787 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3788 EXPECT_EQ("is an object whose given property isn't >= 0",
3789 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003790}
3791
3792// Tests that Property() can explain the result of matching a pointer.
3793TEST(PropertyForPointerTest, CanExplainMatchResult) {
3794 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3795
3796 AClass a;
3797 a.set_n(1);
3798 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003799 EXPECT_EQ(
3800 "which points to an object whose given property is 1" + OfType("int"),
3801 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003802
3803 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003804 EXPECT_EQ("which points to an object whose given property is 1" +
3805 OfType("int") + ", which is 1 more than 0",
3806 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003807}
3808
3809// Tests ResultOf.
3810
3811// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3812// function pointer.
3813string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; }
3814
3815TEST(ResultOfTest, WorksForFunctionPointers) {
3816 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo")));
3817
3818 EXPECT_TRUE(matcher.Matches(1));
3819 EXPECT_FALSE(matcher.Matches(2));
3820}
3821
3822// Tests that ResultOf() can describe itself.
3823TEST(ResultOfTest, CanDescribeItself) {
3824 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
3825
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003826 EXPECT_EQ("is mapped by the given callable to a value that "
3827 "is equal to \"foo\"", Describe(matcher));
3828 EXPECT_EQ("is mapped by the given callable to a value that "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003829 "isn't equal to \"foo\"", DescribeNegation(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00003830}
3831
3832// Tests that ResultOf() can explain the match result.
3833int IntFunction(int input) { return input == 42 ? 80 : 90; }
3834
3835TEST(ResultOfTest, CanExplainMatchResult) {
3836 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003837 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003838 Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003839
3840 matcher = ResultOf(&IntFunction, GreaterThan(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003841 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
3842 ", which is 5 more than 85", Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003843}
3844
3845// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3846// returns a non-reference.
3847TEST(ResultOfTest, WorksForNonReferenceResults) {
3848 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
3849
3850 EXPECT_TRUE(matcher.Matches(42));
3851 EXPECT_FALSE(matcher.Matches(36));
3852}
3853
3854// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3855// returns a reference to non-const.
zhanyong.wan736baa82010-09-27 17:44:16 +00003856double& DoubleFunction(double& input) { return input; } // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003857
zhanyong.wan736baa82010-09-27 17:44:16 +00003858Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003859 return obj;
3860}
3861
3862TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
3863 double x = 3.14;
3864 double x2 = x;
3865 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
3866
3867 EXPECT_TRUE(matcher.Matches(x));
3868 EXPECT_FALSE(matcher.Matches(x2));
3869
3870 // Test that ResultOf works with uncopyable objects
3871 Uncopyable obj(0);
3872 Uncopyable obj2(0);
3873 Matcher<Uncopyable&> matcher2 =
3874 ResultOf(&RefUncopyableFunction, Ref(obj));
3875
3876 EXPECT_TRUE(matcher2.Matches(obj));
3877 EXPECT_FALSE(matcher2.Matches(obj2));
3878}
3879
3880// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3881// returns a reference to const.
3882const string& StringFunction(const string& input) { return input; }
3883
3884TEST(ResultOfTest, WorksForReferenceToConstResults) {
3885 string s = "foo";
3886 string s2 = s;
3887 Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s));
3888
3889 EXPECT_TRUE(matcher.Matches(s));
3890 EXPECT_FALSE(matcher.Matches(s2));
3891}
3892
3893// Tests that ResultOf(f, m) works when f(x) and m's
3894// argument types are compatible but different.
3895TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
3896 // IntFunction() returns int but the inner matcher expects a signed char.
3897 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
3898
3899 EXPECT_TRUE(matcher.Matches(36));
3900 EXPECT_FALSE(matcher.Matches(42));
3901}
3902
shiqiane35fdd92008-12-10 05:08:54 +00003903// Tests that the program aborts when ResultOf is passed
3904// a NULL function pointer.
3905TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
zhanyong.wan04d6ed82009-09-11 07:01:08 +00003906 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan736baa82010-09-27 17:44:16 +00003907 ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))),
shiqiane35fdd92008-12-10 05:08:54 +00003908 "NULL function pointer is passed into ResultOf\\(\\)\\.");
3909}
shiqiane35fdd92008-12-10 05:08:54 +00003910
3911// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3912// function reference.
3913TEST(ResultOfTest, WorksForFunctionReferences) {
3914 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
3915 EXPECT_TRUE(matcher.Matches(1));
3916 EXPECT_FALSE(matcher.Matches(2));
3917}
3918
3919// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3920// function object.
3921struct Functor : public ::std::unary_function<int, string> {
3922 result_type operator()(argument_type input) const {
3923 return IntToStringFunction(input);
3924 }
3925};
3926
3927TEST(ResultOfTest, WorksForFunctors) {
3928 Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo")));
3929
3930 EXPECT_TRUE(matcher.Matches(1));
3931 EXPECT_FALSE(matcher.Matches(2));
3932}
3933
3934// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3935// functor with more then one operator() defined. ResultOf() must work
3936// for each defined operator().
3937struct PolymorphicFunctor {
3938 typedef int result_type;
3939 int operator()(int n) { return n; }
3940 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
3941};
3942
3943TEST(ResultOfTest, WorksForPolymorphicFunctors) {
3944 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
3945
3946 EXPECT_TRUE(matcher_int.Matches(10));
3947 EXPECT_FALSE(matcher_int.Matches(2));
3948
3949 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
3950
3951 EXPECT_TRUE(matcher_string.Matches("long string"));
3952 EXPECT_FALSE(matcher_string.Matches("shrt"));
3953}
3954
3955const int* ReferencingFunction(const int& n) { return &n; }
3956
3957struct ReferencingFunctor {
3958 typedef const int* result_type;
3959 result_type operator()(const int& n) { return &n; }
3960};
3961
3962TEST(ResultOfTest, WorksForReferencingCallables) {
3963 const int n = 1;
3964 const int n2 = 1;
3965 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
3966 EXPECT_TRUE(matcher2.Matches(n));
3967 EXPECT_FALSE(matcher2.Matches(n2));
3968
3969 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
3970 EXPECT_TRUE(matcher3.Matches(n));
3971 EXPECT_FALSE(matcher3.Matches(n2));
3972}
3973
shiqiane35fdd92008-12-10 05:08:54 +00003974class DivisibleByImpl {
3975 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003976 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
shiqiane35fdd92008-12-10 05:08:54 +00003977
zhanyong.wandb22c222010-01-28 21:52:29 +00003978 // For testing using ExplainMatchResultTo() with polymorphic matchers.
shiqiane35fdd92008-12-10 05:08:54 +00003979 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00003980 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003981 *listener << "which is " << (n % divider_) << " modulo "
zhanyong.wandb22c222010-01-28 21:52:29 +00003982 << divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003983 return (n % divider_) == 0;
3984 }
3985
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003986 void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003987 *os << "is divisible by " << divider_;
3988 }
3989
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003990 void DescribeNegationTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003991 *os << "is not divisible by " << divider_;
3992 }
3993
zhanyong.wan32de5f52009-12-23 00:13:23 +00003994 void set_divider(int a_divider) { divider_ = a_divider; }
shiqiane35fdd92008-12-10 05:08:54 +00003995 int divider() const { return divider_; }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003996
shiqiane35fdd92008-12-10 05:08:54 +00003997 private:
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003998 int divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003999};
4000
shiqiane35fdd92008-12-10 05:08:54 +00004001PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
4002 return MakePolymorphicMatcher(DivisibleByImpl(n));
4003}
4004
4005// Tests that when AllOf() fails, only the first failing matcher is
4006// asked to explain why.
4007TEST(ExplainMatchResultTest, AllOf_False_False) {
4008 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004009 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00004010}
4011
4012// Tests that when AllOf() fails, only the first failing matcher is
4013// asked to explain why.
4014TEST(ExplainMatchResultTest, AllOf_False_True) {
4015 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004016 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00004017}
4018
4019// Tests that when AllOf() fails, only the first failing matcher is
4020// asked to explain why.
4021TEST(ExplainMatchResultTest, AllOf_True_False) {
4022 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004023 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00004024}
4025
4026// Tests that when AllOf() succeeds, all matchers are asked to explain
4027// why.
4028TEST(ExplainMatchResultTest, AllOf_True_True) {
4029 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004030 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00004031}
4032
4033TEST(ExplainMatchResultTest, AllOf_True_True_2) {
4034 const Matcher<int> m = AllOf(Ge(2), Le(3));
4035 EXPECT_EQ("", Explain(m, 2));
4036}
4037
4038TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
4039 const Matcher<int> m = GreaterThan(5);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00004040 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00004041}
4042
4043// The following two tests verify that values without a public copy
4044// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
4045// with the help of ByRef().
4046
4047class NotCopyable {
4048 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00004049 explicit NotCopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00004050
4051 int value() const { return value_; }
4052
4053 bool operator==(const NotCopyable& rhs) const {
4054 return value() == rhs.value();
4055 }
4056
4057 bool operator>=(const NotCopyable& rhs) const {
4058 return value() >= rhs.value();
4059 }
4060 private:
4061 int value_;
4062
4063 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
4064};
4065
4066TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
4067 const NotCopyable const_value1(1);
4068 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
4069
4070 const NotCopyable n1(1), n2(2);
4071 EXPECT_TRUE(m.Matches(n1));
4072 EXPECT_FALSE(m.Matches(n2));
4073}
4074
4075TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
4076 NotCopyable value2(2);
4077 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
4078
4079 NotCopyable n1(1), n2(2);
4080 EXPECT_FALSE(m.Matches(n1));
4081 EXPECT_TRUE(m.Matches(n2));
4082}
4083
zhanyong.wan320814a2013-03-01 00:20:30 +00004084TEST(IsEmptyTest, ImplementsIsEmpty) {
4085 vector<int> container;
4086 EXPECT_THAT(container, IsEmpty());
4087 container.push_back(0);
4088 EXPECT_THAT(container, Not(IsEmpty()));
4089 container.push_back(1);
4090 EXPECT_THAT(container, Not(IsEmpty()));
4091}
4092
4093TEST(IsEmptyTest, WorksWithString) {
4094 string text;
4095 EXPECT_THAT(text, IsEmpty());
4096 text = "foo";
4097 EXPECT_THAT(text, Not(IsEmpty()));
4098 text = string("\0", 1);
4099 EXPECT_THAT(text, Not(IsEmpty()));
4100}
4101
4102TEST(IsEmptyTest, CanDescribeSelf) {
4103 Matcher<vector<int> > m = IsEmpty();
4104 EXPECT_EQ("is empty", Describe(m));
4105 EXPECT_EQ("isn't empty", DescribeNegation(m));
4106}
4107
4108TEST(IsEmptyTest, ExplainsResult) {
4109 Matcher<vector<int> > m = IsEmpty();
4110 vector<int> container;
4111 EXPECT_EQ("", Explain(m, container));
4112 container.push_back(0);
4113 EXPECT_EQ("whose size is 1", Explain(m, container));
4114}
4115
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004116TEST(SizeIsTest, ImplementsSizeIs) {
4117 vector<int> container;
4118 EXPECT_THAT(container, SizeIs(0));
4119 EXPECT_THAT(container, Not(SizeIs(1)));
4120 container.push_back(0);
4121 EXPECT_THAT(container, Not(SizeIs(0)));
4122 EXPECT_THAT(container, SizeIs(1));
4123 container.push_back(0);
4124 EXPECT_THAT(container, Not(SizeIs(0)));
4125 EXPECT_THAT(container, SizeIs(2));
4126}
4127
4128TEST(SizeIsTest, WorksWithMap) {
4129 map<string, int> container;
4130 EXPECT_THAT(container, SizeIs(0));
4131 EXPECT_THAT(container, Not(SizeIs(1)));
4132 container.insert(make_pair("foo", 1));
4133 EXPECT_THAT(container, Not(SizeIs(0)));
4134 EXPECT_THAT(container, SizeIs(1));
4135 container.insert(make_pair("bar", 2));
4136 EXPECT_THAT(container, Not(SizeIs(0)));
4137 EXPECT_THAT(container, SizeIs(2));
4138}
4139
4140TEST(SizeIsTest, WorksWithReferences) {
4141 vector<int> container;
4142 Matcher<const vector<int>&> m = SizeIs(1);
4143 EXPECT_THAT(container, Not(m));
4144 container.push_back(0);
4145 EXPECT_THAT(container, m);
4146}
4147
4148TEST(SizeIsTest, CanDescribeSelf) {
4149 Matcher<vector<int> > m = SizeIs(2);
4150 EXPECT_EQ("size is equal to 2", Describe(m));
4151 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
4152}
4153
4154TEST(SizeIsTest, ExplainsResult) {
4155 Matcher<vector<int> > m1 = SizeIs(2);
4156 Matcher<vector<int> > m2 = SizeIs(Lt(2u));
4157 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
4158 Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
4159 vector<int> container;
4160 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
4161 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
4162 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
4163 EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
4164 Explain(m4, container));
4165 container.push_back(0);
4166 container.push_back(0);
4167 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
4168 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
4169 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
4170 EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
4171 Explain(m4, container));
4172}
4173
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004174#if GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004175// Tests ContainerEq with different container types, and
4176// different element types.
4177
4178template <typename T>
zhanyong.wanb8243162009-06-04 05:48:20 +00004179class ContainerEqTest : public testing::Test {};
zhanyong.wan6a896b52009-01-16 01:13:50 +00004180
4181typedef testing::Types<
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004182 set<int>,
4183 vector<size_t>,
4184 multiset<size_t>,
4185 list<int> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004186 ContainerEqTestTypes;
4187
4188TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
4189
4190// Tests that the filled container is equal to itself.
4191TYPED_TEST(ContainerEqTest, EqualsSelf) {
4192 static const int vals[] = {1, 1, 2, 3, 5, 8};
4193 TypeParam my_set(vals, vals + 6);
4194 const Matcher<TypeParam> m = ContainerEq(my_set);
4195 EXPECT_TRUE(m.Matches(my_set));
4196 EXPECT_EQ("", Explain(m, my_set));
4197}
4198
4199// Tests that missing values are reported.
4200TYPED_TEST(ContainerEqTest, ValueMissing) {
4201 static const int vals[] = {1, 1, 2, 3, 5, 8};
4202 static const int test_vals[] = {2, 1, 8, 5};
4203 TypeParam my_set(vals, vals + 6);
4204 TypeParam test_set(test_vals, test_vals + 4);
4205 const Matcher<TypeParam> m = ContainerEq(my_set);
4206 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004207 EXPECT_EQ("which doesn't have these expected elements: 3",
4208 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004209}
4210
4211// Tests that added values are reported.
4212TYPED_TEST(ContainerEqTest, ValueAdded) {
4213 static const int vals[] = {1, 1, 2, 3, 5, 8};
4214 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4215 TypeParam my_set(vals, vals + 6);
4216 TypeParam test_set(test_vals, test_vals + 6);
4217 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4218 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004219 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004220}
4221
4222// Tests that added and missing values are reported together.
4223TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4224 static const int vals[] = {1, 1, 2, 3, 5, 8};
4225 static const int test_vals[] = {1, 2, 3, 8, 46};
4226 TypeParam my_set(vals, vals + 6);
4227 TypeParam test_set(test_vals, test_vals + 5);
4228 const Matcher<TypeParam> m = ContainerEq(my_set);
4229 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004230 EXPECT_EQ("which has these unexpected elements: 46,\n"
4231 "and doesn't have these expected elements: 5",
4232 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004233}
4234
4235// Tests duplicated value -- expect no explanation.
4236TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4237 static const int vals[] = {1, 1, 2, 3, 5, 8};
4238 static const int test_vals[] = {1, 2, 3, 5, 8};
4239 TypeParam my_set(vals, vals + 6);
4240 TypeParam test_set(test_vals, test_vals + 5);
4241 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4242 // Depending on the container, match may be true or false
4243 // But in any case there should be no explanation.
4244 EXPECT_EQ("", Explain(m, test_set));
4245}
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004246#endif // GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004247
4248// Tests that mutliple missing values are reported.
4249// Using just vector here, so order is predicatble.
4250TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4251 static const int vals[] = {1, 1, 2, 3, 5, 8};
4252 static const int test_vals[] = {2, 1, 5};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004253 vector<int> my_set(vals, vals + 6);
4254 vector<int> test_set(test_vals, test_vals + 3);
4255 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004256 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004257 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4258 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004259}
4260
4261// Tests that added values are reported.
4262// Using just vector here, so order is predicatble.
4263TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4264 static const int vals[] = {1, 1, 2, 3, 5, 8};
4265 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004266 list<size_t> my_set(vals, vals + 6);
4267 list<size_t> test_set(test_vals, test_vals + 7);
4268 const Matcher<const list<size_t>&> m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004269 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004270 EXPECT_EQ("which has these unexpected elements: 92, 46",
4271 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004272}
4273
4274// Tests that added and missing values are reported together.
4275TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
4276 static const int vals[] = {1, 1, 2, 3, 5, 8};
4277 static const int test_vals[] = {1, 2, 3, 92, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004278 list<size_t> my_set(vals, vals + 6);
4279 list<size_t> test_set(test_vals, test_vals + 5);
4280 const Matcher<const list<size_t> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004281 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004282 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4283 "and doesn't have these expected elements: 5, 8",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004284 Explain(m, test_set));
4285}
4286
4287// Tests to see that duplicate elements are detected,
4288// but (as above) not reported in the explanation.
4289TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
4290 static const int vals[] = {1, 1, 2, 3, 5, 8};
4291 static const int test_vals[] = {1, 2, 3, 5, 8};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004292 vector<int> my_set(vals, vals + 6);
4293 vector<int> test_set(test_vals, test_vals + 5);
4294 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004295 EXPECT_TRUE(m.Matches(my_set));
4296 EXPECT_FALSE(m.Matches(test_set));
4297 // There is nothing to report when both sets contain all the same values.
4298 EXPECT_EQ("", Explain(m, test_set));
4299}
4300
4301// Tests that ContainerEq works for non-trivial associative containers,
4302// like maps.
4303TEST(ContainerEqExtraTest, WorksForMaps) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004304 map<int, std::string> my_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004305 my_map[0] = "a";
4306 my_map[1] = "b";
4307
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004308 map<int, std::string> test_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004309 test_map[0] = "aa";
4310 test_map[1] = "b";
4311
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004312 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004313 EXPECT_TRUE(m.Matches(my_map));
4314 EXPECT_FALSE(m.Matches(test_map));
4315
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004316 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
4317 "and doesn't have these expected elements: (0, \"a\")",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004318 Explain(m, test_map));
4319}
4320
zhanyong.wanb8243162009-06-04 05:48:20 +00004321TEST(ContainerEqExtraTest, WorksForNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00004322 int a1[] = {1, 2, 3};
4323 int a2[] = {1, 2, 3};
4324 int b[] = {1, 2, 4};
zhanyong.wanb8243162009-06-04 05:48:20 +00004325
4326 EXPECT_THAT(a1, ContainerEq(a2));
4327 EXPECT_THAT(a1, Not(ContainerEq(b)));
4328}
4329
4330TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00004331 const char a1[][3] = {"hi", "lo"};
4332 const char a2[][3] = {"hi", "lo"};
4333 const char b[][3] = {"lo", "hi"};
zhanyong.wanb8243162009-06-04 05:48:20 +00004334
4335 // Tests using ContainerEq() in the first dimension.
4336 EXPECT_THAT(a1, ContainerEq(a2));
4337 EXPECT_THAT(a1, Not(ContainerEq(b)));
4338
4339 // Tests using ContainerEq() in the second dimension.
4340 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
4341 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
4342}
4343
4344TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
kosak2336e9c2014-07-28 22:57:30 +00004345 const int a1[] = {1, 2, 3};
4346 const int a2[] = {1, 2, 3};
4347 const int b[] = {1, 2, 3, 4};
zhanyong.wanb8243162009-06-04 05:48:20 +00004348
zhanyong.wan2661c682009-06-09 05:42:12 +00004349 const int* const p1 = a1;
4350 EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
4351 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004352
kosak2336e9c2014-07-28 22:57:30 +00004353 const int c[] = {1, 3, 2};
zhanyong.wan2661c682009-06-09 05:42:12 +00004354 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004355}
4356
4357TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
4358 std::string a1[][3] = {
kosak2336e9c2014-07-28 22:57:30 +00004359 {"hi", "hello", "ciao"},
4360 {"bye", "see you", "ciao"}
zhanyong.wanb8243162009-06-04 05:48:20 +00004361 };
4362
4363 std::string a2[][3] = {
kosak2336e9c2014-07-28 22:57:30 +00004364 {"hi", "hello", "ciao"},
4365 {"bye", "see you", "ciao"}
zhanyong.wanb8243162009-06-04 05:48:20 +00004366 };
4367
4368 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
4369 EXPECT_THAT(a1, m);
4370
4371 a2[0][0] = "ha";
4372 EXPECT_THAT(a1, m);
4373}
4374
zhanyong.wan898725c2011-09-16 16:45:39 +00004375TEST(WhenSortedByTest, WorksForEmptyContainer) {
4376 const vector<int> numbers;
4377 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
4378 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
4379}
4380
4381TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
4382 vector<unsigned> numbers;
4383 numbers.push_back(3);
4384 numbers.push_back(1);
4385 numbers.push_back(2);
4386 numbers.push_back(2);
4387 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
4388 ElementsAre(3, 2, 2, 1)));
4389 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
4390 ElementsAre(1, 2, 2, 3))));
4391}
4392
4393TEST(WhenSortedByTest, WorksForNonVectorContainer) {
4394 list<string> words;
4395 words.push_back("say");
4396 words.push_back("hello");
4397 words.push_back("world");
4398 EXPECT_THAT(words, WhenSortedBy(less<string>(),
4399 ElementsAre("hello", "say", "world")));
4400 EXPECT_THAT(words, Not(WhenSortedBy(less<string>(),
4401 ElementsAre("say", "hello", "world"))));
4402}
4403
4404TEST(WhenSortedByTest, WorksForNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00004405 const int numbers[] = {1, 3, 2, 4};
4406 const int sorted_numbers[] = {1, 2, 3, 4};
zhanyong.wan898725c2011-09-16 16:45:39 +00004407 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
4408 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
4409 ElementsAreArray(sorted_numbers)));
4410 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
4411}
4412
4413TEST(WhenSortedByTest, CanDescribeSelf) {
4414 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
4415 EXPECT_EQ("(when sorted) has 2 elements where\n"
4416 "element #0 is equal to 1,\n"
4417 "element #1 is equal to 2",
4418 Describe(m));
4419 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
4420 "element #0 isn't equal to 1, or\n"
4421 "element #1 isn't equal to 2",
4422 DescribeNegation(m));
4423}
4424
4425TEST(WhenSortedByTest, ExplainsMatchResult) {
kosak2336e9c2014-07-28 22:57:30 +00004426 const int a[] = {2, 1};
zhanyong.wan898725c2011-09-16 16:45:39 +00004427 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
4428 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
4429 EXPECT_EQ("which is { 1, 2 } when sorted",
4430 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
4431}
4432
4433// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
4434// need to test it as exhaustively as we test the latter.
4435
4436TEST(WhenSortedTest, WorksForEmptyContainer) {
4437 const vector<int> numbers;
4438 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
4439 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
4440}
4441
4442TEST(WhenSortedTest, WorksForNonEmptyContainer) {
4443 list<string> words;
4444 words.push_back("3");
4445 words.push_back("1");
4446 words.push_back("2");
4447 words.push_back("2");
4448 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
4449 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
4450}
4451
zhanyong.wana9a59e02013-03-27 16:14:55 +00004452TEST(WhenSortedTest, WorksForMapTypes) {
4453 map<string, int> word_counts;
4454 word_counts["and"] = 1;
4455 word_counts["the"] = 1;
4456 word_counts["buffalo"] = 2;
4457 EXPECT_THAT(word_counts, WhenSorted(ElementsAre(
4458 Pair("and", 1), Pair("buffalo", 2), Pair("the", 1))));
4459 EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre(
4460 Pair("and", 1), Pair("the", 1), Pair("buffalo", 2)))));
4461}
4462
4463TEST(WhenSortedTest, WorksForMultiMapTypes) {
4464 multimap<int, int> ifib;
4465 ifib.insert(make_pair(8, 6));
4466 ifib.insert(make_pair(2, 3));
4467 ifib.insert(make_pair(1, 1));
4468 ifib.insert(make_pair(3, 4));
4469 ifib.insert(make_pair(1, 2));
4470 ifib.insert(make_pair(5, 5));
4471 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
4472 Pair(1, 2),
4473 Pair(2, 3),
4474 Pair(3, 4),
4475 Pair(5, 5),
4476 Pair(8, 6))));
4477 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
4478 Pair(2, 3),
4479 Pair(1, 1),
4480 Pair(3, 4),
4481 Pair(1, 2),
4482 Pair(5, 5)))));
4483}
4484
4485TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
4486 std::deque<int> d;
4487 d.push_back(2);
4488 d.push_back(1);
4489 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
4490 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
4491}
4492
4493TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
4494 std::deque<int> d;
4495 d.push_back(2);
4496 d.push_back(1);
4497 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
4498 EXPECT_THAT(d, WhenSorted(vector_match));
4499 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
4500 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
4501}
4502
4503// Deliberately bare pseudo-container.
4504// Offers only begin() and end() accessors, yielding InputIterator.
4505template <typename T>
4506class Streamlike {
4507 private:
4508 class ConstIter;
4509 public:
4510 typedef ConstIter const_iterator;
4511 typedef T value_type;
4512
4513 template <typename InIter>
4514 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
4515
4516 const_iterator begin() const {
4517 return const_iterator(this, remainder_.begin());
4518 }
4519 const_iterator end() const {
4520 return const_iterator(this, remainder_.end());
4521 }
4522
4523 private:
4524 class ConstIter : public std::iterator<std::input_iterator_tag,
4525 value_type,
4526 ptrdiff_t,
kosakcd99eb02014-11-17 02:18:28 +00004527 const value_type*,
4528 const value_type&> {
zhanyong.wana9a59e02013-03-27 16:14:55 +00004529 public:
4530 ConstIter(const Streamlike* s,
4531 typename std::list<value_type>::iterator pos)
4532 : s_(s), pos_(pos) {}
4533
4534 const value_type& operator*() const { return *pos_; }
4535 const value_type* operator->() const { return &*pos_; }
4536 ConstIter& operator++() {
4537 s_->remainder_.erase(pos_++);
4538 return *this;
4539 }
4540
4541 // *iter++ is required to work (see std::istreambuf_iterator).
4542 // (void)iter++ is also required to work.
4543 class PostIncrProxy {
4544 public:
4545 explicit PostIncrProxy(const value_type& value) : value_(value) {}
4546 value_type operator*() const { return value_; }
4547 private:
4548 value_type value_;
4549 };
4550 PostIncrProxy operator++(int) {
4551 PostIncrProxy proxy(**this);
4552 ++(*this);
4553 return proxy;
4554 }
4555
4556 friend bool operator==(const ConstIter& a, const ConstIter& b) {
4557 return a.s_ == b.s_ && a.pos_ == b.pos_;
4558 }
4559 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
4560 return !(a == b);
4561 }
4562
4563 private:
4564 const Streamlike* s_;
4565 typename std::list<value_type>::iterator pos_;
4566 };
4567
4568 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
4569 os << "[";
4570 typedef typename std::list<value_type>::const_iterator Iter;
4571 const char* sep = "";
4572 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
4573 os << sep << *it;
4574 sep = ",";
4575 }
4576 os << "]";
4577 return os;
4578 }
4579
4580 mutable std::list<value_type> remainder_; // modified by iteration
4581};
4582
4583TEST(StreamlikeTest, Iteration) {
kosak2336e9c2014-07-28 22:57:30 +00004584 const int a[5] = {2, 1, 4, 5, 3};
zhanyong.wana9a59e02013-03-27 16:14:55 +00004585 Streamlike<int> s(a, a + 5);
4586 Streamlike<int>::const_iterator it = s.begin();
4587 const int* ip = a;
4588 while (it != s.end()) {
4589 SCOPED_TRACE(ip - a);
4590 EXPECT_EQ(*ip++, *it++);
4591 }
4592}
4593
kosak5b9cbbb2014-11-17 00:28:55 +00004594#if GTEST_HAS_STD_FORWARD_LIST_
kosakb6a34882014-03-12 21:06:46 +00004595TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
4596 std::forward_list<int> container;
4597 EXPECT_THAT(container, BeginEndDistanceIs(0));
4598 EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
4599 container.push_front(0);
4600 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4601 EXPECT_THAT(container, BeginEndDistanceIs(1));
4602 container.push_front(0);
4603 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4604 EXPECT_THAT(container, BeginEndDistanceIs(2));
4605}
kosak5b9cbbb2014-11-17 00:28:55 +00004606#endif // GTEST_HAS_STD_FORWARD_LIST_
kosakb6a34882014-03-12 21:06:46 +00004607
4608TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
kosak2336e9c2014-07-28 22:57:30 +00004609 const int a[5] = {1, 2, 3, 4, 5};
kosakb6a34882014-03-12 21:06:46 +00004610 Streamlike<int> s(a, a + 5);
4611 EXPECT_THAT(s, BeginEndDistanceIs(5));
4612}
4613
4614TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
4615 Matcher<vector<int> > m = BeginEndDistanceIs(2);
4616 EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
4617 EXPECT_EQ("distance between begin() and end() isn't equal to 2",
4618 DescribeNegation(m));
4619}
4620
4621TEST(BeginEndDistanceIsTest, ExplainsResult) {
4622 Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
4623 Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
4624 Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
4625 Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
4626 vector<int> container;
4627 EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
4628 Explain(m1, container));
4629 EXPECT_EQ("whose distance between begin() and end() 0 matches",
4630 Explain(m2, container));
4631 EXPECT_EQ("whose distance between begin() and end() 0 matches",
4632 Explain(m3, container));
4633 EXPECT_EQ(
4634 "whose distance between begin() and end() 0 doesn't match, which is 1 "
4635 "less than 1",
4636 Explain(m4, container));
4637 container.push_back(0);
4638 container.push_back(0);
4639 EXPECT_EQ("whose distance between begin() and end() 2 matches",
4640 Explain(m1, container));
4641 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4642 Explain(m2, container));
4643 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4644 Explain(m3, container));
4645 EXPECT_EQ(
4646 "whose distance between begin() and end() 2 matches, which is 1 more "
4647 "than 1",
4648 Explain(m4, container));
4649}
4650
zhanyong.wana9a59e02013-03-27 16:14:55 +00004651TEST(WhenSortedTest, WorksForStreamlike) {
4652 // Streamlike 'container' provides only minimal iterator support.
4653 // Its iterators are tagged with input_iterator_tag.
kosak2336e9c2014-07-28 22:57:30 +00004654 const int a[5] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00004655 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004656 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
4657 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4658}
4659
4660TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
kosak2336e9c2014-07-28 22:57:30 +00004661 const int a[] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00004662 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004663 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
4664 EXPECT_THAT(s, WhenSorted(vector_match));
4665 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4666}
4667
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004668// Tests using ElementsAre() and ElementsAreArray() with stream-like
4669// "containers".
4670
4671TEST(ElemensAreStreamTest, WorksForStreamlike) {
kosak2336e9c2014-07-28 22:57:30 +00004672 const int a[5] = {1, 2, 3, 4, 5};
kosak6414d802013-12-03 23:19:36 +00004673 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004674 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
4675 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
4676}
4677
4678TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
kosak2336e9c2014-07-28 22:57:30 +00004679 const int a[5] = {1, 2, 3, 4, 5};
kosak6414d802013-12-03 23:19:36 +00004680 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004681
4682 vector<int> expected;
4683 expected.push_back(1);
4684 expected.push_back(2);
4685 expected.push_back(3);
4686 expected.push_back(4);
4687 expected.push_back(5);
4688 EXPECT_THAT(s, ElementsAreArray(expected));
4689
4690 expected[3] = 0;
4691 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
4692}
4693
billydonahue1f5fdea2014-05-19 17:54:51 +00004694TEST(ElementsAreTest, WorksWithUncopyable) {
4695 Uncopyable objs[2];
4696 objs[0].set_value(-3);
4697 objs[1].set_value(1);
4698 EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
4699}
4700
kosak06678922014-07-28 20:01:28 +00004701TEST(ElementsAreTest, TakesStlContainer) {
4702 const int actual[] = {3, 1, 2};
4703
4704 ::std::list<int> expected;
4705 expected.push_back(3);
4706 expected.push_back(1);
4707 expected.push_back(2);
4708 EXPECT_THAT(actual, ElementsAreArray(expected));
4709
4710 expected.push_back(4);
4711 EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
4712}
4713
zhanyong.wanfb25d532013-07-28 08:24:00 +00004714// Tests for UnorderedElementsAreArray()
4715
4716TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
kosak2336e9c2014-07-28 22:57:30 +00004717 const int a[] = {0, 1, 2, 3, 4};
kosak6414d802013-12-03 23:19:36 +00004718 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004719 do {
4720 StringMatchResultListener listener;
4721 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
4722 s, &listener)) << listener.str();
4723 } while (std::next_permutation(s.begin(), s.end()));
4724}
4725
4726TEST(UnorderedElementsAreArrayTest, VectorBool) {
kosak2336e9c2014-07-28 22:57:30 +00004727 const bool a[] = {0, 1, 0, 1, 1};
4728 const bool b[] = {1, 0, 1, 1, 0};
kosak6414d802013-12-03 23:19:36 +00004729 std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a));
4730 std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004731 StringMatchResultListener listener;
4732 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
4733 actual, &listener)) << listener.str();
4734}
4735
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004736TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
4737 // Streamlike 'container' provides only minimal iterator support.
4738 // Its iterators are tagged with input_iterator_tag, and it has no
4739 // size() or empty() methods.
kosak2336e9c2014-07-28 22:57:30 +00004740 const int a[5] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00004741 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004742
4743 ::std::vector<int> expected;
4744 expected.push_back(1);
4745 expected.push_back(2);
4746 expected.push_back(3);
4747 expected.push_back(4);
4748 expected.push_back(5);
4749 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
4750
4751 expected.push_back(6);
4752 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
4753}
4754
kosak06678922014-07-28 20:01:28 +00004755TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
4756 const int actual[] = {3, 1, 2};
4757
4758 ::std::list<int> expected;
4759 expected.push_back(1);
4760 expected.push_back(2);
4761 expected.push_back(3);
4762 EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
4763
4764 expected.push_back(4);
4765 EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
4766}
4767
kosak18489fa2013-12-04 23:49:07 +00004768#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004769
4770TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
kosak2336e9c2014-07-28 22:57:30 +00004771 const int a[5] = {2, 1, 4, 5, 3};
4772 EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
4773 EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004774}
4775
4776TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
kosak2336e9c2014-07-28 22:57:30 +00004777 const string a[5] = {"a", "b", "c", "d", "e"};
4778 EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
4779 EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004780}
4781
4782TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
kosak2336e9c2014-07-28 22:57:30 +00004783 const int a[5] = {2, 1, 4, 5, 3};
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004784 EXPECT_THAT(a, UnorderedElementsAreArray(
kosak2336e9c2014-07-28 22:57:30 +00004785 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004786 EXPECT_THAT(a, Not(UnorderedElementsAreArray(
kosak2336e9c2014-07-28 22:57:30 +00004787 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004788}
4789
4790TEST(UnorderedElementsAreArrayTest,
4791 TakesInitializerListOfDifferentTypedMatchers) {
kosak2336e9c2014-07-28 22:57:30 +00004792 const int a[5] = {2, 1, 4, 5, 3};
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004793 // The compiler cannot infer the type of the initializer list if its
4794 // elements have different types. We must explicitly specify the
4795 // unified element type in this case.
4796 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
kosak2336e9c2014-07-28 22:57:30 +00004797 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004798 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
kosak2336e9c2014-07-28 22:57:30 +00004799 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004800}
4801
kosak18489fa2013-12-04 23:49:07 +00004802#endif // GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004803
zhanyong.wanfb25d532013-07-28 08:24:00 +00004804class UnorderedElementsAreTest : public testing::Test {
4805 protected:
4806 typedef std::vector<int> IntVec;
4807};
4808
billydonahue1f5fdea2014-05-19 17:54:51 +00004809TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
4810 Uncopyable objs[2];
4811 objs[0].set_value(-3);
4812 objs[1].set_value(1);
4813 EXPECT_THAT(objs,
4814 UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
4815}
4816
zhanyong.wanfb25d532013-07-28 08:24:00 +00004817TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
kosak2336e9c2014-07-28 22:57:30 +00004818 const int a[] = {1, 2, 3};
kosak6414d802013-12-03 23:19:36 +00004819 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004820 do {
4821 StringMatchResultListener listener;
4822 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4823 s, &listener)) << listener.str();
4824 } while (std::next_permutation(s.begin(), s.end()));
4825}
4826
4827TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
kosak2336e9c2014-07-28 22:57:30 +00004828 const int a[] = {1, 2, 3};
kosak6414d802013-12-03 23:19:36 +00004829 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004830 std::vector<Matcher<int> > mv;
4831 mv.push_back(1);
4832 mv.push_back(2);
4833 mv.push_back(2);
4834 // The element with value '3' matches nothing: fail fast.
4835 StringMatchResultListener listener;
4836 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4837 s, &listener)) << listener.str();
4838}
4839
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004840TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
4841 // Streamlike 'container' provides only minimal iterator support.
4842 // Its iterators are tagged with input_iterator_tag, and it has no
4843 // size() or empty() methods.
kosak2336e9c2014-07-28 22:57:30 +00004844 const int a[5] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00004845 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004846
4847 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
4848 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
4849}
4850
zhanyong.wanfb25d532013-07-28 08:24:00 +00004851// One naive implementation of the matcher runs in O(N!) time, which is too
4852// slow for many real-world inputs. This test shows that our matcher can match
4853// 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
4854// iterations and obviously effectively incomputable.
4855// [ RUN ] UnorderedElementsAreTest.Performance
4856// [ OK ] UnorderedElementsAreTest.Performance (4 ms)
4857TEST_F(UnorderedElementsAreTest, Performance) {
4858 std::vector<int> s;
4859 std::vector<Matcher<int> > mv;
4860 for (int i = 0; i < 100; ++i) {
4861 s.push_back(i);
4862 mv.push_back(_);
4863 }
4864 mv[50] = Eq(0);
4865 StringMatchResultListener listener;
4866 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4867 s, &listener)) << listener.str();
4868}
4869
4870// Another variant of 'Performance' with similar expectations.
4871// [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
4872// [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
4873TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
4874 std::vector<int> s;
4875 std::vector<Matcher<int> > mv;
4876 for (int i = 0; i < 100; ++i) {
4877 s.push_back(i);
4878 if (i & 1) {
4879 mv.push_back(_);
4880 } else {
4881 mv.push_back(i);
4882 }
4883 }
4884 StringMatchResultListener listener;
4885 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4886 s, &listener)) << listener.str();
4887}
4888
4889TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
4890 std::vector<int> v;
4891 v.push_back(4);
4892 StringMatchResultListener listener;
4893 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4894 v, &listener)) << listener.str();
4895 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
4896}
4897
4898TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
4899 std::vector<int> v;
4900 StringMatchResultListener listener;
4901 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4902 v, &listener)) << listener.str();
4903 EXPECT_THAT(listener.str(), Eq(""));
4904}
4905
4906TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
4907 std::vector<int> v;
4908 v.push_back(1);
4909 v.push_back(1);
4910 StringMatchResultListener listener;
4911 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4912 v, &listener)) << listener.str();
4913 EXPECT_THAT(
4914 listener.str(),
4915 Eq("where the following matchers don't match any elements:\n"
4916 "matcher #1: is equal to 2"));
4917}
4918
4919TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
4920 std::vector<int> v;
4921 v.push_back(1);
4922 v.push_back(2);
4923 StringMatchResultListener listener;
4924 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
4925 v, &listener)) << listener.str();
4926 EXPECT_THAT(
4927 listener.str(),
4928 Eq("where the following elements don't match any matchers:\n"
4929 "element #1: 2"));
4930}
4931
4932TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
4933 std::vector<int> v;
4934 v.push_back(2);
4935 v.push_back(3);
4936 StringMatchResultListener listener;
4937 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4938 v, &listener)) << listener.str();
4939 EXPECT_THAT(
4940 listener.str(),
4941 Eq("where"
4942 " the following matchers don't match any elements:\n"
4943 "matcher #0: is equal to 1\n"
4944 "and"
4945 " where"
4946 " the following elements don't match any matchers:\n"
4947 "element #1: 3"));
4948}
4949
4950// Test helper for formatting element, matcher index pairs in expectations.
4951static string EMString(int element, int matcher) {
4952 stringstream ss;
4953 ss << "(element #" << element << ", matcher #" << matcher << ")";
4954 return ss.str();
4955}
4956
4957TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
4958 // A situation where all elements and matchers have a match
4959 // associated with them, but the max matching is not perfect.
4960 std::vector<string> v;
4961 v.push_back("a");
4962 v.push_back("b");
4963 v.push_back("c");
4964 StringMatchResultListener listener;
4965 EXPECT_FALSE(ExplainMatchResult(
4966 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
4967 << listener.str();
4968
4969 string prefix =
4970 "where no permutation of the elements can satisfy all matchers, "
4971 "and the closest match is 2 of 3 matchers with the "
4972 "pairings:\n";
4973
4974 // We have to be a bit loose here, because there are 4 valid max matches.
4975 EXPECT_THAT(
4976 listener.str(),
4977 AnyOf(prefix + "{\n " + EMString(0, 0) +
4978 ",\n " + EMString(1, 2) + "\n}",
4979 prefix + "{\n " + EMString(0, 1) +
4980 ",\n " + EMString(1, 2) + "\n}",
4981 prefix + "{\n " + EMString(0, 0) +
4982 ",\n " + EMString(2, 2) + "\n}",
4983 prefix + "{\n " + EMString(0, 1) +
4984 ",\n " + EMString(2, 2) + "\n}"));
4985}
4986
4987TEST_F(UnorderedElementsAreTest, Describe) {
4988 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
4989 Eq("is empty"));
4990 EXPECT_THAT(
4991 Describe<IntVec>(UnorderedElementsAre(345)),
4992 Eq("has 1 element and that element is equal to 345"));
4993 EXPECT_THAT(
4994 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
4995 Eq("has 3 elements and there exists some permutation "
4996 "of elements such that:\n"
4997 " - element #0 is equal to 111, and\n"
4998 " - element #1 is equal to 222, and\n"
4999 " - element #2 is equal to 333"));
5000}
5001
5002TEST_F(UnorderedElementsAreTest, DescribeNegation) {
5003 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
5004 Eq("isn't empty"));
5005 EXPECT_THAT(
5006 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
5007 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
5008 EXPECT_THAT(
5009 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
5010 Eq("doesn't have 3 elements, or there exists no permutation "
5011 "of elements such that:\n"
5012 " - element #0 is equal to 123, and\n"
5013 " - element #1 is equal to 234, and\n"
5014 " - element #2 is equal to 345"));
5015}
5016
5017namespace {
5018
5019// Used as a check on the more complex max flow method used in the
5020// real testing::internal::FindMaxBipartiteMatching. This method is
5021// compatible but runs in worst-case factorial time, so we only
5022// use it in testing for small problem sizes.
5023template <typename Graph>
5024class BacktrackingMaxBPMState {
5025 public:
5026 // Does not take ownership of 'g'.
5027 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
5028
5029 ElementMatcherPairs Compute() {
5030 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
5031 return best_so_far_;
5032 }
5033 lhs_used_.assign(graph_->LhsSize(), kUnused);
5034 rhs_used_.assign(graph_->RhsSize(), kUnused);
5035 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
5036 matches_.clear();
5037 RecurseInto(irhs);
5038 if (best_so_far_.size() == graph_->RhsSize())
5039 break;
5040 }
5041 return best_so_far_;
5042 }
5043
5044 private:
5045 static const size_t kUnused = static_cast<size_t>(-1);
5046
5047 void PushMatch(size_t lhs, size_t rhs) {
5048 matches_.push_back(ElementMatcherPair(lhs, rhs));
5049 lhs_used_[lhs] = rhs;
5050 rhs_used_[rhs] = lhs;
5051 if (matches_.size() > best_so_far_.size()) {
5052 best_so_far_ = matches_;
5053 }
5054 }
5055
5056 void PopMatch() {
5057 const ElementMatcherPair& back = matches_.back();
5058 lhs_used_[back.first] = kUnused;
5059 rhs_used_[back.second] = kUnused;
5060 matches_.pop_back();
5061 }
5062
5063 bool RecurseInto(size_t irhs) {
5064 if (rhs_used_[irhs] != kUnused) {
5065 return true;
5066 }
5067 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
5068 if (lhs_used_[ilhs] != kUnused) {
5069 continue;
5070 }
5071 if (!graph_->HasEdge(ilhs, irhs)) {
5072 continue;
5073 }
5074 PushMatch(ilhs, irhs);
5075 if (best_so_far_.size() == graph_->RhsSize()) {
5076 return false;
5077 }
5078 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
5079 if (!RecurseInto(mi)) return false;
5080 }
5081 PopMatch();
5082 }
5083 return true;
5084 }
5085
5086 const Graph* graph_; // not owned
5087 std::vector<size_t> lhs_used_;
5088 std::vector<size_t> rhs_used_;
5089 ElementMatcherPairs matches_;
5090 ElementMatcherPairs best_so_far_;
5091};
5092
5093template <typename Graph>
5094const size_t BacktrackingMaxBPMState<Graph>::kUnused;
5095
5096} // namespace
5097
5098// Implement a simple backtracking algorithm to determine if it is possible
5099// to find one element per matcher, without reusing elements.
5100template <typename Graph>
5101ElementMatcherPairs
5102FindBacktrackingMaxBPM(const Graph& g) {
5103 return BacktrackingMaxBPMState<Graph>(&g).Compute();
5104}
5105
5106class BacktrackingBPMTest : public ::testing::Test { };
5107
5108// Tests the MaxBipartiteMatching algorithm with square matrices.
5109// The single int param is the # of nodes on each of the left and right sides.
5110class BipartiteTest : public ::testing::TestWithParam<int> { };
5111
5112// Verify all match graphs up to some moderate number of edges.
5113TEST_P(BipartiteTest, Exhaustive) {
5114 int nodes = GetParam();
5115 MatchMatrix graph(nodes, nodes);
5116 do {
5117 ElementMatcherPairs matches =
5118 internal::FindMaxBipartiteMatching(graph);
5119 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
5120 << "graph: " << graph.DebugString();
5121 // Check that all elements of matches are in the graph.
5122 // Check that elements of first and second are unique.
5123 std::vector<bool> seen_element(graph.LhsSize());
5124 std::vector<bool> seen_matcher(graph.RhsSize());
5125 SCOPED_TRACE(PrintToString(matches));
5126 for (size_t i = 0; i < matches.size(); ++i) {
5127 size_t ilhs = matches[i].first;
5128 size_t irhs = matches[i].second;
5129 EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
5130 EXPECT_FALSE(seen_element[ilhs]);
5131 EXPECT_FALSE(seen_matcher[irhs]);
5132 seen_element[ilhs] = true;
5133 seen_matcher[irhs] = true;
5134 }
5135 } while (graph.NextGraph());
5136}
5137
5138INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest,
5139 ::testing::Range(0, 5));
5140
5141// Parameterized by a pair interpreted as (LhsSize, RhsSize).
5142class BipartiteNonSquareTest
5143 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
5144};
5145
5146TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
5147 // .......
5148 // 0:-----\ :
5149 // 1:---\ | :
5150 // 2:---\ | :
5151 // 3:-\ | | :
5152 // :.......:
5153 // 0 1 2
5154 MatchMatrix g(4, 3);
kosak2336e9c2014-07-28 22:57:30 +00005155 static const int kEdges[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}};
kosak6414d802013-12-03 23:19:36 +00005156 for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00005157 g.SetEdge(kEdges[i][0], kEdges[i][1], true);
5158 }
5159 EXPECT_THAT(FindBacktrackingMaxBPM(g),
5160 ElementsAre(Pair(3, 0),
5161 Pair(AnyOf(1, 2), 1),
5162 Pair(0, 2))) << g.DebugString();
5163}
5164
5165// Verify a few nonsquare matrices.
5166TEST_P(BipartiteNonSquareTest, Exhaustive) {
5167 size_t nlhs = GetParam().first;
5168 size_t nrhs = GetParam().second;
5169 MatchMatrix graph(nlhs, nrhs);
5170 do {
5171 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5172 internal::FindMaxBipartiteMatching(graph).size())
5173 << "graph: " << graph.DebugString()
5174 << "\nbacktracking: "
5175 << PrintToString(FindBacktrackingMaxBPM(graph))
5176 << "\nmax flow: "
5177 << PrintToString(internal::FindMaxBipartiteMatching(graph));
5178 } while (graph.NextGraph());
5179}
5180
5181INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest,
5182 testing::Values(
5183 std::make_pair(1, 2),
5184 std::make_pair(2, 1),
5185 std::make_pair(3, 2),
5186 std::make_pair(2, 3),
5187 std::make_pair(4, 1),
5188 std::make_pair(1, 4),
5189 std::make_pair(4, 3),
5190 std::make_pair(3, 4)));
5191
5192class BipartiteRandomTest
5193 : public ::testing::TestWithParam<std::pair<int, int> > {
5194};
5195
5196// Verifies a large sample of larger graphs.
5197TEST_P(BipartiteRandomTest, LargerNets) {
5198 int nodes = GetParam().first;
5199 int iters = GetParam().second;
5200 MatchMatrix graph(nodes, nodes);
5201
5202 testing::internal::Int32 seed = GTEST_FLAG(random_seed);
5203 if (seed == 0) {
5204 seed = static_cast<testing::internal::Int32>(time(NULL));
5205 }
5206
5207 for (; iters > 0; --iters, ++seed) {
5208 srand(static_cast<int>(seed));
5209 graph.Randomize();
5210 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5211 internal::FindMaxBipartiteMatching(graph).size())
5212 << " graph: " << graph.DebugString()
5213 << "\nTo reproduce the failure, rerun the test with the flag"
5214 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
5215 }
5216}
5217
5218// Test argument is a std::pair<int, int> representing (nodes, iters).
5219INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest,
5220 testing::Values(
5221 std::make_pair(5, 10000),
5222 std::make_pair(6, 5000),
5223 std::make_pair(7, 2000),
5224 std::make_pair(8, 500),
5225 std::make_pair(9, 100)));
5226
zhanyong.wan736baa82010-09-27 17:44:16 +00005227// Tests IsReadableTypeName().
5228
5229TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
5230 EXPECT_TRUE(IsReadableTypeName("int"));
5231 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
5232 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
5233 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
5234}
5235
5236TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
5237 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
5238 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
5239 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
5240}
5241
5242TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
5243 EXPECT_FALSE(
5244 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
5245 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
5246}
5247
5248TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
5249 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
5250}
5251
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005252// Tests JoinAsTuple().
5253
5254TEST(JoinAsTupleTest, JoinsEmptyTuple) {
5255 EXPECT_EQ("", JoinAsTuple(Strings()));
5256}
5257
5258TEST(JoinAsTupleTest, JoinsOneTuple) {
kosak2336e9c2014-07-28 22:57:30 +00005259 const char* fields[] = {"1"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005260 EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
5261}
5262
5263TEST(JoinAsTupleTest, JoinsTwoTuple) {
kosak2336e9c2014-07-28 22:57:30 +00005264 const char* fields[] = {"1", "a"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005265 EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
5266}
5267
5268TEST(JoinAsTupleTest, JoinsTenTuple) {
kosak2336e9c2014-07-28 22:57:30 +00005269 const char* fields[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005270 EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
5271 JoinAsTuple(Strings(fields, fields + 10)));
5272}
5273
5274// Tests FormatMatcherDescription().
5275
5276TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
5277 EXPECT_EQ("is even",
zhanyong.wanb4140802010-06-08 22:53:57 +00005278 FormatMatcherDescription(false, "IsEven", Strings()));
5279 EXPECT_EQ("not (is even)",
5280 FormatMatcherDescription(true, "IsEven", Strings()));
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005281
kosak2336e9c2014-07-28 22:57:30 +00005282 const char* params[] = {"5"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005283 EXPECT_EQ("equals 5",
zhanyong.wanb4140802010-06-08 22:53:57 +00005284 FormatMatcherDescription(false, "Equals",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005285 Strings(params, params + 1)));
5286
kosak2336e9c2014-07-28 22:57:30 +00005287 const char* params2[] = {"5", "8"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005288 EXPECT_EQ("is in range (5, 8)",
zhanyong.wanb4140802010-06-08 22:53:57 +00005289 FormatMatcherDescription(false, "IsInRange",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005290 Strings(params2, params2 + 2)));
5291}
5292
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00005293// Tests PolymorphicMatcher::mutable_impl().
5294TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
5295 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5296 DivisibleByImpl& impl = m.mutable_impl();
5297 EXPECT_EQ(42, impl.divider());
5298
5299 impl.set_divider(0);
5300 EXPECT_EQ(0, m.mutable_impl().divider());
5301}
5302
5303// Tests PolymorphicMatcher::impl().
5304TEST(PolymorphicMatcherTest, CanAccessImpl) {
5305 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5306 const DivisibleByImpl& impl = m.impl();
5307 EXPECT_EQ(42, impl.divider());
5308}
5309
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005310TEST(MatcherTupleTest, ExplainsMatchFailure) {
5311 stringstream ss1;
5312 ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
5313 make_tuple('a', 10), &ss1);
5314 EXPECT_EQ("", ss1.str()); // Successful match.
5315
5316 stringstream ss2;
5317 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5318 make_tuple(2, 'b'), &ss2);
5319 EXPECT_EQ(" Expected arg #0: is > 5\n"
5320 " Actual: 2, which is 3 less than 5\n"
zhanyong.wand60c5f42010-07-21 22:21:07 +00005321 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
5322 " Actual: 'b' (98, 0x62)\n",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005323 ss2.str()); // Failed match where both arguments need explanation.
5324
5325 stringstream ss3;
5326 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5327 make_tuple(2, 'a'), &ss3);
5328 EXPECT_EQ(" Expected arg #0: is > 5\n"
5329 " Actual: 2, which is 3 less than 5\n",
5330 ss3.str()); // Failed match where only one argument needs
5331 // explanation.
5332}
5333
zhanyong.wan33605ba2010-04-22 23:37:47 +00005334// Tests Each().
5335
5336TEST(EachTest, ExplainsMatchResultCorrectly) {
5337 set<int> a; // empty
5338
5339 Matcher<set<int> > m = Each(2);
5340 EXPECT_EQ("", Explain(m, a));
5341
zhanyong.wan736baa82010-09-27 17:44:16 +00005342 Matcher<const int(&)[1]> n = Each(1); // NOLINT
zhanyong.wan33605ba2010-04-22 23:37:47 +00005343
kosak2336e9c2014-07-28 22:57:30 +00005344 const int b[1] = {1};
zhanyong.wan33605ba2010-04-22 23:37:47 +00005345 EXPECT_EQ("", Explain(n, b));
5346
5347 n = Each(3);
5348 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
5349
5350 a.insert(1);
5351 a.insert(2);
5352 a.insert(3);
5353 m = Each(GreaterThan(0));
5354 EXPECT_EQ("", Explain(m, a));
5355
5356 m = Each(GreaterThan(10));
5357 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
5358 Explain(m, a));
5359}
5360
5361TEST(EachTest, DescribesItselfCorrectly) {
5362 Matcher<vector<int> > m = Each(1);
5363 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
5364
5365 Matcher<vector<int> > m2 = Not(m);
5366 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
5367}
5368
5369TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
5370 vector<int> some_vector;
5371 EXPECT_THAT(some_vector, Each(1));
5372 some_vector.push_back(3);
5373 EXPECT_THAT(some_vector, Not(Each(1)));
5374 EXPECT_THAT(some_vector, Each(3));
5375 some_vector.push_back(1);
5376 some_vector.push_back(2);
5377 EXPECT_THAT(some_vector, Not(Each(3)));
5378 EXPECT_THAT(some_vector, Each(Lt(3.5)));
5379
5380 vector<string> another_vector;
5381 another_vector.push_back("fee");
5382 EXPECT_THAT(another_vector, Each(string("fee")));
5383 another_vector.push_back("fie");
5384 another_vector.push_back("foe");
5385 another_vector.push_back("fum");
5386 EXPECT_THAT(another_vector, Not(Each(string("fee"))));
5387}
5388
5389TEST(EachTest, MatchesMapWhenAllElementsMatch) {
5390 map<const char*, int> my_map;
5391 const char* bar = "a string";
5392 my_map[bar] = 2;
5393 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
5394
5395 map<string, int> another_map;
5396 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5397 another_map["fee"] = 1;
5398 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5399 another_map["fie"] = 2;
5400 another_map["foe"] = 3;
5401 another_map["fum"] = 4;
5402 EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1))));
5403 EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1))));
5404 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
5405}
5406
5407TEST(EachTest, AcceptsMatcher) {
kosak2336e9c2014-07-28 22:57:30 +00005408 const int a[] = {1, 2, 3};
zhanyong.wan33605ba2010-04-22 23:37:47 +00005409 EXPECT_THAT(a, Each(Gt(0)));
5410 EXPECT_THAT(a, Not(Each(Gt(1))));
5411}
5412
5413TEST(EachTest, WorksForNativeArrayAsTuple) {
kosak2336e9c2014-07-28 22:57:30 +00005414 const int a[] = {1, 2};
zhanyong.wan33605ba2010-04-22 23:37:47 +00005415 const int* const pointer = a;
5416 EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
5417 EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
5418}
5419
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005420// For testing Pointwise().
5421class IsHalfOfMatcher {
5422 public:
5423 template <typename T1, typename T2>
5424 bool MatchAndExplain(const tuple<T1, T2>& a_pair,
5425 MatchResultListener* listener) const {
5426 if (get<0>(a_pair) == get<1>(a_pair)/2) {
5427 *listener << "where the second is " << get<1>(a_pair);
5428 return true;
5429 } else {
5430 *listener << "where the second/2 is " << get<1>(a_pair)/2;
5431 return false;
5432 }
5433 }
5434
5435 void DescribeTo(ostream* os) const {
5436 *os << "are a pair where the first is half of the second";
5437 }
5438
5439 void DescribeNegationTo(ostream* os) const {
5440 *os << "are a pair where the first isn't half of the second";
5441 }
5442};
5443
5444PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
5445 return MakePolymorphicMatcher(IsHalfOfMatcher());
5446}
5447
5448TEST(PointwiseTest, DescribesSelf) {
5449 vector<int> rhs;
5450 rhs.push_back(1);
5451 rhs.push_back(2);
5452 rhs.push_back(3);
5453 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
5454 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
5455 "in { 1, 2, 3 } are a pair where the first is half of the second",
5456 Describe(m));
5457 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
5458 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
5459 "where the first isn't half of the second",
5460 DescribeNegation(m));
5461}
5462
5463TEST(PointwiseTest, MakesCopyOfRhs) {
5464 list<signed char> rhs;
5465 rhs.push_back(2);
5466 rhs.push_back(4);
5467
kosak2336e9c2014-07-28 22:57:30 +00005468 int lhs[] = {1, 2};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005469 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
5470 EXPECT_THAT(lhs, m);
5471
5472 // Changing rhs now shouldn't affect m, which made a copy of rhs.
5473 rhs.push_back(6);
5474 EXPECT_THAT(lhs, m);
5475}
5476
5477TEST(PointwiseTest, WorksForLhsNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00005478 const int lhs[] = {1, 2, 3};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005479 vector<int> rhs;
5480 rhs.push_back(2);
5481 rhs.push_back(4);
5482 rhs.push_back(6);
5483 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
5484 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5485}
5486
5487TEST(PointwiseTest, WorksForRhsNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00005488 const int rhs[] = {1, 2, 3};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005489 vector<int> lhs;
5490 lhs.push_back(2);
5491 lhs.push_back(4);
5492 lhs.push_back(6);
5493 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
5494 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
5495}
5496
kosak2336e9c2014-07-28 22:57:30 +00005497#if GTEST_HAS_STD_INITIALIZER_LIST_
5498
5499TEST(PointwiseTest, WorksForRhsInitializerList) {
5500 const vector<int> lhs{2, 4, 6};
5501 EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
5502 EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
5503}
5504
5505#endif // GTEST_HAS_STD_INITIALIZER_LIST_
5506
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005507TEST(PointwiseTest, RejectsWrongSize) {
kosak2336e9c2014-07-28 22:57:30 +00005508 const double lhs[2] = {1, 2};
5509 const int rhs[1] = {0};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005510 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5511 EXPECT_EQ("which contains 2 values",
5512 Explain(Pointwise(Gt(), rhs), lhs));
5513
kosak2336e9c2014-07-28 22:57:30 +00005514 const int rhs2[3] = {0, 1, 2};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005515 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
5516}
5517
5518TEST(PointwiseTest, RejectsWrongContent) {
kosak2336e9c2014-07-28 22:57:30 +00005519 const double lhs[3] = {1, 2, 3};
5520 const int rhs[3] = {2, 6, 4};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005521 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
5522 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
5523 "where the second/2 is 3",
5524 Explain(Pointwise(IsHalfOf(), rhs), lhs));
5525}
5526
5527TEST(PointwiseTest, AcceptsCorrectContent) {
kosak2336e9c2014-07-28 22:57:30 +00005528 const double lhs[3] = {1, 2, 3};
5529 const int rhs[3] = {2, 4, 6};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005530 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
5531 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
5532}
5533
5534TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
kosak2336e9c2014-07-28 22:57:30 +00005535 const double lhs[3] = {1, 2, 3};
5536 const int rhs[3] = {2, 4, 6};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005537 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5538 EXPECT_THAT(lhs, Pointwise(m1, rhs));
5539 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
5540
5541 // This type works as a tuple<const double&, const int&> can be
5542 // implicitly cast to tuple<double, int>.
5543 const Matcher<tuple<double, int> > m2 = IsHalfOf();
5544 EXPECT_THAT(lhs, Pointwise(m2, rhs));
5545 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
5546}
5547
kosak2336e9c2014-07-28 22:57:30 +00005548TEST(UnorderedPointwiseTest, DescribesSelf) {
5549 vector<int> rhs;
5550 rhs.push_back(1);
5551 rhs.push_back(2);
5552 rhs.push_back(3);
5553 const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
5554 EXPECT_EQ(
5555 "has 3 elements and there exists some permutation of elements such "
5556 "that:\n"
5557 " - element #0 and 1 are a pair where the first is half of the second, "
5558 "and\n"
5559 " - element #1 and 2 are a pair where the first is half of the second, "
5560 "and\n"
5561 " - element #2 and 3 are a pair where the first is half of the second",
5562 Describe(m));
5563 EXPECT_EQ(
5564 "doesn't have 3 elements, or there exists no permutation of elements "
5565 "such that:\n"
5566 " - element #0 and 1 are a pair where the first is half of the second, "
5567 "and\n"
5568 " - element #1 and 2 are a pair where the first is half of the second, "
5569 "and\n"
5570 " - element #2 and 3 are a pair where the first is half of the second",
5571 DescribeNegation(m));
5572}
5573
5574TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
5575 list<signed char> rhs;
5576 rhs.push_back(2);
5577 rhs.push_back(4);
5578
5579 int lhs[] = {2, 1};
5580 const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
5581 EXPECT_THAT(lhs, m);
5582
5583 // Changing rhs now shouldn't affect m, which made a copy of rhs.
5584 rhs.push_back(6);
5585 EXPECT_THAT(lhs, m);
5586}
5587
5588TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
5589 const int lhs[] = {1, 2, 3};
5590 vector<int> rhs;
5591 rhs.push_back(4);
5592 rhs.push_back(6);
5593 rhs.push_back(2);
5594 EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
5595 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
5596}
5597
5598TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
5599 const int rhs[] = {1, 2, 3};
5600 vector<int> lhs;
5601 lhs.push_back(4);
5602 lhs.push_back(2);
5603 lhs.push_back(6);
5604 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
5605 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
5606}
5607
5608#if GTEST_HAS_STD_INITIALIZER_LIST_
5609
5610TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
5611 const vector<int> lhs{2, 4, 6};
5612 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
5613 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
5614}
5615
5616#endif // GTEST_HAS_STD_INITIALIZER_LIST_
5617
5618TEST(UnorderedPointwiseTest, RejectsWrongSize) {
5619 const double lhs[2] = {1, 2};
5620 const int rhs[1] = {0};
5621 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
5622 EXPECT_EQ("which has 2 elements",
5623 Explain(UnorderedPointwise(Gt(), rhs), lhs));
5624
5625 const int rhs2[3] = {0, 1, 2};
5626 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
5627}
5628
5629TEST(UnorderedPointwiseTest, RejectsWrongContent) {
5630 const double lhs[3] = {1, 2, 3};
5631 const int rhs[3] = {2, 6, 6};
5632 EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
5633 EXPECT_EQ("where the following elements don't match any matchers:\n"
5634 "element #1: 2",
5635 Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
5636}
5637
5638TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
5639 const double lhs[3] = {1, 2, 3};
5640 const int rhs[3] = {2, 4, 6};
5641 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
5642}
5643
5644TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
5645 const double lhs[3] = {1, 2, 3};
5646 const int rhs[3] = {6, 4, 2};
5647 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
5648}
5649
5650TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
5651 const double lhs[3] = {1, 2, 3};
5652 const int rhs[3] = {4, 6, 2};
5653 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5654 EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
5655
5656 // This type works as a tuple<const double&, const int&> can be
5657 // implicitly cast to tuple<double, int>.
5658 const Matcher<tuple<double, int> > m2 = IsHalfOf();
5659 EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
5660}
5661
shiqiane35fdd92008-12-10 05:08:54 +00005662} // namespace gmock_matchers_test
5663} // namespace testing