blob: 11b6de2d3df501583fb9e9ff65b83fc0b67c30f2 [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file tests some commonly used argument matchers.
35
zhanyong.wan53e08c42010-09-14 05:38:21 +000036#include "gmock/gmock-matchers.h"
zhanyong.wan320814a2013-03-01 00:20:30 +000037#include "gmock/gmock-more-matchers.h"
shiqiane35fdd92008-12-10 05:08:54 +000038
39#include <string.h>
zhanyong.wanfb25d532013-07-28 08:24:00 +000040#include <time.h>
zhanyong.wana9a59e02013-03-27 16:14:55 +000041#include <deque>
shiqiane35fdd92008-12-10 05:08:54 +000042#include <functional>
zhanyong.wana862f1d2010-03-15 21:23:04 +000043#include <iostream>
zhanyong.wana9a59e02013-03-27 16:14:55 +000044#include <iterator>
zhanyong.wan616180e2013-06-18 18:49:51 +000045#include <limits>
zhanyong.wan6a896b52009-01-16 01:13:50 +000046#include <list>
47#include <map>
48#include <set>
shiqiane35fdd92008-12-10 05:08:54 +000049#include <sstream>
zhanyong.wan6a896b52009-01-16 01:13:50 +000050#include <string>
zhanyong.wanf5e1ce52009-09-16 07:02:02 +000051#include <utility>
zhanyong.wan6a896b52009-01-16 01:13:50 +000052#include <vector>
zhanyong.wan53e08c42010-09-14 05:38:21 +000053#include "gmock/gmock.h"
54#include "gtest/gtest.h"
55#include "gtest/gtest-spi.h"
shiqiane35fdd92008-12-10 05:08:54 +000056
kosak5b9cbbb2014-11-17 00:28:55 +000057#if GTEST_HAS_STD_FORWARD_LIST_
kosakb6a34882014-03-12 21:06:46 +000058# include <forward_list> // NOLINT
59#endif
60
shiqiane35fdd92008-12-10 05:08:54 +000061namespace testing {
zhanyong.wan4a5330d2009-02-19 00:36:44 +000062
63namespace internal {
vladlosev587c1b32011-05-20 00:42:22 +000064GTEST_API_ string JoinAsTuple(const Strings& fields);
zhanyong.wan4a5330d2009-02-19 00:36:44 +000065} // namespace internal
66
shiqiane35fdd92008-12-10 05:08:54 +000067namespace gmock_matchers_test {
68
zhanyong.wan898725c2011-09-16 16:45:39 +000069using std::greater;
70using std::less;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000071using std::list;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000072using std::make_pair;
zhanyong.wanb5937da2009-07-16 20:26:41 +000073using std::map;
74using std::multimap;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000075using std::multiset;
76using std::ostream;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000077using std::pair;
zhanyong.wan33605ba2010-04-22 23:37:47 +000078using std::set;
shiqiane35fdd92008-12-10 05:08:54 +000079using std::stringstream;
zhanyong.wan33605ba2010-04-22 23:37:47 +000080using std::vector;
shiqiane35fdd92008-12-10 05:08:54 +000081using testing::A;
zhanyong.wanbf550852009-06-09 06:09:53 +000082using testing::AllArgs;
shiqiane35fdd92008-12-10 05:08:54 +000083using testing::AllOf;
84using testing::An;
85using testing::AnyOf;
86using testing::ByRef;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000087using testing::ContainsRegex;
shiqiane35fdd92008-12-10 05:08:54 +000088using testing::DoubleEq;
zhanyong.wan616180e2013-06-18 18:49:51 +000089using testing::DoubleNear;
shiqiane35fdd92008-12-10 05:08:54 +000090using testing::EndsWith;
91using testing::Eq;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000092using testing::ExplainMatchResult;
shiqiane35fdd92008-12-10 05:08:54 +000093using testing::Field;
94using testing::FloatEq;
zhanyong.wan616180e2013-06-18 18:49:51 +000095using testing::FloatNear;
shiqiane35fdd92008-12-10 05:08:54 +000096using testing::Ge;
97using testing::Gt;
98using testing::HasSubstr;
zhanyong.wan320814a2013-03-01 00:20:30 +000099using testing::IsEmpty;
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000100using testing::IsNull;
zhanyong.wanb5937da2009-07-16 20:26:41 +0000101using testing::Key;
shiqiane35fdd92008-12-10 05:08:54 +0000102using testing::Le;
103using testing::Lt;
104using testing::MakeMatcher;
105using testing::MakePolymorphicMatcher;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000106using testing::MatchResultListener;
shiqiane35fdd92008-12-10 05:08:54 +0000107using testing::Matcher;
108using testing::MatcherCast;
109using testing::MatcherInterface;
110using testing::Matches;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000111using testing::MatchesRegex;
shiqiane35fdd92008-12-10 05:08:54 +0000112using testing::NanSensitiveDoubleEq;
zhanyong.wan616180e2013-06-18 18:49:51 +0000113using testing::NanSensitiveDoubleNear;
shiqiane35fdd92008-12-10 05:08:54 +0000114using testing::NanSensitiveFloatEq;
zhanyong.wan616180e2013-06-18 18:49:51 +0000115using testing::NanSensitiveFloatNear;
shiqiane35fdd92008-12-10 05:08:54 +0000116using testing::Ne;
117using testing::Not;
118using testing::NotNull;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000119using testing::Pair;
shiqiane35fdd92008-12-10 05:08:54 +0000120using testing::Pointee;
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000121using testing::Pointwise;
shiqiane35fdd92008-12-10 05:08:54 +0000122using testing::PolymorphicMatcher;
123using testing::Property;
124using testing::Ref;
125using testing::ResultOf;
zhanyong.wana31d9ce2013-03-01 01:50:17 +0000126using testing::SizeIs;
shiqiane35fdd92008-12-10 05:08:54 +0000127using testing::StartsWith;
128using testing::StrCaseEq;
129using testing::StrCaseNe;
130using testing::StrEq;
131using testing::StrNe;
kosak2336e9c2014-07-28 22:57:30 +0000132using testing::StringMatchResultListener;
shiqiane35fdd92008-12-10 05:08:54 +0000133using testing::Truly;
134using testing::TypedEq;
kosak2336e9c2014-07-28 22:57:30 +0000135using testing::UnorderedPointwise;
zhanyong.wanb8243162009-06-04 05:48:20 +0000136using testing::Value;
zhanyong.wan898725c2011-09-16 16:45:39 +0000137using testing::WhenSorted;
138using testing::WhenSortedBy;
shiqiane35fdd92008-12-10 05:08:54 +0000139using testing::_;
kosak2336e9c2014-07-28 22:57:30 +0000140using testing::get;
zhanyong.wana862f1d2010-03-15 21:23:04 +0000141using testing::internal::DummyMatchResultListener;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000142using testing::internal::ElementMatcherPair;
143using testing::internal::ElementMatcherPairs;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000144using testing::internal::ExplainMatchFailureTupleTo;
shiqiane35fdd92008-12-10 05:08:54 +0000145using testing::internal::FloatingEqMatcher;
zhanyong.wanb4140802010-06-08 22:53:57 +0000146using testing::internal::FormatMatcherDescription;
zhanyong.wan736baa82010-09-27 17:44:16 +0000147using testing::internal::IsReadableTypeName;
zhanyong.wan4a5330d2009-02-19 00:36:44 +0000148using testing::internal::JoinAsTuple;
kosakf6df4c62015-07-19 22:58:38 +0000149using testing::internal::linked_ptr;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000150using testing::internal::MatchMatrix;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000151using testing::internal::RE;
kosakf6df4c62015-07-19 22:58:38 +0000152using testing::internal::scoped_ptr;
zhanyong.wana862f1d2010-03-15 21:23:04 +0000153using testing::internal::StreamMatchResultListener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000154using testing::internal::Strings;
vladlosev79b83502009-11-18 00:43:37 +0000155using testing::internal::linked_ptr;
vladloseve56daa72009-11-18 01:08:08 +0000156using testing::internal::scoped_ptr;
shiqiane35fdd92008-12-10 05:08:54 +0000157using testing::internal::string;
kosak2336e9c2014-07-28 22:57:30 +0000158using testing::make_tuple;
159using testing::tuple;
shiqiane35fdd92008-12-10 05:08:54 +0000160
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000161// For testing ExplainMatchResultTo().
162class GreaterThanMatcher : public MatcherInterface<int> {
163 public:
164 explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
165
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000166 virtual void DescribeTo(ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000167 *os << "is > " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000168 }
169
zhanyong.wandb22c222010-01-28 21:52:29 +0000170 virtual bool MatchAndExplain(int lhs,
171 MatchResultListener* listener) const {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000172 const int diff = lhs - rhs_;
173 if (diff > 0) {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000174 *listener << "which is " << diff << " more than " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000175 } else if (diff == 0) {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000176 *listener << "which is the same as " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000177 } else {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000178 *listener << "which is " << -diff << " less than " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000179 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000180
181 return lhs > rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000182 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000183
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000184 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000185 int rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000186};
187
188Matcher<int> GreaterThan(int n) {
189 return MakeMatcher(new GreaterThanMatcher(n));
190}
191
zhanyong.wan736baa82010-09-27 17:44:16 +0000192string OfType(const string& type_name) {
193#if GTEST_HAS_RTTI
194 return " (of type " + type_name + ")";
195#else
196 return "";
197#endif
198}
199
shiqiane35fdd92008-12-10 05:08:54 +0000200// Returns the description of the given matcher.
201template <typename T>
202string Describe(const Matcher<T>& m) {
203 stringstream ss;
204 m.DescribeTo(&ss);
205 return ss.str();
206}
207
208// Returns the description of the negation of the given matcher.
209template <typename T>
210string DescribeNegation(const Matcher<T>& m) {
211 stringstream ss;
212 m.DescribeNegationTo(&ss);
213 return ss.str();
214}
215
216// Returns the reason why x matches, or doesn't match, m.
217template <typename MatcherType, typename Value>
218string Explain(const MatcherType& m, const Value& x) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000219 StringMatchResultListener listener;
220 ExplainMatchResult(m, x, &listener);
221 return listener.str();
shiqiane35fdd92008-12-10 05:08:54 +0000222}
223
zhanyong.wana862f1d2010-03-15 21:23:04 +0000224TEST(MatchResultListenerTest, StreamingWorks) {
225 StringMatchResultListener listener;
226 listener << "hi" << 5;
227 EXPECT_EQ("hi5", listener.str());
228
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000229 listener.Clear();
230 EXPECT_EQ("", listener.str());
231
232 listener << 42;
233 EXPECT_EQ("42", listener.str());
234
zhanyong.wana862f1d2010-03-15 21:23:04 +0000235 // Streaming shouldn't crash when the underlying ostream is NULL.
236 DummyMatchResultListener dummy;
237 dummy << "hi" << 5;
238}
239
240TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
241 EXPECT_TRUE(DummyMatchResultListener().stream() == NULL);
242 EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL);
243
244 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
245}
246
247TEST(MatchResultListenerTest, IsInterestedWorks) {
248 EXPECT_TRUE(StringMatchResultListener().IsInterested());
249 EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
250
251 EXPECT_FALSE(DummyMatchResultListener().IsInterested());
252 EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested());
253}
254
shiqiane35fdd92008-12-10 05:08:54 +0000255// Makes sure that the MatcherInterface<T> interface doesn't
256// change.
257class EvenMatcherImpl : public MatcherInterface<int> {
258 public:
zhanyong.wandb22c222010-01-28 21:52:29 +0000259 virtual bool MatchAndExplain(int x,
260 MatchResultListener* /* listener */) const {
261 return x % 2 == 0;
262 }
shiqiane35fdd92008-12-10 05:08:54 +0000263
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000264 virtual void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +0000265 *os << "is an even number";
266 }
267
268 // We deliberately don't define DescribeNegationTo() and
269 // ExplainMatchResultTo() here, to make sure the definition of these
270 // two methods is optional.
271};
272
zhanyong.wana862f1d2010-03-15 21:23:04 +0000273// Makes sure that the MatcherInterface API doesn't change.
274TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
shiqiane35fdd92008-12-10 05:08:54 +0000275 EvenMatcherImpl m;
276}
277
zhanyong.wan82113312010-01-08 21:55:40 +0000278// Tests implementing a monomorphic matcher using MatchAndExplain().
279
280class NewEvenMatcherImpl : public MatcherInterface<int> {
281 public:
282 virtual bool MatchAndExplain(int x, MatchResultListener* listener) const {
283 const bool match = x % 2 == 0;
284 // Verifies that we can stream to a listener directly.
285 *listener << "value % " << 2;
286 if (listener->stream() != NULL) {
287 // Verifies that we can stream to a listener's underlying stream
288 // too.
289 *listener->stream() << " == " << (x % 2);
290 }
291 return match;
292 }
293
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000294 virtual void DescribeTo(ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000295 *os << "is an even number";
296 }
297};
298
299TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
300 Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
301 EXPECT_TRUE(m.Matches(2));
302 EXPECT_FALSE(m.Matches(3));
303 EXPECT_EQ("value % 2 == 0", Explain(m, 2));
304 EXPECT_EQ("value % 2 == 1", Explain(m, 3));
305}
306
shiqiane35fdd92008-12-10 05:08:54 +0000307// Tests default-constructing a matcher.
308TEST(MatcherTest, CanBeDefaultConstructed) {
309 Matcher<double> m;
310}
311
312// Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
313TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
314 const MatcherInterface<int>* impl = new EvenMatcherImpl;
315 Matcher<int> m(impl);
316 EXPECT_TRUE(m.Matches(4));
317 EXPECT_FALSE(m.Matches(5));
318}
319
320// Tests that value can be used in place of Eq(value).
321TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
322 Matcher<int> m1 = 5;
323 EXPECT_TRUE(m1.Matches(5));
324 EXPECT_FALSE(m1.Matches(6));
325}
326
327// Tests that NULL can be used in place of Eq(NULL).
328TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
329 Matcher<int*> m1 = NULL;
330 EXPECT_TRUE(m1.Matches(NULL));
331 int n = 0;
332 EXPECT_FALSE(m1.Matches(&n));
333}
334
335// Tests that matchers are copyable.
336TEST(MatcherTest, IsCopyable) {
337 // Tests the copy constructor.
338 Matcher<bool> m1 = Eq(false);
339 EXPECT_TRUE(m1.Matches(false));
340 EXPECT_FALSE(m1.Matches(true));
341
342 // Tests the assignment operator.
343 m1 = Eq(true);
344 EXPECT_TRUE(m1.Matches(true));
345 EXPECT_FALSE(m1.Matches(false));
346}
347
348// Tests that Matcher<T>::DescribeTo() calls
349// MatcherInterface<T>::DescribeTo().
350TEST(MatcherTest, CanDescribeItself) {
351 EXPECT_EQ("is an even number",
352 Describe(Matcher<int>(new EvenMatcherImpl)));
353}
354
zhanyong.wan82113312010-01-08 21:55:40 +0000355// Tests Matcher<T>::MatchAndExplain().
356TEST(MatcherTest, MatchAndExplain) {
357 Matcher<int> m = GreaterThan(0);
zhanyong.wan34b034c2010-03-05 21:23:23 +0000358 StringMatchResultListener listener1;
zhanyong.wan82113312010-01-08 21:55:40 +0000359 EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000360 EXPECT_EQ("which is 42 more than 0", listener1.str());
zhanyong.wan82113312010-01-08 21:55:40 +0000361
zhanyong.wan34b034c2010-03-05 21:23:23 +0000362 StringMatchResultListener listener2;
zhanyong.wan82113312010-01-08 21:55:40 +0000363 EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000364 EXPECT_EQ("which is 9 less than 0", listener2.str());
zhanyong.wan82113312010-01-08 21:55:40 +0000365}
366
shiqiane35fdd92008-12-10 05:08:54 +0000367// Tests that a C-string literal can be implicitly converted to a
368// Matcher<string> or Matcher<const string&>.
369TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
370 Matcher<string> m1 = "hi";
371 EXPECT_TRUE(m1.Matches("hi"));
372 EXPECT_FALSE(m1.Matches("hello"));
373
374 Matcher<const string&> m2 = "hi";
375 EXPECT_TRUE(m2.Matches("hi"));
376 EXPECT_FALSE(m2.Matches("hello"));
377}
378
379// Tests that a string object can be implicitly converted to a
380// Matcher<string> or Matcher<const string&>.
381TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
382 Matcher<string> m1 = string("hi");
383 EXPECT_TRUE(m1.Matches("hi"));
384 EXPECT_FALSE(m1.Matches("hello"));
385
386 Matcher<const string&> m2 = string("hi");
387 EXPECT_TRUE(m2.Matches("hi"));
388 EXPECT_FALSE(m2.Matches("hello"));
389}
390
zhanyong.wan1f122a02013-03-25 16:27:03 +0000391#if GTEST_HAS_STRING_PIECE_
392// Tests that a C-string literal can be implicitly converted to a
393// Matcher<StringPiece> or Matcher<const StringPiece&>.
394TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
395 Matcher<StringPiece> m1 = "cats";
396 EXPECT_TRUE(m1.Matches("cats"));
397 EXPECT_FALSE(m1.Matches("dogs"));
398
399 Matcher<const StringPiece&> m2 = "cats";
400 EXPECT_TRUE(m2.Matches("cats"));
401 EXPECT_FALSE(m2.Matches("dogs"));
402}
403
404// Tests that a string object can be implicitly converted to a
405// Matcher<StringPiece> or Matcher<const StringPiece&>.
406TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromString) {
407 Matcher<StringPiece> m1 = string("cats");
408 EXPECT_TRUE(m1.Matches("cats"));
409 EXPECT_FALSE(m1.Matches("dogs"));
410
411 Matcher<const StringPiece&> m2 = string("cats");
412 EXPECT_TRUE(m2.Matches("cats"));
413 EXPECT_FALSE(m2.Matches("dogs"));
414}
415
416// Tests that a StringPiece object can be implicitly converted to a
417// Matcher<StringPiece> or Matcher<const StringPiece&>.
418TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromStringPiece) {
419 Matcher<StringPiece> m1 = StringPiece("cats");
420 EXPECT_TRUE(m1.Matches("cats"));
421 EXPECT_FALSE(m1.Matches("dogs"));
422
423 Matcher<const StringPiece&> m2 = StringPiece("cats");
424 EXPECT_TRUE(m2.Matches("cats"));
425 EXPECT_FALSE(m2.Matches("dogs"));
426}
427#endif // GTEST_HAS_STRING_PIECE_
428
shiqiane35fdd92008-12-10 05:08:54 +0000429// Tests that MakeMatcher() constructs a Matcher<T> from a
430// MatcherInterface* without requiring the user to explicitly
431// write the type.
432TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
433 const MatcherInterface<int>* dummy_impl = NULL;
434 Matcher<int> m = MakeMatcher(dummy_impl);
435}
436
zhanyong.wan82113312010-01-08 21:55:40 +0000437// Tests that MakePolymorphicMatcher() can construct a polymorphic
438// matcher from its implementation using the old API.
zhanyong.wan33605ba2010-04-22 23:37:47 +0000439const int g_bar = 1;
shiqiane35fdd92008-12-10 05:08:54 +0000440class ReferencesBarOrIsZeroImpl {
441 public:
442 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +0000443 bool MatchAndExplain(const T& x,
444 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000445 const void* p = &x;
zhanyong.wan33605ba2010-04-22 23:37:47 +0000446 return p == &g_bar || x == 0;
shiqiane35fdd92008-12-10 05:08:54 +0000447 }
448
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000449 void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
shiqiane35fdd92008-12-10 05:08:54 +0000450
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000451 void DescribeNegationTo(ostream* os) const {
zhanyong.wan33605ba2010-04-22 23:37:47 +0000452 *os << "doesn't reference g_bar and is not zero";
shiqiane35fdd92008-12-10 05:08:54 +0000453 }
454};
455
456// This function verifies that MakePolymorphicMatcher() returns a
457// PolymorphicMatcher<T> where T is the argument's type.
458PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
459 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
460}
461
zhanyong.wan82113312010-01-08 21:55:40 +0000462TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
shiqiane35fdd92008-12-10 05:08:54 +0000463 // Using a polymorphic matcher to match a reference type.
464 Matcher<const int&> m1 = ReferencesBarOrIsZero();
465 EXPECT_TRUE(m1.Matches(0));
466 // Verifies that the identity of a by-reference argument is preserved.
zhanyong.wan33605ba2010-04-22 23:37:47 +0000467 EXPECT_TRUE(m1.Matches(g_bar));
shiqiane35fdd92008-12-10 05:08:54 +0000468 EXPECT_FALSE(m1.Matches(1));
zhanyong.wan33605ba2010-04-22 23:37:47 +0000469 EXPECT_EQ("g_bar or zero", Describe(m1));
shiqiane35fdd92008-12-10 05:08:54 +0000470
471 // Using a polymorphic matcher to match a value type.
472 Matcher<double> m2 = ReferencesBarOrIsZero();
473 EXPECT_TRUE(m2.Matches(0.0));
474 EXPECT_FALSE(m2.Matches(0.1));
zhanyong.wan33605ba2010-04-22 23:37:47 +0000475 EXPECT_EQ("g_bar or zero", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +0000476}
477
zhanyong.wan82113312010-01-08 21:55:40 +0000478// Tests implementing a polymorphic matcher using MatchAndExplain().
479
480class PolymorphicIsEvenImpl {
481 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000482 void DescribeTo(ostream* os) const { *os << "is even"; }
zhanyong.wan82113312010-01-08 21:55:40 +0000483
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000484 void DescribeNegationTo(ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000485 *os << "is odd";
486 }
zhanyong.wan82113312010-01-08 21:55:40 +0000487
zhanyong.wandb22c222010-01-28 21:52:29 +0000488 template <typename T>
489 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
490 // Verifies that we can stream to the listener directly.
491 *listener << "% " << 2;
492 if (listener->stream() != NULL) {
493 // Verifies that we can stream to the listener's underlying stream
494 // too.
495 *listener->stream() << " == " << (x % 2);
496 }
497 return (x % 2) == 0;
zhanyong.wan82113312010-01-08 21:55:40 +0000498 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000499};
zhanyong.wan82113312010-01-08 21:55:40 +0000500
501PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
502 return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
503}
504
505TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
506 // Using PolymorphicIsEven() as a Matcher<int>.
507 const Matcher<int> m1 = PolymorphicIsEven();
508 EXPECT_TRUE(m1.Matches(42));
509 EXPECT_FALSE(m1.Matches(43));
510 EXPECT_EQ("is even", Describe(m1));
511
512 const Matcher<int> not_m1 = Not(m1);
513 EXPECT_EQ("is odd", Describe(not_m1));
514
515 EXPECT_EQ("% 2 == 0", Explain(m1, 42));
516
517 // Using PolymorphicIsEven() as a Matcher<char>.
518 const Matcher<char> m2 = PolymorphicIsEven();
519 EXPECT_TRUE(m2.Matches('\x42'));
520 EXPECT_FALSE(m2.Matches('\x43'));
521 EXPECT_EQ("is even", Describe(m2));
522
523 const Matcher<char> not_m2 = Not(m2);
524 EXPECT_EQ("is odd", Describe(not_m2));
525
526 EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
527}
528
shiqiane35fdd92008-12-10 05:08:54 +0000529// Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
530TEST(MatcherCastTest, FromPolymorphicMatcher) {
531 Matcher<int> m = MatcherCast<int>(Eq(5));
532 EXPECT_TRUE(m.Matches(5));
533 EXPECT_FALSE(m.Matches(6));
534}
535
536// For testing casting matchers between compatible types.
537class IntValue {
538 public:
539 // An int can be statically (although not implicitly) cast to a
540 // IntValue.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000541 explicit IntValue(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +0000542
543 int value() const { return value_; }
544 private:
545 int value_;
546};
547
548// For testing casting matchers between compatible types.
549bool IsPositiveIntValue(const IntValue& foo) {
550 return foo.value() > 0;
551}
552
553// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
554// can be statically converted to U.
555TEST(MatcherCastTest, FromCompatibleType) {
556 Matcher<double> m1 = Eq(2.0);
557 Matcher<int> m2 = MatcherCast<int>(m1);
558 EXPECT_TRUE(m2.Matches(2));
559 EXPECT_FALSE(m2.Matches(3));
560
561 Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
562 Matcher<int> m4 = MatcherCast<int>(m3);
563 // In the following, the arguments 1 and 0 are statically converted
564 // to IntValue objects, and then tested by the IsPositiveIntValue()
565 // predicate.
566 EXPECT_TRUE(m4.Matches(1));
567 EXPECT_FALSE(m4.Matches(0));
568}
569
570// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
571TEST(MatcherCastTest, FromConstReferenceToNonReference) {
572 Matcher<const int&> m1 = Eq(0);
573 Matcher<int> m2 = MatcherCast<int>(m1);
574 EXPECT_TRUE(m2.Matches(0));
575 EXPECT_FALSE(m2.Matches(1));
576}
577
578// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
579TEST(MatcherCastTest, FromReferenceToNonReference) {
580 Matcher<int&> m1 = Eq(0);
581 Matcher<int> m2 = MatcherCast<int>(m1);
582 EXPECT_TRUE(m2.Matches(0));
583 EXPECT_FALSE(m2.Matches(1));
584}
585
586// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
587TEST(MatcherCastTest, FromNonReferenceToConstReference) {
588 Matcher<int> m1 = Eq(0);
589 Matcher<const int&> m2 = MatcherCast<const int&>(m1);
590 EXPECT_TRUE(m2.Matches(0));
591 EXPECT_FALSE(m2.Matches(1));
592}
593
594// Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
595TEST(MatcherCastTest, FromNonReferenceToReference) {
596 Matcher<int> m1 = Eq(0);
597 Matcher<int&> m2 = MatcherCast<int&>(m1);
598 int n = 0;
599 EXPECT_TRUE(m2.Matches(n));
600 n = 1;
601 EXPECT_FALSE(m2.Matches(n));
602}
603
604// Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
605TEST(MatcherCastTest, FromSameType) {
606 Matcher<int> m1 = Eq(0);
607 Matcher<int> m2 = MatcherCast<int>(m1);
608 EXPECT_TRUE(m2.Matches(0));
609 EXPECT_FALSE(m2.Matches(1));
610}
611
kosak506340a2014-11-17 01:47:54 +0000612// Implicitly convertible from any type.
jgm79a367e2012-04-10 16:02:11 +0000613struct ConvertibleFromAny {
614 ConvertibleFromAny(int a_value) : value(a_value) {}
615 template <typename T>
kosak506340a2014-11-17 01:47:54 +0000616 ConvertibleFromAny(const T& /*a_value*/) : value(-1) {
jgm79a367e2012-04-10 16:02:11 +0000617 ADD_FAILURE() << "Conversion constructor called";
618 }
619 int value;
620};
621
622bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
623 return a.value == b.value;
624}
625
626ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
627 return os << a.value;
628}
629
630TEST(MatcherCastTest, ConversionConstructorIsUsed) {
631 Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
632 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
633 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
634}
635
636TEST(MatcherCastTest, FromConvertibleFromAny) {
637 Matcher<ConvertibleFromAny> m =
638 MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
639 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
640 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
641}
642
kosak5f2a6ca2013-12-03 01:43:07 +0000643struct IntReferenceWrapper {
644 IntReferenceWrapper(const int& a_value) : value(&a_value) {}
645 const int* value;
646};
647
648bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
649 return a.value == b.value;
650}
651
652TEST(MatcherCastTest, ValueIsNotCopied) {
653 int n = 42;
654 Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
655 // Verify that the matcher holds a reference to n, not to its temporary copy.
656 EXPECT_TRUE(m.Matches(n));
657}
658
billydonahue1f5fdea2014-05-19 17:54:51 +0000659class Base {
660 public:
661 virtual ~Base() {}
662 Base() {}
663 private:
664 GTEST_DISALLOW_COPY_AND_ASSIGN_(Base);
665};
666
667class Derived : public Base {
668 public:
669 Derived() : Base() {}
670 int i;
671};
672
673class OtherDerived : public Base {};
zhanyong.wan18490652009-05-11 18:54:08 +0000674
675// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
676TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
677 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
678 EXPECT_TRUE(m2.Matches(' '));
679 EXPECT_FALSE(m2.Matches('\n'));
680}
681
zhanyong.wan16cf4732009-05-14 20:55:30 +0000682// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
683// T and U are arithmetic types and T can be losslessly converted to
684// U.
685TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
zhanyong.wan18490652009-05-11 18:54:08 +0000686 Matcher<double> m1 = DoubleEq(1.0);
zhanyong.wan16cf4732009-05-14 20:55:30 +0000687 Matcher<float> m2 = SafeMatcherCast<float>(m1);
688 EXPECT_TRUE(m2.Matches(1.0f));
689 EXPECT_FALSE(m2.Matches(2.0f));
690
691 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
692 EXPECT_TRUE(m3.Matches('a'));
693 EXPECT_FALSE(m3.Matches('b'));
zhanyong.wan18490652009-05-11 18:54:08 +0000694}
695
696// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
697// are pointers or references to a derived and a base class, correspondingly.
698TEST(SafeMatcherCastTest, FromBaseClass) {
699 Derived d, d2;
700 Matcher<Base*> m1 = Eq(&d);
701 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
702 EXPECT_TRUE(m2.Matches(&d));
703 EXPECT_FALSE(m2.Matches(&d2));
704
705 Matcher<Base&> m3 = Ref(d);
706 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
707 EXPECT_TRUE(m4.Matches(d));
708 EXPECT_FALSE(m4.Matches(d2));
709}
710
711// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
712TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
713 int n = 0;
714 Matcher<const int&> m1 = Ref(n);
715 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
716 int n1 = 0;
717 EXPECT_TRUE(m2.Matches(n));
718 EXPECT_FALSE(m2.Matches(n1));
719}
720
721// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
722TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
723 Matcher<int> m1 = Eq(0);
724 Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
725 EXPECT_TRUE(m2.Matches(0));
726 EXPECT_FALSE(m2.Matches(1));
727}
728
729// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
730TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
731 Matcher<int> m1 = Eq(0);
732 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
733 int n = 0;
734 EXPECT_TRUE(m2.Matches(n));
735 n = 1;
736 EXPECT_FALSE(m2.Matches(n));
737}
738
739// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
740TEST(SafeMatcherCastTest, FromSameType) {
741 Matcher<int> m1 = Eq(0);
742 Matcher<int> m2 = SafeMatcherCast<int>(m1);
743 EXPECT_TRUE(m2.Matches(0));
744 EXPECT_FALSE(m2.Matches(1));
745}
746
jgm79a367e2012-04-10 16:02:11 +0000747TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
748 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
749 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
750 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
751}
752
753TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
754 Matcher<ConvertibleFromAny> m =
755 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
756 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
757 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
758}
759
kosak5f2a6ca2013-12-03 01:43:07 +0000760TEST(SafeMatcherCastTest, ValueIsNotCopied) {
761 int n = 42;
762 Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
763 // Verify that the matcher holds a reference to n, not to its temporary copy.
764 EXPECT_TRUE(m.Matches(n));
765}
766
kosak9b1a9442015-04-28 23:06:58 +0000767TEST(ExpectThat, TakesLiterals) {
768 EXPECT_THAT(1, 1);
769 EXPECT_THAT(1.0, 1.0);
770 EXPECT_THAT(string(), "");
771}
772
773TEST(ExpectThat, TakesFunctions) {
774 struct Helper {
775 static void Func() {}
776 };
777 void (*func)() = Helper::Func;
778 EXPECT_THAT(func, Helper::Func);
779 EXPECT_THAT(func, &Helper::Func);
780}
781
shiqiane35fdd92008-12-10 05:08:54 +0000782// Tests that A<T>() matches any value of type T.
783TEST(ATest, MatchesAnyValue) {
784 // Tests a matcher for a value type.
785 Matcher<double> m1 = A<double>();
786 EXPECT_TRUE(m1.Matches(91.43));
787 EXPECT_TRUE(m1.Matches(-15.32));
788
789 // Tests a matcher for a reference type.
790 int a = 2;
791 int b = -6;
792 Matcher<int&> m2 = A<int&>();
793 EXPECT_TRUE(m2.Matches(a));
794 EXPECT_TRUE(m2.Matches(b));
795}
796
zhanyong.wanf4274522013-04-24 02:49:43 +0000797TEST(ATest, WorksForDerivedClass) {
798 Base base;
799 Derived derived;
800 EXPECT_THAT(&base, A<Base*>());
801 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
802 EXPECT_THAT(&derived, A<Base*>());
803 EXPECT_THAT(&derived, A<Derived*>());
804}
805
shiqiane35fdd92008-12-10 05:08:54 +0000806// Tests that A<T>() describes itself properly.
807TEST(ATest, CanDescribeSelf) {
808 EXPECT_EQ("is anything", Describe(A<bool>()));
809}
810
811// Tests that An<T>() matches any value of type T.
812TEST(AnTest, MatchesAnyValue) {
813 // Tests a matcher for a value type.
814 Matcher<int> m1 = An<int>();
815 EXPECT_TRUE(m1.Matches(9143));
816 EXPECT_TRUE(m1.Matches(-1532));
817
818 // Tests a matcher for a reference type.
819 int a = 2;
820 int b = -6;
821 Matcher<int&> m2 = An<int&>();
822 EXPECT_TRUE(m2.Matches(a));
823 EXPECT_TRUE(m2.Matches(b));
824}
825
826// Tests that An<T>() describes itself properly.
827TEST(AnTest, CanDescribeSelf) {
828 EXPECT_EQ("is anything", Describe(An<int>()));
829}
830
831// Tests that _ can be used as a matcher for any type and matches any
832// value of that type.
833TEST(UnderscoreTest, MatchesAnyValue) {
834 // Uses _ as a matcher for a value type.
835 Matcher<int> m1 = _;
836 EXPECT_TRUE(m1.Matches(123));
837 EXPECT_TRUE(m1.Matches(-242));
838
839 // Uses _ as a matcher for a reference type.
840 bool a = false;
841 const bool b = true;
842 Matcher<const bool&> m2 = _;
843 EXPECT_TRUE(m2.Matches(a));
844 EXPECT_TRUE(m2.Matches(b));
845}
846
847// Tests that _ describes itself properly.
848TEST(UnderscoreTest, CanDescribeSelf) {
849 Matcher<int> m = _;
850 EXPECT_EQ("is anything", Describe(m));
851}
852
853// Tests that Eq(x) matches any value equal to x.
854TEST(EqTest, MatchesEqualValue) {
855 // 2 C-strings with same content but different addresses.
856 const char a1[] = "hi";
857 const char a2[] = "hi";
858
859 Matcher<const char*> m1 = Eq(a1);
860 EXPECT_TRUE(m1.Matches(a1));
861 EXPECT_FALSE(m1.Matches(a2));
862}
863
864// Tests that Eq(v) describes itself properly.
865
866class Unprintable {
867 public:
868 Unprintable() : c_('a') {}
869
zhanyong.wan32de5f52009-12-23 00:13:23 +0000870 bool operator==(const Unprintable& /* rhs */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000871 private:
872 char c_;
873};
874
875TEST(EqTest, CanDescribeSelf) {
876 Matcher<Unprintable> m = Eq(Unprintable());
877 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
878}
879
880// Tests that Eq(v) can be used to match any type that supports
881// comparing with type T, where T is v's type.
882TEST(EqTest, IsPolymorphic) {
883 Matcher<int> m1 = Eq(1);
884 EXPECT_TRUE(m1.Matches(1));
885 EXPECT_FALSE(m1.Matches(2));
886
887 Matcher<char> m2 = Eq(1);
888 EXPECT_TRUE(m2.Matches('\1'));
889 EXPECT_FALSE(m2.Matches('a'));
890}
891
892// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
893TEST(TypedEqTest, ChecksEqualityForGivenType) {
894 Matcher<char> m1 = TypedEq<char>('a');
895 EXPECT_TRUE(m1.Matches('a'));
896 EXPECT_FALSE(m1.Matches('b'));
897
898 Matcher<int> m2 = TypedEq<int>(6);
899 EXPECT_TRUE(m2.Matches(6));
900 EXPECT_FALSE(m2.Matches(7));
901}
902
903// Tests that TypedEq(v) describes itself properly.
904TEST(TypedEqTest, CanDescribeSelf) {
905 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
906}
907
908// Tests that TypedEq<T>(v) has type Matcher<T>.
909
910// Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
911// is a "bare" type (i.e. not in the form of const U or U&). If v's
912// type is not T, the compiler will generate a message about
913// "undefined referece".
914template <typename T>
915struct Type {
zhanyong.wan32de5f52009-12-23 00:13:23 +0000916 static bool IsTypeOf(const T& /* v */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000917
918 template <typename T2>
919 static void IsTypeOf(T2 v);
920};
921
922TEST(TypedEqTest, HasSpecifiedType) {
923 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
924 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
925 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
926}
927
928// Tests that Ge(v) matches anything >= v.
929TEST(GeTest, ImplementsGreaterThanOrEqual) {
930 Matcher<int> m1 = Ge(0);
931 EXPECT_TRUE(m1.Matches(1));
932 EXPECT_TRUE(m1.Matches(0));
933 EXPECT_FALSE(m1.Matches(-1));
934}
935
936// Tests that Ge(v) describes itself properly.
937TEST(GeTest, CanDescribeSelf) {
938 Matcher<int> m = Ge(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000939 EXPECT_EQ("is >= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000940}
941
942// Tests that Gt(v) matches anything > v.
943TEST(GtTest, ImplementsGreaterThan) {
944 Matcher<double> m1 = Gt(0);
945 EXPECT_TRUE(m1.Matches(1.0));
946 EXPECT_FALSE(m1.Matches(0.0));
947 EXPECT_FALSE(m1.Matches(-1.0));
948}
949
950// Tests that Gt(v) describes itself properly.
951TEST(GtTest, CanDescribeSelf) {
952 Matcher<int> m = Gt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000953 EXPECT_EQ("is > 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000954}
955
956// Tests that Le(v) matches anything <= v.
957TEST(LeTest, ImplementsLessThanOrEqual) {
958 Matcher<char> m1 = Le('b');
959 EXPECT_TRUE(m1.Matches('a'));
960 EXPECT_TRUE(m1.Matches('b'));
961 EXPECT_FALSE(m1.Matches('c'));
962}
963
964// Tests that Le(v) describes itself properly.
965TEST(LeTest, CanDescribeSelf) {
966 Matcher<int> m = Le(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000967 EXPECT_EQ("is <= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000968}
969
970// Tests that Lt(v) matches anything < v.
971TEST(LtTest, ImplementsLessThan) {
972 Matcher<const string&> m1 = Lt("Hello");
973 EXPECT_TRUE(m1.Matches("Abc"));
974 EXPECT_FALSE(m1.Matches("Hello"));
975 EXPECT_FALSE(m1.Matches("Hello, world!"));
976}
977
978// Tests that Lt(v) describes itself properly.
979TEST(LtTest, CanDescribeSelf) {
980 Matcher<int> m = Lt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000981 EXPECT_EQ("is < 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000982}
983
984// Tests that Ne(v) matches anything != v.
985TEST(NeTest, ImplementsNotEqual) {
986 Matcher<int> m1 = Ne(0);
987 EXPECT_TRUE(m1.Matches(1));
988 EXPECT_TRUE(m1.Matches(-1));
989 EXPECT_FALSE(m1.Matches(0));
990}
991
992// Tests that Ne(v) describes itself properly.
993TEST(NeTest, CanDescribeSelf) {
994 Matcher<int> m = Ne(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000995 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000996}
997
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000998// Tests that IsNull() matches any NULL pointer of any type.
999TEST(IsNullTest, MatchesNullPointer) {
1000 Matcher<int*> m1 = IsNull();
1001 int* p1 = NULL;
1002 int n = 0;
1003 EXPECT_TRUE(m1.Matches(p1));
1004 EXPECT_FALSE(m1.Matches(&n));
1005
1006 Matcher<const char*> m2 = IsNull();
1007 const char* p2 = NULL;
1008 EXPECT_TRUE(m2.Matches(p2));
1009 EXPECT_FALSE(m2.Matches("hi"));
1010
zhanyong.wan95b12332009-09-25 18:55:50 +00001011#if !GTEST_OS_SYMBIAN
1012 // Nokia's Symbian compiler generates:
1013 // gmock-matchers.h: ambiguous access to overloaded function
1014 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
1015 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
1016 // MatcherInterface<void *> *)'
1017 // gmock-matchers.h: (point of instantiation: 'testing::
1018 // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
1019 // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001020 Matcher<void*> m3 = IsNull();
1021 void* p3 = NULL;
1022 EXPECT_TRUE(m3.Matches(p3));
1023 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
zhanyong.wan95b12332009-09-25 18:55:50 +00001024#endif
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001025}
1026
vladlosev79b83502009-11-18 00:43:37 +00001027TEST(IsNullTest, LinkedPtr) {
1028 const Matcher<linked_ptr<int> > m = IsNull();
1029 const linked_ptr<int> null_p;
1030 const linked_ptr<int> non_null_p(new int);
1031
1032 EXPECT_TRUE(m.Matches(null_p));
1033 EXPECT_FALSE(m.Matches(non_null_p));
1034}
1035
1036TEST(IsNullTest, ReferenceToConstLinkedPtr) {
1037 const Matcher<const linked_ptr<double>&> m = IsNull();
1038 const linked_ptr<double> null_p;
1039 const linked_ptr<double> non_null_p(new double);
1040
1041 EXPECT_TRUE(m.Matches(null_p));
1042 EXPECT_FALSE(m.Matches(non_null_p));
1043}
1044
Mark Mentovaia0435dc2015-10-12 17:57:51 -04001045#if GTEST_HAS_STD_FUNCTION_
kosak6305ff52015-04-28 22:36:31 +00001046TEST(IsNullTest, StdFunction) {
1047 const Matcher<std::function<void()>> m = IsNull();
1048
1049 EXPECT_TRUE(m.Matches(std::function<void()>()));
1050 EXPECT_FALSE(m.Matches([]{}));
1051}
Mark Mentovaia0435dc2015-10-12 17:57:51 -04001052#endif // GTEST_HAS_STD_FUNCTION_
kosak6305ff52015-04-28 22:36:31 +00001053
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001054// Tests that IsNull() describes itself properly.
1055TEST(IsNullTest, CanDescribeSelf) {
1056 Matcher<int*> m = IsNull();
1057 EXPECT_EQ("is NULL", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001058 EXPECT_EQ("isn't NULL", DescribeNegation(m));
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001059}
1060
shiqiane35fdd92008-12-10 05:08:54 +00001061// Tests that NotNull() matches any non-NULL pointer of any type.
1062TEST(NotNullTest, MatchesNonNullPointer) {
1063 Matcher<int*> m1 = NotNull();
1064 int* p1 = NULL;
1065 int n = 0;
1066 EXPECT_FALSE(m1.Matches(p1));
1067 EXPECT_TRUE(m1.Matches(&n));
1068
1069 Matcher<const char*> m2 = NotNull();
1070 const char* p2 = NULL;
1071 EXPECT_FALSE(m2.Matches(p2));
1072 EXPECT_TRUE(m2.Matches("hi"));
1073}
1074
vladlosev79b83502009-11-18 00:43:37 +00001075TEST(NotNullTest, LinkedPtr) {
1076 const Matcher<linked_ptr<int> > m = NotNull();
1077 const linked_ptr<int> null_p;
1078 const linked_ptr<int> non_null_p(new int);
1079
1080 EXPECT_FALSE(m.Matches(null_p));
1081 EXPECT_TRUE(m.Matches(non_null_p));
1082}
1083
1084TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1085 const Matcher<const linked_ptr<double>&> m = NotNull();
1086 const linked_ptr<double> null_p;
1087 const linked_ptr<double> non_null_p(new double);
1088
1089 EXPECT_FALSE(m.Matches(null_p));
1090 EXPECT_TRUE(m.Matches(non_null_p));
1091}
1092
Mark Mentovaia0435dc2015-10-12 17:57:51 -04001093#if GTEST_HAS_STD_FUNCTION_
kosak6305ff52015-04-28 22:36:31 +00001094TEST(NotNullTest, StdFunction) {
1095 const Matcher<std::function<void()>> m = NotNull();
1096
1097 EXPECT_TRUE(m.Matches([]{}));
1098 EXPECT_FALSE(m.Matches(std::function<void()>()));
1099}
Mark Mentovaia0435dc2015-10-12 17:57:51 -04001100#endif // GTEST_HAS_STD_FUNCTION_
kosak6305ff52015-04-28 22:36:31 +00001101
shiqiane35fdd92008-12-10 05:08:54 +00001102// Tests that NotNull() describes itself properly.
1103TEST(NotNullTest, CanDescribeSelf) {
1104 Matcher<int*> m = NotNull();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001105 EXPECT_EQ("isn't NULL", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001106}
1107
1108// Tests that Ref(variable) matches an argument that references
1109// 'variable'.
1110TEST(RefTest, MatchesSameVariable) {
1111 int a = 0;
1112 int b = 0;
1113 Matcher<int&> m = Ref(a);
1114 EXPECT_TRUE(m.Matches(a));
1115 EXPECT_FALSE(m.Matches(b));
1116}
1117
1118// Tests that Ref(variable) describes itself properly.
1119TEST(RefTest, CanDescribeSelf) {
1120 int n = 5;
1121 Matcher<int&> m = Ref(n);
1122 stringstream ss;
1123 ss << "references the variable @" << &n << " 5";
1124 EXPECT_EQ(string(ss.str()), Describe(m));
1125}
1126
1127// Test that Ref(non_const_varialbe) can be used as a matcher for a
1128// const reference.
1129TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1130 int a = 0;
1131 int b = 0;
1132 Matcher<const int&> m = Ref(a);
1133 EXPECT_TRUE(m.Matches(a));
1134 EXPECT_FALSE(m.Matches(b));
1135}
1136
1137// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1138// used wherever Ref(base) can be used (Ref(derived) is a sub-type
1139// of Ref(base), but not vice versa.
1140
shiqiane35fdd92008-12-10 05:08:54 +00001141TEST(RefTest, IsCovariant) {
1142 Base base, base2;
1143 Derived derived;
1144 Matcher<const Base&> m1 = Ref(base);
1145 EXPECT_TRUE(m1.Matches(base));
1146 EXPECT_FALSE(m1.Matches(base2));
1147 EXPECT_FALSE(m1.Matches(derived));
1148
1149 m1 = Ref(derived);
1150 EXPECT_TRUE(m1.Matches(derived));
1151 EXPECT_FALSE(m1.Matches(base));
1152 EXPECT_FALSE(m1.Matches(base2));
1153}
1154
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001155TEST(RefTest, ExplainsResult) {
1156 int n = 0;
1157 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1158 StartsWith("which is located @"));
1159
1160 int m = 0;
1161 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1162 StartsWith("which is located @"));
1163}
1164
shiqiane35fdd92008-12-10 05:08:54 +00001165// Tests string comparison matchers.
1166
1167TEST(StrEqTest, MatchesEqualString) {
1168 Matcher<const char*> m = StrEq(string("Hello"));
1169 EXPECT_TRUE(m.Matches("Hello"));
1170 EXPECT_FALSE(m.Matches("hello"));
1171 EXPECT_FALSE(m.Matches(NULL));
1172
1173 Matcher<const string&> m2 = StrEq("Hello");
1174 EXPECT_TRUE(m2.Matches("Hello"));
1175 EXPECT_FALSE(m2.Matches("Hi"));
1176}
1177
1178TEST(StrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001179 Matcher<string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1180 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
shiqiane35fdd92008-12-10 05:08:54 +00001181 Describe(m));
1182
1183 string str("01204500800");
1184 str[3] = '\0';
1185 Matcher<string> m2 = StrEq(str);
1186 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1187 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1188 Matcher<string> m3 = StrEq(str);
1189 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1190}
1191
1192TEST(StrNeTest, MatchesUnequalString) {
1193 Matcher<const char*> m = StrNe("Hello");
1194 EXPECT_TRUE(m.Matches(""));
1195 EXPECT_TRUE(m.Matches(NULL));
1196 EXPECT_FALSE(m.Matches("Hello"));
1197
1198 Matcher<string> m2 = StrNe(string("Hello"));
1199 EXPECT_TRUE(m2.Matches("hello"));
1200 EXPECT_FALSE(m2.Matches("Hello"));
1201}
1202
1203TEST(StrNeTest, CanDescribeSelf) {
1204 Matcher<const char*> m = StrNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001205 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001206}
1207
1208TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1209 Matcher<const char*> m = StrCaseEq(string("Hello"));
1210 EXPECT_TRUE(m.Matches("Hello"));
1211 EXPECT_TRUE(m.Matches("hello"));
1212 EXPECT_FALSE(m.Matches("Hi"));
1213 EXPECT_FALSE(m.Matches(NULL));
1214
1215 Matcher<const string&> m2 = StrCaseEq("Hello");
1216 EXPECT_TRUE(m2.Matches("hello"));
1217 EXPECT_FALSE(m2.Matches("Hi"));
1218}
1219
1220TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1221 string str1("oabocdooeoo");
1222 string str2("OABOCDOOEOO");
1223 Matcher<const string&> m0 = StrCaseEq(str1);
1224 EXPECT_FALSE(m0.Matches(str2 + string(1, '\0')));
1225
1226 str1[3] = str2[3] = '\0';
1227 Matcher<const string&> m1 = StrCaseEq(str1);
1228 EXPECT_TRUE(m1.Matches(str2));
1229
1230 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1231 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1232 Matcher<const string&> m2 = StrCaseEq(str1);
1233 str1[9] = str2[9] = '\0';
1234 EXPECT_FALSE(m2.Matches(str2));
1235
1236 Matcher<const string&> m3 = StrCaseEq(str1);
1237 EXPECT_TRUE(m3.Matches(str2));
1238
1239 EXPECT_FALSE(m3.Matches(str2 + "x"));
1240 str2.append(1, '\0');
1241 EXPECT_FALSE(m3.Matches(str2));
1242 EXPECT_FALSE(m3.Matches(string(str2, 0, 9)));
1243}
1244
1245TEST(StrCaseEqTest, CanDescribeSelf) {
1246 Matcher<string> m = StrCaseEq("Hi");
1247 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1248}
1249
1250TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1251 Matcher<const char*> m = StrCaseNe("Hello");
1252 EXPECT_TRUE(m.Matches("Hi"));
1253 EXPECT_TRUE(m.Matches(NULL));
1254 EXPECT_FALSE(m.Matches("Hello"));
1255 EXPECT_FALSE(m.Matches("hello"));
1256
1257 Matcher<string> m2 = StrCaseNe(string("Hello"));
1258 EXPECT_TRUE(m2.Matches(""));
1259 EXPECT_FALSE(m2.Matches("Hello"));
1260}
1261
1262TEST(StrCaseNeTest, CanDescribeSelf) {
1263 Matcher<const char*> m = StrCaseNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001264 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001265}
1266
1267// Tests that HasSubstr() works for matching string-typed values.
1268TEST(HasSubstrTest, WorksForStringClasses) {
1269 const Matcher<string> m1 = HasSubstr("foo");
1270 EXPECT_TRUE(m1.Matches(string("I love food.")));
1271 EXPECT_FALSE(m1.Matches(string("tofo")));
1272
1273 const Matcher<const std::string&> m2 = HasSubstr("foo");
1274 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1275 EXPECT_FALSE(m2.Matches(std::string("tofo")));
1276}
1277
1278// Tests that HasSubstr() works for matching C-string-typed values.
1279TEST(HasSubstrTest, WorksForCStrings) {
1280 const Matcher<char*> m1 = HasSubstr("foo");
1281 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1282 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1283 EXPECT_FALSE(m1.Matches(NULL));
1284
1285 const Matcher<const char*> m2 = HasSubstr("foo");
1286 EXPECT_TRUE(m2.Matches("I love food."));
1287 EXPECT_FALSE(m2.Matches("tofo"));
1288 EXPECT_FALSE(m2.Matches(NULL));
1289}
1290
1291// Tests that HasSubstr(s) describes itself properly.
1292TEST(HasSubstrTest, CanDescribeSelf) {
1293 Matcher<string> m = HasSubstr("foo\n\"");
1294 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1295}
1296
zhanyong.wanb5937da2009-07-16 20:26:41 +00001297TEST(KeyTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001298 Matcher<const pair<std::string, int>&> m = Key("foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001299 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001300 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1301}
1302
1303TEST(KeyTest, ExplainsResult) {
1304 Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1305 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1306 Explain(m, make_pair(5, true)));
1307 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1308 Explain(m, make_pair(15, true)));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001309}
1310
1311TEST(KeyTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001312 pair<int, std::string> p(25, "foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001313 EXPECT_THAT(p, Key(25));
1314 EXPECT_THAT(p, Not(Key(42)));
1315 EXPECT_THAT(p, Key(Ge(20)));
1316 EXPECT_THAT(p, Not(Key(Lt(25))));
1317}
1318
1319TEST(KeyTest, SafelyCastsInnerMatcher) {
1320 Matcher<int> is_positive = Gt(0);
1321 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001322 pair<char, bool> p('a', true);
zhanyong.wanb5937da2009-07-16 20:26:41 +00001323 EXPECT_THAT(p, Key(is_positive));
1324 EXPECT_THAT(p, Not(Key(is_negative)));
1325}
1326
1327TEST(KeyTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001328 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001329 container.insert(make_pair(1, 'a'));
1330 container.insert(make_pair(2, 'b'));
1331 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001332 EXPECT_THAT(container, Contains(Key(1)));
1333 EXPECT_THAT(container, Not(Contains(Key(3))));
1334}
1335
1336TEST(KeyTest, InsideContainsUsingMultimap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001337 multimap<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001338 container.insert(make_pair(1, 'a'));
1339 container.insert(make_pair(2, 'b'));
1340 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001341
1342 EXPECT_THAT(container, Not(Contains(Key(25))));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001343 container.insert(make_pair(25, 'd'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001344 EXPECT_THAT(container, Contains(Key(25)));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001345 container.insert(make_pair(25, 'e'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001346 EXPECT_THAT(container, Contains(Key(25)));
1347
1348 EXPECT_THAT(container, Contains(Key(1)));
1349 EXPECT_THAT(container, Not(Contains(Key(3))));
1350}
1351
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001352TEST(PairTest, Typing) {
1353 // Test verifies the following type conversions can be compiled.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001354 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1355 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1356 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001357
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001358 Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1359 Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001360}
1361
1362TEST(PairTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001363 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001364 EXPECT_EQ("has a first field that is equal to \"foo\""
1365 ", and has a second field that is equal to 42",
1366 Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001367 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1368 ", or has a second field that isn't equal to 42",
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001369 DescribeNegation(m1));
1370 // Double and triple negation (1 or 2 times not and description of negation).
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001371 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1372 EXPECT_EQ("has a first field that isn't equal to 13"
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001373 ", and has a second field that is equal to 42",
1374 DescribeNegation(m2));
1375}
1376
1377TEST(PairTest, CanExplainMatchResultTo) {
zhanyong.wan82113312010-01-08 21:55:40 +00001378 // If neither field matches, Pair() should explain about the first
1379 // field.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001380 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001381 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001382 Explain(m, make_pair(-1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001383
zhanyong.wan82113312010-01-08 21:55:40 +00001384 // If the first field matches but the second doesn't, Pair() should
1385 // explain about the second field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001386 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001387 Explain(m, make_pair(1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001388
zhanyong.wan82113312010-01-08 21:55:40 +00001389 // If the first field doesn't match but the second does, Pair()
1390 // should explain about the first field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001391 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001392 Explain(m, make_pair(-1, 2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001393
zhanyong.wan82113312010-01-08 21:55:40 +00001394 // If both fields match, Pair() should explain about them both.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001395 EXPECT_EQ("whose both fields match, where the first field is a value "
1396 "which is 1 more than 0, and the second field is a value "
1397 "which is 2 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001398 Explain(m, make_pair(1, 2)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001399
1400 // If only the first match has an explanation, only this explanation should
1401 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001402 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001403 EXPECT_EQ("whose both fields match, where the first field is a value "
1404 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001405 Explain(explain_first, make_pair(1, 0)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001406
1407 // If only the second match has an explanation, only this explanation should
1408 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001409 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001410 EXPECT_EQ("whose both fields match, where the second field is a value "
1411 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001412 Explain(explain_second, make_pair(0, 1)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001413}
1414
1415TEST(PairTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001416 pair<int, std::string> p(25, "foo");
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001417
1418 // Both fields match.
1419 EXPECT_THAT(p, Pair(25, "foo"));
1420 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1421
1422 // 'first' doesnt' match, but 'second' matches.
1423 EXPECT_THAT(p, Not(Pair(42, "foo")));
1424 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1425
1426 // 'first' matches, but 'second' doesn't match.
1427 EXPECT_THAT(p, Not(Pair(25, "bar")));
1428 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1429
1430 // Neither field matches.
1431 EXPECT_THAT(p, Not(Pair(13, "bar")));
1432 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1433}
1434
1435TEST(PairTest, SafelyCastsInnerMatchers) {
1436 Matcher<int> is_positive = Gt(0);
1437 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001438 pair<char, bool> p('a', true);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001439 EXPECT_THAT(p, Pair(is_positive, _));
1440 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1441 EXPECT_THAT(p, Pair(_, is_positive));
1442 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1443}
1444
1445TEST(PairTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001446 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001447 container.insert(make_pair(1, 'a'));
1448 container.insert(make_pair(2, 'b'));
1449 container.insert(make_pair(4, 'c'));
zhanyong.wan95b12332009-09-25 18:55:50 +00001450 EXPECT_THAT(container, Contains(Pair(1, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001451 EXPECT_THAT(container, Contains(Pair(1, _)));
zhanyong.wan95b12332009-09-25 18:55:50 +00001452 EXPECT_THAT(container, Contains(Pair(_, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001453 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1454}
1455
shiqiane35fdd92008-12-10 05:08:54 +00001456// Tests StartsWith(s).
1457
1458TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1459 const Matcher<const char*> m1 = StartsWith(string(""));
1460 EXPECT_TRUE(m1.Matches("Hi"));
1461 EXPECT_TRUE(m1.Matches(""));
1462 EXPECT_FALSE(m1.Matches(NULL));
1463
1464 const Matcher<const string&> m2 = StartsWith("Hi");
1465 EXPECT_TRUE(m2.Matches("Hi"));
1466 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1467 EXPECT_TRUE(m2.Matches("High"));
1468 EXPECT_FALSE(m2.Matches("H"));
1469 EXPECT_FALSE(m2.Matches(" Hi"));
1470}
1471
1472TEST(StartsWithTest, CanDescribeSelf) {
1473 Matcher<const std::string> m = StartsWith("Hi");
1474 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1475}
1476
1477// Tests EndsWith(s).
1478
1479TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1480 const Matcher<const char*> m1 = EndsWith("");
1481 EXPECT_TRUE(m1.Matches("Hi"));
1482 EXPECT_TRUE(m1.Matches(""));
1483 EXPECT_FALSE(m1.Matches(NULL));
1484
1485 const Matcher<const string&> m2 = EndsWith(string("Hi"));
1486 EXPECT_TRUE(m2.Matches("Hi"));
1487 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1488 EXPECT_TRUE(m2.Matches("Super Hi"));
1489 EXPECT_FALSE(m2.Matches("i"));
1490 EXPECT_FALSE(m2.Matches("Hi "));
1491}
1492
1493TEST(EndsWithTest, CanDescribeSelf) {
1494 Matcher<const std::string> m = EndsWith("Hi");
1495 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1496}
1497
shiqiane35fdd92008-12-10 05:08:54 +00001498// Tests MatchesRegex().
1499
1500TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1501 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1502 EXPECT_TRUE(m1.Matches("az"));
1503 EXPECT_TRUE(m1.Matches("abcz"));
1504 EXPECT_FALSE(m1.Matches(NULL));
1505
1506 const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z"));
1507 EXPECT_TRUE(m2.Matches("azbz"));
1508 EXPECT_FALSE(m2.Matches("az1"));
1509 EXPECT_FALSE(m2.Matches("1az"));
1510}
1511
1512TEST(MatchesRegexTest, CanDescribeSelf) {
1513 Matcher<const std::string> m1 = MatchesRegex(string("Hi.*"));
1514 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1515
zhanyong.wand14aaed2010-01-14 05:36:32 +00001516 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1517 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001518}
1519
1520// Tests ContainsRegex().
1521
1522TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1523 const Matcher<const char*> m1 = ContainsRegex(string("a.*z"));
1524 EXPECT_TRUE(m1.Matches("az"));
1525 EXPECT_TRUE(m1.Matches("0abcz1"));
1526 EXPECT_FALSE(m1.Matches(NULL));
1527
1528 const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z"));
1529 EXPECT_TRUE(m2.Matches("azbz"));
1530 EXPECT_TRUE(m2.Matches("az1"));
1531 EXPECT_FALSE(m2.Matches("1a"));
1532}
1533
1534TEST(ContainsRegexTest, CanDescribeSelf) {
1535 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1536 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1537
zhanyong.wand14aaed2010-01-14 05:36:32 +00001538 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1539 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001540}
shiqiane35fdd92008-12-10 05:08:54 +00001541
1542// Tests for wide strings.
1543#if GTEST_HAS_STD_WSTRING
1544TEST(StdWideStrEqTest, MatchesEqual) {
1545 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1546 EXPECT_TRUE(m.Matches(L"Hello"));
1547 EXPECT_FALSE(m.Matches(L"hello"));
1548 EXPECT_FALSE(m.Matches(NULL));
1549
1550 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1551 EXPECT_TRUE(m2.Matches(L"Hello"));
1552 EXPECT_FALSE(m2.Matches(L"Hi"));
1553
1554 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1555 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1556 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1557
1558 ::std::wstring str(L"01204500800");
1559 str[3] = L'\0';
1560 Matcher<const ::std::wstring&> m4 = StrEq(str);
1561 EXPECT_TRUE(m4.Matches(str));
1562 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1563 Matcher<const ::std::wstring&> m5 = StrEq(str);
1564 EXPECT_TRUE(m5.Matches(str));
1565}
1566
1567TEST(StdWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001568 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1569 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001570 Describe(m));
1571
1572 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1573 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1574 Describe(m2));
1575
1576 ::std::wstring str(L"01204500800");
1577 str[3] = L'\0';
1578 Matcher<const ::std::wstring&> m4 = StrEq(str);
1579 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1580 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1581 Matcher<const ::std::wstring&> m5 = StrEq(str);
1582 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1583}
1584
1585TEST(StdWideStrNeTest, MatchesUnequalString) {
1586 Matcher<const wchar_t*> m = StrNe(L"Hello");
1587 EXPECT_TRUE(m.Matches(L""));
1588 EXPECT_TRUE(m.Matches(NULL));
1589 EXPECT_FALSE(m.Matches(L"Hello"));
1590
1591 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1592 EXPECT_TRUE(m2.Matches(L"hello"));
1593 EXPECT_FALSE(m2.Matches(L"Hello"));
1594}
1595
1596TEST(StdWideStrNeTest, CanDescribeSelf) {
1597 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001598 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001599}
1600
1601TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1602 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1603 EXPECT_TRUE(m.Matches(L"Hello"));
1604 EXPECT_TRUE(m.Matches(L"hello"));
1605 EXPECT_FALSE(m.Matches(L"Hi"));
1606 EXPECT_FALSE(m.Matches(NULL));
1607
1608 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1609 EXPECT_TRUE(m2.Matches(L"hello"));
1610 EXPECT_FALSE(m2.Matches(L"Hi"));
1611}
1612
1613TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1614 ::std::wstring str1(L"oabocdooeoo");
1615 ::std::wstring str2(L"OABOCDOOEOO");
1616 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1617 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1618
1619 str1[3] = str2[3] = L'\0';
1620 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1621 EXPECT_TRUE(m1.Matches(str2));
1622
1623 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1624 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1625 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1626 str1[9] = str2[9] = L'\0';
1627 EXPECT_FALSE(m2.Matches(str2));
1628
1629 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1630 EXPECT_TRUE(m3.Matches(str2));
1631
1632 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1633 str2.append(1, L'\0');
1634 EXPECT_FALSE(m3.Matches(str2));
1635 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1636}
1637
1638TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1639 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1640 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1641}
1642
1643TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1644 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1645 EXPECT_TRUE(m.Matches(L"Hi"));
1646 EXPECT_TRUE(m.Matches(NULL));
1647 EXPECT_FALSE(m.Matches(L"Hello"));
1648 EXPECT_FALSE(m.Matches(L"hello"));
1649
1650 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1651 EXPECT_TRUE(m2.Matches(L""));
1652 EXPECT_FALSE(m2.Matches(L"Hello"));
1653}
1654
1655TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1656 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001657 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001658}
1659
1660// Tests that HasSubstr() works for matching wstring-typed values.
1661TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1662 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1663 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1664 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1665
1666 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1667 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1668 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1669}
1670
1671// Tests that HasSubstr() works for matching C-wide-string-typed values.
1672TEST(StdWideHasSubstrTest, WorksForCStrings) {
1673 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1674 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1675 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1676 EXPECT_FALSE(m1.Matches(NULL));
1677
1678 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1679 EXPECT_TRUE(m2.Matches(L"I love food."));
1680 EXPECT_FALSE(m2.Matches(L"tofo"));
1681 EXPECT_FALSE(m2.Matches(NULL));
1682}
1683
1684// Tests that HasSubstr(s) describes itself properly.
1685TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1686 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1687 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1688}
1689
1690// Tests StartsWith(s).
1691
1692TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1693 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1694 EXPECT_TRUE(m1.Matches(L"Hi"));
1695 EXPECT_TRUE(m1.Matches(L""));
1696 EXPECT_FALSE(m1.Matches(NULL));
1697
1698 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1699 EXPECT_TRUE(m2.Matches(L"Hi"));
1700 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1701 EXPECT_TRUE(m2.Matches(L"High"));
1702 EXPECT_FALSE(m2.Matches(L"H"));
1703 EXPECT_FALSE(m2.Matches(L" Hi"));
1704}
1705
1706TEST(StdWideStartsWithTest, CanDescribeSelf) {
1707 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
1708 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1709}
1710
1711// Tests EndsWith(s).
1712
1713TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
1714 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1715 EXPECT_TRUE(m1.Matches(L"Hi"));
1716 EXPECT_TRUE(m1.Matches(L""));
1717 EXPECT_FALSE(m1.Matches(NULL));
1718
1719 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
1720 EXPECT_TRUE(m2.Matches(L"Hi"));
1721 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1722 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1723 EXPECT_FALSE(m2.Matches(L"i"));
1724 EXPECT_FALSE(m2.Matches(L"Hi "));
1725}
1726
1727TEST(StdWideEndsWithTest, CanDescribeSelf) {
1728 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
1729 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1730}
1731
1732#endif // GTEST_HAS_STD_WSTRING
1733
1734#if GTEST_HAS_GLOBAL_WSTRING
1735TEST(GlobalWideStrEqTest, MatchesEqual) {
1736 Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
1737 EXPECT_TRUE(m.Matches(L"Hello"));
1738 EXPECT_FALSE(m.Matches(L"hello"));
1739 EXPECT_FALSE(m.Matches(NULL));
1740
1741 Matcher<const ::wstring&> m2 = StrEq(L"Hello");
1742 EXPECT_TRUE(m2.Matches(L"Hello"));
1743 EXPECT_FALSE(m2.Matches(L"Hi"));
1744
1745 Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1746 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1747 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1748
1749 ::wstring str(L"01204500800");
1750 str[3] = L'\0';
1751 Matcher<const ::wstring&> m4 = StrEq(str);
1752 EXPECT_TRUE(m4.Matches(str));
1753 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1754 Matcher<const ::wstring&> m5 = StrEq(str);
1755 EXPECT_TRUE(m5.Matches(str));
1756}
1757
1758TEST(GlobalWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001759 Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1760 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001761 Describe(m));
1762
1763 Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1764 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1765 Describe(m2));
1766
1767 ::wstring str(L"01204500800");
1768 str[3] = L'\0';
1769 Matcher<const ::wstring&> m4 = StrEq(str);
1770 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1771 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1772 Matcher<const ::wstring&> m5 = StrEq(str);
1773 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1774}
1775
1776TEST(GlobalWideStrNeTest, MatchesUnequalString) {
1777 Matcher<const wchar_t*> m = StrNe(L"Hello");
1778 EXPECT_TRUE(m.Matches(L""));
1779 EXPECT_TRUE(m.Matches(NULL));
1780 EXPECT_FALSE(m.Matches(L"Hello"));
1781
1782 Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
1783 EXPECT_TRUE(m2.Matches(L"hello"));
1784 EXPECT_FALSE(m2.Matches(L"Hello"));
1785}
1786
1787TEST(GlobalWideStrNeTest, CanDescribeSelf) {
1788 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001789 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001790}
1791
1792TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1793 Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
1794 EXPECT_TRUE(m.Matches(L"Hello"));
1795 EXPECT_TRUE(m.Matches(L"hello"));
1796 EXPECT_FALSE(m.Matches(L"Hi"));
1797 EXPECT_FALSE(m.Matches(NULL));
1798
1799 Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
1800 EXPECT_TRUE(m2.Matches(L"hello"));
1801 EXPECT_FALSE(m2.Matches(L"Hi"));
1802}
1803
1804TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1805 ::wstring str1(L"oabocdooeoo");
1806 ::wstring str2(L"OABOCDOOEOO");
1807 Matcher<const ::wstring&> m0 = StrCaseEq(str1);
1808 EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
1809
1810 str1[3] = str2[3] = L'\0';
1811 Matcher<const ::wstring&> m1 = StrCaseEq(str1);
1812 EXPECT_TRUE(m1.Matches(str2));
1813
1814 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1815 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1816 Matcher<const ::wstring&> m2 = StrCaseEq(str1);
1817 str1[9] = str2[9] = L'\0';
1818 EXPECT_FALSE(m2.Matches(str2));
1819
1820 Matcher<const ::wstring&> m3 = StrCaseEq(str1);
1821 EXPECT_TRUE(m3.Matches(str2));
1822
1823 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1824 str2.append(1, L'\0');
1825 EXPECT_FALSE(m3.Matches(str2));
1826 EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
1827}
1828
1829TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
1830 Matcher< ::wstring> m = StrCaseEq(L"Hi");
1831 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1832}
1833
1834TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1835 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1836 EXPECT_TRUE(m.Matches(L"Hi"));
1837 EXPECT_TRUE(m.Matches(NULL));
1838 EXPECT_FALSE(m.Matches(L"Hello"));
1839 EXPECT_FALSE(m.Matches(L"hello"));
1840
1841 Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
1842 EXPECT_TRUE(m2.Matches(L""));
1843 EXPECT_FALSE(m2.Matches(L"Hello"));
1844}
1845
1846TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
1847 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001848 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001849}
1850
1851// Tests that HasSubstr() works for matching wstring-typed values.
1852TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
1853 const Matcher< ::wstring> m1 = HasSubstr(L"foo");
1854 EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
1855 EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
1856
1857 const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
1858 EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
1859 EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
1860}
1861
1862// Tests that HasSubstr() works for matching C-wide-string-typed values.
1863TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
1864 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1865 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1866 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1867 EXPECT_FALSE(m1.Matches(NULL));
1868
1869 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1870 EXPECT_TRUE(m2.Matches(L"I love food."));
1871 EXPECT_FALSE(m2.Matches(L"tofo"));
1872 EXPECT_FALSE(m2.Matches(NULL));
1873}
1874
1875// Tests that HasSubstr(s) describes itself properly.
1876TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
1877 Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
1878 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1879}
1880
1881// Tests StartsWith(s).
1882
1883TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
1884 const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
1885 EXPECT_TRUE(m1.Matches(L"Hi"));
1886 EXPECT_TRUE(m1.Matches(L""));
1887 EXPECT_FALSE(m1.Matches(NULL));
1888
1889 const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
1890 EXPECT_TRUE(m2.Matches(L"Hi"));
1891 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1892 EXPECT_TRUE(m2.Matches(L"High"));
1893 EXPECT_FALSE(m2.Matches(L"H"));
1894 EXPECT_FALSE(m2.Matches(L" Hi"));
1895}
1896
1897TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
1898 Matcher<const ::wstring> m = StartsWith(L"Hi");
1899 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1900}
1901
1902// Tests EndsWith(s).
1903
1904TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
1905 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1906 EXPECT_TRUE(m1.Matches(L"Hi"));
1907 EXPECT_TRUE(m1.Matches(L""));
1908 EXPECT_FALSE(m1.Matches(NULL));
1909
1910 const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
1911 EXPECT_TRUE(m2.Matches(L"Hi"));
1912 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1913 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1914 EXPECT_FALSE(m2.Matches(L"i"));
1915 EXPECT_FALSE(m2.Matches(L"Hi "));
1916}
1917
1918TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
1919 Matcher<const ::wstring> m = EndsWith(L"Hi");
1920 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1921}
1922
1923#endif // GTEST_HAS_GLOBAL_WSTRING
1924
1925
kosakbd018832014-04-02 20:30:00 +00001926typedef ::testing::tuple<long, int> Tuple2; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00001927
1928// Tests that Eq() matches a 2-tuple where the first field == the
1929// second field.
1930TEST(Eq2Test, MatchesEqualArguments) {
1931 Matcher<const Tuple2&> m = Eq();
1932 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1933 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1934}
1935
1936// Tests that Eq() describes itself properly.
1937TEST(Eq2Test, CanDescribeSelf) {
1938 Matcher<const Tuple2&> m = Eq();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001939 EXPECT_EQ("are an equal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001940}
1941
1942// Tests that Ge() matches a 2-tuple where the first field >= the
1943// second field.
1944TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
1945 Matcher<const Tuple2&> m = Ge();
1946 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1947 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1948 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1949}
1950
1951// Tests that Ge() describes itself properly.
1952TEST(Ge2Test, CanDescribeSelf) {
1953 Matcher<const Tuple2&> m = Ge();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001954 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001955}
1956
1957// Tests that Gt() matches a 2-tuple where the first field > the
1958// second field.
1959TEST(Gt2Test, MatchesGreaterThanArguments) {
1960 Matcher<const Tuple2&> m = Gt();
1961 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1962 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1963 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1964}
1965
1966// Tests that Gt() describes itself properly.
1967TEST(Gt2Test, CanDescribeSelf) {
1968 Matcher<const Tuple2&> m = Gt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001969 EXPECT_EQ("are a pair where the first > the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001970}
1971
1972// Tests that Le() matches a 2-tuple where the first field <= the
1973// second field.
1974TEST(Le2Test, MatchesLessThanOrEqualArguments) {
1975 Matcher<const Tuple2&> m = Le();
1976 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1977 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1978 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1979}
1980
1981// Tests that Le() describes itself properly.
1982TEST(Le2Test, CanDescribeSelf) {
1983 Matcher<const Tuple2&> m = Le();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001984 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001985}
1986
1987// Tests that Lt() matches a 2-tuple where the first field < the
1988// second field.
1989TEST(Lt2Test, MatchesLessThanArguments) {
1990 Matcher<const Tuple2&> m = Lt();
1991 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1992 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1993 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1994}
1995
1996// Tests that Lt() describes itself properly.
1997TEST(Lt2Test, CanDescribeSelf) {
1998 Matcher<const Tuple2&> m = Lt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001999 EXPECT_EQ("are a pair where the first < the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002000}
2001
2002// Tests that Ne() matches a 2-tuple where the first field != the
2003// second field.
2004TEST(Ne2Test, MatchesUnequalArguments) {
2005 Matcher<const Tuple2&> m = Ne();
2006 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
2007 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
2008 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
2009}
2010
2011// Tests that Ne() describes itself properly.
2012TEST(Ne2Test, CanDescribeSelf) {
2013 Matcher<const Tuple2&> m = Ne();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00002014 EXPECT_EQ("are an unequal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002015}
2016
2017// Tests that Not(m) matches any value that doesn't match m.
2018TEST(NotTest, NegatesMatcher) {
2019 Matcher<int> m;
2020 m = Not(Eq(2));
2021 EXPECT_TRUE(m.Matches(3));
2022 EXPECT_FALSE(m.Matches(2));
2023}
2024
2025// Tests that Not(m) describes itself properly.
2026TEST(NotTest, CanDescribeSelf) {
2027 Matcher<int> m = Not(Eq(5));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002028 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002029}
2030
zhanyong.wan18490652009-05-11 18:54:08 +00002031// Tests that monomorphic matchers are safely cast by the Not matcher.
2032TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2033 // greater_than_5 is a monomorphic matcher.
2034 Matcher<int> greater_than_5 = Gt(5);
2035
2036 Matcher<const int&> m = Not(greater_than_5);
2037 Matcher<int&> m2 = Not(greater_than_5);
2038 Matcher<int&> m3 = Not(m);
2039}
2040
zhanyong.wan02c15052010-06-09 19:21:30 +00002041// Helper to allow easy testing of AllOf matchers with num parameters.
2042void AllOfMatches(int num, const Matcher<int>& m) {
2043 SCOPED_TRACE(Describe(m));
2044 EXPECT_TRUE(m.Matches(0));
2045 for (int i = 1; i <= num; ++i) {
2046 EXPECT_FALSE(m.Matches(i));
2047 }
2048 EXPECT_TRUE(m.Matches(num + 1));
2049}
2050
shiqiane35fdd92008-12-10 05:08:54 +00002051// Tests that AllOf(m1, ..., mn) matches any value that matches all of
2052// the given matchers.
2053TEST(AllOfTest, MatchesWhenAllMatch) {
2054 Matcher<int> m;
2055 m = AllOf(Le(2), Ge(1));
2056 EXPECT_TRUE(m.Matches(1));
2057 EXPECT_TRUE(m.Matches(2));
2058 EXPECT_FALSE(m.Matches(0));
2059 EXPECT_FALSE(m.Matches(3));
2060
2061 m = AllOf(Gt(0), Ne(1), Ne(2));
2062 EXPECT_TRUE(m.Matches(3));
2063 EXPECT_FALSE(m.Matches(2));
2064 EXPECT_FALSE(m.Matches(1));
2065 EXPECT_FALSE(m.Matches(0));
2066
2067 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2068 EXPECT_TRUE(m.Matches(4));
2069 EXPECT_FALSE(m.Matches(3));
2070 EXPECT_FALSE(m.Matches(2));
2071 EXPECT_FALSE(m.Matches(1));
2072 EXPECT_FALSE(m.Matches(0));
2073
2074 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2075 EXPECT_TRUE(m.Matches(0));
2076 EXPECT_TRUE(m.Matches(1));
2077 EXPECT_FALSE(m.Matches(3));
zhanyong.wan02c15052010-06-09 19:21:30 +00002078
2079 // The following tests for varying number of sub-matchers. Due to the way
2080 // the sub-matchers are handled it is enough to test every sub-matcher once
2081 // with sub-matchers using the same matcher type. Varying matcher types are
2082 // checked for above.
2083 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2084 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2085 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2086 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2087 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2088 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2089 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2090 Ne(8)));
2091 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2092 Ne(8), Ne(9)));
2093 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2094 Ne(9), Ne(10)));
shiqiane35fdd92008-12-10 05:08:54 +00002095}
2096
zhanyong.wan616180e2013-06-18 18:49:51 +00002097#if GTEST_LANG_CXX11
2098// Tests the variadic version of the AllOfMatcher.
2099TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
2100 // Make sure AllOf is defined in the right namespace and does not depend on
2101 // ADL.
2102 ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2103 Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2104 Ne(9), Ne(10), Ne(11));
2105 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))"));
2106 AllOfMatches(11, m);
2107 AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2108 Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
2109 Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22),
2110 Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29),
2111 Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36),
2112 Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43),
2113 Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2114 Ne(50)));
2115}
2116
2117#endif // GTEST_LANG_CXX11
2118
shiqiane35fdd92008-12-10 05:08:54 +00002119// Tests that AllOf(m1, ..., mn) describes itself properly.
2120TEST(AllOfTest, CanDescribeSelf) {
2121 Matcher<int> m;
2122 m = AllOf(Le(2), Ge(1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002123 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002124
2125 m = AllOf(Gt(0), Ne(1), Ne(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002126 EXPECT_EQ("(is > 0) and "
2127 "((isn't equal to 1) and "
2128 "(isn't equal to 2))",
shiqiane35fdd92008-12-10 05:08:54 +00002129 Describe(m));
2130
2131
2132 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002133 EXPECT_EQ("((is > 0) and "
2134 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002135 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002136 "(isn't equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002137 Describe(m));
2138
2139
2140 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002141 EXPECT_EQ("((is >= 0) and "
2142 "(is < 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002143 "((isn't equal to 3) and "
2144 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002145 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002146 Describe(m));
2147}
2148
2149// Tests that AllOf(m1, ..., mn) describes its negation properly.
2150TEST(AllOfTest, CanDescribeNegation) {
2151 Matcher<int> m;
2152 m = AllOf(Le(2), Ge(1));
2153 EXPECT_EQ("(isn't <= 2) or "
2154 "(isn't >= 1)",
2155 DescribeNegation(m));
2156
2157 m = AllOf(Gt(0), Ne(1), Ne(2));
2158 EXPECT_EQ("(isn't > 0) or "
2159 "((is equal to 1) or "
2160 "(is equal to 2))",
2161 DescribeNegation(m));
2162
2163
2164 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002165 EXPECT_EQ("((isn't > 0) or "
2166 "(is equal to 1)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002167 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002168 "(is equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002169 DescribeNegation(m));
2170
2171
2172 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002173 EXPECT_EQ("((isn't >= 0) or "
2174 "(isn't < 10)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002175 "((is equal to 3) or "
2176 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002177 "(is equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002178 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00002179}
2180
zhanyong.wan18490652009-05-11 18:54:08 +00002181// Tests that monomorphic matchers are safely cast by the AllOf matcher.
2182TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2183 // greater_than_5 and less_than_10 are monomorphic matchers.
2184 Matcher<int> greater_than_5 = Gt(5);
2185 Matcher<int> less_than_10 = Lt(10);
2186
2187 Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2188 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2189 Matcher<int&> m3 = AllOf(greater_than_5, m2);
2190
2191 // Tests that BothOf works when composing itself.
2192 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2193 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2194}
2195
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002196TEST(AllOfTest, ExplainsResult) {
2197 Matcher<int> m;
2198
2199 // Successful match. Both matchers need to explain. The second
2200 // matcher doesn't give an explanation, so only the first matcher's
2201 // explanation is printed.
2202 m = AllOf(GreaterThan(10), Lt(30));
2203 EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2204
2205 // Successful match. Both matchers need to explain.
2206 m = AllOf(GreaterThan(10), GreaterThan(20));
2207 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2208 Explain(m, 30));
2209
2210 // Successful match. All matchers need to explain. The second
2211 // matcher doesn't given an explanation.
2212 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2213 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2214 Explain(m, 25));
2215
2216 // Successful match. All matchers need to explain.
2217 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2218 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2219 "and which is 10 more than 30",
2220 Explain(m, 40));
2221
2222 // Failed match. The first matcher, which failed, needs to
2223 // explain.
2224 m = AllOf(GreaterThan(10), GreaterThan(20));
2225 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2226
2227 // Failed match. The second matcher, which failed, needs to
2228 // explain. Since it doesn't given an explanation, nothing is
2229 // printed.
2230 m = AllOf(GreaterThan(10), Lt(30));
2231 EXPECT_EQ("", Explain(m, 40));
2232
2233 // Failed match. The second matcher, which failed, needs to
2234 // explain.
2235 m = AllOf(GreaterThan(10), GreaterThan(20));
2236 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2237}
2238
zhanyong.wan02c15052010-06-09 19:21:30 +00002239// Helper to allow easy testing of AnyOf matchers with num parameters.
2240void AnyOfMatches(int num, const Matcher<int>& m) {
2241 SCOPED_TRACE(Describe(m));
2242 EXPECT_FALSE(m.Matches(0));
2243 for (int i = 1; i <= num; ++i) {
2244 EXPECT_TRUE(m.Matches(i));
2245 }
2246 EXPECT_FALSE(m.Matches(num + 1));
2247}
2248
shiqiane35fdd92008-12-10 05:08:54 +00002249// Tests that AnyOf(m1, ..., mn) matches any value that matches at
2250// least one of the given matchers.
2251TEST(AnyOfTest, MatchesWhenAnyMatches) {
2252 Matcher<int> m;
2253 m = AnyOf(Le(1), Ge(3));
2254 EXPECT_TRUE(m.Matches(1));
2255 EXPECT_TRUE(m.Matches(4));
2256 EXPECT_FALSE(m.Matches(2));
2257
2258 m = AnyOf(Lt(0), Eq(1), Eq(2));
2259 EXPECT_TRUE(m.Matches(-1));
2260 EXPECT_TRUE(m.Matches(1));
2261 EXPECT_TRUE(m.Matches(2));
2262 EXPECT_FALSE(m.Matches(0));
2263
2264 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2265 EXPECT_TRUE(m.Matches(-1));
2266 EXPECT_TRUE(m.Matches(1));
2267 EXPECT_TRUE(m.Matches(2));
2268 EXPECT_TRUE(m.Matches(3));
2269 EXPECT_FALSE(m.Matches(0));
2270
2271 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2272 EXPECT_TRUE(m.Matches(0));
2273 EXPECT_TRUE(m.Matches(11));
2274 EXPECT_TRUE(m.Matches(3));
2275 EXPECT_FALSE(m.Matches(2));
zhanyong.wan02c15052010-06-09 19:21:30 +00002276
2277 // The following tests for varying number of sub-matchers. Due to the way
2278 // the sub-matchers are handled it is enough to test every sub-matcher once
2279 // with sub-matchers using the same matcher type. Varying matcher types are
2280 // checked for above.
2281 AnyOfMatches(2, AnyOf(1, 2));
2282 AnyOfMatches(3, AnyOf(1, 2, 3));
2283 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2284 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2285 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2286 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2287 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2288 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2289 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
shiqiane35fdd92008-12-10 05:08:54 +00002290}
2291
zhanyong.wan616180e2013-06-18 18:49:51 +00002292#if GTEST_LANG_CXX11
2293// Tests the variadic version of the AnyOfMatcher.
2294TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2295 // Also make sure AnyOf is defined in the right namespace and does not depend
2296 // on ADL.
2297 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2298
2299 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))"));
2300 AnyOfMatches(11, m);
2301 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2302 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2303 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2304 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2305 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2306}
2307
2308#endif // GTEST_LANG_CXX11
2309
shiqiane35fdd92008-12-10 05:08:54 +00002310// Tests that AnyOf(m1, ..., mn) describes itself properly.
2311TEST(AnyOfTest, CanDescribeSelf) {
2312 Matcher<int> m;
2313 m = AnyOf(Le(1), Ge(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002314 EXPECT_EQ("(is <= 1) or (is >= 3)",
shiqiane35fdd92008-12-10 05:08:54 +00002315 Describe(m));
2316
2317 m = AnyOf(Lt(0), Eq(1), Eq(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002318 EXPECT_EQ("(is < 0) or "
shiqiane35fdd92008-12-10 05:08:54 +00002319 "((is equal to 1) or (is equal to 2))",
2320 Describe(m));
2321
2322 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002323 EXPECT_EQ("((is < 0) or "
2324 "(is equal to 1)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002325 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002326 "(is equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002327 Describe(m));
2328
2329 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002330 EXPECT_EQ("((is <= 0) or "
2331 "(is > 10)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002332 "((is equal to 3) or "
2333 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002334 "(is equal to 7)))",
shiqiane35fdd92008-12-10 05:08:54 +00002335 Describe(m));
2336}
2337
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002338// Tests that AnyOf(m1, ..., mn) describes its negation properly.
2339TEST(AnyOfTest, CanDescribeNegation) {
2340 Matcher<int> m;
2341 m = AnyOf(Le(1), Ge(3));
2342 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2343 DescribeNegation(m));
2344
2345 m = AnyOf(Lt(0), Eq(1), Eq(2));
2346 EXPECT_EQ("(isn't < 0) and "
2347 "((isn't equal to 1) and (isn't equal to 2))",
2348 DescribeNegation(m));
2349
2350 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002351 EXPECT_EQ("((isn't < 0) and "
2352 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002353 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002354 "(isn't equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002355 DescribeNegation(m));
2356
2357 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002358 EXPECT_EQ("((isn't <= 0) and "
2359 "(isn't > 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002360 "((isn't equal to 3) and "
2361 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002362 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002363 DescribeNegation(m));
2364}
2365
zhanyong.wan18490652009-05-11 18:54:08 +00002366// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2367TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2368 // greater_than_5 and less_than_10 are monomorphic matchers.
2369 Matcher<int> greater_than_5 = Gt(5);
2370 Matcher<int> less_than_10 = Lt(10);
2371
2372 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2373 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2374 Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2375
2376 // Tests that EitherOf works when composing itself.
2377 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2378 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2379}
2380
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002381TEST(AnyOfTest, ExplainsResult) {
2382 Matcher<int> m;
2383
2384 // Failed match. Both matchers need to explain. The second
2385 // matcher doesn't give an explanation, so only the first matcher's
2386 // explanation is printed.
2387 m = AnyOf(GreaterThan(10), Lt(0));
2388 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2389
2390 // Failed match. Both matchers need to explain.
2391 m = AnyOf(GreaterThan(10), GreaterThan(20));
2392 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2393 Explain(m, 5));
2394
2395 // Failed match. All matchers need to explain. The second
2396 // matcher doesn't given an explanation.
2397 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2398 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2399 Explain(m, 5));
2400
2401 // Failed match. All matchers need to explain.
2402 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2403 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2404 "and which is 25 less than 30",
2405 Explain(m, 5));
2406
2407 // Successful match. The first matcher, which succeeded, needs to
2408 // explain.
2409 m = AnyOf(GreaterThan(10), GreaterThan(20));
2410 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2411
2412 // Successful match. The second matcher, which succeeded, needs to
2413 // explain. Since it doesn't given an explanation, nothing is
2414 // printed.
2415 m = AnyOf(GreaterThan(10), Lt(30));
2416 EXPECT_EQ("", Explain(m, 0));
2417
2418 // Successful match. The second matcher, which succeeded, needs to
2419 // explain.
2420 m = AnyOf(GreaterThan(30), GreaterThan(20));
2421 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2422}
2423
shiqiane35fdd92008-12-10 05:08:54 +00002424// The following predicate function and predicate functor are for
2425// testing the Truly(predicate) matcher.
2426
2427// Returns non-zero if the input is positive. Note that the return
2428// type of this function is not bool. It's OK as Truly() accepts any
2429// unary function or functor whose return type can be implicitly
2430// converted to bool.
2431int IsPositive(double x) {
2432 return x > 0 ? 1 : 0;
2433}
2434
2435// This functor returns true if the input is greater than the given
2436// number.
2437class IsGreaterThan {
2438 public:
2439 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2440
2441 bool operator()(int n) const { return n > threshold_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002442
shiqiane35fdd92008-12-10 05:08:54 +00002443 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002444 int threshold_;
shiqiane35fdd92008-12-10 05:08:54 +00002445};
2446
2447// For testing Truly().
2448const int foo = 0;
2449
2450// This predicate returns true iff the argument references foo and has
2451// a zero value.
2452bool ReferencesFooAndIsZero(const int& n) {
2453 return (&n == &foo) && (n == 0);
2454}
2455
2456// Tests that Truly(predicate) matches what satisfies the given
2457// predicate.
2458TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2459 Matcher<double> m = Truly(IsPositive);
2460 EXPECT_TRUE(m.Matches(2.0));
2461 EXPECT_FALSE(m.Matches(-1.5));
2462}
2463
2464// Tests that Truly(predicate_functor) works too.
2465TEST(TrulyTest, CanBeUsedWithFunctor) {
2466 Matcher<int> m = Truly(IsGreaterThan(5));
2467 EXPECT_TRUE(m.Matches(6));
2468 EXPECT_FALSE(m.Matches(4));
2469}
2470
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00002471// A class that can be implicitly converted to bool.
2472class ConvertibleToBool {
2473 public:
2474 explicit ConvertibleToBool(int number) : number_(number) {}
2475 operator bool() const { return number_ != 0; }
2476
2477 private:
2478 int number_;
2479};
2480
2481ConvertibleToBool IsNotZero(int number) {
2482 return ConvertibleToBool(number);
2483}
2484
2485// Tests that the predicate used in Truly() may return a class that's
2486// implicitly convertible to bool, even when the class has no
2487// operator!().
2488TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2489 Matcher<int> m = Truly(IsNotZero);
2490 EXPECT_TRUE(m.Matches(1));
2491 EXPECT_FALSE(m.Matches(0));
2492}
2493
shiqiane35fdd92008-12-10 05:08:54 +00002494// Tests that Truly(predicate) can describe itself properly.
2495TEST(TrulyTest, CanDescribeSelf) {
2496 Matcher<double> m = Truly(IsPositive);
2497 EXPECT_EQ("satisfies the given predicate",
2498 Describe(m));
2499}
2500
2501// Tests that Truly(predicate) works when the matcher takes its
2502// argument by reference.
2503TEST(TrulyTest, WorksForByRefArguments) {
2504 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2505 EXPECT_TRUE(m.Matches(foo));
2506 int n = 0;
2507 EXPECT_FALSE(m.Matches(n));
2508}
2509
2510// Tests that Matches(m) is a predicate satisfied by whatever that
2511// matches matcher m.
2512TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2513 EXPECT_TRUE(Matches(Ge(0))(1));
2514 EXPECT_FALSE(Matches(Eq('a'))('b'));
2515}
2516
2517// Tests that Matches(m) works when the matcher takes its argument by
2518// reference.
2519TEST(MatchesTest, WorksOnByRefArguments) {
2520 int m = 0, n = 0;
2521 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2522 EXPECT_FALSE(Matches(Ref(m))(n));
2523}
2524
2525// Tests that a Matcher on non-reference type can be used in
2526// Matches().
2527TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
2528 Matcher<int> eq5 = Eq(5);
2529 EXPECT_TRUE(Matches(eq5)(5));
2530 EXPECT_FALSE(Matches(eq5)(2));
2531}
2532
zhanyong.wanb8243162009-06-04 05:48:20 +00002533// Tests Value(value, matcher). Since Value() is a simple wrapper for
2534// Matches(), which has been tested already, we don't spend a lot of
2535// effort on testing Value().
2536TEST(ValueTest, WorksWithPolymorphicMatcher) {
2537 EXPECT_TRUE(Value("hi", StartsWith("h")));
2538 EXPECT_FALSE(Value(5, Gt(10)));
2539}
2540
2541TEST(ValueTest, WorksWithMonomorphicMatcher) {
2542 const Matcher<int> is_zero = Eq(0);
2543 EXPECT_TRUE(Value(0, is_zero));
2544 EXPECT_FALSE(Value('a', is_zero));
2545
2546 int n = 0;
2547 const Matcher<const int&> ref_n = Ref(n);
2548 EXPECT_TRUE(Value(n, ref_n));
2549 EXPECT_FALSE(Value(1, ref_n));
2550}
2551
zhanyong.wana862f1d2010-03-15 21:23:04 +00002552TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002553 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002554 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002555 EXPECT_EQ("% 2 == 0", listener1.str());
2556
2557 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002558 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002559 EXPECT_EQ("", listener2.str());
2560}
2561
zhanyong.wana862f1d2010-03-15 21:23:04 +00002562TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002563 const Matcher<int> is_even = PolymorphicIsEven();
2564 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002565 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002566 EXPECT_EQ("% 2 == 0", listener1.str());
2567
2568 const Matcher<const double&> is_zero = Eq(0);
2569 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002570 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002571 EXPECT_EQ("", listener2.str());
2572}
2573
zhanyong.wana862f1d2010-03-15 21:23:04 +00002574MATCHER_P(Really, inner_matcher, "") {
2575 return ExplainMatchResult(inner_matcher, arg, result_listener);
2576}
2577
2578TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
2579 EXPECT_THAT(0, Really(Eq(0)));
2580}
2581
zhanyong.wanbf550852009-06-09 06:09:53 +00002582TEST(AllArgsTest, WorksForTuple) {
2583 EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
2584 EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
2585}
2586
2587TEST(AllArgsTest, WorksForNonTuple) {
2588 EXPECT_THAT(42, AllArgs(Gt(0)));
2589 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
2590}
2591
2592class AllArgsHelper {
2593 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002594 AllArgsHelper() {}
2595
zhanyong.wanbf550852009-06-09 06:09:53 +00002596 MOCK_METHOD2(Helper, int(char x, int y));
zhanyong.wan32de5f52009-12-23 00:13:23 +00002597
2598 private:
2599 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
zhanyong.wanbf550852009-06-09 06:09:53 +00002600};
2601
2602TEST(AllArgsTest, WorksInWithClause) {
2603 AllArgsHelper helper;
2604 ON_CALL(helper, Helper(_, _))
2605 .With(AllArgs(Lt()))
2606 .WillByDefault(Return(1));
2607 EXPECT_CALL(helper, Helper(_, _));
2608 EXPECT_CALL(helper, Helper(_, _))
2609 .With(AllArgs(Gt()))
2610 .WillOnce(Return(2));
2611
2612 EXPECT_EQ(1, helper.Helper('\1', 2));
2613 EXPECT_EQ(2, helper.Helper('a', 1));
2614}
2615
shiqiane35fdd92008-12-10 05:08:54 +00002616// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2617// matches the matcher.
2618TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
2619 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
2620 ASSERT_THAT("Foo", EndsWith("oo"));
2621 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
2622 EXPECT_THAT("Hello", StartsWith("Hell"));
2623}
2624
2625// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2626// doesn't match the matcher.
2627TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
2628 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
2629 // which cannot reference auto variables.
zhanyong.wan736baa82010-09-27 17:44:16 +00002630 static unsigned short n; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00002631 n = 5;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002632
2633 // VC++ prior to version 8.0 SP1 has a bug where it will not see any
2634 // functions declared in the namespace scope from within nested classes.
2635 // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
2636 // namespace-level functions invoked inside them need to be explicitly
2637 // resolved.
2638 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
shiqiane35fdd92008-12-10 05:08:54 +00002639 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002640 "Expected: is > 10\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002641 " Actual: 5" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002642 n = 0;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002643 EXPECT_NONFATAL_FAILURE(
2644 EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
2645 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002646 "Expected: (is <= 7) and (is >= 5)\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002647 " Actual: 0" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002648}
2649
2650// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
2651// has a reference type.
2652TEST(MatcherAssertionTest, WorksForByRefArguments) {
2653 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
2654 // reference auto variables.
2655 static int n;
2656 n = 0;
2657 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002658 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
shiqiane35fdd92008-12-10 05:08:54 +00002659 "Value of: n\n"
2660 "Expected: does not reference the variable @");
2661 // Tests the "Actual" part.
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002662 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
zhanyong.wan736baa82010-09-27 17:44:16 +00002663 "Actual: 0" + OfType("int") + ", which is located @");
shiqiane35fdd92008-12-10 05:08:54 +00002664}
2665
zhanyong.wan95b12332009-09-25 18:55:50 +00002666#if !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002667// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
2668// monomorphic.
zhanyong.wan95b12332009-09-25 18:55:50 +00002669
2670// ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
2671// Symbian compiler: it tries to compile
2672// template<T, U> class MatcherCastImpl { ...
zhanyong.wandb22c222010-01-28 21:52:29 +00002673// virtual bool MatchAndExplain(T x, ...) const {
2674// return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
zhanyong.wan95b12332009-09-25 18:55:50 +00002675// with U == string and T == const char*
2676// With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
2677// the compiler silently crashes with no output.
2678// If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
2679// the code compiles but the converted string is bogus.
shiqiane35fdd92008-12-10 05:08:54 +00002680TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
2681 Matcher<const char*> starts_with_he = StartsWith("he");
2682 ASSERT_THAT("hello", starts_with_he);
2683
2684 Matcher<const string&> ends_with_ok = EndsWith("ok");
2685 ASSERT_THAT("book", ends_with_ok);
zhanyong.wan736baa82010-09-27 17:44:16 +00002686 const string bad = "bad";
2687 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
2688 "Value of: bad\n"
2689 "Expected: ends with \"ok\"\n"
2690 " Actual: \"bad\"");
shiqiane35fdd92008-12-10 05:08:54 +00002691 Matcher<int> is_greater_than_5 = Gt(5);
2692 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
2693 "Value of: 5\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002694 "Expected: is > 5\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002695 " Actual: 5" + OfType("int"));
shiqiane35fdd92008-12-10 05:08:54 +00002696}
zhanyong.wan95b12332009-09-25 18:55:50 +00002697#endif // !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002698
2699// Tests floating-point matchers.
2700template <typename RawType>
2701class FloatingPointTest : public testing::Test {
2702 protected:
zhanyong.wan35877b72013-09-18 17:51:08 +00002703 typedef testing::internal::FloatingPoint<RawType> Floating;
shiqiane35fdd92008-12-10 05:08:54 +00002704 typedef typename Floating::Bits Bits;
2705
zhanyong.wan35877b72013-09-18 17:51:08 +00002706 FloatingPointTest()
2707 : max_ulps_(Floating::kMaxUlps),
2708 zero_bits_(Floating(0).bits()),
2709 one_bits_(Floating(1).bits()),
2710 infinity_bits_(Floating(Floating::Infinity()).bits()),
Mark Mentovaicbce23f2015-11-11 17:44:12 -05002711 close_to_positive_zero_(Floating::ReinterpretBits(
2712 static_cast<Bits>(zero_bits_ + max_ulps_/2))),
2713 close_to_negative_zero_(-Floating::ReinterpretBits(
2714 static_cast<Bits>(zero_bits_ + max_ulps_ - max_ulps_/2))),
zhanyong.wan35877b72013-09-18 17:51:08 +00002715 further_from_negative_zero_(-Floating::ReinterpretBits(
Mark Mentovaicbce23f2015-11-11 17:44:12 -05002716 static_cast<Bits>(zero_bits_ + max_ulps_ + 1 - max_ulps_/2))),
2717 close_to_one_(Floating::ReinterpretBits(
2718 static_cast<Bits>(one_bits_ + max_ulps_))),
2719 further_from_one_(Floating::ReinterpretBits(
2720 static_cast<Bits>(one_bits_ + max_ulps_ + 1))),
zhanyong.wan35877b72013-09-18 17:51:08 +00002721 infinity_(Floating::Infinity()),
Mark Mentovaicbce23f2015-11-11 17:44:12 -05002722 close_to_infinity_(Floating::ReinterpretBits(
2723 static_cast<Bits>(infinity_bits_ - max_ulps_))),
2724 further_from_infinity_(Floating::ReinterpretBits(
2725 static_cast<Bits>(infinity_bits_ - max_ulps_ - 1))),
zhanyong.wan35877b72013-09-18 17:51:08 +00002726 max_(Floating::Max()),
2727 nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
2728 nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
shiqiane35fdd92008-12-10 05:08:54 +00002729 }
2730
2731 void TestSize() {
2732 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2733 }
2734
2735 // A battery of tests for FloatingEqMatcher::Matches.
2736 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2737 void TestMatches(
2738 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
2739 Matcher<RawType> m1 = matcher_maker(0.0);
2740 EXPECT_TRUE(m1.Matches(-0.0));
2741 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
2742 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
2743 EXPECT_FALSE(m1.Matches(1.0));
2744
2745 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
2746 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
2747
2748 Matcher<RawType> m3 = matcher_maker(1.0);
2749 EXPECT_TRUE(m3.Matches(close_to_one_));
2750 EXPECT_FALSE(m3.Matches(further_from_one_));
2751
2752 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
2753 EXPECT_FALSE(m3.Matches(0.0));
2754
2755 Matcher<RawType> m4 = matcher_maker(-infinity_);
2756 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
2757
2758 Matcher<RawType> m5 = matcher_maker(infinity_);
2759 EXPECT_TRUE(m5.Matches(close_to_infinity_));
2760
2761 // This is interesting as the representations of infinity_ and nan1_
2762 // are only 1 DLP apart.
2763 EXPECT_FALSE(m5.Matches(nan1_));
2764
2765 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2766 // some cases.
2767 Matcher<const RawType&> m6 = matcher_maker(0.0);
2768 EXPECT_TRUE(m6.Matches(-0.0));
2769 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
2770 EXPECT_FALSE(m6.Matches(1.0));
2771
2772 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2773 // cases.
2774 Matcher<RawType&> m7 = matcher_maker(0.0);
2775 RawType x = 0.0;
2776 EXPECT_TRUE(m7.Matches(x));
2777 x = 0.01f;
2778 EXPECT_FALSE(m7.Matches(x));
2779 }
2780
2781 // Pre-calculated numbers to be used by the tests.
2782
Mark Mentovaicbce23f2015-11-11 17:44:12 -05002783 const size_t max_ulps_;
shiqiane35fdd92008-12-10 05:08:54 +00002784
zhanyong.wan35877b72013-09-18 17:51:08 +00002785 const Bits zero_bits_; // The bits that represent 0.0.
2786 const Bits one_bits_; // The bits that represent 1.0.
2787 const Bits infinity_bits_; // The bits that represent +infinity.
shiqiane35fdd92008-12-10 05:08:54 +00002788
zhanyong.wan35877b72013-09-18 17:51:08 +00002789 // Some numbers close to 0.0.
2790 const RawType close_to_positive_zero_;
2791 const RawType close_to_negative_zero_;
2792 const RawType further_from_negative_zero_;
shiqiane35fdd92008-12-10 05:08:54 +00002793
zhanyong.wan35877b72013-09-18 17:51:08 +00002794 // Some numbers close to 1.0.
2795 const RawType close_to_one_;
2796 const RawType further_from_one_;
2797
2798 // Some numbers close to +infinity.
2799 const RawType infinity_;
2800 const RawType close_to_infinity_;
2801 const RawType further_from_infinity_;
2802
2803 // Maximum representable value that's not infinity.
2804 const RawType max_;
2805
2806 // Some NaNs.
2807 const RawType nan1_;
2808 const RawType nan2_;
shiqiane35fdd92008-12-10 05:08:54 +00002809};
2810
zhanyong.wan616180e2013-06-18 18:49:51 +00002811// Tests floating-point matchers with fixed epsilons.
2812template <typename RawType>
2813class FloatingPointNearTest : public FloatingPointTest<RawType> {
2814 protected:
2815 typedef FloatingPointTest<RawType> ParentType;
2816
2817 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
2818 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2819 void TestNearMatches(
2820 testing::internal::FloatingEqMatcher<RawType>
2821 (*matcher_maker)(RawType, RawType)) {
2822 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
2823 EXPECT_TRUE(m1.Matches(0.0));
2824 EXPECT_TRUE(m1.Matches(-0.0));
2825 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
2826 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
2827 EXPECT_FALSE(m1.Matches(1.0));
2828
2829 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
2830 EXPECT_TRUE(m2.Matches(0.0));
2831 EXPECT_TRUE(m2.Matches(-0.0));
2832 EXPECT_TRUE(m2.Matches(1.0));
2833 EXPECT_TRUE(m2.Matches(-1.0));
2834 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
2835 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
2836
2837 // Check that inf matches inf, regardless of the of the specified max
2838 // absolute error.
2839 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
2840 EXPECT_TRUE(m3.Matches(ParentType::infinity_));
2841 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
2842 EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
2843
2844 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
2845 EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
2846 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
2847 EXPECT_FALSE(m4.Matches(ParentType::infinity_));
2848
2849 // Test various overflow scenarios.
zhanyong.wan35877b72013-09-18 17:51:08 +00002850 Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
2851 EXPECT_TRUE(m5.Matches(ParentType::max_));
2852 EXPECT_FALSE(m5.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002853
zhanyong.wan35877b72013-09-18 17:51:08 +00002854 Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
2855 EXPECT_FALSE(m6.Matches(ParentType::max_));
2856 EXPECT_TRUE(m6.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002857
zhanyong.wan35877b72013-09-18 17:51:08 +00002858 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
2859 EXPECT_TRUE(m7.Matches(ParentType::max_));
2860 EXPECT_FALSE(m7.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002861
zhanyong.wan35877b72013-09-18 17:51:08 +00002862 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
2863 EXPECT_FALSE(m8.Matches(ParentType::max_));
2864 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002865
2866 // The difference between max() and -max() normally overflows to infinity,
2867 // but it should still match if the max_abs_error is also infinity.
2868 Matcher<RawType> m9 = matcher_maker(
zhanyong.wan35877b72013-09-18 17:51:08 +00002869 ParentType::max_, ParentType::infinity_);
2870 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002871
2872 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2873 // some cases.
2874 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
2875 EXPECT_TRUE(m10.Matches(-0.0));
2876 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
2877 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
2878
2879 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2880 // cases.
2881 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
2882 RawType x = 0.0;
2883 EXPECT_TRUE(m11.Matches(x));
2884 x = 1.0f;
2885 EXPECT_TRUE(m11.Matches(x));
2886 x = -1.0f;
2887 EXPECT_TRUE(m11.Matches(x));
2888 x = 1.1f;
2889 EXPECT_FALSE(m11.Matches(x));
2890 x = -1.1f;
2891 EXPECT_FALSE(m11.Matches(x));
2892 }
2893};
2894
shiqiane35fdd92008-12-10 05:08:54 +00002895// Instantiate FloatingPointTest for testing floats.
2896typedef FloatingPointTest<float> FloatTest;
2897
2898TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
2899 TestMatches(&FloatEq);
2900}
2901
2902TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
2903 TestMatches(&NanSensitiveFloatEq);
2904}
2905
2906TEST_F(FloatTest, FloatEqCannotMatchNaN) {
2907 // FloatEq never matches NaN.
2908 Matcher<float> m = FloatEq(nan1_);
2909 EXPECT_FALSE(m.Matches(nan1_));
2910 EXPECT_FALSE(m.Matches(nan2_));
2911 EXPECT_FALSE(m.Matches(1.0));
2912}
2913
2914TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
2915 // NanSensitiveFloatEq will match NaN.
2916 Matcher<float> m = NanSensitiveFloatEq(nan1_);
2917 EXPECT_TRUE(m.Matches(nan1_));
2918 EXPECT_TRUE(m.Matches(nan2_));
2919 EXPECT_FALSE(m.Matches(1.0));
2920}
2921
2922TEST_F(FloatTest, FloatEqCanDescribeSelf) {
2923 Matcher<float> m1 = FloatEq(2.0f);
2924 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002925 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002926
2927 Matcher<float> m2 = FloatEq(0.5f);
2928 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002929 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002930
2931 Matcher<float> m3 = FloatEq(nan1_);
2932 EXPECT_EQ("never matches", Describe(m3));
2933 EXPECT_EQ("is anything", DescribeNegation(m3));
2934}
2935
2936TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
2937 Matcher<float> m1 = NanSensitiveFloatEq(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 = NanSensitiveFloatEq(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 = NanSensitiveFloatEq(nan1_);
2946 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002947 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00002948}
2949
zhanyong.wan616180e2013-06-18 18:49:51 +00002950// Instantiate FloatingPointTest for testing floats with a user-specified
2951// max absolute error.
2952typedef FloatingPointNearTest<float> FloatNearTest;
2953
2954TEST_F(FloatNearTest, FloatNearMatches) {
2955 TestNearMatches(&FloatNear);
2956}
2957
2958TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
2959 TestNearMatches(&NanSensitiveFloatNear);
2960}
2961
2962TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
2963 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
2964 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2965 EXPECT_EQ(
2966 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2967
2968 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
2969 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2970 EXPECT_EQ(
2971 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2972
2973 Matcher<float> m3 = FloatNear(nan1_, 0.0);
2974 EXPECT_EQ("never matches", Describe(m3));
2975 EXPECT_EQ("is anything", DescribeNegation(m3));
2976}
2977
2978TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
2979 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
2980 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2981 EXPECT_EQ(
2982 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2983
2984 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
2985 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2986 EXPECT_EQ(
2987 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2988
2989 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
2990 EXPECT_EQ("is NaN", Describe(m3));
2991 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
2992}
2993
2994TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
2995 // FloatNear never matches NaN.
2996 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
2997 EXPECT_FALSE(m.Matches(nan1_));
2998 EXPECT_FALSE(m.Matches(nan2_));
2999 EXPECT_FALSE(m.Matches(1.0));
3000}
3001
3002TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
3003 // NanSensitiveFloatNear will match NaN.
3004 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
3005 EXPECT_TRUE(m.Matches(nan1_));
3006 EXPECT_TRUE(m.Matches(nan2_));
3007 EXPECT_FALSE(m.Matches(1.0));
3008}
3009
shiqiane35fdd92008-12-10 05:08:54 +00003010// Instantiate FloatingPointTest for testing doubles.
3011typedef FloatingPointTest<double> DoubleTest;
3012
3013TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
3014 TestMatches(&DoubleEq);
3015}
3016
3017TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
3018 TestMatches(&NanSensitiveDoubleEq);
3019}
3020
3021TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
3022 // DoubleEq never matches NaN.
3023 Matcher<double> m = DoubleEq(nan1_);
3024 EXPECT_FALSE(m.Matches(nan1_));
3025 EXPECT_FALSE(m.Matches(nan2_));
3026 EXPECT_FALSE(m.Matches(1.0));
3027}
3028
3029TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3030 // NanSensitiveDoubleEq will match NaN.
3031 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
3032 EXPECT_TRUE(m.Matches(nan1_));
3033 EXPECT_TRUE(m.Matches(nan2_));
3034 EXPECT_FALSE(m.Matches(1.0));
3035}
3036
3037TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3038 Matcher<double> m1 = DoubleEq(2.0);
3039 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003040 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003041
3042 Matcher<double> m2 = DoubleEq(0.5);
3043 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003044 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003045
3046 Matcher<double> m3 = DoubleEq(nan1_);
3047 EXPECT_EQ("never matches", Describe(m3));
3048 EXPECT_EQ("is anything", DescribeNegation(m3));
3049}
3050
3051TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3052 Matcher<double> m1 = NanSensitiveDoubleEq(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 = NanSensitiveDoubleEq(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 = NanSensitiveDoubleEq(nan1_);
3061 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003062 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00003063}
3064
zhanyong.wan616180e2013-06-18 18:49:51 +00003065// Instantiate FloatingPointTest for testing floats with a user-specified
3066// max absolute error.
3067typedef FloatingPointNearTest<double> DoubleNearTest;
3068
3069TEST_F(DoubleNearTest, DoubleNearMatches) {
3070 TestNearMatches(&DoubleNear);
3071}
3072
3073TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3074 TestNearMatches(&NanSensitiveDoubleNear);
3075}
3076
3077TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3078 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3079 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3080 EXPECT_EQ(
3081 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3082
3083 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3084 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3085 EXPECT_EQ(
3086 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3087
3088 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3089 EXPECT_EQ("never matches", Describe(m3));
3090 EXPECT_EQ("is anything", DescribeNegation(m3));
3091}
3092
kosak6b817802015-01-08 02:38:14 +00003093TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {
3094 EXPECT_EQ("", Explain(DoubleNear(2.0, 0.1), 2.05));
3095 EXPECT_EQ("which is 0.2 from 2", Explain(DoubleNear(2.0, 0.1), 2.2));
3096 EXPECT_EQ("which is -0.3 from 2", Explain(DoubleNear(2.0, 0.1), 1.7));
3097
3098 const string explanation = Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);
3099 // Different C++ implementations may print floating-point numbers
3100 // slightly differently.
3101 EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC
3102 explanation == "which is 1.2e-010 from 2.1") // MSVC
3103 << " where explanation is \"" << explanation << "\".";
3104}
3105
zhanyong.wan616180e2013-06-18 18:49:51 +00003106TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3107 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3108 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3109 EXPECT_EQ(
3110 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3111
3112 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3113 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3114 EXPECT_EQ(
3115 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3116
3117 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3118 EXPECT_EQ("is NaN", Describe(m3));
3119 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3120}
3121
3122TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3123 // DoubleNear never matches NaN.
3124 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3125 EXPECT_FALSE(m.Matches(nan1_));
3126 EXPECT_FALSE(m.Matches(nan2_));
3127 EXPECT_FALSE(m.Matches(1.0));
3128}
3129
3130TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3131 // NanSensitiveDoubleNear will match NaN.
3132 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3133 EXPECT_TRUE(m.Matches(nan1_));
3134 EXPECT_TRUE(m.Matches(nan2_));
3135 EXPECT_FALSE(m.Matches(1.0));
3136}
3137
shiqiane35fdd92008-12-10 05:08:54 +00003138TEST(PointeeTest, RawPointer) {
3139 const Matcher<int*> m = Pointee(Ge(0));
3140
3141 int n = 1;
3142 EXPECT_TRUE(m.Matches(&n));
3143 n = -1;
3144 EXPECT_FALSE(m.Matches(&n));
3145 EXPECT_FALSE(m.Matches(NULL));
3146}
3147
3148TEST(PointeeTest, RawPointerToConst) {
3149 const Matcher<const double*> m = Pointee(Ge(0));
3150
3151 double x = 1;
3152 EXPECT_TRUE(m.Matches(&x));
3153 x = -1;
3154 EXPECT_FALSE(m.Matches(&x));
3155 EXPECT_FALSE(m.Matches(NULL));
3156}
3157
3158TEST(PointeeTest, ReferenceToConstRawPointer) {
3159 const Matcher<int* const &> m = Pointee(Ge(0));
3160
3161 int n = 1;
3162 EXPECT_TRUE(m.Matches(&n));
3163 n = -1;
3164 EXPECT_FALSE(m.Matches(&n));
3165 EXPECT_FALSE(m.Matches(NULL));
3166}
3167
3168TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3169 const Matcher<double* &> m = Pointee(Ge(0));
3170
3171 double x = 1.0;
3172 double* p = &x;
3173 EXPECT_TRUE(m.Matches(p));
3174 x = -1;
3175 EXPECT_FALSE(m.Matches(p));
3176 p = NULL;
3177 EXPECT_FALSE(m.Matches(p));
3178}
3179
billydonahue1f5fdea2014-05-19 17:54:51 +00003180MATCHER_P(FieldIIs, inner_matcher, "") {
3181 return ExplainMatchResult(inner_matcher, arg.i, result_listener);
3182}
3183
Mark Mentovaic8a10502015-10-12 18:01:43 -04003184#if GTEST_HAS_RTTI
3185
billydonahue1f5fdea2014-05-19 17:54:51 +00003186TEST(WhenDynamicCastToTest, SameType) {
3187 Derived derived;
3188 derived.i = 4;
3189
3190 // Right type. A pointer is passed down.
3191 Base* as_base_ptr = &derived;
3192 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
3193 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
3194 EXPECT_THAT(as_base_ptr,
3195 Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
3196}
3197
3198TEST(WhenDynamicCastToTest, WrongTypes) {
3199 Base base;
3200 Derived derived;
3201 OtherDerived other_derived;
3202
3203 // Wrong types. NULL is passed.
3204 EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3205 EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
3206 Base* as_base_ptr = &derived;
3207 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
3208 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
3209 as_base_ptr = &other_derived;
3210 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3211 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3212}
3213
3214TEST(WhenDynamicCastToTest, AlreadyNull) {
3215 // Already NULL.
3216 Base* as_base_ptr = NULL;
3217 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3218}
3219
3220struct AmbiguousCastTypes {
3221 class VirtualDerived : public virtual Base {};
3222 class DerivedSub1 : public VirtualDerived {};
3223 class DerivedSub2 : public VirtualDerived {};
3224 class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
3225};
3226
3227TEST(WhenDynamicCastToTest, AmbiguousCast) {
3228 AmbiguousCastTypes::DerivedSub1 sub1;
3229 AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
3230 // Multiply derived from Base. dynamic_cast<> returns NULL.
3231 Base* as_base_ptr =
3232 static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
3233 EXPECT_THAT(as_base_ptr,
3234 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
3235 as_base_ptr = &sub1;
3236 EXPECT_THAT(
3237 as_base_ptr,
3238 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
3239}
3240
3241TEST(WhenDynamicCastToTest, Describe) {
3242 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
billydonahue1f5fdea2014-05-19 17:54:51 +00003243 const string prefix =
3244 "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
billydonahue1f5fdea2014-05-19 17:54:51 +00003245 EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
3246 EXPECT_EQ(prefix + "does not point to a value that is anything",
3247 DescribeNegation(matcher));
3248}
3249
3250TEST(WhenDynamicCastToTest, Explain) {
3251 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3252 Base* null = NULL;
3253 EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
3254 Derived derived;
3255 EXPECT_TRUE(matcher.Matches(&derived));
3256 EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
3257
3258 // With references, the matcher itself can fail. Test for that one.
3259 Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
3260 EXPECT_THAT(Explain(ref_matcher, derived),
3261 HasSubstr("which cannot be dynamic_cast"));
3262}
3263
3264TEST(WhenDynamicCastToTest, GoodReference) {
3265 Derived derived;
3266 derived.i = 4;
3267 Base& as_base_ref = derived;
3268 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
3269 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
3270}
3271
3272TEST(WhenDynamicCastToTest, BadReference) {
3273 Derived derived;
3274 Base& as_base_ref = derived;
3275 EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
3276}
3277
Mark Mentovaic8a10502015-10-12 18:01:43 -04003278#endif // GTEST_HAS_RTTI
3279
vladlosevada23472012-08-14 15:38:49 +00003280// Minimal const-propagating pointer.
3281template <typename T>
3282class ConstPropagatingPtr {
3283 public:
3284 typedef T element_type;
3285
3286 ConstPropagatingPtr() : val_() {}
3287 explicit ConstPropagatingPtr(T* t) : val_(t) {}
3288 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3289
3290 T* get() { return val_; }
3291 T& operator*() { return *val_; }
3292 // Most smart pointers return non-const T* and T& from the next methods.
3293 const T* get() const { return val_; }
3294 const T& operator*() const { return *val_; }
3295
3296 private:
3297 T* val_;
3298};
3299
3300TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3301 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3302 int three = 3;
3303 const ConstPropagatingPtr<int> co(&three);
3304 ConstPropagatingPtr<int> o(&three);
3305 EXPECT_TRUE(m.Matches(o));
3306 EXPECT_TRUE(m.Matches(co));
3307 *o = 6;
3308 EXPECT_FALSE(m.Matches(o));
3309 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3310}
3311
shiqiane35fdd92008-12-10 05:08:54 +00003312TEST(PointeeTest, NeverMatchesNull) {
3313 const Matcher<const char*> m = Pointee(_);
3314 EXPECT_FALSE(m.Matches(NULL));
3315}
3316
3317// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3318TEST(PointeeTest, MatchesAgainstAValue) {
3319 const Matcher<int*> m = Pointee(5);
3320
3321 int n = 5;
3322 EXPECT_TRUE(m.Matches(&n));
3323 n = -1;
3324 EXPECT_FALSE(m.Matches(&n));
3325 EXPECT_FALSE(m.Matches(NULL));
3326}
3327
3328TEST(PointeeTest, CanDescribeSelf) {
3329 const Matcher<int*> m = Pointee(Gt(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003330 EXPECT_EQ("points to a value that is > 3", Describe(m));
3331 EXPECT_EQ("does not point to a value that is > 3",
shiqiane35fdd92008-12-10 05:08:54 +00003332 DescribeNegation(m));
3333}
3334
shiqiane35fdd92008-12-10 05:08:54 +00003335TEST(PointeeTest, CanExplainMatchResult) {
3336 const Matcher<const string*> m = Pointee(StartsWith("Hi"));
3337
3338 EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL)));
3339
zhanyong.wan736baa82010-09-27 17:44:16 +00003340 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
3341 long n = 3; // NOLINT
3342 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003343 Explain(m2, &n));
3344}
3345
3346TEST(PointeeTest, AlwaysExplainsPointee) {
3347 const Matcher<int*> m = Pointee(0);
3348 int n = 42;
zhanyong.wan736baa82010-09-27 17:44:16 +00003349 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
shiqiane35fdd92008-12-10 05:08:54 +00003350}
3351
3352// An uncopyable class.
3353class Uncopyable {
3354 public:
billydonahue1f5fdea2014-05-19 17:54:51 +00003355 Uncopyable() : value_(-1) {}
zhanyong.wan32de5f52009-12-23 00:13:23 +00003356 explicit Uncopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003357
3358 int value() const { return value_; }
billydonahue1f5fdea2014-05-19 17:54:51 +00003359 void set_value(int i) { value_ = i; }
3360
shiqiane35fdd92008-12-10 05:08:54 +00003361 private:
billydonahue1f5fdea2014-05-19 17:54:51 +00003362 int value_;
shiqiane35fdd92008-12-10 05:08:54 +00003363 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3364};
3365
3366// Returns true iff x.value() is positive.
3367bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3368
billydonahue1f5fdea2014-05-19 17:54:51 +00003369MATCHER_P(UncopyableIs, inner_matcher, "") {
3370 return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
3371}
3372
shiqiane35fdd92008-12-10 05:08:54 +00003373// A user-defined struct for testing Field().
3374struct AStruct {
3375 AStruct() : x(0), y(1.0), z(5), p(NULL) {}
3376 AStruct(const AStruct& rhs)
3377 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3378
3379 int x; // A non-const field.
3380 const double y; // A const field.
3381 Uncopyable z; // An uncopyable field.
3382 const char* p; // A pointer field.
zhanyong.wan32de5f52009-12-23 00:13:23 +00003383
3384 private:
3385 GTEST_DISALLOW_ASSIGN_(AStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003386};
3387
3388// A derived struct for testing Field().
3389struct DerivedStruct : public AStruct {
3390 char ch;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003391
3392 private:
3393 GTEST_DISALLOW_ASSIGN_(DerivedStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003394};
3395
3396// Tests that Field(&Foo::field, ...) works when field is non-const.
3397TEST(FieldTest, WorksForNonConstField) {
3398 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
3399
3400 AStruct a;
3401 EXPECT_TRUE(m.Matches(a));
3402 a.x = -1;
3403 EXPECT_FALSE(m.Matches(a));
3404}
3405
3406// Tests that Field(&Foo::field, ...) works when field is const.
3407TEST(FieldTest, WorksForConstField) {
3408 AStruct a;
3409
3410 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
3411 EXPECT_TRUE(m.Matches(a));
3412 m = Field(&AStruct::y, Le(0.0));
3413 EXPECT_FALSE(m.Matches(a));
3414}
3415
3416// Tests that Field(&Foo::field, ...) works when field is not copyable.
3417TEST(FieldTest, WorksForUncopyableField) {
3418 AStruct a;
3419
3420 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3421 EXPECT_TRUE(m.Matches(a));
3422 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3423 EXPECT_FALSE(m.Matches(a));
3424}
3425
3426// Tests that Field(&Foo::field, ...) works when field is a pointer.
3427TEST(FieldTest, WorksForPointerField) {
3428 // Matching against NULL.
3429 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
3430 AStruct a;
3431 EXPECT_TRUE(m.Matches(a));
3432 a.p = "hi";
3433 EXPECT_FALSE(m.Matches(a));
3434
3435 // Matching a pointer that is not NULL.
3436 m = Field(&AStruct::p, StartsWith("hi"));
3437 a.p = "hill";
3438 EXPECT_TRUE(m.Matches(a));
3439 a.p = "hole";
3440 EXPECT_FALSE(m.Matches(a));
3441}
3442
3443// Tests that Field() works when the object is passed by reference.
3444TEST(FieldTest, WorksForByRefArgument) {
3445 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3446
3447 AStruct a;
3448 EXPECT_TRUE(m.Matches(a));
3449 a.x = -1;
3450 EXPECT_FALSE(m.Matches(a));
3451}
3452
3453// Tests that Field(&Foo::field, ...) works when the argument's type
3454// is a sub-type of Foo.
3455TEST(FieldTest, WorksForArgumentOfSubType) {
3456 // Note that the matcher expects DerivedStruct but we say AStruct
3457 // inside Field().
3458 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
3459
3460 DerivedStruct d;
3461 EXPECT_TRUE(m.Matches(d));
3462 d.x = -1;
3463 EXPECT_FALSE(m.Matches(d));
3464}
3465
3466// Tests that Field(&Foo::field, m) works when field's type and m's
3467// argument type are compatible but not the same.
3468TEST(FieldTest, WorksForCompatibleMatcherType) {
3469 // The field is an int, but the inner matcher expects a signed char.
3470 Matcher<const AStruct&> m = Field(&AStruct::x,
3471 Matcher<signed char>(Ge(0)));
3472
3473 AStruct a;
3474 EXPECT_TRUE(m.Matches(a));
3475 a.x = -1;
3476 EXPECT_FALSE(m.Matches(a));
3477}
3478
3479// Tests that Field() can describe itself.
3480TEST(FieldTest, CanDescribeSelf) {
3481 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3482
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003483 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3484 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003485}
3486
3487// Tests that Field() can explain the match result.
3488TEST(FieldTest, CanExplainMatchResult) {
3489 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3490
3491 AStruct a;
3492 a.x = 1;
zhanyong.wan736baa82010-09-27 17:44:16 +00003493 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003494
3495 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003496 EXPECT_EQ(
3497 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
3498 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003499}
3500
3501// Tests that Field() works when the argument is a pointer to const.
3502TEST(FieldForPointerTest, WorksForPointerToConst) {
3503 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3504
3505 AStruct a;
3506 EXPECT_TRUE(m.Matches(&a));
3507 a.x = -1;
3508 EXPECT_FALSE(m.Matches(&a));
3509}
3510
3511// Tests that Field() works when the argument is a pointer to non-const.
3512TEST(FieldForPointerTest, WorksForPointerToNonConst) {
3513 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
3514
3515 AStruct a;
3516 EXPECT_TRUE(m.Matches(&a));
3517 a.x = -1;
3518 EXPECT_FALSE(m.Matches(&a));
3519}
3520
zhanyong.wan6953a722010-01-13 05:15:07 +00003521// Tests that Field() works when the argument is a reference to a const pointer.
3522TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
3523 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
3524
3525 AStruct a;
3526 EXPECT_TRUE(m.Matches(&a));
3527 a.x = -1;
3528 EXPECT_FALSE(m.Matches(&a));
3529}
3530
shiqiane35fdd92008-12-10 05:08:54 +00003531// Tests that Field() does not match the NULL pointer.
3532TEST(FieldForPointerTest, DoesNotMatchNull) {
3533 Matcher<const AStruct*> m = Field(&AStruct::x, _);
3534 EXPECT_FALSE(m.Matches(NULL));
3535}
3536
3537// Tests that Field(&Foo::field, ...) works when the argument's type
3538// is a sub-type of const Foo*.
3539TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
3540 // Note that the matcher expects DerivedStruct but we say AStruct
3541 // inside Field().
3542 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
3543
3544 DerivedStruct d;
3545 EXPECT_TRUE(m.Matches(&d));
3546 d.x = -1;
3547 EXPECT_FALSE(m.Matches(&d));
3548}
3549
3550// Tests that Field() can describe itself when used to match a pointer.
3551TEST(FieldForPointerTest, CanDescribeSelf) {
3552 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3553
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003554 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3555 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003556}
3557
3558// Tests that Field() can explain the result of matching a pointer.
3559TEST(FieldForPointerTest, CanExplainMatchResult) {
3560 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3561
3562 AStruct a;
3563 a.x = 1;
3564 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003565 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
3566 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003567
3568 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003569 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
3570 ", which is 1 more than 0", Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003571}
3572
3573// A user-defined class for testing Property().
3574class AClass {
3575 public:
3576 AClass() : n_(0) {}
3577
3578 // A getter that returns a non-reference.
3579 int n() const { return n_; }
3580
3581 void set_n(int new_n) { n_ = new_n; }
3582
3583 // A getter that returns a reference to const.
3584 const string& s() const { return s_; }
3585
3586 void set_s(const string& new_s) { s_ = new_s; }
3587
3588 // A getter that returns a reference to non-const.
3589 double& x() const { return x_; }
3590 private:
3591 int n_;
3592 string s_;
3593
3594 static double x_;
3595};
3596
3597double AClass::x_ = 0.0;
3598
3599// A derived class for testing Property().
3600class DerivedClass : public AClass {
kosak6414d802013-12-03 23:19:36 +00003601 public:
3602 int k() const { return k_; }
shiqiane35fdd92008-12-10 05:08:54 +00003603 private:
3604 int k_;
3605};
3606
3607// Tests that Property(&Foo::property, ...) works when property()
3608// returns a non-reference.
3609TEST(PropertyTest, WorksForNonReferenceProperty) {
3610 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3611
3612 AClass a;
3613 a.set_n(1);
3614 EXPECT_TRUE(m.Matches(a));
3615
3616 a.set_n(-1);
3617 EXPECT_FALSE(m.Matches(a));
3618}
3619
3620// Tests that Property(&Foo::property, ...) works when property()
3621// returns a reference to const.
3622TEST(PropertyTest, WorksForReferenceToConstProperty) {
3623 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
3624
3625 AClass a;
3626 a.set_s("hill");
3627 EXPECT_TRUE(m.Matches(a));
3628
3629 a.set_s("hole");
3630 EXPECT_FALSE(m.Matches(a));
3631}
3632
3633// Tests that Property(&Foo::property, ...) works when property()
3634// returns a reference to non-const.
3635TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
3636 double x = 0.0;
3637 AClass a;
3638
3639 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
3640 EXPECT_FALSE(m.Matches(a));
3641
3642 m = Property(&AClass::x, Not(Ref(x)));
3643 EXPECT_TRUE(m.Matches(a));
3644}
3645
3646// Tests that Property(&Foo::property, ...) works when the argument is
3647// passed by value.
3648TEST(PropertyTest, WorksForByValueArgument) {
3649 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
3650
3651 AClass a;
3652 a.set_s("hill");
3653 EXPECT_TRUE(m.Matches(a));
3654
3655 a.set_s("hole");
3656 EXPECT_FALSE(m.Matches(a));
3657}
3658
3659// Tests that Property(&Foo::property, ...) works when the argument's
3660// type is a sub-type of Foo.
3661TEST(PropertyTest, WorksForArgumentOfSubType) {
3662 // The matcher expects a DerivedClass, but inside the Property() we
3663 // say AClass.
3664 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
3665
3666 DerivedClass d;
3667 d.set_n(1);
3668 EXPECT_TRUE(m.Matches(d));
3669
3670 d.set_n(-1);
3671 EXPECT_FALSE(m.Matches(d));
3672}
3673
3674// Tests that Property(&Foo::property, m) works when property()'s type
3675// and m's argument type are compatible but different.
3676TEST(PropertyTest, WorksForCompatibleMatcherType) {
3677 // n() returns an int but the inner matcher expects a signed char.
3678 Matcher<const AClass&> m = Property(&AClass::n,
3679 Matcher<signed char>(Ge(0)));
3680
3681 AClass a;
3682 EXPECT_TRUE(m.Matches(a));
3683 a.set_n(-1);
3684 EXPECT_FALSE(m.Matches(a));
3685}
3686
3687// Tests that Property() can describe itself.
3688TEST(PropertyTest, CanDescribeSelf) {
3689 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3690
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003691 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3692 EXPECT_EQ("is an object whose given property isn't >= 0",
3693 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003694}
3695
3696// Tests that Property() can explain the match result.
3697TEST(PropertyTest, CanExplainMatchResult) {
3698 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3699
3700 AClass a;
3701 a.set_n(1);
zhanyong.wan736baa82010-09-27 17:44:16 +00003702 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003703
3704 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003705 EXPECT_EQ(
3706 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
3707 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003708}
3709
3710// Tests that Property() works when the argument is a pointer to const.
3711TEST(PropertyForPointerTest, WorksForPointerToConst) {
3712 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3713
3714 AClass a;
3715 a.set_n(1);
3716 EXPECT_TRUE(m.Matches(&a));
3717
3718 a.set_n(-1);
3719 EXPECT_FALSE(m.Matches(&a));
3720}
3721
3722// Tests that Property() works when the argument is a pointer to non-const.
3723TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
3724 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
3725
3726 AClass a;
3727 a.set_s("hill");
3728 EXPECT_TRUE(m.Matches(&a));
3729
3730 a.set_s("hole");
3731 EXPECT_FALSE(m.Matches(&a));
3732}
3733
zhanyong.wan6953a722010-01-13 05:15:07 +00003734// Tests that Property() works when the argument is a reference to a
3735// const pointer.
3736TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
3737 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
3738
3739 AClass a;
3740 a.set_s("hill");
3741 EXPECT_TRUE(m.Matches(&a));
3742
3743 a.set_s("hole");
3744 EXPECT_FALSE(m.Matches(&a));
3745}
3746
shiqiane35fdd92008-12-10 05:08:54 +00003747// Tests that Property() does not match the NULL pointer.
3748TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
3749 Matcher<const AClass*> m = Property(&AClass::x, _);
3750 EXPECT_FALSE(m.Matches(NULL));
3751}
3752
3753// Tests that Property(&Foo::property, ...) works when the argument's
3754// type is a sub-type of const Foo*.
3755TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
3756 // The matcher expects a DerivedClass, but inside the Property() we
3757 // say AClass.
3758 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
3759
3760 DerivedClass d;
3761 d.set_n(1);
3762 EXPECT_TRUE(m.Matches(&d));
3763
3764 d.set_n(-1);
3765 EXPECT_FALSE(m.Matches(&d));
3766}
3767
3768// Tests that Property() can describe itself when used to match a pointer.
3769TEST(PropertyForPointerTest, CanDescribeSelf) {
3770 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3771
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003772 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3773 EXPECT_EQ("is an object whose given property isn't >= 0",
3774 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003775}
3776
3777// Tests that Property() can explain the result of matching a pointer.
3778TEST(PropertyForPointerTest, CanExplainMatchResult) {
3779 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3780
3781 AClass a;
3782 a.set_n(1);
3783 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003784 EXPECT_EQ(
3785 "which points to an object whose given property is 1" + OfType("int"),
3786 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003787
3788 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003789 EXPECT_EQ("which points to an object whose given property is 1" +
3790 OfType("int") + ", which is 1 more than 0",
3791 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003792}
3793
3794// Tests ResultOf.
3795
3796// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3797// function pointer.
3798string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; }
3799
3800TEST(ResultOfTest, WorksForFunctionPointers) {
3801 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo")));
3802
3803 EXPECT_TRUE(matcher.Matches(1));
3804 EXPECT_FALSE(matcher.Matches(2));
3805}
3806
3807// Tests that ResultOf() can describe itself.
3808TEST(ResultOfTest, CanDescribeItself) {
3809 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
3810
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003811 EXPECT_EQ("is mapped by the given callable to a value that "
3812 "is equal to \"foo\"", Describe(matcher));
3813 EXPECT_EQ("is mapped by the given callable to a value that "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003814 "isn't equal to \"foo\"", DescribeNegation(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00003815}
3816
3817// Tests that ResultOf() can explain the match result.
3818int IntFunction(int input) { return input == 42 ? 80 : 90; }
3819
3820TEST(ResultOfTest, CanExplainMatchResult) {
3821 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003822 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003823 Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003824
3825 matcher = ResultOf(&IntFunction, GreaterThan(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003826 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
3827 ", which is 5 more than 85", Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003828}
3829
3830// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3831// returns a non-reference.
3832TEST(ResultOfTest, WorksForNonReferenceResults) {
3833 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
3834
3835 EXPECT_TRUE(matcher.Matches(42));
3836 EXPECT_FALSE(matcher.Matches(36));
3837}
3838
3839// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3840// returns a reference to non-const.
zhanyong.wan736baa82010-09-27 17:44:16 +00003841double& DoubleFunction(double& input) { return input; } // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003842
zhanyong.wan736baa82010-09-27 17:44:16 +00003843Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003844 return obj;
3845}
3846
3847TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
3848 double x = 3.14;
3849 double x2 = x;
3850 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
3851
3852 EXPECT_TRUE(matcher.Matches(x));
3853 EXPECT_FALSE(matcher.Matches(x2));
3854
3855 // Test that ResultOf works with uncopyable objects
3856 Uncopyable obj(0);
3857 Uncopyable obj2(0);
3858 Matcher<Uncopyable&> matcher2 =
3859 ResultOf(&RefUncopyableFunction, Ref(obj));
3860
3861 EXPECT_TRUE(matcher2.Matches(obj));
3862 EXPECT_FALSE(matcher2.Matches(obj2));
3863}
3864
3865// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3866// returns a reference to const.
3867const string& StringFunction(const string& input) { return input; }
3868
3869TEST(ResultOfTest, WorksForReferenceToConstResults) {
3870 string s = "foo";
3871 string s2 = s;
3872 Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s));
3873
3874 EXPECT_TRUE(matcher.Matches(s));
3875 EXPECT_FALSE(matcher.Matches(s2));
3876}
3877
3878// Tests that ResultOf(f, m) works when f(x) and m's
3879// argument types are compatible but different.
3880TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
3881 // IntFunction() returns int but the inner matcher expects a signed char.
3882 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
3883
3884 EXPECT_TRUE(matcher.Matches(36));
3885 EXPECT_FALSE(matcher.Matches(42));
3886}
3887
shiqiane35fdd92008-12-10 05:08:54 +00003888// Tests that the program aborts when ResultOf is passed
3889// a NULL function pointer.
3890TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
zhanyong.wan04d6ed82009-09-11 07:01:08 +00003891 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan736baa82010-09-27 17:44:16 +00003892 ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))),
shiqiane35fdd92008-12-10 05:08:54 +00003893 "NULL function pointer is passed into ResultOf\\(\\)\\.");
3894}
shiqiane35fdd92008-12-10 05:08:54 +00003895
3896// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3897// function reference.
3898TEST(ResultOfTest, WorksForFunctionReferences) {
3899 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
3900 EXPECT_TRUE(matcher.Matches(1));
3901 EXPECT_FALSE(matcher.Matches(2));
3902}
3903
3904// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3905// function object.
3906struct Functor : public ::std::unary_function<int, string> {
3907 result_type operator()(argument_type input) const {
3908 return IntToStringFunction(input);
3909 }
3910};
3911
3912TEST(ResultOfTest, WorksForFunctors) {
3913 Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo")));
3914
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// functor with more then one operator() defined. ResultOf() must work
3921// for each defined operator().
3922struct PolymorphicFunctor {
3923 typedef int result_type;
3924 int operator()(int n) { return n; }
3925 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
3926};
3927
3928TEST(ResultOfTest, WorksForPolymorphicFunctors) {
3929 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
3930
3931 EXPECT_TRUE(matcher_int.Matches(10));
3932 EXPECT_FALSE(matcher_int.Matches(2));
3933
3934 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
3935
3936 EXPECT_TRUE(matcher_string.Matches("long string"));
3937 EXPECT_FALSE(matcher_string.Matches("shrt"));
3938}
3939
3940const int* ReferencingFunction(const int& n) { return &n; }
3941
3942struct ReferencingFunctor {
3943 typedef const int* result_type;
3944 result_type operator()(const int& n) { return &n; }
3945};
3946
3947TEST(ResultOfTest, WorksForReferencingCallables) {
3948 const int n = 1;
3949 const int n2 = 1;
3950 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
3951 EXPECT_TRUE(matcher2.Matches(n));
3952 EXPECT_FALSE(matcher2.Matches(n2));
3953
3954 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
3955 EXPECT_TRUE(matcher3.Matches(n));
3956 EXPECT_FALSE(matcher3.Matches(n2));
3957}
3958
shiqiane35fdd92008-12-10 05:08:54 +00003959class DivisibleByImpl {
3960 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003961 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
shiqiane35fdd92008-12-10 05:08:54 +00003962
zhanyong.wandb22c222010-01-28 21:52:29 +00003963 // For testing using ExplainMatchResultTo() with polymorphic matchers.
shiqiane35fdd92008-12-10 05:08:54 +00003964 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00003965 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003966 *listener << "which is " << (n % divider_) << " modulo "
zhanyong.wandb22c222010-01-28 21:52:29 +00003967 << divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003968 return (n % divider_) == 0;
3969 }
3970
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003971 void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003972 *os << "is divisible by " << divider_;
3973 }
3974
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003975 void DescribeNegationTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003976 *os << "is not divisible by " << divider_;
3977 }
3978
zhanyong.wan32de5f52009-12-23 00:13:23 +00003979 void set_divider(int a_divider) { divider_ = a_divider; }
shiqiane35fdd92008-12-10 05:08:54 +00003980 int divider() const { return divider_; }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003981
shiqiane35fdd92008-12-10 05:08:54 +00003982 private:
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003983 int divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003984};
3985
shiqiane35fdd92008-12-10 05:08:54 +00003986PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
3987 return MakePolymorphicMatcher(DivisibleByImpl(n));
3988}
3989
3990// Tests that when AllOf() fails, only the first failing matcher is
3991// asked to explain why.
3992TEST(ExplainMatchResultTest, AllOf_False_False) {
3993 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003994 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00003995}
3996
3997// Tests that when AllOf() fails, only the first failing matcher is
3998// asked to explain why.
3999TEST(ExplainMatchResultTest, AllOf_False_True) {
4000 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004001 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00004002}
4003
4004// Tests that when AllOf() fails, only the first failing matcher is
4005// asked to explain why.
4006TEST(ExplainMatchResultTest, AllOf_True_False) {
4007 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004008 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00004009}
4010
4011// Tests that when AllOf() succeeds, all matchers are asked to explain
4012// why.
4013TEST(ExplainMatchResultTest, AllOf_True_True) {
4014 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004015 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00004016}
4017
4018TEST(ExplainMatchResultTest, AllOf_True_True_2) {
4019 const Matcher<int> m = AllOf(Ge(2), Le(3));
4020 EXPECT_EQ("", Explain(m, 2));
4021}
4022
4023TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
4024 const Matcher<int> m = GreaterThan(5);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00004025 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00004026}
4027
4028// The following two tests verify that values without a public copy
4029// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
4030// with the help of ByRef().
4031
4032class NotCopyable {
4033 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00004034 explicit NotCopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00004035
4036 int value() const { return value_; }
4037
4038 bool operator==(const NotCopyable& rhs) const {
4039 return value() == rhs.value();
4040 }
4041
4042 bool operator>=(const NotCopyable& rhs) const {
4043 return value() >= rhs.value();
4044 }
4045 private:
4046 int value_;
4047
4048 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
4049};
4050
4051TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
4052 const NotCopyable const_value1(1);
4053 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
4054
4055 const NotCopyable n1(1), n2(2);
4056 EXPECT_TRUE(m.Matches(n1));
4057 EXPECT_FALSE(m.Matches(n2));
4058}
4059
4060TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
4061 NotCopyable value2(2);
4062 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
4063
4064 NotCopyable n1(1), n2(2);
4065 EXPECT_FALSE(m.Matches(n1));
4066 EXPECT_TRUE(m.Matches(n2));
4067}
4068
zhanyong.wan320814a2013-03-01 00:20:30 +00004069TEST(IsEmptyTest, ImplementsIsEmpty) {
4070 vector<int> container;
4071 EXPECT_THAT(container, IsEmpty());
4072 container.push_back(0);
4073 EXPECT_THAT(container, Not(IsEmpty()));
4074 container.push_back(1);
4075 EXPECT_THAT(container, Not(IsEmpty()));
4076}
4077
4078TEST(IsEmptyTest, WorksWithString) {
4079 string text;
4080 EXPECT_THAT(text, IsEmpty());
4081 text = "foo";
4082 EXPECT_THAT(text, Not(IsEmpty()));
4083 text = string("\0", 1);
4084 EXPECT_THAT(text, Not(IsEmpty()));
4085}
4086
4087TEST(IsEmptyTest, CanDescribeSelf) {
4088 Matcher<vector<int> > m = IsEmpty();
4089 EXPECT_EQ("is empty", Describe(m));
4090 EXPECT_EQ("isn't empty", DescribeNegation(m));
4091}
4092
4093TEST(IsEmptyTest, ExplainsResult) {
4094 Matcher<vector<int> > m = IsEmpty();
4095 vector<int> container;
4096 EXPECT_EQ("", Explain(m, container));
4097 container.push_back(0);
4098 EXPECT_EQ("whose size is 1", Explain(m, container));
4099}
4100
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004101TEST(SizeIsTest, ImplementsSizeIs) {
4102 vector<int> container;
4103 EXPECT_THAT(container, SizeIs(0));
4104 EXPECT_THAT(container, Not(SizeIs(1)));
4105 container.push_back(0);
4106 EXPECT_THAT(container, Not(SizeIs(0)));
4107 EXPECT_THAT(container, SizeIs(1));
4108 container.push_back(0);
4109 EXPECT_THAT(container, Not(SizeIs(0)));
4110 EXPECT_THAT(container, SizeIs(2));
4111}
4112
4113TEST(SizeIsTest, WorksWithMap) {
4114 map<string, int> container;
4115 EXPECT_THAT(container, SizeIs(0));
4116 EXPECT_THAT(container, Not(SizeIs(1)));
4117 container.insert(make_pair("foo", 1));
4118 EXPECT_THAT(container, Not(SizeIs(0)));
4119 EXPECT_THAT(container, SizeIs(1));
4120 container.insert(make_pair("bar", 2));
4121 EXPECT_THAT(container, Not(SizeIs(0)));
4122 EXPECT_THAT(container, SizeIs(2));
4123}
4124
4125TEST(SizeIsTest, WorksWithReferences) {
4126 vector<int> container;
4127 Matcher<const vector<int>&> m = SizeIs(1);
4128 EXPECT_THAT(container, Not(m));
4129 container.push_back(0);
4130 EXPECT_THAT(container, m);
4131}
4132
4133TEST(SizeIsTest, CanDescribeSelf) {
4134 Matcher<vector<int> > m = SizeIs(2);
4135 EXPECT_EQ("size is equal to 2", Describe(m));
4136 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
4137}
4138
4139TEST(SizeIsTest, ExplainsResult) {
4140 Matcher<vector<int> > m1 = SizeIs(2);
4141 Matcher<vector<int> > m2 = SizeIs(Lt(2u));
4142 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
4143 Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
4144 vector<int> container;
4145 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
4146 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
4147 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
4148 EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
4149 Explain(m4, container));
4150 container.push_back(0);
4151 container.push_back(0);
4152 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
4153 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
4154 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
4155 EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
4156 Explain(m4, container));
4157}
4158
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004159#if GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004160// Tests ContainerEq with different container types, and
4161// different element types.
4162
4163template <typename T>
zhanyong.wanb8243162009-06-04 05:48:20 +00004164class ContainerEqTest : public testing::Test {};
zhanyong.wan6a896b52009-01-16 01:13:50 +00004165
4166typedef testing::Types<
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004167 set<int>,
4168 vector<size_t>,
4169 multiset<size_t>,
4170 list<int> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004171 ContainerEqTestTypes;
4172
4173TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
4174
4175// Tests that the filled container is equal to itself.
4176TYPED_TEST(ContainerEqTest, EqualsSelf) {
4177 static const int vals[] = {1, 1, 2, 3, 5, 8};
4178 TypeParam my_set(vals, vals + 6);
4179 const Matcher<TypeParam> m = ContainerEq(my_set);
4180 EXPECT_TRUE(m.Matches(my_set));
4181 EXPECT_EQ("", Explain(m, my_set));
4182}
4183
4184// Tests that missing values are reported.
4185TYPED_TEST(ContainerEqTest, ValueMissing) {
4186 static const int vals[] = {1, 1, 2, 3, 5, 8};
4187 static const int test_vals[] = {2, 1, 8, 5};
4188 TypeParam my_set(vals, vals + 6);
4189 TypeParam test_set(test_vals, test_vals + 4);
4190 const Matcher<TypeParam> m = ContainerEq(my_set);
4191 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004192 EXPECT_EQ("which doesn't have these expected elements: 3",
4193 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004194}
4195
4196// Tests that added values are reported.
4197TYPED_TEST(ContainerEqTest, ValueAdded) {
4198 static const int vals[] = {1, 1, 2, 3, 5, 8};
4199 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4200 TypeParam my_set(vals, vals + 6);
4201 TypeParam test_set(test_vals, test_vals + 6);
4202 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4203 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004204 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004205}
4206
4207// Tests that added and missing values are reported together.
4208TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4209 static const int vals[] = {1, 1, 2, 3, 5, 8};
4210 static const int test_vals[] = {1, 2, 3, 8, 46};
4211 TypeParam my_set(vals, vals + 6);
4212 TypeParam test_set(test_vals, test_vals + 5);
4213 const Matcher<TypeParam> m = ContainerEq(my_set);
4214 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004215 EXPECT_EQ("which has these unexpected elements: 46,\n"
4216 "and doesn't have these expected elements: 5",
4217 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004218}
4219
4220// Tests duplicated value -- expect no explanation.
4221TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4222 static const int vals[] = {1, 1, 2, 3, 5, 8};
4223 static const int test_vals[] = {1, 2, 3, 5, 8};
4224 TypeParam my_set(vals, vals + 6);
4225 TypeParam test_set(test_vals, test_vals + 5);
4226 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4227 // Depending on the container, match may be true or false
4228 // But in any case there should be no explanation.
4229 EXPECT_EQ("", Explain(m, test_set));
4230}
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004231#endif // GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004232
4233// Tests that mutliple missing values are reported.
4234// Using just vector here, so order is predicatble.
4235TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4236 static const int vals[] = {1, 1, 2, 3, 5, 8};
4237 static const int test_vals[] = {2, 1, 5};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004238 vector<int> my_set(vals, vals + 6);
4239 vector<int> test_set(test_vals, test_vals + 3);
4240 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004241 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004242 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4243 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004244}
4245
4246// Tests that added values are reported.
4247// Using just vector here, so order is predicatble.
4248TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4249 static const int vals[] = {1, 1, 2, 3, 5, 8};
4250 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004251 list<size_t> my_set(vals, vals + 6);
4252 list<size_t> test_set(test_vals, test_vals + 7);
4253 const Matcher<const list<size_t>&> m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004254 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004255 EXPECT_EQ("which has these unexpected elements: 92, 46",
4256 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004257}
4258
4259// Tests that added and missing values are reported together.
4260TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
4261 static const int vals[] = {1, 1, 2, 3, 5, 8};
4262 static const int test_vals[] = {1, 2, 3, 92, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004263 list<size_t> my_set(vals, vals + 6);
4264 list<size_t> test_set(test_vals, test_vals + 5);
4265 const Matcher<const list<size_t> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004266 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004267 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4268 "and doesn't have these expected elements: 5, 8",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004269 Explain(m, test_set));
4270}
4271
4272// Tests to see that duplicate elements are detected,
4273// but (as above) not reported in the explanation.
4274TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
4275 static const int vals[] = {1, 1, 2, 3, 5, 8};
4276 static const int test_vals[] = {1, 2, 3, 5, 8};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004277 vector<int> my_set(vals, vals + 6);
4278 vector<int> test_set(test_vals, test_vals + 5);
4279 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004280 EXPECT_TRUE(m.Matches(my_set));
4281 EXPECT_FALSE(m.Matches(test_set));
4282 // There is nothing to report when both sets contain all the same values.
4283 EXPECT_EQ("", Explain(m, test_set));
4284}
4285
4286// Tests that ContainerEq works for non-trivial associative containers,
4287// like maps.
4288TEST(ContainerEqExtraTest, WorksForMaps) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004289 map<int, std::string> my_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004290 my_map[0] = "a";
4291 my_map[1] = "b";
4292
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004293 map<int, std::string> test_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004294 test_map[0] = "aa";
4295 test_map[1] = "b";
4296
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004297 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004298 EXPECT_TRUE(m.Matches(my_map));
4299 EXPECT_FALSE(m.Matches(test_map));
4300
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004301 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
4302 "and doesn't have these expected elements: (0, \"a\")",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004303 Explain(m, test_map));
4304}
4305
zhanyong.wanb8243162009-06-04 05:48:20 +00004306TEST(ContainerEqExtraTest, WorksForNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00004307 int a1[] = {1, 2, 3};
4308 int a2[] = {1, 2, 3};
4309 int b[] = {1, 2, 4};
zhanyong.wanb8243162009-06-04 05:48:20 +00004310
4311 EXPECT_THAT(a1, ContainerEq(a2));
4312 EXPECT_THAT(a1, Not(ContainerEq(b)));
4313}
4314
4315TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00004316 const char a1[][3] = {"hi", "lo"};
4317 const char a2[][3] = {"hi", "lo"};
4318 const char b[][3] = {"lo", "hi"};
zhanyong.wanb8243162009-06-04 05:48:20 +00004319
4320 // Tests using ContainerEq() in the first dimension.
4321 EXPECT_THAT(a1, ContainerEq(a2));
4322 EXPECT_THAT(a1, Not(ContainerEq(b)));
4323
4324 // Tests using ContainerEq() in the second dimension.
4325 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
4326 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
4327}
4328
4329TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
kosak2336e9c2014-07-28 22:57:30 +00004330 const int a1[] = {1, 2, 3};
4331 const int a2[] = {1, 2, 3};
4332 const int b[] = {1, 2, 3, 4};
zhanyong.wanb8243162009-06-04 05:48:20 +00004333
zhanyong.wan2661c682009-06-09 05:42:12 +00004334 const int* const p1 = a1;
4335 EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
4336 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004337
kosak2336e9c2014-07-28 22:57:30 +00004338 const int c[] = {1, 3, 2};
zhanyong.wan2661c682009-06-09 05:42:12 +00004339 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004340}
4341
4342TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
4343 std::string a1[][3] = {
kosak2336e9c2014-07-28 22:57:30 +00004344 {"hi", "hello", "ciao"},
4345 {"bye", "see you", "ciao"}
zhanyong.wanb8243162009-06-04 05:48:20 +00004346 };
4347
4348 std::string a2[][3] = {
kosak2336e9c2014-07-28 22:57:30 +00004349 {"hi", "hello", "ciao"},
4350 {"bye", "see you", "ciao"}
zhanyong.wanb8243162009-06-04 05:48:20 +00004351 };
4352
4353 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
4354 EXPECT_THAT(a1, m);
4355
4356 a2[0][0] = "ha";
4357 EXPECT_THAT(a1, m);
4358}
4359
zhanyong.wan898725c2011-09-16 16:45:39 +00004360TEST(WhenSortedByTest, WorksForEmptyContainer) {
4361 const vector<int> numbers;
4362 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
4363 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
4364}
4365
4366TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
4367 vector<unsigned> numbers;
4368 numbers.push_back(3);
4369 numbers.push_back(1);
4370 numbers.push_back(2);
4371 numbers.push_back(2);
4372 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
4373 ElementsAre(3, 2, 2, 1)));
4374 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
4375 ElementsAre(1, 2, 2, 3))));
4376}
4377
4378TEST(WhenSortedByTest, WorksForNonVectorContainer) {
4379 list<string> words;
4380 words.push_back("say");
4381 words.push_back("hello");
4382 words.push_back("world");
4383 EXPECT_THAT(words, WhenSortedBy(less<string>(),
4384 ElementsAre("hello", "say", "world")));
4385 EXPECT_THAT(words, Not(WhenSortedBy(less<string>(),
4386 ElementsAre("say", "hello", "world"))));
4387}
4388
4389TEST(WhenSortedByTest, WorksForNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00004390 const int numbers[] = {1, 3, 2, 4};
4391 const int sorted_numbers[] = {1, 2, 3, 4};
zhanyong.wan898725c2011-09-16 16:45:39 +00004392 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
4393 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
4394 ElementsAreArray(sorted_numbers)));
4395 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
4396}
4397
4398TEST(WhenSortedByTest, CanDescribeSelf) {
4399 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
4400 EXPECT_EQ("(when sorted) has 2 elements where\n"
4401 "element #0 is equal to 1,\n"
4402 "element #1 is equal to 2",
4403 Describe(m));
4404 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
4405 "element #0 isn't equal to 1, or\n"
4406 "element #1 isn't equal to 2",
4407 DescribeNegation(m));
4408}
4409
4410TEST(WhenSortedByTest, ExplainsMatchResult) {
kosak2336e9c2014-07-28 22:57:30 +00004411 const int a[] = {2, 1};
zhanyong.wan898725c2011-09-16 16:45:39 +00004412 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
4413 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
4414 EXPECT_EQ("which is { 1, 2 } when sorted",
4415 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
4416}
4417
4418// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
4419// need to test it as exhaustively as we test the latter.
4420
4421TEST(WhenSortedTest, WorksForEmptyContainer) {
4422 const vector<int> numbers;
4423 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
4424 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
4425}
4426
4427TEST(WhenSortedTest, WorksForNonEmptyContainer) {
4428 list<string> words;
4429 words.push_back("3");
4430 words.push_back("1");
4431 words.push_back("2");
4432 words.push_back("2");
4433 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
4434 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
4435}
4436
zhanyong.wana9a59e02013-03-27 16:14:55 +00004437TEST(WhenSortedTest, WorksForMapTypes) {
4438 map<string, int> word_counts;
4439 word_counts["and"] = 1;
4440 word_counts["the"] = 1;
4441 word_counts["buffalo"] = 2;
4442 EXPECT_THAT(word_counts, WhenSorted(ElementsAre(
4443 Pair("and", 1), Pair("buffalo", 2), Pair("the", 1))));
4444 EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre(
4445 Pair("and", 1), Pair("the", 1), Pair("buffalo", 2)))));
4446}
4447
4448TEST(WhenSortedTest, WorksForMultiMapTypes) {
4449 multimap<int, int> ifib;
4450 ifib.insert(make_pair(8, 6));
4451 ifib.insert(make_pair(2, 3));
4452 ifib.insert(make_pair(1, 1));
4453 ifib.insert(make_pair(3, 4));
4454 ifib.insert(make_pair(1, 2));
4455 ifib.insert(make_pair(5, 5));
4456 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
4457 Pair(1, 2),
4458 Pair(2, 3),
4459 Pair(3, 4),
4460 Pair(5, 5),
4461 Pair(8, 6))));
4462 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
4463 Pair(2, 3),
4464 Pair(1, 1),
4465 Pair(3, 4),
4466 Pair(1, 2),
4467 Pair(5, 5)))));
4468}
4469
4470TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
4471 std::deque<int> d;
4472 d.push_back(2);
4473 d.push_back(1);
4474 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
4475 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
4476}
4477
4478TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
4479 std::deque<int> d;
4480 d.push_back(2);
4481 d.push_back(1);
4482 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
4483 EXPECT_THAT(d, WhenSorted(vector_match));
4484 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
4485 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
4486}
4487
4488// Deliberately bare pseudo-container.
4489// Offers only begin() and end() accessors, yielding InputIterator.
4490template <typename T>
4491class Streamlike {
4492 private:
4493 class ConstIter;
4494 public:
4495 typedef ConstIter const_iterator;
4496 typedef T value_type;
4497
4498 template <typename InIter>
4499 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
4500
4501 const_iterator begin() const {
4502 return const_iterator(this, remainder_.begin());
4503 }
4504 const_iterator end() const {
4505 return const_iterator(this, remainder_.end());
4506 }
4507
4508 private:
4509 class ConstIter : public std::iterator<std::input_iterator_tag,
4510 value_type,
4511 ptrdiff_t,
kosakcd99eb02014-11-17 02:18:28 +00004512 const value_type*,
4513 const value_type&> {
zhanyong.wana9a59e02013-03-27 16:14:55 +00004514 public:
4515 ConstIter(const Streamlike* s,
4516 typename std::list<value_type>::iterator pos)
4517 : s_(s), pos_(pos) {}
4518
4519 const value_type& operator*() const { return *pos_; }
4520 const value_type* operator->() const { return &*pos_; }
4521 ConstIter& operator++() {
4522 s_->remainder_.erase(pos_++);
4523 return *this;
4524 }
4525
4526 // *iter++ is required to work (see std::istreambuf_iterator).
4527 // (void)iter++ is also required to work.
4528 class PostIncrProxy {
4529 public:
4530 explicit PostIncrProxy(const value_type& value) : value_(value) {}
4531 value_type operator*() const { return value_; }
4532 private:
4533 value_type value_;
4534 };
4535 PostIncrProxy operator++(int) {
4536 PostIncrProxy proxy(**this);
4537 ++(*this);
4538 return proxy;
4539 }
4540
4541 friend bool operator==(const ConstIter& a, const ConstIter& b) {
4542 return a.s_ == b.s_ && a.pos_ == b.pos_;
4543 }
4544 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
4545 return !(a == b);
4546 }
4547
4548 private:
4549 const Streamlike* s_;
4550 typename std::list<value_type>::iterator pos_;
4551 };
4552
4553 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
4554 os << "[";
4555 typedef typename std::list<value_type>::const_iterator Iter;
4556 const char* sep = "";
4557 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
4558 os << sep << *it;
4559 sep = ",";
4560 }
4561 os << "]";
4562 return os;
4563 }
4564
4565 mutable std::list<value_type> remainder_; // modified by iteration
4566};
4567
4568TEST(StreamlikeTest, Iteration) {
kosak2336e9c2014-07-28 22:57:30 +00004569 const int a[5] = {2, 1, 4, 5, 3};
zhanyong.wana9a59e02013-03-27 16:14:55 +00004570 Streamlike<int> s(a, a + 5);
4571 Streamlike<int>::const_iterator it = s.begin();
4572 const int* ip = a;
4573 while (it != s.end()) {
4574 SCOPED_TRACE(ip - a);
4575 EXPECT_EQ(*ip++, *it++);
4576 }
4577}
4578
kosak5b9cbbb2014-11-17 00:28:55 +00004579#if GTEST_HAS_STD_FORWARD_LIST_
kosakb6a34882014-03-12 21:06:46 +00004580TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
4581 std::forward_list<int> container;
4582 EXPECT_THAT(container, BeginEndDistanceIs(0));
4583 EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
4584 container.push_front(0);
4585 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4586 EXPECT_THAT(container, BeginEndDistanceIs(1));
4587 container.push_front(0);
4588 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4589 EXPECT_THAT(container, BeginEndDistanceIs(2));
4590}
kosak5b9cbbb2014-11-17 00:28:55 +00004591#endif // GTEST_HAS_STD_FORWARD_LIST_
kosakb6a34882014-03-12 21:06:46 +00004592
4593TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
kosak2336e9c2014-07-28 22:57:30 +00004594 const int a[5] = {1, 2, 3, 4, 5};
kosakb6a34882014-03-12 21:06:46 +00004595 Streamlike<int> s(a, a + 5);
4596 EXPECT_THAT(s, BeginEndDistanceIs(5));
4597}
4598
4599TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
4600 Matcher<vector<int> > m = BeginEndDistanceIs(2);
4601 EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
4602 EXPECT_EQ("distance between begin() and end() isn't equal to 2",
4603 DescribeNegation(m));
4604}
4605
4606TEST(BeginEndDistanceIsTest, ExplainsResult) {
4607 Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
4608 Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
4609 Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
4610 Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
4611 vector<int> container;
4612 EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
4613 Explain(m1, container));
4614 EXPECT_EQ("whose distance between begin() and end() 0 matches",
4615 Explain(m2, container));
4616 EXPECT_EQ("whose distance between begin() and end() 0 matches",
4617 Explain(m3, container));
4618 EXPECT_EQ(
4619 "whose distance between begin() and end() 0 doesn't match, which is 1 "
4620 "less than 1",
4621 Explain(m4, container));
4622 container.push_back(0);
4623 container.push_back(0);
4624 EXPECT_EQ("whose distance between begin() and end() 2 matches",
4625 Explain(m1, container));
4626 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4627 Explain(m2, container));
4628 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4629 Explain(m3, container));
4630 EXPECT_EQ(
4631 "whose distance between begin() and end() 2 matches, which is 1 more "
4632 "than 1",
4633 Explain(m4, container));
4634}
4635
zhanyong.wana9a59e02013-03-27 16:14:55 +00004636TEST(WhenSortedTest, WorksForStreamlike) {
4637 // Streamlike 'container' provides only minimal iterator support.
4638 // Its iterators are tagged with input_iterator_tag.
kosak2336e9c2014-07-28 22:57:30 +00004639 const int a[5] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00004640 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004641 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
4642 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4643}
4644
4645TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
kosak2336e9c2014-07-28 22:57:30 +00004646 const int a[] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00004647 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004648 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
4649 EXPECT_THAT(s, WhenSorted(vector_match));
4650 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4651}
4652
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004653// Tests using ElementsAre() and ElementsAreArray() with stream-like
4654// "containers".
4655
4656TEST(ElemensAreStreamTest, WorksForStreamlike) {
kosak2336e9c2014-07-28 22:57:30 +00004657 const int a[5] = {1, 2, 3, 4, 5};
kosak6414d802013-12-03 23:19:36 +00004658 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004659 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
4660 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
4661}
4662
4663TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
kosak2336e9c2014-07-28 22:57:30 +00004664 const int a[5] = {1, 2, 3, 4, 5};
kosak6414d802013-12-03 23:19:36 +00004665 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004666
4667 vector<int> expected;
4668 expected.push_back(1);
4669 expected.push_back(2);
4670 expected.push_back(3);
4671 expected.push_back(4);
4672 expected.push_back(5);
4673 EXPECT_THAT(s, ElementsAreArray(expected));
4674
4675 expected[3] = 0;
4676 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
4677}
4678
billydonahue1f5fdea2014-05-19 17:54:51 +00004679TEST(ElementsAreTest, WorksWithUncopyable) {
4680 Uncopyable objs[2];
4681 objs[0].set_value(-3);
4682 objs[1].set_value(1);
4683 EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
4684}
4685
kosak06678922014-07-28 20:01:28 +00004686TEST(ElementsAreTest, TakesStlContainer) {
4687 const int actual[] = {3, 1, 2};
4688
4689 ::std::list<int> expected;
4690 expected.push_back(3);
4691 expected.push_back(1);
4692 expected.push_back(2);
4693 EXPECT_THAT(actual, ElementsAreArray(expected));
4694
4695 expected.push_back(4);
4696 EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
4697}
4698
zhanyong.wanfb25d532013-07-28 08:24:00 +00004699// Tests for UnorderedElementsAreArray()
4700
4701TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
kosak2336e9c2014-07-28 22:57:30 +00004702 const int a[] = {0, 1, 2, 3, 4};
kosak6414d802013-12-03 23:19:36 +00004703 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004704 do {
4705 StringMatchResultListener listener;
4706 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
4707 s, &listener)) << listener.str();
4708 } while (std::next_permutation(s.begin(), s.end()));
4709}
4710
4711TEST(UnorderedElementsAreArrayTest, VectorBool) {
kosak2336e9c2014-07-28 22:57:30 +00004712 const bool a[] = {0, 1, 0, 1, 1};
4713 const bool b[] = {1, 0, 1, 1, 0};
kosak6414d802013-12-03 23:19:36 +00004714 std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a));
4715 std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004716 StringMatchResultListener listener;
4717 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
4718 actual, &listener)) << listener.str();
4719}
4720
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004721TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
4722 // Streamlike 'container' provides only minimal iterator support.
4723 // Its iterators are tagged with input_iterator_tag, and it has no
4724 // size() or empty() methods.
kosak2336e9c2014-07-28 22:57:30 +00004725 const int a[5] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00004726 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004727
4728 ::std::vector<int> expected;
4729 expected.push_back(1);
4730 expected.push_back(2);
4731 expected.push_back(3);
4732 expected.push_back(4);
4733 expected.push_back(5);
4734 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
4735
4736 expected.push_back(6);
4737 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
4738}
4739
kosak06678922014-07-28 20:01:28 +00004740TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
4741 const int actual[] = {3, 1, 2};
4742
4743 ::std::list<int> expected;
4744 expected.push_back(1);
4745 expected.push_back(2);
4746 expected.push_back(3);
4747 EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
4748
4749 expected.push_back(4);
4750 EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
4751}
4752
kosak18489fa2013-12-04 23:49:07 +00004753#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004754
4755TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
kosak2336e9c2014-07-28 22:57:30 +00004756 const int a[5] = {2, 1, 4, 5, 3};
4757 EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));
4758 EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004759}
4760
4761TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
kosak2336e9c2014-07-28 22:57:30 +00004762 const string a[5] = {"a", "b", "c", "d", "e"};
4763 EXPECT_THAT(a, UnorderedElementsAreArray({"a", "b", "c", "d", "e"}));
4764 EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a", "b", "c", "d", "ef"})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004765}
4766
4767TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
kosak2336e9c2014-07-28 22:57:30 +00004768 const int a[5] = {2, 1, 4, 5, 3};
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004769 EXPECT_THAT(a, UnorderedElementsAreArray(
kosak2336e9c2014-07-28 22:57:30 +00004770 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004771 EXPECT_THAT(a, Not(UnorderedElementsAreArray(
kosak2336e9c2014-07-28 22:57:30 +00004772 {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004773}
4774
4775TEST(UnorderedElementsAreArrayTest,
4776 TakesInitializerListOfDifferentTypedMatchers) {
kosak2336e9c2014-07-28 22:57:30 +00004777 const int a[5] = {2, 1, 4, 5, 3};
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004778 // The compiler cannot infer the type of the initializer list if its
4779 // elements have different types. We must explicitly specify the
4780 // unified element type in this case.
4781 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
kosak2336e9c2014-07-28 22:57:30 +00004782 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004783 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
kosak2336e9c2014-07-28 22:57:30 +00004784 {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004785}
4786
kosak18489fa2013-12-04 23:49:07 +00004787#endif // GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004788
zhanyong.wanfb25d532013-07-28 08:24:00 +00004789class UnorderedElementsAreTest : public testing::Test {
4790 protected:
4791 typedef std::vector<int> IntVec;
4792};
4793
billydonahue1f5fdea2014-05-19 17:54:51 +00004794TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
4795 Uncopyable objs[2];
4796 objs[0].set_value(-3);
4797 objs[1].set_value(1);
4798 EXPECT_THAT(objs,
4799 UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
4800}
4801
zhanyong.wanfb25d532013-07-28 08:24:00 +00004802TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
kosak2336e9c2014-07-28 22:57:30 +00004803 const int a[] = {1, 2, 3};
kosak6414d802013-12-03 23:19:36 +00004804 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004805 do {
4806 StringMatchResultListener listener;
4807 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4808 s, &listener)) << listener.str();
4809 } while (std::next_permutation(s.begin(), s.end()));
4810}
4811
4812TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
kosak2336e9c2014-07-28 22:57:30 +00004813 const int a[] = {1, 2, 3};
kosak6414d802013-12-03 23:19:36 +00004814 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004815 std::vector<Matcher<int> > mv;
4816 mv.push_back(1);
4817 mv.push_back(2);
4818 mv.push_back(2);
4819 // The element with value '3' matches nothing: fail fast.
4820 StringMatchResultListener listener;
4821 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4822 s, &listener)) << listener.str();
4823}
4824
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004825TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
4826 // Streamlike 'container' provides only minimal iterator support.
4827 // Its iterators are tagged with input_iterator_tag, and it has no
4828 // size() or empty() methods.
kosak2336e9c2014-07-28 22:57:30 +00004829 const int a[5] = {2, 1, 4, 5, 3};
kosak6414d802013-12-03 23:19:36 +00004830 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004831
4832 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
4833 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
4834}
4835
zhanyong.wanfb25d532013-07-28 08:24:00 +00004836// One naive implementation of the matcher runs in O(N!) time, which is too
4837// slow for many real-world inputs. This test shows that our matcher can match
4838// 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
4839// iterations and obviously effectively incomputable.
4840// [ RUN ] UnorderedElementsAreTest.Performance
4841// [ OK ] UnorderedElementsAreTest.Performance (4 ms)
4842TEST_F(UnorderedElementsAreTest, Performance) {
4843 std::vector<int> s;
4844 std::vector<Matcher<int> > mv;
4845 for (int i = 0; i < 100; ++i) {
4846 s.push_back(i);
4847 mv.push_back(_);
4848 }
4849 mv[50] = Eq(0);
4850 StringMatchResultListener listener;
4851 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4852 s, &listener)) << listener.str();
4853}
4854
4855// Another variant of 'Performance' with similar expectations.
4856// [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
4857// [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
4858TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
4859 std::vector<int> s;
4860 std::vector<Matcher<int> > mv;
4861 for (int i = 0; i < 100; ++i) {
4862 s.push_back(i);
4863 if (i & 1) {
4864 mv.push_back(_);
4865 } else {
4866 mv.push_back(i);
4867 }
4868 }
4869 StringMatchResultListener listener;
4870 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4871 s, &listener)) << listener.str();
4872}
4873
4874TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
4875 std::vector<int> v;
4876 v.push_back(4);
4877 StringMatchResultListener listener;
4878 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4879 v, &listener)) << listener.str();
4880 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
4881}
4882
4883TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
4884 std::vector<int> v;
4885 StringMatchResultListener listener;
4886 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4887 v, &listener)) << listener.str();
4888 EXPECT_THAT(listener.str(), Eq(""));
4889}
4890
4891TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
4892 std::vector<int> v;
4893 v.push_back(1);
4894 v.push_back(1);
4895 StringMatchResultListener listener;
4896 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4897 v, &listener)) << listener.str();
4898 EXPECT_THAT(
4899 listener.str(),
4900 Eq("where the following matchers don't match any elements:\n"
4901 "matcher #1: is equal to 2"));
4902}
4903
4904TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
4905 std::vector<int> v;
4906 v.push_back(1);
4907 v.push_back(2);
4908 StringMatchResultListener listener;
4909 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
4910 v, &listener)) << listener.str();
4911 EXPECT_THAT(
4912 listener.str(),
4913 Eq("where the following elements don't match any matchers:\n"
4914 "element #1: 2"));
4915}
4916
4917TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
4918 std::vector<int> v;
4919 v.push_back(2);
4920 v.push_back(3);
4921 StringMatchResultListener listener;
4922 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4923 v, &listener)) << listener.str();
4924 EXPECT_THAT(
4925 listener.str(),
4926 Eq("where"
4927 " the following matchers don't match any elements:\n"
4928 "matcher #0: is equal to 1\n"
4929 "and"
4930 " where"
4931 " the following elements don't match any matchers:\n"
4932 "element #1: 3"));
4933}
4934
4935// Test helper for formatting element, matcher index pairs in expectations.
4936static string EMString(int element, int matcher) {
4937 stringstream ss;
4938 ss << "(element #" << element << ", matcher #" << matcher << ")";
4939 return ss.str();
4940}
4941
4942TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
4943 // A situation where all elements and matchers have a match
4944 // associated with them, but the max matching is not perfect.
4945 std::vector<string> v;
4946 v.push_back("a");
4947 v.push_back("b");
4948 v.push_back("c");
4949 StringMatchResultListener listener;
4950 EXPECT_FALSE(ExplainMatchResult(
4951 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
4952 << listener.str();
4953
4954 string prefix =
4955 "where no permutation of the elements can satisfy all matchers, "
4956 "and the closest match is 2 of 3 matchers with the "
4957 "pairings:\n";
4958
4959 // We have to be a bit loose here, because there are 4 valid max matches.
4960 EXPECT_THAT(
4961 listener.str(),
4962 AnyOf(prefix + "{\n " + EMString(0, 0) +
4963 ",\n " + EMString(1, 2) + "\n}",
4964 prefix + "{\n " + EMString(0, 1) +
4965 ",\n " + EMString(1, 2) + "\n}",
4966 prefix + "{\n " + EMString(0, 0) +
4967 ",\n " + EMString(2, 2) + "\n}",
4968 prefix + "{\n " + EMString(0, 1) +
4969 ",\n " + EMString(2, 2) + "\n}"));
4970}
4971
4972TEST_F(UnorderedElementsAreTest, Describe) {
4973 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
4974 Eq("is empty"));
4975 EXPECT_THAT(
4976 Describe<IntVec>(UnorderedElementsAre(345)),
4977 Eq("has 1 element and that element is equal to 345"));
4978 EXPECT_THAT(
4979 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
4980 Eq("has 3 elements and there exists some permutation "
4981 "of elements such that:\n"
4982 " - element #0 is equal to 111, and\n"
4983 " - element #1 is equal to 222, and\n"
4984 " - element #2 is equal to 333"));
4985}
4986
4987TEST_F(UnorderedElementsAreTest, DescribeNegation) {
4988 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
4989 Eq("isn't empty"));
4990 EXPECT_THAT(
4991 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
4992 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
4993 EXPECT_THAT(
4994 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
4995 Eq("doesn't have 3 elements, or there exists no permutation "
4996 "of elements such that:\n"
4997 " - element #0 is equal to 123, and\n"
4998 " - element #1 is equal to 234, and\n"
4999 " - element #2 is equal to 345"));
5000}
5001
5002namespace {
5003
5004// Used as a check on the more complex max flow method used in the
5005// real testing::internal::FindMaxBipartiteMatching. This method is
5006// compatible but runs in worst-case factorial time, so we only
5007// use it in testing for small problem sizes.
5008template <typename Graph>
5009class BacktrackingMaxBPMState {
5010 public:
5011 // Does not take ownership of 'g'.
5012 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
5013
5014 ElementMatcherPairs Compute() {
5015 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
5016 return best_so_far_;
5017 }
5018 lhs_used_.assign(graph_->LhsSize(), kUnused);
5019 rhs_used_.assign(graph_->RhsSize(), kUnused);
5020 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
5021 matches_.clear();
5022 RecurseInto(irhs);
5023 if (best_so_far_.size() == graph_->RhsSize())
5024 break;
5025 }
5026 return best_so_far_;
5027 }
5028
5029 private:
5030 static const size_t kUnused = static_cast<size_t>(-1);
5031
5032 void PushMatch(size_t lhs, size_t rhs) {
5033 matches_.push_back(ElementMatcherPair(lhs, rhs));
5034 lhs_used_[lhs] = rhs;
5035 rhs_used_[rhs] = lhs;
5036 if (matches_.size() > best_so_far_.size()) {
5037 best_so_far_ = matches_;
5038 }
5039 }
5040
5041 void PopMatch() {
5042 const ElementMatcherPair& back = matches_.back();
5043 lhs_used_[back.first] = kUnused;
5044 rhs_used_[back.second] = kUnused;
5045 matches_.pop_back();
5046 }
5047
5048 bool RecurseInto(size_t irhs) {
5049 if (rhs_used_[irhs] != kUnused) {
5050 return true;
5051 }
5052 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
5053 if (lhs_used_[ilhs] != kUnused) {
5054 continue;
5055 }
5056 if (!graph_->HasEdge(ilhs, irhs)) {
5057 continue;
5058 }
5059 PushMatch(ilhs, irhs);
5060 if (best_so_far_.size() == graph_->RhsSize()) {
5061 return false;
5062 }
5063 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
5064 if (!RecurseInto(mi)) return false;
5065 }
5066 PopMatch();
5067 }
5068 return true;
5069 }
5070
5071 const Graph* graph_; // not owned
5072 std::vector<size_t> lhs_used_;
5073 std::vector<size_t> rhs_used_;
5074 ElementMatcherPairs matches_;
5075 ElementMatcherPairs best_so_far_;
5076};
5077
5078template <typename Graph>
5079const size_t BacktrackingMaxBPMState<Graph>::kUnused;
5080
5081} // namespace
5082
5083// Implement a simple backtracking algorithm to determine if it is possible
5084// to find one element per matcher, without reusing elements.
5085template <typename Graph>
5086ElementMatcherPairs
5087FindBacktrackingMaxBPM(const Graph& g) {
5088 return BacktrackingMaxBPMState<Graph>(&g).Compute();
5089}
5090
5091class BacktrackingBPMTest : public ::testing::Test { };
5092
5093// Tests the MaxBipartiteMatching algorithm with square matrices.
5094// The single int param is the # of nodes on each of the left and right sides.
5095class BipartiteTest : public ::testing::TestWithParam<int> { };
5096
5097// Verify all match graphs up to some moderate number of edges.
5098TEST_P(BipartiteTest, Exhaustive) {
5099 int nodes = GetParam();
5100 MatchMatrix graph(nodes, nodes);
5101 do {
5102 ElementMatcherPairs matches =
5103 internal::FindMaxBipartiteMatching(graph);
5104 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
5105 << "graph: " << graph.DebugString();
5106 // Check that all elements of matches are in the graph.
5107 // Check that elements of first and second are unique.
5108 std::vector<bool> seen_element(graph.LhsSize());
5109 std::vector<bool> seen_matcher(graph.RhsSize());
5110 SCOPED_TRACE(PrintToString(matches));
5111 for (size_t i = 0; i < matches.size(); ++i) {
5112 size_t ilhs = matches[i].first;
5113 size_t irhs = matches[i].second;
5114 EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
5115 EXPECT_FALSE(seen_element[ilhs]);
5116 EXPECT_FALSE(seen_matcher[irhs]);
5117 seen_element[ilhs] = true;
5118 seen_matcher[irhs] = true;
5119 }
5120 } while (graph.NextGraph());
5121}
5122
5123INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest,
5124 ::testing::Range(0, 5));
5125
5126// Parameterized by a pair interpreted as (LhsSize, RhsSize).
5127class BipartiteNonSquareTest
5128 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
5129};
5130
5131TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
5132 // .......
5133 // 0:-----\ :
5134 // 1:---\ | :
5135 // 2:---\ | :
5136 // 3:-\ | | :
5137 // :.......:
5138 // 0 1 2
5139 MatchMatrix g(4, 3);
kosak2336e9c2014-07-28 22:57:30 +00005140 static const int kEdges[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}};
kosak6414d802013-12-03 23:19:36 +00005141 for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00005142 g.SetEdge(kEdges[i][0], kEdges[i][1], true);
5143 }
5144 EXPECT_THAT(FindBacktrackingMaxBPM(g),
5145 ElementsAre(Pair(3, 0),
5146 Pair(AnyOf(1, 2), 1),
5147 Pair(0, 2))) << g.DebugString();
5148}
5149
5150// Verify a few nonsquare matrices.
5151TEST_P(BipartiteNonSquareTest, Exhaustive) {
5152 size_t nlhs = GetParam().first;
5153 size_t nrhs = GetParam().second;
5154 MatchMatrix graph(nlhs, nrhs);
5155 do {
5156 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5157 internal::FindMaxBipartiteMatching(graph).size())
5158 << "graph: " << graph.DebugString()
5159 << "\nbacktracking: "
5160 << PrintToString(FindBacktrackingMaxBPM(graph))
5161 << "\nmax flow: "
5162 << PrintToString(internal::FindMaxBipartiteMatching(graph));
5163 } while (graph.NextGraph());
5164}
5165
5166INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest,
5167 testing::Values(
5168 std::make_pair(1, 2),
5169 std::make_pair(2, 1),
5170 std::make_pair(3, 2),
5171 std::make_pair(2, 3),
5172 std::make_pair(4, 1),
5173 std::make_pair(1, 4),
5174 std::make_pair(4, 3),
5175 std::make_pair(3, 4)));
5176
5177class BipartiteRandomTest
5178 : public ::testing::TestWithParam<std::pair<int, int> > {
5179};
5180
5181// Verifies a large sample of larger graphs.
5182TEST_P(BipartiteRandomTest, LargerNets) {
5183 int nodes = GetParam().first;
5184 int iters = GetParam().second;
5185 MatchMatrix graph(nodes, nodes);
5186
5187 testing::internal::Int32 seed = GTEST_FLAG(random_seed);
5188 if (seed == 0) {
5189 seed = static_cast<testing::internal::Int32>(time(NULL));
5190 }
5191
5192 for (; iters > 0; --iters, ++seed) {
5193 srand(static_cast<int>(seed));
5194 graph.Randomize();
5195 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5196 internal::FindMaxBipartiteMatching(graph).size())
5197 << " graph: " << graph.DebugString()
5198 << "\nTo reproduce the failure, rerun the test with the flag"
5199 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
5200 }
5201}
5202
5203// Test argument is a std::pair<int, int> representing (nodes, iters).
5204INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest,
5205 testing::Values(
5206 std::make_pair(5, 10000),
5207 std::make_pair(6, 5000),
5208 std::make_pair(7, 2000),
5209 std::make_pair(8, 500),
5210 std::make_pair(9, 100)));
5211
zhanyong.wan736baa82010-09-27 17:44:16 +00005212// Tests IsReadableTypeName().
5213
5214TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
5215 EXPECT_TRUE(IsReadableTypeName("int"));
5216 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
5217 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
5218 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
5219}
5220
5221TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
5222 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
5223 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
5224 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
5225}
5226
5227TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
5228 EXPECT_FALSE(
5229 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
5230 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
5231}
5232
5233TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
5234 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
5235}
5236
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005237// Tests JoinAsTuple().
5238
5239TEST(JoinAsTupleTest, JoinsEmptyTuple) {
5240 EXPECT_EQ("", JoinAsTuple(Strings()));
5241}
5242
5243TEST(JoinAsTupleTest, JoinsOneTuple) {
kosak2336e9c2014-07-28 22:57:30 +00005244 const char* fields[] = {"1"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005245 EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
5246}
5247
5248TEST(JoinAsTupleTest, JoinsTwoTuple) {
kosak2336e9c2014-07-28 22:57:30 +00005249 const char* fields[] = {"1", "a"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005250 EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
5251}
5252
5253TEST(JoinAsTupleTest, JoinsTenTuple) {
kosak2336e9c2014-07-28 22:57:30 +00005254 const char* fields[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005255 EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
5256 JoinAsTuple(Strings(fields, fields + 10)));
5257}
5258
5259// Tests FormatMatcherDescription().
5260
5261TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
5262 EXPECT_EQ("is even",
zhanyong.wanb4140802010-06-08 22:53:57 +00005263 FormatMatcherDescription(false, "IsEven", Strings()));
5264 EXPECT_EQ("not (is even)",
5265 FormatMatcherDescription(true, "IsEven", Strings()));
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005266
kosak2336e9c2014-07-28 22:57:30 +00005267 const char* params[] = {"5"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005268 EXPECT_EQ("equals 5",
zhanyong.wanb4140802010-06-08 22:53:57 +00005269 FormatMatcherDescription(false, "Equals",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005270 Strings(params, params + 1)));
5271
kosak2336e9c2014-07-28 22:57:30 +00005272 const char* params2[] = {"5", "8"};
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005273 EXPECT_EQ("is in range (5, 8)",
zhanyong.wanb4140802010-06-08 22:53:57 +00005274 FormatMatcherDescription(false, "IsInRange",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005275 Strings(params2, params2 + 2)));
5276}
5277
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00005278// Tests PolymorphicMatcher::mutable_impl().
5279TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
5280 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5281 DivisibleByImpl& impl = m.mutable_impl();
5282 EXPECT_EQ(42, impl.divider());
5283
5284 impl.set_divider(0);
5285 EXPECT_EQ(0, m.mutable_impl().divider());
5286}
5287
5288// Tests PolymorphicMatcher::impl().
5289TEST(PolymorphicMatcherTest, CanAccessImpl) {
5290 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5291 const DivisibleByImpl& impl = m.impl();
5292 EXPECT_EQ(42, impl.divider());
5293}
5294
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005295TEST(MatcherTupleTest, ExplainsMatchFailure) {
5296 stringstream ss1;
5297 ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
5298 make_tuple('a', 10), &ss1);
5299 EXPECT_EQ("", ss1.str()); // Successful match.
5300
5301 stringstream ss2;
5302 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5303 make_tuple(2, 'b'), &ss2);
5304 EXPECT_EQ(" Expected arg #0: is > 5\n"
5305 " Actual: 2, which is 3 less than 5\n"
zhanyong.wand60c5f42010-07-21 22:21:07 +00005306 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
5307 " Actual: 'b' (98, 0x62)\n",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005308 ss2.str()); // Failed match where both arguments need explanation.
5309
5310 stringstream ss3;
5311 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5312 make_tuple(2, 'a'), &ss3);
5313 EXPECT_EQ(" Expected arg #0: is > 5\n"
5314 " Actual: 2, which is 3 less than 5\n",
5315 ss3.str()); // Failed match where only one argument needs
5316 // explanation.
5317}
5318
zhanyong.wan33605ba2010-04-22 23:37:47 +00005319// Tests Each().
5320
5321TEST(EachTest, ExplainsMatchResultCorrectly) {
5322 set<int> a; // empty
5323
5324 Matcher<set<int> > m = Each(2);
5325 EXPECT_EQ("", Explain(m, a));
5326
zhanyong.wan736baa82010-09-27 17:44:16 +00005327 Matcher<const int(&)[1]> n = Each(1); // NOLINT
zhanyong.wan33605ba2010-04-22 23:37:47 +00005328
kosak2336e9c2014-07-28 22:57:30 +00005329 const int b[1] = {1};
zhanyong.wan33605ba2010-04-22 23:37:47 +00005330 EXPECT_EQ("", Explain(n, b));
5331
5332 n = Each(3);
5333 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
5334
5335 a.insert(1);
5336 a.insert(2);
5337 a.insert(3);
5338 m = Each(GreaterThan(0));
5339 EXPECT_EQ("", Explain(m, a));
5340
5341 m = Each(GreaterThan(10));
5342 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
5343 Explain(m, a));
5344}
5345
5346TEST(EachTest, DescribesItselfCorrectly) {
5347 Matcher<vector<int> > m = Each(1);
5348 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
5349
5350 Matcher<vector<int> > m2 = Not(m);
5351 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
5352}
5353
5354TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
5355 vector<int> some_vector;
5356 EXPECT_THAT(some_vector, Each(1));
5357 some_vector.push_back(3);
5358 EXPECT_THAT(some_vector, Not(Each(1)));
5359 EXPECT_THAT(some_vector, Each(3));
5360 some_vector.push_back(1);
5361 some_vector.push_back(2);
5362 EXPECT_THAT(some_vector, Not(Each(3)));
5363 EXPECT_THAT(some_vector, Each(Lt(3.5)));
5364
5365 vector<string> another_vector;
5366 another_vector.push_back("fee");
5367 EXPECT_THAT(another_vector, Each(string("fee")));
5368 another_vector.push_back("fie");
5369 another_vector.push_back("foe");
5370 another_vector.push_back("fum");
5371 EXPECT_THAT(another_vector, Not(Each(string("fee"))));
5372}
5373
5374TEST(EachTest, MatchesMapWhenAllElementsMatch) {
5375 map<const char*, int> my_map;
5376 const char* bar = "a string";
5377 my_map[bar] = 2;
5378 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
5379
5380 map<string, int> another_map;
5381 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5382 another_map["fee"] = 1;
5383 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5384 another_map["fie"] = 2;
5385 another_map["foe"] = 3;
5386 another_map["fum"] = 4;
5387 EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1))));
5388 EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1))));
5389 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
5390}
5391
5392TEST(EachTest, AcceptsMatcher) {
kosak2336e9c2014-07-28 22:57:30 +00005393 const int a[] = {1, 2, 3};
zhanyong.wan33605ba2010-04-22 23:37:47 +00005394 EXPECT_THAT(a, Each(Gt(0)));
5395 EXPECT_THAT(a, Not(Each(Gt(1))));
5396}
5397
5398TEST(EachTest, WorksForNativeArrayAsTuple) {
kosak2336e9c2014-07-28 22:57:30 +00005399 const int a[] = {1, 2};
zhanyong.wan33605ba2010-04-22 23:37:47 +00005400 const int* const pointer = a;
5401 EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
5402 EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
5403}
5404
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005405// For testing Pointwise().
5406class IsHalfOfMatcher {
5407 public:
5408 template <typename T1, typename T2>
5409 bool MatchAndExplain(const tuple<T1, T2>& a_pair,
5410 MatchResultListener* listener) const {
5411 if (get<0>(a_pair) == get<1>(a_pair)/2) {
5412 *listener << "where the second is " << get<1>(a_pair);
5413 return true;
5414 } else {
5415 *listener << "where the second/2 is " << get<1>(a_pair)/2;
5416 return false;
5417 }
5418 }
5419
5420 void DescribeTo(ostream* os) const {
5421 *os << "are a pair where the first is half of the second";
5422 }
5423
5424 void DescribeNegationTo(ostream* os) const {
5425 *os << "are a pair where the first isn't half of the second";
5426 }
5427};
5428
5429PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
5430 return MakePolymorphicMatcher(IsHalfOfMatcher());
5431}
5432
5433TEST(PointwiseTest, DescribesSelf) {
5434 vector<int> rhs;
5435 rhs.push_back(1);
5436 rhs.push_back(2);
5437 rhs.push_back(3);
5438 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
5439 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
5440 "in { 1, 2, 3 } are a pair where the first is half of the second",
5441 Describe(m));
5442 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
5443 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
5444 "where the first isn't half of the second",
5445 DescribeNegation(m));
5446}
5447
5448TEST(PointwiseTest, MakesCopyOfRhs) {
5449 list<signed char> rhs;
5450 rhs.push_back(2);
5451 rhs.push_back(4);
5452
kosak2336e9c2014-07-28 22:57:30 +00005453 int lhs[] = {1, 2};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005454 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
5455 EXPECT_THAT(lhs, m);
5456
5457 // Changing rhs now shouldn't affect m, which made a copy of rhs.
5458 rhs.push_back(6);
5459 EXPECT_THAT(lhs, m);
5460}
5461
5462TEST(PointwiseTest, WorksForLhsNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00005463 const int lhs[] = {1, 2, 3};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005464 vector<int> rhs;
5465 rhs.push_back(2);
5466 rhs.push_back(4);
5467 rhs.push_back(6);
5468 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
5469 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5470}
5471
5472TEST(PointwiseTest, WorksForRhsNativeArray) {
kosak2336e9c2014-07-28 22:57:30 +00005473 const int rhs[] = {1, 2, 3};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005474 vector<int> lhs;
5475 lhs.push_back(2);
5476 lhs.push_back(4);
5477 lhs.push_back(6);
5478 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
5479 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
5480}
5481
kosak2336e9c2014-07-28 22:57:30 +00005482#if GTEST_HAS_STD_INITIALIZER_LIST_
5483
5484TEST(PointwiseTest, WorksForRhsInitializerList) {
5485 const vector<int> lhs{2, 4, 6};
5486 EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));
5487 EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));
5488}
5489
5490#endif // GTEST_HAS_STD_INITIALIZER_LIST_
5491
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005492TEST(PointwiseTest, RejectsWrongSize) {
kosak2336e9c2014-07-28 22:57:30 +00005493 const double lhs[2] = {1, 2};
5494 const int rhs[1] = {0};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005495 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5496 EXPECT_EQ("which contains 2 values",
5497 Explain(Pointwise(Gt(), rhs), lhs));
5498
kosak2336e9c2014-07-28 22:57:30 +00005499 const int rhs2[3] = {0, 1, 2};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005500 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
5501}
5502
5503TEST(PointwiseTest, RejectsWrongContent) {
kosak2336e9c2014-07-28 22:57:30 +00005504 const double lhs[3] = {1, 2, 3};
5505 const int rhs[3] = {2, 6, 4};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005506 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
5507 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
5508 "where the second/2 is 3",
5509 Explain(Pointwise(IsHalfOf(), rhs), lhs));
5510}
5511
5512TEST(PointwiseTest, AcceptsCorrectContent) {
kosak2336e9c2014-07-28 22:57:30 +00005513 const double lhs[3] = {1, 2, 3};
5514 const int rhs[3] = {2, 4, 6};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005515 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
5516 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
5517}
5518
5519TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
kosak2336e9c2014-07-28 22:57:30 +00005520 const double lhs[3] = {1, 2, 3};
5521 const int rhs[3] = {2, 4, 6};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005522 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5523 EXPECT_THAT(lhs, Pointwise(m1, rhs));
5524 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
5525
5526 // This type works as a tuple<const double&, const int&> can be
5527 // implicitly cast to tuple<double, int>.
5528 const Matcher<tuple<double, int> > m2 = IsHalfOf();
5529 EXPECT_THAT(lhs, Pointwise(m2, rhs));
5530 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
5531}
5532
kosak2336e9c2014-07-28 22:57:30 +00005533TEST(UnorderedPointwiseTest, DescribesSelf) {
5534 vector<int> rhs;
5535 rhs.push_back(1);
5536 rhs.push_back(2);
5537 rhs.push_back(3);
5538 const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);
5539 EXPECT_EQ(
5540 "has 3 elements and there exists some permutation of elements such "
5541 "that:\n"
5542 " - element #0 and 1 are a pair where the first is half of the second, "
5543 "and\n"
5544 " - element #1 and 2 are a pair where the first is half of the second, "
5545 "and\n"
5546 " - element #2 and 3 are a pair where the first is half of the second",
5547 Describe(m));
5548 EXPECT_EQ(
5549 "doesn't have 3 elements, or there exists no permutation of elements "
5550 "such that:\n"
5551 " - element #0 and 1 are a pair where the first is half of the second, "
5552 "and\n"
5553 " - element #1 and 2 are a pair where the first is half of the second, "
5554 "and\n"
5555 " - element #2 and 3 are a pair where the first is half of the second",
5556 DescribeNegation(m));
5557}
5558
5559TEST(UnorderedPointwiseTest, MakesCopyOfRhs) {
5560 list<signed char> rhs;
5561 rhs.push_back(2);
5562 rhs.push_back(4);
5563
5564 int lhs[] = {2, 1};
5565 const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);
5566 EXPECT_THAT(lhs, m);
5567
5568 // Changing rhs now shouldn't affect m, which made a copy of rhs.
5569 rhs.push_back(6);
5570 EXPECT_THAT(lhs, m);
5571}
5572
5573TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {
5574 const int lhs[] = {1, 2, 3};
5575 vector<int> rhs;
5576 rhs.push_back(4);
5577 rhs.push_back(6);
5578 rhs.push_back(2);
5579 EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));
5580 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
5581}
5582
5583TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {
5584 const int rhs[] = {1, 2, 3};
5585 vector<int> lhs;
5586 lhs.push_back(4);
5587 lhs.push_back(2);
5588 lhs.push_back(6);
5589 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));
5590 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));
5591}
5592
5593#if GTEST_HAS_STD_INITIALIZER_LIST_
5594
5595TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {
5596 const vector<int> lhs{2, 4, 6};
5597 EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));
5598 EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));
5599}
5600
5601#endif // GTEST_HAS_STD_INITIALIZER_LIST_
5602
5603TEST(UnorderedPointwiseTest, RejectsWrongSize) {
5604 const double lhs[2] = {1, 2};
5605 const int rhs[1] = {0};
5606 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));
5607 EXPECT_EQ("which has 2 elements",
5608 Explain(UnorderedPointwise(Gt(), rhs), lhs));
5609
5610 const int rhs2[3] = {0, 1, 2};
5611 EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));
5612}
5613
5614TEST(UnorderedPointwiseTest, RejectsWrongContent) {
5615 const double lhs[3] = {1, 2, 3};
5616 const int rhs[3] = {2, 6, 6};
5617 EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));
5618 EXPECT_EQ("where the following elements don't match any matchers:\n"
5619 "element #1: 2",
5620 Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));
5621}
5622
5623TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {
5624 const double lhs[3] = {1, 2, 3};
5625 const int rhs[3] = {2, 4, 6};
5626 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
5627}
5628
5629TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {
5630 const double lhs[3] = {1, 2, 3};
5631 const int rhs[3] = {6, 4, 2};
5632 EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));
5633}
5634
5635TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {
5636 const double lhs[3] = {1, 2, 3};
5637 const int rhs[3] = {4, 6, 2};
5638 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5639 EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));
5640
5641 // This type works as a tuple<const double&, const int&> can be
5642 // implicitly cast to tuple<double, int>.
5643 const Matcher<tuple<double, int> > m2 = IsHalfOf();
5644 EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));
5645}
5646
shiqiane35fdd92008-12-10 05:08:54 +00005647} // namespace gmock_matchers_test
5648} // namespace testing