blob: bd20add2f4e589e12e87b4bbcfa85898cf3bc372 [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
kosakb6a34882014-03-12 21:06:46 +000057#if GTEST_LANG_CXX11
58# 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.wanab5b77c2010-05-17 19:32:48 +000080using std::tr1::get;
zhanyong.wanb8243162009-06-04 05:48:20 +000081using std::tr1::make_tuple;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000082using std::tr1::tuple;
zhanyong.wan33605ba2010-04-22 23:37:47 +000083using std::vector;
shiqiane35fdd92008-12-10 05:08:54 +000084using testing::A;
zhanyong.wanbf550852009-06-09 06:09:53 +000085using testing::AllArgs;
shiqiane35fdd92008-12-10 05:08:54 +000086using testing::AllOf;
87using testing::An;
88using testing::AnyOf;
89using testing::ByRef;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000090using testing::ContainsRegex;
shiqiane35fdd92008-12-10 05:08:54 +000091using testing::DoubleEq;
zhanyong.wan616180e2013-06-18 18:49:51 +000092using testing::DoubleNear;
shiqiane35fdd92008-12-10 05:08:54 +000093using testing::EndsWith;
94using testing::Eq;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000095using testing::ExplainMatchResult;
shiqiane35fdd92008-12-10 05:08:54 +000096using testing::Field;
97using testing::FloatEq;
zhanyong.wan616180e2013-06-18 18:49:51 +000098using testing::FloatNear;
shiqiane35fdd92008-12-10 05:08:54 +000099using testing::Ge;
100using testing::Gt;
101using testing::HasSubstr;
zhanyong.wan320814a2013-03-01 00:20:30 +0000102using testing::IsEmpty;
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000103using testing::IsNull;
zhanyong.wanb5937da2009-07-16 20:26:41 +0000104using testing::Key;
shiqiane35fdd92008-12-10 05:08:54 +0000105using testing::Le;
106using testing::Lt;
107using testing::MakeMatcher;
108using testing::MakePolymorphicMatcher;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000109using testing::MatchResultListener;
shiqiane35fdd92008-12-10 05:08:54 +0000110using testing::Matcher;
111using testing::MatcherCast;
112using testing::MatcherInterface;
113using testing::Matches;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000114using testing::MatchesRegex;
shiqiane35fdd92008-12-10 05:08:54 +0000115using testing::NanSensitiveDoubleEq;
zhanyong.wan616180e2013-06-18 18:49:51 +0000116using testing::NanSensitiveDoubleNear;
shiqiane35fdd92008-12-10 05:08:54 +0000117using testing::NanSensitiveFloatEq;
zhanyong.wan616180e2013-06-18 18:49:51 +0000118using testing::NanSensitiveFloatNear;
shiqiane35fdd92008-12-10 05:08:54 +0000119using testing::Ne;
120using testing::Not;
121using testing::NotNull;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000122using testing::Pair;
shiqiane35fdd92008-12-10 05:08:54 +0000123using testing::Pointee;
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000124using testing::Pointwise;
shiqiane35fdd92008-12-10 05:08:54 +0000125using testing::PolymorphicMatcher;
126using testing::Property;
127using testing::Ref;
128using testing::ResultOf;
zhanyong.wana31d9ce2013-03-01 01:50:17 +0000129using testing::SizeIs;
shiqiane35fdd92008-12-10 05:08:54 +0000130using testing::StartsWith;
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000131using testing::StringMatchResultListener;
shiqiane35fdd92008-12-10 05:08:54 +0000132using testing::StrCaseEq;
133using testing::StrCaseNe;
134using testing::StrEq;
135using testing::StrNe;
136using testing::Truly;
137using testing::TypedEq;
zhanyong.wanb8243162009-06-04 05:48:20 +0000138using testing::Value;
zhanyong.wan898725c2011-09-16 16:45:39 +0000139using testing::WhenSorted;
140using testing::WhenSortedBy;
shiqiane35fdd92008-12-10 05:08:54 +0000141using testing::_;
zhanyong.wana862f1d2010-03-15 21:23:04 +0000142using testing::internal::DummyMatchResultListener;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000143using testing::internal::ElementMatcherPair;
144using testing::internal::ElementMatcherPairs;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000145using testing::internal::ExplainMatchFailureTupleTo;
shiqiane35fdd92008-12-10 05:08:54 +0000146using testing::internal::FloatingEqMatcher;
zhanyong.wanb4140802010-06-08 22:53:57 +0000147using testing::internal::FormatMatcherDescription;
zhanyong.wan736baa82010-09-27 17:44:16 +0000148using testing::internal::IsReadableTypeName;
zhanyong.wan4a5330d2009-02-19 00:36:44 +0000149using testing::internal::JoinAsTuple;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000150using testing::internal::MatchMatrix;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000151using testing::internal::RE;
zhanyong.wana862f1d2010-03-15 21:23:04 +0000152using testing::internal::StreamMatchResultListener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000153using testing::internal::Strings;
vladlosev79b83502009-11-18 00:43:37 +0000154using testing::internal::linked_ptr;
vladloseve56daa72009-11-18 01:08:08 +0000155using testing::internal::scoped_ptr;
shiqiane35fdd92008-12-10 05:08:54 +0000156using testing::internal::string;
157
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000158// For testing ExplainMatchResultTo().
159class GreaterThanMatcher : public MatcherInterface<int> {
160 public:
161 explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
162
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000163 virtual void DescribeTo(ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000164 *os << "is > " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000165 }
166
zhanyong.wandb22c222010-01-28 21:52:29 +0000167 virtual bool MatchAndExplain(int lhs,
168 MatchResultListener* listener) const {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000169 const int diff = lhs - rhs_;
170 if (diff > 0) {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000171 *listener << "which is " << diff << " more than " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000172 } else if (diff == 0) {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000173 *listener << "which is the same as " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000174 } else {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000175 *listener << "which is " << -diff << " less than " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000176 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000177
178 return lhs > rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000179 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000180
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000181 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000182 int rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000183};
184
185Matcher<int> GreaterThan(int n) {
186 return MakeMatcher(new GreaterThanMatcher(n));
187}
188
zhanyong.wan736baa82010-09-27 17:44:16 +0000189string OfType(const string& type_name) {
190#if GTEST_HAS_RTTI
191 return " (of type " + type_name + ")";
192#else
193 return "";
194#endif
195}
196
shiqiane35fdd92008-12-10 05:08:54 +0000197// Returns the description of the given matcher.
198template <typename T>
199string Describe(const Matcher<T>& m) {
200 stringstream ss;
201 m.DescribeTo(&ss);
202 return ss.str();
203}
204
205// Returns the description of the negation of the given matcher.
206template <typename T>
207string DescribeNegation(const Matcher<T>& m) {
208 stringstream ss;
209 m.DescribeNegationTo(&ss);
210 return ss.str();
211}
212
213// Returns the reason why x matches, or doesn't match, m.
214template <typename MatcherType, typename Value>
215string Explain(const MatcherType& m, const Value& x) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000216 StringMatchResultListener listener;
217 ExplainMatchResult(m, x, &listener);
218 return listener.str();
shiqiane35fdd92008-12-10 05:08:54 +0000219}
220
zhanyong.wana862f1d2010-03-15 21:23:04 +0000221TEST(MatchResultListenerTest, StreamingWorks) {
222 StringMatchResultListener listener;
223 listener << "hi" << 5;
224 EXPECT_EQ("hi5", listener.str());
225
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000226 listener.Clear();
227 EXPECT_EQ("", listener.str());
228
229 listener << 42;
230 EXPECT_EQ("42", listener.str());
231
zhanyong.wana862f1d2010-03-15 21:23:04 +0000232 // Streaming shouldn't crash when the underlying ostream is NULL.
233 DummyMatchResultListener dummy;
234 dummy << "hi" << 5;
235}
236
237TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
238 EXPECT_TRUE(DummyMatchResultListener().stream() == NULL);
239 EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL);
240
241 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
242}
243
244TEST(MatchResultListenerTest, IsInterestedWorks) {
245 EXPECT_TRUE(StringMatchResultListener().IsInterested());
246 EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
247
248 EXPECT_FALSE(DummyMatchResultListener().IsInterested());
249 EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested());
250}
251
shiqiane35fdd92008-12-10 05:08:54 +0000252// Makes sure that the MatcherInterface<T> interface doesn't
253// change.
254class EvenMatcherImpl : public MatcherInterface<int> {
255 public:
zhanyong.wandb22c222010-01-28 21:52:29 +0000256 virtual bool MatchAndExplain(int x,
257 MatchResultListener* /* listener */) const {
258 return x % 2 == 0;
259 }
shiqiane35fdd92008-12-10 05:08:54 +0000260
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000261 virtual void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +0000262 *os << "is an even number";
263 }
264
265 // We deliberately don't define DescribeNegationTo() and
266 // ExplainMatchResultTo() here, to make sure the definition of these
267 // two methods is optional.
268};
269
zhanyong.wana862f1d2010-03-15 21:23:04 +0000270// Makes sure that the MatcherInterface API doesn't change.
271TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
shiqiane35fdd92008-12-10 05:08:54 +0000272 EvenMatcherImpl m;
273}
274
zhanyong.wan82113312010-01-08 21:55:40 +0000275// Tests implementing a monomorphic matcher using MatchAndExplain().
276
277class NewEvenMatcherImpl : public MatcherInterface<int> {
278 public:
279 virtual bool MatchAndExplain(int x, MatchResultListener* listener) const {
280 const bool match = x % 2 == 0;
281 // Verifies that we can stream to a listener directly.
282 *listener << "value % " << 2;
283 if (listener->stream() != NULL) {
284 // Verifies that we can stream to a listener's underlying stream
285 // too.
286 *listener->stream() << " == " << (x % 2);
287 }
288 return match;
289 }
290
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000291 virtual void DescribeTo(ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000292 *os << "is an even number";
293 }
294};
295
296TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
297 Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
298 EXPECT_TRUE(m.Matches(2));
299 EXPECT_FALSE(m.Matches(3));
300 EXPECT_EQ("value % 2 == 0", Explain(m, 2));
301 EXPECT_EQ("value % 2 == 1", Explain(m, 3));
302}
303
shiqiane35fdd92008-12-10 05:08:54 +0000304// Tests default-constructing a matcher.
305TEST(MatcherTest, CanBeDefaultConstructed) {
306 Matcher<double> m;
307}
308
309// Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
310TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
311 const MatcherInterface<int>* impl = new EvenMatcherImpl;
312 Matcher<int> m(impl);
313 EXPECT_TRUE(m.Matches(4));
314 EXPECT_FALSE(m.Matches(5));
315}
316
317// Tests that value can be used in place of Eq(value).
318TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
319 Matcher<int> m1 = 5;
320 EXPECT_TRUE(m1.Matches(5));
321 EXPECT_FALSE(m1.Matches(6));
322}
323
324// Tests that NULL can be used in place of Eq(NULL).
325TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
326 Matcher<int*> m1 = NULL;
327 EXPECT_TRUE(m1.Matches(NULL));
328 int n = 0;
329 EXPECT_FALSE(m1.Matches(&n));
330}
331
332// Tests that matchers are copyable.
333TEST(MatcherTest, IsCopyable) {
334 // Tests the copy constructor.
335 Matcher<bool> m1 = Eq(false);
336 EXPECT_TRUE(m1.Matches(false));
337 EXPECT_FALSE(m1.Matches(true));
338
339 // Tests the assignment operator.
340 m1 = Eq(true);
341 EXPECT_TRUE(m1.Matches(true));
342 EXPECT_FALSE(m1.Matches(false));
343}
344
345// Tests that Matcher<T>::DescribeTo() calls
346// MatcherInterface<T>::DescribeTo().
347TEST(MatcherTest, CanDescribeItself) {
348 EXPECT_EQ("is an even number",
349 Describe(Matcher<int>(new EvenMatcherImpl)));
350}
351
zhanyong.wan82113312010-01-08 21:55:40 +0000352// Tests Matcher<T>::MatchAndExplain().
353TEST(MatcherTest, MatchAndExplain) {
354 Matcher<int> m = GreaterThan(0);
zhanyong.wan34b034c2010-03-05 21:23:23 +0000355 StringMatchResultListener listener1;
zhanyong.wan82113312010-01-08 21:55:40 +0000356 EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000357 EXPECT_EQ("which is 42 more than 0", listener1.str());
zhanyong.wan82113312010-01-08 21:55:40 +0000358
zhanyong.wan34b034c2010-03-05 21:23:23 +0000359 StringMatchResultListener listener2;
zhanyong.wan82113312010-01-08 21:55:40 +0000360 EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000361 EXPECT_EQ("which is 9 less than 0", listener2.str());
zhanyong.wan82113312010-01-08 21:55:40 +0000362}
363
shiqiane35fdd92008-12-10 05:08:54 +0000364// Tests that a C-string literal can be implicitly converted to a
365// Matcher<string> or Matcher<const string&>.
366TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
367 Matcher<string> m1 = "hi";
368 EXPECT_TRUE(m1.Matches("hi"));
369 EXPECT_FALSE(m1.Matches("hello"));
370
371 Matcher<const string&> m2 = "hi";
372 EXPECT_TRUE(m2.Matches("hi"));
373 EXPECT_FALSE(m2.Matches("hello"));
374}
375
376// Tests that a string object can be implicitly converted to a
377// Matcher<string> or Matcher<const string&>.
378TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
379 Matcher<string> m1 = string("hi");
380 EXPECT_TRUE(m1.Matches("hi"));
381 EXPECT_FALSE(m1.Matches("hello"));
382
383 Matcher<const string&> m2 = string("hi");
384 EXPECT_TRUE(m2.Matches("hi"));
385 EXPECT_FALSE(m2.Matches("hello"));
386}
387
zhanyong.wan1f122a02013-03-25 16:27:03 +0000388#if GTEST_HAS_STRING_PIECE_
389// Tests that a C-string literal can be implicitly converted to a
390// Matcher<StringPiece> or Matcher<const StringPiece&>.
391TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
392 Matcher<StringPiece> m1 = "cats";
393 EXPECT_TRUE(m1.Matches("cats"));
394 EXPECT_FALSE(m1.Matches("dogs"));
395
396 Matcher<const StringPiece&> m2 = "cats";
397 EXPECT_TRUE(m2.Matches("cats"));
398 EXPECT_FALSE(m2.Matches("dogs"));
399}
400
401// Tests that a string object can be implicitly converted to a
402// Matcher<StringPiece> or Matcher<const StringPiece&>.
403TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromString) {
404 Matcher<StringPiece> m1 = string("cats");
405 EXPECT_TRUE(m1.Matches("cats"));
406 EXPECT_FALSE(m1.Matches("dogs"));
407
408 Matcher<const StringPiece&> m2 = string("cats");
409 EXPECT_TRUE(m2.Matches("cats"));
410 EXPECT_FALSE(m2.Matches("dogs"));
411}
412
413// Tests that a StringPiece object can be implicitly converted to a
414// Matcher<StringPiece> or Matcher<const StringPiece&>.
415TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromStringPiece) {
416 Matcher<StringPiece> m1 = StringPiece("cats");
417 EXPECT_TRUE(m1.Matches("cats"));
418 EXPECT_FALSE(m1.Matches("dogs"));
419
420 Matcher<const StringPiece&> m2 = StringPiece("cats");
421 EXPECT_TRUE(m2.Matches("cats"));
422 EXPECT_FALSE(m2.Matches("dogs"));
423}
424#endif // GTEST_HAS_STRING_PIECE_
425
shiqiane35fdd92008-12-10 05:08:54 +0000426// Tests that MakeMatcher() constructs a Matcher<T> from a
427// MatcherInterface* without requiring the user to explicitly
428// write the type.
429TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
430 const MatcherInterface<int>* dummy_impl = NULL;
431 Matcher<int> m = MakeMatcher(dummy_impl);
432}
433
zhanyong.wan82113312010-01-08 21:55:40 +0000434// Tests that MakePolymorphicMatcher() can construct a polymorphic
435// matcher from its implementation using the old API.
zhanyong.wan33605ba2010-04-22 23:37:47 +0000436const int g_bar = 1;
shiqiane35fdd92008-12-10 05:08:54 +0000437class ReferencesBarOrIsZeroImpl {
438 public:
439 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +0000440 bool MatchAndExplain(const T& x,
441 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000442 const void* p = &x;
zhanyong.wan33605ba2010-04-22 23:37:47 +0000443 return p == &g_bar || x == 0;
shiqiane35fdd92008-12-10 05:08:54 +0000444 }
445
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000446 void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
shiqiane35fdd92008-12-10 05:08:54 +0000447
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000448 void DescribeNegationTo(ostream* os) const {
zhanyong.wan33605ba2010-04-22 23:37:47 +0000449 *os << "doesn't reference g_bar and is not zero";
shiqiane35fdd92008-12-10 05:08:54 +0000450 }
451};
452
453// This function verifies that MakePolymorphicMatcher() returns a
454// PolymorphicMatcher<T> where T is the argument's type.
455PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
456 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
457}
458
zhanyong.wan82113312010-01-08 21:55:40 +0000459TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
shiqiane35fdd92008-12-10 05:08:54 +0000460 // Using a polymorphic matcher to match a reference type.
461 Matcher<const int&> m1 = ReferencesBarOrIsZero();
462 EXPECT_TRUE(m1.Matches(0));
463 // Verifies that the identity of a by-reference argument is preserved.
zhanyong.wan33605ba2010-04-22 23:37:47 +0000464 EXPECT_TRUE(m1.Matches(g_bar));
shiqiane35fdd92008-12-10 05:08:54 +0000465 EXPECT_FALSE(m1.Matches(1));
zhanyong.wan33605ba2010-04-22 23:37:47 +0000466 EXPECT_EQ("g_bar or zero", Describe(m1));
shiqiane35fdd92008-12-10 05:08:54 +0000467
468 // Using a polymorphic matcher to match a value type.
469 Matcher<double> m2 = ReferencesBarOrIsZero();
470 EXPECT_TRUE(m2.Matches(0.0));
471 EXPECT_FALSE(m2.Matches(0.1));
zhanyong.wan33605ba2010-04-22 23:37:47 +0000472 EXPECT_EQ("g_bar or zero", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +0000473}
474
zhanyong.wan82113312010-01-08 21:55:40 +0000475// Tests implementing a polymorphic matcher using MatchAndExplain().
476
477class PolymorphicIsEvenImpl {
478 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000479 void DescribeTo(ostream* os) const { *os << "is even"; }
zhanyong.wan82113312010-01-08 21:55:40 +0000480
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000481 void DescribeNegationTo(ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000482 *os << "is odd";
483 }
zhanyong.wan82113312010-01-08 21:55:40 +0000484
zhanyong.wandb22c222010-01-28 21:52:29 +0000485 template <typename T>
486 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
487 // Verifies that we can stream to the listener directly.
488 *listener << "% " << 2;
489 if (listener->stream() != NULL) {
490 // Verifies that we can stream to the listener's underlying stream
491 // too.
492 *listener->stream() << " == " << (x % 2);
493 }
494 return (x % 2) == 0;
zhanyong.wan82113312010-01-08 21:55:40 +0000495 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000496};
zhanyong.wan82113312010-01-08 21:55:40 +0000497
498PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
499 return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
500}
501
502TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
503 // Using PolymorphicIsEven() as a Matcher<int>.
504 const Matcher<int> m1 = PolymorphicIsEven();
505 EXPECT_TRUE(m1.Matches(42));
506 EXPECT_FALSE(m1.Matches(43));
507 EXPECT_EQ("is even", Describe(m1));
508
509 const Matcher<int> not_m1 = Not(m1);
510 EXPECT_EQ("is odd", Describe(not_m1));
511
512 EXPECT_EQ("% 2 == 0", Explain(m1, 42));
513
514 // Using PolymorphicIsEven() as a Matcher<char>.
515 const Matcher<char> m2 = PolymorphicIsEven();
516 EXPECT_TRUE(m2.Matches('\x42'));
517 EXPECT_FALSE(m2.Matches('\x43'));
518 EXPECT_EQ("is even", Describe(m2));
519
520 const Matcher<char> not_m2 = Not(m2);
521 EXPECT_EQ("is odd", Describe(not_m2));
522
523 EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
524}
525
shiqiane35fdd92008-12-10 05:08:54 +0000526// Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
527TEST(MatcherCastTest, FromPolymorphicMatcher) {
528 Matcher<int> m = MatcherCast<int>(Eq(5));
529 EXPECT_TRUE(m.Matches(5));
530 EXPECT_FALSE(m.Matches(6));
531}
532
533// For testing casting matchers between compatible types.
534class IntValue {
535 public:
536 // An int can be statically (although not implicitly) cast to a
537 // IntValue.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000538 explicit IntValue(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +0000539
540 int value() const { return value_; }
541 private:
542 int value_;
543};
544
545// For testing casting matchers between compatible types.
546bool IsPositiveIntValue(const IntValue& foo) {
547 return foo.value() > 0;
548}
549
550// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
551// can be statically converted to U.
552TEST(MatcherCastTest, FromCompatibleType) {
553 Matcher<double> m1 = Eq(2.0);
554 Matcher<int> m2 = MatcherCast<int>(m1);
555 EXPECT_TRUE(m2.Matches(2));
556 EXPECT_FALSE(m2.Matches(3));
557
558 Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
559 Matcher<int> m4 = MatcherCast<int>(m3);
560 // In the following, the arguments 1 and 0 are statically converted
561 // to IntValue objects, and then tested by the IsPositiveIntValue()
562 // predicate.
563 EXPECT_TRUE(m4.Matches(1));
564 EXPECT_FALSE(m4.Matches(0));
565}
566
567// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
568TEST(MatcherCastTest, FromConstReferenceToNonReference) {
569 Matcher<const int&> m1 = Eq(0);
570 Matcher<int> m2 = MatcherCast<int>(m1);
571 EXPECT_TRUE(m2.Matches(0));
572 EXPECT_FALSE(m2.Matches(1));
573}
574
575// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
576TEST(MatcherCastTest, FromReferenceToNonReference) {
577 Matcher<int&> m1 = Eq(0);
578 Matcher<int> m2 = MatcherCast<int>(m1);
579 EXPECT_TRUE(m2.Matches(0));
580 EXPECT_FALSE(m2.Matches(1));
581}
582
583// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
584TEST(MatcherCastTest, FromNonReferenceToConstReference) {
585 Matcher<int> m1 = Eq(0);
586 Matcher<const int&> m2 = MatcherCast<const int&>(m1);
587 EXPECT_TRUE(m2.Matches(0));
588 EXPECT_FALSE(m2.Matches(1));
589}
590
591// Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
592TEST(MatcherCastTest, FromNonReferenceToReference) {
593 Matcher<int> m1 = Eq(0);
594 Matcher<int&> m2 = MatcherCast<int&>(m1);
595 int n = 0;
596 EXPECT_TRUE(m2.Matches(n));
597 n = 1;
598 EXPECT_FALSE(m2.Matches(n));
599}
600
601// Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
602TEST(MatcherCastTest, FromSameType) {
603 Matcher<int> m1 = Eq(0);
604 Matcher<int> m2 = MatcherCast<int>(m1);
605 EXPECT_TRUE(m2.Matches(0));
606 EXPECT_FALSE(m2.Matches(1));
607}
608
jgm79a367e2012-04-10 16:02:11 +0000609// Implicitly convertible form any type.
610struct ConvertibleFromAny {
611 ConvertibleFromAny(int a_value) : value(a_value) {}
612 template <typename T>
613 ConvertibleFromAny(const T& a_value) : value(-1) {
614 ADD_FAILURE() << "Conversion constructor called";
615 }
616 int value;
617};
618
619bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
620 return a.value == b.value;
621}
622
623ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
624 return os << a.value;
625}
626
627TEST(MatcherCastTest, ConversionConstructorIsUsed) {
628 Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
629 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
630 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
631}
632
633TEST(MatcherCastTest, FromConvertibleFromAny) {
634 Matcher<ConvertibleFromAny> m =
635 MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
636 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
637 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
638}
639
kosak5f2a6ca2013-12-03 01:43:07 +0000640struct IntReferenceWrapper {
641 IntReferenceWrapper(const int& a_value) : value(&a_value) {}
642 const int* value;
643};
644
645bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
646 return a.value == b.value;
647}
648
649TEST(MatcherCastTest, ValueIsNotCopied) {
650 int n = 42;
651 Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
652 // Verify that the matcher holds a reference to n, not to its temporary copy.
653 EXPECT_TRUE(m.Matches(n));
654}
655
zhanyong.wan18490652009-05-11 18:54:08 +0000656class Base {};
657class Derived : public Base {};
658
659// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
660TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
661 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
662 EXPECT_TRUE(m2.Matches(' '));
663 EXPECT_FALSE(m2.Matches('\n'));
664}
665
zhanyong.wan16cf4732009-05-14 20:55:30 +0000666// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
667// T and U are arithmetic types and T can be losslessly converted to
668// U.
669TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
zhanyong.wan18490652009-05-11 18:54:08 +0000670 Matcher<double> m1 = DoubleEq(1.0);
zhanyong.wan16cf4732009-05-14 20:55:30 +0000671 Matcher<float> m2 = SafeMatcherCast<float>(m1);
672 EXPECT_TRUE(m2.Matches(1.0f));
673 EXPECT_FALSE(m2.Matches(2.0f));
674
675 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
676 EXPECT_TRUE(m3.Matches('a'));
677 EXPECT_FALSE(m3.Matches('b'));
zhanyong.wan18490652009-05-11 18:54:08 +0000678}
679
680// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
681// are pointers or references to a derived and a base class, correspondingly.
682TEST(SafeMatcherCastTest, FromBaseClass) {
683 Derived d, d2;
684 Matcher<Base*> m1 = Eq(&d);
685 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
686 EXPECT_TRUE(m2.Matches(&d));
687 EXPECT_FALSE(m2.Matches(&d2));
688
689 Matcher<Base&> m3 = Ref(d);
690 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
691 EXPECT_TRUE(m4.Matches(d));
692 EXPECT_FALSE(m4.Matches(d2));
693}
694
695// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
696TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
697 int n = 0;
698 Matcher<const int&> m1 = Ref(n);
699 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
700 int n1 = 0;
701 EXPECT_TRUE(m2.Matches(n));
702 EXPECT_FALSE(m2.Matches(n1));
703}
704
705// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
706TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
707 Matcher<int> m1 = Eq(0);
708 Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
709 EXPECT_TRUE(m2.Matches(0));
710 EXPECT_FALSE(m2.Matches(1));
711}
712
713// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
714TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
715 Matcher<int> m1 = Eq(0);
716 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
717 int n = 0;
718 EXPECT_TRUE(m2.Matches(n));
719 n = 1;
720 EXPECT_FALSE(m2.Matches(n));
721}
722
723// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
724TEST(SafeMatcherCastTest, FromSameType) {
725 Matcher<int> m1 = Eq(0);
726 Matcher<int> m2 = SafeMatcherCast<int>(m1);
727 EXPECT_TRUE(m2.Matches(0));
728 EXPECT_FALSE(m2.Matches(1));
729}
730
jgm79a367e2012-04-10 16:02:11 +0000731TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
732 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
733 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
734 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
735}
736
737TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
738 Matcher<ConvertibleFromAny> m =
739 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
740 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
741 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
742}
743
kosak5f2a6ca2013-12-03 01:43:07 +0000744TEST(SafeMatcherCastTest, ValueIsNotCopied) {
745 int n = 42;
746 Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
747 // Verify that the matcher holds a reference to n, not to its temporary copy.
748 EXPECT_TRUE(m.Matches(n));
749}
750
shiqiane35fdd92008-12-10 05:08:54 +0000751// Tests that A<T>() matches any value of type T.
752TEST(ATest, MatchesAnyValue) {
753 // Tests a matcher for a value type.
754 Matcher<double> m1 = A<double>();
755 EXPECT_TRUE(m1.Matches(91.43));
756 EXPECT_TRUE(m1.Matches(-15.32));
757
758 // Tests a matcher for a reference type.
759 int a = 2;
760 int b = -6;
761 Matcher<int&> m2 = A<int&>();
762 EXPECT_TRUE(m2.Matches(a));
763 EXPECT_TRUE(m2.Matches(b));
764}
765
zhanyong.wanf4274522013-04-24 02:49:43 +0000766TEST(ATest, WorksForDerivedClass) {
767 Base base;
768 Derived derived;
769 EXPECT_THAT(&base, A<Base*>());
770 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
771 EXPECT_THAT(&derived, A<Base*>());
772 EXPECT_THAT(&derived, A<Derived*>());
773}
774
shiqiane35fdd92008-12-10 05:08:54 +0000775// Tests that A<T>() describes itself properly.
776TEST(ATest, CanDescribeSelf) {
777 EXPECT_EQ("is anything", Describe(A<bool>()));
778}
779
780// Tests that An<T>() matches any value of type T.
781TEST(AnTest, MatchesAnyValue) {
782 // Tests a matcher for a value type.
783 Matcher<int> m1 = An<int>();
784 EXPECT_TRUE(m1.Matches(9143));
785 EXPECT_TRUE(m1.Matches(-1532));
786
787 // Tests a matcher for a reference type.
788 int a = 2;
789 int b = -6;
790 Matcher<int&> m2 = An<int&>();
791 EXPECT_TRUE(m2.Matches(a));
792 EXPECT_TRUE(m2.Matches(b));
793}
794
795// Tests that An<T>() describes itself properly.
796TEST(AnTest, CanDescribeSelf) {
797 EXPECT_EQ("is anything", Describe(An<int>()));
798}
799
800// Tests that _ can be used as a matcher for any type and matches any
801// value of that type.
802TEST(UnderscoreTest, MatchesAnyValue) {
803 // Uses _ as a matcher for a value type.
804 Matcher<int> m1 = _;
805 EXPECT_TRUE(m1.Matches(123));
806 EXPECT_TRUE(m1.Matches(-242));
807
808 // Uses _ as a matcher for a reference type.
809 bool a = false;
810 const bool b = true;
811 Matcher<const bool&> m2 = _;
812 EXPECT_TRUE(m2.Matches(a));
813 EXPECT_TRUE(m2.Matches(b));
814}
815
816// Tests that _ describes itself properly.
817TEST(UnderscoreTest, CanDescribeSelf) {
818 Matcher<int> m = _;
819 EXPECT_EQ("is anything", Describe(m));
820}
821
822// Tests that Eq(x) matches any value equal to x.
823TEST(EqTest, MatchesEqualValue) {
824 // 2 C-strings with same content but different addresses.
825 const char a1[] = "hi";
826 const char a2[] = "hi";
827
828 Matcher<const char*> m1 = Eq(a1);
829 EXPECT_TRUE(m1.Matches(a1));
830 EXPECT_FALSE(m1.Matches(a2));
831}
832
833// Tests that Eq(v) describes itself properly.
834
835class Unprintable {
836 public:
837 Unprintable() : c_('a') {}
838
zhanyong.wan32de5f52009-12-23 00:13:23 +0000839 bool operator==(const Unprintable& /* rhs */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000840 private:
841 char c_;
842};
843
844TEST(EqTest, CanDescribeSelf) {
845 Matcher<Unprintable> m = Eq(Unprintable());
846 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
847}
848
849// Tests that Eq(v) can be used to match any type that supports
850// comparing with type T, where T is v's type.
851TEST(EqTest, IsPolymorphic) {
852 Matcher<int> m1 = Eq(1);
853 EXPECT_TRUE(m1.Matches(1));
854 EXPECT_FALSE(m1.Matches(2));
855
856 Matcher<char> m2 = Eq(1);
857 EXPECT_TRUE(m2.Matches('\1'));
858 EXPECT_FALSE(m2.Matches('a'));
859}
860
861// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
862TEST(TypedEqTest, ChecksEqualityForGivenType) {
863 Matcher<char> m1 = TypedEq<char>('a');
864 EXPECT_TRUE(m1.Matches('a'));
865 EXPECT_FALSE(m1.Matches('b'));
866
867 Matcher<int> m2 = TypedEq<int>(6);
868 EXPECT_TRUE(m2.Matches(6));
869 EXPECT_FALSE(m2.Matches(7));
870}
871
872// Tests that TypedEq(v) describes itself properly.
873TEST(TypedEqTest, CanDescribeSelf) {
874 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
875}
876
877// Tests that TypedEq<T>(v) has type Matcher<T>.
878
879// Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
880// is a "bare" type (i.e. not in the form of const U or U&). If v's
881// type is not T, the compiler will generate a message about
882// "undefined referece".
883template <typename T>
884struct Type {
zhanyong.wan32de5f52009-12-23 00:13:23 +0000885 static bool IsTypeOf(const T& /* v */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000886
887 template <typename T2>
888 static void IsTypeOf(T2 v);
889};
890
891TEST(TypedEqTest, HasSpecifiedType) {
892 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
893 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
894 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
895}
896
897// Tests that Ge(v) matches anything >= v.
898TEST(GeTest, ImplementsGreaterThanOrEqual) {
899 Matcher<int> m1 = Ge(0);
900 EXPECT_TRUE(m1.Matches(1));
901 EXPECT_TRUE(m1.Matches(0));
902 EXPECT_FALSE(m1.Matches(-1));
903}
904
905// Tests that Ge(v) describes itself properly.
906TEST(GeTest, CanDescribeSelf) {
907 Matcher<int> m = Ge(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000908 EXPECT_EQ("is >= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000909}
910
911// Tests that Gt(v) matches anything > v.
912TEST(GtTest, ImplementsGreaterThan) {
913 Matcher<double> m1 = Gt(0);
914 EXPECT_TRUE(m1.Matches(1.0));
915 EXPECT_FALSE(m1.Matches(0.0));
916 EXPECT_FALSE(m1.Matches(-1.0));
917}
918
919// Tests that Gt(v) describes itself properly.
920TEST(GtTest, CanDescribeSelf) {
921 Matcher<int> m = Gt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000922 EXPECT_EQ("is > 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000923}
924
925// Tests that Le(v) matches anything <= v.
926TEST(LeTest, ImplementsLessThanOrEqual) {
927 Matcher<char> m1 = Le('b');
928 EXPECT_TRUE(m1.Matches('a'));
929 EXPECT_TRUE(m1.Matches('b'));
930 EXPECT_FALSE(m1.Matches('c'));
931}
932
933// Tests that Le(v) describes itself properly.
934TEST(LeTest, CanDescribeSelf) {
935 Matcher<int> m = Le(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000936 EXPECT_EQ("is <= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000937}
938
939// Tests that Lt(v) matches anything < v.
940TEST(LtTest, ImplementsLessThan) {
941 Matcher<const string&> m1 = Lt("Hello");
942 EXPECT_TRUE(m1.Matches("Abc"));
943 EXPECT_FALSE(m1.Matches("Hello"));
944 EXPECT_FALSE(m1.Matches("Hello, world!"));
945}
946
947// Tests that Lt(v) describes itself properly.
948TEST(LtTest, CanDescribeSelf) {
949 Matcher<int> m = Lt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000950 EXPECT_EQ("is < 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000951}
952
953// Tests that Ne(v) matches anything != v.
954TEST(NeTest, ImplementsNotEqual) {
955 Matcher<int> m1 = Ne(0);
956 EXPECT_TRUE(m1.Matches(1));
957 EXPECT_TRUE(m1.Matches(-1));
958 EXPECT_FALSE(m1.Matches(0));
959}
960
961// Tests that Ne(v) describes itself properly.
962TEST(NeTest, CanDescribeSelf) {
963 Matcher<int> m = Ne(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000964 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000965}
966
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000967// Tests that IsNull() matches any NULL pointer of any type.
968TEST(IsNullTest, MatchesNullPointer) {
969 Matcher<int*> m1 = IsNull();
970 int* p1 = NULL;
971 int n = 0;
972 EXPECT_TRUE(m1.Matches(p1));
973 EXPECT_FALSE(m1.Matches(&n));
974
975 Matcher<const char*> m2 = IsNull();
976 const char* p2 = NULL;
977 EXPECT_TRUE(m2.Matches(p2));
978 EXPECT_FALSE(m2.Matches("hi"));
979
zhanyong.wan95b12332009-09-25 18:55:50 +0000980#if !GTEST_OS_SYMBIAN
981 // Nokia's Symbian compiler generates:
982 // gmock-matchers.h: ambiguous access to overloaded function
983 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
984 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
985 // MatcherInterface<void *> *)'
986 // gmock-matchers.h: (point of instantiation: 'testing::
987 // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
988 // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000989 Matcher<void*> m3 = IsNull();
990 void* p3 = NULL;
991 EXPECT_TRUE(m3.Matches(p3));
992 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
zhanyong.wan95b12332009-09-25 18:55:50 +0000993#endif
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000994}
995
vladlosev79b83502009-11-18 00:43:37 +0000996TEST(IsNullTest, LinkedPtr) {
997 const Matcher<linked_ptr<int> > m = IsNull();
998 const linked_ptr<int> null_p;
999 const linked_ptr<int> non_null_p(new int);
1000
1001 EXPECT_TRUE(m.Matches(null_p));
1002 EXPECT_FALSE(m.Matches(non_null_p));
1003}
1004
1005TEST(IsNullTest, ReferenceToConstLinkedPtr) {
1006 const Matcher<const linked_ptr<double>&> m = IsNull();
1007 const linked_ptr<double> null_p;
1008 const linked_ptr<double> non_null_p(new double);
1009
1010 EXPECT_TRUE(m.Matches(null_p));
1011 EXPECT_FALSE(m.Matches(non_null_p));
1012}
1013
vladloseve56daa72009-11-18 01:08:08 +00001014TEST(IsNullTest, ReferenceToConstScopedPtr) {
1015 const Matcher<const scoped_ptr<double>&> m = IsNull();
1016 const scoped_ptr<double> null_p;
1017 const scoped_ptr<double> non_null_p(new double);
1018
1019 EXPECT_TRUE(m.Matches(null_p));
1020 EXPECT_FALSE(m.Matches(non_null_p));
1021}
1022
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001023// Tests that IsNull() describes itself properly.
1024TEST(IsNullTest, CanDescribeSelf) {
1025 Matcher<int*> m = IsNull();
1026 EXPECT_EQ("is NULL", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001027 EXPECT_EQ("isn't NULL", DescribeNegation(m));
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001028}
1029
shiqiane35fdd92008-12-10 05:08:54 +00001030// Tests that NotNull() matches any non-NULL pointer of any type.
1031TEST(NotNullTest, MatchesNonNullPointer) {
1032 Matcher<int*> m1 = NotNull();
1033 int* p1 = NULL;
1034 int n = 0;
1035 EXPECT_FALSE(m1.Matches(p1));
1036 EXPECT_TRUE(m1.Matches(&n));
1037
1038 Matcher<const char*> m2 = NotNull();
1039 const char* p2 = NULL;
1040 EXPECT_FALSE(m2.Matches(p2));
1041 EXPECT_TRUE(m2.Matches("hi"));
1042}
1043
vladlosev79b83502009-11-18 00:43:37 +00001044TEST(NotNullTest, LinkedPtr) {
1045 const Matcher<linked_ptr<int> > m = NotNull();
1046 const linked_ptr<int> null_p;
1047 const linked_ptr<int> non_null_p(new int);
1048
1049 EXPECT_FALSE(m.Matches(null_p));
1050 EXPECT_TRUE(m.Matches(non_null_p));
1051}
1052
1053TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1054 const Matcher<const linked_ptr<double>&> m = NotNull();
1055 const linked_ptr<double> null_p;
1056 const linked_ptr<double> non_null_p(new double);
1057
1058 EXPECT_FALSE(m.Matches(null_p));
1059 EXPECT_TRUE(m.Matches(non_null_p));
1060}
1061
vladloseve56daa72009-11-18 01:08:08 +00001062TEST(NotNullTest, ReferenceToConstScopedPtr) {
1063 const Matcher<const scoped_ptr<double>&> m = NotNull();
1064 const scoped_ptr<double> null_p;
1065 const scoped_ptr<double> non_null_p(new double);
1066
1067 EXPECT_FALSE(m.Matches(null_p));
1068 EXPECT_TRUE(m.Matches(non_null_p));
1069}
1070
shiqiane35fdd92008-12-10 05:08:54 +00001071// Tests that NotNull() describes itself properly.
1072TEST(NotNullTest, CanDescribeSelf) {
1073 Matcher<int*> m = NotNull();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001074 EXPECT_EQ("isn't NULL", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001075}
1076
1077// Tests that Ref(variable) matches an argument that references
1078// 'variable'.
1079TEST(RefTest, MatchesSameVariable) {
1080 int a = 0;
1081 int b = 0;
1082 Matcher<int&> m = Ref(a);
1083 EXPECT_TRUE(m.Matches(a));
1084 EXPECT_FALSE(m.Matches(b));
1085}
1086
1087// Tests that Ref(variable) describes itself properly.
1088TEST(RefTest, CanDescribeSelf) {
1089 int n = 5;
1090 Matcher<int&> m = Ref(n);
1091 stringstream ss;
1092 ss << "references the variable @" << &n << " 5";
1093 EXPECT_EQ(string(ss.str()), Describe(m));
1094}
1095
1096// Test that Ref(non_const_varialbe) can be used as a matcher for a
1097// const reference.
1098TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1099 int a = 0;
1100 int b = 0;
1101 Matcher<const int&> m = Ref(a);
1102 EXPECT_TRUE(m.Matches(a));
1103 EXPECT_FALSE(m.Matches(b));
1104}
1105
1106// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1107// used wherever Ref(base) can be used (Ref(derived) is a sub-type
1108// of Ref(base), but not vice versa.
1109
shiqiane35fdd92008-12-10 05:08:54 +00001110TEST(RefTest, IsCovariant) {
1111 Base base, base2;
1112 Derived derived;
1113 Matcher<const Base&> m1 = Ref(base);
1114 EXPECT_TRUE(m1.Matches(base));
1115 EXPECT_FALSE(m1.Matches(base2));
1116 EXPECT_FALSE(m1.Matches(derived));
1117
1118 m1 = Ref(derived);
1119 EXPECT_TRUE(m1.Matches(derived));
1120 EXPECT_FALSE(m1.Matches(base));
1121 EXPECT_FALSE(m1.Matches(base2));
1122}
1123
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001124TEST(RefTest, ExplainsResult) {
1125 int n = 0;
1126 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1127 StartsWith("which is located @"));
1128
1129 int m = 0;
1130 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1131 StartsWith("which is located @"));
1132}
1133
shiqiane35fdd92008-12-10 05:08:54 +00001134// Tests string comparison matchers.
1135
1136TEST(StrEqTest, MatchesEqualString) {
1137 Matcher<const char*> m = StrEq(string("Hello"));
1138 EXPECT_TRUE(m.Matches("Hello"));
1139 EXPECT_FALSE(m.Matches("hello"));
1140 EXPECT_FALSE(m.Matches(NULL));
1141
1142 Matcher<const string&> m2 = StrEq("Hello");
1143 EXPECT_TRUE(m2.Matches("Hello"));
1144 EXPECT_FALSE(m2.Matches("Hi"));
1145}
1146
1147TEST(StrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001148 Matcher<string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1149 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
shiqiane35fdd92008-12-10 05:08:54 +00001150 Describe(m));
1151
1152 string str("01204500800");
1153 str[3] = '\0';
1154 Matcher<string> m2 = StrEq(str);
1155 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1156 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1157 Matcher<string> m3 = StrEq(str);
1158 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1159}
1160
1161TEST(StrNeTest, MatchesUnequalString) {
1162 Matcher<const char*> m = StrNe("Hello");
1163 EXPECT_TRUE(m.Matches(""));
1164 EXPECT_TRUE(m.Matches(NULL));
1165 EXPECT_FALSE(m.Matches("Hello"));
1166
1167 Matcher<string> m2 = StrNe(string("Hello"));
1168 EXPECT_TRUE(m2.Matches("hello"));
1169 EXPECT_FALSE(m2.Matches("Hello"));
1170}
1171
1172TEST(StrNeTest, CanDescribeSelf) {
1173 Matcher<const char*> m = StrNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001174 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001175}
1176
1177TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1178 Matcher<const char*> m = StrCaseEq(string("Hello"));
1179 EXPECT_TRUE(m.Matches("Hello"));
1180 EXPECT_TRUE(m.Matches("hello"));
1181 EXPECT_FALSE(m.Matches("Hi"));
1182 EXPECT_FALSE(m.Matches(NULL));
1183
1184 Matcher<const string&> m2 = StrCaseEq("Hello");
1185 EXPECT_TRUE(m2.Matches("hello"));
1186 EXPECT_FALSE(m2.Matches("Hi"));
1187}
1188
1189TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1190 string str1("oabocdooeoo");
1191 string str2("OABOCDOOEOO");
1192 Matcher<const string&> m0 = StrCaseEq(str1);
1193 EXPECT_FALSE(m0.Matches(str2 + string(1, '\0')));
1194
1195 str1[3] = str2[3] = '\0';
1196 Matcher<const string&> m1 = StrCaseEq(str1);
1197 EXPECT_TRUE(m1.Matches(str2));
1198
1199 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1200 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1201 Matcher<const string&> m2 = StrCaseEq(str1);
1202 str1[9] = str2[9] = '\0';
1203 EXPECT_FALSE(m2.Matches(str2));
1204
1205 Matcher<const string&> m3 = StrCaseEq(str1);
1206 EXPECT_TRUE(m3.Matches(str2));
1207
1208 EXPECT_FALSE(m3.Matches(str2 + "x"));
1209 str2.append(1, '\0');
1210 EXPECT_FALSE(m3.Matches(str2));
1211 EXPECT_FALSE(m3.Matches(string(str2, 0, 9)));
1212}
1213
1214TEST(StrCaseEqTest, CanDescribeSelf) {
1215 Matcher<string> m = StrCaseEq("Hi");
1216 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1217}
1218
1219TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1220 Matcher<const char*> m = StrCaseNe("Hello");
1221 EXPECT_TRUE(m.Matches("Hi"));
1222 EXPECT_TRUE(m.Matches(NULL));
1223 EXPECT_FALSE(m.Matches("Hello"));
1224 EXPECT_FALSE(m.Matches("hello"));
1225
1226 Matcher<string> m2 = StrCaseNe(string("Hello"));
1227 EXPECT_TRUE(m2.Matches(""));
1228 EXPECT_FALSE(m2.Matches("Hello"));
1229}
1230
1231TEST(StrCaseNeTest, CanDescribeSelf) {
1232 Matcher<const char*> m = StrCaseNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001233 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001234}
1235
1236// Tests that HasSubstr() works for matching string-typed values.
1237TEST(HasSubstrTest, WorksForStringClasses) {
1238 const Matcher<string> m1 = HasSubstr("foo");
1239 EXPECT_TRUE(m1.Matches(string("I love food.")));
1240 EXPECT_FALSE(m1.Matches(string("tofo")));
1241
1242 const Matcher<const std::string&> m2 = HasSubstr("foo");
1243 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1244 EXPECT_FALSE(m2.Matches(std::string("tofo")));
1245}
1246
1247// Tests that HasSubstr() works for matching C-string-typed values.
1248TEST(HasSubstrTest, WorksForCStrings) {
1249 const Matcher<char*> m1 = HasSubstr("foo");
1250 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1251 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1252 EXPECT_FALSE(m1.Matches(NULL));
1253
1254 const Matcher<const char*> m2 = HasSubstr("foo");
1255 EXPECT_TRUE(m2.Matches("I love food."));
1256 EXPECT_FALSE(m2.Matches("tofo"));
1257 EXPECT_FALSE(m2.Matches(NULL));
1258}
1259
1260// Tests that HasSubstr(s) describes itself properly.
1261TEST(HasSubstrTest, CanDescribeSelf) {
1262 Matcher<string> m = HasSubstr("foo\n\"");
1263 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1264}
1265
zhanyong.wanb5937da2009-07-16 20:26:41 +00001266TEST(KeyTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001267 Matcher<const pair<std::string, int>&> m = Key("foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001268 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001269 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1270}
1271
1272TEST(KeyTest, ExplainsResult) {
1273 Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1274 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1275 Explain(m, make_pair(5, true)));
1276 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1277 Explain(m, make_pair(15, true)));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001278}
1279
1280TEST(KeyTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001281 pair<int, std::string> p(25, "foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001282 EXPECT_THAT(p, Key(25));
1283 EXPECT_THAT(p, Not(Key(42)));
1284 EXPECT_THAT(p, Key(Ge(20)));
1285 EXPECT_THAT(p, Not(Key(Lt(25))));
1286}
1287
1288TEST(KeyTest, SafelyCastsInnerMatcher) {
1289 Matcher<int> is_positive = Gt(0);
1290 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001291 pair<char, bool> p('a', true);
zhanyong.wanb5937da2009-07-16 20:26:41 +00001292 EXPECT_THAT(p, Key(is_positive));
1293 EXPECT_THAT(p, Not(Key(is_negative)));
1294}
1295
1296TEST(KeyTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001297 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001298 container.insert(make_pair(1, 'a'));
1299 container.insert(make_pair(2, 'b'));
1300 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001301 EXPECT_THAT(container, Contains(Key(1)));
1302 EXPECT_THAT(container, Not(Contains(Key(3))));
1303}
1304
1305TEST(KeyTest, InsideContainsUsingMultimap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001306 multimap<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001307 container.insert(make_pair(1, 'a'));
1308 container.insert(make_pair(2, 'b'));
1309 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001310
1311 EXPECT_THAT(container, Not(Contains(Key(25))));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001312 container.insert(make_pair(25, 'd'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001313 EXPECT_THAT(container, Contains(Key(25)));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001314 container.insert(make_pair(25, 'e'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001315 EXPECT_THAT(container, Contains(Key(25)));
1316
1317 EXPECT_THAT(container, Contains(Key(1)));
1318 EXPECT_THAT(container, Not(Contains(Key(3))));
1319}
1320
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001321TEST(PairTest, Typing) {
1322 // Test verifies the following type conversions can be compiled.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001323 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1324 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1325 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001326
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001327 Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1328 Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001329}
1330
1331TEST(PairTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001332 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001333 EXPECT_EQ("has a first field that is equal to \"foo\""
1334 ", and has a second field that is equal to 42",
1335 Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001336 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1337 ", or has a second field that isn't equal to 42",
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001338 DescribeNegation(m1));
1339 // Double and triple negation (1 or 2 times not and description of negation).
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001340 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1341 EXPECT_EQ("has a first field that isn't equal to 13"
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001342 ", and has a second field that is equal to 42",
1343 DescribeNegation(m2));
1344}
1345
1346TEST(PairTest, CanExplainMatchResultTo) {
zhanyong.wan82113312010-01-08 21:55:40 +00001347 // If neither field matches, Pair() should explain about the first
1348 // field.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001349 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001350 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001351 Explain(m, make_pair(-1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001352
zhanyong.wan82113312010-01-08 21:55:40 +00001353 // If the first field matches but the second doesn't, Pair() should
1354 // explain about the second field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001355 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001356 Explain(m, make_pair(1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001357
zhanyong.wan82113312010-01-08 21:55:40 +00001358 // If the first field doesn't match but the second does, Pair()
1359 // should explain about the first field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001360 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001361 Explain(m, make_pair(-1, 2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001362
zhanyong.wan82113312010-01-08 21:55:40 +00001363 // If both fields match, Pair() should explain about them both.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001364 EXPECT_EQ("whose both fields match, where the first field is a value "
1365 "which is 1 more than 0, and the second field is a value "
1366 "which is 2 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001367 Explain(m, make_pair(1, 2)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001368
1369 // If only the first match has an explanation, only this explanation should
1370 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001371 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001372 EXPECT_EQ("whose both fields match, where the first field is a value "
1373 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001374 Explain(explain_first, make_pair(1, 0)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001375
1376 // If only the second match has an explanation, only this explanation should
1377 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001378 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001379 EXPECT_EQ("whose both fields match, where the second field is a value "
1380 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001381 Explain(explain_second, make_pair(0, 1)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001382}
1383
1384TEST(PairTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001385 pair<int, std::string> p(25, "foo");
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001386
1387 // Both fields match.
1388 EXPECT_THAT(p, Pair(25, "foo"));
1389 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1390
1391 // 'first' doesnt' match, but 'second' matches.
1392 EXPECT_THAT(p, Not(Pair(42, "foo")));
1393 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1394
1395 // 'first' matches, but 'second' doesn't match.
1396 EXPECT_THAT(p, Not(Pair(25, "bar")));
1397 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1398
1399 // Neither field matches.
1400 EXPECT_THAT(p, Not(Pair(13, "bar")));
1401 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1402}
1403
1404TEST(PairTest, SafelyCastsInnerMatchers) {
1405 Matcher<int> is_positive = Gt(0);
1406 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001407 pair<char, bool> p('a', true);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001408 EXPECT_THAT(p, Pair(is_positive, _));
1409 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1410 EXPECT_THAT(p, Pair(_, is_positive));
1411 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1412}
1413
1414TEST(PairTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001415 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001416 container.insert(make_pair(1, 'a'));
1417 container.insert(make_pair(2, 'b'));
1418 container.insert(make_pair(4, 'c'));
zhanyong.wan95b12332009-09-25 18:55:50 +00001419 EXPECT_THAT(container, Contains(Pair(1, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001420 EXPECT_THAT(container, Contains(Pair(1, _)));
zhanyong.wan95b12332009-09-25 18:55:50 +00001421 EXPECT_THAT(container, Contains(Pair(_, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001422 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1423}
1424
shiqiane35fdd92008-12-10 05:08:54 +00001425// Tests StartsWith(s).
1426
1427TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1428 const Matcher<const char*> m1 = StartsWith(string(""));
1429 EXPECT_TRUE(m1.Matches("Hi"));
1430 EXPECT_TRUE(m1.Matches(""));
1431 EXPECT_FALSE(m1.Matches(NULL));
1432
1433 const Matcher<const string&> m2 = StartsWith("Hi");
1434 EXPECT_TRUE(m2.Matches("Hi"));
1435 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1436 EXPECT_TRUE(m2.Matches("High"));
1437 EXPECT_FALSE(m2.Matches("H"));
1438 EXPECT_FALSE(m2.Matches(" Hi"));
1439}
1440
1441TEST(StartsWithTest, CanDescribeSelf) {
1442 Matcher<const std::string> m = StartsWith("Hi");
1443 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1444}
1445
1446// Tests EndsWith(s).
1447
1448TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1449 const Matcher<const char*> m1 = EndsWith("");
1450 EXPECT_TRUE(m1.Matches("Hi"));
1451 EXPECT_TRUE(m1.Matches(""));
1452 EXPECT_FALSE(m1.Matches(NULL));
1453
1454 const Matcher<const string&> m2 = EndsWith(string("Hi"));
1455 EXPECT_TRUE(m2.Matches("Hi"));
1456 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1457 EXPECT_TRUE(m2.Matches("Super Hi"));
1458 EXPECT_FALSE(m2.Matches("i"));
1459 EXPECT_FALSE(m2.Matches("Hi "));
1460}
1461
1462TEST(EndsWithTest, CanDescribeSelf) {
1463 Matcher<const std::string> m = EndsWith("Hi");
1464 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1465}
1466
shiqiane35fdd92008-12-10 05:08:54 +00001467// Tests MatchesRegex().
1468
1469TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1470 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1471 EXPECT_TRUE(m1.Matches("az"));
1472 EXPECT_TRUE(m1.Matches("abcz"));
1473 EXPECT_FALSE(m1.Matches(NULL));
1474
1475 const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z"));
1476 EXPECT_TRUE(m2.Matches("azbz"));
1477 EXPECT_FALSE(m2.Matches("az1"));
1478 EXPECT_FALSE(m2.Matches("1az"));
1479}
1480
1481TEST(MatchesRegexTest, CanDescribeSelf) {
1482 Matcher<const std::string> m1 = MatchesRegex(string("Hi.*"));
1483 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1484
zhanyong.wand14aaed2010-01-14 05:36:32 +00001485 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1486 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001487}
1488
1489// Tests ContainsRegex().
1490
1491TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1492 const Matcher<const char*> m1 = ContainsRegex(string("a.*z"));
1493 EXPECT_TRUE(m1.Matches("az"));
1494 EXPECT_TRUE(m1.Matches("0abcz1"));
1495 EXPECT_FALSE(m1.Matches(NULL));
1496
1497 const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z"));
1498 EXPECT_TRUE(m2.Matches("azbz"));
1499 EXPECT_TRUE(m2.Matches("az1"));
1500 EXPECT_FALSE(m2.Matches("1a"));
1501}
1502
1503TEST(ContainsRegexTest, CanDescribeSelf) {
1504 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1505 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1506
zhanyong.wand14aaed2010-01-14 05:36:32 +00001507 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1508 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001509}
shiqiane35fdd92008-12-10 05:08:54 +00001510
1511// Tests for wide strings.
1512#if GTEST_HAS_STD_WSTRING
1513TEST(StdWideStrEqTest, MatchesEqual) {
1514 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1515 EXPECT_TRUE(m.Matches(L"Hello"));
1516 EXPECT_FALSE(m.Matches(L"hello"));
1517 EXPECT_FALSE(m.Matches(NULL));
1518
1519 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1520 EXPECT_TRUE(m2.Matches(L"Hello"));
1521 EXPECT_FALSE(m2.Matches(L"Hi"));
1522
1523 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1524 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1525 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1526
1527 ::std::wstring str(L"01204500800");
1528 str[3] = L'\0';
1529 Matcher<const ::std::wstring&> m4 = StrEq(str);
1530 EXPECT_TRUE(m4.Matches(str));
1531 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1532 Matcher<const ::std::wstring&> m5 = StrEq(str);
1533 EXPECT_TRUE(m5.Matches(str));
1534}
1535
1536TEST(StdWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001537 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1538 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001539 Describe(m));
1540
1541 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1542 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1543 Describe(m2));
1544
1545 ::std::wstring str(L"01204500800");
1546 str[3] = L'\0';
1547 Matcher<const ::std::wstring&> m4 = StrEq(str);
1548 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1549 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1550 Matcher<const ::std::wstring&> m5 = StrEq(str);
1551 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1552}
1553
1554TEST(StdWideStrNeTest, MatchesUnequalString) {
1555 Matcher<const wchar_t*> m = StrNe(L"Hello");
1556 EXPECT_TRUE(m.Matches(L""));
1557 EXPECT_TRUE(m.Matches(NULL));
1558 EXPECT_FALSE(m.Matches(L"Hello"));
1559
1560 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1561 EXPECT_TRUE(m2.Matches(L"hello"));
1562 EXPECT_FALSE(m2.Matches(L"Hello"));
1563}
1564
1565TEST(StdWideStrNeTest, CanDescribeSelf) {
1566 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001567 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001568}
1569
1570TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1571 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1572 EXPECT_TRUE(m.Matches(L"Hello"));
1573 EXPECT_TRUE(m.Matches(L"hello"));
1574 EXPECT_FALSE(m.Matches(L"Hi"));
1575 EXPECT_FALSE(m.Matches(NULL));
1576
1577 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1578 EXPECT_TRUE(m2.Matches(L"hello"));
1579 EXPECT_FALSE(m2.Matches(L"Hi"));
1580}
1581
1582TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1583 ::std::wstring str1(L"oabocdooeoo");
1584 ::std::wstring str2(L"OABOCDOOEOO");
1585 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1586 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1587
1588 str1[3] = str2[3] = L'\0';
1589 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1590 EXPECT_TRUE(m1.Matches(str2));
1591
1592 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1593 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1594 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1595 str1[9] = str2[9] = L'\0';
1596 EXPECT_FALSE(m2.Matches(str2));
1597
1598 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1599 EXPECT_TRUE(m3.Matches(str2));
1600
1601 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1602 str2.append(1, L'\0');
1603 EXPECT_FALSE(m3.Matches(str2));
1604 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1605}
1606
1607TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1608 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1609 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1610}
1611
1612TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1613 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1614 EXPECT_TRUE(m.Matches(L"Hi"));
1615 EXPECT_TRUE(m.Matches(NULL));
1616 EXPECT_FALSE(m.Matches(L"Hello"));
1617 EXPECT_FALSE(m.Matches(L"hello"));
1618
1619 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1620 EXPECT_TRUE(m2.Matches(L""));
1621 EXPECT_FALSE(m2.Matches(L"Hello"));
1622}
1623
1624TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1625 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001626 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001627}
1628
1629// Tests that HasSubstr() works for matching wstring-typed values.
1630TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1631 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1632 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1633 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1634
1635 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1636 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1637 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1638}
1639
1640// Tests that HasSubstr() works for matching C-wide-string-typed values.
1641TEST(StdWideHasSubstrTest, WorksForCStrings) {
1642 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1643 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1644 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1645 EXPECT_FALSE(m1.Matches(NULL));
1646
1647 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1648 EXPECT_TRUE(m2.Matches(L"I love food."));
1649 EXPECT_FALSE(m2.Matches(L"tofo"));
1650 EXPECT_FALSE(m2.Matches(NULL));
1651}
1652
1653// Tests that HasSubstr(s) describes itself properly.
1654TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1655 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1656 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1657}
1658
1659// Tests StartsWith(s).
1660
1661TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1662 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1663 EXPECT_TRUE(m1.Matches(L"Hi"));
1664 EXPECT_TRUE(m1.Matches(L""));
1665 EXPECT_FALSE(m1.Matches(NULL));
1666
1667 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1668 EXPECT_TRUE(m2.Matches(L"Hi"));
1669 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1670 EXPECT_TRUE(m2.Matches(L"High"));
1671 EXPECT_FALSE(m2.Matches(L"H"));
1672 EXPECT_FALSE(m2.Matches(L" Hi"));
1673}
1674
1675TEST(StdWideStartsWithTest, CanDescribeSelf) {
1676 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
1677 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1678}
1679
1680// Tests EndsWith(s).
1681
1682TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
1683 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1684 EXPECT_TRUE(m1.Matches(L"Hi"));
1685 EXPECT_TRUE(m1.Matches(L""));
1686 EXPECT_FALSE(m1.Matches(NULL));
1687
1688 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
1689 EXPECT_TRUE(m2.Matches(L"Hi"));
1690 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1691 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1692 EXPECT_FALSE(m2.Matches(L"i"));
1693 EXPECT_FALSE(m2.Matches(L"Hi "));
1694}
1695
1696TEST(StdWideEndsWithTest, CanDescribeSelf) {
1697 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
1698 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1699}
1700
1701#endif // GTEST_HAS_STD_WSTRING
1702
1703#if GTEST_HAS_GLOBAL_WSTRING
1704TEST(GlobalWideStrEqTest, MatchesEqual) {
1705 Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
1706 EXPECT_TRUE(m.Matches(L"Hello"));
1707 EXPECT_FALSE(m.Matches(L"hello"));
1708 EXPECT_FALSE(m.Matches(NULL));
1709
1710 Matcher<const ::wstring&> m2 = StrEq(L"Hello");
1711 EXPECT_TRUE(m2.Matches(L"Hello"));
1712 EXPECT_FALSE(m2.Matches(L"Hi"));
1713
1714 Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1715 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1716 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1717
1718 ::wstring str(L"01204500800");
1719 str[3] = L'\0';
1720 Matcher<const ::wstring&> m4 = StrEq(str);
1721 EXPECT_TRUE(m4.Matches(str));
1722 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1723 Matcher<const ::wstring&> m5 = StrEq(str);
1724 EXPECT_TRUE(m5.Matches(str));
1725}
1726
1727TEST(GlobalWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001728 Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1729 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001730 Describe(m));
1731
1732 Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1733 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1734 Describe(m2));
1735
1736 ::wstring str(L"01204500800");
1737 str[3] = L'\0';
1738 Matcher<const ::wstring&> m4 = StrEq(str);
1739 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1740 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1741 Matcher<const ::wstring&> m5 = StrEq(str);
1742 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1743}
1744
1745TEST(GlobalWideStrNeTest, MatchesUnequalString) {
1746 Matcher<const wchar_t*> m = StrNe(L"Hello");
1747 EXPECT_TRUE(m.Matches(L""));
1748 EXPECT_TRUE(m.Matches(NULL));
1749 EXPECT_FALSE(m.Matches(L"Hello"));
1750
1751 Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
1752 EXPECT_TRUE(m2.Matches(L"hello"));
1753 EXPECT_FALSE(m2.Matches(L"Hello"));
1754}
1755
1756TEST(GlobalWideStrNeTest, CanDescribeSelf) {
1757 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001758 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001759}
1760
1761TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1762 Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
1763 EXPECT_TRUE(m.Matches(L"Hello"));
1764 EXPECT_TRUE(m.Matches(L"hello"));
1765 EXPECT_FALSE(m.Matches(L"Hi"));
1766 EXPECT_FALSE(m.Matches(NULL));
1767
1768 Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
1769 EXPECT_TRUE(m2.Matches(L"hello"));
1770 EXPECT_FALSE(m2.Matches(L"Hi"));
1771}
1772
1773TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1774 ::wstring str1(L"oabocdooeoo");
1775 ::wstring str2(L"OABOCDOOEOO");
1776 Matcher<const ::wstring&> m0 = StrCaseEq(str1);
1777 EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
1778
1779 str1[3] = str2[3] = L'\0';
1780 Matcher<const ::wstring&> m1 = StrCaseEq(str1);
1781 EXPECT_TRUE(m1.Matches(str2));
1782
1783 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1784 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1785 Matcher<const ::wstring&> m2 = StrCaseEq(str1);
1786 str1[9] = str2[9] = L'\0';
1787 EXPECT_FALSE(m2.Matches(str2));
1788
1789 Matcher<const ::wstring&> m3 = StrCaseEq(str1);
1790 EXPECT_TRUE(m3.Matches(str2));
1791
1792 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1793 str2.append(1, L'\0');
1794 EXPECT_FALSE(m3.Matches(str2));
1795 EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
1796}
1797
1798TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
1799 Matcher< ::wstring> m = StrCaseEq(L"Hi");
1800 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1801}
1802
1803TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1804 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1805 EXPECT_TRUE(m.Matches(L"Hi"));
1806 EXPECT_TRUE(m.Matches(NULL));
1807 EXPECT_FALSE(m.Matches(L"Hello"));
1808 EXPECT_FALSE(m.Matches(L"hello"));
1809
1810 Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
1811 EXPECT_TRUE(m2.Matches(L""));
1812 EXPECT_FALSE(m2.Matches(L"Hello"));
1813}
1814
1815TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
1816 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001817 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001818}
1819
1820// Tests that HasSubstr() works for matching wstring-typed values.
1821TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
1822 const Matcher< ::wstring> m1 = HasSubstr(L"foo");
1823 EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
1824 EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
1825
1826 const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
1827 EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
1828 EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
1829}
1830
1831// Tests that HasSubstr() works for matching C-wide-string-typed values.
1832TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
1833 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1834 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1835 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1836 EXPECT_FALSE(m1.Matches(NULL));
1837
1838 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1839 EXPECT_TRUE(m2.Matches(L"I love food."));
1840 EXPECT_FALSE(m2.Matches(L"tofo"));
1841 EXPECT_FALSE(m2.Matches(NULL));
1842}
1843
1844// Tests that HasSubstr(s) describes itself properly.
1845TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
1846 Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
1847 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1848}
1849
1850// Tests StartsWith(s).
1851
1852TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
1853 const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
1854 EXPECT_TRUE(m1.Matches(L"Hi"));
1855 EXPECT_TRUE(m1.Matches(L""));
1856 EXPECT_FALSE(m1.Matches(NULL));
1857
1858 const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
1859 EXPECT_TRUE(m2.Matches(L"Hi"));
1860 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1861 EXPECT_TRUE(m2.Matches(L"High"));
1862 EXPECT_FALSE(m2.Matches(L"H"));
1863 EXPECT_FALSE(m2.Matches(L" Hi"));
1864}
1865
1866TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
1867 Matcher<const ::wstring> m = StartsWith(L"Hi");
1868 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1869}
1870
1871// Tests EndsWith(s).
1872
1873TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
1874 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1875 EXPECT_TRUE(m1.Matches(L"Hi"));
1876 EXPECT_TRUE(m1.Matches(L""));
1877 EXPECT_FALSE(m1.Matches(NULL));
1878
1879 const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
1880 EXPECT_TRUE(m2.Matches(L"Hi"));
1881 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1882 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1883 EXPECT_FALSE(m2.Matches(L"i"));
1884 EXPECT_FALSE(m2.Matches(L"Hi "));
1885}
1886
1887TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
1888 Matcher<const ::wstring> m = EndsWith(L"Hi");
1889 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1890}
1891
1892#endif // GTEST_HAS_GLOBAL_WSTRING
1893
1894
1895typedef ::std::tr1::tuple<long, int> Tuple2; // NOLINT
1896
1897// Tests that Eq() matches a 2-tuple where the first field == the
1898// second field.
1899TEST(Eq2Test, MatchesEqualArguments) {
1900 Matcher<const Tuple2&> m = Eq();
1901 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1902 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1903}
1904
1905// Tests that Eq() describes itself properly.
1906TEST(Eq2Test, CanDescribeSelf) {
1907 Matcher<const Tuple2&> m = Eq();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001908 EXPECT_EQ("are an equal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001909}
1910
1911// Tests that Ge() matches a 2-tuple where the first field >= the
1912// second field.
1913TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
1914 Matcher<const Tuple2&> m = Ge();
1915 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1916 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1917 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1918}
1919
1920// Tests that Ge() describes itself properly.
1921TEST(Ge2Test, CanDescribeSelf) {
1922 Matcher<const Tuple2&> m = Ge();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001923 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001924}
1925
1926// Tests that Gt() matches a 2-tuple where the first field > the
1927// second field.
1928TEST(Gt2Test, MatchesGreaterThanArguments) {
1929 Matcher<const Tuple2&> m = Gt();
1930 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1931 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1932 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1933}
1934
1935// Tests that Gt() describes itself properly.
1936TEST(Gt2Test, CanDescribeSelf) {
1937 Matcher<const Tuple2&> m = Gt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001938 EXPECT_EQ("are a pair where the first > the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001939}
1940
1941// Tests that Le() matches a 2-tuple where the first field <= the
1942// second field.
1943TEST(Le2Test, MatchesLessThanOrEqualArguments) {
1944 Matcher<const Tuple2&> m = Le();
1945 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1946 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1947 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1948}
1949
1950// Tests that Le() describes itself properly.
1951TEST(Le2Test, CanDescribeSelf) {
1952 Matcher<const Tuple2&> m = Le();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001953 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001954}
1955
1956// Tests that Lt() matches a 2-tuple where the first field < the
1957// second field.
1958TEST(Lt2Test, MatchesLessThanArguments) {
1959 Matcher<const Tuple2&> m = Lt();
1960 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1961 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1962 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1963}
1964
1965// Tests that Lt() describes itself properly.
1966TEST(Lt2Test, CanDescribeSelf) {
1967 Matcher<const Tuple2&> m = Lt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001968 EXPECT_EQ("are a pair where the first < the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001969}
1970
1971// Tests that Ne() matches a 2-tuple where the first field != the
1972// second field.
1973TEST(Ne2Test, MatchesUnequalArguments) {
1974 Matcher<const Tuple2&> m = Ne();
1975 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1976 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1977 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1978}
1979
1980// Tests that Ne() describes itself properly.
1981TEST(Ne2Test, CanDescribeSelf) {
1982 Matcher<const Tuple2&> m = Ne();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001983 EXPECT_EQ("are an unequal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001984}
1985
1986// Tests that Not(m) matches any value that doesn't match m.
1987TEST(NotTest, NegatesMatcher) {
1988 Matcher<int> m;
1989 m = Not(Eq(2));
1990 EXPECT_TRUE(m.Matches(3));
1991 EXPECT_FALSE(m.Matches(2));
1992}
1993
1994// Tests that Not(m) describes itself properly.
1995TEST(NotTest, CanDescribeSelf) {
1996 Matcher<int> m = Not(Eq(5));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001997 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001998}
1999
zhanyong.wan18490652009-05-11 18:54:08 +00002000// Tests that monomorphic matchers are safely cast by the Not matcher.
2001TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2002 // greater_than_5 is a monomorphic matcher.
2003 Matcher<int> greater_than_5 = Gt(5);
2004
2005 Matcher<const int&> m = Not(greater_than_5);
2006 Matcher<int&> m2 = Not(greater_than_5);
2007 Matcher<int&> m3 = Not(m);
2008}
2009
zhanyong.wan02c15052010-06-09 19:21:30 +00002010// Helper to allow easy testing of AllOf matchers with num parameters.
2011void AllOfMatches(int num, const Matcher<int>& m) {
2012 SCOPED_TRACE(Describe(m));
2013 EXPECT_TRUE(m.Matches(0));
2014 for (int i = 1; i <= num; ++i) {
2015 EXPECT_FALSE(m.Matches(i));
2016 }
2017 EXPECT_TRUE(m.Matches(num + 1));
2018}
2019
shiqiane35fdd92008-12-10 05:08:54 +00002020// Tests that AllOf(m1, ..., mn) matches any value that matches all of
2021// the given matchers.
2022TEST(AllOfTest, MatchesWhenAllMatch) {
2023 Matcher<int> m;
2024 m = AllOf(Le(2), Ge(1));
2025 EXPECT_TRUE(m.Matches(1));
2026 EXPECT_TRUE(m.Matches(2));
2027 EXPECT_FALSE(m.Matches(0));
2028 EXPECT_FALSE(m.Matches(3));
2029
2030 m = AllOf(Gt(0), Ne(1), Ne(2));
2031 EXPECT_TRUE(m.Matches(3));
2032 EXPECT_FALSE(m.Matches(2));
2033 EXPECT_FALSE(m.Matches(1));
2034 EXPECT_FALSE(m.Matches(0));
2035
2036 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2037 EXPECT_TRUE(m.Matches(4));
2038 EXPECT_FALSE(m.Matches(3));
2039 EXPECT_FALSE(m.Matches(2));
2040 EXPECT_FALSE(m.Matches(1));
2041 EXPECT_FALSE(m.Matches(0));
2042
2043 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2044 EXPECT_TRUE(m.Matches(0));
2045 EXPECT_TRUE(m.Matches(1));
2046 EXPECT_FALSE(m.Matches(3));
zhanyong.wan02c15052010-06-09 19:21:30 +00002047
2048 // The following tests for varying number of sub-matchers. Due to the way
2049 // the sub-matchers are handled it is enough to test every sub-matcher once
2050 // with sub-matchers using the same matcher type. Varying matcher types are
2051 // checked for above.
2052 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2053 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2054 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2055 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2056 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2057 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2058 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2059 Ne(8)));
2060 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2061 Ne(8), Ne(9)));
2062 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2063 Ne(9), Ne(10)));
shiqiane35fdd92008-12-10 05:08:54 +00002064}
2065
zhanyong.wan616180e2013-06-18 18:49:51 +00002066#if GTEST_LANG_CXX11
2067// Tests the variadic version of the AllOfMatcher.
2068TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
2069 // Make sure AllOf is defined in the right namespace and does not depend on
2070 // ADL.
2071 ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2072 Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2073 Ne(9), Ne(10), Ne(11));
2074 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))"));
2075 AllOfMatches(11, m);
2076 AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2077 Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
2078 Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22),
2079 Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29),
2080 Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36),
2081 Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43),
2082 Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2083 Ne(50)));
2084}
2085
2086#endif // GTEST_LANG_CXX11
2087
shiqiane35fdd92008-12-10 05:08:54 +00002088// Tests that AllOf(m1, ..., mn) describes itself properly.
2089TEST(AllOfTest, CanDescribeSelf) {
2090 Matcher<int> m;
2091 m = AllOf(Le(2), Ge(1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002092 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002093
2094 m = AllOf(Gt(0), Ne(1), Ne(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002095 EXPECT_EQ("(is > 0) and "
2096 "((isn't equal to 1) and "
2097 "(isn't equal to 2))",
shiqiane35fdd92008-12-10 05:08:54 +00002098 Describe(m));
2099
2100
2101 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002102 EXPECT_EQ("((is > 0) and "
2103 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002104 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002105 "(isn't equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002106 Describe(m));
2107
2108
2109 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002110 EXPECT_EQ("((is >= 0) and "
2111 "(is < 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002112 "((isn't equal to 3) and "
2113 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002114 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002115 Describe(m));
2116}
2117
2118// Tests that AllOf(m1, ..., mn) describes its negation properly.
2119TEST(AllOfTest, CanDescribeNegation) {
2120 Matcher<int> m;
2121 m = AllOf(Le(2), Ge(1));
2122 EXPECT_EQ("(isn't <= 2) or "
2123 "(isn't >= 1)",
2124 DescribeNegation(m));
2125
2126 m = AllOf(Gt(0), Ne(1), Ne(2));
2127 EXPECT_EQ("(isn't > 0) or "
2128 "((is equal to 1) or "
2129 "(is equal to 2))",
2130 DescribeNegation(m));
2131
2132
2133 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002134 EXPECT_EQ("((isn't > 0) or "
2135 "(is equal to 1)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002136 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002137 "(is equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002138 DescribeNegation(m));
2139
2140
2141 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002142 EXPECT_EQ("((isn't >= 0) or "
2143 "(isn't < 10)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002144 "((is equal to 3) or "
2145 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002146 "(is equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002147 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00002148}
2149
zhanyong.wan18490652009-05-11 18:54:08 +00002150// Tests that monomorphic matchers are safely cast by the AllOf matcher.
2151TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2152 // greater_than_5 and less_than_10 are monomorphic matchers.
2153 Matcher<int> greater_than_5 = Gt(5);
2154 Matcher<int> less_than_10 = Lt(10);
2155
2156 Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2157 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2158 Matcher<int&> m3 = AllOf(greater_than_5, m2);
2159
2160 // Tests that BothOf works when composing itself.
2161 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2162 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2163}
2164
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002165TEST(AllOfTest, ExplainsResult) {
2166 Matcher<int> m;
2167
2168 // Successful match. Both matchers need to explain. The second
2169 // matcher doesn't give an explanation, so only the first matcher's
2170 // explanation is printed.
2171 m = AllOf(GreaterThan(10), Lt(30));
2172 EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2173
2174 // Successful match. Both matchers need to explain.
2175 m = AllOf(GreaterThan(10), GreaterThan(20));
2176 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2177 Explain(m, 30));
2178
2179 // Successful match. All matchers need to explain. The second
2180 // matcher doesn't given an explanation.
2181 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2182 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2183 Explain(m, 25));
2184
2185 // Successful match. All matchers need to explain.
2186 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2187 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2188 "and which is 10 more than 30",
2189 Explain(m, 40));
2190
2191 // Failed match. The first matcher, which failed, needs to
2192 // explain.
2193 m = AllOf(GreaterThan(10), GreaterThan(20));
2194 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2195
2196 // Failed match. The second matcher, which failed, needs to
2197 // explain. Since it doesn't given an explanation, nothing is
2198 // printed.
2199 m = AllOf(GreaterThan(10), Lt(30));
2200 EXPECT_EQ("", Explain(m, 40));
2201
2202 // Failed match. The second matcher, which failed, needs to
2203 // explain.
2204 m = AllOf(GreaterThan(10), GreaterThan(20));
2205 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2206}
2207
zhanyong.wan02c15052010-06-09 19:21:30 +00002208// Helper to allow easy testing of AnyOf matchers with num parameters.
2209void AnyOfMatches(int num, const Matcher<int>& m) {
2210 SCOPED_TRACE(Describe(m));
2211 EXPECT_FALSE(m.Matches(0));
2212 for (int i = 1; i <= num; ++i) {
2213 EXPECT_TRUE(m.Matches(i));
2214 }
2215 EXPECT_FALSE(m.Matches(num + 1));
2216}
2217
shiqiane35fdd92008-12-10 05:08:54 +00002218// Tests that AnyOf(m1, ..., mn) matches any value that matches at
2219// least one of the given matchers.
2220TEST(AnyOfTest, MatchesWhenAnyMatches) {
2221 Matcher<int> m;
2222 m = AnyOf(Le(1), Ge(3));
2223 EXPECT_TRUE(m.Matches(1));
2224 EXPECT_TRUE(m.Matches(4));
2225 EXPECT_FALSE(m.Matches(2));
2226
2227 m = AnyOf(Lt(0), Eq(1), Eq(2));
2228 EXPECT_TRUE(m.Matches(-1));
2229 EXPECT_TRUE(m.Matches(1));
2230 EXPECT_TRUE(m.Matches(2));
2231 EXPECT_FALSE(m.Matches(0));
2232
2233 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2234 EXPECT_TRUE(m.Matches(-1));
2235 EXPECT_TRUE(m.Matches(1));
2236 EXPECT_TRUE(m.Matches(2));
2237 EXPECT_TRUE(m.Matches(3));
2238 EXPECT_FALSE(m.Matches(0));
2239
2240 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2241 EXPECT_TRUE(m.Matches(0));
2242 EXPECT_TRUE(m.Matches(11));
2243 EXPECT_TRUE(m.Matches(3));
2244 EXPECT_FALSE(m.Matches(2));
zhanyong.wan02c15052010-06-09 19:21:30 +00002245
2246 // The following tests for varying number of sub-matchers. Due to the way
2247 // the sub-matchers are handled it is enough to test every sub-matcher once
2248 // with sub-matchers using the same matcher type. Varying matcher types are
2249 // checked for above.
2250 AnyOfMatches(2, AnyOf(1, 2));
2251 AnyOfMatches(3, AnyOf(1, 2, 3));
2252 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2253 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2254 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2255 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2256 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2257 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2258 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
shiqiane35fdd92008-12-10 05:08:54 +00002259}
2260
zhanyong.wan616180e2013-06-18 18:49:51 +00002261#if GTEST_LANG_CXX11
2262// Tests the variadic version of the AnyOfMatcher.
2263TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2264 // Also make sure AnyOf is defined in the right namespace and does not depend
2265 // on ADL.
2266 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2267
2268 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))"));
2269 AnyOfMatches(11, m);
2270 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2271 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2272 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2273 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2274 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2275}
2276
2277#endif // GTEST_LANG_CXX11
2278
shiqiane35fdd92008-12-10 05:08:54 +00002279// Tests that AnyOf(m1, ..., mn) describes itself properly.
2280TEST(AnyOfTest, CanDescribeSelf) {
2281 Matcher<int> m;
2282 m = AnyOf(Le(1), Ge(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002283 EXPECT_EQ("(is <= 1) or (is >= 3)",
shiqiane35fdd92008-12-10 05:08:54 +00002284 Describe(m));
2285
2286 m = AnyOf(Lt(0), Eq(1), Eq(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002287 EXPECT_EQ("(is < 0) or "
shiqiane35fdd92008-12-10 05:08:54 +00002288 "((is equal to 1) or (is equal to 2))",
2289 Describe(m));
2290
2291 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002292 EXPECT_EQ("((is < 0) or "
2293 "(is equal to 1)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002294 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002295 "(is equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002296 Describe(m));
2297
2298 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002299 EXPECT_EQ("((is <= 0) or "
2300 "(is > 10)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002301 "((is equal to 3) or "
2302 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002303 "(is equal to 7)))",
shiqiane35fdd92008-12-10 05:08:54 +00002304 Describe(m));
2305}
2306
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002307// Tests that AnyOf(m1, ..., mn) describes its negation properly.
2308TEST(AnyOfTest, CanDescribeNegation) {
2309 Matcher<int> m;
2310 m = AnyOf(Le(1), Ge(3));
2311 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2312 DescribeNegation(m));
2313
2314 m = AnyOf(Lt(0), Eq(1), Eq(2));
2315 EXPECT_EQ("(isn't < 0) and "
2316 "((isn't equal to 1) and (isn't equal to 2))",
2317 DescribeNegation(m));
2318
2319 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002320 EXPECT_EQ("((isn't < 0) and "
2321 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002322 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002323 "(isn't equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002324 DescribeNegation(m));
2325
2326 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002327 EXPECT_EQ("((isn't <= 0) and "
2328 "(isn't > 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002329 "((isn't equal to 3) and "
2330 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002331 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002332 DescribeNegation(m));
2333}
2334
zhanyong.wan18490652009-05-11 18:54:08 +00002335// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2336TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2337 // greater_than_5 and less_than_10 are monomorphic matchers.
2338 Matcher<int> greater_than_5 = Gt(5);
2339 Matcher<int> less_than_10 = Lt(10);
2340
2341 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2342 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2343 Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2344
2345 // Tests that EitherOf works when composing itself.
2346 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2347 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2348}
2349
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002350TEST(AnyOfTest, ExplainsResult) {
2351 Matcher<int> m;
2352
2353 // Failed match. Both matchers need to explain. The second
2354 // matcher doesn't give an explanation, so only the first matcher's
2355 // explanation is printed.
2356 m = AnyOf(GreaterThan(10), Lt(0));
2357 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2358
2359 // Failed match. Both matchers need to explain.
2360 m = AnyOf(GreaterThan(10), GreaterThan(20));
2361 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2362 Explain(m, 5));
2363
2364 // Failed match. All matchers need to explain. The second
2365 // matcher doesn't given an explanation.
2366 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2367 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2368 Explain(m, 5));
2369
2370 // Failed match. All matchers need to explain.
2371 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2372 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2373 "and which is 25 less than 30",
2374 Explain(m, 5));
2375
2376 // Successful match. The first matcher, which succeeded, needs to
2377 // explain.
2378 m = AnyOf(GreaterThan(10), GreaterThan(20));
2379 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2380
2381 // Successful match. The second matcher, which succeeded, needs to
2382 // explain. Since it doesn't given an explanation, nothing is
2383 // printed.
2384 m = AnyOf(GreaterThan(10), Lt(30));
2385 EXPECT_EQ("", Explain(m, 0));
2386
2387 // Successful match. The second matcher, which succeeded, needs to
2388 // explain.
2389 m = AnyOf(GreaterThan(30), GreaterThan(20));
2390 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2391}
2392
shiqiane35fdd92008-12-10 05:08:54 +00002393// The following predicate function and predicate functor are for
2394// testing the Truly(predicate) matcher.
2395
2396// Returns non-zero if the input is positive. Note that the return
2397// type of this function is not bool. It's OK as Truly() accepts any
2398// unary function or functor whose return type can be implicitly
2399// converted to bool.
2400int IsPositive(double x) {
2401 return x > 0 ? 1 : 0;
2402}
2403
2404// This functor returns true if the input is greater than the given
2405// number.
2406class IsGreaterThan {
2407 public:
2408 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2409
2410 bool operator()(int n) const { return n > threshold_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002411
shiqiane35fdd92008-12-10 05:08:54 +00002412 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002413 int threshold_;
shiqiane35fdd92008-12-10 05:08:54 +00002414};
2415
2416// For testing Truly().
2417const int foo = 0;
2418
2419// This predicate returns true iff the argument references foo and has
2420// a zero value.
2421bool ReferencesFooAndIsZero(const int& n) {
2422 return (&n == &foo) && (n == 0);
2423}
2424
2425// Tests that Truly(predicate) matches what satisfies the given
2426// predicate.
2427TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2428 Matcher<double> m = Truly(IsPositive);
2429 EXPECT_TRUE(m.Matches(2.0));
2430 EXPECT_FALSE(m.Matches(-1.5));
2431}
2432
2433// Tests that Truly(predicate_functor) works too.
2434TEST(TrulyTest, CanBeUsedWithFunctor) {
2435 Matcher<int> m = Truly(IsGreaterThan(5));
2436 EXPECT_TRUE(m.Matches(6));
2437 EXPECT_FALSE(m.Matches(4));
2438}
2439
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00002440// A class that can be implicitly converted to bool.
2441class ConvertibleToBool {
2442 public:
2443 explicit ConvertibleToBool(int number) : number_(number) {}
2444 operator bool() const { return number_ != 0; }
2445
2446 private:
2447 int number_;
2448};
2449
2450ConvertibleToBool IsNotZero(int number) {
2451 return ConvertibleToBool(number);
2452}
2453
2454// Tests that the predicate used in Truly() may return a class that's
2455// implicitly convertible to bool, even when the class has no
2456// operator!().
2457TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2458 Matcher<int> m = Truly(IsNotZero);
2459 EXPECT_TRUE(m.Matches(1));
2460 EXPECT_FALSE(m.Matches(0));
2461}
2462
shiqiane35fdd92008-12-10 05:08:54 +00002463// Tests that Truly(predicate) can describe itself properly.
2464TEST(TrulyTest, CanDescribeSelf) {
2465 Matcher<double> m = Truly(IsPositive);
2466 EXPECT_EQ("satisfies the given predicate",
2467 Describe(m));
2468}
2469
2470// Tests that Truly(predicate) works when the matcher takes its
2471// argument by reference.
2472TEST(TrulyTest, WorksForByRefArguments) {
2473 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2474 EXPECT_TRUE(m.Matches(foo));
2475 int n = 0;
2476 EXPECT_FALSE(m.Matches(n));
2477}
2478
2479// Tests that Matches(m) is a predicate satisfied by whatever that
2480// matches matcher m.
2481TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2482 EXPECT_TRUE(Matches(Ge(0))(1));
2483 EXPECT_FALSE(Matches(Eq('a'))('b'));
2484}
2485
2486// Tests that Matches(m) works when the matcher takes its argument by
2487// reference.
2488TEST(MatchesTest, WorksOnByRefArguments) {
2489 int m = 0, n = 0;
2490 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2491 EXPECT_FALSE(Matches(Ref(m))(n));
2492}
2493
2494// Tests that a Matcher on non-reference type can be used in
2495// Matches().
2496TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
2497 Matcher<int> eq5 = Eq(5);
2498 EXPECT_TRUE(Matches(eq5)(5));
2499 EXPECT_FALSE(Matches(eq5)(2));
2500}
2501
zhanyong.wanb8243162009-06-04 05:48:20 +00002502// Tests Value(value, matcher). Since Value() is a simple wrapper for
2503// Matches(), which has been tested already, we don't spend a lot of
2504// effort on testing Value().
2505TEST(ValueTest, WorksWithPolymorphicMatcher) {
2506 EXPECT_TRUE(Value("hi", StartsWith("h")));
2507 EXPECT_FALSE(Value(5, Gt(10)));
2508}
2509
2510TEST(ValueTest, WorksWithMonomorphicMatcher) {
2511 const Matcher<int> is_zero = Eq(0);
2512 EXPECT_TRUE(Value(0, is_zero));
2513 EXPECT_FALSE(Value('a', is_zero));
2514
2515 int n = 0;
2516 const Matcher<const int&> ref_n = Ref(n);
2517 EXPECT_TRUE(Value(n, ref_n));
2518 EXPECT_FALSE(Value(1, ref_n));
2519}
2520
zhanyong.wana862f1d2010-03-15 21:23:04 +00002521TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002522 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002523 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002524 EXPECT_EQ("% 2 == 0", listener1.str());
2525
2526 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002527 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002528 EXPECT_EQ("", listener2.str());
2529}
2530
zhanyong.wana862f1d2010-03-15 21:23:04 +00002531TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002532 const Matcher<int> is_even = PolymorphicIsEven();
2533 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002534 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002535 EXPECT_EQ("% 2 == 0", listener1.str());
2536
2537 const Matcher<const double&> is_zero = Eq(0);
2538 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002539 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002540 EXPECT_EQ("", listener2.str());
2541}
2542
zhanyong.wana862f1d2010-03-15 21:23:04 +00002543MATCHER_P(Really, inner_matcher, "") {
2544 return ExplainMatchResult(inner_matcher, arg, result_listener);
2545}
2546
2547TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
2548 EXPECT_THAT(0, Really(Eq(0)));
2549}
2550
zhanyong.wanbf550852009-06-09 06:09:53 +00002551TEST(AllArgsTest, WorksForTuple) {
2552 EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
2553 EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
2554}
2555
2556TEST(AllArgsTest, WorksForNonTuple) {
2557 EXPECT_THAT(42, AllArgs(Gt(0)));
2558 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
2559}
2560
2561class AllArgsHelper {
2562 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002563 AllArgsHelper() {}
2564
zhanyong.wanbf550852009-06-09 06:09:53 +00002565 MOCK_METHOD2(Helper, int(char x, int y));
zhanyong.wan32de5f52009-12-23 00:13:23 +00002566
2567 private:
2568 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
zhanyong.wanbf550852009-06-09 06:09:53 +00002569};
2570
2571TEST(AllArgsTest, WorksInWithClause) {
2572 AllArgsHelper helper;
2573 ON_CALL(helper, Helper(_, _))
2574 .With(AllArgs(Lt()))
2575 .WillByDefault(Return(1));
2576 EXPECT_CALL(helper, Helper(_, _));
2577 EXPECT_CALL(helper, Helper(_, _))
2578 .With(AllArgs(Gt()))
2579 .WillOnce(Return(2));
2580
2581 EXPECT_EQ(1, helper.Helper('\1', 2));
2582 EXPECT_EQ(2, helper.Helper('a', 1));
2583}
2584
shiqiane35fdd92008-12-10 05:08:54 +00002585// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2586// matches the matcher.
2587TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
2588 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
2589 ASSERT_THAT("Foo", EndsWith("oo"));
2590 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
2591 EXPECT_THAT("Hello", StartsWith("Hell"));
2592}
2593
2594// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2595// doesn't match the matcher.
2596TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
2597 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
2598 // which cannot reference auto variables.
zhanyong.wan736baa82010-09-27 17:44:16 +00002599 static unsigned short n; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00002600 n = 5;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002601
2602 // VC++ prior to version 8.0 SP1 has a bug where it will not see any
2603 // functions declared in the namespace scope from within nested classes.
2604 // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
2605 // namespace-level functions invoked inside them need to be explicitly
2606 // resolved.
2607 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
shiqiane35fdd92008-12-10 05:08:54 +00002608 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002609 "Expected: is > 10\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002610 " Actual: 5" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002611 n = 0;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002612 EXPECT_NONFATAL_FAILURE(
2613 EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
2614 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002615 "Expected: (is <= 7) and (is >= 5)\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002616 " Actual: 0" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002617}
2618
2619// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
2620// has a reference type.
2621TEST(MatcherAssertionTest, WorksForByRefArguments) {
2622 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
2623 // reference auto variables.
2624 static int n;
2625 n = 0;
2626 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002627 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
shiqiane35fdd92008-12-10 05:08:54 +00002628 "Value of: n\n"
2629 "Expected: does not reference the variable @");
2630 // Tests the "Actual" part.
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002631 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
zhanyong.wan736baa82010-09-27 17:44:16 +00002632 "Actual: 0" + OfType("int") + ", which is located @");
shiqiane35fdd92008-12-10 05:08:54 +00002633}
2634
zhanyong.wan95b12332009-09-25 18:55:50 +00002635#if !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002636// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
2637// monomorphic.
zhanyong.wan95b12332009-09-25 18:55:50 +00002638
2639// ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
2640// Symbian compiler: it tries to compile
2641// template<T, U> class MatcherCastImpl { ...
zhanyong.wandb22c222010-01-28 21:52:29 +00002642// virtual bool MatchAndExplain(T x, ...) const {
2643// return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
zhanyong.wan95b12332009-09-25 18:55:50 +00002644// with U == string and T == const char*
2645// With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
2646// the compiler silently crashes with no output.
2647// If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
2648// the code compiles but the converted string is bogus.
shiqiane35fdd92008-12-10 05:08:54 +00002649TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
2650 Matcher<const char*> starts_with_he = StartsWith("he");
2651 ASSERT_THAT("hello", starts_with_he);
2652
2653 Matcher<const string&> ends_with_ok = EndsWith("ok");
2654 ASSERT_THAT("book", ends_with_ok);
zhanyong.wan736baa82010-09-27 17:44:16 +00002655 const string bad = "bad";
2656 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
2657 "Value of: bad\n"
2658 "Expected: ends with \"ok\"\n"
2659 " Actual: \"bad\"");
shiqiane35fdd92008-12-10 05:08:54 +00002660 Matcher<int> is_greater_than_5 = Gt(5);
2661 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
2662 "Value of: 5\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002663 "Expected: is > 5\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002664 " Actual: 5" + OfType("int"));
shiqiane35fdd92008-12-10 05:08:54 +00002665}
zhanyong.wan95b12332009-09-25 18:55:50 +00002666#endif // !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002667
2668// Tests floating-point matchers.
2669template <typename RawType>
2670class FloatingPointTest : public testing::Test {
2671 protected:
zhanyong.wan35877b72013-09-18 17:51:08 +00002672 typedef testing::internal::FloatingPoint<RawType> Floating;
shiqiane35fdd92008-12-10 05:08:54 +00002673 typedef typename Floating::Bits Bits;
2674
zhanyong.wan35877b72013-09-18 17:51:08 +00002675 FloatingPointTest()
2676 : max_ulps_(Floating::kMaxUlps),
2677 zero_bits_(Floating(0).bits()),
2678 one_bits_(Floating(1).bits()),
2679 infinity_bits_(Floating(Floating::Infinity()).bits()),
2680 close_to_positive_zero_(
2681 Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
2682 close_to_negative_zero_(
2683 -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
2684 further_from_negative_zero_(-Floating::ReinterpretBits(
2685 zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
2686 close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
2687 further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
2688 infinity_(Floating::Infinity()),
2689 close_to_infinity_(
2690 Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
2691 further_from_infinity_(
2692 Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
2693 max_(Floating::Max()),
2694 nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
2695 nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
shiqiane35fdd92008-12-10 05:08:54 +00002696 }
2697
2698 void TestSize() {
2699 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2700 }
2701
2702 // A battery of tests for FloatingEqMatcher::Matches.
2703 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2704 void TestMatches(
2705 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
2706 Matcher<RawType> m1 = matcher_maker(0.0);
2707 EXPECT_TRUE(m1.Matches(-0.0));
2708 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
2709 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
2710 EXPECT_FALSE(m1.Matches(1.0));
2711
2712 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
2713 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
2714
2715 Matcher<RawType> m3 = matcher_maker(1.0);
2716 EXPECT_TRUE(m3.Matches(close_to_one_));
2717 EXPECT_FALSE(m3.Matches(further_from_one_));
2718
2719 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
2720 EXPECT_FALSE(m3.Matches(0.0));
2721
2722 Matcher<RawType> m4 = matcher_maker(-infinity_);
2723 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
2724
2725 Matcher<RawType> m5 = matcher_maker(infinity_);
2726 EXPECT_TRUE(m5.Matches(close_to_infinity_));
2727
2728 // This is interesting as the representations of infinity_ and nan1_
2729 // are only 1 DLP apart.
2730 EXPECT_FALSE(m5.Matches(nan1_));
2731
2732 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2733 // some cases.
2734 Matcher<const RawType&> m6 = matcher_maker(0.0);
2735 EXPECT_TRUE(m6.Matches(-0.0));
2736 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
2737 EXPECT_FALSE(m6.Matches(1.0));
2738
2739 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2740 // cases.
2741 Matcher<RawType&> m7 = matcher_maker(0.0);
2742 RawType x = 0.0;
2743 EXPECT_TRUE(m7.Matches(x));
2744 x = 0.01f;
2745 EXPECT_FALSE(m7.Matches(x));
2746 }
2747
2748 // Pre-calculated numbers to be used by the tests.
2749
zhanyong.wan35877b72013-09-18 17:51:08 +00002750 const size_t max_ulps_;
shiqiane35fdd92008-12-10 05:08:54 +00002751
zhanyong.wan35877b72013-09-18 17:51:08 +00002752 const Bits zero_bits_; // The bits that represent 0.0.
2753 const Bits one_bits_; // The bits that represent 1.0.
2754 const Bits infinity_bits_; // The bits that represent +infinity.
shiqiane35fdd92008-12-10 05:08:54 +00002755
zhanyong.wan35877b72013-09-18 17:51:08 +00002756 // Some numbers close to 0.0.
2757 const RawType close_to_positive_zero_;
2758 const RawType close_to_negative_zero_;
2759 const RawType further_from_negative_zero_;
shiqiane35fdd92008-12-10 05:08:54 +00002760
zhanyong.wan35877b72013-09-18 17:51:08 +00002761 // Some numbers close to 1.0.
2762 const RawType close_to_one_;
2763 const RawType further_from_one_;
2764
2765 // Some numbers close to +infinity.
2766 const RawType infinity_;
2767 const RawType close_to_infinity_;
2768 const RawType further_from_infinity_;
2769
2770 // Maximum representable value that's not infinity.
2771 const RawType max_;
2772
2773 // Some NaNs.
2774 const RawType nan1_;
2775 const RawType nan2_;
shiqiane35fdd92008-12-10 05:08:54 +00002776};
2777
zhanyong.wan616180e2013-06-18 18:49:51 +00002778// Tests floating-point matchers with fixed epsilons.
2779template <typename RawType>
2780class FloatingPointNearTest : public FloatingPointTest<RawType> {
2781 protected:
2782 typedef FloatingPointTest<RawType> ParentType;
2783
2784 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
2785 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2786 void TestNearMatches(
2787 testing::internal::FloatingEqMatcher<RawType>
2788 (*matcher_maker)(RawType, RawType)) {
2789 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
2790 EXPECT_TRUE(m1.Matches(0.0));
2791 EXPECT_TRUE(m1.Matches(-0.0));
2792 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
2793 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
2794 EXPECT_FALSE(m1.Matches(1.0));
2795
2796 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
2797 EXPECT_TRUE(m2.Matches(0.0));
2798 EXPECT_TRUE(m2.Matches(-0.0));
2799 EXPECT_TRUE(m2.Matches(1.0));
2800 EXPECT_TRUE(m2.Matches(-1.0));
2801 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
2802 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
2803
2804 // Check that inf matches inf, regardless of the of the specified max
2805 // absolute error.
2806 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
2807 EXPECT_TRUE(m3.Matches(ParentType::infinity_));
2808 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
2809 EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
2810
2811 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
2812 EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
2813 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
2814 EXPECT_FALSE(m4.Matches(ParentType::infinity_));
2815
2816 // Test various overflow scenarios.
zhanyong.wan35877b72013-09-18 17:51:08 +00002817 Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
2818 EXPECT_TRUE(m5.Matches(ParentType::max_));
2819 EXPECT_FALSE(m5.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002820
zhanyong.wan35877b72013-09-18 17:51:08 +00002821 Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
2822 EXPECT_FALSE(m6.Matches(ParentType::max_));
2823 EXPECT_TRUE(m6.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002824
zhanyong.wan35877b72013-09-18 17:51:08 +00002825 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
2826 EXPECT_TRUE(m7.Matches(ParentType::max_));
2827 EXPECT_FALSE(m7.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002828
zhanyong.wan35877b72013-09-18 17:51:08 +00002829 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
2830 EXPECT_FALSE(m8.Matches(ParentType::max_));
2831 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002832
2833 // The difference between max() and -max() normally overflows to infinity,
2834 // but it should still match if the max_abs_error is also infinity.
2835 Matcher<RawType> m9 = matcher_maker(
zhanyong.wan35877b72013-09-18 17:51:08 +00002836 ParentType::max_, ParentType::infinity_);
2837 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002838
2839 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2840 // some cases.
2841 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
2842 EXPECT_TRUE(m10.Matches(-0.0));
2843 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
2844 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
2845
2846 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2847 // cases.
2848 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
2849 RawType x = 0.0;
2850 EXPECT_TRUE(m11.Matches(x));
2851 x = 1.0f;
2852 EXPECT_TRUE(m11.Matches(x));
2853 x = -1.0f;
2854 EXPECT_TRUE(m11.Matches(x));
2855 x = 1.1f;
2856 EXPECT_FALSE(m11.Matches(x));
2857 x = -1.1f;
2858 EXPECT_FALSE(m11.Matches(x));
2859 }
2860};
2861
shiqiane35fdd92008-12-10 05:08:54 +00002862// Instantiate FloatingPointTest for testing floats.
2863typedef FloatingPointTest<float> FloatTest;
2864
2865TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
2866 TestMatches(&FloatEq);
2867}
2868
2869TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
2870 TestMatches(&NanSensitiveFloatEq);
2871}
2872
2873TEST_F(FloatTest, FloatEqCannotMatchNaN) {
2874 // FloatEq never matches NaN.
2875 Matcher<float> m = FloatEq(nan1_);
2876 EXPECT_FALSE(m.Matches(nan1_));
2877 EXPECT_FALSE(m.Matches(nan2_));
2878 EXPECT_FALSE(m.Matches(1.0));
2879}
2880
2881TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
2882 // NanSensitiveFloatEq will match NaN.
2883 Matcher<float> m = NanSensitiveFloatEq(nan1_);
2884 EXPECT_TRUE(m.Matches(nan1_));
2885 EXPECT_TRUE(m.Matches(nan2_));
2886 EXPECT_FALSE(m.Matches(1.0));
2887}
2888
2889TEST_F(FloatTest, FloatEqCanDescribeSelf) {
2890 Matcher<float> m1 = FloatEq(2.0f);
2891 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002892 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002893
2894 Matcher<float> m2 = FloatEq(0.5f);
2895 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002896 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002897
2898 Matcher<float> m3 = FloatEq(nan1_);
2899 EXPECT_EQ("never matches", Describe(m3));
2900 EXPECT_EQ("is anything", DescribeNegation(m3));
2901}
2902
2903TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
2904 Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
2905 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002906 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002907
2908 Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
2909 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002910 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002911
2912 Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
2913 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002914 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00002915}
2916
zhanyong.wan616180e2013-06-18 18:49:51 +00002917// Instantiate FloatingPointTest for testing floats with a user-specified
2918// max absolute error.
2919typedef FloatingPointNearTest<float> FloatNearTest;
2920
2921TEST_F(FloatNearTest, FloatNearMatches) {
2922 TestNearMatches(&FloatNear);
2923}
2924
2925TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
2926 TestNearMatches(&NanSensitiveFloatNear);
2927}
2928
2929TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
2930 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
2931 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2932 EXPECT_EQ(
2933 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2934
2935 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
2936 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2937 EXPECT_EQ(
2938 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2939
2940 Matcher<float> m3 = FloatNear(nan1_, 0.0);
2941 EXPECT_EQ("never matches", Describe(m3));
2942 EXPECT_EQ("is anything", DescribeNegation(m3));
2943}
2944
2945TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
2946 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
2947 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2948 EXPECT_EQ(
2949 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2950
2951 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
2952 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2953 EXPECT_EQ(
2954 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2955
2956 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
2957 EXPECT_EQ("is NaN", Describe(m3));
2958 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
2959}
2960
2961TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
2962 // FloatNear never matches NaN.
2963 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
2964 EXPECT_FALSE(m.Matches(nan1_));
2965 EXPECT_FALSE(m.Matches(nan2_));
2966 EXPECT_FALSE(m.Matches(1.0));
2967}
2968
2969TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
2970 // NanSensitiveFloatNear will match NaN.
2971 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
2972 EXPECT_TRUE(m.Matches(nan1_));
2973 EXPECT_TRUE(m.Matches(nan2_));
2974 EXPECT_FALSE(m.Matches(1.0));
2975}
2976
shiqiane35fdd92008-12-10 05:08:54 +00002977// Instantiate FloatingPointTest for testing doubles.
2978typedef FloatingPointTest<double> DoubleTest;
2979
2980TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
2981 TestMatches(&DoubleEq);
2982}
2983
2984TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
2985 TestMatches(&NanSensitiveDoubleEq);
2986}
2987
2988TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
2989 // DoubleEq never matches NaN.
2990 Matcher<double> m = DoubleEq(nan1_);
2991 EXPECT_FALSE(m.Matches(nan1_));
2992 EXPECT_FALSE(m.Matches(nan2_));
2993 EXPECT_FALSE(m.Matches(1.0));
2994}
2995
2996TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
2997 // NanSensitiveDoubleEq will match NaN.
2998 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
2999 EXPECT_TRUE(m.Matches(nan1_));
3000 EXPECT_TRUE(m.Matches(nan2_));
3001 EXPECT_FALSE(m.Matches(1.0));
3002}
3003
3004TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3005 Matcher<double> m1 = DoubleEq(2.0);
3006 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003007 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003008
3009 Matcher<double> m2 = DoubleEq(0.5);
3010 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003011 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003012
3013 Matcher<double> m3 = DoubleEq(nan1_);
3014 EXPECT_EQ("never matches", Describe(m3));
3015 EXPECT_EQ("is anything", DescribeNegation(m3));
3016}
3017
3018TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3019 Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3020 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003021 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003022
3023 Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3024 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003025 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003026
3027 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3028 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003029 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00003030}
3031
zhanyong.wan616180e2013-06-18 18:49:51 +00003032// Instantiate FloatingPointTest for testing floats with a user-specified
3033// max absolute error.
3034typedef FloatingPointNearTest<double> DoubleNearTest;
3035
3036TEST_F(DoubleNearTest, DoubleNearMatches) {
3037 TestNearMatches(&DoubleNear);
3038}
3039
3040TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3041 TestNearMatches(&NanSensitiveDoubleNear);
3042}
3043
3044TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3045 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3046 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3047 EXPECT_EQ(
3048 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3049
3050 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3051 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3052 EXPECT_EQ(
3053 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3054
3055 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3056 EXPECT_EQ("never matches", Describe(m3));
3057 EXPECT_EQ("is anything", DescribeNegation(m3));
3058}
3059
3060TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3061 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3062 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3063 EXPECT_EQ(
3064 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3065
3066 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3067 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3068 EXPECT_EQ(
3069 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3070
3071 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3072 EXPECT_EQ("is NaN", Describe(m3));
3073 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3074}
3075
3076TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3077 // DoubleNear never matches NaN.
3078 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3079 EXPECT_FALSE(m.Matches(nan1_));
3080 EXPECT_FALSE(m.Matches(nan2_));
3081 EXPECT_FALSE(m.Matches(1.0));
3082}
3083
3084TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3085 // NanSensitiveDoubleNear will match NaN.
3086 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3087 EXPECT_TRUE(m.Matches(nan1_));
3088 EXPECT_TRUE(m.Matches(nan2_));
3089 EXPECT_FALSE(m.Matches(1.0));
3090}
3091
shiqiane35fdd92008-12-10 05:08:54 +00003092TEST(PointeeTest, RawPointer) {
3093 const Matcher<int*> m = Pointee(Ge(0));
3094
3095 int n = 1;
3096 EXPECT_TRUE(m.Matches(&n));
3097 n = -1;
3098 EXPECT_FALSE(m.Matches(&n));
3099 EXPECT_FALSE(m.Matches(NULL));
3100}
3101
3102TEST(PointeeTest, RawPointerToConst) {
3103 const Matcher<const double*> m = Pointee(Ge(0));
3104
3105 double x = 1;
3106 EXPECT_TRUE(m.Matches(&x));
3107 x = -1;
3108 EXPECT_FALSE(m.Matches(&x));
3109 EXPECT_FALSE(m.Matches(NULL));
3110}
3111
3112TEST(PointeeTest, ReferenceToConstRawPointer) {
3113 const Matcher<int* const &> m = Pointee(Ge(0));
3114
3115 int n = 1;
3116 EXPECT_TRUE(m.Matches(&n));
3117 n = -1;
3118 EXPECT_FALSE(m.Matches(&n));
3119 EXPECT_FALSE(m.Matches(NULL));
3120}
3121
3122TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3123 const Matcher<double* &> m = Pointee(Ge(0));
3124
3125 double x = 1.0;
3126 double* p = &x;
3127 EXPECT_TRUE(m.Matches(p));
3128 x = -1;
3129 EXPECT_FALSE(m.Matches(p));
3130 p = NULL;
3131 EXPECT_FALSE(m.Matches(p));
3132}
3133
vladlosevada23472012-08-14 15:38:49 +00003134// Minimal const-propagating pointer.
3135template <typename T>
3136class ConstPropagatingPtr {
3137 public:
3138 typedef T element_type;
3139
3140 ConstPropagatingPtr() : val_() {}
3141 explicit ConstPropagatingPtr(T* t) : val_(t) {}
3142 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3143
3144 T* get() { return val_; }
3145 T& operator*() { return *val_; }
3146 // Most smart pointers return non-const T* and T& from the next methods.
3147 const T* get() const { return val_; }
3148 const T& operator*() const { return *val_; }
3149
3150 private:
3151 T* val_;
3152};
3153
3154TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3155 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3156 int three = 3;
3157 const ConstPropagatingPtr<int> co(&three);
3158 ConstPropagatingPtr<int> o(&three);
3159 EXPECT_TRUE(m.Matches(o));
3160 EXPECT_TRUE(m.Matches(co));
3161 *o = 6;
3162 EXPECT_FALSE(m.Matches(o));
3163 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3164}
3165
shiqiane35fdd92008-12-10 05:08:54 +00003166TEST(PointeeTest, NeverMatchesNull) {
3167 const Matcher<const char*> m = Pointee(_);
3168 EXPECT_FALSE(m.Matches(NULL));
3169}
3170
3171// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3172TEST(PointeeTest, MatchesAgainstAValue) {
3173 const Matcher<int*> m = Pointee(5);
3174
3175 int n = 5;
3176 EXPECT_TRUE(m.Matches(&n));
3177 n = -1;
3178 EXPECT_FALSE(m.Matches(&n));
3179 EXPECT_FALSE(m.Matches(NULL));
3180}
3181
3182TEST(PointeeTest, CanDescribeSelf) {
3183 const Matcher<int*> m = Pointee(Gt(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003184 EXPECT_EQ("points to a value that is > 3", Describe(m));
3185 EXPECT_EQ("does not point to a value that is > 3",
shiqiane35fdd92008-12-10 05:08:54 +00003186 DescribeNegation(m));
3187}
3188
shiqiane35fdd92008-12-10 05:08:54 +00003189TEST(PointeeTest, CanExplainMatchResult) {
3190 const Matcher<const string*> m = Pointee(StartsWith("Hi"));
3191
3192 EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL)));
3193
zhanyong.wan736baa82010-09-27 17:44:16 +00003194 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
3195 long n = 3; // NOLINT
3196 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003197 Explain(m2, &n));
3198}
3199
3200TEST(PointeeTest, AlwaysExplainsPointee) {
3201 const Matcher<int*> m = Pointee(0);
3202 int n = 42;
zhanyong.wan736baa82010-09-27 17:44:16 +00003203 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
shiqiane35fdd92008-12-10 05:08:54 +00003204}
3205
3206// An uncopyable class.
3207class Uncopyable {
3208 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003209 explicit Uncopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003210
3211 int value() const { return value_; }
3212 private:
3213 const int value_;
3214 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3215};
3216
3217// Returns true iff x.value() is positive.
3218bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3219
3220// A user-defined struct for testing Field().
3221struct AStruct {
3222 AStruct() : x(0), y(1.0), z(5), p(NULL) {}
3223 AStruct(const AStruct& rhs)
3224 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3225
3226 int x; // A non-const field.
3227 const double y; // A const field.
3228 Uncopyable z; // An uncopyable field.
3229 const char* p; // A pointer field.
zhanyong.wan32de5f52009-12-23 00:13:23 +00003230
3231 private:
3232 GTEST_DISALLOW_ASSIGN_(AStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003233};
3234
3235// A derived struct for testing Field().
3236struct DerivedStruct : public AStruct {
3237 char ch;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003238
3239 private:
3240 GTEST_DISALLOW_ASSIGN_(DerivedStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003241};
3242
3243// Tests that Field(&Foo::field, ...) works when field is non-const.
3244TEST(FieldTest, WorksForNonConstField) {
3245 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
3246
3247 AStruct a;
3248 EXPECT_TRUE(m.Matches(a));
3249 a.x = -1;
3250 EXPECT_FALSE(m.Matches(a));
3251}
3252
3253// Tests that Field(&Foo::field, ...) works when field is const.
3254TEST(FieldTest, WorksForConstField) {
3255 AStruct a;
3256
3257 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
3258 EXPECT_TRUE(m.Matches(a));
3259 m = Field(&AStruct::y, Le(0.0));
3260 EXPECT_FALSE(m.Matches(a));
3261}
3262
3263// Tests that Field(&Foo::field, ...) works when field is not copyable.
3264TEST(FieldTest, WorksForUncopyableField) {
3265 AStruct a;
3266
3267 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3268 EXPECT_TRUE(m.Matches(a));
3269 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3270 EXPECT_FALSE(m.Matches(a));
3271}
3272
3273// Tests that Field(&Foo::field, ...) works when field is a pointer.
3274TEST(FieldTest, WorksForPointerField) {
3275 // Matching against NULL.
3276 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
3277 AStruct a;
3278 EXPECT_TRUE(m.Matches(a));
3279 a.p = "hi";
3280 EXPECT_FALSE(m.Matches(a));
3281
3282 // Matching a pointer that is not NULL.
3283 m = Field(&AStruct::p, StartsWith("hi"));
3284 a.p = "hill";
3285 EXPECT_TRUE(m.Matches(a));
3286 a.p = "hole";
3287 EXPECT_FALSE(m.Matches(a));
3288}
3289
3290// Tests that Field() works when the object is passed by reference.
3291TEST(FieldTest, WorksForByRefArgument) {
3292 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3293
3294 AStruct a;
3295 EXPECT_TRUE(m.Matches(a));
3296 a.x = -1;
3297 EXPECT_FALSE(m.Matches(a));
3298}
3299
3300// Tests that Field(&Foo::field, ...) works when the argument's type
3301// is a sub-type of Foo.
3302TEST(FieldTest, WorksForArgumentOfSubType) {
3303 // Note that the matcher expects DerivedStruct but we say AStruct
3304 // inside Field().
3305 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
3306
3307 DerivedStruct d;
3308 EXPECT_TRUE(m.Matches(d));
3309 d.x = -1;
3310 EXPECT_FALSE(m.Matches(d));
3311}
3312
3313// Tests that Field(&Foo::field, m) works when field's type and m's
3314// argument type are compatible but not the same.
3315TEST(FieldTest, WorksForCompatibleMatcherType) {
3316 // The field is an int, but the inner matcher expects a signed char.
3317 Matcher<const AStruct&> m = Field(&AStruct::x,
3318 Matcher<signed char>(Ge(0)));
3319
3320 AStruct a;
3321 EXPECT_TRUE(m.Matches(a));
3322 a.x = -1;
3323 EXPECT_FALSE(m.Matches(a));
3324}
3325
3326// Tests that Field() can describe itself.
3327TEST(FieldTest, CanDescribeSelf) {
3328 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3329
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003330 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3331 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003332}
3333
3334// Tests that Field() can explain the match result.
3335TEST(FieldTest, CanExplainMatchResult) {
3336 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3337
3338 AStruct a;
3339 a.x = 1;
zhanyong.wan736baa82010-09-27 17:44:16 +00003340 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003341
3342 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003343 EXPECT_EQ(
3344 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
3345 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003346}
3347
3348// Tests that Field() works when the argument is a pointer to const.
3349TEST(FieldForPointerTest, WorksForPointerToConst) {
3350 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3351
3352 AStruct a;
3353 EXPECT_TRUE(m.Matches(&a));
3354 a.x = -1;
3355 EXPECT_FALSE(m.Matches(&a));
3356}
3357
3358// Tests that Field() works when the argument is a pointer to non-const.
3359TEST(FieldForPointerTest, WorksForPointerToNonConst) {
3360 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
3361
3362 AStruct a;
3363 EXPECT_TRUE(m.Matches(&a));
3364 a.x = -1;
3365 EXPECT_FALSE(m.Matches(&a));
3366}
3367
zhanyong.wan6953a722010-01-13 05:15:07 +00003368// Tests that Field() works when the argument is a reference to a const pointer.
3369TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
3370 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
3371
3372 AStruct a;
3373 EXPECT_TRUE(m.Matches(&a));
3374 a.x = -1;
3375 EXPECT_FALSE(m.Matches(&a));
3376}
3377
shiqiane35fdd92008-12-10 05:08:54 +00003378// Tests that Field() does not match the NULL pointer.
3379TEST(FieldForPointerTest, DoesNotMatchNull) {
3380 Matcher<const AStruct*> m = Field(&AStruct::x, _);
3381 EXPECT_FALSE(m.Matches(NULL));
3382}
3383
3384// Tests that Field(&Foo::field, ...) works when the argument's type
3385// is a sub-type of const Foo*.
3386TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
3387 // Note that the matcher expects DerivedStruct but we say AStruct
3388 // inside Field().
3389 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
3390
3391 DerivedStruct d;
3392 EXPECT_TRUE(m.Matches(&d));
3393 d.x = -1;
3394 EXPECT_FALSE(m.Matches(&d));
3395}
3396
3397// Tests that Field() can describe itself when used to match a pointer.
3398TEST(FieldForPointerTest, CanDescribeSelf) {
3399 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3400
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003401 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3402 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003403}
3404
3405// Tests that Field() can explain the result of matching a pointer.
3406TEST(FieldForPointerTest, CanExplainMatchResult) {
3407 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3408
3409 AStruct a;
3410 a.x = 1;
3411 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003412 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
3413 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003414
3415 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003416 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
3417 ", which is 1 more than 0", Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003418}
3419
3420// A user-defined class for testing Property().
3421class AClass {
3422 public:
3423 AClass() : n_(0) {}
3424
3425 // A getter that returns a non-reference.
3426 int n() const { return n_; }
3427
3428 void set_n(int new_n) { n_ = new_n; }
3429
3430 // A getter that returns a reference to const.
3431 const string& s() const { return s_; }
3432
3433 void set_s(const string& new_s) { s_ = new_s; }
3434
3435 // A getter that returns a reference to non-const.
3436 double& x() const { return x_; }
3437 private:
3438 int n_;
3439 string s_;
3440
3441 static double x_;
3442};
3443
3444double AClass::x_ = 0.0;
3445
3446// A derived class for testing Property().
3447class DerivedClass : public AClass {
kosak6414d802013-12-03 23:19:36 +00003448 public:
3449 int k() const { return k_; }
shiqiane35fdd92008-12-10 05:08:54 +00003450 private:
3451 int k_;
3452};
3453
3454// Tests that Property(&Foo::property, ...) works when property()
3455// returns a non-reference.
3456TEST(PropertyTest, WorksForNonReferenceProperty) {
3457 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3458
3459 AClass a;
3460 a.set_n(1);
3461 EXPECT_TRUE(m.Matches(a));
3462
3463 a.set_n(-1);
3464 EXPECT_FALSE(m.Matches(a));
3465}
3466
3467// Tests that Property(&Foo::property, ...) works when property()
3468// returns a reference to const.
3469TEST(PropertyTest, WorksForReferenceToConstProperty) {
3470 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
3471
3472 AClass a;
3473 a.set_s("hill");
3474 EXPECT_TRUE(m.Matches(a));
3475
3476 a.set_s("hole");
3477 EXPECT_FALSE(m.Matches(a));
3478}
3479
3480// Tests that Property(&Foo::property, ...) works when property()
3481// returns a reference to non-const.
3482TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
3483 double x = 0.0;
3484 AClass a;
3485
3486 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
3487 EXPECT_FALSE(m.Matches(a));
3488
3489 m = Property(&AClass::x, Not(Ref(x)));
3490 EXPECT_TRUE(m.Matches(a));
3491}
3492
3493// Tests that Property(&Foo::property, ...) works when the argument is
3494// passed by value.
3495TEST(PropertyTest, WorksForByValueArgument) {
3496 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
3497
3498 AClass a;
3499 a.set_s("hill");
3500 EXPECT_TRUE(m.Matches(a));
3501
3502 a.set_s("hole");
3503 EXPECT_FALSE(m.Matches(a));
3504}
3505
3506// Tests that Property(&Foo::property, ...) works when the argument's
3507// type is a sub-type of Foo.
3508TEST(PropertyTest, WorksForArgumentOfSubType) {
3509 // The matcher expects a DerivedClass, but inside the Property() we
3510 // say AClass.
3511 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
3512
3513 DerivedClass d;
3514 d.set_n(1);
3515 EXPECT_TRUE(m.Matches(d));
3516
3517 d.set_n(-1);
3518 EXPECT_FALSE(m.Matches(d));
3519}
3520
3521// Tests that Property(&Foo::property, m) works when property()'s type
3522// and m's argument type are compatible but different.
3523TEST(PropertyTest, WorksForCompatibleMatcherType) {
3524 // n() returns an int but the inner matcher expects a signed char.
3525 Matcher<const AClass&> m = Property(&AClass::n,
3526 Matcher<signed char>(Ge(0)));
3527
3528 AClass a;
3529 EXPECT_TRUE(m.Matches(a));
3530 a.set_n(-1);
3531 EXPECT_FALSE(m.Matches(a));
3532}
3533
3534// Tests that Property() can describe itself.
3535TEST(PropertyTest, CanDescribeSelf) {
3536 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3537
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003538 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3539 EXPECT_EQ("is an object whose given property isn't >= 0",
3540 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003541}
3542
3543// Tests that Property() can explain the match result.
3544TEST(PropertyTest, CanExplainMatchResult) {
3545 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3546
3547 AClass a;
3548 a.set_n(1);
zhanyong.wan736baa82010-09-27 17:44:16 +00003549 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003550
3551 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003552 EXPECT_EQ(
3553 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
3554 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003555}
3556
3557// Tests that Property() works when the argument is a pointer to const.
3558TEST(PropertyForPointerTest, WorksForPointerToConst) {
3559 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3560
3561 AClass a;
3562 a.set_n(1);
3563 EXPECT_TRUE(m.Matches(&a));
3564
3565 a.set_n(-1);
3566 EXPECT_FALSE(m.Matches(&a));
3567}
3568
3569// Tests that Property() works when the argument is a pointer to non-const.
3570TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
3571 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
3572
3573 AClass a;
3574 a.set_s("hill");
3575 EXPECT_TRUE(m.Matches(&a));
3576
3577 a.set_s("hole");
3578 EXPECT_FALSE(m.Matches(&a));
3579}
3580
zhanyong.wan6953a722010-01-13 05:15:07 +00003581// Tests that Property() works when the argument is a reference to a
3582// const pointer.
3583TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
3584 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
3585
3586 AClass a;
3587 a.set_s("hill");
3588 EXPECT_TRUE(m.Matches(&a));
3589
3590 a.set_s("hole");
3591 EXPECT_FALSE(m.Matches(&a));
3592}
3593
shiqiane35fdd92008-12-10 05:08:54 +00003594// Tests that Property() does not match the NULL pointer.
3595TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
3596 Matcher<const AClass*> m = Property(&AClass::x, _);
3597 EXPECT_FALSE(m.Matches(NULL));
3598}
3599
3600// Tests that Property(&Foo::property, ...) works when the argument's
3601// type is a sub-type of const Foo*.
3602TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
3603 // The matcher expects a DerivedClass, but inside the Property() we
3604 // say AClass.
3605 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
3606
3607 DerivedClass d;
3608 d.set_n(1);
3609 EXPECT_TRUE(m.Matches(&d));
3610
3611 d.set_n(-1);
3612 EXPECT_FALSE(m.Matches(&d));
3613}
3614
3615// Tests that Property() can describe itself when used to match a pointer.
3616TEST(PropertyForPointerTest, CanDescribeSelf) {
3617 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3618
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003619 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3620 EXPECT_EQ("is an object whose given property isn't >= 0",
3621 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003622}
3623
3624// Tests that Property() can explain the result of matching a pointer.
3625TEST(PropertyForPointerTest, CanExplainMatchResult) {
3626 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3627
3628 AClass a;
3629 a.set_n(1);
3630 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003631 EXPECT_EQ(
3632 "which points to an object whose given property is 1" + OfType("int"),
3633 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003634
3635 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003636 EXPECT_EQ("which points to an object whose given property is 1" +
3637 OfType("int") + ", which is 1 more than 0",
3638 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003639}
3640
3641// Tests ResultOf.
3642
3643// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3644// function pointer.
3645string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; }
3646
3647TEST(ResultOfTest, WorksForFunctionPointers) {
3648 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo")));
3649
3650 EXPECT_TRUE(matcher.Matches(1));
3651 EXPECT_FALSE(matcher.Matches(2));
3652}
3653
3654// Tests that ResultOf() can describe itself.
3655TEST(ResultOfTest, CanDescribeItself) {
3656 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
3657
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003658 EXPECT_EQ("is mapped by the given callable to a value that "
3659 "is equal to \"foo\"", Describe(matcher));
3660 EXPECT_EQ("is mapped by the given callable to a value that "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003661 "isn't equal to \"foo\"", DescribeNegation(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00003662}
3663
3664// Tests that ResultOf() can explain the match result.
3665int IntFunction(int input) { return input == 42 ? 80 : 90; }
3666
3667TEST(ResultOfTest, CanExplainMatchResult) {
3668 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003669 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003670 Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003671
3672 matcher = ResultOf(&IntFunction, GreaterThan(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003673 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
3674 ", which is 5 more than 85", Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003675}
3676
3677// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3678// returns a non-reference.
3679TEST(ResultOfTest, WorksForNonReferenceResults) {
3680 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
3681
3682 EXPECT_TRUE(matcher.Matches(42));
3683 EXPECT_FALSE(matcher.Matches(36));
3684}
3685
3686// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3687// returns a reference to non-const.
zhanyong.wan736baa82010-09-27 17:44:16 +00003688double& DoubleFunction(double& input) { return input; } // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003689
zhanyong.wan736baa82010-09-27 17:44:16 +00003690Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003691 return obj;
3692}
3693
3694TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
3695 double x = 3.14;
3696 double x2 = x;
3697 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
3698
3699 EXPECT_TRUE(matcher.Matches(x));
3700 EXPECT_FALSE(matcher.Matches(x2));
3701
3702 // Test that ResultOf works with uncopyable objects
3703 Uncopyable obj(0);
3704 Uncopyable obj2(0);
3705 Matcher<Uncopyable&> matcher2 =
3706 ResultOf(&RefUncopyableFunction, Ref(obj));
3707
3708 EXPECT_TRUE(matcher2.Matches(obj));
3709 EXPECT_FALSE(matcher2.Matches(obj2));
3710}
3711
3712// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3713// returns a reference to const.
3714const string& StringFunction(const string& input) { return input; }
3715
3716TEST(ResultOfTest, WorksForReferenceToConstResults) {
3717 string s = "foo";
3718 string s2 = s;
3719 Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s));
3720
3721 EXPECT_TRUE(matcher.Matches(s));
3722 EXPECT_FALSE(matcher.Matches(s2));
3723}
3724
3725// Tests that ResultOf(f, m) works when f(x) and m's
3726// argument types are compatible but different.
3727TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
3728 // IntFunction() returns int but the inner matcher expects a signed char.
3729 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
3730
3731 EXPECT_TRUE(matcher.Matches(36));
3732 EXPECT_FALSE(matcher.Matches(42));
3733}
3734
shiqiane35fdd92008-12-10 05:08:54 +00003735// Tests that the program aborts when ResultOf is passed
3736// a NULL function pointer.
3737TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
zhanyong.wan04d6ed82009-09-11 07:01:08 +00003738 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan736baa82010-09-27 17:44:16 +00003739 ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))),
shiqiane35fdd92008-12-10 05:08:54 +00003740 "NULL function pointer is passed into ResultOf\\(\\)\\.");
3741}
shiqiane35fdd92008-12-10 05:08:54 +00003742
3743// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3744// function reference.
3745TEST(ResultOfTest, WorksForFunctionReferences) {
3746 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
3747 EXPECT_TRUE(matcher.Matches(1));
3748 EXPECT_FALSE(matcher.Matches(2));
3749}
3750
3751// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3752// function object.
3753struct Functor : public ::std::unary_function<int, string> {
3754 result_type operator()(argument_type input) const {
3755 return IntToStringFunction(input);
3756 }
3757};
3758
3759TEST(ResultOfTest, WorksForFunctors) {
3760 Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo")));
3761
3762 EXPECT_TRUE(matcher.Matches(1));
3763 EXPECT_FALSE(matcher.Matches(2));
3764}
3765
3766// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3767// functor with more then one operator() defined. ResultOf() must work
3768// for each defined operator().
3769struct PolymorphicFunctor {
3770 typedef int result_type;
3771 int operator()(int n) { return n; }
3772 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
3773};
3774
3775TEST(ResultOfTest, WorksForPolymorphicFunctors) {
3776 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
3777
3778 EXPECT_TRUE(matcher_int.Matches(10));
3779 EXPECT_FALSE(matcher_int.Matches(2));
3780
3781 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
3782
3783 EXPECT_TRUE(matcher_string.Matches("long string"));
3784 EXPECT_FALSE(matcher_string.Matches("shrt"));
3785}
3786
3787const int* ReferencingFunction(const int& n) { return &n; }
3788
3789struct ReferencingFunctor {
3790 typedef const int* result_type;
3791 result_type operator()(const int& n) { return &n; }
3792};
3793
3794TEST(ResultOfTest, WorksForReferencingCallables) {
3795 const int n = 1;
3796 const int n2 = 1;
3797 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
3798 EXPECT_TRUE(matcher2.Matches(n));
3799 EXPECT_FALSE(matcher2.Matches(n2));
3800
3801 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
3802 EXPECT_TRUE(matcher3.Matches(n));
3803 EXPECT_FALSE(matcher3.Matches(n2));
3804}
3805
shiqiane35fdd92008-12-10 05:08:54 +00003806class DivisibleByImpl {
3807 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003808 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
shiqiane35fdd92008-12-10 05:08:54 +00003809
zhanyong.wandb22c222010-01-28 21:52:29 +00003810 // For testing using ExplainMatchResultTo() with polymorphic matchers.
shiqiane35fdd92008-12-10 05:08:54 +00003811 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00003812 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003813 *listener << "which is " << (n % divider_) << " modulo "
zhanyong.wandb22c222010-01-28 21:52:29 +00003814 << divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003815 return (n % divider_) == 0;
3816 }
3817
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003818 void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003819 *os << "is divisible by " << divider_;
3820 }
3821
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003822 void DescribeNegationTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003823 *os << "is not divisible by " << divider_;
3824 }
3825
zhanyong.wan32de5f52009-12-23 00:13:23 +00003826 void set_divider(int a_divider) { divider_ = a_divider; }
shiqiane35fdd92008-12-10 05:08:54 +00003827 int divider() const { return divider_; }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003828
shiqiane35fdd92008-12-10 05:08:54 +00003829 private:
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003830 int divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003831};
3832
shiqiane35fdd92008-12-10 05:08:54 +00003833PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
3834 return MakePolymorphicMatcher(DivisibleByImpl(n));
3835}
3836
3837// Tests that when AllOf() fails, only the first failing matcher is
3838// asked to explain why.
3839TEST(ExplainMatchResultTest, AllOf_False_False) {
3840 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003841 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00003842}
3843
3844// Tests that when AllOf() fails, only the first failing matcher is
3845// asked to explain why.
3846TEST(ExplainMatchResultTest, AllOf_False_True) {
3847 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003848 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003849}
3850
3851// Tests that when AllOf() fails, only the first failing matcher is
3852// asked to explain why.
3853TEST(ExplainMatchResultTest, AllOf_True_False) {
3854 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003855 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00003856}
3857
3858// Tests that when AllOf() succeeds, all matchers are asked to explain
3859// why.
3860TEST(ExplainMatchResultTest, AllOf_True_True) {
3861 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003862 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003863}
3864
3865TEST(ExplainMatchResultTest, AllOf_True_True_2) {
3866 const Matcher<int> m = AllOf(Ge(2), Le(3));
3867 EXPECT_EQ("", Explain(m, 2));
3868}
3869
3870TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
3871 const Matcher<int> m = GreaterThan(5);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003872 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003873}
3874
3875// The following two tests verify that values without a public copy
3876// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
3877// with the help of ByRef().
3878
3879class NotCopyable {
3880 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003881 explicit NotCopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003882
3883 int value() const { return value_; }
3884
3885 bool operator==(const NotCopyable& rhs) const {
3886 return value() == rhs.value();
3887 }
3888
3889 bool operator>=(const NotCopyable& rhs) const {
3890 return value() >= rhs.value();
3891 }
3892 private:
3893 int value_;
3894
3895 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
3896};
3897
3898TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
3899 const NotCopyable const_value1(1);
3900 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
3901
3902 const NotCopyable n1(1), n2(2);
3903 EXPECT_TRUE(m.Matches(n1));
3904 EXPECT_FALSE(m.Matches(n2));
3905}
3906
3907TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
3908 NotCopyable value2(2);
3909 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
3910
3911 NotCopyable n1(1), n2(2);
3912 EXPECT_FALSE(m.Matches(n1));
3913 EXPECT_TRUE(m.Matches(n2));
3914}
3915
zhanyong.wan320814a2013-03-01 00:20:30 +00003916TEST(IsEmptyTest, ImplementsIsEmpty) {
3917 vector<int> container;
3918 EXPECT_THAT(container, IsEmpty());
3919 container.push_back(0);
3920 EXPECT_THAT(container, Not(IsEmpty()));
3921 container.push_back(1);
3922 EXPECT_THAT(container, Not(IsEmpty()));
3923}
3924
3925TEST(IsEmptyTest, WorksWithString) {
3926 string text;
3927 EXPECT_THAT(text, IsEmpty());
3928 text = "foo";
3929 EXPECT_THAT(text, Not(IsEmpty()));
3930 text = string("\0", 1);
3931 EXPECT_THAT(text, Not(IsEmpty()));
3932}
3933
3934TEST(IsEmptyTest, CanDescribeSelf) {
3935 Matcher<vector<int> > m = IsEmpty();
3936 EXPECT_EQ("is empty", Describe(m));
3937 EXPECT_EQ("isn't empty", DescribeNegation(m));
3938}
3939
3940TEST(IsEmptyTest, ExplainsResult) {
3941 Matcher<vector<int> > m = IsEmpty();
3942 vector<int> container;
3943 EXPECT_EQ("", Explain(m, container));
3944 container.push_back(0);
3945 EXPECT_EQ("whose size is 1", Explain(m, container));
3946}
3947
zhanyong.wana31d9ce2013-03-01 01:50:17 +00003948TEST(SizeIsTest, ImplementsSizeIs) {
3949 vector<int> container;
3950 EXPECT_THAT(container, SizeIs(0));
3951 EXPECT_THAT(container, Not(SizeIs(1)));
3952 container.push_back(0);
3953 EXPECT_THAT(container, Not(SizeIs(0)));
3954 EXPECT_THAT(container, SizeIs(1));
3955 container.push_back(0);
3956 EXPECT_THAT(container, Not(SizeIs(0)));
3957 EXPECT_THAT(container, SizeIs(2));
3958}
3959
3960TEST(SizeIsTest, WorksWithMap) {
3961 map<string, int> container;
3962 EXPECT_THAT(container, SizeIs(0));
3963 EXPECT_THAT(container, Not(SizeIs(1)));
3964 container.insert(make_pair("foo", 1));
3965 EXPECT_THAT(container, Not(SizeIs(0)));
3966 EXPECT_THAT(container, SizeIs(1));
3967 container.insert(make_pair("bar", 2));
3968 EXPECT_THAT(container, Not(SizeIs(0)));
3969 EXPECT_THAT(container, SizeIs(2));
3970}
3971
3972TEST(SizeIsTest, WorksWithReferences) {
3973 vector<int> container;
3974 Matcher<const vector<int>&> m = SizeIs(1);
3975 EXPECT_THAT(container, Not(m));
3976 container.push_back(0);
3977 EXPECT_THAT(container, m);
3978}
3979
3980TEST(SizeIsTest, CanDescribeSelf) {
3981 Matcher<vector<int> > m = SizeIs(2);
3982 EXPECT_EQ("size is equal to 2", Describe(m));
3983 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
3984}
3985
3986TEST(SizeIsTest, ExplainsResult) {
3987 Matcher<vector<int> > m1 = SizeIs(2);
3988 Matcher<vector<int> > m2 = SizeIs(Lt(2u));
3989 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
3990 Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
3991 vector<int> container;
3992 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
3993 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
3994 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
3995 EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
3996 Explain(m4, container));
3997 container.push_back(0);
3998 container.push_back(0);
3999 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
4000 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
4001 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
4002 EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
4003 Explain(m4, container));
4004}
4005
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004006#if GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004007// Tests ContainerEq with different container types, and
4008// different element types.
4009
4010template <typename T>
zhanyong.wanb8243162009-06-04 05:48:20 +00004011class ContainerEqTest : public testing::Test {};
zhanyong.wan6a896b52009-01-16 01:13:50 +00004012
4013typedef testing::Types<
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004014 set<int>,
4015 vector<size_t>,
4016 multiset<size_t>,
4017 list<int> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004018 ContainerEqTestTypes;
4019
4020TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
4021
4022// Tests that the filled container is equal to itself.
4023TYPED_TEST(ContainerEqTest, EqualsSelf) {
4024 static const int vals[] = {1, 1, 2, 3, 5, 8};
4025 TypeParam my_set(vals, vals + 6);
4026 const Matcher<TypeParam> m = ContainerEq(my_set);
4027 EXPECT_TRUE(m.Matches(my_set));
4028 EXPECT_EQ("", Explain(m, my_set));
4029}
4030
4031// Tests that missing values are reported.
4032TYPED_TEST(ContainerEqTest, ValueMissing) {
4033 static const int vals[] = {1, 1, 2, 3, 5, 8};
4034 static const int test_vals[] = {2, 1, 8, 5};
4035 TypeParam my_set(vals, vals + 6);
4036 TypeParam test_set(test_vals, test_vals + 4);
4037 const Matcher<TypeParam> m = ContainerEq(my_set);
4038 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004039 EXPECT_EQ("which doesn't have these expected elements: 3",
4040 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004041}
4042
4043// Tests that added values are reported.
4044TYPED_TEST(ContainerEqTest, ValueAdded) {
4045 static const int vals[] = {1, 1, 2, 3, 5, 8};
4046 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4047 TypeParam my_set(vals, vals + 6);
4048 TypeParam test_set(test_vals, test_vals + 6);
4049 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4050 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004051 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004052}
4053
4054// Tests that added and missing values are reported together.
4055TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4056 static const int vals[] = {1, 1, 2, 3, 5, 8};
4057 static const int test_vals[] = {1, 2, 3, 8, 46};
4058 TypeParam my_set(vals, vals + 6);
4059 TypeParam test_set(test_vals, test_vals + 5);
4060 const Matcher<TypeParam> m = ContainerEq(my_set);
4061 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004062 EXPECT_EQ("which has these unexpected elements: 46,\n"
4063 "and doesn't have these expected elements: 5",
4064 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004065}
4066
4067// Tests duplicated value -- expect no explanation.
4068TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4069 static const int vals[] = {1, 1, 2, 3, 5, 8};
4070 static const int test_vals[] = {1, 2, 3, 5, 8};
4071 TypeParam my_set(vals, vals + 6);
4072 TypeParam test_set(test_vals, test_vals + 5);
4073 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4074 // Depending on the container, match may be true or false
4075 // But in any case there should be no explanation.
4076 EXPECT_EQ("", Explain(m, test_set));
4077}
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004078#endif // GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004079
4080// Tests that mutliple missing values are reported.
4081// Using just vector here, so order is predicatble.
4082TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4083 static const int vals[] = {1, 1, 2, 3, 5, 8};
4084 static const int test_vals[] = {2, 1, 5};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004085 vector<int> my_set(vals, vals + 6);
4086 vector<int> test_set(test_vals, test_vals + 3);
4087 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004088 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004089 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4090 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004091}
4092
4093// Tests that added values are reported.
4094// Using just vector here, so order is predicatble.
4095TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4096 static const int vals[] = {1, 1, 2, 3, 5, 8};
4097 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004098 list<size_t> my_set(vals, vals + 6);
4099 list<size_t> test_set(test_vals, test_vals + 7);
4100 const Matcher<const list<size_t>&> m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004101 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004102 EXPECT_EQ("which has these unexpected elements: 92, 46",
4103 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004104}
4105
4106// Tests that added and missing values are reported together.
4107TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
4108 static const int vals[] = {1, 1, 2, 3, 5, 8};
4109 static const int test_vals[] = {1, 2, 3, 92, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004110 list<size_t> my_set(vals, vals + 6);
4111 list<size_t> test_set(test_vals, test_vals + 5);
4112 const Matcher<const list<size_t> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004113 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004114 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4115 "and doesn't have these expected elements: 5, 8",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004116 Explain(m, test_set));
4117}
4118
4119// Tests to see that duplicate elements are detected,
4120// but (as above) not reported in the explanation.
4121TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
4122 static const int vals[] = {1, 1, 2, 3, 5, 8};
4123 static const int test_vals[] = {1, 2, 3, 5, 8};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004124 vector<int> my_set(vals, vals + 6);
4125 vector<int> test_set(test_vals, test_vals + 5);
4126 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004127 EXPECT_TRUE(m.Matches(my_set));
4128 EXPECT_FALSE(m.Matches(test_set));
4129 // There is nothing to report when both sets contain all the same values.
4130 EXPECT_EQ("", Explain(m, test_set));
4131}
4132
4133// Tests that ContainerEq works for non-trivial associative containers,
4134// like maps.
4135TEST(ContainerEqExtraTest, WorksForMaps) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004136 map<int, std::string> my_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004137 my_map[0] = "a";
4138 my_map[1] = "b";
4139
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004140 map<int, std::string> test_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004141 test_map[0] = "aa";
4142 test_map[1] = "b";
4143
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004144 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004145 EXPECT_TRUE(m.Matches(my_map));
4146 EXPECT_FALSE(m.Matches(test_map));
4147
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004148 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
4149 "and doesn't have these expected elements: (0, \"a\")",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004150 Explain(m, test_map));
4151}
4152
zhanyong.wanb8243162009-06-04 05:48:20 +00004153TEST(ContainerEqExtraTest, WorksForNativeArray) {
4154 int a1[] = { 1, 2, 3 };
4155 int a2[] = { 1, 2, 3 };
4156 int b[] = { 1, 2, 4 };
4157
4158 EXPECT_THAT(a1, ContainerEq(a2));
4159 EXPECT_THAT(a1, Not(ContainerEq(b)));
4160}
4161
4162TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
4163 const char a1[][3] = { "hi", "lo" };
4164 const char a2[][3] = { "hi", "lo" };
4165 const char b[][3] = { "lo", "hi" };
4166
4167 // Tests using ContainerEq() in the first dimension.
4168 EXPECT_THAT(a1, ContainerEq(a2));
4169 EXPECT_THAT(a1, Not(ContainerEq(b)));
4170
4171 // Tests using ContainerEq() in the second dimension.
4172 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
4173 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
4174}
4175
4176TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
4177 const int a1[] = { 1, 2, 3 };
4178 const int a2[] = { 1, 2, 3 };
4179 const int b[] = { 1, 2, 3, 4 };
4180
zhanyong.wan2661c682009-06-09 05:42:12 +00004181 const int* const p1 = a1;
4182 EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
4183 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004184
4185 const int c[] = { 1, 3, 2 };
zhanyong.wan2661c682009-06-09 05:42:12 +00004186 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004187}
4188
4189TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
4190 std::string a1[][3] = {
4191 { "hi", "hello", "ciao" },
4192 { "bye", "see you", "ciao" }
4193 };
4194
4195 std::string a2[][3] = {
4196 { "hi", "hello", "ciao" },
4197 { "bye", "see you", "ciao" }
4198 };
4199
4200 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
4201 EXPECT_THAT(a1, m);
4202
4203 a2[0][0] = "ha";
4204 EXPECT_THAT(a1, m);
4205}
4206
zhanyong.wan898725c2011-09-16 16:45:39 +00004207TEST(WhenSortedByTest, WorksForEmptyContainer) {
4208 const vector<int> numbers;
4209 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
4210 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
4211}
4212
4213TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
4214 vector<unsigned> numbers;
4215 numbers.push_back(3);
4216 numbers.push_back(1);
4217 numbers.push_back(2);
4218 numbers.push_back(2);
4219 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
4220 ElementsAre(3, 2, 2, 1)));
4221 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
4222 ElementsAre(1, 2, 2, 3))));
4223}
4224
4225TEST(WhenSortedByTest, WorksForNonVectorContainer) {
4226 list<string> words;
4227 words.push_back("say");
4228 words.push_back("hello");
4229 words.push_back("world");
4230 EXPECT_THAT(words, WhenSortedBy(less<string>(),
4231 ElementsAre("hello", "say", "world")));
4232 EXPECT_THAT(words, Not(WhenSortedBy(less<string>(),
4233 ElementsAre("say", "hello", "world"))));
4234}
4235
4236TEST(WhenSortedByTest, WorksForNativeArray) {
4237 const int numbers[] = { 1, 3, 2, 4 };
4238 const int sorted_numbers[] = { 1, 2, 3, 4 };
4239 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
4240 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
4241 ElementsAreArray(sorted_numbers)));
4242 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
4243}
4244
4245TEST(WhenSortedByTest, CanDescribeSelf) {
4246 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
4247 EXPECT_EQ("(when sorted) has 2 elements where\n"
4248 "element #0 is equal to 1,\n"
4249 "element #1 is equal to 2",
4250 Describe(m));
4251 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
4252 "element #0 isn't equal to 1, or\n"
4253 "element #1 isn't equal to 2",
4254 DescribeNegation(m));
4255}
4256
4257TEST(WhenSortedByTest, ExplainsMatchResult) {
4258 const int a[] = { 2, 1 };
4259 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
4260 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
4261 EXPECT_EQ("which is { 1, 2 } when sorted",
4262 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
4263}
4264
4265// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
4266// need to test it as exhaustively as we test the latter.
4267
4268TEST(WhenSortedTest, WorksForEmptyContainer) {
4269 const vector<int> numbers;
4270 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
4271 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
4272}
4273
4274TEST(WhenSortedTest, WorksForNonEmptyContainer) {
4275 list<string> words;
4276 words.push_back("3");
4277 words.push_back("1");
4278 words.push_back("2");
4279 words.push_back("2");
4280 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
4281 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
4282}
4283
zhanyong.wana9a59e02013-03-27 16:14:55 +00004284TEST(WhenSortedTest, WorksForMapTypes) {
4285 map<string, int> word_counts;
4286 word_counts["and"] = 1;
4287 word_counts["the"] = 1;
4288 word_counts["buffalo"] = 2;
4289 EXPECT_THAT(word_counts, WhenSorted(ElementsAre(
4290 Pair("and", 1), Pair("buffalo", 2), Pair("the", 1))));
4291 EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre(
4292 Pair("and", 1), Pair("the", 1), Pair("buffalo", 2)))));
4293}
4294
4295TEST(WhenSortedTest, WorksForMultiMapTypes) {
4296 multimap<int, int> ifib;
4297 ifib.insert(make_pair(8, 6));
4298 ifib.insert(make_pair(2, 3));
4299 ifib.insert(make_pair(1, 1));
4300 ifib.insert(make_pair(3, 4));
4301 ifib.insert(make_pair(1, 2));
4302 ifib.insert(make_pair(5, 5));
4303 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
4304 Pair(1, 2),
4305 Pair(2, 3),
4306 Pair(3, 4),
4307 Pair(5, 5),
4308 Pair(8, 6))));
4309 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
4310 Pair(2, 3),
4311 Pair(1, 1),
4312 Pair(3, 4),
4313 Pair(1, 2),
4314 Pair(5, 5)))));
4315}
4316
4317TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
4318 std::deque<int> d;
4319 d.push_back(2);
4320 d.push_back(1);
4321 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
4322 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
4323}
4324
4325TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
4326 std::deque<int> d;
4327 d.push_back(2);
4328 d.push_back(1);
4329 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
4330 EXPECT_THAT(d, WhenSorted(vector_match));
4331 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
4332 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
4333}
4334
4335// Deliberately bare pseudo-container.
4336// Offers only begin() and end() accessors, yielding InputIterator.
4337template <typename T>
4338class Streamlike {
4339 private:
4340 class ConstIter;
4341 public:
4342 typedef ConstIter const_iterator;
4343 typedef T value_type;
4344
4345 template <typename InIter>
4346 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
4347
4348 const_iterator begin() const {
4349 return const_iterator(this, remainder_.begin());
4350 }
4351 const_iterator end() const {
4352 return const_iterator(this, remainder_.end());
4353 }
4354
4355 private:
4356 class ConstIter : public std::iterator<std::input_iterator_tag,
4357 value_type,
4358 ptrdiff_t,
4359 const value_type&,
4360 const value_type*> {
4361 public:
4362 ConstIter(const Streamlike* s,
4363 typename std::list<value_type>::iterator pos)
4364 : s_(s), pos_(pos) {}
4365
4366 const value_type& operator*() const { return *pos_; }
4367 const value_type* operator->() const { return &*pos_; }
4368 ConstIter& operator++() {
4369 s_->remainder_.erase(pos_++);
4370 return *this;
4371 }
4372
4373 // *iter++ is required to work (see std::istreambuf_iterator).
4374 // (void)iter++ is also required to work.
4375 class PostIncrProxy {
4376 public:
4377 explicit PostIncrProxy(const value_type& value) : value_(value) {}
4378 value_type operator*() const { return value_; }
4379 private:
4380 value_type value_;
4381 };
4382 PostIncrProxy operator++(int) {
4383 PostIncrProxy proxy(**this);
4384 ++(*this);
4385 return proxy;
4386 }
4387
4388 friend bool operator==(const ConstIter& a, const ConstIter& b) {
4389 return a.s_ == b.s_ && a.pos_ == b.pos_;
4390 }
4391 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
4392 return !(a == b);
4393 }
4394
4395 private:
4396 const Streamlike* s_;
4397 typename std::list<value_type>::iterator pos_;
4398 };
4399
4400 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
4401 os << "[";
4402 typedef typename std::list<value_type>::const_iterator Iter;
4403 const char* sep = "";
4404 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
4405 os << sep << *it;
4406 sep = ",";
4407 }
4408 os << "]";
4409 return os;
4410 }
4411
4412 mutable std::list<value_type> remainder_; // modified by iteration
4413};
4414
4415TEST(StreamlikeTest, Iteration) {
4416 const int a[5] = { 2, 1, 4, 5, 3 };
4417 Streamlike<int> s(a, a + 5);
4418 Streamlike<int>::const_iterator it = s.begin();
4419 const int* ip = a;
4420 while (it != s.end()) {
4421 SCOPED_TRACE(ip - a);
4422 EXPECT_EQ(*ip++, *it++);
4423 }
4424}
4425
kosakb6a34882014-03-12 21:06:46 +00004426#if GTEST_LANG_CXX11
4427TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
4428 std::forward_list<int> container;
4429 EXPECT_THAT(container, BeginEndDistanceIs(0));
4430 EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
4431 container.push_front(0);
4432 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4433 EXPECT_THAT(container, BeginEndDistanceIs(1));
4434 container.push_front(0);
4435 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4436 EXPECT_THAT(container, BeginEndDistanceIs(2));
4437}
4438#endif // GTEST_LANG_CXX11
4439
4440TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
4441 const int a[5] = { 1, 2, 3, 4, 5 };
4442 Streamlike<int> s(a, a + 5);
4443 EXPECT_THAT(s, BeginEndDistanceIs(5));
4444}
4445
4446TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
4447 Matcher<vector<int> > m = BeginEndDistanceIs(2);
4448 EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
4449 EXPECT_EQ("distance between begin() and end() isn't equal to 2",
4450 DescribeNegation(m));
4451}
4452
4453TEST(BeginEndDistanceIsTest, ExplainsResult) {
4454 Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
4455 Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
4456 Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
4457 Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
4458 vector<int> container;
4459 EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
4460 Explain(m1, container));
4461 EXPECT_EQ("whose distance between begin() and end() 0 matches",
4462 Explain(m2, container));
4463 EXPECT_EQ("whose distance between begin() and end() 0 matches",
4464 Explain(m3, container));
4465 EXPECT_EQ(
4466 "whose distance between begin() and end() 0 doesn't match, which is 1 "
4467 "less than 1",
4468 Explain(m4, container));
4469 container.push_back(0);
4470 container.push_back(0);
4471 EXPECT_EQ("whose distance between begin() and end() 2 matches",
4472 Explain(m1, container));
4473 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4474 Explain(m2, container));
4475 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4476 Explain(m3, container));
4477 EXPECT_EQ(
4478 "whose distance between begin() and end() 2 matches, which is 1 more "
4479 "than 1",
4480 Explain(m4, container));
4481}
4482
zhanyong.wana9a59e02013-03-27 16:14:55 +00004483TEST(WhenSortedTest, WorksForStreamlike) {
4484 // Streamlike 'container' provides only minimal iterator support.
4485 // Its iterators are tagged with input_iterator_tag.
4486 const int a[5] = { 2, 1, 4, 5, 3 };
kosak6414d802013-12-03 23:19:36 +00004487 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004488 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
4489 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4490}
4491
4492TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00004493 const int a[] = { 2, 1, 4, 5, 3 };
kosak6414d802013-12-03 23:19:36 +00004494 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004495 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
4496 EXPECT_THAT(s, WhenSorted(vector_match));
4497 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4498}
4499
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004500// Tests using ElementsAre() and ElementsAreArray() with stream-like
4501// "containers".
4502
4503TEST(ElemensAreStreamTest, WorksForStreamlike) {
4504 const int a[5] = { 1, 2, 3, 4, 5 };
kosak6414d802013-12-03 23:19:36 +00004505 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004506 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
4507 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
4508}
4509
4510TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
4511 const int a[5] = { 1, 2, 3, 4, 5 };
kosak6414d802013-12-03 23:19:36 +00004512 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004513
4514 vector<int> expected;
4515 expected.push_back(1);
4516 expected.push_back(2);
4517 expected.push_back(3);
4518 expected.push_back(4);
4519 expected.push_back(5);
4520 EXPECT_THAT(s, ElementsAreArray(expected));
4521
4522 expected[3] = 0;
4523 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
4524}
4525
zhanyong.wanfb25d532013-07-28 08:24:00 +00004526// Tests for UnorderedElementsAreArray()
4527
4528TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
4529 const int a[] = { 0, 1, 2, 3, 4 };
kosak6414d802013-12-03 23:19:36 +00004530 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004531 do {
4532 StringMatchResultListener listener;
4533 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
4534 s, &listener)) << listener.str();
4535 } while (std::next_permutation(s.begin(), s.end()));
4536}
4537
4538TEST(UnorderedElementsAreArrayTest, VectorBool) {
4539 const bool a[] = { 0, 1, 0, 1, 1 };
4540 const bool b[] = { 1, 0, 1, 1, 0 };
kosak6414d802013-12-03 23:19:36 +00004541 std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a));
4542 std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004543 StringMatchResultListener listener;
4544 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
4545 actual, &listener)) << listener.str();
4546}
4547
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004548TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
4549 // Streamlike 'container' provides only minimal iterator support.
4550 // Its iterators are tagged with input_iterator_tag, and it has no
4551 // size() or empty() methods.
4552 const int a[5] = { 2, 1, 4, 5, 3 };
kosak6414d802013-12-03 23:19:36 +00004553 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004554
4555 ::std::vector<int> expected;
4556 expected.push_back(1);
4557 expected.push_back(2);
4558 expected.push_back(3);
4559 expected.push_back(4);
4560 expected.push_back(5);
4561 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
4562
4563 expected.push_back(6);
4564 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
4565}
4566
kosak18489fa2013-12-04 23:49:07 +00004567#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004568
4569TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
4570 const int a[5] = { 2, 1, 4, 5, 3 };
4571 EXPECT_THAT(a, UnorderedElementsAreArray({ 1, 2, 3, 4, 5 }));
4572 EXPECT_THAT(a, Not(UnorderedElementsAreArray({ 1, 2, 3, 4, 6 })));
4573}
4574
4575TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
4576 const string a[5] = { "a", "b", "c", "d", "e" };
4577 EXPECT_THAT(a, UnorderedElementsAreArray({ "a", "b", "c", "d", "e" }));
4578 EXPECT_THAT(a, Not(UnorderedElementsAreArray({ "a", "b", "c", "d", "ef" })));
4579}
4580
4581TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
4582 const int a[5] = { 2, 1, 4, 5, 3 };
4583 EXPECT_THAT(a, UnorderedElementsAreArray(
4584 { Eq(1), Eq(2), Eq(3), Eq(4), Eq(5) }));
4585 EXPECT_THAT(a, Not(UnorderedElementsAreArray(
4586 { Eq(1), Eq(2), Eq(3), Eq(4), Eq(6) })));
4587}
4588
4589TEST(UnorderedElementsAreArrayTest,
4590 TakesInitializerListOfDifferentTypedMatchers) {
4591 const int a[5] = { 2, 1, 4, 5, 3 };
4592 // The compiler cannot infer the type of the initializer list if its
4593 // elements have different types. We must explicitly specify the
4594 // unified element type in this case.
4595 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
4596 { Eq(1), Ne(-2), Ge(3), Le(4), Eq(5) }));
4597 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
4598 { Eq(1), Ne(-2), Ge(3), Le(4), Eq(6) })));
4599}
4600
kosak18489fa2013-12-04 23:49:07 +00004601#endif // GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004602
zhanyong.wanfb25d532013-07-28 08:24:00 +00004603class UnorderedElementsAreTest : public testing::Test {
4604 protected:
4605 typedef std::vector<int> IntVec;
4606};
4607
4608TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
4609 const int a[] = { 1, 2, 3 };
kosak6414d802013-12-03 23:19:36 +00004610 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004611 do {
4612 StringMatchResultListener listener;
4613 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4614 s, &listener)) << listener.str();
4615 } while (std::next_permutation(s.begin(), s.end()));
4616}
4617
4618TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
4619 const int a[] = { 1, 2, 3 };
kosak6414d802013-12-03 23:19:36 +00004620 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004621 std::vector<Matcher<int> > mv;
4622 mv.push_back(1);
4623 mv.push_back(2);
4624 mv.push_back(2);
4625 // The element with value '3' matches nothing: fail fast.
4626 StringMatchResultListener listener;
4627 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4628 s, &listener)) << listener.str();
4629}
4630
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004631TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
4632 // Streamlike 'container' provides only minimal iterator support.
4633 // Its iterators are tagged with input_iterator_tag, and it has no
4634 // size() or empty() methods.
4635 const int a[5] = { 2, 1, 4, 5, 3 };
kosak6414d802013-12-03 23:19:36 +00004636 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004637
4638 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
4639 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
4640}
4641
zhanyong.wanfb25d532013-07-28 08:24:00 +00004642// One naive implementation of the matcher runs in O(N!) time, which is too
4643// slow for many real-world inputs. This test shows that our matcher can match
4644// 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
4645// iterations and obviously effectively incomputable.
4646// [ RUN ] UnorderedElementsAreTest.Performance
4647// [ OK ] UnorderedElementsAreTest.Performance (4 ms)
4648TEST_F(UnorderedElementsAreTest, Performance) {
4649 std::vector<int> s;
4650 std::vector<Matcher<int> > mv;
4651 for (int i = 0; i < 100; ++i) {
4652 s.push_back(i);
4653 mv.push_back(_);
4654 }
4655 mv[50] = Eq(0);
4656 StringMatchResultListener listener;
4657 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4658 s, &listener)) << listener.str();
4659}
4660
4661// Another variant of 'Performance' with similar expectations.
4662// [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
4663// [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
4664TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
4665 std::vector<int> s;
4666 std::vector<Matcher<int> > mv;
4667 for (int i = 0; i < 100; ++i) {
4668 s.push_back(i);
4669 if (i & 1) {
4670 mv.push_back(_);
4671 } else {
4672 mv.push_back(i);
4673 }
4674 }
4675 StringMatchResultListener listener;
4676 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4677 s, &listener)) << listener.str();
4678}
4679
4680TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
4681 std::vector<int> v;
4682 v.push_back(4);
4683 StringMatchResultListener listener;
4684 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4685 v, &listener)) << listener.str();
4686 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
4687}
4688
4689TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
4690 std::vector<int> v;
4691 StringMatchResultListener listener;
4692 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4693 v, &listener)) << listener.str();
4694 EXPECT_THAT(listener.str(), Eq(""));
4695}
4696
4697TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
4698 std::vector<int> v;
4699 v.push_back(1);
4700 v.push_back(1);
4701 StringMatchResultListener listener;
4702 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4703 v, &listener)) << listener.str();
4704 EXPECT_THAT(
4705 listener.str(),
4706 Eq("where the following matchers don't match any elements:\n"
4707 "matcher #1: is equal to 2"));
4708}
4709
4710TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
4711 std::vector<int> v;
4712 v.push_back(1);
4713 v.push_back(2);
4714 StringMatchResultListener listener;
4715 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
4716 v, &listener)) << listener.str();
4717 EXPECT_THAT(
4718 listener.str(),
4719 Eq("where the following elements don't match any matchers:\n"
4720 "element #1: 2"));
4721}
4722
4723TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
4724 std::vector<int> v;
4725 v.push_back(2);
4726 v.push_back(3);
4727 StringMatchResultListener listener;
4728 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4729 v, &listener)) << listener.str();
4730 EXPECT_THAT(
4731 listener.str(),
4732 Eq("where"
4733 " the following matchers don't match any elements:\n"
4734 "matcher #0: is equal to 1\n"
4735 "and"
4736 " where"
4737 " the following elements don't match any matchers:\n"
4738 "element #1: 3"));
4739}
4740
4741// Test helper for formatting element, matcher index pairs in expectations.
4742static string EMString(int element, int matcher) {
4743 stringstream ss;
4744 ss << "(element #" << element << ", matcher #" << matcher << ")";
4745 return ss.str();
4746}
4747
4748TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
4749 // A situation where all elements and matchers have a match
4750 // associated with them, but the max matching is not perfect.
4751 std::vector<string> v;
4752 v.push_back("a");
4753 v.push_back("b");
4754 v.push_back("c");
4755 StringMatchResultListener listener;
4756 EXPECT_FALSE(ExplainMatchResult(
4757 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
4758 << listener.str();
4759
4760 string prefix =
4761 "where no permutation of the elements can satisfy all matchers, "
4762 "and the closest match is 2 of 3 matchers with the "
4763 "pairings:\n";
4764
4765 // We have to be a bit loose here, because there are 4 valid max matches.
4766 EXPECT_THAT(
4767 listener.str(),
4768 AnyOf(prefix + "{\n " + EMString(0, 0) +
4769 ",\n " + EMString(1, 2) + "\n}",
4770 prefix + "{\n " + EMString(0, 1) +
4771 ",\n " + EMString(1, 2) + "\n}",
4772 prefix + "{\n " + EMString(0, 0) +
4773 ",\n " + EMString(2, 2) + "\n}",
4774 prefix + "{\n " + EMString(0, 1) +
4775 ",\n " + EMString(2, 2) + "\n}"));
4776}
4777
4778TEST_F(UnorderedElementsAreTest, Describe) {
4779 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
4780 Eq("is empty"));
4781 EXPECT_THAT(
4782 Describe<IntVec>(UnorderedElementsAre(345)),
4783 Eq("has 1 element and that element is equal to 345"));
4784 EXPECT_THAT(
4785 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
4786 Eq("has 3 elements and there exists some permutation "
4787 "of elements such that:\n"
4788 " - element #0 is equal to 111, and\n"
4789 " - element #1 is equal to 222, and\n"
4790 " - element #2 is equal to 333"));
4791}
4792
4793TEST_F(UnorderedElementsAreTest, DescribeNegation) {
4794 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
4795 Eq("isn't empty"));
4796 EXPECT_THAT(
4797 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
4798 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
4799 EXPECT_THAT(
4800 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
4801 Eq("doesn't have 3 elements, or there exists no permutation "
4802 "of elements such that:\n"
4803 " - element #0 is equal to 123, and\n"
4804 " - element #1 is equal to 234, and\n"
4805 " - element #2 is equal to 345"));
4806}
4807
4808namespace {
4809
4810// Used as a check on the more complex max flow method used in the
4811// real testing::internal::FindMaxBipartiteMatching. This method is
4812// compatible but runs in worst-case factorial time, so we only
4813// use it in testing for small problem sizes.
4814template <typename Graph>
4815class BacktrackingMaxBPMState {
4816 public:
4817 // Does not take ownership of 'g'.
4818 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
4819
4820 ElementMatcherPairs Compute() {
4821 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
4822 return best_so_far_;
4823 }
4824 lhs_used_.assign(graph_->LhsSize(), kUnused);
4825 rhs_used_.assign(graph_->RhsSize(), kUnused);
4826 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
4827 matches_.clear();
4828 RecurseInto(irhs);
4829 if (best_so_far_.size() == graph_->RhsSize())
4830 break;
4831 }
4832 return best_so_far_;
4833 }
4834
4835 private:
4836 static const size_t kUnused = static_cast<size_t>(-1);
4837
4838 void PushMatch(size_t lhs, size_t rhs) {
4839 matches_.push_back(ElementMatcherPair(lhs, rhs));
4840 lhs_used_[lhs] = rhs;
4841 rhs_used_[rhs] = lhs;
4842 if (matches_.size() > best_so_far_.size()) {
4843 best_so_far_ = matches_;
4844 }
4845 }
4846
4847 void PopMatch() {
4848 const ElementMatcherPair& back = matches_.back();
4849 lhs_used_[back.first] = kUnused;
4850 rhs_used_[back.second] = kUnused;
4851 matches_.pop_back();
4852 }
4853
4854 bool RecurseInto(size_t irhs) {
4855 if (rhs_used_[irhs] != kUnused) {
4856 return true;
4857 }
4858 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
4859 if (lhs_used_[ilhs] != kUnused) {
4860 continue;
4861 }
4862 if (!graph_->HasEdge(ilhs, irhs)) {
4863 continue;
4864 }
4865 PushMatch(ilhs, irhs);
4866 if (best_so_far_.size() == graph_->RhsSize()) {
4867 return false;
4868 }
4869 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
4870 if (!RecurseInto(mi)) return false;
4871 }
4872 PopMatch();
4873 }
4874 return true;
4875 }
4876
4877 const Graph* graph_; // not owned
4878 std::vector<size_t> lhs_used_;
4879 std::vector<size_t> rhs_used_;
4880 ElementMatcherPairs matches_;
4881 ElementMatcherPairs best_so_far_;
4882};
4883
4884template <typename Graph>
4885const size_t BacktrackingMaxBPMState<Graph>::kUnused;
4886
4887} // namespace
4888
4889// Implement a simple backtracking algorithm to determine if it is possible
4890// to find one element per matcher, without reusing elements.
4891template <typename Graph>
4892ElementMatcherPairs
4893FindBacktrackingMaxBPM(const Graph& g) {
4894 return BacktrackingMaxBPMState<Graph>(&g).Compute();
4895}
4896
4897class BacktrackingBPMTest : public ::testing::Test { };
4898
4899// Tests the MaxBipartiteMatching algorithm with square matrices.
4900// The single int param is the # of nodes on each of the left and right sides.
4901class BipartiteTest : public ::testing::TestWithParam<int> { };
4902
4903// Verify all match graphs up to some moderate number of edges.
4904TEST_P(BipartiteTest, Exhaustive) {
4905 int nodes = GetParam();
4906 MatchMatrix graph(nodes, nodes);
4907 do {
4908 ElementMatcherPairs matches =
4909 internal::FindMaxBipartiteMatching(graph);
4910 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
4911 << "graph: " << graph.DebugString();
4912 // Check that all elements of matches are in the graph.
4913 // Check that elements of first and second are unique.
4914 std::vector<bool> seen_element(graph.LhsSize());
4915 std::vector<bool> seen_matcher(graph.RhsSize());
4916 SCOPED_TRACE(PrintToString(matches));
4917 for (size_t i = 0; i < matches.size(); ++i) {
4918 size_t ilhs = matches[i].first;
4919 size_t irhs = matches[i].second;
4920 EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
4921 EXPECT_FALSE(seen_element[ilhs]);
4922 EXPECT_FALSE(seen_matcher[irhs]);
4923 seen_element[ilhs] = true;
4924 seen_matcher[irhs] = true;
4925 }
4926 } while (graph.NextGraph());
4927}
4928
4929INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest,
4930 ::testing::Range(0, 5));
4931
4932// Parameterized by a pair interpreted as (LhsSize, RhsSize).
4933class BipartiteNonSquareTest
4934 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
4935};
4936
4937TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
4938 // .......
4939 // 0:-----\ :
4940 // 1:---\ | :
4941 // 2:---\ | :
4942 // 3:-\ | | :
4943 // :.......:
4944 // 0 1 2
4945 MatchMatrix g(4, 3);
4946 static const int kEdges[][2] = { {0, 2}, {1, 1}, {2, 1}, {3, 0} };
kosak6414d802013-12-03 23:19:36 +00004947 for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00004948 g.SetEdge(kEdges[i][0], kEdges[i][1], true);
4949 }
4950 EXPECT_THAT(FindBacktrackingMaxBPM(g),
4951 ElementsAre(Pair(3, 0),
4952 Pair(AnyOf(1, 2), 1),
4953 Pair(0, 2))) << g.DebugString();
4954}
4955
4956// Verify a few nonsquare matrices.
4957TEST_P(BipartiteNonSquareTest, Exhaustive) {
4958 size_t nlhs = GetParam().first;
4959 size_t nrhs = GetParam().second;
4960 MatchMatrix graph(nlhs, nrhs);
4961 do {
4962 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
4963 internal::FindMaxBipartiteMatching(graph).size())
4964 << "graph: " << graph.DebugString()
4965 << "\nbacktracking: "
4966 << PrintToString(FindBacktrackingMaxBPM(graph))
4967 << "\nmax flow: "
4968 << PrintToString(internal::FindMaxBipartiteMatching(graph));
4969 } while (graph.NextGraph());
4970}
4971
4972INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest,
4973 testing::Values(
4974 std::make_pair(1, 2),
4975 std::make_pair(2, 1),
4976 std::make_pair(3, 2),
4977 std::make_pair(2, 3),
4978 std::make_pair(4, 1),
4979 std::make_pair(1, 4),
4980 std::make_pair(4, 3),
4981 std::make_pair(3, 4)));
4982
4983class BipartiteRandomTest
4984 : public ::testing::TestWithParam<std::pair<int, int> > {
4985};
4986
4987// Verifies a large sample of larger graphs.
4988TEST_P(BipartiteRandomTest, LargerNets) {
4989 int nodes = GetParam().first;
4990 int iters = GetParam().second;
4991 MatchMatrix graph(nodes, nodes);
4992
4993 testing::internal::Int32 seed = GTEST_FLAG(random_seed);
4994 if (seed == 0) {
4995 seed = static_cast<testing::internal::Int32>(time(NULL));
4996 }
4997
4998 for (; iters > 0; --iters, ++seed) {
4999 srand(static_cast<int>(seed));
5000 graph.Randomize();
5001 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5002 internal::FindMaxBipartiteMatching(graph).size())
5003 << " graph: " << graph.DebugString()
5004 << "\nTo reproduce the failure, rerun the test with the flag"
5005 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
5006 }
5007}
5008
5009// Test argument is a std::pair<int, int> representing (nodes, iters).
5010INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest,
5011 testing::Values(
5012 std::make_pair(5, 10000),
5013 std::make_pair(6, 5000),
5014 std::make_pair(7, 2000),
5015 std::make_pair(8, 500),
5016 std::make_pair(9, 100)));
5017
zhanyong.wan736baa82010-09-27 17:44:16 +00005018// Tests IsReadableTypeName().
5019
5020TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
5021 EXPECT_TRUE(IsReadableTypeName("int"));
5022 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
5023 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
5024 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
5025}
5026
5027TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
5028 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
5029 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
5030 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
5031}
5032
5033TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
5034 EXPECT_FALSE(
5035 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
5036 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
5037}
5038
5039TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
5040 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
5041}
5042
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005043// Tests JoinAsTuple().
5044
5045TEST(JoinAsTupleTest, JoinsEmptyTuple) {
5046 EXPECT_EQ("", JoinAsTuple(Strings()));
5047}
5048
5049TEST(JoinAsTupleTest, JoinsOneTuple) {
5050 const char* fields[] = { "1" };
5051 EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
5052}
5053
5054TEST(JoinAsTupleTest, JoinsTwoTuple) {
5055 const char* fields[] = { "1", "a" };
5056 EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
5057}
5058
5059TEST(JoinAsTupleTest, JoinsTenTuple) {
5060 const char* fields[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
5061 EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
5062 JoinAsTuple(Strings(fields, fields + 10)));
5063}
5064
5065// Tests FormatMatcherDescription().
5066
5067TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
5068 EXPECT_EQ("is even",
zhanyong.wanb4140802010-06-08 22:53:57 +00005069 FormatMatcherDescription(false, "IsEven", Strings()));
5070 EXPECT_EQ("not (is even)",
5071 FormatMatcherDescription(true, "IsEven", Strings()));
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005072
5073 const char* params[] = { "5" };
5074 EXPECT_EQ("equals 5",
zhanyong.wanb4140802010-06-08 22:53:57 +00005075 FormatMatcherDescription(false, "Equals",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005076 Strings(params, params + 1)));
5077
5078 const char* params2[] = { "5", "8" };
5079 EXPECT_EQ("is in range (5, 8)",
zhanyong.wanb4140802010-06-08 22:53:57 +00005080 FormatMatcherDescription(false, "IsInRange",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005081 Strings(params2, params2 + 2)));
5082}
5083
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00005084// Tests PolymorphicMatcher::mutable_impl().
5085TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
5086 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5087 DivisibleByImpl& impl = m.mutable_impl();
5088 EXPECT_EQ(42, impl.divider());
5089
5090 impl.set_divider(0);
5091 EXPECT_EQ(0, m.mutable_impl().divider());
5092}
5093
5094// Tests PolymorphicMatcher::impl().
5095TEST(PolymorphicMatcherTest, CanAccessImpl) {
5096 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5097 const DivisibleByImpl& impl = m.impl();
5098 EXPECT_EQ(42, impl.divider());
5099}
5100
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005101TEST(MatcherTupleTest, ExplainsMatchFailure) {
5102 stringstream ss1;
5103 ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
5104 make_tuple('a', 10), &ss1);
5105 EXPECT_EQ("", ss1.str()); // Successful match.
5106
5107 stringstream ss2;
5108 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5109 make_tuple(2, 'b'), &ss2);
5110 EXPECT_EQ(" Expected arg #0: is > 5\n"
5111 " Actual: 2, which is 3 less than 5\n"
zhanyong.wand60c5f42010-07-21 22:21:07 +00005112 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
5113 " Actual: 'b' (98, 0x62)\n",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005114 ss2.str()); // Failed match where both arguments need explanation.
5115
5116 stringstream ss3;
5117 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5118 make_tuple(2, 'a'), &ss3);
5119 EXPECT_EQ(" Expected arg #0: is > 5\n"
5120 " Actual: 2, which is 3 less than 5\n",
5121 ss3.str()); // Failed match where only one argument needs
5122 // explanation.
5123}
5124
zhanyong.wan33605ba2010-04-22 23:37:47 +00005125// Tests Each().
5126
5127TEST(EachTest, ExplainsMatchResultCorrectly) {
5128 set<int> a; // empty
5129
5130 Matcher<set<int> > m = Each(2);
5131 EXPECT_EQ("", Explain(m, a));
5132
zhanyong.wan736baa82010-09-27 17:44:16 +00005133 Matcher<const int(&)[1]> n = Each(1); // NOLINT
zhanyong.wan33605ba2010-04-22 23:37:47 +00005134
5135 const int b[1] = { 1 };
5136 EXPECT_EQ("", Explain(n, b));
5137
5138 n = Each(3);
5139 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
5140
5141 a.insert(1);
5142 a.insert(2);
5143 a.insert(3);
5144 m = Each(GreaterThan(0));
5145 EXPECT_EQ("", Explain(m, a));
5146
5147 m = Each(GreaterThan(10));
5148 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
5149 Explain(m, a));
5150}
5151
5152TEST(EachTest, DescribesItselfCorrectly) {
5153 Matcher<vector<int> > m = Each(1);
5154 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
5155
5156 Matcher<vector<int> > m2 = Not(m);
5157 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
5158}
5159
5160TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
5161 vector<int> some_vector;
5162 EXPECT_THAT(some_vector, Each(1));
5163 some_vector.push_back(3);
5164 EXPECT_THAT(some_vector, Not(Each(1)));
5165 EXPECT_THAT(some_vector, Each(3));
5166 some_vector.push_back(1);
5167 some_vector.push_back(2);
5168 EXPECT_THAT(some_vector, Not(Each(3)));
5169 EXPECT_THAT(some_vector, Each(Lt(3.5)));
5170
5171 vector<string> another_vector;
5172 another_vector.push_back("fee");
5173 EXPECT_THAT(another_vector, Each(string("fee")));
5174 another_vector.push_back("fie");
5175 another_vector.push_back("foe");
5176 another_vector.push_back("fum");
5177 EXPECT_THAT(another_vector, Not(Each(string("fee"))));
5178}
5179
5180TEST(EachTest, MatchesMapWhenAllElementsMatch) {
5181 map<const char*, int> my_map;
5182 const char* bar = "a string";
5183 my_map[bar] = 2;
5184 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
5185
5186 map<string, int> another_map;
5187 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5188 another_map["fee"] = 1;
5189 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5190 another_map["fie"] = 2;
5191 another_map["foe"] = 3;
5192 another_map["fum"] = 4;
5193 EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1))));
5194 EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1))));
5195 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
5196}
5197
5198TEST(EachTest, AcceptsMatcher) {
5199 const int a[] = { 1, 2, 3 };
5200 EXPECT_THAT(a, Each(Gt(0)));
5201 EXPECT_THAT(a, Not(Each(Gt(1))));
5202}
5203
5204TEST(EachTest, WorksForNativeArrayAsTuple) {
5205 const int a[] = { 1, 2 };
5206 const int* const pointer = a;
5207 EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
5208 EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
5209}
5210
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005211// For testing Pointwise().
5212class IsHalfOfMatcher {
5213 public:
5214 template <typename T1, typename T2>
5215 bool MatchAndExplain(const tuple<T1, T2>& a_pair,
5216 MatchResultListener* listener) const {
5217 if (get<0>(a_pair) == get<1>(a_pair)/2) {
5218 *listener << "where the second is " << get<1>(a_pair);
5219 return true;
5220 } else {
5221 *listener << "where the second/2 is " << get<1>(a_pair)/2;
5222 return false;
5223 }
5224 }
5225
5226 void DescribeTo(ostream* os) const {
5227 *os << "are a pair where the first is half of the second";
5228 }
5229
5230 void DescribeNegationTo(ostream* os) const {
5231 *os << "are a pair where the first isn't half of the second";
5232 }
5233};
5234
5235PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
5236 return MakePolymorphicMatcher(IsHalfOfMatcher());
5237}
5238
5239TEST(PointwiseTest, DescribesSelf) {
5240 vector<int> rhs;
5241 rhs.push_back(1);
5242 rhs.push_back(2);
5243 rhs.push_back(3);
5244 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
5245 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
5246 "in { 1, 2, 3 } are a pair where the first is half of the second",
5247 Describe(m));
5248 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
5249 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
5250 "where the first isn't half of the second",
5251 DescribeNegation(m));
5252}
5253
5254TEST(PointwiseTest, MakesCopyOfRhs) {
5255 list<signed char> rhs;
5256 rhs.push_back(2);
5257 rhs.push_back(4);
5258
5259 int lhs[] = { 1, 2 };
5260 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
5261 EXPECT_THAT(lhs, m);
5262
5263 // Changing rhs now shouldn't affect m, which made a copy of rhs.
5264 rhs.push_back(6);
5265 EXPECT_THAT(lhs, m);
5266}
5267
5268TEST(PointwiseTest, WorksForLhsNativeArray) {
5269 const int lhs[] = { 1, 2, 3 };
5270 vector<int> rhs;
5271 rhs.push_back(2);
5272 rhs.push_back(4);
5273 rhs.push_back(6);
5274 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
5275 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5276}
5277
5278TEST(PointwiseTest, WorksForRhsNativeArray) {
5279 const int rhs[] = { 1, 2, 3 };
5280 vector<int> lhs;
5281 lhs.push_back(2);
5282 lhs.push_back(4);
5283 lhs.push_back(6);
5284 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
5285 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
5286}
5287
5288TEST(PointwiseTest, RejectsWrongSize) {
5289 const double lhs[2] = { 1, 2 };
5290 const int rhs[1] = { 0 };
5291 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5292 EXPECT_EQ("which contains 2 values",
5293 Explain(Pointwise(Gt(), rhs), lhs));
5294
5295 const int rhs2[3] = { 0, 1, 2 };
5296 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
5297}
5298
5299TEST(PointwiseTest, RejectsWrongContent) {
5300 const double lhs[3] = { 1, 2, 3 };
5301 const int rhs[3] = { 2, 6, 4 };
5302 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
5303 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
5304 "where the second/2 is 3",
5305 Explain(Pointwise(IsHalfOf(), rhs), lhs));
5306}
5307
5308TEST(PointwiseTest, AcceptsCorrectContent) {
5309 const double lhs[3] = { 1, 2, 3 };
5310 const int rhs[3] = { 2, 4, 6 };
5311 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
5312 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
5313}
5314
5315TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
5316 const double lhs[3] = { 1, 2, 3 };
5317 const int rhs[3] = { 2, 4, 6 };
5318 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5319 EXPECT_THAT(lhs, Pointwise(m1, rhs));
5320 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
5321
5322 // This type works as a tuple<const double&, const int&> can be
5323 // implicitly cast to tuple<double, int>.
5324 const Matcher<tuple<double, int> > m2 = IsHalfOf();
5325 EXPECT_THAT(lhs, Pointwise(m2, rhs));
5326 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
5327}
5328
shiqiane35fdd92008-12-10 05:08:54 +00005329} // namespace gmock_matchers_test
5330} // namespace testing