blob: 52fbc3b6ddb102c320ec788fcf90aba43fd5d551 [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;
kosakbd018832014-04-02 20:30:00 +000080using testing::get;
81using testing::make_tuple;
82using testing::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
billydonahue1f5fdea2014-05-19 17:54:51 +0000656class Base {
657 public:
658 virtual ~Base() {}
659 Base() {}
660 private:
661 GTEST_DISALLOW_COPY_AND_ASSIGN_(Base);
662};
663
664class Derived : public Base {
665 public:
666 Derived() : Base() {}
667 int i;
668};
669
670class OtherDerived : public Base {};
zhanyong.wan18490652009-05-11 18:54:08 +0000671
672// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
673TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
674 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
675 EXPECT_TRUE(m2.Matches(' '));
676 EXPECT_FALSE(m2.Matches('\n'));
677}
678
zhanyong.wan16cf4732009-05-14 20:55:30 +0000679// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
680// T and U are arithmetic types and T can be losslessly converted to
681// U.
682TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
zhanyong.wan18490652009-05-11 18:54:08 +0000683 Matcher<double> m1 = DoubleEq(1.0);
zhanyong.wan16cf4732009-05-14 20:55:30 +0000684 Matcher<float> m2 = SafeMatcherCast<float>(m1);
685 EXPECT_TRUE(m2.Matches(1.0f));
686 EXPECT_FALSE(m2.Matches(2.0f));
687
688 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
689 EXPECT_TRUE(m3.Matches('a'));
690 EXPECT_FALSE(m3.Matches('b'));
zhanyong.wan18490652009-05-11 18:54:08 +0000691}
692
693// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
694// are pointers or references to a derived and a base class, correspondingly.
695TEST(SafeMatcherCastTest, FromBaseClass) {
696 Derived d, d2;
697 Matcher<Base*> m1 = Eq(&d);
698 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
699 EXPECT_TRUE(m2.Matches(&d));
700 EXPECT_FALSE(m2.Matches(&d2));
701
702 Matcher<Base&> m3 = Ref(d);
703 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
704 EXPECT_TRUE(m4.Matches(d));
705 EXPECT_FALSE(m4.Matches(d2));
706}
707
708// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
709TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
710 int n = 0;
711 Matcher<const int&> m1 = Ref(n);
712 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
713 int n1 = 0;
714 EXPECT_TRUE(m2.Matches(n));
715 EXPECT_FALSE(m2.Matches(n1));
716}
717
718// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
719TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
720 Matcher<int> m1 = Eq(0);
721 Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
722 EXPECT_TRUE(m2.Matches(0));
723 EXPECT_FALSE(m2.Matches(1));
724}
725
726// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
727TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
728 Matcher<int> m1 = Eq(0);
729 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
730 int n = 0;
731 EXPECT_TRUE(m2.Matches(n));
732 n = 1;
733 EXPECT_FALSE(m2.Matches(n));
734}
735
736// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
737TEST(SafeMatcherCastTest, FromSameType) {
738 Matcher<int> m1 = Eq(0);
739 Matcher<int> m2 = SafeMatcherCast<int>(m1);
740 EXPECT_TRUE(m2.Matches(0));
741 EXPECT_FALSE(m2.Matches(1));
742}
743
jgm79a367e2012-04-10 16:02:11 +0000744TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
745 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
746 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
747 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
748}
749
750TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
751 Matcher<ConvertibleFromAny> m =
752 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
753 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
754 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
755}
756
kosak5f2a6ca2013-12-03 01:43:07 +0000757TEST(SafeMatcherCastTest, ValueIsNotCopied) {
758 int n = 42;
759 Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
760 // Verify that the matcher holds a reference to n, not to its temporary copy.
761 EXPECT_TRUE(m.Matches(n));
762}
763
shiqiane35fdd92008-12-10 05:08:54 +0000764// Tests that A<T>() matches any value of type T.
765TEST(ATest, MatchesAnyValue) {
766 // Tests a matcher for a value type.
767 Matcher<double> m1 = A<double>();
768 EXPECT_TRUE(m1.Matches(91.43));
769 EXPECT_TRUE(m1.Matches(-15.32));
770
771 // Tests a matcher for a reference type.
772 int a = 2;
773 int b = -6;
774 Matcher<int&> m2 = A<int&>();
775 EXPECT_TRUE(m2.Matches(a));
776 EXPECT_TRUE(m2.Matches(b));
777}
778
zhanyong.wanf4274522013-04-24 02:49:43 +0000779TEST(ATest, WorksForDerivedClass) {
780 Base base;
781 Derived derived;
782 EXPECT_THAT(&base, A<Base*>());
783 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
784 EXPECT_THAT(&derived, A<Base*>());
785 EXPECT_THAT(&derived, A<Derived*>());
786}
787
shiqiane35fdd92008-12-10 05:08:54 +0000788// Tests that A<T>() describes itself properly.
789TEST(ATest, CanDescribeSelf) {
790 EXPECT_EQ("is anything", Describe(A<bool>()));
791}
792
793// Tests that An<T>() matches any value of type T.
794TEST(AnTest, MatchesAnyValue) {
795 // Tests a matcher for a value type.
796 Matcher<int> m1 = An<int>();
797 EXPECT_TRUE(m1.Matches(9143));
798 EXPECT_TRUE(m1.Matches(-1532));
799
800 // Tests a matcher for a reference type.
801 int a = 2;
802 int b = -6;
803 Matcher<int&> m2 = An<int&>();
804 EXPECT_TRUE(m2.Matches(a));
805 EXPECT_TRUE(m2.Matches(b));
806}
807
808// Tests that An<T>() describes itself properly.
809TEST(AnTest, CanDescribeSelf) {
810 EXPECT_EQ("is anything", Describe(An<int>()));
811}
812
813// Tests that _ can be used as a matcher for any type and matches any
814// value of that type.
815TEST(UnderscoreTest, MatchesAnyValue) {
816 // Uses _ as a matcher for a value type.
817 Matcher<int> m1 = _;
818 EXPECT_TRUE(m1.Matches(123));
819 EXPECT_TRUE(m1.Matches(-242));
820
821 // Uses _ as a matcher for a reference type.
822 bool a = false;
823 const bool b = true;
824 Matcher<const bool&> m2 = _;
825 EXPECT_TRUE(m2.Matches(a));
826 EXPECT_TRUE(m2.Matches(b));
827}
828
829// Tests that _ describes itself properly.
830TEST(UnderscoreTest, CanDescribeSelf) {
831 Matcher<int> m = _;
832 EXPECT_EQ("is anything", Describe(m));
833}
834
835// Tests that Eq(x) matches any value equal to x.
836TEST(EqTest, MatchesEqualValue) {
837 // 2 C-strings with same content but different addresses.
838 const char a1[] = "hi";
839 const char a2[] = "hi";
840
841 Matcher<const char*> m1 = Eq(a1);
842 EXPECT_TRUE(m1.Matches(a1));
843 EXPECT_FALSE(m1.Matches(a2));
844}
845
846// Tests that Eq(v) describes itself properly.
847
848class Unprintable {
849 public:
850 Unprintable() : c_('a') {}
851
zhanyong.wan32de5f52009-12-23 00:13:23 +0000852 bool operator==(const Unprintable& /* rhs */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000853 private:
854 char c_;
855};
856
857TEST(EqTest, CanDescribeSelf) {
858 Matcher<Unprintable> m = Eq(Unprintable());
859 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
860}
861
862// Tests that Eq(v) can be used to match any type that supports
863// comparing with type T, where T is v's type.
864TEST(EqTest, IsPolymorphic) {
865 Matcher<int> m1 = Eq(1);
866 EXPECT_TRUE(m1.Matches(1));
867 EXPECT_FALSE(m1.Matches(2));
868
869 Matcher<char> m2 = Eq(1);
870 EXPECT_TRUE(m2.Matches('\1'));
871 EXPECT_FALSE(m2.Matches('a'));
872}
873
874// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
875TEST(TypedEqTest, ChecksEqualityForGivenType) {
876 Matcher<char> m1 = TypedEq<char>('a');
877 EXPECT_TRUE(m1.Matches('a'));
878 EXPECT_FALSE(m1.Matches('b'));
879
880 Matcher<int> m2 = TypedEq<int>(6);
881 EXPECT_TRUE(m2.Matches(6));
882 EXPECT_FALSE(m2.Matches(7));
883}
884
885// Tests that TypedEq(v) describes itself properly.
886TEST(TypedEqTest, CanDescribeSelf) {
887 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
888}
889
890// Tests that TypedEq<T>(v) has type Matcher<T>.
891
892// Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
893// is a "bare" type (i.e. not in the form of const U or U&). If v's
894// type is not T, the compiler will generate a message about
895// "undefined referece".
896template <typename T>
897struct Type {
zhanyong.wan32de5f52009-12-23 00:13:23 +0000898 static bool IsTypeOf(const T& /* v */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000899
900 template <typename T2>
901 static void IsTypeOf(T2 v);
902};
903
904TEST(TypedEqTest, HasSpecifiedType) {
905 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
906 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
907 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
908}
909
910// Tests that Ge(v) matches anything >= v.
911TEST(GeTest, ImplementsGreaterThanOrEqual) {
912 Matcher<int> m1 = Ge(0);
913 EXPECT_TRUE(m1.Matches(1));
914 EXPECT_TRUE(m1.Matches(0));
915 EXPECT_FALSE(m1.Matches(-1));
916}
917
918// Tests that Ge(v) describes itself properly.
919TEST(GeTest, CanDescribeSelf) {
920 Matcher<int> m = Ge(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000921 EXPECT_EQ("is >= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000922}
923
924// Tests that Gt(v) matches anything > v.
925TEST(GtTest, ImplementsGreaterThan) {
926 Matcher<double> m1 = Gt(0);
927 EXPECT_TRUE(m1.Matches(1.0));
928 EXPECT_FALSE(m1.Matches(0.0));
929 EXPECT_FALSE(m1.Matches(-1.0));
930}
931
932// Tests that Gt(v) describes itself properly.
933TEST(GtTest, CanDescribeSelf) {
934 Matcher<int> m = Gt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000935 EXPECT_EQ("is > 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000936}
937
938// Tests that Le(v) matches anything <= v.
939TEST(LeTest, ImplementsLessThanOrEqual) {
940 Matcher<char> m1 = Le('b');
941 EXPECT_TRUE(m1.Matches('a'));
942 EXPECT_TRUE(m1.Matches('b'));
943 EXPECT_FALSE(m1.Matches('c'));
944}
945
946// Tests that Le(v) describes itself properly.
947TEST(LeTest, CanDescribeSelf) {
948 Matcher<int> m = Le(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000949 EXPECT_EQ("is <= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000950}
951
952// Tests that Lt(v) matches anything < v.
953TEST(LtTest, ImplementsLessThan) {
954 Matcher<const string&> m1 = Lt("Hello");
955 EXPECT_TRUE(m1.Matches("Abc"));
956 EXPECT_FALSE(m1.Matches("Hello"));
957 EXPECT_FALSE(m1.Matches("Hello, world!"));
958}
959
960// Tests that Lt(v) describes itself properly.
961TEST(LtTest, CanDescribeSelf) {
962 Matcher<int> m = Lt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000963 EXPECT_EQ("is < 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000964}
965
966// Tests that Ne(v) matches anything != v.
967TEST(NeTest, ImplementsNotEqual) {
968 Matcher<int> m1 = Ne(0);
969 EXPECT_TRUE(m1.Matches(1));
970 EXPECT_TRUE(m1.Matches(-1));
971 EXPECT_FALSE(m1.Matches(0));
972}
973
974// Tests that Ne(v) describes itself properly.
975TEST(NeTest, CanDescribeSelf) {
976 Matcher<int> m = Ne(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000977 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000978}
979
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000980// Tests that IsNull() matches any NULL pointer of any type.
981TEST(IsNullTest, MatchesNullPointer) {
982 Matcher<int*> m1 = IsNull();
983 int* p1 = NULL;
984 int n = 0;
985 EXPECT_TRUE(m1.Matches(p1));
986 EXPECT_FALSE(m1.Matches(&n));
987
988 Matcher<const char*> m2 = IsNull();
989 const char* p2 = NULL;
990 EXPECT_TRUE(m2.Matches(p2));
991 EXPECT_FALSE(m2.Matches("hi"));
992
zhanyong.wan95b12332009-09-25 18:55:50 +0000993#if !GTEST_OS_SYMBIAN
994 // Nokia's Symbian compiler generates:
995 // gmock-matchers.h: ambiguous access to overloaded function
996 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
997 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
998 // MatcherInterface<void *> *)'
999 // gmock-matchers.h: (point of instantiation: 'testing::
1000 // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
1001 // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001002 Matcher<void*> m3 = IsNull();
1003 void* p3 = NULL;
1004 EXPECT_TRUE(m3.Matches(p3));
1005 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
zhanyong.wan95b12332009-09-25 18:55:50 +00001006#endif
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001007}
1008
vladlosev79b83502009-11-18 00:43:37 +00001009TEST(IsNullTest, LinkedPtr) {
1010 const Matcher<linked_ptr<int> > m = IsNull();
1011 const linked_ptr<int> null_p;
1012 const linked_ptr<int> non_null_p(new int);
1013
1014 EXPECT_TRUE(m.Matches(null_p));
1015 EXPECT_FALSE(m.Matches(non_null_p));
1016}
1017
1018TEST(IsNullTest, ReferenceToConstLinkedPtr) {
1019 const Matcher<const linked_ptr<double>&> m = IsNull();
1020 const linked_ptr<double> null_p;
1021 const linked_ptr<double> non_null_p(new double);
1022
1023 EXPECT_TRUE(m.Matches(null_p));
1024 EXPECT_FALSE(m.Matches(non_null_p));
1025}
1026
vladloseve56daa72009-11-18 01:08:08 +00001027TEST(IsNullTest, ReferenceToConstScopedPtr) {
1028 const Matcher<const scoped_ptr<double>&> m = IsNull();
1029 const scoped_ptr<double> null_p;
1030 const scoped_ptr<double> non_null_p(new double);
1031
1032 EXPECT_TRUE(m.Matches(null_p));
1033 EXPECT_FALSE(m.Matches(non_null_p));
1034}
1035
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001036// Tests that IsNull() describes itself properly.
1037TEST(IsNullTest, CanDescribeSelf) {
1038 Matcher<int*> m = IsNull();
1039 EXPECT_EQ("is NULL", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001040 EXPECT_EQ("isn't NULL", DescribeNegation(m));
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001041}
1042
shiqiane35fdd92008-12-10 05:08:54 +00001043// Tests that NotNull() matches any non-NULL pointer of any type.
1044TEST(NotNullTest, MatchesNonNullPointer) {
1045 Matcher<int*> m1 = NotNull();
1046 int* p1 = NULL;
1047 int n = 0;
1048 EXPECT_FALSE(m1.Matches(p1));
1049 EXPECT_TRUE(m1.Matches(&n));
1050
1051 Matcher<const char*> m2 = NotNull();
1052 const char* p2 = NULL;
1053 EXPECT_FALSE(m2.Matches(p2));
1054 EXPECT_TRUE(m2.Matches("hi"));
1055}
1056
vladlosev79b83502009-11-18 00:43:37 +00001057TEST(NotNullTest, LinkedPtr) {
1058 const Matcher<linked_ptr<int> > m = NotNull();
1059 const linked_ptr<int> null_p;
1060 const linked_ptr<int> non_null_p(new int);
1061
1062 EXPECT_FALSE(m.Matches(null_p));
1063 EXPECT_TRUE(m.Matches(non_null_p));
1064}
1065
1066TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1067 const Matcher<const linked_ptr<double>&> m = NotNull();
1068 const linked_ptr<double> null_p;
1069 const linked_ptr<double> non_null_p(new double);
1070
1071 EXPECT_FALSE(m.Matches(null_p));
1072 EXPECT_TRUE(m.Matches(non_null_p));
1073}
1074
vladloseve56daa72009-11-18 01:08:08 +00001075TEST(NotNullTest, ReferenceToConstScopedPtr) {
1076 const Matcher<const scoped_ptr<double>&> m = NotNull();
1077 const scoped_ptr<double> null_p;
1078 const scoped_ptr<double> non_null_p(new double);
1079
1080 EXPECT_FALSE(m.Matches(null_p));
1081 EXPECT_TRUE(m.Matches(non_null_p));
1082}
1083
shiqiane35fdd92008-12-10 05:08:54 +00001084// Tests that NotNull() describes itself properly.
1085TEST(NotNullTest, CanDescribeSelf) {
1086 Matcher<int*> m = NotNull();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001087 EXPECT_EQ("isn't NULL", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001088}
1089
1090// Tests that Ref(variable) matches an argument that references
1091// 'variable'.
1092TEST(RefTest, MatchesSameVariable) {
1093 int a = 0;
1094 int b = 0;
1095 Matcher<int&> m = Ref(a);
1096 EXPECT_TRUE(m.Matches(a));
1097 EXPECT_FALSE(m.Matches(b));
1098}
1099
1100// Tests that Ref(variable) describes itself properly.
1101TEST(RefTest, CanDescribeSelf) {
1102 int n = 5;
1103 Matcher<int&> m = Ref(n);
1104 stringstream ss;
1105 ss << "references the variable @" << &n << " 5";
1106 EXPECT_EQ(string(ss.str()), Describe(m));
1107}
1108
1109// Test that Ref(non_const_varialbe) can be used as a matcher for a
1110// const reference.
1111TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1112 int a = 0;
1113 int b = 0;
1114 Matcher<const int&> m = Ref(a);
1115 EXPECT_TRUE(m.Matches(a));
1116 EXPECT_FALSE(m.Matches(b));
1117}
1118
1119// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1120// used wherever Ref(base) can be used (Ref(derived) is a sub-type
1121// of Ref(base), but not vice versa.
1122
shiqiane35fdd92008-12-10 05:08:54 +00001123TEST(RefTest, IsCovariant) {
1124 Base base, base2;
1125 Derived derived;
1126 Matcher<const Base&> m1 = Ref(base);
1127 EXPECT_TRUE(m1.Matches(base));
1128 EXPECT_FALSE(m1.Matches(base2));
1129 EXPECT_FALSE(m1.Matches(derived));
1130
1131 m1 = Ref(derived);
1132 EXPECT_TRUE(m1.Matches(derived));
1133 EXPECT_FALSE(m1.Matches(base));
1134 EXPECT_FALSE(m1.Matches(base2));
1135}
1136
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001137TEST(RefTest, ExplainsResult) {
1138 int n = 0;
1139 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1140 StartsWith("which is located @"));
1141
1142 int m = 0;
1143 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1144 StartsWith("which is located @"));
1145}
1146
shiqiane35fdd92008-12-10 05:08:54 +00001147// Tests string comparison matchers.
1148
1149TEST(StrEqTest, MatchesEqualString) {
1150 Matcher<const char*> m = StrEq(string("Hello"));
1151 EXPECT_TRUE(m.Matches("Hello"));
1152 EXPECT_FALSE(m.Matches("hello"));
1153 EXPECT_FALSE(m.Matches(NULL));
1154
1155 Matcher<const string&> m2 = StrEq("Hello");
1156 EXPECT_TRUE(m2.Matches("Hello"));
1157 EXPECT_FALSE(m2.Matches("Hi"));
1158}
1159
1160TEST(StrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001161 Matcher<string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1162 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
shiqiane35fdd92008-12-10 05:08:54 +00001163 Describe(m));
1164
1165 string str("01204500800");
1166 str[3] = '\0';
1167 Matcher<string> m2 = StrEq(str);
1168 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1169 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1170 Matcher<string> m3 = StrEq(str);
1171 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1172}
1173
1174TEST(StrNeTest, MatchesUnequalString) {
1175 Matcher<const char*> m = StrNe("Hello");
1176 EXPECT_TRUE(m.Matches(""));
1177 EXPECT_TRUE(m.Matches(NULL));
1178 EXPECT_FALSE(m.Matches("Hello"));
1179
1180 Matcher<string> m2 = StrNe(string("Hello"));
1181 EXPECT_TRUE(m2.Matches("hello"));
1182 EXPECT_FALSE(m2.Matches("Hello"));
1183}
1184
1185TEST(StrNeTest, CanDescribeSelf) {
1186 Matcher<const char*> m = StrNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001187 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001188}
1189
1190TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1191 Matcher<const char*> m = StrCaseEq(string("Hello"));
1192 EXPECT_TRUE(m.Matches("Hello"));
1193 EXPECT_TRUE(m.Matches("hello"));
1194 EXPECT_FALSE(m.Matches("Hi"));
1195 EXPECT_FALSE(m.Matches(NULL));
1196
1197 Matcher<const string&> m2 = StrCaseEq("Hello");
1198 EXPECT_TRUE(m2.Matches("hello"));
1199 EXPECT_FALSE(m2.Matches("Hi"));
1200}
1201
1202TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1203 string str1("oabocdooeoo");
1204 string str2("OABOCDOOEOO");
1205 Matcher<const string&> m0 = StrCaseEq(str1);
1206 EXPECT_FALSE(m0.Matches(str2 + string(1, '\0')));
1207
1208 str1[3] = str2[3] = '\0';
1209 Matcher<const string&> m1 = StrCaseEq(str1);
1210 EXPECT_TRUE(m1.Matches(str2));
1211
1212 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1213 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1214 Matcher<const string&> m2 = StrCaseEq(str1);
1215 str1[9] = str2[9] = '\0';
1216 EXPECT_FALSE(m2.Matches(str2));
1217
1218 Matcher<const string&> m3 = StrCaseEq(str1);
1219 EXPECT_TRUE(m3.Matches(str2));
1220
1221 EXPECT_FALSE(m3.Matches(str2 + "x"));
1222 str2.append(1, '\0');
1223 EXPECT_FALSE(m3.Matches(str2));
1224 EXPECT_FALSE(m3.Matches(string(str2, 0, 9)));
1225}
1226
1227TEST(StrCaseEqTest, CanDescribeSelf) {
1228 Matcher<string> m = StrCaseEq("Hi");
1229 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1230}
1231
1232TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1233 Matcher<const char*> m = StrCaseNe("Hello");
1234 EXPECT_TRUE(m.Matches("Hi"));
1235 EXPECT_TRUE(m.Matches(NULL));
1236 EXPECT_FALSE(m.Matches("Hello"));
1237 EXPECT_FALSE(m.Matches("hello"));
1238
1239 Matcher<string> m2 = StrCaseNe(string("Hello"));
1240 EXPECT_TRUE(m2.Matches(""));
1241 EXPECT_FALSE(m2.Matches("Hello"));
1242}
1243
1244TEST(StrCaseNeTest, CanDescribeSelf) {
1245 Matcher<const char*> m = StrCaseNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001246 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001247}
1248
1249// Tests that HasSubstr() works for matching string-typed values.
1250TEST(HasSubstrTest, WorksForStringClasses) {
1251 const Matcher<string> m1 = HasSubstr("foo");
1252 EXPECT_TRUE(m1.Matches(string("I love food.")));
1253 EXPECT_FALSE(m1.Matches(string("tofo")));
1254
1255 const Matcher<const std::string&> m2 = HasSubstr("foo");
1256 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1257 EXPECT_FALSE(m2.Matches(std::string("tofo")));
1258}
1259
1260// Tests that HasSubstr() works for matching C-string-typed values.
1261TEST(HasSubstrTest, WorksForCStrings) {
1262 const Matcher<char*> m1 = HasSubstr("foo");
1263 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1264 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1265 EXPECT_FALSE(m1.Matches(NULL));
1266
1267 const Matcher<const char*> m2 = HasSubstr("foo");
1268 EXPECT_TRUE(m2.Matches("I love food."));
1269 EXPECT_FALSE(m2.Matches("tofo"));
1270 EXPECT_FALSE(m2.Matches(NULL));
1271}
1272
1273// Tests that HasSubstr(s) describes itself properly.
1274TEST(HasSubstrTest, CanDescribeSelf) {
1275 Matcher<string> m = HasSubstr("foo\n\"");
1276 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1277}
1278
zhanyong.wanb5937da2009-07-16 20:26:41 +00001279TEST(KeyTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001280 Matcher<const pair<std::string, int>&> m = Key("foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001281 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001282 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1283}
1284
1285TEST(KeyTest, ExplainsResult) {
1286 Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1287 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1288 Explain(m, make_pair(5, true)));
1289 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1290 Explain(m, make_pair(15, true)));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001291}
1292
1293TEST(KeyTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001294 pair<int, std::string> p(25, "foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001295 EXPECT_THAT(p, Key(25));
1296 EXPECT_THAT(p, Not(Key(42)));
1297 EXPECT_THAT(p, Key(Ge(20)));
1298 EXPECT_THAT(p, Not(Key(Lt(25))));
1299}
1300
1301TEST(KeyTest, SafelyCastsInnerMatcher) {
1302 Matcher<int> is_positive = Gt(0);
1303 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001304 pair<char, bool> p('a', true);
zhanyong.wanb5937da2009-07-16 20:26:41 +00001305 EXPECT_THAT(p, Key(is_positive));
1306 EXPECT_THAT(p, Not(Key(is_negative)));
1307}
1308
1309TEST(KeyTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001310 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001311 container.insert(make_pair(1, 'a'));
1312 container.insert(make_pair(2, 'b'));
1313 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001314 EXPECT_THAT(container, Contains(Key(1)));
1315 EXPECT_THAT(container, Not(Contains(Key(3))));
1316}
1317
1318TEST(KeyTest, InsideContainsUsingMultimap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001319 multimap<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001320 container.insert(make_pair(1, 'a'));
1321 container.insert(make_pair(2, 'b'));
1322 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001323
1324 EXPECT_THAT(container, Not(Contains(Key(25))));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001325 container.insert(make_pair(25, 'd'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001326 EXPECT_THAT(container, Contains(Key(25)));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001327 container.insert(make_pair(25, 'e'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001328 EXPECT_THAT(container, Contains(Key(25)));
1329
1330 EXPECT_THAT(container, Contains(Key(1)));
1331 EXPECT_THAT(container, Not(Contains(Key(3))));
1332}
1333
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001334TEST(PairTest, Typing) {
1335 // Test verifies the following type conversions can be compiled.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001336 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1337 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1338 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001339
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001340 Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1341 Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001342}
1343
1344TEST(PairTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001345 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001346 EXPECT_EQ("has a first field that is equal to \"foo\""
1347 ", and has a second field that is equal to 42",
1348 Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001349 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1350 ", or has a second field that isn't equal to 42",
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001351 DescribeNegation(m1));
1352 // Double and triple negation (1 or 2 times not and description of negation).
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001353 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1354 EXPECT_EQ("has a first field that isn't equal to 13"
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001355 ", and has a second field that is equal to 42",
1356 DescribeNegation(m2));
1357}
1358
1359TEST(PairTest, CanExplainMatchResultTo) {
zhanyong.wan82113312010-01-08 21:55:40 +00001360 // If neither field matches, Pair() should explain about the first
1361 // field.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001362 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001363 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001364 Explain(m, make_pair(-1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001365
zhanyong.wan82113312010-01-08 21:55:40 +00001366 // If the first field matches but the second doesn't, Pair() should
1367 // explain about the second field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001368 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001369 Explain(m, make_pair(1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001370
zhanyong.wan82113312010-01-08 21:55:40 +00001371 // If the first field doesn't match but the second does, Pair()
1372 // should explain about the first field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001373 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001374 Explain(m, make_pair(-1, 2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001375
zhanyong.wan82113312010-01-08 21:55:40 +00001376 // If both fields match, Pair() should explain about them both.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001377 EXPECT_EQ("whose both fields match, where the first field is a value "
1378 "which is 1 more than 0, and the second field is a value "
1379 "which is 2 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001380 Explain(m, make_pair(1, 2)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001381
1382 // If only the first match has an explanation, only this explanation should
1383 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001384 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001385 EXPECT_EQ("whose both fields match, where the first field is a value "
1386 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001387 Explain(explain_first, make_pair(1, 0)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001388
1389 // If only the second match has an explanation, only this explanation should
1390 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001391 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001392 EXPECT_EQ("whose both fields match, where the second field is a value "
1393 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001394 Explain(explain_second, make_pair(0, 1)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001395}
1396
1397TEST(PairTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001398 pair<int, std::string> p(25, "foo");
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001399
1400 // Both fields match.
1401 EXPECT_THAT(p, Pair(25, "foo"));
1402 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1403
1404 // 'first' doesnt' match, but 'second' matches.
1405 EXPECT_THAT(p, Not(Pair(42, "foo")));
1406 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1407
1408 // 'first' matches, but 'second' doesn't match.
1409 EXPECT_THAT(p, Not(Pair(25, "bar")));
1410 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1411
1412 // Neither field matches.
1413 EXPECT_THAT(p, Not(Pair(13, "bar")));
1414 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1415}
1416
1417TEST(PairTest, SafelyCastsInnerMatchers) {
1418 Matcher<int> is_positive = Gt(0);
1419 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001420 pair<char, bool> p('a', true);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001421 EXPECT_THAT(p, Pair(is_positive, _));
1422 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1423 EXPECT_THAT(p, Pair(_, is_positive));
1424 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1425}
1426
1427TEST(PairTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001428 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001429 container.insert(make_pair(1, 'a'));
1430 container.insert(make_pair(2, 'b'));
1431 container.insert(make_pair(4, 'c'));
zhanyong.wan95b12332009-09-25 18:55:50 +00001432 EXPECT_THAT(container, Contains(Pair(1, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001433 EXPECT_THAT(container, Contains(Pair(1, _)));
zhanyong.wan95b12332009-09-25 18:55:50 +00001434 EXPECT_THAT(container, Contains(Pair(_, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001435 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1436}
1437
shiqiane35fdd92008-12-10 05:08:54 +00001438// Tests StartsWith(s).
1439
1440TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1441 const Matcher<const char*> m1 = StartsWith(string(""));
1442 EXPECT_TRUE(m1.Matches("Hi"));
1443 EXPECT_TRUE(m1.Matches(""));
1444 EXPECT_FALSE(m1.Matches(NULL));
1445
1446 const Matcher<const string&> m2 = StartsWith("Hi");
1447 EXPECT_TRUE(m2.Matches("Hi"));
1448 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1449 EXPECT_TRUE(m2.Matches("High"));
1450 EXPECT_FALSE(m2.Matches("H"));
1451 EXPECT_FALSE(m2.Matches(" Hi"));
1452}
1453
1454TEST(StartsWithTest, CanDescribeSelf) {
1455 Matcher<const std::string> m = StartsWith("Hi");
1456 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1457}
1458
1459// Tests EndsWith(s).
1460
1461TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1462 const Matcher<const char*> m1 = EndsWith("");
1463 EXPECT_TRUE(m1.Matches("Hi"));
1464 EXPECT_TRUE(m1.Matches(""));
1465 EXPECT_FALSE(m1.Matches(NULL));
1466
1467 const Matcher<const string&> m2 = EndsWith(string("Hi"));
1468 EXPECT_TRUE(m2.Matches("Hi"));
1469 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1470 EXPECT_TRUE(m2.Matches("Super Hi"));
1471 EXPECT_FALSE(m2.Matches("i"));
1472 EXPECT_FALSE(m2.Matches("Hi "));
1473}
1474
1475TEST(EndsWithTest, CanDescribeSelf) {
1476 Matcher<const std::string> m = EndsWith("Hi");
1477 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1478}
1479
shiqiane35fdd92008-12-10 05:08:54 +00001480// Tests MatchesRegex().
1481
1482TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1483 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1484 EXPECT_TRUE(m1.Matches("az"));
1485 EXPECT_TRUE(m1.Matches("abcz"));
1486 EXPECT_FALSE(m1.Matches(NULL));
1487
1488 const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z"));
1489 EXPECT_TRUE(m2.Matches("azbz"));
1490 EXPECT_FALSE(m2.Matches("az1"));
1491 EXPECT_FALSE(m2.Matches("1az"));
1492}
1493
1494TEST(MatchesRegexTest, CanDescribeSelf) {
1495 Matcher<const std::string> m1 = MatchesRegex(string("Hi.*"));
1496 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1497
zhanyong.wand14aaed2010-01-14 05:36:32 +00001498 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1499 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001500}
1501
1502// Tests ContainsRegex().
1503
1504TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1505 const Matcher<const char*> m1 = ContainsRegex(string("a.*z"));
1506 EXPECT_TRUE(m1.Matches("az"));
1507 EXPECT_TRUE(m1.Matches("0abcz1"));
1508 EXPECT_FALSE(m1.Matches(NULL));
1509
1510 const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z"));
1511 EXPECT_TRUE(m2.Matches("azbz"));
1512 EXPECT_TRUE(m2.Matches("az1"));
1513 EXPECT_FALSE(m2.Matches("1a"));
1514}
1515
1516TEST(ContainsRegexTest, CanDescribeSelf) {
1517 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1518 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1519
zhanyong.wand14aaed2010-01-14 05:36:32 +00001520 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1521 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001522}
shiqiane35fdd92008-12-10 05:08:54 +00001523
1524// Tests for wide strings.
1525#if GTEST_HAS_STD_WSTRING
1526TEST(StdWideStrEqTest, MatchesEqual) {
1527 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1528 EXPECT_TRUE(m.Matches(L"Hello"));
1529 EXPECT_FALSE(m.Matches(L"hello"));
1530 EXPECT_FALSE(m.Matches(NULL));
1531
1532 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1533 EXPECT_TRUE(m2.Matches(L"Hello"));
1534 EXPECT_FALSE(m2.Matches(L"Hi"));
1535
1536 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1537 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1538 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1539
1540 ::std::wstring str(L"01204500800");
1541 str[3] = L'\0';
1542 Matcher<const ::std::wstring&> m4 = StrEq(str);
1543 EXPECT_TRUE(m4.Matches(str));
1544 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1545 Matcher<const ::std::wstring&> m5 = StrEq(str);
1546 EXPECT_TRUE(m5.Matches(str));
1547}
1548
1549TEST(StdWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001550 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1551 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001552 Describe(m));
1553
1554 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1555 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1556 Describe(m2));
1557
1558 ::std::wstring str(L"01204500800");
1559 str[3] = L'\0';
1560 Matcher<const ::std::wstring&> m4 = StrEq(str);
1561 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1562 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1563 Matcher<const ::std::wstring&> m5 = StrEq(str);
1564 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1565}
1566
1567TEST(StdWideStrNeTest, MatchesUnequalString) {
1568 Matcher<const wchar_t*> m = StrNe(L"Hello");
1569 EXPECT_TRUE(m.Matches(L""));
1570 EXPECT_TRUE(m.Matches(NULL));
1571 EXPECT_FALSE(m.Matches(L"Hello"));
1572
1573 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1574 EXPECT_TRUE(m2.Matches(L"hello"));
1575 EXPECT_FALSE(m2.Matches(L"Hello"));
1576}
1577
1578TEST(StdWideStrNeTest, CanDescribeSelf) {
1579 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001580 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001581}
1582
1583TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1584 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1585 EXPECT_TRUE(m.Matches(L"Hello"));
1586 EXPECT_TRUE(m.Matches(L"hello"));
1587 EXPECT_FALSE(m.Matches(L"Hi"));
1588 EXPECT_FALSE(m.Matches(NULL));
1589
1590 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1591 EXPECT_TRUE(m2.Matches(L"hello"));
1592 EXPECT_FALSE(m2.Matches(L"Hi"));
1593}
1594
1595TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1596 ::std::wstring str1(L"oabocdooeoo");
1597 ::std::wstring str2(L"OABOCDOOEOO");
1598 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1599 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1600
1601 str1[3] = str2[3] = L'\0';
1602 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1603 EXPECT_TRUE(m1.Matches(str2));
1604
1605 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1606 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1607 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1608 str1[9] = str2[9] = L'\0';
1609 EXPECT_FALSE(m2.Matches(str2));
1610
1611 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1612 EXPECT_TRUE(m3.Matches(str2));
1613
1614 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1615 str2.append(1, L'\0');
1616 EXPECT_FALSE(m3.Matches(str2));
1617 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1618}
1619
1620TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1621 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1622 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1623}
1624
1625TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1626 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1627 EXPECT_TRUE(m.Matches(L"Hi"));
1628 EXPECT_TRUE(m.Matches(NULL));
1629 EXPECT_FALSE(m.Matches(L"Hello"));
1630 EXPECT_FALSE(m.Matches(L"hello"));
1631
1632 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1633 EXPECT_TRUE(m2.Matches(L""));
1634 EXPECT_FALSE(m2.Matches(L"Hello"));
1635}
1636
1637TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1638 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001639 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001640}
1641
1642// Tests that HasSubstr() works for matching wstring-typed values.
1643TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1644 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1645 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1646 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1647
1648 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1649 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1650 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1651}
1652
1653// Tests that HasSubstr() works for matching C-wide-string-typed values.
1654TEST(StdWideHasSubstrTest, WorksForCStrings) {
1655 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1656 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1657 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1658 EXPECT_FALSE(m1.Matches(NULL));
1659
1660 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1661 EXPECT_TRUE(m2.Matches(L"I love food."));
1662 EXPECT_FALSE(m2.Matches(L"tofo"));
1663 EXPECT_FALSE(m2.Matches(NULL));
1664}
1665
1666// Tests that HasSubstr(s) describes itself properly.
1667TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1668 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1669 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1670}
1671
1672// Tests StartsWith(s).
1673
1674TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1675 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1676 EXPECT_TRUE(m1.Matches(L"Hi"));
1677 EXPECT_TRUE(m1.Matches(L""));
1678 EXPECT_FALSE(m1.Matches(NULL));
1679
1680 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1681 EXPECT_TRUE(m2.Matches(L"Hi"));
1682 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1683 EXPECT_TRUE(m2.Matches(L"High"));
1684 EXPECT_FALSE(m2.Matches(L"H"));
1685 EXPECT_FALSE(m2.Matches(L" Hi"));
1686}
1687
1688TEST(StdWideStartsWithTest, CanDescribeSelf) {
1689 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
1690 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1691}
1692
1693// Tests EndsWith(s).
1694
1695TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
1696 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1697 EXPECT_TRUE(m1.Matches(L"Hi"));
1698 EXPECT_TRUE(m1.Matches(L""));
1699 EXPECT_FALSE(m1.Matches(NULL));
1700
1701 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
1702 EXPECT_TRUE(m2.Matches(L"Hi"));
1703 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1704 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1705 EXPECT_FALSE(m2.Matches(L"i"));
1706 EXPECT_FALSE(m2.Matches(L"Hi "));
1707}
1708
1709TEST(StdWideEndsWithTest, CanDescribeSelf) {
1710 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
1711 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1712}
1713
1714#endif // GTEST_HAS_STD_WSTRING
1715
1716#if GTEST_HAS_GLOBAL_WSTRING
1717TEST(GlobalWideStrEqTest, MatchesEqual) {
1718 Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
1719 EXPECT_TRUE(m.Matches(L"Hello"));
1720 EXPECT_FALSE(m.Matches(L"hello"));
1721 EXPECT_FALSE(m.Matches(NULL));
1722
1723 Matcher<const ::wstring&> m2 = StrEq(L"Hello");
1724 EXPECT_TRUE(m2.Matches(L"Hello"));
1725 EXPECT_FALSE(m2.Matches(L"Hi"));
1726
1727 Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1728 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1729 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1730
1731 ::wstring str(L"01204500800");
1732 str[3] = L'\0';
1733 Matcher<const ::wstring&> m4 = StrEq(str);
1734 EXPECT_TRUE(m4.Matches(str));
1735 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1736 Matcher<const ::wstring&> m5 = StrEq(str);
1737 EXPECT_TRUE(m5.Matches(str));
1738}
1739
1740TEST(GlobalWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001741 Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1742 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001743 Describe(m));
1744
1745 Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1746 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1747 Describe(m2));
1748
1749 ::wstring str(L"01204500800");
1750 str[3] = L'\0';
1751 Matcher<const ::wstring&> m4 = StrEq(str);
1752 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1753 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1754 Matcher<const ::wstring&> m5 = StrEq(str);
1755 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1756}
1757
1758TEST(GlobalWideStrNeTest, MatchesUnequalString) {
1759 Matcher<const wchar_t*> m = StrNe(L"Hello");
1760 EXPECT_TRUE(m.Matches(L""));
1761 EXPECT_TRUE(m.Matches(NULL));
1762 EXPECT_FALSE(m.Matches(L"Hello"));
1763
1764 Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
1765 EXPECT_TRUE(m2.Matches(L"hello"));
1766 EXPECT_FALSE(m2.Matches(L"Hello"));
1767}
1768
1769TEST(GlobalWideStrNeTest, CanDescribeSelf) {
1770 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001771 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001772}
1773
1774TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1775 Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
1776 EXPECT_TRUE(m.Matches(L"Hello"));
1777 EXPECT_TRUE(m.Matches(L"hello"));
1778 EXPECT_FALSE(m.Matches(L"Hi"));
1779 EXPECT_FALSE(m.Matches(NULL));
1780
1781 Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
1782 EXPECT_TRUE(m2.Matches(L"hello"));
1783 EXPECT_FALSE(m2.Matches(L"Hi"));
1784}
1785
1786TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1787 ::wstring str1(L"oabocdooeoo");
1788 ::wstring str2(L"OABOCDOOEOO");
1789 Matcher<const ::wstring&> m0 = StrCaseEq(str1);
1790 EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
1791
1792 str1[3] = str2[3] = L'\0';
1793 Matcher<const ::wstring&> m1 = StrCaseEq(str1);
1794 EXPECT_TRUE(m1.Matches(str2));
1795
1796 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1797 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1798 Matcher<const ::wstring&> m2 = StrCaseEq(str1);
1799 str1[9] = str2[9] = L'\0';
1800 EXPECT_FALSE(m2.Matches(str2));
1801
1802 Matcher<const ::wstring&> m3 = StrCaseEq(str1);
1803 EXPECT_TRUE(m3.Matches(str2));
1804
1805 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1806 str2.append(1, L'\0');
1807 EXPECT_FALSE(m3.Matches(str2));
1808 EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
1809}
1810
1811TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
1812 Matcher< ::wstring> m = StrCaseEq(L"Hi");
1813 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1814}
1815
1816TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1817 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1818 EXPECT_TRUE(m.Matches(L"Hi"));
1819 EXPECT_TRUE(m.Matches(NULL));
1820 EXPECT_FALSE(m.Matches(L"Hello"));
1821 EXPECT_FALSE(m.Matches(L"hello"));
1822
1823 Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
1824 EXPECT_TRUE(m2.Matches(L""));
1825 EXPECT_FALSE(m2.Matches(L"Hello"));
1826}
1827
1828TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
1829 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001830 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001831}
1832
1833// Tests that HasSubstr() works for matching wstring-typed values.
1834TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
1835 const Matcher< ::wstring> m1 = HasSubstr(L"foo");
1836 EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
1837 EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
1838
1839 const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
1840 EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
1841 EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
1842}
1843
1844// Tests that HasSubstr() works for matching C-wide-string-typed values.
1845TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
1846 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1847 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1848 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1849 EXPECT_FALSE(m1.Matches(NULL));
1850
1851 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1852 EXPECT_TRUE(m2.Matches(L"I love food."));
1853 EXPECT_FALSE(m2.Matches(L"tofo"));
1854 EXPECT_FALSE(m2.Matches(NULL));
1855}
1856
1857// Tests that HasSubstr(s) describes itself properly.
1858TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
1859 Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
1860 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1861}
1862
1863// Tests StartsWith(s).
1864
1865TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
1866 const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
1867 EXPECT_TRUE(m1.Matches(L"Hi"));
1868 EXPECT_TRUE(m1.Matches(L""));
1869 EXPECT_FALSE(m1.Matches(NULL));
1870
1871 const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
1872 EXPECT_TRUE(m2.Matches(L"Hi"));
1873 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1874 EXPECT_TRUE(m2.Matches(L"High"));
1875 EXPECT_FALSE(m2.Matches(L"H"));
1876 EXPECT_FALSE(m2.Matches(L" Hi"));
1877}
1878
1879TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
1880 Matcher<const ::wstring> m = StartsWith(L"Hi");
1881 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1882}
1883
1884// Tests EndsWith(s).
1885
1886TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
1887 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1888 EXPECT_TRUE(m1.Matches(L"Hi"));
1889 EXPECT_TRUE(m1.Matches(L""));
1890 EXPECT_FALSE(m1.Matches(NULL));
1891
1892 const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
1893 EXPECT_TRUE(m2.Matches(L"Hi"));
1894 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1895 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1896 EXPECT_FALSE(m2.Matches(L"i"));
1897 EXPECT_FALSE(m2.Matches(L"Hi "));
1898}
1899
1900TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
1901 Matcher<const ::wstring> m = EndsWith(L"Hi");
1902 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1903}
1904
1905#endif // GTEST_HAS_GLOBAL_WSTRING
1906
1907
kosakbd018832014-04-02 20:30:00 +00001908typedef ::testing::tuple<long, int> Tuple2; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00001909
1910// Tests that Eq() matches a 2-tuple where the first field == the
1911// second field.
1912TEST(Eq2Test, MatchesEqualArguments) {
1913 Matcher<const Tuple2&> m = Eq();
1914 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1915 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1916}
1917
1918// Tests that Eq() describes itself properly.
1919TEST(Eq2Test, CanDescribeSelf) {
1920 Matcher<const Tuple2&> m = Eq();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001921 EXPECT_EQ("are an equal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001922}
1923
1924// Tests that Ge() matches a 2-tuple where the first field >= the
1925// second field.
1926TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
1927 Matcher<const Tuple2&> m = Ge();
1928 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1929 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1930 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1931}
1932
1933// Tests that Ge() describes itself properly.
1934TEST(Ge2Test, CanDescribeSelf) {
1935 Matcher<const Tuple2&> m = Ge();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001936 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001937}
1938
1939// Tests that Gt() matches a 2-tuple where the first field > the
1940// second field.
1941TEST(Gt2Test, MatchesGreaterThanArguments) {
1942 Matcher<const Tuple2&> m = Gt();
1943 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1944 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1945 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1946}
1947
1948// Tests that Gt() describes itself properly.
1949TEST(Gt2Test, CanDescribeSelf) {
1950 Matcher<const Tuple2&> m = Gt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001951 EXPECT_EQ("are a pair where the first > the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001952}
1953
1954// Tests that Le() matches a 2-tuple where the first field <= the
1955// second field.
1956TEST(Le2Test, MatchesLessThanOrEqualArguments) {
1957 Matcher<const Tuple2&> m = Le();
1958 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1959 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1960 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1961}
1962
1963// Tests that Le() describes itself properly.
1964TEST(Le2Test, CanDescribeSelf) {
1965 Matcher<const Tuple2&> m = Le();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001966 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001967}
1968
1969// Tests that Lt() matches a 2-tuple where the first field < the
1970// second field.
1971TEST(Lt2Test, MatchesLessThanArguments) {
1972 Matcher<const Tuple2&> m = Lt();
1973 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1974 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1975 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1976}
1977
1978// Tests that Lt() describes itself properly.
1979TEST(Lt2Test, CanDescribeSelf) {
1980 Matcher<const Tuple2&> m = Lt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001981 EXPECT_EQ("are a pair where the first < the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001982}
1983
1984// Tests that Ne() matches a 2-tuple where the first field != the
1985// second field.
1986TEST(Ne2Test, MatchesUnequalArguments) {
1987 Matcher<const Tuple2&> m = Ne();
1988 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1989 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1990 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1991}
1992
1993// Tests that Ne() describes itself properly.
1994TEST(Ne2Test, CanDescribeSelf) {
1995 Matcher<const Tuple2&> m = Ne();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001996 EXPECT_EQ("are an unequal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001997}
1998
1999// Tests that Not(m) matches any value that doesn't match m.
2000TEST(NotTest, NegatesMatcher) {
2001 Matcher<int> m;
2002 m = Not(Eq(2));
2003 EXPECT_TRUE(m.Matches(3));
2004 EXPECT_FALSE(m.Matches(2));
2005}
2006
2007// Tests that Not(m) describes itself properly.
2008TEST(NotTest, CanDescribeSelf) {
2009 Matcher<int> m = Not(Eq(5));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002010 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002011}
2012
zhanyong.wan18490652009-05-11 18:54:08 +00002013// Tests that monomorphic matchers are safely cast by the Not matcher.
2014TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2015 // greater_than_5 is a monomorphic matcher.
2016 Matcher<int> greater_than_5 = Gt(5);
2017
2018 Matcher<const int&> m = Not(greater_than_5);
2019 Matcher<int&> m2 = Not(greater_than_5);
2020 Matcher<int&> m3 = Not(m);
2021}
2022
zhanyong.wan02c15052010-06-09 19:21:30 +00002023// Helper to allow easy testing of AllOf matchers with num parameters.
2024void AllOfMatches(int num, const Matcher<int>& m) {
2025 SCOPED_TRACE(Describe(m));
2026 EXPECT_TRUE(m.Matches(0));
2027 for (int i = 1; i <= num; ++i) {
2028 EXPECT_FALSE(m.Matches(i));
2029 }
2030 EXPECT_TRUE(m.Matches(num + 1));
2031}
2032
shiqiane35fdd92008-12-10 05:08:54 +00002033// Tests that AllOf(m1, ..., mn) matches any value that matches all of
2034// the given matchers.
2035TEST(AllOfTest, MatchesWhenAllMatch) {
2036 Matcher<int> m;
2037 m = AllOf(Le(2), Ge(1));
2038 EXPECT_TRUE(m.Matches(1));
2039 EXPECT_TRUE(m.Matches(2));
2040 EXPECT_FALSE(m.Matches(0));
2041 EXPECT_FALSE(m.Matches(3));
2042
2043 m = AllOf(Gt(0), Ne(1), Ne(2));
2044 EXPECT_TRUE(m.Matches(3));
2045 EXPECT_FALSE(m.Matches(2));
2046 EXPECT_FALSE(m.Matches(1));
2047 EXPECT_FALSE(m.Matches(0));
2048
2049 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2050 EXPECT_TRUE(m.Matches(4));
2051 EXPECT_FALSE(m.Matches(3));
2052 EXPECT_FALSE(m.Matches(2));
2053 EXPECT_FALSE(m.Matches(1));
2054 EXPECT_FALSE(m.Matches(0));
2055
2056 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2057 EXPECT_TRUE(m.Matches(0));
2058 EXPECT_TRUE(m.Matches(1));
2059 EXPECT_FALSE(m.Matches(3));
zhanyong.wan02c15052010-06-09 19:21:30 +00002060
2061 // The following tests for varying number of sub-matchers. Due to the way
2062 // the sub-matchers are handled it is enough to test every sub-matcher once
2063 // with sub-matchers using the same matcher type. Varying matcher types are
2064 // checked for above.
2065 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2066 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2067 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2068 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2069 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2070 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2071 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2072 Ne(8)));
2073 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2074 Ne(8), Ne(9)));
2075 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2076 Ne(9), Ne(10)));
shiqiane35fdd92008-12-10 05:08:54 +00002077}
2078
zhanyong.wan616180e2013-06-18 18:49:51 +00002079#if GTEST_LANG_CXX11
2080// Tests the variadic version of the AllOfMatcher.
2081TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
2082 // Make sure AllOf is defined in the right namespace and does not depend on
2083 // ADL.
2084 ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2085 Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2086 Ne(9), Ne(10), Ne(11));
2087 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))"));
2088 AllOfMatches(11, m);
2089 AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2090 Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
2091 Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22),
2092 Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29),
2093 Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36),
2094 Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43),
2095 Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2096 Ne(50)));
2097}
2098
2099#endif // GTEST_LANG_CXX11
2100
shiqiane35fdd92008-12-10 05:08:54 +00002101// Tests that AllOf(m1, ..., mn) describes itself properly.
2102TEST(AllOfTest, CanDescribeSelf) {
2103 Matcher<int> m;
2104 m = AllOf(Le(2), Ge(1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002105 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002106
2107 m = AllOf(Gt(0), Ne(1), Ne(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002108 EXPECT_EQ("(is > 0) and "
2109 "((isn't equal to 1) and "
2110 "(isn't equal to 2))",
shiqiane35fdd92008-12-10 05:08:54 +00002111 Describe(m));
2112
2113
2114 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002115 EXPECT_EQ("((is > 0) and "
2116 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002117 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002118 "(isn't equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002119 Describe(m));
2120
2121
2122 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002123 EXPECT_EQ("((is >= 0) and "
2124 "(is < 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002125 "((isn't equal to 3) and "
2126 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002127 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002128 Describe(m));
2129}
2130
2131// Tests that AllOf(m1, ..., mn) describes its negation properly.
2132TEST(AllOfTest, CanDescribeNegation) {
2133 Matcher<int> m;
2134 m = AllOf(Le(2), Ge(1));
2135 EXPECT_EQ("(isn't <= 2) or "
2136 "(isn't >= 1)",
2137 DescribeNegation(m));
2138
2139 m = AllOf(Gt(0), Ne(1), Ne(2));
2140 EXPECT_EQ("(isn't > 0) or "
2141 "((is equal to 1) or "
2142 "(is equal to 2))",
2143 DescribeNegation(m));
2144
2145
2146 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002147 EXPECT_EQ("((isn't > 0) or "
2148 "(is equal to 1)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002149 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002150 "(is equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002151 DescribeNegation(m));
2152
2153
2154 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002155 EXPECT_EQ("((isn't >= 0) or "
2156 "(isn't < 10)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002157 "((is equal to 3) or "
2158 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002159 "(is equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002160 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00002161}
2162
zhanyong.wan18490652009-05-11 18:54:08 +00002163// Tests that monomorphic matchers are safely cast by the AllOf matcher.
2164TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2165 // greater_than_5 and less_than_10 are monomorphic matchers.
2166 Matcher<int> greater_than_5 = Gt(5);
2167 Matcher<int> less_than_10 = Lt(10);
2168
2169 Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2170 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2171 Matcher<int&> m3 = AllOf(greater_than_5, m2);
2172
2173 // Tests that BothOf works when composing itself.
2174 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2175 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2176}
2177
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002178TEST(AllOfTest, ExplainsResult) {
2179 Matcher<int> m;
2180
2181 // Successful match. Both matchers need to explain. The second
2182 // matcher doesn't give an explanation, so only the first matcher's
2183 // explanation is printed.
2184 m = AllOf(GreaterThan(10), Lt(30));
2185 EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2186
2187 // Successful match. Both matchers need to explain.
2188 m = AllOf(GreaterThan(10), GreaterThan(20));
2189 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2190 Explain(m, 30));
2191
2192 // Successful match. All matchers need to explain. The second
2193 // matcher doesn't given an explanation.
2194 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2195 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2196 Explain(m, 25));
2197
2198 // Successful match. All matchers need to explain.
2199 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2200 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2201 "and which is 10 more than 30",
2202 Explain(m, 40));
2203
2204 // Failed match. The first matcher, which failed, needs to
2205 // explain.
2206 m = AllOf(GreaterThan(10), GreaterThan(20));
2207 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2208
2209 // Failed match. The second matcher, which failed, needs to
2210 // explain. Since it doesn't given an explanation, nothing is
2211 // printed.
2212 m = AllOf(GreaterThan(10), Lt(30));
2213 EXPECT_EQ("", Explain(m, 40));
2214
2215 // Failed match. The second matcher, which failed, needs to
2216 // explain.
2217 m = AllOf(GreaterThan(10), GreaterThan(20));
2218 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2219}
2220
zhanyong.wan02c15052010-06-09 19:21:30 +00002221// Helper to allow easy testing of AnyOf matchers with num parameters.
2222void AnyOfMatches(int num, const Matcher<int>& m) {
2223 SCOPED_TRACE(Describe(m));
2224 EXPECT_FALSE(m.Matches(0));
2225 for (int i = 1; i <= num; ++i) {
2226 EXPECT_TRUE(m.Matches(i));
2227 }
2228 EXPECT_FALSE(m.Matches(num + 1));
2229}
2230
shiqiane35fdd92008-12-10 05:08:54 +00002231// Tests that AnyOf(m1, ..., mn) matches any value that matches at
2232// least one of the given matchers.
2233TEST(AnyOfTest, MatchesWhenAnyMatches) {
2234 Matcher<int> m;
2235 m = AnyOf(Le(1), Ge(3));
2236 EXPECT_TRUE(m.Matches(1));
2237 EXPECT_TRUE(m.Matches(4));
2238 EXPECT_FALSE(m.Matches(2));
2239
2240 m = AnyOf(Lt(0), Eq(1), Eq(2));
2241 EXPECT_TRUE(m.Matches(-1));
2242 EXPECT_TRUE(m.Matches(1));
2243 EXPECT_TRUE(m.Matches(2));
2244 EXPECT_FALSE(m.Matches(0));
2245
2246 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2247 EXPECT_TRUE(m.Matches(-1));
2248 EXPECT_TRUE(m.Matches(1));
2249 EXPECT_TRUE(m.Matches(2));
2250 EXPECT_TRUE(m.Matches(3));
2251 EXPECT_FALSE(m.Matches(0));
2252
2253 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2254 EXPECT_TRUE(m.Matches(0));
2255 EXPECT_TRUE(m.Matches(11));
2256 EXPECT_TRUE(m.Matches(3));
2257 EXPECT_FALSE(m.Matches(2));
zhanyong.wan02c15052010-06-09 19:21:30 +00002258
2259 // The following tests for varying number of sub-matchers. Due to the way
2260 // the sub-matchers are handled it is enough to test every sub-matcher once
2261 // with sub-matchers using the same matcher type. Varying matcher types are
2262 // checked for above.
2263 AnyOfMatches(2, AnyOf(1, 2));
2264 AnyOfMatches(3, AnyOf(1, 2, 3));
2265 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2266 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2267 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2268 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2269 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2270 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2271 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
shiqiane35fdd92008-12-10 05:08:54 +00002272}
2273
zhanyong.wan616180e2013-06-18 18:49:51 +00002274#if GTEST_LANG_CXX11
2275// Tests the variadic version of the AnyOfMatcher.
2276TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2277 // Also make sure AnyOf is defined in the right namespace and does not depend
2278 // on ADL.
2279 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2280
2281 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))"));
2282 AnyOfMatches(11, m);
2283 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2284 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2285 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2286 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2287 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2288}
2289
2290#endif // GTEST_LANG_CXX11
2291
shiqiane35fdd92008-12-10 05:08:54 +00002292// Tests that AnyOf(m1, ..., mn) describes itself properly.
2293TEST(AnyOfTest, CanDescribeSelf) {
2294 Matcher<int> m;
2295 m = AnyOf(Le(1), Ge(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002296 EXPECT_EQ("(is <= 1) or (is >= 3)",
shiqiane35fdd92008-12-10 05:08:54 +00002297 Describe(m));
2298
2299 m = AnyOf(Lt(0), Eq(1), Eq(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002300 EXPECT_EQ("(is < 0) or "
shiqiane35fdd92008-12-10 05:08:54 +00002301 "((is equal to 1) or (is equal to 2))",
2302 Describe(m));
2303
2304 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002305 EXPECT_EQ("((is < 0) or "
2306 "(is equal to 1)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002307 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002308 "(is equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002309 Describe(m));
2310
2311 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002312 EXPECT_EQ("((is <= 0) or "
2313 "(is > 10)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002314 "((is equal to 3) or "
2315 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002316 "(is equal to 7)))",
shiqiane35fdd92008-12-10 05:08:54 +00002317 Describe(m));
2318}
2319
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002320// Tests that AnyOf(m1, ..., mn) describes its negation properly.
2321TEST(AnyOfTest, CanDescribeNegation) {
2322 Matcher<int> m;
2323 m = AnyOf(Le(1), Ge(3));
2324 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2325 DescribeNegation(m));
2326
2327 m = AnyOf(Lt(0), Eq(1), Eq(2));
2328 EXPECT_EQ("(isn't < 0) and "
2329 "((isn't equal to 1) and (isn't equal to 2))",
2330 DescribeNegation(m));
2331
2332 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002333 EXPECT_EQ("((isn't < 0) and "
2334 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002335 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002336 "(isn't equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002337 DescribeNegation(m));
2338
2339 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002340 EXPECT_EQ("((isn't <= 0) and "
2341 "(isn't > 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002342 "((isn't equal to 3) and "
2343 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002344 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002345 DescribeNegation(m));
2346}
2347
zhanyong.wan18490652009-05-11 18:54:08 +00002348// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2349TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2350 // greater_than_5 and less_than_10 are monomorphic matchers.
2351 Matcher<int> greater_than_5 = Gt(5);
2352 Matcher<int> less_than_10 = Lt(10);
2353
2354 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2355 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2356 Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2357
2358 // Tests that EitherOf works when composing itself.
2359 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2360 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2361}
2362
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002363TEST(AnyOfTest, ExplainsResult) {
2364 Matcher<int> m;
2365
2366 // Failed match. Both matchers need to explain. The second
2367 // matcher doesn't give an explanation, so only the first matcher's
2368 // explanation is printed.
2369 m = AnyOf(GreaterThan(10), Lt(0));
2370 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2371
2372 // Failed match. Both matchers need to explain.
2373 m = AnyOf(GreaterThan(10), GreaterThan(20));
2374 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2375 Explain(m, 5));
2376
2377 // Failed match. All matchers need to explain. The second
2378 // matcher doesn't given an explanation.
2379 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2380 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2381 Explain(m, 5));
2382
2383 // Failed match. All matchers need to explain.
2384 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2385 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2386 "and which is 25 less than 30",
2387 Explain(m, 5));
2388
2389 // Successful match. The first matcher, which succeeded, needs to
2390 // explain.
2391 m = AnyOf(GreaterThan(10), GreaterThan(20));
2392 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2393
2394 // Successful match. The second matcher, which succeeded, needs to
2395 // explain. Since it doesn't given an explanation, nothing is
2396 // printed.
2397 m = AnyOf(GreaterThan(10), Lt(30));
2398 EXPECT_EQ("", Explain(m, 0));
2399
2400 // Successful match. The second matcher, which succeeded, needs to
2401 // explain.
2402 m = AnyOf(GreaterThan(30), GreaterThan(20));
2403 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2404}
2405
shiqiane35fdd92008-12-10 05:08:54 +00002406// The following predicate function and predicate functor are for
2407// testing the Truly(predicate) matcher.
2408
2409// Returns non-zero if the input is positive. Note that the return
2410// type of this function is not bool. It's OK as Truly() accepts any
2411// unary function or functor whose return type can be implicitly
2412// converted to bool.
2413int IsPositive(double x) {
2414 return x > 0 ? 1 : 0;
2415}
2416
2417// This functor returns true if the input is greater than the given
2418// number.
2419class IsGreaterThan {
2420 public:
2421 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2422
2423 bool operator()(int n) const { return n > threshold_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002424
shiqiane35fdd92008-12-10 05:08:54 +00002425 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002426 int threshold_;
shiqiane35fdd92008-12-10 05:08:54 +00002427};
2428
2429// For testing Truly().
2430const int foo = 0;
2431
2432// This predicate returns true iff the argument references foo and has
2433// a zero value.
2434bool ReferencesFooAndIsZero(const int& n) {
2435 return (&n == &foo) && (n == 0);
2436}
2437
2438// Tests that Truly(predicate) matches what satisfies the given
2439// predicate.
2440TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2441 Matcher<double> m = Truly(IsPositive);
2442 EXPECT_TRUE(m.Matches(2.0));
2443 EXPECT_FALSE(m.Matches(-1.5));
2444}
2445
2446// Tests that Truly(predicate_functor) works too.
2447TEST(TrulyTest, CanBeUsedWithFunctor) {
2448 Matcher<int> m = Truly(IsGreaterThan(5));
2449 EXPECT_TRUE(m.Matches(6));
2450 EXPECT_FALSE(m.Matches(4));
2451}
2452
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00002453// A class that can be implicitly converted to bool.
2454class ConvertibleToBool {
2455 public:
2456 explicit ConvertibleToBool(int number) : number_(number) {}
2457 operator bool() const { return number_ != 0; }
2458
2459 private:
2460 int number_;
2461};
2462
2463ConvertibleToBool IsNotZero(int number) {
2464 return ConvertibleToBool(number);
2465}
2466
2467// Tests that the predicate used in Truly() may return a class that's
2468// implicitly convertible to bool, even when the class has no
2469// operator!().
2470TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2471 Matcher<int> m = Truly(IsNotZero);
2472 EXPECT_TRUE(m.Matches(1));
2473 EXPECT_FALSE(m.Matches(0));
2474}
2475
shiqiane35fdd92008-12-10 05:08:54 +00002476// Tests that Truly(predicate) can describe itself properly.
2477TEST(TrulyTest, CanDescribeSelf) {
2478 Matcher<double> m = Truly(IsPositive);
2479 EXPECT_EQ("satisfies the given predicate",
2480 Describe(m));
2481}
2482
2483// Tests that Truly(predicate) works when the matcher takes its
2484// argument by reference.
2485TEST(TrulyTest, WorksForByRefArguments) {
2486 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2487 EXPECT_TRUE(m.Matches(foo));
2488 int n = 0;
2489 EXPECT_FALSE(m.Matches(n));
2490}
2491
2492// Tests that Matches(m) is a predicate satisfied by whatever that
2493// matches matcher m.
2494TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2495 EXPECT_TRUE(Matches(Ge(0))(1));
2496 EXPECT_FALSE(Matches(Eq('a'))('b'));
2497}
2498
2499// Tests that Matches(m) works when the matcher takes its argument by
2500// reference.
2501TEST(MatchesTest, WorksOnByRefArguments) {
2502 int m = 0, n = 0;
2503 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2504 EXPECT_FALSE(Matches(Ref(m))(n));
2505}
2506
2507// Tests that a Matcher on non-reference type can be used in
2508// Matches().
2509TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
2510 Matcher<int> eq5 = Eq(5);
2511 EXPECT_TRUE(Matches(eq5)(5));
2512 EXPECT_FALSE(Matches(eq5)(2));
2513}
2514
zhanyong.wanb8243162009-06-04 05:48:20 +00002515// Tests Value(value, matcher). Since Value() is a simple wrapper for
2516// Matches(), which has been tested already, we don't spend a lot of
2517// effort on testing Value().
2518TEST(ValueTest, WorksWithPolymorphicMatcher) {
2519 EXPECT_TRUE(Value("hi", StartsWith("h")));
2520 EXPECT_FALSE(Value(5, Gt(10)));
2521}
2522
2523TEST(ValueTest, WorksWithMonomorphicMatcher) {
2524 const Matcher<int> is_zero = Eq(0);
2525 EXPECT_TRUE(Value(0, is_zero));
2526 EXPECT_FALSE(Value('a', is_zero));
2527
2528 int n = 0;
2529 const Matcher<const int&> ref_n = Ref(n);
2530 EXPECT_TRUE(Value(n, ref_n));
2531 EXPECT_FALSE(Value(1, ref_n));
2532}
2533
zhanyong.wana862f1d2010-03-15 21:23:04 +00002534TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002535 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002536 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002537 EXPECT_EQ("% 2 == 0", listener1.str());
2538
2539 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002540 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002541 EXPECT_EQ("", listener2.str());
2542}
2543
zhanyong.wana862f1d2010-03-15 21:23:04 +00002544TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002545 const Matcher<int> is_even = PolymorphicIsEven();
2546 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002547 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002548 EXPECT_EQ("% 2 == 0", listener1.str());
2549
2550 const Matcher<const double&> is_zero = Eq(0);
2551 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002552 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002553 EXPECT_EQ("", listener2.str());
2554}
2555
zhanyong.wana862f1d2010-03-15 21:23:04 +00002556MATCHER_P(Really, inner_matcher, "") {
2557 return ExplainMatchResult(inner_matcher, arg, result_listener);
2558}
2559
2560TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
2561 EXPECT_THAT(0, Really(Eq(0)));
2562}
2563
zhanyong.wanbf550852009-06-09 06:09:53 +00002564TEST(AllArgsTest, WorksForTuple) {
2565 EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
2566 EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
2567}
2568
2569TEST(AllArgsTest, WorksForNonTuple) {
2570 EXPECT_THAT(42, AllArgs(Gt(0)));
2571 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
2572}
2573
2574class AllArgsHelper {
2575 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002576 AllArgsHelper() {}
2577
zhanyong.wanbf550852009-06-09 06:09:53 +00002578 MOCK_METHOD2(Helper, int(char x, int y));
zhanyong.wan32de5f52009-12-23 00:13:23 +00002579
2580 private:
2581 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
zhanyong.wanbf550852009-06-09 06:09:53 +00002582};
2583
2584TEST(AllArgsTest, WorksInWithClause) {
2585 AllArgsHelper helper;
2586 ON_CALL(helper, Helper(_, _))
2587 .With(AllArgs(Lt()))
2588 .WillByDefault(Return(1));
2589 EXPECT_CALL(helper, Helper(_, _));
2590 EXPECT_CALL(helper, Helper(_, _))
2591 .With(AllArgs(Gt()))
2592 .WillOnce(Return(2));
2593
2594 EXPECT_EQ(1, helper.Helper('\1', 2));
2595 EXPECT_EQ(2, helper.Helper('a', 1));
2596}
2597
shiqiane35fdd92008-12-10 05:08:54 +00002598// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2599// matches the matcher.
2600TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
2601 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
2602 ASSERT_THAT("Foo", EndsWith("oo"));
2603 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
2604 EXPECT_THAT("Hello", StartsWith("Hell"));
2605}
2606
2607// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2608// doesn't match the matcher.
2609TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
2610 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
2611 // which cannot reference auto variables.
zhanyong.wan736baa82010-09-27 17:44:16 +00002612 static unsigned short n; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00002613 n = 5;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002614
2615 // VC++ prior to version 8.0 SP1 has a bug where it will not see any
2616 // functions declared in the namespace scope from within nested classes.
2617 // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
2618 // namespace-level functions invoked inside them need to be explicitly
2619 // resolved.
2620 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
shiqiane35fdd92008-12-10 05:08:54 +00002621 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002622 "Expected: is > 10\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002623 " Actual: 5" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002624 n = 0;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002625 EXPECT_NONFATAL_FAILURE(
2626 EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
2627 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002628 "Expected: (is <= 7) and (is >= 5)\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002629 " Actual: 0" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002630}
2631
2632// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
2633// has a reference type.
2634TEST(MatcherAssertionTest, WorksForByRefArguments) {
2635 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
2636 // reference auto variables.
2637 static int n;
2638 n = 0;
2639 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002640 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
shiqiane35fdd92008-12-10 05:08:54 +00002641 "Value of: n\n"
2642 "Expected: does not reference the variable @");
2643 // Tests the "Actual" part.
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002644 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
zhanyong.wan736baa82010-09-27 17:44:16 +00002645 "Actual: 0" + OfType("int") + ", which is located @");
shiqiane35fdd92008-12-10 05:08:54 +00002646}
2647
zhanyong.wan95b12332009-09-25 18:55:50 +00002648#if !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002649// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
2650// monomorphic.
zhanyong.wan95b12332009-09-25 18:55:50 +00002651
2652// ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
2653// Symbian compiler: it tries to compile
2654// template<T, U> class MatcherCastImpl { ...
zhanyong.wandb22c222010-01-28 21:52:29 +00002655// virtual bool MatchAndExplain(T x, ...) const {
2656// return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
zhanyong.wan95b12332009-09-25 18:55:50 +00002657// with U == string and T == const char*
2658// With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
2659// the compiler silently crashes with no output.
2660// If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
2661// the code compiles but the converted string is bogus.
shiqiane35fdd92008-12-10 05:08:54 +00002662TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
2663 Matcher<const char*> starts_with_he = StartsWith("he");
2664 ASSERT_THAT("hello", starts_with_he);
2665
2666 Matcher<const string&> ends_with_ok = EndsWith("ok");
2667 ASSERT_THAT("book", ends_with_ok);
zhanyong.wan736baa82010-09-27 17:44:16 +00002668 const string bad = "bad";
2669 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
2670 "Value of: bad\n"
2671 "Expected: ends with \"ok\"\n"
2672 " Actual: \"bad\"");
shiqiane35fdd92008-12-10 05:08:54 +00002673 Matcher<int> is_greater_than_5 = Gt(5);
2674 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
2675 "Value of: 5\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002676 "Expected: is > 5\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002677 " Actual: 5" + OfType("int"));
shiqiane35fdd92008-12-10 05:08:54 +00002678}
zhanyong.wan95b12332009-09-25 18:55:50 +00002679#endif // !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002680
2681// Tests floating-point matchers.
2682template <typename RawType>
2683class FloatingPointTest : public testing::Test {
2684 protected:
zhanyong.wan35877b72013-09-18 17:51:08 +00002685 typedef testing::internal::FloatingPoint<RawType> Floating;
shiqiane35fdd92008-12-10 05:08:54 +00002686 typedef typename Floating::Bits Bits;
2687
zhanyong.wan35877b72013-09-18 17:51:08 +00002688 FloatingPointTest()
2689 : max_ulps_(Floating::kMaxUlps),
2690 zero_bits_(Floating(0).bits()),
2691 one_bits_(Floating(1).bits()),
2692 infinity_bits_(Floating(Floating::Infinity()).bits()),
2693 close_to_positive_zero_(
2694 Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
2695 close_to_negative_zero_(
2696 -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
2697 further_from_negative_zero_(-Floating::ReinterpretBits(
2698 zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
2699 close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
2700 further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
2701 infinity_(Floating::Infinity()),
2702 close_to_infinity_(
2703 Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
2704 further_from_infinity_(
2705 Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
2706 max_(Floating::Max()),
2707 nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
2708 nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
shiqiane35fdd92008-12-10 05:08:54 +00002709 }
2710
2711 void TestSize() {
2712 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2713 }
2714
2715 // A battery of tests for FloatingEqMatcher::Matches.
2716 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2717 void TestMatches(
2718 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
2719 Matcher<RawType> m1 = matcher_maker(0.0);
2720 EXPECT_TRUE(m1.Matches(-0.0));
2721 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
2722 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
2723 EXPECT_FALSE(m1.Matches(1.0));
2724
2725 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
2726 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
2727
2728 Matcher<RawType> m3 = matcher_maker(1.0);
2729 EXPECT_TRUE(m3.Matches(close_to_one_));
2730 EXPECT_FALSE(m3.Matches(further_from_one_));
2731
2732 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
2733 EXPECT_FALSE(m3.Matches(0.0));
2734
2735 Matcher<RawType> m4 = matcher_maker(-infinity_);
2736 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
2737
2738 Matcher<RawType> m5 = matcher_maker(infinity_);
2739 EXPECT_TRUE(m5.Matches(close_to_infinity_));
2740
2741 // This is interesting as the representations of infinity_ and nan1_
2742 // are only 1 DLP apart.
2743 EXPECT_FALSE(m5.Matches(nan1_));
2744
2745 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2746 // some cases.
2747 Matcher<const RawType&> m6 = matcher_maker(0.0);
2748 EXPECT_TRUE(m6.Matches(-0.0));
2749 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
2750 EXPECT_FALSE(m6.Matches(1.0));
2751
2752 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2753 // cases.
2754 Matcher<RawType&> m7 = matcher_maker(0.0);
2755 RawType x = 0.0;
2756 EXPECT_TRUE(m7.Matches(x));
2757 x = 0.01f;
2758 EXPECT_FALSE(m7.Matches(x));
2759 }
2760
2761 // Pre-calculated numbers to be used by the tests.
2762
zhanyong.wan35877b72013-09-18 17:51:08 +00002763 const size_t max_ulps_;
shiqiane35fdd92008-12-10 05:08:54 +00002764
zhanyong.wan35877b72013-09-18 17:51:08 +00002765 const Bits zero_bits_; // The bits that represent 0.0.
2766 const Bits one_bits_; // The bits that represent 1.0.
2767 const Bits infinity_bits_; // The bits that represent +infinity.
shiqiane35fdd92008-12-10 05:08:54 +00002768
zhanyong.wan35877b72013-09-18 17:51:08 +00002769 // Some numbers close to 0.0.
2770 const RawType close_to_positive_zero_;
2771 const RawType close_to_negative_zero_;
2772 const RawType further_from_negative_zero_;
shiqiane35fdd92008-12-10 05:08:54 +00002773
zhanyong.wan35877b72013-09-18 17:51:08 +00002774 // Some numbers close to 1.0.
2775 const RawType close_to_one_;
2776 const RawType further_from_one_;
2777
2778 // Some numbers close to +infinity.
2779 const RawType infinity_;
2780 const RawType close_to_infinity_;
2781 const RawType further_from_infinity_;
2782
2783 // Maximum representable value that's not infinity.
2784 const RawType max_;
2785
2786 // Some NaNs.
2787 const RawType nan1_;
2788 const RawType nan2_;
shiqiane35fdd92008-12-10 05:08:54 +00002789};
2790
zhanyong.wan616180e2013-06-18 18:49:51 +00002791// Tests floating-point matchers with fixed epsilons.
2792template <typename RawType>
2793class FloatingPointNearTest : public FloatingPointTest<RawType> {
2794 protected:
2795 typedef FloatingPointTest<RawType> ParentType;
2796
2797 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
2798 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2799 void TestNearMatches(
2800 testing::internal::FloatingEqMatcher<RawType>
2801 (*matcher_maker)(RawType, RawType)) {
2802 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
2803 EXPECT_TRUE(m1.Matches(0.0));
2804 EXPECT_TRUE(m1.Matches(-0.0));
2805 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
2806 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
2807 EXPECT_FALSE(m1.Matches(1.0));
2808
2809 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
2810 EXPECT_TRUE(m2.Matches(0.0));
2811 EXPECT_TRUE(m2.Matches(-0.0));
2812 EXPECT_TRUE(m2.Matches(1.0));
2813 EXPECT_TRUE(m2.Matches(-1.0));
2814 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
2815 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
2816
2817 // Check that inf matches inf, regardless of the of the specified max
2818 // absolute error.
2819 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
2820 EXPECT_TRUE(m3.Matches(ParentType::infinity_));
2821 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
2822 EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
2823
2824 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
2825 EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
2826 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
2827 EXPECT_FALSE(m4.Matches(ParentType::infinity_));
2828
2829 // Test various overflow scenarios.
zhanyong.wan35877b72013-09-18 17:51:08 +00002830 Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
2831 EXPECT_TRUE(m5.Matches(ParentType::max_));
2832 EXPECT_FALSE(m5.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002833
zhanyong.wan35877b72013-09-18 17:51:08 +00002834 Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
2835 EXPECT_FALSE(m6.Matches(ParentType::max_));
2836 EXPECT_TRUE(m6.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002837
zhanyong.wan35877b72013-09-18 17:51:08 +00002838 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
2839 EXPECT_TRUE(m7.Matches(ParentType::max_));
2840 EXPECT_FALSE(m7.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002841
zhanyong.wan35877b72013-09-18 17:51:08 +00002842 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
2843 EXPECT_FALSE(m8.Matches(ParentType::max_));
2844 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002845
2846 // The difference between max() and -max() normally overflows to infinity,
2847 // but it should still match if the max_abs_error is also infinity.
2848 Matcher<RawType> m9 = matcher_maker(
zhanyong.wan35877b72013-09-18 17:51:08 +00002849 ParentType::max_, ParentType::infinity_);
2850 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002851
2852 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2853 // some cases.
2854 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
2855 EXPECT_TRUE(m10.Matches(-0.0));
2856 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
2857 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
2858
2859 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2860 // cases.
2861 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
2862 RawType x = 0.0;
2863 EXPECT_TRUE(m11.Matches(x));
2864 x = 1.0f;
2865 EXPECT_TRUE(m11.Matches(x));
2866 x = -1.0f;
2867 EXPECT_TRUE(m11.Matches(x));
2868 x = 1.1f;
2869 EXPECT_FALSE(m11.Matches(x));
2870 x = -1.1f;
2871 EXPECT_FALSE(m11.Matches(x));
2872 }
2873};
2874
shiqiane35fdd92008-12-10 05:08:54 +00002875// Instantiate FloatingPointTest for testing floats.
2876typedef FloatingPointTest<float> FloatTest;
2877
2878TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
2879 TestMatches(&FloatEq);
2880}
2881
2882TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
2883 TestMatches(&NanSensitiveFloatEq);
2884}
2885
2886TEST_F(FloatTest, FloatEqCannotMatchNaN) {
2887 // FloatEq never matches NaN.
2888 Matcher<float> m = FloatEq(nan1_);
2889 EXPECT_FALSE(m.Matches(nan1_));
2890 EXPECT_FALSE(m.Matches(nan2_));
2891 EXPECT_FALSE(m.Matches(1.0));
2892}
2893
2894TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
2895 // NanSensitiveFloatEq will match NaN.
2896 Matcher<float> m = NanSensitiveFloatEq(nan1_);
2897 EXPECT_TRUE(m.Matches(nan1_));
2898 EXPECT_TRUE(m.Matches(nan2_));
2899 EXPECT_FALSE(m.Matches(1.0));
2900}
2901
2902TEST_F(FloatTest, FloatEqCanDescribeSelf) {
2903 Matcher<float> m1 = FloatEq(2.0f);
2904 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002905 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002906
2907 Matcher<float> m2 = FloatEq(0.5f);
2908 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002909 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002910
2911 Matcher<float> m3 = FloatEq(nan1_);
2912 EXPECT_EQ("never matches", Describe(m3));
2913 EXPECT_EQ("is anything", DescribeNegation(m3));
2914}
2915
2916TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
2917 Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
2918 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002919 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002920
2921 Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
2922 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002923 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002924
2925 Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
2926 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002927 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00002928}
2929
zhanyong.wan616180e2013-06-18 18:49:51 +00002930// Instantiate FloatingPointTest for testing floats with a user-specified
2931// max absolute error.
2932typedef FloatingPointNearTest<float> FloatNearTest;
2933
2934TEST_F(FloatNearTest, FloatNearMatches) {
2935 TestNearMatches(&FloatNear);
2936}
2937
2938TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
2939 TestNearMatches(&NanSensitiveFloatNear);
2940}
2941
2942TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
2943 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
2944 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2945 EXPECT_EQ(
2946 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2947
2948 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
2949 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2950 EXPECT_EQ(
2951 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2952
2953 Matcher<float> m3 = FloatNear(nan1_, 0.0);
2954 EXPECT_EQ("never matches", Describe(m3));
2955 EXPECT_EQ("is anything", DescribeNegation(m3));
2956}
2957
2958TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
2959 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
2960 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2961 EXPECT_EQ(
2962 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2963
2964 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
2965 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2966 EXPECT_EQ(
2967 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2968
2969 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
2970 EXPECT_EQ("is NaN", Describe(m3));
2971 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
2972}
2973
2974TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
2975 // FloatNear never matches NaN.
2976 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
2977 EXPECT_FALSE(m.Matches(nan1_));
2978 EXPECT_FALSE(m.Matches(nan2_));
2979 EXPECT_FALSE(m.Matches(1.0));
2980}
2981
2982TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
2983 // NanSensitiveFloatNear will match NaN.
2984 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
2985 EXPECT_TRUE(m.Matches(nan1_));
2986 EXPECT_TRUE(m.Matches(nan2_));
2987 EXPECT_FALSE(m.Matches(1.0));
2988}
2989
shiqiane35fdd92008-12-10 05:08:54 +00002990// Instantiate FloatingPointTest for testing doubles.
2991typedef FloatingPointTest<double> DoubleTest;
2992
2993TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
2994 TestMatches(&DoubleEq);
2995}
2996
2997TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
2998 TestMatches(&NanSensitiveDoubleEq);
2999}
3000
3001TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
3002 // DoubleEq never matches NaN.
3003 Matcher<double> m = DoubleEq(nan1_);
3004 EXPECT_FALSE(m.Matches(nan1_));
3005 EXPECT_FALSE(m.Matches(nan2_));
3006 EXPECT_FALSE(m.Matches(1.0));
3007}
3008
3009TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3010 // NanSensitiveDoubleEq will match NaN.
3011 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
3012 EXPECT_TRUE(m.Matches(nan1_));
3013 EXPECT_TRUE(m.Matches(nan2_));
3014 EXPECT_FALSE(m.Matches(1.0));
3015}
3016
3017TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3018 Matcher<double> m1 = DoubleEq(2.0);
3019 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003020 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003021
3022 Matcher<double> m2 = DoubleEq(0.5);
3023 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003024 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003025
3026 Matcher<double> m3 = DoubleEq(nan1_);
3027 EXPECT_EQ("never matches", Describe(m3));
3028 EXPECT_EQ("is anything", DescribeNegation(m3));
3029}
3030
3031TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3032 Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3033 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003034 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003035
3036 Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3037 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003038 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003039
3040 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3041 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003042 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00003043}
3044
zhanyong.wan616180e2013-06-18 18:49:51 +00003045// Instantiate FloatingPointTest for testing floats with a user-specified
3046// max absolute error.
3047typedef FloatingPointNearTest<double> DoubleNearTest;
3048
3049TEST_F(DoubleNearTest, DoubleNearMatches) {
3050 TestNearMatches(&DoubleNear);
3051}
3052
3053TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3054 TestNearMatches(&NanSensitiveDoubleNear);
3055}
3056
3057TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3058 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3059 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3060 EXPECT_EQ(
3061 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3062
3063 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3064 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3065 EXPECT_EQ(
3066 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3067
3068 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3069 EXPECT_EQ("never matches", Describe(m3));
3070 EXPECT_EQ("is anything", DescribeNegation(m3));
3071}
3072
3073TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3074 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3075 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3076 EXPECT_EQ(
3077 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3078
3079 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3080 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3081 EXPECT_EQ(
3082 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3083
3084 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3085 EXPECT_EQ("is NaN", Describe(m3));
3086 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3087}
3088
3089TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3090 // DoubleNear never matches NaN.
3091 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3092 EXPECT_FALSE(m.Matches(nan1_));
3093 EXPECT_FALSE(m.Matches(nan2_));
3094 EXPECT_FALSE(m.Matches(1.0));
3095}
3096
3097TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3098 // NanSensitiveDoubleNear will match NaN.
3099 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3100 EXPECT_TRUE(m.Matches(nan1_));
3101 EXPECT_TRUE(m.Matches(nan2_));
3102 EXPECT_FALSE(m.Matches(1.0));
3103}
3104
shiqiane35fdd92008-12-10 05:08:54 +00003105TEST(PointeeTest, RawPointer) {
3106 const Matcher<int*> m = Pointee(Ge(0));
3107
3108 int n = 1;
3109 EXPECT_TRUE(m.Matches(&n));
3110 n = -1;
3111 EXPECT_FALSE(m.Matches(&n));
3112 EXPECT_FALSE(m.Matches(NULL));
3113}
3114
3115TEST(PointeeTest, RawPointerToConst) {
3116 const Matcher<const double*> m = Pointee(Ge(0));
3117
3118 double x = 1;
3119 EXPECT_TRUE(m.Matches(&x));
3120 x = -1;
3121 EXPECT_FALSE(m.Matches(&x));
3122 EXPECT_FALSE(m.Matches(NULL));
3123}
3124
3125TEST(PointeeTest, ReferenceToConstRawPointer) {
3126 const Matcher<int* const &> m = Pointee(Ge(0));
3127
3128 int n = 1;
3129 EXPECT_TRUE(m.Matches(&n));
3130 n = -1;
3131 EXPECT_FALSE(m.Matches(&n));
3132 EXPECT_FALSE(m.Matches(NULL));
3133}
3134
3135TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3136 const Matcher<double* &> m = Pointee(Ge(0));
3137
3138 double x = 1.0;
3139 double* p = &x;
3140 EXPECT_TRUE(m.Matches(p));
3141 x = -1;
3142 EXPECT_FALSE(m.Matches(p));
3143 p = NULL;
3144 EXPECT_FALSE(m.Matches(p));
3145}
3146
billydonahue1f5fdea2014-05-19 17:54:51 +00003147
3148MATCHER_P(FieldIIs, inner_matcher, "") {
3149 return ExplainMatchResult(inner_matcher, arg.i, result_listener);
3150}
3151
3152TEST(WhenDynamicCastToTest, SameType) {
3153 Derived derived;
3154 derived.i = 4;
3155
3156 // Right type. A pointer is passed down.
3157 Base* as_base_ptr = &derived;
3158 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));
3159 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));
3160 EXPECT_THAT(as_base_ptr,
3161 Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));
3162}
3163
3164TEST(WhenDynamicCastToTest, WrongTypes) {
3165 Base base;
3166 Derived derived;
3167 OtherDerived other_derived;
3168
3169 // Wrong types. NULL is passed.
3170 EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3171 EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));
3172 Base* as_base_ptr = &derived;
3173 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));
3174 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));
3175 as_base_ptr = &other_derived;
3176 EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));
3177 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3178}
3179
3180TEST(WhenDynamicCastToTest, AlreadyNull) {
3181 // Already NULL.
3182 Base* as_base_ptr = NULL;
3183 EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));
3184}
3185
3186struct AmbiguousCastTypes {
3187 class VirtualDerived : public virtual Base {};
3188 class DerivedSub1 : public VirtualDerived {};
3189 class DerivedSub2 : public VirtualDerived {};
3190 class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};
3191};
3192
3193TEST(WhenDynamicCastToTest, AmbiguousCast) {
3194 AmbiguousCastTypes::DerivedSub1 sub1;
3195 AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;
3196 // Multiply derived from Base. dynamic_cast<> returns NULL.
3197 Base* as_base_ptr =
3198 static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);
3199 EXPECT_THAT(as_base_ptr,
3200 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));
3201 as_base_ptr = &sub1;
3202 EXPECT_THAT(
3203 as_base_ptr,
3204 WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));
3205}
3206
3207TEST(WhenDynamicCastToTest, Describe) {
3208 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3209#if GTEST_HAS_RTTI
3210 const string prefix =
3211 "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", ";
3212#else // GTEST_HAS_RTTI
3213 const string prefix = "when dynamic_cast, ";
3214#endif // GTEST_HAS_RTTI
3215 EXPECT_EQ(prefix + "points to a value that is anything", Describe(matcher));
3216 EXPECT_EQ(prefix + "does not point to a value that is anything",
3217 DescribeNegation(matcher));
3218}
3219
3220TEST(WhenDynamicCastToTest, Explain) {
3221 Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));
3222 Base* null = NULL;
3223 EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL"));
3224 Derived derived;
3225 EXPECT_TRUE(matcher.Matches(&derived));
3226 EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to "));
3227
3228 // With references, the matcher itself can fail. Test for that one.
3229 Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);
3230 EXPECT_THAT(Explain(ref_matcher, derived),
3231 HasSubstr("which cannot be dynamic_cast"));
3232}
3233
3234TEST(WhenDynamicCastToTest, GoodReference) {
3235 Derived derived;
3236 derived.i = 4;
3237 Base& as_base_ref = derived;
3238 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));
3239 EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));
3240}
3241
3242TEST(WhenDynamicCastToTest, BadReference) {
3243 Derived derived;
3244 Base& as_base_ref = derived;
3245 EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));
3246}
3247
vladlosevada23472012-08-14 15:38:49 +00003248// Minimal const-propagating pointer.
3249template <typename T>
3250class ConstPropagatingPtr {
3251 public:
3252 typedef T element_type;
3253
3254 ConstPropagatingPtr() : val_() {}
3255 explicit ConstPropagatingPtr(T* t) : val_(t) {}
3256 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3257
3258 T* get() { return val_; }
3259 T& operator*() { return *val_; }
3260 // Most smart pointers return non-const T* and T& from the next methods.
3261 const T* get() const { return val_; }
3262 const T& operator*() const { return *val_; }
3263
3264 private:
3265 T* val_;
3266};
3267
3268TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3269 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3270 int three = 3;
3271 const ConstPropagatingPtr<int> co(&three);
3272 ConstPropagatingPtr<int> o(&three);
3273 EXPECT_TRUE(m.Matches(o));
3274 EXPECT_TRUE(m.Matches(co));
3275 *o = 6;
3276 EXPECT_FALSE(m.Matches(o));
3277 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3278}
3279
shiqiane35fdd92008-12-10 05:08:54 +00003280TEST(PointeeTest, NeverMatchesNull) {
3281 const Matcher<const char*> m = Pointee(_);
3282 EXPECT_FALSE(m.Matches(NULL));
3283}
3284
3285// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3286TEST(PointeeTest, MatchesAgainstAValue) {
3287 const Matcher<int*> m = Pointee(5);
3288
3289 int n = 5;
3290 EXPECT_TRUE(m.Matches(&n));
3291 n = -1;
3292 EXPECT_FALSE(m.Matches(&n));
3293 EXPECT_FALSE(m.Matches(NULL));
3294}
3295
3296TEST(PointeeTest, CanDescribeSelf) {
3297 const Matcher<int*> m = Pointee(Gt(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003298 EXPECT_EQ("points to a value that is > 3", Describe(m));
3299 EXPECT_EQ("does not point to a value that is > 3",
shiqiane35fdd92008-12-10 05:08:54 +00003300 DescribeNegation(m));
3301}
3302
shiqiane35fdd92008-12-10 05:08:54 +00003303TEST(PointeeTest, CanExplainMatchResult) {
3304 const Matcher<const string*> m = Pointee(StartsWith("Hi"));
3305
3306 EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL)));
3307
zhanyong.wan736baa82010-09-27 17:44:16 +00003308 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
3309 long n = 3; // NOLINT
3310 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003311 Explain(m2, &n));
3312}
3313
3314TEST(PointeeTest, AlwaysExplainsPointee) {
3315 const Matcher<int*> m = Pointee(0);
3316 int n = 42;
zhanyong.wan736baa82010-09-27 17:44:16 +00003317 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
shiqiane35fdd92008-12-10 05:08:54 +00003318}
3319
3320// An uncopyable class.
3321class Uncopyable {
3322 public:
billydonahue1f5fdea2014-05-19 17:54:51 +00003323 Uncopyable() : value_(-1) {}
zhanyong.wan32de5f52009-12-23 00:13:23 +00003324 explicit Uncopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003325
3326 int value() const { return value_; }
billydonahue1f5fdea2014-05-19 17:54:51 +00003327 void set_value(int i) { value_ = i; }
3328
shiqiane35fdd92008-12-10 05:08:54 +00003329 private:
billydonahue1f5fdea2014-05-19 17:54:51 +00003330 int value_;
shiqiane35fdd92008-12-10 05:08:54 +00003331 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3332};
3333
3334// Returns true iff x.value() is positive.
3335bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3336
billydonahue1f5fdea2014-05-19 17:54:51 +00003337MATCHER_P(UncopyableIs, inner_matcher, "") {
3338 return ExplainMatchResult(inner_matcher, arg.value(), result_listener);
3339}
3340
shiqiane35fdd92008-12-10 05:08:54 +00003341// A user-defined struct for testing Field().
3342struct AStruct {
3343 AStruct() : x(0), y(1.0), z(5), p(NULL) {}
3344 AStruct(const AStruct& rhs)
3345 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3346
3347 int x; // A non-const field.
3348 const double y; // A const field.
3349 Uncopyable z; // An uncopyable field.
3350 const char* p; // A pointer field.
zhanyong.wan32de5f52009-12-23 00:13:23 +00003351
3352 private:
3353 GTEST_DISALLOW_ASSIGN_(AStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003354};
3355
3356// A derived struct for testing Field().
3357struct DerivedStruct : public AStruct {
3358 char ch;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003359
3360 private:
3361 GTEST_DISALLOW_ASSIGN_(DerivedStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003362};
3363
3364// Tests that Field(&Foo::field, ...) works when field is non-const.
3365TEST(FieldTest, WorksForNonConstField) {
3366 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
3367
3368 AStruct a;
3369 EXPECT_TRUE(m.Matches(a));
3370 a.x = -1;
3371 EXPECT_FALSE(m.Matches(a));
3372}
3373
3374// Tests that Field(&Foo::field, ...) works when field is const.
3375TEST(FieldTest, WorksForConstField) {
3376 AStruct a;
3377
3378 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
3379 EXPECT_TRUE(m.Matches(a));
3380 m = Field(&AStruct::y, Le(0.0));
3381 EXPECT_FALSE(m.Matches(a));
3382}
3383
3384// Tests that Field(&Foo::field, ...) works when field is not copyable.
3385TEST(FieldTest, WorksForUncopyableField) {
3386 AStruct a;
3387
3388 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3389 EXPECT_TRUE(m.Matches(a));
3390 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3391 EXPECT_FALSE(m.Matches(a));
3392}
3393
3394// Tests that Field(&Foo::field, ...) works when field is a pointer.
3395TEST(FieldTest, WorksForPointerField) {
3396 // Matching against NULL.
3397 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
3398 AStruct a;
3399 EXPECT_TRUE(m.Matches(a));
3400 a.p = "hi";
3401 EXPECT_FALSE(m.Matches(a));
3402
3403 // Matching a pointer that is not NULL.
3404 m = Field(&AStruct::p, StartsWith("hi"));
3405 a.p = "hill";
3406 EXPECT_TRUE(m.Matches(a));
3407 a.p = "hole";
3408 EXPECT_FALSE(m.Matches(a));
3409}
3410
3411// Tests that Field() works when the object is passed by reference.
3412TEST(FieldTest, WorksForByRefArgument) {
3413 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3414
3415 AStruct a;
3416 EXPECT_TRUE(m.Matches(a));
3417 a.x = -1;
3418 EXPECT_FALSE(m.Matches(a));
3419}
3420
3421// Tests that Field(&Foo::field, ...) works when the argument's type
3422// is a sub-type of Foo.
3423TEST(FieldTest, WorksForArgumentOfSubType) {
3424 // Note that the matcher expects DerivedStruct but we say AStruct
3425 // inside Field().
3426 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
3427
3428 DerivedStruct d;
3429 EXPECT_TRUE(m.Matches(d));
3430 d.x = -1;
3431 EXPECT_FALSE(m.Matches(d));
3432}
3433
3434// Tests that Field(&Foo::field, m) works when field's type and m's
3435// argument type are compatible but not the same.
3436TEST(FieldTest, WorksForCompatibleMatcherType) {
3437 // The field is an int, but the inner matcher expects a signed char.
3438 Matcher<const AStruct&> m = Field(&AStruct::x,
3439 Matcher<signed char>(Ge(0)));
3440
3441 AStruct a;
3442 EXPECT_TRUE(m.Matches(a));
3443 a.x = -1;
3444 EXPECT_FALSE(m.Matches(a));
3445}
3446
3447// Tests that Field() can describe itself.
3448TEST(FieldTest, CanDescribeSelf) {
3449 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3450
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003451 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3452 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003453}
3454
3455// Tests that Field() can explain the match result.
3456TEST(FieldTest, CanExplainMatchResult) {
3457 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3458
3459 AStruct a;
3460 a.x = 1;
zhanyong.wan736baa82010-09-27 17:44:16 +00003461 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003462
3463 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003464 EXPECT_EQ(
3465 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
3466 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003467}
3468
3469// Tests that Field() works when the argument is a pointer to const.
3470TEST(FieldForPointerTest, WorksForPointerToConst) {
3471 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3472
3473 AStruct a;
3474 EXPECT_TRUE(m.Matches(&a));
3475 a.x = -1;
3476 EXPECT_FALSE(m.Matches(&a));
3477}
3478
3479// Tests that Field() works when the argument is a pointer to non-const.
3480TEST(FieldForPointerTest, WorksForPointerToNonConst) {
3481 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
3482
3483 AStruct a;
3484 EXPECT_TRUE(m.Matches(&a));
3485 a.x = -1;
3486 EXPECT_FALSE(m.Matches(&a));
3487}
3488
zhanyong.wan6953a722010-01-13 05:15:07 +00003489// Tests that Field() works when the argument is a reference to a const pointer.
3490TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
3491 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
3492
3493 AStruct a;
3494 EXPECT_TRUE(m.Matches(&a));
3495 a.x = -1;
3496 EXPECT_FALSE(m.Matches(&a));
3497}
3498
shiqiane35fdd92008-12-10 05:08:54 +00003499// Tests that Field() does not match the NULL pointer.
3500TEST(FieldForPointerTest, DoesNotMatchNull) {
3501 Matcher<const AStruct*> m = Field(&AStruct::x, _);
3502 EXPECT_FALSE(m.Matches(NULL));
3503}
3504
3505// Tests that Field(&Foo::field, ...) works when the argument's type
3506// is a sub-type of const Foo*.
3507TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
3508 // Note that the matcher expects DerivedStruct but we say AStruct
3509 // inside Field().
3510 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
3511
3512 DerivedStruct d;
3513 EXPECT_TRUE(m.Matches(&d));
3514 d.x = -1;
3515 EXPECT_FALSE(m.Matches(&d));
3516}
3517
3518// Tests that Field() can describe itself when used to match a pointer.
3519TEST(FieldForPointerTest, CanDescribeSelf) {
3520 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3521
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003522 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3523 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003524}
3525
3526// Tests that Field() can explain the result of matching a pointer.
3527TEST(FieldForPointerTest, CanExplainMatchResult) {
3528 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3529
3530 AStruct a;
3531 a.x = 1;
3532 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003533 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
3534 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003535
3536 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003537 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
3538 ", which is 1 more than 0", Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003539}
3540
3541// A user-defined class for testing Property().
3542class AClass {
3543 public:
3544 AClass() : n_(0) {}
3545
3546 // A getter that returns a non-reference.
3547 int n() const { return n_; }
3548
3549 void set_n(int new_n) { n_ = new_n; }
3550
3551 // A getter that returns a reference to const.
3552 const string& s() const { return s_; }
3553
3554 void set_s(const string& new_s) { s_ = new_s; }
3555
3556 // A getter that returns a reference to non-const.
3557 double& x() const { return x_; }
3558 private:
3559 int n_;
3560 string s_;
3561
3562 static double x_;
3563};
3564
3565double AClass::x_ = 0.0;
3566
3567// A derived class for testing Property().
3568class DerivedClass : public AClass {
kosak6414d802013-12-03 23:19:36 +00003569 public:
3570 int k() const { return k_; }
shiqiane35fdd92008-12-10 05:08:54 +00003571 private:
3572 int k_;
3573};
3574
3575// Tests that Property(&Foo::property, ...) works when property()
3576// returns a non-reference.
3577TEST(PropertyTest, WorksForNonReferenceProperty) {
3578 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3579
3580 AClass a;
3581 a.set_n(1);
3582 EXPECT_TRUE(m.Matches(a));
3583
3584 a.set_n(-1);
3585 EXPECT_FALSE(m.Matches(a));
3586}
3587
3588// Tests that Property(&Foo::property, ...) works when property()
3589// returns a reference to const.
3590TEST(PropertyTest, WorksForReferenceToConstProperty) {
3591 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
3592
3593 AClass a;
3594 a.set_s("hill");
3595 EXPECT_TRUE(m.Matches(a));
3596
3597 a.set_s("hole");
3598 EXPECT_FALSE(m.Matches(a));
3599}
3600
3601// Tests that Property(&Foo::property, ...) works when property()
3602// returns a reference to non-const.
3603TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
3604 double x = 0.0;
3605 AClass a;
3606
3607 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
3608 EXPECT_FALSE(m.Matches(a));
3609
3610 m = Property(&AClass::x, Not(Ref(x)));
3611 EXPECT_TRUE(m.Matches(a));
3612}
3613
3614// Tests that Property(&Foo::property, ...) works when the argument is
3615// passed by value.
3616TEST(PropertyTest, WorksForByValueArgument) {
3617 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
3618
3619 AClass a;
3620 a.set_s("hill");
3621 EXPECT_TRUE(m.Matches(a));
3622
3623 a.set_s("hole");
3624 EXPECT_FALSE(m.Matches(a));
3625}
3626
3627// Tests that Property(&Foo::property, ...) works when the argument's
3628// type is a sub-type of Foo.
3629TEST(PropertyTest, WorksForArgumentOfSubType) {
3630 // The matcher expects a DerivedClass, but inside the Property() we
3631 // say AClass.
3632 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
3633
3634 DerivedClass d;
3635 d.set_n(1);
3636 EXPECT_TRUE(m.Matches(d));
3637
3638 d.set_n(-1);
3639 EXPECT_FALSE(m.Matches(d));
3640}
3641
3642// Tests that Property(&Foo::property, m) works when property()'s type
3643// and m's argument type are compatible but different.
3644TEST(PropertyTest, WorksForCompatibleMatcherType) {
3645 // n() returns an int but the inner matcher expects a signed char.
3646 Matcher<const AClass&> m = Property(&AClass::n,
3647 Matcher<signed char>(Ge(0)));
3648
3649 AClass a;
3650 EXPECT_TRUE(m.Matches(a));
3651 a.set_n(-1);
3652 EXPECT_FALSE(m.Matches(a));
3653}
3654
3655// Tests that Property() can describe itself.
3656TEST(PropertyTest, CanDescribeSelf) {
3657 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3658
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003659 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3660 EXPECT_EQ("is an object whose given property isn't >= 0",
3661 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003662}
3663
3664// Tests that Property() can explain the match result.
3665TEST(PropertyTest, CanExplainMatchResult) {
3666 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3667
3668 AClass a;
3669 a.set_n(1);
zhanyong.wan736baa82010-09-27 17:44:16 +00003670 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003671
3672 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003673 EXPECT_EQ(
3674 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
3675 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003676}
3677
3678// Tests that Property() works when the argument is a pointer to const.
3679TEST(PropertyForPointerTest, WorksForPointerToConst) {
3680 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3681
3682 AClass a;
3683 a.set_n(1);
3684 EXPECT_TRUE(m.Matches(&a));
3685
3686 a.set_n(-1);
3687 EXPECT_FALSE(m.Matches(&a));
3688}
3689
3690// Tests that Property() works when the argument is a pointer to non-const.
3691TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
3692 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
3693
3694 AClass a;
3695 a.set_s("hill");
3696 EXPECT_TRUE(m.Matches(&a));
3697
3698 a.set_s("hole");
3699 EXPECT_FALSE(m.Matches(&a));
3700}
3701
zhanyong.wan6953a722010-01-13 05:15:07 +00003702// Tests that Property() works when the argument is a reference to a
3703// const pointer.
3704TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
3705 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
3706
3707 AClass a;
3708 a.set_s("hill");
3709 EXPECT_TRUE(m.Matches(&a));
3710
3711 a.set_s("hole");
3712 EXPECT_FALSE(m.Matches(&a));
3713}
3714
shiqiane35fdd92008-12-10 05:08:54 +00003715// Tests that Property() does not match the NULL pointer.
3716TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
3717 Matcher<const AClass*> m = Property(&AClass::x, _);
3718 EXPECT_FALSE(m.Matches(NULL));
3719}
3720
3721// Tests that Property(&Foo::property, ...) works when the argument's
3722// type is a sub-type of const Foo*.
3723TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
3724 // The matcher expects a DerivedClass, but inside the Property() we
3725 // say AClass.
3726 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
3727
3728 DerivedClass d;
3729 d.set_n(1);
3730 EXPECT_TRUE(m.Matches(&d));
3731
3732 d.set_n(-1);
3733 EXPECT_FALSE(m.Matches(&d));
3734}
3735
3736// Tests that Property() can describe itself when used to match a pointer.
3737TEST(PropertyForPointerTest, CanDescribeSelf) {
3738 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3739
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003740 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3741 EXPECT_EQ("is an object whose given property isn't >= 0",
3742 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003743}
3744
3745// Tests that Property() can explain the result of matching a pointer.
3746TEST(PropertyForPointerTest, CanExplainMatchResult) {
3747 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3748
3749 AClass a;
3750 a.set_n(1);
3751 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003752 EXPECT_EQ(
3753 "which points to an object whose given property is 1" + OfType("int"),
3754 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003755
3756 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003757 EXPECT_EQ("which points to an object whose given property is 1" +
3758 OfType("int") + ", which is 1 more than 0",
3759 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003760}
3761
3762// Tests ResultOf.
3763
3764// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3765// function pointer.
3766string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; }
3767
3768TEST(ResultOfTest, WorksForFunctionPointers) {
3769 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo")));
3770
3771 EXPECT_TRUE(matcher.Matches(1));
3772 EXPECT_FALSE(matcher.Matches(2));
3773}
3774
3775// Tests that ResultOf() can describe itself.
3776TEST(ResultOfTest, CanDescribeItself) {
3777 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
3778
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003779 EXPECT_EQ("is mapped by the given callable to a value that "
3780 "is equal to \"foo\"", Describe(matcher));
3781 EXPECT_EQ("is mapped by the given callable to a value that "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003782 "isn't equal to \"foo\"", DescribeNegation(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00003783}
3784
3785// Tests that ResultOf() can explain the match result.
3786int IntFunction(int input) { return input == 42 ? 80 : 90; }
3787
3788TEST(ResultOfTest, CanExplainMatchResult) {
3789 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003790 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003791 Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003792
3793 matcher = ResultOf(&IntFunction, GreaterThan(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003794 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
3795 ", which is 5 more than 85", Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003796}
3797
3798// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3799// returns a non-reference.
3800TEST(ResultOfTest, WorksForNonReferenceResults) {
3801 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
3802
3803 EXPECT_TRUE(matcher.Matches(42));
3804 EXPECT_FALSE(matcher.Matches(36));
3805}
3806
3807// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3808// returns a reference to non-const.
zhanyong.wan736baa82010-09-27 17:44:16 +00003809double& DoubleFunction(double& input) { return input; } // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003810
zhanyong.wan736baa82010-09-27 17:44:16 +00003811Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003812 return obj;
3813}
3814
3815TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
3816 double x = 3.14;
3817 double x2 = x;
3818 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
3819
3820 EXPECT_TRUE(matcher.Matches(x));
3821 EXPECT_FALSE(matcher.Matches(x2));
3822
3823 // Test that ResultOf works with uncopyable objects
3824 Uncopyable obj(0);
3825 Uncopyable obj2(0);
3826 Matcher<Uncopyable&> matcher2 =
3827 ResultOf(&RefUncopyableFunction, Ref(obj));
3828
3829 EXPECT_TRUE(matcher2.Matches(obj));
3830 EXPECT_FALSE(matcher2.Matches(obj2));
3831}
3832
3833// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3834// returns a reference to const.
3835const string& StringFunction(const string& input) { return input; }
3836
3837TEST(ResultOfTest, WorksForReferenceToConstResults) {
3838 string s = "foo";
3839 string s2 = s;
3840 Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s));
3841
3842 EXPECT_TRUE(matcher.Matches(s));
3843 EXPECT_FALSE(matcher.Matches(s2));
3844}
3845
3846// Tests that ResultOf(f, m) works when f(x) and m's
3847// argument types are compatible but different.
3848TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
3849 // IntFunction() returns int but the inner matcher expects a signed char.
3850 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
3851
3852 EXPECT_TRUE(matcher.Matches(36));
3853 EXPECT_FALSE(matcher.Matches(42));
3854}
3855
shiqiane35fdd92008-12-10 05:08:54 +00003856// Tests that the program aborts when ResultOf is passed
3857// a NULL function pointer.
3858TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
zhanyong.wan04d6ed82009-09-11 07:01:08 +00003859 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan736baa82010-09-27 17:44:16 +00003860 ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))),
shiqiane35fdd92008-12-10 05:08:54 +00003861 "NULL function pointer is passed into ResultOf\\(\\)\\.");
3862}
shiqiane35fdd92008-12-10 05:08:54 +00003863
3864// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3865// function reference.
3866TEST(ResultOfTest, WorksForFunctionReferences) {
3867 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
3868 EXPECT_TRUE(matcher.Matches(1));
3869 EXPECT_FALSE(matcher.Matches(2));
3870}
3871
3872// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3873// function object.
3874struct Functor : public ::std::unary_function<int, string> {
3875 result_type operator()(argument_type input) const {
3876 return IntToStringFunction(input);
3877 }
3878};
3879
3880TEST(ResultOfTest, WorksForFunctors) {
3881 Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo")));
3882
3883 EXPECT_TRUE(matcher.Matches(1));
3884 EXPECT_FALSE(matcher.Matches(2));
3885}
3886
3887// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3888// functor with more then one operator() defined. ResultOf() must work
3889// for each defined operator().
3890struct PolymorphicFunctor {
3891 typedef int result_type;
3892 int operator()(int n) { return n; }
3893 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
3894};
3895
3896TEST(ResultOfTest, WorksForPolymorphicFunctors) {
3897 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
3898
3899 EXPECT_TRUE(matcher_int.Matches(10));
3900 EXPECT_FALSE(matcher_int.Matches(2));
3901
3902 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
3903
3904 EXPECT_TRUE(matcher_string.Matches("long string"));
3905 EXPECT_FALSE(matcher_string.Matches("shrt"));
3906}
3907
3908const int* ReferencingFunction(const int& n) { return &n; }
3909
3910struct ReferencingFunctor {
3911 typedef const int* result_type;
3912 result_type operator()(const int& n) { return &n; }
3913};
3914
3915TEST(ResultOfTest, WorksForReferencingCallables) {
3916 const int n = 1;
3917 const int n2 = 1;
3918 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
3919 EXPECT_TRUE(matcher2.Matches(n));
3920 EXPECT_FALSE(matcher2.Matches(n2));
3921
3922 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
3923 EXPECT_TRUE(matcher3.Matches(n));
3924 EXPECT_FALSE(matcher3.Matches(n2));
3925}
3926
shiqiane35fdd92008-12-10 05:08:54 +00003927class DivisibleByImpl {
3928 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003929 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
shiqiane35fdd92008-12-10 05:08:54 +00003930
zhanyong.wandb22c222010-01-28 21:52:29 +00003931 // For testing using ExplainMatchResultTo() with polymorphic matchers.
shiqiane35fdd92008-12-10 05:08:54 +00003932 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00003933 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003934 *listener << "which is " << (n % divider_) << " modulo "
zhanyong.wandb22c222010-01-28 21:52:29 +00003935 << divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003936 return (n % divider_) == 0;
3937 }
3938
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003939 void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003940 *os << "is divisible by " << divider_;
3941 }
3942
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003943 void DescribeNegationTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003944 *os << "is not divisible by " << divider_;
3945 }
3946
zhanyong.wan32de5f52009-12-23 00:13:23 +00003947 void set_divider(int a_divider) { divider_ = a_divider; }
shiqiane35fdd92008-12-10 05:08:54 +00003948 int divider() const { return divider_; }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003949
shiqiane35fdd92008-12-10 05:08:54 +00003950 private:
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003951 int divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003952};
3953
shiqiane35fdd92008-12-10 05:08:54 +00003954PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
3955 return MakePolymorphicMatcher(DivisibleByImpl(n));
3956}
3957
3958// Tests that when AllOf() fails, only the first failing matcher is
3959// asked to explain why.
3960TEST(ExplainMatchResultTest, AllOf_False_False) {
3961 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003962 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00003963}
3964
3965// Tests that when AllOf() fails, only the first failing matcher is
3966// asked to explain why.
3967TEST(ExplainMatchResultTest, AllOf_False_True) {
3968 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003969 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003970}
3971
3972// Tests that when AllOf() fails, only the first failing matcher is
3973// asked to explain why.
3974TEST(ExplainMatchResultTest, AllOf_True_False) {
3975 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003976 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00003977}
3978
3979// Tests that when AllOf() succeeds, all matchers are asked to explain
3980// why.
3981TEST(ExplainMatchResultTest, AllOf_True_True) {
3982 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003983 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003984}
3985
3986TEST(ExplainMatchResultTest, AllOf_True_True_2) {
3987 const Matcher<int> m = AllOf(Ge(2), Le(3));
3988 EXPECT_EQ("", Explain(m, 2));
3989}
3990
3991TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
3992 const Matcher<int> m = GreaterThan(5);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003993 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003994}
3995
3996// The following two tests verify that values without a public copy
3997// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
3998// with the help of ByRef().
3999
4000class NotCopyable {
4001 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00004002 explicit NotCopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00004003
4004 int value() const { return value_; }
4005
4006 bool operator==(const NotCopyable& rhs) const {
4007 return value() == rhs.value();
4008 }
4009
4010 bool operator>=(const NotCopyable& rhs) const {
4011 return value() >= rhs.value();
4012 }
4013 private:
4014 int value_;
4015
4016 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
4017};
4018
4019TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
4020 const NotCopyable const_value1(1);
4021 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
4022
4023 const NotCopyable n1(1), n2(2);
4024 EXPECT_TRUE(m.Matches(n1));
4025 EXPECT_FALSE(m.Matches(n2));
4026}
4027
4028TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
4029 NotCopyable value2(2);
4030 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
4031
4032 NotCopyable n1(1), n2(2);
4033 EXPECT_FALSE(m.Matches(n1));
4034 EXPECT_TRUE(m.Matches(n2));
4035}
4036
zhanyong.wan320814a2013-03-01 00:20:30 +00004037TEST(IsEmptyTest, ImplementsIsEmpty) {
4038 vector<int> container;
4039 EXPECT_THAT(container, IsEmpty());
4040 container.push_back(0);
4041 EXPECT_THAT(container, Not(IsEmpty()));
4042 container.push_back(1);
4043 EXPECT_THAT(container, Not(IsEmpty()));
4044}
4045
4046TEST(IsEmptyTest, WorksWithString) {
4047 string text;
4048 EXPECT_THAT(text, IsEmpty());
4049 text = "foo";
4050 EXPECT_THAT(text, Not(IsEmpty()));
4051 text = string("\0", 1);
4052 EXPECT_THAT(text, Not(IsEmpty()));
4053}
4054
4055TEST(IsEmptyTest, CanDescribeSelf) {
4056 Matcher<vector<int> > m = IsEmpty();
4057 EXPECT_EQ("is empty", Describe(m));
4058 EXPECT_EQ("isn't empty", DescribeNegation(m));
4059}
4060
4061TEST(IsEmptyTest, ExplainsResult) {
4062 Matcher<vector<int> > m = IsEmpty();
4063 vector<int> container;
4064 EXPECT_EQ("", Explain(m, container));
4065 container.push_back(0);
4066 EXPECT_EQ("whose size is 1", Explain(m, container));
4067}
4068
zhanyong.wana31d9ce2013-03-01 01:50:17 +00004069TEST(SizeIsTest, ImplementsSizeIs) {
4070 vector<int> container;
4071 EXPECT_THAT(container, SizeIs(0));
4072 EXPECT_THAT(container, Not(SizeIs(1)));
4073 container.push_back(0);
4074 EXPECT_THAT(container, Not(SizeIs(0)));
4075 EXPECT_THAT(container, SizeIs(1));
4076 container.push_back(0);
4077 EXPECT_THAT(container, Not(SizeIs(0)));
4078 EXPECT_THAT(container, SizeIs(2));
4079}
4080
4081TEST(SizeIsTest, WorksWithMap) {
4082 map<string, int> container;
4083 EXPECT_THAT(container, SizeIs(0));
4084 EXPECT_THAT(container, Not(SizeIs(1)));
4085 container.insert(make_pair("foo", 1));
4086 EXPECT_THAT(container, Not(SizeIs(0)));
4087 EXPECT_THAT(container, SizeIs(1));
4088 container.insert(make_pair("bar", 2));
4089 EXPECT_THAT(container, Not(SizeIs(0)));
4090 EXPECT_THAT(container, SizeIs(2));
4091}
4092
4093TEST(SizeIsTest, WorksWithReferences) {
4094 vector<int> container;
4095 Matcher<const vector<int>&> m = SizeIs(1);
4096 EXPECT_THAT(container, Not(m));
4097 container.push_back(0);
4098 EXPECT_THAT(container, m);
4099}
4100
4101TEST(SizeIsTest, CanDescribeSelf) {
4102 Matcher<vector<int> > m = SizeIs(2);
4103 EXPECT_EQ("size is equal to 2", Describe(m));
4104 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
4105}
4106
4107TEST(SizeIsTest, ExplainsResult) {
4108 Matcher<vector<int> > m1 = SizeIs(2);
4109 Matcher<vector<int> > m2 = SizeIs(Lt(2u));
4110 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
4111 Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
4112 vector<int> container;
4113 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
4114 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
4115 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
4116 EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
4117 Explain(m4, container));
4118 container.push_back(0);
4119 container.push_back(0);
4120 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
4121 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
4122 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
4123 EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
4124 Explain(m4, container));
4125}
4126
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004127#if GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004128// Tests ContainerEq with different container types, and
4129// different element types.
4130
4131template <typename T>
zhanyong.wanb8243162009-06-04 05:48:20 +00004132class ContainerEqTest : public testing::Test {};
zhanyong.wan6a896b52009-01-16 01:13:50 +00004133
4134typedef testing::Types<
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004135 set<int>,
4136 vector<size_t>,
4137 multiset<size_t>,
4138 list<int> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004139 ContainerEqTestTypes;
4140
4141TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
4142
4143// Tests that the filled container is equal to itself.
4144TYPED_TEST(ContainerEqTest, EqualsSelf) {
4145 static const int vals[] = {1, 1, 2, 3, 5, 8};
4146 TypeParam my_set(vals, vals + 6);
4147 const Matcher<TypeParam> m = ContainerEq(my_set);
4148 EXPECT_TRUE(m.Matches(my_set));
4149 EXPECT_EQ("", Explain(m, my_set));
4150}
4151
4152// Tests that missing values are reported.
4153TYPED_TEST(ContainerEqTest, ValueMissing) {
4154 static const int vals[] = {1, 1, 2, 3, 5, 8};
4155 static const int test_vals[] = {2, 1, 8, 5};
4156 TypeParam my_set(vals, vals + 6);
4157 TypeParam test_set(test_vals, test_vals + 4);
4158 const Matcher<TypeParam> m = ContainerEq(my_set);
4159 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004160 EXPECT_EQ("which doesn't have these expected elements: 3",
4161 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004162}
4163
4164// Tests that added values are reported.
4165TYPED_TEST(ContainerEqTest, ValueAdded) {
4166 static const int vals[] = {1, 1, 2, 3, 5, 8};
4167 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4168 TypeParam my_set(vals, vals + 6);
4169 TypeParam test_set(test_vals, test_vals + 6);
4170 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4171 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004172 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004173}
4174
4175// Tests that added and missing values are reported together.
4176TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4177 static const int vals[] = {1, 1, 2, 3, 5, 8};
4178 static const int test_vals[] = {1, 2, 3, 8, 46};
4179 TypeParam my_set(vals, vals + 6);
4180 TypeParam test_set(test_vals, test_vals + 5);
4181 const Matcher<TypeParam> m = ContainerEq(my_set);
4182 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004183 EXPECT_EQ("which has these unexpected elements: 46,\n"
4184 "and doesn't have these expected elements: 5",
4185 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004186}
4187
4188// Tests duplicated value -- expect no explanation.
4189TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4190 static const int vals[] = {1, 1, 2, 3, 5, 8};
4191 static const int test_vals[] = {1, 2, 3, 5, 8};
4192 TypeParam my_set(vals, vals + 6);
4193 TypeParam test_set(test_vals, test_vals + 5);
4194 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4195 // Depending on the container, match may be true or false
4196 // But in any case there should be no explanation.
4197 EXPECT_EQ("", Explain(m, test_set));
4198}
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004199#endif // GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004200
4201// Tests that mutliple missing values are reported.
4202// Using just vector here, so order is predicatble.
4203TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4204 static const int vals[] = {1, 1, 2, 3, 5, 8};
4205 static const int test_vals[] = {2, 1, 5};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004206 vector<int> my_set(vals, vals + 6);
4207 vector<int> test_set(test_vals, test_vals + 3);
4208 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004209 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004210 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4211 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004212}
4213
4214// Tests that added values are reported.
4215// Using just vector here, so order is predicatble.
4216TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4217 static const int vals[] = {1, 1, 2, 3, 5, 8};
4218 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004219 list<size_t> my_set(vals, vals + 6);
4220 list<size_t> test_set(test_vals, test_vals + 7);
4221 const Matcher<const list<size_t>&> m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004222 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004223 EXPECT_EQ("which has these unexpected elements: 92, 46",
4224 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004225}
4226
4227// Tests that added and missing values are reported together.
4228TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
4229 static const int vals[] = {1, 1, 2, 3, 5, 8};
4230 static const int test_vals[] = {1, 2, 3, 92, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004231 list<size_t> my_set(vals, vals + 6);
4232 list<size_t> test_set(test_vals, test_vals + 5);
4233 const Matcher<const list<size_t> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004234 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004235 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4236 "and doesn't have these expected elements: 5, 8",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004237 Explain(m, test_set));
4238}
4239
4240// Tests to see that duplicate elements are detected,
4241// but (as above) not reported in the explanation.
4242TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
4243 static const int vals[] = {1, 1, 2, 3, 5, 8};
4244 static const int test_vals[] = {1, 2, 3, 5, 8};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004245 vector<int> my_set(vals, vals + 6);
4246 vector<int> test_set(test_vals, test_vals + 5);
4247 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004248 EXPECT_TRUE(m.Matches(my_set));
4249 EXPECT_FALSE(m.Matches(test_set));
4250 // There is nothing to report when both sets contain all the same values.
4251 EXPECT_EQ("", Explain(m, test_set));
4252}
4253
4254// Tests that ContainerEq works for non-trivial associative containers,
4255// like maps.
4256TEST(ContainerEqExtraTest, WorksForMaps) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004257 map<int, std::string> my_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004258 my_map[0] = "a";
4259 my_map[1] = "b";
4260
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004261 map<int, std::string> test_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004262 test_map[0] = "aa";
4263 test_map[1] = "b";
4264
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004265 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004266 EXPECT_TRUE(m.Matches(my_map));
4267 EXPECT_FALSE(m.Matches(test_map));
4268
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004269 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
4270 "and doesn't have these expected elements: (0, \"a\")",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004271 Explain(m, test_map));
4272}
4273
zhanyong.wanb8243162009-06-04 05:48:20 +00004274TEST(ContainerEqExtraTest, WorksForNativeArray) {
4275 int a1[] = { 1, 2, 3 };
4276 int a2[] = { 1, 2, 3 };
4277 int b[] = { 1, 2, 4 };
4278
4279 EXPECT_THAT(a1, ContainerEq(a2));
4280 EXPECT_THAT(a1, Not(ContainerEq(b)));
4281}
4282
4283TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
4284 const char a1[][3] = { "hi", "lo" };
4285 const char a2[][3] = { "hi", "lo" };
4286 const char b[][3] = { "lo", "hi" };
4287
4288 // Tests using ContainerEq() in the first dimension.
4289 EXPECT_THAT(a1, ContainerEq(a2));
4290 EXPECT_THAT(a1, Not(ContainerEq(b)));
4291
4292 // Tests using ContainerEq() in the second dimension.
4293 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
4294 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
4295}
4296
4297TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
4298 const int a1[] = { 1, 2, 3 };
4299 const int a2[] = { 1, 2, 3 };
4300 const int b[] = { 1, 2, 3, 4 };
4301
zhanyong.wan2661c682009-06-09 05:42:12 +00004302 const int* const p1 = a1;
4303 EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
4304 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004305
4306 const int c[] = { 1, 3, 2 };
zhanyong.wan2661c682009-06-09 05:42:12 +00004307 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004308}
4309
4310TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
4311 std::string a1[][3] = {
4312 { "hi", "hello", "ciao" },
4313 { "bye", "see you", "ciao" }
4314 };
4315
4316 std::string a2[][3] = {
4317 { "hi", "hello", "ciao" },
4318 { "bye", "see you", "ciao" }
4319 };
4320
4321 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
4322 EXPECT_THAT(a1, m);
4323
4324 a2[0][0] = "ha";
4325 EXPECT_THAT(a1, m);
4326}
4327
zhanyong.wan898725c2011-09-16 16:45:39 +00004328TEST(WhenSortedByTest, WorksForEmptyContainer) {
4329 const vector<int> numbers;
4330 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
4331 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
4332}
4333
4334TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
4335 vector<unsigned> numbers;
4336 numbers.push_back(3);
4337 numbers.push_back(1);
4338 numbers.push_back(2);
4339 numbers.push_back(2);
4340 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
4341 ElementsAre(3, 2, 2, 1)));
4342 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
4343 ElementsAre(1, 2, 2, 3))));
4344}
4345
4346TEST(WhenSortedByTest, WorksForNonVectorContainer) {
4347 list<string> words;
4348 words.push_back("say");
4349 words.push_back("hello");
4350 words.push_back("world");
4351 EXPECT_THAT(words, WhenSortedBy(less<string>(),
4352 ElementsAre("hello", "say", "world")));
4353 EXPECT_THAT(words, Not(WhenSortedBy(less<string>(),
4354 ElementsAre("say", "hello", "world"))));
4355}
4356
4357TEST(WhenSortedByTest, WorksForNativeArray) {
4358 const int numbers[] = { 1, 3, 2, 4 };
4359 const int sorted_numbers[] = { 1, 2, 3, 4 };
4360 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
4361 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
4362 ElementsAreArray(sorted_numbers)));
4363 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
4364}
4365
4366TEST(WhenSortedByTest, CanDescribeSelf) {
4367 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
4368 EXPECT_EQ("(when sorted) has 2 elements where\n"
4369 "element #0 is equal to 1,\n"
4370 "element #1 is equal to 2",
4371 Describe(m));
4372 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
4373 "element #0 isn't equal to 1, or\n"
4374 "element #1 isn't equal to 2",
4375 DescribeNegation(m));
4376}
4377
4378TEST(WhenSortedByTest, ExplainsMatchResult) {
4379 const int a[] = { 2, 1 };
4380 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
4381 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
4382 EXPECT_EQ("which is { 1, 2 } when sorted",
4383 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
4384}
4385
4386// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
4387// need to test it as exhaustively as we test the latter.
4388
4389TEST(WhenSortedTest, WorksForEmptyContainer) {
4390 const vector<int> numbers;
4391 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
4392 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
4393}
4394
4395TEST(WhenSortedTest, WorksForNonEmptyContainer) {
4396 list<string> words;
4397 words.push_back("3");
4398 words.push_back("1");
4399 words.push_back("2");
4400 words.push_back("2");
4401 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
4402 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
4403}
4404
zhanyong.wana9a59e02013-03-27 16:14:55 +00004405TEST(WhenSortedTest, WorksForMapTypes) {
4406 map<string, int> word_counts;
4407 word_counts["and"] = 1;
4408 word_counts["the"] = 1;
4409 word_counts["buffalo"] = 2;
4410 EXPECT_THAT(word_counts, WhenSorted(ElementsAre(
4411 Pair("and", 1), Pair("buffalo", 2), Pair("the", 1))));
4412 EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre(
4413 Pair("and", 1), Pair("the", 1), Pair("buffalo", 2)))));
4414}
4415
4416TEST(WhenSortedTest, WorksForMultiMapTypes) {
4417 multimap<int, int> ifib;
4418 ifib.insert(make_pair(8, 6));
4419 ifib.insert(make_pair(2, 3));
4420 ifib.insert(make_pair(1, 1));
4421 ifib.insert(make_pair(3, 4));
4422 ifib.insert(make_pair(1, 2));
4423 ifib.insert(make_pair(5, 5));
4424 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
4425 Pair(1, 2),
4426 Pair(2, 3),
4427 Pair(3, 4),
4428 Pair(5, 5),
4429 Pair(8, 6))));
4430 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
4431 Pair(2, 3),
4432 Pair(1, 1),
4433 Pair(3, 4),
4434 Pair(1, 2),
4435 Pair(5, 5)))));
4436}
4437
4438TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
4439 std::deque<int> d;
4440 d.push_back(2);
4441 d.push_back(1);
4442 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
4443 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
4444}
4445
4446TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
4447 std::deque<int> d;
4448 d.push_back(2);
4449 d.push_back(1);
4450 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
4451 EXPECT_THAT(d, WhenSorted(vector_match));
4452 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
4453 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
4454}
4455
4456// Deliberately bare pseudo-container.
4457// Offers only begin() and end() accessors, yielding InputIterator.
4458template <typename T>
4459class Streamlike {
4460 private:
4461 class ConstIter;
4462 public:
4463 typedef ConstIter const_iterator;
4464 typedef T value_type;
4465
4466 template <typename InIter>
4467 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
4468
4469 const_iterator begin() const {
4470 return const_iterator(this, remainder_.begin());
4471 }
4472 const_iterator end() const {
4473 return const_iterator(this, remainder_.end());
4474 }
4475
4476 private:
4477 class ConstIter : public std::iterator<std::input_iterator_tag,
4478 value_type,
4479 ptrdiff_t,
4480 const value_type&,
4481 const value_type*> {
4482 public:
4483 ConstIter(const Streamlike* s,
4484 typename std::list<value_type>::iterator pos)
4485 : s_(s), pos_(pos) {}
4486
4487 const value_type& operator*() const { return *pos_; }
4488 const value_type* operator->() const { return &*pos_; }
4489 ConstIter& operator++() {
4490 s_->remainder_.erase(pos_++);
4491 return *this;
4492 }
4493
4494 // *iter++ is required to work (see std::istreambuf_iterator).
4495 // (void)iter++ is also required to work.
4496 class PostIncrProxy {
4497 public:
4498 explicit PostIncrProxy(const value_type& value) : value_(value) {}
4499 value_type operator*() const { return value_; }
4500 private:
4501 value_type value_;
4502 };
4503 PostIncrProxy operator++(int) {
4504 PostIncrProxy proxy(**this);
4505 ++(*this);
4506 return proxy;
4507 }
4508
4509 friend bool operator==(const ConstIter& a, const ConstIter& b) {
4510 return a.s_ == b.s_ && a.pos_ == b.pos_;
4511 }
4512 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
4513 return !(a == b);
4514 }
4515
4516 private:
4517 const Streamlike* s_;
4518 typename std::list<value_type>::iterator pos_;
4519 };
4520
4521 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
4522 os << "[";
4523 typedef typename std::list<value_type>::const_iterator Iter;
4524 const char* sep = "";
4525 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
4526 os << sep << *it;
4527 sep = ",";
4528 }
4529 os << "]";
4530 return os;
4531 }
4532
4533 mutable std::list<value_type> remainder_; // modified by iteration
4534};
4535
4536TEST(StreamlikeTest, Iteration) {
4537 const int a[5] = { 2, 1, 4, 5, 3 };
4538 Streamlike<int> s(a, a + 5);
4539 Streamlike<int>::const_iterator it = s.begin();
4540 const int* ip = a;
4541 while (it != s.end()) {
4542 SCOPED_TRACE(ip - a);
4543 EXPECT_EQ(*ip++, *it++);
4544 }
4545}
4546
kosakb6a34882014-03-12 21:06:46 +00004547#if GTEST_LANG_CXX11
4548TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
4549 std::forward_list<int> container;
4550 EXPECT_THAT(container, BeginEndDistanceIs(0));
4551 EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
4552 container.push_front(0);
4553 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4554 EXPECT_THAT(container, BeginEndDistanceIs(1));
4555 container.push_front(0);
4556 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4557 EXPECT_THAT(container, BeginEndDistanceIs(2));
4558}
4559#endif // GTEST_LANG_CXX11
4560
4561TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
4562 const int a[5] = { 1, 2, 3, 4, 5 };
4563 Streamlike<int> s(a, a + 5);
4564 EXPECT_THAT(s, BeginEndDistanceIs(5));
4565}
4566
4567TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
4568 Matcher<vector<int> > m = BeginEndDistanceIs(2);
4569 EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
4570 EXPECT_EQ("distance between begin() and end() isn't equal to 2",
4571 DescribeNegation(m));
4572}
4573
4574TEST(BeginEndDistanceIsTest, ExplainsResult) {
4575 Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
4576 Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
4577 Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
4578 Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
4579 vector<int> container;
4580 EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
4581 Explain(m1, container));
4582 EXPECT_EQ("whose distance between begin() and end() 0 matches",
4583 Explain(m2, container));
4584 EXPECT_EQ("whose distance between begin() and end() 0 matches",
4585 Explain(m3, container));
4586 EXPECT_EQ(
4587 "whose distance between begin() and end() 0 doesn't match, which is 1 "
4588 "less than 1",
4589 Explain(m4, container));
4590 container.push_back(0);
4591 container.push_back(0);
4592 EXPECT_EQ("whose distance between begin() and end() 2 matches",
4593 Explain(m1, container));
4594 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4595 Explain(m2, container));
4596 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4597 Explain(m3, container));
4598 EXPECT_EQ(
4599 "whose distance between begin() and end() 2 matches, which is 1 more "
4600 "than 1",
4601 Explain(m4, container));
4602}
4603
zhanyong.wana9a59e02013-03-27 16:14:55 +00004604TEST(WhenSortedTest, WorksForStreamlike) {
4605 // Streamlike 'container' provides only minimal iterator support.
4606 // Its iterators are tagged with input_iterator_tag.
4607 const int a[5] = { 2, 1, 4, 5, 3 };
kosak6414d802013-12-03 23:19:36 +00004608 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004609 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
4610 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4611}
4612
4613TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00004614 const int a[] = { 2, 1, 4, 5, 3 };
kosak6414d802013-12-03 23:19:36 +00004615 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004616 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
4617 EXPECT_THAT(s, WhenSorted(vector_match));
4618 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4619}
4620
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004621// Tests using ElementsAre() and ElementsAreArray() with stream-like
4622// "containers".
4623
4624TEST(ElemensAreStreamTest, WorksForStreamlike) {
4625 const int a[5] = { 1, 2, 3, 4, 5 };
kosak6414d802013-12-03 23:19:36 +00004626 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004627 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
4628 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
4629}
4630
4631TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
4632 const int a[5] = { 1, 2, 3, 4, 5 };
kosak6414d802013-12-03 23:19:36 +00004633 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004634
4635 vector<int> expected;
4636 expected.push_back(1);
4637 expected.push_back(2);
4638 expected.push_back(3);
4639 expected.push_back(4);
4640 expected.push_back(5);
4641 EXPECT_THAT(s, ElementsAreArray(expected));
4642
4643 expected[3] = 0;
4644 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
4645}
4646
billydonahue1f5fdea2014-05-19 17:54:51 +00004647TEST(ElementsAreTest, WorksWithUncopyable) {
4648 Uncopyable objs[2];
4649 objs[0].set_value(-3);
4650 objs[1].set_value(1);
4651 EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));
4652}
4653
kosak06678922014-07-28 20:01:28 +00004654TEST(ElementsAreTest, TakesStlContainer) {
4655 const int actual[] = {3, 1, 2};
4656
4657 ::std::list<int> expected;
4658 expected.push_back(3);
4659 expected.push_back(1);
4660 expected.push_back(2);
4661 EXPECT_THAT(actual, ElementsAreArray(expected));
4662
4663 expected.push_back(4);
4664 EXPECT_THAT(actual, Not(ElementsAreArray(expected)));
4665}
4666
zhanyong.wanfb25d532013-07-28 08:24:00 +00004667// Tests for UnorderedElementsAreArray()
4668
4669TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
4670 const int a[] = { 0, 1, 2, 3, 4 };
kosak6414d802013-12-03 23:19:36 +00004671 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004672 do {
4673 StringMatchResultListener listener;
4674 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
4675 s, &listener)) << listener.str();
4676 } while (std::next_permutation(s.begin(), s.end()));
4677}
4678
4679TEST(UnorderedElementsAreArrayTest, VectorBool) {
4680 const bool a[] = { 0, 1, 0, 1, 1 };
4681 const bool b[] = { 1, 0, 1, 1, 0 };
kosak6414d802013-12-03 23:19:36 +00004682 std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a));
4683 std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004684 StringMatchResultListener listener;
4685 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
4686 actual, &listener)) << listener.str();
4687}
4688
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004689TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
4690 // Streamlike 'container' provides only minimal iterator support.
4691 // Its iterators are tagged with input_iterator_tag, and it has no
4692 // size() or empty() methods.
4693 const int a[5] = { 2, 1, 4, 5, 3 };
kosak6414d802013-12-03 23:19:36 +00004694 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004695
4696 ::std::vector<int> expected;
4697 expected.push_back(1);
4698 expected.push_back(2);
4699 expected.push_back(3);
4700 expected.push_back(4);
4701 expected.push_back(5);
4702 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
4703
4704 expected.push_back(6);
4705 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
4706}
4707
kosak06678922014-07-28 20:01:28 +00004708TEST(UnorderedElementsAreArrayTest, TakesStlContainer) {
4709 const int actual[] = {3, 1, 2};
4710
4711 ::std::list<int> expected;
4712 expected.push_back(1);
4713 expected.push_back(2);
4714 expected.push_back(3);
4715 EXPECT_THAT(actual, UnorderedElementsAreArray(expected));
4716
4717 expected.push_back(4);
4718 EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));
4719}
4720
kosak18489fa2013-12-04 23:49:07 +00004721#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004722
4723TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
4724 const int a[5] = { 2, 1, 4, 5, 3 };
4725 EXPECT_THAT(a, UnorderedElementsAreArray({ 1, 2, 3, 4, 5 }));
4726 EXPECT_THAT(a, Not(UnorderedElementsAreArray({ 1, 2, 3, 4, 6 })));
4727}
4728
4729TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
4730 const string a[5] = { "a", "b", "c", "d", "e" };
4731 EXPECT_THAT(a, UnorderedElementsAreArray({ "a", "b", "c", "d", "e" }));
4732 EXPECT_THAT(a, Not(UnorderedElementsAreArray({ "a", "b", "c", "d", "ef" })));
4733}
4734
4735TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
4736 const int a[5] = { 2, 1, 4, 5, 3 };
4737 EXPECT_THAT(a, UnorderedElementsAreArray(
4738 { Eq(1), Eq(2), Eq(3), Eq(4), Eq(5) }));
4739 EXPECT_THAT(a, Not(UnorderedElementsAreArray(
4740 { Eq(1), Eq(2), Eq(3), Eq(4), Eq(6) })));
4741}
4742
4743TEST(UnorderedElementsAreArrayTest,
4744 TakesInitializerListOfDifferentTypedMatchers) {
4745 const int a[5] = { 2, 1, 4, 5, 3 };
4746 // The compiler cannot infer the type of the initializer list if its
4747 // elements have different types. We must explicitly specify the
4748 // unified element type in this case.
4749 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
4750 { Eq(1), Ne(-2), Ge(3), Le(4), Eq(5) }));
4751 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
4752 { Eq(1), Ne(-2), Ge(3), Le(4), Eq(6) })));
4753}
4754
kosak18489fa2013-12-04 23:49:07 +00004755#endif // GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004756
zhanyong.wanfb25d532013-07-28 08:24:00 +00004757class UnorderedElementsAreTest : public testing::Test {
4758 protected:
4759 typedef std::vector<int> IntVec;
4760};
4761
billydonahue1f5fdea2014-05-19 17:54:51 +00004762TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {
4763 Uncopyable objs[2];
4764 objs[0].set_value(-3);
4765 objs[1].set_value(1);
4766 EXPECT_THAT(objs,
4767 UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));
4768}
4769
zhanyong.wanfb25d532013-07-28 08:24:00 +00004770TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
4771 const int a[] = { 1, 2, 3 };
kosak6414d802013-12-03 23:19:36 +00004772 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004773 do {
4774 StringMatchResultListener listener;
4775 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4776 s, &listener)) << listener.str();
4777 } while (std::next_permutation(s.begin(), s.end()));
4778}
4779
4780TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
4781 const int a[] = { 1, 2, 3 };
kosak6414d802013-12-03 23:19:36 +00004782 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004783 std::vector<Matcher<int> > mv;
4784 mv.push_back(1);
4785 mv.push_back(2);
4786 mv.push_back(2);
4787 // The element with value '3' matches nothing: fail fast.
4788 StringMatchResultListener listener;
4789 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4790 s, &listener)) << listener.str();
4791}
4792
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004793TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
4794 // Streamlike 'container' provides only minimal iterator support.
4795 // Its iterators are tagged with input_iterator_tag, and it has no
4796 // size() or empty() methods.
4797 const int a[5] = { 2, 1, 4, 5, 3 };
kosak6414d802013-12-03 23:19:36 +00004798 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004799
4800 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
4801 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
4802}
4803
zhanyong.wanfb25d532013-07-28 08:24:00 +00004804// One naive implementation of the matcher runs in O(N!) time, which is too
4805// slow for many real-world inputs. This test shows that our matcher can match
4806// 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
4807// iterations and obviously effectively incomputable.
4808// [ RUN ] UnorderedElementsAreTest.Performance
4809// [ OK ] UnorderedElementsAreTest.Performance (4 ms)
4810TEST_F(UnorderedElementsAreTest, Performance) {
4811 std::vector<int> s;
4812 std::vector<Matcher<int> > mv;
4813 for (int i = 0; i < 100; ++i) {
4814 s.push_back(i);
4815 mv.push_back(_);
4816 }
4817 mv[50] = Eq(0);
4818 StringMatchResultListener listener;
4819 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4820 s, &listener)) << listener.str();
4821}
4822
4823// Another variant of 'Performance' with similar expectations.
4824// [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
4825// [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
4826TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
4827 std::vector<int> s;
4828 std::vector<Matcher<int> > mv;
4829 for (int i = 0; i < 100; ++i) {
4830 s.push_back(i);
4831 if (i & 1) {
4832 mv.push_back(_);
4833 } else {
4834 mv.push_back(i);
4835 }
4836 }
4837 StringMatchResultListener listener;
4838 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4839 s, &listener)) << listener.str();
4840}
4841
4842TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
4843 std::vector<int> v;
4844 v.push_back(4);
4845 StringMatchResultListener listener;
4846 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4847 v, &listener)) << listener.str();
4848 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
4849}
4850
4851TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
4852 std::vector<int> v;
4853 StringMatchResultListener listener;
4854 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4855 v, &listener)) << listener.str();
4856 EXPECT_THAT(listener.str(), Eq(""));
4857}
4858
4859TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
4860 std::vector<int> v;
4861 v.push_back(1);
4862 v.push_back(1);
4863 StringMatchResultListener listener;
4864 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4865 v, &listener)) << listener.str();
4866 EXPECT_THAT(
4867 listener.str(),
4868 Eq("where the following matchers don't match any elements:\n"
4869 "matcher #1: is equal to 2"));
4870}
4871
4872TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
4873 std::vector<int> v;
4874 v.push_back(1);
4875 v.push_back(2);
4876 StringMatchResultListener listener;
4877 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
4878 v, &listener)) << listener.str();
4879 EXPECT_THAT(
4880 listener.str(),
4881 Eq("where the following elements don't match any matchers:\n"
4882 "element #1: 2"));
4883}
4884
4885TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
4886 std::vector<int> v;
4887 v.push_back(2);
4888 v.push_back(3);
4889 StringMatchResultListener listener;
4890 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4891 v, &listener)) << listener.str();
4892 EXPECT_THAT(
4893 listener.str(),
4894 Eq("where"
4895 " the following matchers don't match any elements:\n"
4896 "matcher #0: is equal to 1\n"
4897 "and"
4898 " where"
4899 " the following elements don't match any matchers:\n"
4900 "element #1: 3"));
4901}
4902
4903// Test helper for formatting element, matcher index pairs in expectations.
4904static string EMString(int element, int matcher) {
4905 stringstream ss;
4906 ss << "(element #" << element << ", matcher #" << matcher << ")";
4907 return ss.str();
4908}
4909
4910TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
4911 // A situation where all elements and matchers have a match
4912 // associated with them, but the max matching is not perfect.
4913 std::vector<string> v;
4914 v.push_back("a");
4915 v.push_back("b");
4916 v.push_back("c");
4917 StringMatchResultListener listener;
4918 EXPECT_FALSE(ExplainMatchResult(
4919 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
4920 << listener.str();
4921
4922 string prefix =
4923 "where no permutation of the elements can satisfy all matchers, "
4924 "and the closest match is 2 of 3 matchers with the "
4925 "pairings:\n";
4926
4927 // We have to be a bit loose here, because there are 4 valid max matches.
4928 EXPECT_THAT(
4929 listener.str(),
4930 AnyOf(prefix + "{\n " + EMString(0, 0) +
4931 ",\n " + EMString(1, 2) + "\n}",
4932 prefix + "{\n " + EMString(0, 1) +
4933 ",\n " + EMString(1, 2) + "\n}",
4934 prefix + "{\n " + EMString(0, 0) +
4935 ",\n " + EMString(2, 2) + "\n}",
4936 prefix + "{\n " + EMString(0, 1) +
4937 ",\n " + EMString(2, 2) + "\n}"));
4938}
4939
4940TEST_F(UnorderedElementsAreTest, Describe) {
4941 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
4942 Eq("is empty"));
4943 EXPECT_THAT(
4944 Describe<IntVec>(UnorderedElementsAre(345)),
4945 Eq("has 1 element and that element is equal to 345"));
4946 EXPECT_THAT(
4947 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
4948 Eq("has 3 elements and there exists some permutation "
4949 "of elements such that:\n"
4950 " - element #0 is equal to 111, and\n"
4951 " - element #1 is equal to 222, and\n"
4952 " - element #2 is equal to 333"));
4953}
4954
4955TEST_F(UnorderedElementsAreTest, DescribeNegation) {
4956 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
4957 Eq("isn't empty"));
4958 EXPECT_THAT(
4959 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
4960 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
4961 EXPECT_THAT(
4962 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
4963 Eq("doesn't have 3 elements, or there exists no permutation "
4964 "of elements such that:\n"
4965 " - element #0 is equal to 123, and\n"
4966 " - element #1 is equal to 234, and\n"
4967 " - element #2 is equal to 345"));
4968}
4969
4970namespace {
4971
4972// Used as a check on the more complex max flow method used in the
4973// real testing::internal::FindMaxBipartiteMatching. This method is
4974// compatible but runs in worst-case factorial time, so we only
4975// use it in testing for small problem sizes.
4976template <typename Graph>
4977class BacktrackingMaxBPMState {
4978 public:
4979 // Does not take ownership of 'g'.
4980 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
4981
4982 ElementMatcherPairs Compute() {
4983 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
4984 return best_so_far_;
4985 }
4986 lhs_used_.assign(graph_->LhsSize(), kUnused);
4987 rhs_used_.assign(graph_->RhsSize(), kUnused);
4988 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
4989 matches_.clear();
4990 RecurseInto(irhs);
4991 if (best_so_far_.size() == graph_->RhsSize())
4992 break;
4993 }
4994 return best_so_far_;
4995 }
4996
4997 private:
4998 static const size_t kUnused = static_cast<size_t>(-1);
4999
5000 void PushMatch(size_t lhs, size_t rhs) {
5001 matches_.push_back(ElementMatcherPair(lhs, rhs));
5002 lhs_used_[lhs] = rhs;
5003 rhs_used_[rhs] = lhs;
5004 if (matches_.size() > best_so_far_.size()) {
5005 best_so_far_ = matches_;
5006 }
5007 }
5008
5009 void PopMatch() {
5010 const ElementMatcherPair& back = matches_.back();
5011 lhs_used_[back.first] = kUnused;
5012 rhs_used_[back.second] = kUnused;
5013 matches_.pop_back();
5014 }
5015
5016 bool RecurseInto(size_t irhs) {
5017 if (rhs_used_[irhs] != kUnused) {
5018 return true;
5019 }
5020 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
5021 if (lhs_used_[ilhs] != kUnused) {
5022 continue;
5023 }
5024 if (!graph_->HasEdge(ilhs, irhs)) {
5025 continue;
5026 }
5027 PushMatch(ilhs, irhs);
5028 if (best_so_far_.size() == graph_->RhsSize()) {
5029 return false;
5030 }
5031 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
5032 if (!RecurseInto(mi)) return false;
5033 }
5034 PopMatch();
5035 }
5036 return true;
5037 }
5038
5039 const Graph* graph_; // not owned
5040 std::vector<size_t> lhs_used_;
5041 std::vector<size_t> rhs_used_;
5042 ElementMatcherPairs matches_;
5043 ElementMatcherPairs best_so_far_;
5044};
5045
5046template <typename Graph>
5047const size_t BacktrackingMaxBPMState<Graph>::kUnused;
5048
5049} // namespace
5050
5051// Implement a simple backtracking algorithm to determine if it is possible
5052// to find one element per matcher, without reusing elements.
5053template <typename Graph>
5054ElementMatcherPairs
5055FindBacktrackingMaxBPM(const Graph& g) {
5056 return BacktrackingMaxBPMState<Graph>(&g).Compute();
5057}
5058
5059class BacktrackingBPMTest : public ::testing::Test { };
5060
5061// Tests the MaxBipartiteMatching algorithm with square matrices.
5062// The single int param is the # of nodes on each of the left and right sides.
5063class BipartiteTest : public ::testing::TestWithParam<int> { };
5064
5065// Verify all match graphs up to some moderate number of edges.
5066TEST_P(BipartiteTest, Exhaustive) {
5067 int nodes = GetParam();
5068 MatchMatrix graph(nodes, nodes);
5069 do {
5070 ElementMatcherPairs matches =
5071 internal::FindMaxBipartiteMatching(graph);
5072 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
5073 << "graph: " << graph.DebugString();
5074 // Check that all elements of matches are in the graph.
5075 // Check that elements of first and second are unique.
5076 std::vector<bool> seen_element(graph.LhsSize());
5077 std::vector<bool> seen_matcher(graph.RhsSize());
5078 SCOPED_TRACE(PrintToString(matches));
5079 for (size_t i = 0; i < matches.size(); ++i) {
5080 size_t ilhs = matches[i].first;
5081 size_t irhs = matches[i].second;
5082 EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
5083 EXPECT_FALSE(seen_element[ilhs]);
5084 EXPECT_FALSE(seen_matcher[irhs]);
5085 seen_element[ilhs] = true;
5086 seen_matcher[irhs] = true;
5087 }
5088 } while (graph.NextGraph());
5089}
5090
5091INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest,
5092 ::testing::Range(0, 5));
5093
5094// Parameterized by a pair interpreted as (LhsSize, RhsSize).
5095class BipartiteNonSquareTest
5096 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
5097};
5098
5099TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
5100 // .......
5101 // 0:-----\ :
5102 // 1:---\ | :
5103 // 2:---\ | :
5104 // 3:-\ | | :
5105 // :.......:
5106 // 0 1 2
5107 MatchMatrix g(4, 3);
5108 static const int kEdges[][2] = { {0, 2}, {1, 1}, {2, 1}, {3, 0} };
kosak6414d802013-12-03 23:19:36 +00005109 for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00005110 g.SetEdge(kEdges[i][0], kEdges[i][1], true);
5111 }
5112 EXPECT_THAT(FindBacktrackingMaxBPM(g),
5113 ElementsAre(Pair(3, 0),
5114 Pair(AnyOf(1, 2), 1),
5115 Pair(0, 2))) << g.DebugString();
5116}
5117
5118// Verify a few nonsquare matrices.
5119TEST_P(BipartiteNonSquareTest, Exhaustive) {
5120 size_t nlhs = GetParam().first;
5121 size_t nrhs = GetParam().second;
5122 MatchMatrix graph(nlhs, nrhs);
5123 do {
5124 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5125 internal::FindMaxBipartiteMatching(graph).size())
5126 << "graph: " << graph.DebugString()
5127 << "\nbacktracking: "
5128 << PrintToString(FindBacktrackingMaxBPM(graph))
5129 << "\nmax flow: "
5130 << PrintToString(internal::FindMaxBipartiteMatching(graph));
5131 } while (graph.NextGraph());
5132}
5133
5134INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest,
5135 testing::Values(
5136 std::make_pair(1, 2),
5137 std::make_pair(2, 1),
5138 std::make_pair(3, 2),
5139 std::make_pair(2, 3),
5140 std::make_pair(4, 1),
5141 std::make_pair(1, 4),
5142 std::make_pair(4, 3),
5143 std::make_pair(3, 4)));
5144
5145class BipartiteRandomTest
5146 : public ::testing::TestWithParam<std::pair<int, int> > {
5147};
5148
5149// Verifies a large sample of larger graphs.
5150TEST_P(BipartiteRandomTest, LargerNets) {
5151 int nodes = GetParam().first;
5152 int iters = GetParam().second;
5153 MatchMatrix graph(nodes, nodes);
5154
5155 testing::internal::Int32 seed = GTEST_FLAG(random_seed);
5156 if (seed == 0) {
5157 seed = static_cast<testing::internal::Int32>(time(NULL));
5158 }
5159
5160 for (; iters > 0; --iters, ++seed) {
5161 srand(static_cast<int>(seed));
5162 graph.Randomize();
5163 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5164 internal::FindMaxBipartiteMatching(graph).size())
5165 << " graph: " << graph.DebugString()
5166 << "\nTo reproduce the failure, rerun the test with the flag"
5167 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
5168 }
5169}
5170
5171// Test argument is a std::pair<int, int> representing (nodes, iters).
5172INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest,
5173 testing::Values(
5174 std::make_pair(5, 10000),
5175 std::make_pair(6, 5000),
5176 std::make_pair(7, 2000),
5177 std::make_pair(8, 500),
5178 std::make_pair(9, 100)));
5179
zhanyong.wan736baa82010-09-27 17:44:16 +00005180// Tests IsReadableTypeName().
5181
5182TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
5183 EXPECT_TRUE(IsReadableTypeName("int"));
5184 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
5185 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
5186 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
5187}
5188
5189TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
5190 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
5191 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
5192 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
5193}
5194
5195TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
5196 EXPECT_FALSE(
5197 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
5198 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
5199}
5200
5201TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
5202 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
5203}
5204
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005205// Tests JoinAsTuple().
5206
5207TEST(JoinAsTupleTest, JoinsEmptyTuple) {
5208 EXPECT_EQ("", JoinAsTuple(Strings()));
5209}
5210
5211TEST(JoinAsTupleTest, JoinsOneTuple) {
5212 const char* fields[] = { "1" };
5213 EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
5214}
5215
5216TEST(JoinAsTupleTest, JoinsTwoTuple) {
5217 const char* fields[] = { "1", "a" };
5218 EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
5219}
5220
5221TEST(JoinAsTupleTest, JoinsTenTuple) {
5222 const char* fields[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
5223 EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
5224 JoinAsTuple(Strings(fields, fields + 10)));
5225}
5226
5227// Tests FormatMatcherDescription().
5228
5229TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
5230 EXPECT_EQ("is even",
zhanyong.wanb4140802010-06-08 22:53:57 +00005231 FormatMatcherDescription(false, "IsEven", Strings()));
5232 EXPECT_EQ("not (is even)",
5233 FormatMatcherDescription(true, "IsEven", Strings()));
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005234
5235 const char* params[] = { "5" };
5236 EXPECT_EQ("equals 5",
zhanyong.wanb4140802010-06-08 22:53:57 +00005237 FormatMatcherDescription(false, "Equals",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005238 Strings(params, params + 1)));
5239
5240 const char* params2[] = { "5", "8" };
5241 EXPECT_EQ("is in range (5, 8)",
zhanyong.wanb4140802010-06-08 22:53:57 +00005242 FormatMatcherDescription(false, "IsInRange",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005243 Strings(params2, params2 + 2)));
5244}
5245
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00005246// Tests PolymorphicMatcher::mutable_impl().
5247TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
5248 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5249 DivisibleByImpl& impl = m.mutable_impl();
5250 EXPECT_EQ(42, impl.divider());
5251
5252 impl.set_divider(0);
5253 EXPECT_EQ(0, m.mutable_impl().divider());
5254}
5255
5256// Tests PolymorphicMatcher::impl().
5257TEST(PolymorphicMatcherTest, CanAccessImpl) {
5258 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5259 const DivisibleByImpl& impl = m.impl();
5260 EXPECT_EQ(42, impl.divider());
5261}
5262
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005263TEST(MatcherTupleTest, ExplainsMatchFailure) {
5264 stringstream ss1;
5265 ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
5266 make_tuple('a', 10), &ss1);
5267 EXPECT_EQ("", ss1.str()); // Successful match.
5268
5269 stringstream ss2;
5270 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5271 make_tuple(2, 'b'), &ss2);
5272 EXPECT_EQ(" Expected arg #0: is > 5\n"
5273 " Actual: 2, which is 3 less than 5\n"
zhanyong.wand60c5f42010-07-21 22:21:07 +00005274 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
5275 " Actual: 'b' (98, 0x62)\n",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005276 ss2.str()); // Failed match where both arguments need explanation.
5277
5278 stringstream ss3;
5279 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5280 make_tuple(2, 'a'), &ss3);
5281 EXPECT_EQ(" Expected arg #0: is > 5\n"
5282 " Actual: 2, which is 3 less than 5\n",
5283 ss3.str()); // Failed match where only one argument needs
5284 // explanation.
5285}
5286
zhanyong.wan33605ba2010-04-22 23:37:47 +00005287// Tests Each().
5288
5289TEST(EachTest, ExplainsMatchResultCorrectly) {
5290 set<int> a; // empty
5291
5292 Matcher<set<int> > m = Each(2);
5293 EXPECT_EQ("", Explain(m, a));
5294
zhanyong.wan736baa82010-09-27 17:44:16 +00005295 Matcher<const int(&)[1]> n = Each(1); // NOLINT
zhanyong.wan33605ba2010-04-22 23:37:47 +00005296
5297 const int b[1] = { 1 };
5298 EXPECT_EQ("", Explain(n, b));
5299
5300 n = Each(3);
5301 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
5302
5303 a.insert(1);
5304 a.insert(2);
5305 a.insert(3);
5306 m = Each(GreaterThan(0));
5307 EXPECT_EQ("", Explain(m, a));
5308
5309 m = Each(GreaterThan(10));
5310 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
5311 Explain(m, a));
5312}
5313
5314TEST(EachTest, DescribesItselfCorrectly) {
5315 Matcher<vector<int> > m = Each(1);
5316 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
5317
5318 Matcher<vector<int> > m2 = Not(m);
5319 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
5320}
5321
5322TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
5323 vector<int> some_vector;
5324 EXPECT_THAT(some_vector, Each(1));
5325 some_vector.push_back(3);
5326 EXPECT_THAT(some_vector, Not(Each(1)));
5327 EXPECT_THAT(some_vector, Each(3));
5328 some_vector.push_back(1);
5329 some_vector.push_back(2);
5330 EXPECT_THAT(some_vector, Not(Each(3)));
5331 EXPECT_THAT(some_vector, Each(Lt(3.5)));
5332
5333 vector<string> another_vector;
5334 another_vector.push_back("fee");
5335 EXPECT_THAT(another_vector, Each(string("fee")));
5336 another_vector.push_back("fie");
5337 another_vector.push_back("foe");
5338 another_vector.push_back("fum");
5339 EXPECT_THAT(another_vector, Not(Each(string("fee"))));
5340}
5341
5342TEST(EachTest, MatchesMapWhenAllElementsMatch) {
5343 map<const char*, int> my_map;
5344 const char* bar = "a string";
5345 my_map[bar] = 2;
5346 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
5347
5348 map<string, int> another_map;
5349 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5350 another_map["fee"] = 1;
5351 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5352 another_map["fie"] = 2;
5353 another_map["foe"] = 3;
5354 another_map["fum"] = 4;
5355 EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1))));
5356 EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1))));
5357 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
5358}
5359
5360TEST(EachTest, AcceptsMatcher) {
5361 const int a[] = { 1, 2, 3 };
5362 EXPECT_THAT(a, Each(Gt(0)));
5363 EXPECT_THAT(a, Not(Each(Gt(1))));
5364}
5365
5366TEST(EachTest, WorksForNativeArrayAsTuple) {
5367 const int a[] = { 1, 2 };
5368 const int* const pointer = a;
5369 EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
5370 EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
5371}
5372
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005373// For testing Pointwise().
5374class IsHalfOfMatcher {
5375 public:
5376 template <typename T1, typename T2>
5377 bool MatchAndExplain(const tuple<T1, T2>& a_pair,
5378 MatchResultListener* listener) const {
5379 if (get<0>(a_pair) == get<1>(a_pair)/2) {
5380 *listener << "where the second is " << get<1>(a_pair);
5381 return true;
5382 } else {
5383 *listener << "where the second/2 is " << get<1>(a_pair)/2;
5384 return false;
5385 }
5386 }
5387
5388 void DescribeTo(ostream* os) const {
5389 *os << "are a pair where the first is half of the second";
5390 }
5391
5392 void DescribeNegationTo(ostream* os) const {
5393 *os << "are a pair where the first isn't half of the second";
5394 }
5395};
5396
5397PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
5398 return MakePolymorphicMatcher(IsHalfOfMatcher());
5399}
5400
5401TEST(PointwiseTest, DescribesSelf) {
5402 vector<int> rhs;
5403 rhs.push_back(1);
5404 rhs.push_back(2);
5405 rhs.push_back(3);
5406 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
5407 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
5408 "in { 1, 2, 3 } are a pair where the first is half of the second",
5409 Describe(m));
5410 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
5411 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
5412 "where the first isn't half of the second",
5413 DescribeNegation(m));
5414}
5415
5416TEST(PointwiseTest, MakesCopyOfRhs) {
5417 list<signed char> rhs;
5418 rhs.push_back(2);
5419 rhs.push_back(4);
5420
5421 int lhs[] = { 1, 2 };
5422 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
5423 EXPECT_THAT(lhs, m);
5424
5425 // Changing rhs now shouldn't affect m, which made a copy of rhs.
5426 rhs.push_back(6);
5427 EXPECT_THAT(lhs, m);
5428}
5429
5430TEST(PointwiseTest, WorksForLhsNativeArray) {
5431 const int lhs[] = { 1, 2, 3 };
5432 vector<int> rhs;
5433 rhs.push_back(2);
5434 rhs.push_back(4);
5435 rhs.push_back(6);
5436 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
5437 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5438}
5439
5440TEST(PointwiseTest, WorksForRhsNativeArray) {
5441 const int rhs[] = { 1, 2, 3 };
5442 vector<int> lhs;
5443 lhs.push_back(2);
5444 lhs.push_back(4);
5445 lhs.push_back(6);
5446 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
5447 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
5448}
5449
5450TEST(PointwiseTest, RejectsWrongSize) {
5451 const double lhs[2] = { 1, 2 };
5452 const int rhs[1] = { 0 };
5453 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5454 EXPECT_EQ("which contains 2 values",
5455 Explain(Pointwise(Gt(), rhs), lhs));
5456
5457 const int rhs2[3] = { 0, 1, 2 };
5458 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
5459}
5460
5461TEST(PointwiseTest, RejectsWrongContent) {
5462 const double lhs[3] = { 1, 2, 3 };
5463 const int rhs[3] = { 2, 6, 4 };
5464 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
5465 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
5466 "where the second/2 is 3",
5467 Explain(Pointwise(IsHalfOf(), rhs), lhs));
5468}
5469
5470TEST(PointwiseTest, AcceptsCorrectContent) {
5471 const double lhs[3] = { 1, 2, 3 };
5472 const int rhs[3] = { 2, 4, 6 };
5473 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
5474 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
5475}
5476
5477TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
5478 const double lhs[3] = { 1, 2, 3 };
5479 const int rhs[3] = { 2, 4, 6 };
5480 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5481 EXPECT_THAT(lhs, Pointwise(m1, rhs));
5482 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
5483
5484 // This type works as a tuple<const double&, const int&> can be
5485 // implicitly cast to tuple<double, int>.
5486 const Matcher<tuple<double, int> > m2 = IsHalfOf();
5487 EXPECT_THAT(lhs, Pointwise(m2, rhs));
5488 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
5489}
5490
shiqiane35fdd92008-12-10 05:08:54 +00005491} // namespace gmock_matchers_test
5492} // namespace testing