blob: 68a027bf1f9eaf69ea89d2304eafa0494aa3d6b3 [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
kosak15d61e42014-03-24 22:08:24 +000036// windows.h defines macros which conflict with standard identifiers used in
37// this test. Defining this symbol prevents windows.h from doing that.
38#define NOMINMAX
39
zhanyong.wan53e08c42010-09-14 05:38:21 +000040#include "gmock/gmock-matchers.h"
zhanyong.wan320814a2013-03-01 00:20:30 +000041#include "gmock/gmock-more-matchers.h"
shiqiane35fdd92008-12-10 05:08:54 +000042
43#include <string.h>
zhanyong.wanfb25d532013-07-28 08:24:00 +000044#include <time.h>
zhanyong.wana9a59e02013-03-27 16:14:55 +000045#include <deque>
shiqiane35fdd92008-12-10 05:08:54 +000046#include <functional>
zhanyong.wana862f1d2010-03-15 21:23:04 +000047#include <iostream>
zhanyong.wana9a59e02013-03-27 16:14:55 +000048#include <iterator>
zhanyong.wan616180e2013-06-18 18:49:51 +000049#include <limits>
zhanyong.wan6a896b52009-01-16 01:13:50 +000050#include <list>
51#include <map>
52#include <set>
shiqiane35fdd92008-12-10 05:08:54 +000053#include <sstream>
zhanyong.wan6a896b52009-01-16 01:13:50 +000054#include <string>
zhanyong.wanf5e1ce52009-09-16 07:02:02 +000055#include <utility>
zhanyong.wan6a896b52009-01-16 01:13:50 +000056#include <vector>
zhanyong.wan53e08c42010-09-14 05:38:21 +000057#include "gmock/gmock.h"
58#include "gtest/gtest.h"
59#include "gtest/gtest-spi.h"
shiqiane35fdd92008-12-10 05:08:54 +000060
kosakb6a34882014-03-12 21:06:46 +000061#if GTEST_LANG_CXX11
62# include <forward_list> // NOLINT
63#endif
64
shiqiane35fdd92008-12-10 05:08:54 +000065namespace testing {
zhanyong.wan4a5330d2009-02-19 00:36:44 +000066
67namespace internal {
vladlosev587c1b32011-05-20 00:42:22 +000068GTEST_API_ string JoinAsTuple(const Strings& fields);
zhanyong.wan4a5330d2009-02-19 00:36:44 +000069} // namespace internal
70
shiqiane35fdd92008-12-10 05:08:54 +000071namespace gmock_matchers_test {
72
zhanyong.wan898725c2011-09-16 16:45:39 +000073using std::greater;
74using std::less;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000075using std::list;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000076using std::make_pair;
zhanyong.wanb5937da2009-07-16 20:26:41 +000077using std::map;
78using std::multimap;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000079using std::multiset;
80using std::ostream;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000081using std::pair;
zhanyong.wan33605ba2010-04-22 23:37:47 +000082using std::set;
shiqiane35fdd92008-12-10 05:08:54 +000083using std::stringstream;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000084using std::tr1::get;
zhanyong.wanb8243162009-06-04 05:48:20 +000085using std::tr1::make_tuple;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000086using std::tr1::tuple;
zhanyong.wan33605ba2010-04-22 23:37:47 +000087using std::vector;
shiqiane35fdd92008-12-10 05:08:54 +000088using testing::A;
zhanyong.wanbf550852009-06-09 06:09:53 +000089using testing::AllArgs;
shiqiane35fdd92008-12-10 05:08:54 +000090using testing::AllOf;
91using testing::An;
92using testing::AnyOf;
93using testing::ByRef;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000094using testing::ContainsRegex;
shiqiane35fdd92008-12-10 05:08:54 +000095using testing::DoubleEq;
zhanyong.wan616180e2013-06-18 18:49:51 +000096using testing::DoubleNear;
shiqiane35fdd92008-12-10 05:08:54 +000097using testing::EndsWith;
98using testing::Eq;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000099using testing::ExplainMatchResult;
shiqiane35fdd92008-12-10 05:08:54 +0000100using testing::Field;
101using testing::FloatEq;
zhanyong.wan616180e2013-06-18 18:49:51 +0000102using testing::FloatNear;
shiqiane35fdd92008-12-10 05:08:54 +0000103using testing::Ge;
104using testing::Gt;
105using testing::HasSubstr;
zhanyong.wan320814a2013-03-01 00:20:30 +0000106using testing::IsEmpty;
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000107using testing::IsNull;
zhanyong.wanb5937da2009-07-16 20:26:41 +0000108using testing::Key;
shiqiane35fdd92008-12-10 05:08:54 +0000109using testing::Le;
110using testing::Lt;
111using testing::MakeMatcher;
112using testing::MakePolymorphicMatcher;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000113using testing::MatchResultListener;
shiqiane35fdd92008-12-10 05:08:54 +0000114using testing::Matcher;
115using testing::MatcherCast;
116using testing::MatcherInterface;
117using testing::Matches;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000118using testing::MatchesRegex;
shiqiane35fdd92008-12-10 05:08:54 +0000119using testing::NanSensitiveDoubleEq;
zhanyong.wan616180e2013-06-18 18:49:51 +0000120using testing::NanSensitiveDoubleNear;
shiqiane35fdd92008-12-10 05:08:54 +0000121using testing::NanSensitiveFloatEq;
zhanyong.wan616180e2013-06-18 18:49:51 +0000122using testing::NanSensitiveFloatNear;
shiqiane35fdd92008-12-10 05:08:54 +0000123using testing::Ne;
124using testing::Not;
125using testing::NotNull;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000126using testing::Pair;
shiqiane35fdd92008-12-10 05:08:54 +0000127using testing::Pointee;
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000128using testing::Pointwise;
shiqiane35fdd92008-12-10 05:08:54 +0000129using testing::PolymorphicMatcher;
130using testing::Property;
131using testing::Ref;
132using testing::ResultOf;
zhanyong.wana31d9ce2013-03-01 01:50:17 +0000133using testing::SizeIs;
shiqiane35fdd92008-12-10 05:08:54 +0000134using testing::StartsWith;
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000135using testing::StringMatchResultListener;
shiqiane35fdd92008-12-10 05:08:54 +0000136using testing::StrCaseEq;
137using testing::StrCaseNe;
138using testing::StrEq;
139using testing::StrNe;
140using testing::Truly;
141using testing::TypedEq;
zhanyong.wanb8243162009-06-04 05:48:20 +0000142using testing::Value;
zhanyong.wan898725c2011-09-16 16:45:39 +0000143using testing::WhenSorted;
144using testing::WhenSortedBy;
shiqiane35fdd92008-12-10 05:08:54 +0000145using testing::_;
zhanyong.wana862f1d2010-03-15 21:23:04 +0000146using testing::internal::DummyMatchResultListener;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000147using testing::internal::ElementMatcherPair;
148using testing::internal::ElementMatcherPairs;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000149using testing::internal::ExplainMatchFailureTupleTo;
shiqiane35fdd92008-12-10 05:08:54 +0000150using testing::internal::FloatingEqMatcher;
zhanyong.wanb4140802010-06-08 22:53:57 +0000151using testing::internal::FormatMatcherDescription;
zhanyong.wan736baa82010-09-27 17:44:16 +0000152using testing::internal::IsReadableTypeName;
zhanyong.wan4a5330d2009-02-19 00:36:44 +0000153using testing::internal::JoinAsTuple;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000154using testing::internal::MatchMatrix;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000155using testing::internal::RE;
zhanyong.wana862f1d2010-03-15 21:23:04 +0000156using testing::internal::StreamMatchResultListener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000157using testing::internal::Strings;
vladlosev79b83502009-11-18 00:43:37 +0000158using testing::internal::linked_ptr;
vladloseve56daa72009-11-18 01:08:08 +0000159using testing::internal::scoped_ptr;
shiqiane35fdd92008-12-10 05:08:54 +0000160using testing::internal::string;
161
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000162// For testing ExplainMatchResultTo().
163class GreaterThanMatcher : public MatcherInterface<int> {
164 public:
165 explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
166
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000167 virtual void DescribeTo(ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000168 *os << "is > " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000169 }
170
zhanyong.wandb22c222010-01-28 21:52:29 +0000171 virtual bool MatchAndExplain(int lhs,
172 MatchResultListener* listener) const {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000173 const int diff = lhs - rhs_;
174 if (diff > 0) {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000175 *listener << "which is " << diff << " more than " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000176 } else if (diff == 0) {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000177 *listener << "which is the same as " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000178 } else {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000179 *listener << "which is " << -diff << " less than " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000180 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000181
182 return lhs > rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000183 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000184
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000185 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000186 int rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000187};
188
189Matcher<int> GreaterThan(int n) {
190 return MakeMatcher(new GreaterThanMatcher(n));
191}
192
zhanyong.wan736baa82010-09-27 17:44:16 +0000193string OfType(const string& type_name) {
194#if GTEST_HAS_RTTI
195 return " (of type " + type_name + ")";
196#else
197 return "";
198#endif
199}
200
shiqiane35fdd92008-12-10 05:08:54 +0000201// Returns the description of the given matcher.
202template <typename T>
203string Describe(const Matcher<T>& m) {
204 stringstream ss;
205 m.DescribeTo(&ss);
206 return ss.str();
207}
208
209// Returns the description of the negation of the given matcher.
210template <typename T>
211string DescribeNegation(const Matcher<T>& m) {
212 stringstream ss;
213 m.DescribeNegationTo(&ss);
214 return ss.str();
215}
216
217// Returns the reason why x matches, or doesn't match, m.
218template <typename MatcherType, typename Value>
219string Explain(const MatcherType& m, const Value& x) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000220 StringMatchResultListener listener;
221 ExplainMatchResult(m, x, &listener);
222 return listener.str();
shiqiane35fdd92008-12-10 05:08:54 +0000223}
224
zhanyong.wana862f1d2010-03-15 21:23:04 +0000225TEST(MatchResultListenerTest, StreamingWorks) {
226 StringMatchResultListener listener;
227 listener << "hi" << 5;
228 EXPECT_EQ("hi5", listener.str());
229
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000230 listener.Clear();
231 EXPECT_EQ("", listener.str());
232
233 listener << 42;
234 EXPECT_EQ("42", listener.str());
235
zhanyong.wana862f1d2010-03-15 21:23:04 +0000236 // Streaming shouldn't crash when the underlying ostream is NULL.
237 DummyMatchResultListener dummy;
238 dummy << "hi" << 5;
239}
240
241TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
242 EXPECT_TRUE(DummyMatchResultListener().stream() == NULL);
243 EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL);
244
245 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
246}
247
248TEST(MatchResultListenerTest, IsInterestedWorks) {
249 EXPECT_TRUE(StringMatchResultListener().IsInterested());
250 EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
251
252 EXPECT_FALSE(DummyMatchResultListener().IsInterested());
253 EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested());
254}
255
shiqiane35fdd92008-12-10 05:08:54 +0000256// Makes sure that the MatcherInterface<T> interface doesn't
257// change.
258class EvenMatcherImpl : public MatcherInterface<int> {
259 public:
zhanyong.wandb22c222010-01-28 21:52:29 +0000260 virtual bool MatchAndExplain(int x,
261 MatchResultListener* /* listener */) const {
262 return x % 2 == 0;
263 }
shiqiane35fdd92008-12-10 05:08:54 +0000264
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000265 virtual void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +0000266 *os << "is an even number";
267 }
268
269 // We deliberately don't define DescribeNegationTo() and
270 // ExplainMatchResultTo() here, to make sure the definition of these
271 // two methods is optional.
272};
273
zhanyong.wana862f1d2010-03-15 21:23:04 +0000274// Makes sure that the MatcherInterface API doesn't change.
275TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
shiqiane35fdd92008-12-10 05:08:54 +0000276 EvenMatcherImpl m;
277}
278
zhanyong.wan82113312010-01-08 21:55:40 +0000279// Tests implementing a monomorphic matcher using MatchAndExplain().
280
281class NewEvenMatcherImpl : public MatcherInterface<int> {
282 public:
283 virtual bool MatchAndExplain(int x, MatchResultListener* listener) const {
284 const bool match = x % 2 == 0;
285 // Verifies that we can stream to a listener directly.
286 *listener << "value % " << 2;
287 if (listener->stream() != NULL) {
288 // Verifies that we can stream to a listener's underlying stream
289 // too.
290 *listener->stream() << " == " << (x % 2);
291 }
292 return match;
293 }
294
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000295 virtual void DescribeTo(ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000296 *os << "is an even number";
297 }
298};
299
300TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
301 Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
302 EXPECT_TRUE(m.Matches(2));
303 EXPECT_FALSE(m.Matches(3));
304 EXPECT_EQ("value % 2 == 0", Explain(m, 2));
305 EXPECT_EQ("value % 2 == 1", Explain(m, 3));
306}
307
shiqiane35fdd92008-12-10 05:08:54 +0000308// Tests default-constructing a matcher.
309TEST(MatcherTest, CanBeDefaultConstructed) {
310 Matcher<double> m;
311}
312
313// Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
314TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
315 const MatcherInterface<int>* impl = new EvenMatcherImpl;
316 Matcher<int> m(impl);
317 EXPECT_TRUE(m.Matches(4));
318 EXPECT_FALSE(m.Matches(5));
319}
320
321// Tests that value can be used in place of Eq(value).
322TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
323 Matcher<int> m1 = 5;
324 EXPECT_TRUE(m1.Matches(5));
325 EXPECT_FALSE(m1.Matches(6));
326}
327
328// Tests that NULL can be used in place of Eq(NULL).
329TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
330 Matcher<int*> m1 = NULL;
331 EXPECT_TRUE(m1.Matches(NULL));
332 int n = 0;
333 EXPECT_FALSE(m1.Matches(&n));
334}
335
336// Tests that matchers are copyable.
337TEST(MatcherTest, IsCopyable) {
338 // Tests the copy constructor.
339 Matcher<bool> m1 = Eq(false);
340 EXPECT_TRUE(m1.Matches(false));
341 EXPECT_FALSE(m1.Matches(true));
342
343 // Tests the assignment operator.
344 m1 = Eq(true);
345 EXPECT_TRUE(m1.Matches(true));
346 EXPECT_FALSE(m1.Matches(false));
347}
348
349// Tests that Matcher<T>::DescribeTo() calls
350// MatcherInterface<T>::DescribeTo().
351TEST(MatcherTest, CanDescribeItself) {
352 EXPECT_EQ("is an even number",
353 Describe(Matcher<int>(new EvenMatcherImpl)));
354}
355
zhanyong.wan82113312010-01-08 21:55:40 +0000356// Tests Matcher<T>::MatchAndExplain().
357TEST(MatcherTest, MatchAndExplain) {
358 Matcher<int> m = GreaterThan(0);
zhanyong.wan34b034c2010-03-05 21:23:23 +0000359 StringMatchResultListener listener1;
zhanyong.wan82113312010-01-08 21:55:40 +0000360 EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000361 EXPECT_EQ("which is 42 more than 0", listener1.str());
zhanyong.wan82113312010-01-08 21:55:40 +0000362
zhanyong.wan34b034c2010-03-05 21:23:23 +0000363 StringMatchResultListener listener2;
zhanyong.wan82113312010-01-08 21:55:40 +0000364 EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000365 EXPECT_EQ("which is 9 less than 0", listener2.str());
zhanyong.wan82113312010-01-08 21:55:40 +0000366}
367
shiqiane35fdd92008-12-10 05:08:54 +0000368// Tests that a C-string literal can be implicitly converted to a
369// Matcher<string> or Matcher<const string&>.
370TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
371 Matcher<string> m1 = "hi";
372 EXPECT_TRUE(m1.Matches("hi"));
373 EXPECT_FALSE(m1.Matches("hello"));
374
375 Matcher<const string&> m2 = "hi";
376 EXPECT_TRUE(m2.Matches("hi"));
377 EXPECT_FALSE(m2.Matches("hello"));
378}
379
380// Tests that a string object can be implicitly converted to a
381// Matcher<string> or Matcher<const string&>.
382TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
383 Matcher<string> m1 = string("hi");
384 EXPECT_TRUE(m1.Matches("hi"));
385 EXPECT_FALSE(m1.Matches("hello"));
386
387 Matcher<const string&> m2 = string("hi");
388 EXPECT_TRUE(m2.Matches("hi"));
389 EXPECT_FALSE(m2.Matches("hello"));
390}
391
zhanyong.wan1f122a02013-03-25 16:27:03 +0000392#if GTEST_HAS_STRING_PIECE_
393// Tests that a C-string literal can be implicitly converted to a
394// Matcher<StringPiece> or Matcher<const StringPiece&>.
395TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
396 Matcher<StringPiece> m1 = "cats";
397 EXPECT_TRUE(m1.Matches("cats"));
398 EXPECT_FALSE(m1.Matches("dogs"));
399
400 Matcher<const StringPiece&> m2 = "cats";
401 EXPECT_TRUE(m2.Matches("cats"));
402 EXPECT_FALSE(m2.Matches("dogs"));
403}
404
405// Tests that a string object can be implicitly converted to a
406// Matcher<StringPiece> or Matcher<const StringPiece&>.
407TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromString) {
408 Matcher<StringPiece> m1 = string("cats");
409 EXPECT_TRUE(m1.Matches("cats"));
410 EXPECT_FALSE(m1.Matches("dogs"));
411
412 Matcher<const StringPiece&> m2 = string("cats");
413 EXPECT_TRUE(m2.Matches("cats"));
414 EXPECT_FALSE(m2.Matches("dogs"));
415}
416
417// Tests that a StringPiece object can be implicitly converted to a
418// Matcher<StringPiece> or Matcher<const StringPiece&>.
419TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromStringPiece) {
420 Matcher<StringPiece> m1 = StringPiece("cats");
421 EXPECT_TRUE(m1.Matches("cats"));
422 EXPECT_FALSE(m1.Matches("dogs"));
423
424 Matcher<const StringPiece&> m2 = StringPiece("cats");
425 EXPECT_TRUE(m2.Matches("cats"));
426 EXPECT_FALSE(m2.Matches("dogs"));
427}
428#endif // GTEST_HAS_STRING_PIECE_
429
shiqiane35fdd92008-12-10 05:08:54 +0000430// Tests that MakeMatcher() constructs a Matcher<T> from a
431// MatcherInterface* without requiring the user to explicitly
432// write the type.
433TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
434 const MatcherInterface<int>* dummy_impl = NULL;
435 Matcher<int> m = MakeMatcher(dummy_impl);
436}
437
zhanyong.wan82113312010-01-08 21:55:40 +0000438// Tests that MakePolymorphicMatcher() can construct a polymorphic
439// matcher from its implementation using the old API.
zhanyong.wan33605ba2010-04-22 23:37:47 +0000440const int g_bar = 1;
shiqiane35fdd92008-12-10 05:08:54 +0000441class ReferencesBarOrIsZeroImpl {
442 public:
443 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +0000444 bool MatchAndExplain(const T& x,
445 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000446 const void* p = &x;
zhanyong.wan33605ba2010-04-22 23:37:47 +0000447 return p == &g_bar || x == 0;
shiqiane35fdd92008-12-10 05:08:54 +0000448 }
449
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000450 void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
shiqiane35fdd92008-12-10 05:08:54 +0000451
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000452 void DescribeNegationTo(ostream* os) const {
zhanyong.wan33605ba2010-04-22 23:37:47 +0000453 *os << "doesn't reference g_bar and is not zero";
shiqiane35fdd92008-12-10 05:08:54 +0000454 }
455};
456
457// This function verifies that MakePolymorphicMatcher() returns a
458// PolymorphicMatcher<T> where T is the argument's type.
459PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
460 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
461}
462
zhanyong.wan82113312010-01-08 21:55:40 +0000463TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
shiqiane35fdd92008-12-10 05:08:54 +0000464 // Using a polymorphic matcher to match a reference type.
465 Matcher<const int&> m1 = ReferencesBarOrIsZero();
466 EXPECT_TRUE(m1.Matches(0));
467 // Verifies that the identity of a by-reference argument is preserved.
zhanyong.wan33605ba2010-04-22 23:37:47 +0000468 EXPECT_TRUE(m1.Matches(g_bar));
shiqiane35fdd92008-12-10 05:08:54 +0000469 EXPECT_FALSE(m1.Matches(1));
zhanyong.wan33605ba2010-04-22 23:37:47 +0000470 EXPECT_EQ("g_bar or zero", Describe(m1));
shiqiane35fdd92008-12-10 05:08:54 +0000471
472 // Using a polymorphic matcher to match a value type.
473 Matcher<double> m2 = ReferencesBarOrIsZero();
474 EXPECT_TRUE(m2.Matches(0.0));
475 EXPECT_FALSE(m2.Matches(0.1));
zhanyong.wan33605ba2010-04-22 23:37:47 +0000476 EXPECT_EQ("g_bar or zero", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +0000477}
478
zhanyong.wan82113312010-01-08 21:55:40 +0000479// Tests implementing a polymorphic matcher using MatchAndExplain().
480
481class PolymorphicIsEvenImpl {
482 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000483 void DescribeTo(ostream* os) const { *os << "is even"; }
zhanyong.wan82113312010-01-08 21:55:40 +0000484
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000485 void DescribeNegationTo(ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000486 *os << "is odd";
487 }
zhanyong.wan82113312010-01-08 21:55:40 +0000488
zhanyong.wandb22c222010-01-28 21:52:29 +0000489 template <typename T>
490 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
491 // Verifies that we can stream to the listener directly.
492 *listener << "% " << 2;
493 if (listener->stream() != NULL) {
494 // Verifies that we can stream to the listener's underlying stream
495 // too.
496 *listener->stream() << " == " << (x % 2);
497 }
498 return (x % 2) == 0;
zhanyong.wan82113312010-01-08 21:55:40 +0000499 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000500};
zhanyong.wan82113312010-01-08 21:55:40 +0000501
502PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
503 return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
504}
505
506TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
507 // Using PolymorphicIsEven() as a Matcher<int>.
508 const Matcher<int> m1 = PolymorphicIsEven();
509 EXPECT_TRUE(m1.Matches(42));
510 EXPECT_FALSE(m1.Matches(43));
511 EXPECT_EQ("is even", Describe(m1));
512
513 const Matcher<int> not_m1 = Not(m1);
514 EXPECT_EQ("is odd", Describe(not_m1));
515
516 EXPECT_EQ("% 2 == 0", Explain(m1, 42));
517
518 // Using PolymorphicIsEven() as a Matcher<char>.
519 const Matcher<char> m2 = PolymorphicIsEven();
520 EXPECT_TRUE(m2.Matches('\x42'));
521 EXPECT_FALSE(m2.Matches('\x43'));
522 EXPECT_EQ("is even", Describe(m2));
523
524 const Matcher<char> not_m2 = Not(m2);
525 EXPECT_EQ("is odd", Describe(not_m2));
526
527 EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
528}
529
shiqiane35fdd92008-12-10 05:08:54 +0000530// Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
531TEST(MatcherCastTest, FromPolymorphicMatcher) {
532 Matcher<int> m = MatcherCast<int>(Eq(5));
533 EXPECT_TRUE(m.Matches(5));
534 EXPECT_FALSE(m.Matches(6));
535}
536
537// For testing casting matchers between compatible types.
538class IntValue {
539 public:
540 // An int can be statically (although not implicitly) cast to a
541 // IntValue.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000542 explicit IntValue(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +0000543
544 int value() const { return value_; }
545 private:
546 int value_;
547};
548
549// For testing casting matchers between compatible types.
550bool IsPositiveIntValue(const IntValue& foo) {
551 return foo.value() > 0;
552}
553
554// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
555// can be statically converted to U.
556TEST(MatcherCastTest, FromCompatibleType) {
557 Matcher<double> m1 = Eq(2.0);
558 Matcher<int> m2 = MatcherCast<int>(m1);
559 EXPECT_TRUE(m2.Matches(2));
560 EXPECT_FALSE(m2.Matches(3));
561
562 Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
563 Matcher<int> m4 = MatcherCast<int>(m3);
564 // In the following, the arguments 1 and 0 are statically converted
565 // to IntValue objects, and then tested by the IsPositiveIntValue()
566 // predicate.
567 EXPECT_TRUE(m4.Matches(1));
568 EXPECT_FALSE(m4.Matches(0));
569}
570
571// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
572TEST(MatcherCastTest, FromConstReferenceToNonReference) {
573 Matcher<const int&> m1 = Eq(0);
574 Matcher<int> m2 = MatcherCast<int>(m1);
575 EXPECT_TRUE(m2.Matches(0));
576 EXPECT_FALSE(m2.Matches(1));
577}
578
579// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
580TEST(MatcherCastTest, FromReferenceToNonReference) {
581 Matcher<int&> m1 = Eq(0);
582 Matcher<int> m2 = MatcherCast<int>(m1);
583 EXPECT_TRUE(m2.Matches(0));
584 EXPECT_FALSE(m2.Matches(1));
585}
586
587// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
588TEST(MatcherCastTest, FromNonReferenceToConstReference) {
589 Matcher<int> m1 = Eq(0);
590 Matcher<const int&> m2 = MatcherCast<const int&>(m1);
591 EXPECT_TRUE(m2.Matches(0));
592 EXPECT_FALSE(m2.Matches(1));
593}
594
595// Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
596TEST(MatcherCastTest, FromNonReferenceToReference) {
597 Matcher<int> m1 = Eq(0);
598 Matcher<int&> m2 = MatcherCast<int&>(m1);
599 int n = 0;
600 EXPECT_TRUE(m2.Matches(n));
601 n = 1;
602 EXPECT_FALSE(m2.Matches(n));
603}
604
605// Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
606TEST(MatcherCastTest, FromSameType) {
607 Matcher<int> m1 = Eq(0);
608 Matcher<int> m2 = MatcherCast<int>(m1);
609 EXPECT_TRUE(m2.Matches(0));
610 EXPECT_FALSE(m2.Matches(1));
611}
612
jgm79a367e2012-04-10 16:02:11 +0000613// Implicitly convertible form any type.
614struct ConvertibleFromAny {
615 ConvertibleFromAny(int a_value) : value(a_value) {}
616 template <typename T>
617 ConvertibleFromAny(const T& a_value) : value(-1) {
618 ADD_FAILURE() << "Conversion constructor called";
619 }
620 int value;
621};
622
623bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
624 return a.value == b.value;
625}
626
627ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
628 return os << a.value;
629}
630
631TEST(MatcherCastTest, ConversionConstructorIsUsed) {
632 Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
633 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
634 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
635}
636
637TEST(MatcherCastTest, FromConvertibleFromAny) {
638 Matcher<ConvertibleFromAny> m =
639 MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
640 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
641 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
642}
643
kosak5f2a6ca2013-12-03 01:43:07 +0000644struct IntReferenceWrapper {
645 IntReferenceWrapper(const int& a_value) : value(&a_value) {}
646 const int* value;
647};
648
649bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
650 return a.value == b.value;
651}
652
653TEST(MatcherCastTest, ValueIsNotCopied) {
654 int n = 42;
655 Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
656 // Verify that the matcher holds a reference to n, not to its temporary copy.
657 EXPECT_TRUE(m.Matches(n));
658}
659
zhanyong.wan18490652009-05-11 18:54:08 +0000660class Base {};
661class Derived : public Base {};
662
663// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
664TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
665 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
666 EXPECT_TRUE(m2.Matches(' '));
667 EXPECT_FALSE(m2.Matches('\n'));
668}
669
zhanyong.wan16cf4732009-05-14 20:55:30 +0000670// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
671// T and U are arithmetic types and T can be losslessly converted to
672// U.
673TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
zhanyong.wan18490652009-05-11 18:54:08 +0000674 Matcher<double> m1 = DoubleEq(1.0);
zhanyong.wan16cf4732009-05-14 20:55:30 +0000675 Matcher<float> m2 = SafeMatcherCast<float>(m1);
676 EXPECT_TRUE(m2.Matches(1.0f));
677 EXPECT_FALSE(m2.Matches(2.0f));
678
679 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
680 EXPECT_TRUE(m3.Matches('a'));
681 EXPECT_FALSE(m3.Matches('b'));
zhanyong.wan18490652009-05-11 18:54:08 +0000682}
683
684// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
685// are pointers or references to a derived and a base class, correspondingly.
686TEST(SafeMatcherCastTest, FromBaseClass) {
687 Derived d, d2;
688 Matcher<Base*> m1 = Eq(&d);
689 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
690 EXPECT_TRUE(m2.Matches(&d));
691 EXPECT_FALSE(m2.Matches(&d2));
692
693 Matcher<Base&> m3 = Ref(d);
694 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
695 EXPECT_TRUE(m4.Matches(d));
696 EXPECT_FALSE(m4.Matches(d2));
697}
698
699// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
700TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
701 int n = 0;
702 Matcher<const int&> m1 = Ref(n);
703 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
704 int n1 = 0;
705 EXPECT_TRUE(m2.Matches(n));
706 EXPECT_FALSE(m2.Matches(n1));
707}
708
709// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
710TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
711 Matcher<int> m1 = Eq(0);
712 Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
713 EXPECT_TRUE(m2.Matches(0));
714 EXPECT_FALSE(m2.Matches(1));
715}
716
717// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
718TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
719 Matcher<int> m1 = Eq(0);
720 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
721 int n = 0;
722 EXPECT_TRUE(m2.Matches(n));
723 n = 1;
724 EXPECT_FALSE(m2.Matches(n));
725}
726
727// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
728TEST(SafeMatcherCastTest, FromSameType) {
729 Matcher<int> m1 = Eq(0);
730 Matcher<int> m2 = SafeMatcherCast<int>(m1);
731 EXPECT_TRUE(m2.Matches(0));
732 EXPECT_FALSE(m2.Matches(1));
733}
734
jgm79a367e2012-04-10 16:02:11 +0000735TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
736 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
737 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
738 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
739}
740
741TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
742 Matcher<ConvertibleFromAny> m =
743 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
744 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
745 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
746}
747
kosak5f2a6ca2013-12-03 01:43:07 +0000748TEST(SafeMatcherCastTest, ValueIsNotCopied) {
749 int n = 42;
750 Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
751 // Verify that the matcher holds a reference to n, not to its temporary copy.
752 EXPECT_TRUE(m.Matches(n));
753}
754
shiqiane35fdd92008-12-10 05:08:54 +0000755// Tests that A<T>() matches any value of type T.
756TEST(ATest, MatchesAnyValue) {
757 // Tests a matcher for a value type.
758 Matcher<double> m1 = A<double>();
759 EXPECT_TRUE(m1.Matches(91.43));
760 EXPECT_TRUE(m1.Matches(-15.32));
761
762 // Tests a matcher for a reference type.
763 int a = 2;
764 int b = -6;
765 Matcher<int&> m2 = A<int&>();
766 EXPECT_TRUE(m2.Matches(a));
767 EXPECT_TRUE(m2.Matches(b));
768}
769
zhanyong.wanf4274522013-04-24 02:49:43 +0000770TEST(ATest, WorksForDerivedClass) {
771 Base base;
772 Derived derived;
773 EXPECT_THAT(&base, A<Base*>());
774 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
775 EXPECT_THAT(&derived, A<Base*>());
776 EXPECT_THAT(&derived, A<Derived*>());
777}
778
shiqiane35fdd92008-12-10 05:08:54 +0000779// Tests that A<T>() describes itself properly.
780TEST(ATest, CanDescribeSelf) {
781 EXPECT_EQ("is anything", Describe(A<bool>()));
782}
783
784// Tests that An<T>() matches any value of type T.
785TEST(AnTest, MatchesAnyValue) {
786 // Tests a matcher for a value type.
787 Matcher<int> m1 = An<int>();
788 EXPECT_TRUE(m1.Matches(9143));
789 EXPECT_TRUE(m1.Matches(-1532));
790
791 // Tests a matcher for a reference type.
792 int a = 2;
793 int b = -6;
794 Matcher<int&> m2 = An<int&>();
795 EXPECT_TRUE(m2.Matches(a));
796 EXPECT_TRUE(m2.Matches(b));
797}
798
799// Tests that An<T>() describes itself properly.
800TEST(AnTest, CanDescribeSelf) {
801 EXPECT_EQ("is anything", Describe(An<int>()));
802}
803
804// Tests that _ can be used as a matcher for any type and matches any
805// value of that type.
806TEST(UnderscoreTest, MatchesAnyValue) {
807 // Uses _ as a matcher for a value type.
808 Matcher<int> m1 = _;
809 EXPECT_TRUE(m1.Matches(123));
810 EXPECT_TRUE(m1.Matches(-242));
811
812 // Uses _ as a matcher for a reference type.
813 bool a = false;
814 const bool b = true;
815 Matcher<const bool&> m2 = _;
816 EXPECT_TRUE(m2.Matches(a));
817 EXPECT_TRUE(m2.Matches(b));
818}
819
820// Tests that _ describes itself properly.
821TEST(UnderscoreTest, CanDescribeSelf) {
822 Matcher<int> m = _;
823 EXPECT_EQ("is anything", Describe(m));
824}
825
826// Tests that Eq(x) matches any value equal to x.
827TEST(EqTest, MatchesEqualValue) {
828 // 2 C-strings with same content but different addresses.
829 const char a1[] = "hi";
830 const char a2[] = "hi";
831
832 Matcher<const char*> m1 = Eq(a1);
833 EXPECT_TRUE(m1.Matches(a1));
834 EXPECT_FALSE(m1.Matches(a2));
835}
836
837// Tests that Eq(v) describes itself properly.
838
839class Unprintable {
840 public:
841 Unprintable() : c_('a') {}
842
zhanyong.wan32de5f52009-12-23 00:13:23 +0000843 bool operator==(const Unprintable& /* rhs */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000844 private:
845 char c_;
846};
847
848TEST(EqTest, CanDescribeSelf) {
849 Matcher<Unprintable> m = Eq(Unprintable());
850 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
851}
852
853// Tests that Eq(v) can be used to match any type that supports
854// comparing with type T, where T is v's type.
855TEST(EqTest, IsPolymorphic) {
856 Matcher<int> m1 = Eq(1);
857 EXPECT_TRUE(m1.Matches(1));
858 EXPECT_FALSE(m1.Matches(2));
859
860 Matcher<char> m2 = Eq(1);
861 EXPECT_TRUE(m2.Matches('\1'));
862 EXPECT_FALSE(m2.Matches('a'));
863}
864
865// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
866TEST(TypedEqTest, ChecksEqualityForGivenType) {
867 Matcher<char> m1 = TypedEq<char>('a');
868 EXPECT_TRUE(m1.Matches('a'));
869 EXPECT_FALSE(m1.Matches('b'));
870
871 Matcher<int> m2 = TypedEq<int>(6);
872 EXPECT_TRUE(m2.Matches(6));
873 EXPECT_FALSE(m2.Matches(7));
874}
875
876// Tests that TypedEq(v) describes itself properly.
877TEST(TypedEqTest, CanDescribeSelf) {
878 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
879}
880
881// Tests that TypedEq<T>(v) has type Matcher<T>.
882
883// Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
884// is a "bare" type (i.e. not in the form of const U or U&). If v's
885// type is not T, the compiler will generate a message about
886// "undefined referece".
887template <typename T>
888struct Type {
zhanyong.wan32de5f52009-12-23 00:13:23 +0000889 static bool IsTypeOf(const T& /* v */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000890
891 template <typename T2>
892 static void IsTypeOf(T2 v);
893};
894
895TEST(TypedEqTest, HasSpecifiedType) {
896 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
897 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
898 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
899}
900
901// Tests that Ge(v) matches anything >= v.
902TEST(GeTest, ImplementsGreaterThanOrEqual) {
903 Matcher<int> m1 = Ge(0);
904 EXPECT_TRUE(m1.Matches(1));
905 EXPECT_TRUE(m1.Matches(0));
906 EXPECT_FALSE(m1.Matches(-1));
907}
908
909// Tests that Ge(v) describes itself properly.
910TEST(GeTest, CanDescribeSelf) {
911 Matcher<int> m = Ge(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000912 EXPECT_EQ("is >= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000913}
914
915// Tests that Gt(v) matches anything > v.
916TEST(GtTest, ImplementsGreaterThan) {
917 Matcher<double> m1 = Gt(0);
918 EXPECT_TRUE(m1.Matches(1.0));
919 EXPECT_FALSE(m1.Matches(0.0));
920 EXPECT_FALSE(m1.Matches(-1.0));
921}
922
923// Tests that Gt(v) describes itself properly.
924TEST(GtTest, CanDescribeSelf) {
925 Matcher<int> m = Gt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000926 EXPECT_EQ("is > 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000927}
928
929// Tests that Le(v) matches anything <= v.
930TEST(LeTest, ImplementsLessThanOrEqual) {
931 Matcher<char> m1 = Le('b');
932 EXPECT_TRUE(m1.Matches('a'));
933 EXPECT_TRUE(m1.Matches('b'));
934 EXPECT_FALSE(m1.Matches('c'));
935}
936
937// Tests that Le(v) describes itself properly.
938TEST(LeTest, CanDescribeSelf) {
939 Matcher<int> m = Le(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000940 EXPECT_EQ("is <= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000941}
942
943// Tests that Lt(v) matches anything < v.
944TEST(LtTest, ImplementsLessThan) {
945 Matcher<const string&> m1 = Lt("Hello");
946 EXPECT_TRUE(m1.Matches("Abc"));
947 EXPECT_FALSE(m1.Matches("Hello"));
948 EXPECT_FALSE(m1.Matches("Hello, world!"));
949}
950
951// Tests that Lt(v) describes itself properly.
952TEST(LtTest, CanDescribeSelf) {
953 Matcher<int> m = Lt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000954 EXPECT_EQ("is < 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000955}
956
957// Tests that Ne(v) matches anything != v.
958TEST(NeTest, ImplementsNotEqual) {
959 Matcher<int> m1 = Ne(0);
960 EXPECT_TRUE(m1.Matches(1));
961 EXPECT_TRUE(m1.Matches(-1));
962 EXPECT_FALSE(m1.Matches(0));
963}
964
965// Tests that Ne(v) describes itself properly.
966TEST(NeTest, CanDescribeSelf) {
967 Matcher<int> m = Ne(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000968 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000969}
970
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000971// Tests that IsNull() matches any NULL pointer of any type.
972TEST(IsNullTest, MatchesNullPointer) {
973 Matcher<int*> m1 = IsNull();
974 int* p1 = NULL;
975 int n = 0;
976 EXPECT_TRUE(m1.Matches(p1));
977 EXPECT_FALSE(m1.Matches(&n));
978
979 Matcher<const char*> m2 = IsNull();
980 const char* p2 = NULL;
981 EXPECT_TRUE(m2.Matches(p2));
982 EXPECT_FALSE(m2.Matches("hi"));
983
zhanyong.wan95b12332009-09-25 18:55:50 +0000984#if !GTEST_OS_SYMBIAN
985 // Nokia's Symbian compiler generates:
986 // gmock-matchers.h: ambiguous access to overloaded function
987 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
988 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
989 // MatcherInterface<void *> *)'
990 // gmock-matchers.h: (point of instantiation: 'testing::
991 // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
992 // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000993 Matcher<void*> m3 = IsNull();
994 void* p3 = NULL;
995 EXPECT_TRUE(m3.Matches(p3));
996 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
zhanyong.wan95b12332009-09-25 18:55:50 +0000997#endif
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000998}
999
vladlosev79b83502009-11-18 00:43:37 +00001000TEST(IsNullTest, LinkedPtr) {
1001 const Matcher<linked_ptr<int> > m = IsNull();
1002 const linked_ptr<int> null_p;
1003 const linked_ptr<int> non_null_p(new int);
1004
1005 EXPECT_TRUE(m.Matches(null_p));
1006 EXPECT_FALSE(m.Matches(non_null_p));
1007}
1008
1009TEST(IsNullTest, ReferenceToConstLinkedPtr) {
1010 const Matcher<const linked_ptr<double>&> m = IsNull();
1011 const linked_ptr<double> null_p;
1012 const linked_ptr<double> non_null_p(new double);
1013
1014 EXPECT_TRUE(m.Matches(null_p));
1015 EXPECT_FALSE(m.Matches(non_null_p));
1016}
1017
vladloseve56daa72009-11-18 01:08:08 +00001018TEST(IsNullTest, ReferenceToConstScopedPtr) {
1019 const Matcher<const scoped_ptr<double>&> m = IsNull();
1020 const scoped_ptr<double> null_p;
1021 const scoped_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
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001027// Tests that IsNull() describes itself properly.
1028TEST(IsNullTest, CanDescribeSelf) {
1029 Matcher<int*> m = IsNull();
1030 EXPECT_EQ("is NULL", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001031 EXPECT_EQ("isn't NULL", DescribeNegation(m));
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001032}
1033
shiqiane35fdd92008-12-10 05:08:54 +00001034// Tests that NotNull() matches any non-NULL pointer of any type.
1035TEST(NotNullTest, MatchesNonNullPointer) {
1036 Matcher<int*> m1 = NotNull();
1037 int* p1 = NULL;
1038 int n = 0;
1039 EXPECT_FALSE(m1.Matches(p1));
1040 EXPECT_TRUE(m1.Matches(&n));
1041
1042 Matcher<const char*> m2 = NotNull();
1043 const char* p2 = NULL;
1044 EXPECT_FALSE(m2.Matches(p2));
1045 EXPECT_TRUE(m2.Matches("hi"));
1046}
1047
vladlosev79b83502009-11-18 00:43:37 +00001048TEST(NotNullTest, LinkedPtr) {
1049 const Matcher<linked_ptr<int> > m = NotNull();
1050 const linked_ptr<int> null_p;
1051 const linked_ptr<int> non_null_p(new int);
1052
1053 EXPECT_FALSE(m.Matches(null_p));
1054 EXPECT_TRUE(m.Matches(non_null_p));
1055}
1056
1057TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1058 const Matcher<const linked_ptr<double>&> m = NotNull();
1059 const linked_ptr<double> null_p;
1060 const linked_ptr<double> non_null_p(new double);
1061
1062 EXPECT_FALSE(m.Matches(null_p));
1063 EXPECT_TRUE(m.Matches(non_null_p));
1064}
1065
vladloseve56daa72009-11-18 01:08:08 +00001066TEST(NotNullTest, ReferenceToConstScopedPtr) {
1067 const Matcher<const scoped_ptr<double>&> m = NotNull();
1068 const scoped_ptr<double> null_p;
1069 const scoped_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
shiqiane35fdd92008-12-10 05:08:54 +00001075// Tests that NotNull() describes itself properly.
1076TEST(NotNullTest, CanDescribeSelf) {
1077 Matcher<int*> m = NotNull();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001078 EXPECT_EQ("isn't NULL", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001079}
1080
1081// Tests that Ref(variable) matches an argument that references
1082// 'variable'.
1083TEST(RefTest, MatchesSameVariable) {
1084 int a = 0;
1085 int b = 0;
1086 Matcher<int&> m = Ref(a);
1087 EXPECT_TRUE(m.Matches(a));
1088 EXPECT_FALSE(m.Matches(b));
1089}
1090
1091// Tests that Ref(variable) describes itself properly.
1092TEST(RefTest, CanDescribeSelf) {
1093 int n = 5;
1094 Matcher<int&> m = Ref(n);
1095 stringstream ss;
1096 ss << "references the variable @" << &n << " 5";
1097 EXPECT_EQ(string(ss.str()), Describe(m));
1098}
1099
1100// Test that Ref(non_const_varialbe) can be used as a matcher for a
1101// const reference.
1102TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1103 int a = 0;
1104 int b = 0;
1105 Matcher<const int&> m = Ref(a);
1106 EXPECT_TRUE(m.Matches(a));
1107 EXPECT_FALSE(m.Matches(b));
1108}
1109
1110// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1111// used wherever Ref(base) can be used (Ref(derived) is a sub-type
1112// of Ref(base), but not vice versa.
1113
shiqiane35fdd92008-12-10 05:08:54 +00001114TEST(RefTest, IsCovariant) {
1115 Base base, base2;
1116 Derived derived;
1117 Matcher<const Base&> m1 = Ref(base);
1118 EXPECT_TRUE(m1.Matches(base));
1119 EXPECT_FALSE(m1.Matches(base2));
1120 EXPECT_FALSE(m1.Matches(derived));
1121
1122 m1 = Ref(derived);
1123 EXPECT_TRUE(m1.Matches(derived));
1124 EXPECT_FALSE(m1.Matches(base));
1125 EXPECT_FALSE(m1.Matches(base2));
1126}
1127
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001128TEST(RefTest, ExplainsResult) {
1129 int n = 0;
1130 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1131 StartsWith("which is located @"));
1132
1133 int m = 0;
1134 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1135 StartsWith("which is located @"));
1136}
1137
shiqiane35fdd92008-12-10 05:08:54 +00001138// Tests string comparison matchers.
1139
1140TEST(StrEqTest, MatchesEqualString) {
1141 Matcher<const char*> m = StrEq(string("Hello"));
1142 EXPECT_TRUE(m.Matches("Hello"));
1143 EXPECT_FALSE(m.Matches("hello"));
1144 EXPECT_FALSE(m.Matches(NULL));
1145
1146 Matcher<const string&> m2 = StrEq("Hello");
1147 EXPECT_TRUE(m2.Matches("Hello"));
1148 EXPECT_FALSE(m2.Matches("Hi"));
1149}
1150
1151TEST(StrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001152 Matcher<string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1153 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
shiqiane35fdd92008-12-10 05:08:54 +00001154 Describe(m));
1155
1156 string str("01204500800");
1157 str[3] = '\0';
1158 Matcher<string> m2 = StrEq(str);
1159 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1160 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1161 Matcher<string> m3 = StrEq(str);
1162 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1163}
1164
1165TEST(StrNeTest, MatchesUnequalString) {
1166 Matcher<const char*> m = StrNe("Hello");
1167 EXPECT_TRUE(m.Matches(""));
1168 EXPECT_TRUE(m.Matches(NULL));
1169 EXPECT_FALSE(m.Matches("Hello"));
1170
1171 Matcher<string> m2 = StrNe(string("Hello"));
1172 EXPECT_TRUE(m2.Matches("hello"));
1173 EXPECT_FALSE(m2.Matches("Hello"));
1174}
1175
1176TEST(StrNeTest, CanDescribeSelf) {
1177 Matcher<const char*> m = StrNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001178 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001179}
1180
1181TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1182 Matcher<const char*> m = StrCaseEq(string("Hello"));
1183 EXPECT_TRUE(m.Matches("Hello"));
1184 EXPECT_TRUE(m.Matches("hello"));
1185 EXPECT_FALSE(m.Matches("Hi"));
1186 EXPECT_FALSE(m.Matches(NULL));
1187
1188 Matcher<const string&> m2 = StrCaseEq("Hello");
1189 EXPECT_TRUE(m2.Matches("hello"));
1190 EXPECT_FALSE(m2.Matches("Hi"));
1191}
1192
1193TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1194 string str1("oabocdooeoo");
1195 string str2("OABOCDOOEOO");
1196 Matcher<const string&> m0 = StrCaseEq(str1);
1197 EXPECT_FALSE(m0.Matches(str2 + string(1, '\0')));
1198
1199 str1[3] = str2[3] = '\0';
1200 Matcher<const string&> m1 = StrCaseEq(str1);
1201 EXPECT_TRUE(m1.Matches(str2));
1202
1203 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1204 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1205 Matcher<const string&> m2 = StrCaseEq(str1);
1206 str1[9] = str2[9] = '\0';
1207 EXPECT_FALSE(m2.Matches(str2));
1208
1209 Matcher<const string&> m3 = StrCaseEq(str1);
1210 EXPECT_TRUE(m3.Matches(str2));
1211
1212 EXPECT_FALSE(m3.Matches(str2 + "x"));
1213 str2.append(1, '\0');
1214 EXPECT_FALSE(m3.Matches(str2));
1215 EXPECT_FALSE(m3.Matches(string(str2, 0, 9)));
1216}
1217
1218TEST(StrCaseEqTest, CanDescribeSelf) {
1219 Matcher<string> m = StrCaseEq("Hi");
1220 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1221}
1222
1223TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1224 Matcher<const char*> m = StrCaseNe("Hello");
1225 EXPECT_TRUE(m.Matches("Hi"));
1226 EXPECT_TRUE(m.Matches(NULL));
1227 EXPECT_FALSE(m.Matches("Hello"));
1228 EXPECT_FALSE(m.Matches("hello"));
1229
1230 Matcher<string> m2 = StrCaseNe(string("Hello"));
1231 EXPECT_TRUE(m2.Matches(""));
1232 EXPECT_FALSE(m2.Matches("Hello"));
1233}
1234
1235TEST(StrCaseNeTest, CanDescribeSelf) {
1236 Matcher<const char*> m = StrCaseNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001237 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001238}
1239
1240// Tests that HasSubstr() works for matching string-typed values.
1241TEST(HasSubstrTest, WorksForStringClasses) {
1242 const Matcher<string> m1 = HasSubstr("foo");
1243 EXPECT_TRUE(m1.Matches(string("I love food.")));
1244 EXPECT_FALSE(m1.Matches(string("tofo")));
1245
1246 const Matcher<const std::string&> m2 = HasSubstr("foo");
1247 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1248 EXPECT_FALSE(m2.Matches(std::string("tofo")));
1249}
1250
1251// Tests that HasSubstr() works for matching C-string-typed values.
1252TEST(HasSubstrTest, WorksForCStrings) {
1253 const Matcher<char*> m1 = HasSubstr("foo");
1254 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1255 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1256 EXPECT_FALSE(m1.Matches(NULL));
1257
1258 const Matcher<const char*> m2 = HasSubstr("foo");
1259 EXPECT_TRUE(m2.Matches("I love food."));
1260 EXPECT_FALSE(m2.Matches("tofo"));
1261 EXPECT_FALSE(m2.Matches(NULL));
1262}
1263
1264// Tests that HasSubstr(s) describes itself properly.
1265TEST(HasSubstrTest, CanDescribeSelf) {
1266 Matcher<string> m = HasSubstr("foo\n\"");
1267 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1268}
1269
zhanyong.wanb5937da2009-07-16 20:26:41 +00001270TEST(KeyTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001271 Matcher<const pair<std::string, int>&> m = Key("foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001272 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001273 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1274}
1275
1276TEST(KeyTest, ExplainsResult) {
1277 Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1278 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1279 Explain(m, make_pair(5, true)));
1280 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1281 Explain(m, make_pair(15, true)));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001282}
1283
1284TEST(KeyTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001285 pair<int, std::string> p(25, "foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001286 EXPECT_THAT(p, Key(25));
1287 EXPECT_THAT(p, Not(Key(42)));
1288 EXPECT_THAT(p, Key(Ge(20)));
1289 EXPECT_THAT(p, Not(Key(Lt(25))));
1290}
1291
1292TEST(KeyTest, SafelyCastsInnerMatcher) {
1293 Matcher<int> is_positive = Gt(0);
1294 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001295 pair<char, bool> p('a', true);
zhanyong.wanb5937da2009-07-16 20:26:41 +00001296 EXPECT_THAT(p, Key(is_positive));
1297 EXPECT_THAT(p, Not(Key(is_negative)));
1298}
1299
1300TEST(KeyTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001301 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001302 container.insert(make_pair(1, 'a'));
1303 container.insert(make_pair(2, 'b'));
1304 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001305 EXPECT_THAT(container, Contains(Key(1)));
1306 EXPECT_THAT(container, Not(Contains(Key(3))));
1307}
1308
1309TEST(KeyTest, InsideContainsUsingMultimap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001310 multimap<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
1315 EXPECT_THAT(container, Not(Contains(Key(25))));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001316 container.insert(make_pair(25, 'd'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001317 EXPECT_THAT(container, Contains(Key(25)));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001318 container.insert(make_pair(25, 'e'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001319 EXPECT_THAT(container, Contains(Key(25)));
1320
1321 EXPECT_THAT(container, Contains(Key(1)));
1322 EXPECT_THAT(container, Not(Contains(Key(3))));
1323}
1324
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001325TEST(PairTest, Typing) {
1326 // Test verifies the following type conversions can be compiled.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001327 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1328 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1329 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001330
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001331 Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1332 Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001333}
1334
1335TEST(PairTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001336 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001337 EXPECT_EQ("has a first field that is equal to \"foo\""
1338 ", and has a second field that is equal to 42",
1339 Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001340 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1341 ", or has a second field that isn't equal to 42",
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001342 DescribeNegation(m1));
1343 // Double and triple negation (1 or 2 times not and description of negation).
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001344 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1345 EXPECT_EQ("has a first field that isn't equal to 13"
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001346 ", and has a second field that is equal to 42",
1347 DescribeNegation(m2));
1348}
1349
1350TEST(PairTest, CanExplainMatchResultTo) {
zhanyong.wan82113312010-01-08 21:55:40 +00001351 // If neither field matches, Pair() should explain about the first
1352 // field.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001353 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001354 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001355 Explain(m, make_pair(-1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001356
zhanyong.wan82113312010-01-08 21:55:40 +00001357 // If the first field matches but the second doesn't, Pair() should
1358 // explain about the second field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001359 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001360 Explain(m, make_pair(1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001361
zhanyong.wan82113312010-01-08 21:55:40 +00001362 // If the first field doesn't match but the second does, Pair()
1363 // should explain about the first field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001364 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001365 Explain(m, make_pair(-1, 2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001366
zhanyong.wan82113312010-01-08 21:55:40 +00001367 // If both fields match, Pair() should explain about them both.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001368 EXPECT_EQ("whose both fields match, where the first field is a value "
1369 "which is 1 more than 0, and the second field is a value "
1370 "which is 2 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001371 Explain(m, make_pair(1, 2)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001372
1373 // If only the first match has an explanation, only this explanation should
1374 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001375 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001376 EXPECT_EQ("whose both fields match, where the first field is a value "
1377 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001378 Explain(explain_first, make_pair(1, 0)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001379
1380 // If only the second match has an explanation, only this explanation should
1381 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001382 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001383 EXPECT_EQ("whose both fields match, where the second field is a value "
1384 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001385 Explain(explain_second, make_pair(0, 1)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001386}
1387
1388TEST(PairTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001389 pair<int, std::string> p(25, "foo");
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001390
1391 // Both fields match.
1392 EXPECT_THAT(p, Pair(25, "foo"));
1393 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1394
1395 // 'first' doesnt' match, but 'second' matches.
1396 EXPECT_THAT(p, Not(Pair(42, "foo")));
1397 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1398
1399 // 'first' matches, but 'second' doesn't match.
1400 EXPECT_THAT(p, Not(Pair(25, "bar")));
1401 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1402
1403 // Neither field matches.
1404 EXPECT_THAT(p, Not(Pair(13, "bar")));
1405 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1406}
1407
1408TEST(PairTest, SafelyCastsInnerMatchers) {
1409 Matcher<int> is_positive = Gt(0);
1410 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001411 pair<char, bool> p('a', true);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001412 EXPECT_THAT(p, Pair(is_positive, _));
1413 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1414 EXPECT_THAT(p, Pair(_, is_positive));
1415 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1416}
1417
1418TEST(PairTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001419 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001420 container.insert(make_pair(1, 'a'));
1421 container.insert(make_pair(2, 'b'));
1422 container.insert(make_pair(4, 'c'));
zhanyong.wan95b12332009-09-25 18:55:50 +00001423 EXPECT_THAT(container, Contains(Pair(1, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001424 EXPECT_THAT(container, Contains(Pair(1, _)));
zhanyong.wan95b12332009-09-25 18:55:50 +00001425 EXPECT_THAT(container, Contains(Pair(_, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001426 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1427}
1428
shiqiane35fdd92008-12-10 05:08:54 +00001429// Tests StartsWith(s).
1430
1431TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1432 const Matcher<const char*> m1 = StartsWith(string(""));
1433 EXPECT_TRUE(m1.Matches("Hi"));
1434 EXPECT_TRUE(m1.Matches(""));
1435 EXPECT_FALSE(m1.Matches(NULL));
1436
1437 const Matcher<const string&> m2 = StartsWith("Hi");
1438 EXPECT_TRUE(m2.Matches("Hi"));
1439 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1440 EXPECT_TRUE(m2.Matches("High"));
1441 EXPECT_FALSE(m2.Matches("H"));
1442 EXPECT_FALSE(m2.Matches(" Hi"));
1443}
1444
1445TEST(StartsWithTest, CanDescribeSelf) {
1446 Matcher<const std::string> m = StartsWith("Hi");
1447 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1448}
1449
1450// Tests EndsWith(s).
1451
1452TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1453 const Matcher<const char*> m1 = EndsWith("");
1454 EXPECT_TRUE(m1.Matches("Hi"));
1455 EXPECT_TRUE(m1.Matches(""));
1456 EXPECT_FALSE(m1.Matches(NULL));
1457
1458 const Matcher<const string&> m2 = EndsWith(string("Hi"));
1459 EXPECT_TRUE(m2.Matches("Hi"));
1460 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1461 EXPECT_TRUE(m2.Matches("Super Hi"));
1462 EXPECT_FALSE(m2.Matches("i"));
1463 EXPECT_FALSE(m2.Matches("Hi "));
1464}
1465
1466TEST(EndsWithTest, CanDescribeSelf) {
1467 Matcher<const std::string> m = EndsWith("Hi");
1468 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1469}
1470
shiqiane35fdd92008-12-10 05:08:54 +00001471// Tests MatchesRegex().
1472
1473TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1474 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1475 EXPECT_TRUE(m1.Matches("az"));
1476 EXPECT_TRUE(m1.Matches("abcz"));
1477 EXPECT_FALSE(m1.Matches(NULL));
1478
1479 const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z"));
1480 EXPECT_TRUE(m2.Matches("azbz"));
1481 EXPECT_FALSE(m2.Matches("az1"));
1482 EXPECT_FALSE(m2.Matches("1az"));
1483}
1484
1485TEST(MatchesRegexTest, CanDescribeSelf) {
1486 Matcher<const std::string> m1 = MatchesRegex(string("Hi.*"));
1487 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1488
zhanyong.wand14aaed2010-01-14 05:36:32 +00001489 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1490 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001491}
1492
1493// Tests ContainsRegex().
1494
1495TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1496 const Matcher<const char*> m1 = ContainsRegex(string("a.*z"));
1497 EXPECT_TRUE(m1.Matches("az"));
1498 EXPECT_TRUE(m1.Matches("0abcz1"));
1499 EXPECT_FALSE(m1.Matches(NULL));
1500
1501 const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z"));
1502 EXPECT_TRUE(m2.Matches("azbz"));
1503 EXPECT_TRUE(m2.Matches("az1"));
1504 EXPECT_FALSE(m2.Matches("1a"));
1505}
1506
1507TEST(ContainsRegexTest, CanDescribeSelf) {
1508 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1509 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1510
zhanyong.wand14aaed2010-01-14 05:36:32 +00001511 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1512 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001513}
shiqiane35fdd92008-12-10 05:08:54 +00001514
1515// Tests for wide strings.
1516#if GTEST_HAS_STD_WSTRING
1517TEST(StdWideStrEqTest, MatchesEqual) {
1518 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1519 EXPECT_TRUE(m.Matches(L"Hello"));
1520 EXPECT_FALSE(m.Matches(L"hello"));
1521 EXPECT_FALSE(m.Matches(NULL));
1522
1523 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1524 EXPECT_TRUE(m2.Matches(L"Hello"));
1525 EXPECT_FALSE(m2.Matches(L"Hi"));
1526
1527 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1528 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1529 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1530
1531 ::std::wstring str(L"01204500800");
1532 str[3] = L'\0';
1533 Matcher<const ::std::wstring&> m4 = StrEq(str);
1534 EXPECT_TRUE(m4.Matches(str));
1535 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1536 Matcher<const ::std::wstring&> m5 = StrEq(str);
1537 EXPECT_TRUE(m5.Matches(str));
1538}
1539
1540TEST(StdWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001541 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1542 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001543 Describe(m));
1544
1545 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1546 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1547 Describe(m2));
1548
1549 ::std::wstring str(L"01204500800");
1550 str[3] = L'\0';
1551 Matcher<const ::std::wstring&> m4 = StrEq(str);
1552 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1553 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1554 Matcher<const ::std::wstring&> m5 = StrEq(str);
1555 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1556}
1557
1558TEST(StdWideStrNeTest, MatchesUnequalString) {
1559 Matcher<const wchar_t*> m = StrNe(L"Hello");
1560 EXPECT_TRUE(m.Matches(L""));
1561 EXPECT_TRUE(m.Matches(NULL));
1562 EXPECT_FALSE(m.Matches(L"Hello"));
1563
1564 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1565 EXPECT_TRUE(m2.Matches(L"hello"));
1566 EXPECT_FALSE(m2.Matches(L"Hello"));
1567}
1568
1569TEST(StdWideStrNeTest, CanDescribeSelf) {
1570 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001571 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001572}
1573
1574TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1575 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1576 EXPECT_TRUE(m.Matches(L"Hello"));
1577 EXPECT_TRUE(m.Matches(L"hello"));
1578 EXPECT_FALSE(m.Matches(L"Hi"));
1579 EXPECT_FALSE(m.Matches(NULL));
1580
1581 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1582 EXPECT_TRUE(m2.Matches(L"hello"));
1583 EXPECT_FALSE(m2.Matches(L"Hi"));
1584}
1585
1586TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1587 ::std::wstring str1(L"oabocdooeoo");
1588 ::std::wstring str2(L"OABOCDOOEOO");
1589 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1590 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1591
1592 str1[3] = str2[3] = L'\0';
1593 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1594 EXPECT_TRUE(m1.Matches(str2));
1595
1596 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1597 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1598 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1599 str1[9] = str2[9] = L'\0';
1600 EXPECT_FALSE(m2.Matches(str2));
1601
1602 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1603 EXPECT_TRUE(m3.Matches(str2));
1604
1605 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1606 str2.append(1, L'\0');
1607 EXPECT_FALSE(m3.Matches(str2));
1608 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1609}
1610
1611TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1612 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1613 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1614}
1615
1616TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1617 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1618 EXPECT_TRUE(m.Matches(L"Hi"));
1619 EXPECT_TRUE(m.Matches(NULL));
1620 EXPECT_FALSE(m.Matches(L"Hello"));
1621 EXPECT_FALSE(m.Matches(L"hello"));
1622
1623 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1624 EXPECT_TRUE(m2.Matches(L""));
1625 EXPECT_FALSE(m2.Matches(L"Hello"));
1626}
1627
1628TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1629 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001630 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001631}
1632
1633// Tests that HasSubstr() works for matching wstring-typed values.
1634TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1635 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1636 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1637 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1638
1639 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1640 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1641 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1642}
1643
1644// Tests that HasSubstr() works for matching C-wide-string-typed values.
1645TEST(StdWideHasSubstrTest, WorksForCStrings) {
1646 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1647 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1648 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1649 EXPECT_FALSE(m1.Matches(NULL));
1650
1651 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1652 EXPECT_TRUE(m2.Matches(L"I love food."));
1653 EXPECT_FALSE(m2.Matches(L"tofo"));
1654 EXPECT_FALSE(m2.Matches(NULL));
1655}
1656
1657// Tests that HasSubstr(s) describes itself properly.
1658TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1659 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1660 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1661}
1662
1663// Tests StartsWith(s).
1664
1665TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1666 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1667 EXPECT_TRUE(m1.Matches(L"Hi"));
1668 EXPECT_TRUE(m1.Matches(L""));
1669 EXPECT_FALSE(m1.Matches(NULL));
1670
1671 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1672 EXPECT_TRUE(m2.Matches(L"Hi"));
1673 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1674 EXPECT_TRUE(m2.Matches(L"High"));
1675 EXPECT_FALSE(m2.Matches(L"H"));
1676 EXPECT_FALSE(m2.Matches(L" Hi"));
1677}
1678
1679TEST(StdWideStartsWithTest, CanDescribeSelf) {
1680 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
1681 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1682}
1683
1684// Tests EndsWith(s).
1685
1686TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
1687 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1688 EXPECT_TRUE(m1.Matches(L"Hi"));
1689 EXPECT_TRUE(m1.Matches(L""));
1690 EXPECT_FALSE(m1.Matches(NULL));
1691
1692 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
1693 EXPECT_TRUE(m2.Matches(L"Hi"));
1694 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1695 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1696 EXPECT_FALSE(m2.Matches(L"i"));
1697 EXPECT_FALSE(m2.Matches(L"Hi "));
1698}
1699
1700TEST(StdWideEndsWithTest, CanDescribeSelf) {
1701 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
1702 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1703}
1704
1705#endif // GTEST_HAS_STD_WSTRING
1706
1707#if GTEST_HAS_GLOBAL_WSTRING
1708TEST(GlobalWideStrEqTest, MatchesEqual) {
1709 Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
1710 EXPECT_TRUE(m.Matches(L"Hello"));
1711 EXPECT_FALSE(m.Matches(L"hello"));
1712 EXPECT_FALSE(m.Matches(NULL));
1713
1714 Matcher<const ::wstring&> m2 = StrEq(L"Hello");
1715 EXPECT_TRUE(m2.Matches(L"Hello"));
1716 EXPECT_FALSE(m2.Matches(L"Hi"));
1717
1718 Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1719 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1720 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1721
1722 ::wstring str(L"01204500800");
1723 str[3] = L'\0';
1724 Matcher<const ::wstring&> m4 = StrEq(str);
1725 EXPECT_TRUE(m4.Matches(str));
1726 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1727 Matcher<const ::wstring&> m5 = StrEq(str);
1728 EXPECT_TRUE(m5.Matches(str));
1729}
1730
1731TEST(GlobalWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001732 Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1733 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001734 Describe(m));
1735
1736 Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1737 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1738 Describe(m2));
1739
1740 ::wstring str(L"01204500800");
1741 str[3] = L'\0';
1742 Matcher<const ::wstring&> m4 = StrEq(str);
1743 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1744 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1745 Matcher<const ::wstring&> m5 = StrEq(str);
1746 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1747}
1748
1749TEST(GlobalWideStrNeTest, MatchesUnequalString) {
1750 Matcher<const wchar_t*> m = StrNe(L"Hello");
1751 EXPECT_TRUE(m.Matches(L""));
1752 EXPECT_TRUE(m.Matches(NULL));
1753 EXPECT_FALSE(m.Matches(L"Hello"));
1754
1755 Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
1756 EXPECT_TRUE(m2.Matches(L"hello"));
1757 EXPECT_FALSE(m2.Matches(L"Hello"));
1758}
1759
1760TEST(GlobalWideStrNeTest, CanDescribeSelf) {
1761 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001762 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001763}
1764
1765TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1766 Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
1767 EXPECT_TRUE(m.Matches(L"Hello"));
1768 EXPECT_TRUE(m.Matches(L"hello"));
1769 EXPECT_FALSE(m.Matches(L"Hi"));
1770 EXPECT_FALSE(m.Matches(NULL));
1771
1772 Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
1773 EXPECT_TRUE(m2.Matches(L"hello"));
1774 EXPECT_FALSE(m2.Matches(L"Hi"));
1775}
1776
1777TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1778 ::wstring str1(L"oabocdooeoo");
1779 ::wstring str2(L"OABOCDOOEOO");
1780 Matcher<const ::wstring&> m0 = StrCaseEq(str1);
1781 EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
1782
1783 str1[3] = str2[3] = L'\0';
1784 Matcher<const ::wstring&> m1 = StrCaseEq(str1);
1785 EXPECT_TRUE(m1.Matches(str2));
1786
1787 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1788 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1789 Matcher<const ::wstring&> m2 = StrCaseEq(str1);
1790 str1[9] = str2[9] = L'\0';
1791 EXPECT_FALSE(m2.Matches(str2));
1792
1793 Matcher<const ::wstring&> m3 = StrCaseEq(str1);
1794 EXPECT_TRUE(m3.Matches(str2));
1795
1796 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1797 str2.append(1, L'\0');
1798 EXPECT_FALSE(m3.Matches(str2));
1799 EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
1800}
1801
1802TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
1803 Matcher< ::wstring> m = StrCaseEq(L"Hi");
1804 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1805}
1806
1807TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1808 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1809 EXPECT_TRUE(m.Matches(L"Hi"));
1810 EXPECT_TRUE(m.Matches(NULL));
1811 EXPECT_FALSE(m.Matches(L"Hello"));
1812 EXPECT_FALSE(m.Matches(L"hello"));
1813
1814 Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
1815 EXPECT_TRUE(m2.Matches(L""));
1816 EXPECT_FALSE(m2.Matches(L"Hello"));
1817}
1818
1819TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
1820 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001821 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001822}
1823
1824// Tests that HasSubstr() works for matching wstring-typed values.
1825TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
1826 const Matcher< ::wstring> m1 = HasSubstr(L"foo");
1827 EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
1828 EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
1829
1830 const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
1831 EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
1832 EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
1833}
1834
1835// Tests that HasSubstr() works for matching C-wide-string-typed values.
1836TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
1837 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1838 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1839 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1840 EXPECT_FALSE(m1.Matches(NULL));
1841
1842 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1843 EXPECT_TRUE(m2.Matches(L"I love food."));
1844 EXPECT_FALSE(m2.Matches(L"tofo"));
1845 EXPECT_FALSE(m2.Matches(NULL));
1846}
1847
1848// Tests that HasSubstr(s) describes itself properly.
1849TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
1850 Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
1851 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1852}
1853
1854// Tests StartsWith(s).
1855
1856TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
1857 const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
1858 EXPECT_TRUE(m1.Matches(L"Hi"));
1859 EXPECT_TRUE(m1.Matches(L""));
1860 EXPECT_FALSE(m1.Matches(NULL));
1861
1862 const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
1863 EXPECT_TRUE(m2.Matches(L"Hi"));
1864 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1865 EXPECT_TRUE(m2.Matches(L"High"));
1866 EXPECT_FALSE(m2.Matches(L"H"));
1867 EXPECT_FALSE(m2.Matches(L" Hi"));
1868}
1869
1870TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
1871 Matcher<const ::wstring> m = StartsWith(L"Hi");
1872 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1873}
1874
1875// Tests EndsWith(s).
1876
1877TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
1878 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1879 EXPECT_TRUE(m1.Matches(L"Hi"));
1880 EXPECT_TRUE(m1.Matches(L""));
1881 EXPECT_FALSE(m1.Matches(NULL));
1882
1883 const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
1884 EXPECT_TRUE(m2.Matches(L"Hi"));
1885 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1886 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1887 EXPECT_FALSE(m2.Matches(L"i"));
1888 EXPECT_FALSE(m2.Matches(L"Hi "));
1889}
1890
1891TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
1892 Matcher<const ::wstring> m = EndsWith(L"Hi");
1893 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1894}
1895
1896#endif // GTEST_HAS_GLOBAL_WSTRING
1897
1898
1899typedef ::std::tr1::tuple<long, int> Tuple2; // NOLINT
1900
1901// Tests that Eq() matches a 2-tuple where the first field == the
1902// second field.
1903TEST(Eq2Test, MatchesEqualArguments) {
1904 Matcher<const Tuple2&> m = Eq();
1905 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1906 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1907}
1908
1909// Tests that Eq() describes itself properly.
1910TEST(Eq2Test, CanDescribeSelf) {
1911 Matcher<const Tuple2&> m = Eq();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001912 EXPECT_EQ("are an equal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001913}
1914
1915// Tests that Ge() matches a 2-tuple where the first field >= the
1916// second field.
1917TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
1918 Matcher<const Tuple2&> m = Ge();
1919 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1920 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1921 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1922}
1923
1924// Tests that Ge() describes itself properly.
1925TEST(Ge2Test, CanDescribeSelf) {
1926 Matcher<const Tuple2&> m = Ge();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001927 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001928}
1929
1930// Tests that Gt() matches a 2-tuple where the first field > the
1931// second field.
1932TEST(Gt2Test, MatchesGreaterThanArguments) {
1933 Matcher<const Tuple2&> m = Gt();
1934 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1935 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1936 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1937}
1938
1939// Tests that Gt() describes itself properly.
1940TEST(Gt2Test, CanDescribeSelf) {
1941 Matcher<const Tuple2&> m = Gt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001942 EXPECT_EQ("are a pair where the first > the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001943}
1944
1945// Tests that Le() matches a 2-tuple where the first field <= the
1946// second field.
1947TEST(Le2Test, MatchesLessThanOrEqualArguments) {
1948 Matcher<const Tuple2&> m = Le();
1949 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1950 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1951 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1952}
1953
1954// Tests that Le() describes itself properly.
1955TEST(Le2Test, CanDescribeSelf) {
1956 Matcher<const Tuple2&> m = Le();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001957 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001958}
1959
1960// Tests that Lt() matches a 2-tuple where the first field < the
1961// second field.
1962TEST(Lt2Test, MatchesLessThanArguments) {
1963 Matcher<const Tuple2&> m = Lt();
1964 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1965 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1966 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1967}
1968
1969// Tests that Lt() describes itself properly.
1970TEST(Lt2Test, CanDescribeSelf) {
1971 Matcher<const Tuple2&> m = Lt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001972 EXPECT_EQ("are a pair where the first < the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001973}
1974
1975// Tests that Ne() matches a 2-tuple where the first field != the
1976// second field.
1977TEST(Ne2Test, MatchesUnequalArguments) {
1978 Matcher<const Tuple2&> m = Ne();
1979 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1980 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1981 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1982}
1983
1984// Tests that Ne() describes itself properly.
1985TEST(Ne2Test, CanDescribeSelf) {
1986 Matcher<const Tuple2&> m = Ne();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001987 EXPECT_EQ("are an unequal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001988}
1989
1990// Tests that Not(m) matches any value that doesn't match m.
1991TEST(NotTest, NegatesMatcher) {
1992 Matcher<int> m;
1993 m = Not(Eq(2));
1994 EXPECT_TRUE(m.Matches(3));
1995 EXPECT_FALSE(m.Matches(2));
1996}
1997
1998// Tests that Not(m) describes itself properly.
1999TEST(NotTest, CanDescribeSelf) {
2000 Matcher<int> m = Not(Eq(5));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002001 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002002}
2003
zhanyong.wan18490652009-05-11 18:54:08 +00002004// Tests that monomorphic matchers are safely cast by the Not matcher.
2005TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2006 // greater_than_5 is a monomorphic matcher.
2007 Matcher<int> greater_than_5 = Gt(5);
2008
2009 Matcher<const int&> m = Not(greater_than_5);
2010 Matcher<int&> m2 = Not(greater_than_5);
2011 Matcher<int&> m3 = Not(m);
2012}
2013
zhanyong.wan02c15052010-06-09 19:21:30 +00002014// Helper to allow easy testing of AllOf matchers with num parameters.
2015void AllOfMatches(int num, const Matcher<int>& m) {
2016 SCOPED_TRACE(Describe(m));
2017 EXPECT_TRUE(m.Matches(0));
2018 for (int i = 1; i <= num; ++i) {
2019 EXPECT_FALSE(m.Matches(i));
2020 }
2021 EXPECT_TRUE(m.Matches(num + 1));
2022}
2023
shiqiane35fdd92008-12-10 05:08:54 +00002024// Tests that AllOf(m1, ..., mn) matches any value that matches all of
2025// the given matchers.
2026TEST(AllOfTest, MatchesWhenAllMatch) {
2027 Matcher<int> m;
2028 m = AllOf(Le(2), Ge(1));
2029 EXPECT_TRUE(m.Matches(1));
2030 EXPECT_TRUE(m.Matches(2));
2031 EXPECT_FALSE(m.Matches(0));
2032 EXPECT_FALSE(m.Matches(3));
2033
2034 m = AllOf(Gt(0), Ne(1), Ne(2));
2035 EXPECT_TRUE(m.Matches(3));
2036 EXPECT_FALSE(m.Matches(2));
2037 EXPECT_FALSE(m.Matches(1));
2038 EXPECT_FALSE(m.Matches(0));
2039
2040 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2041 EXPECT_TRUE(m.Matches(4));
2042 EXPECT_FALSE(m.Matches(3));
2043 EXPECT_FALSE(m.Matches(2));
2044 EXPECT_FALSE(m.Matches(1));
2045 EXPECT_FALSE(m.Matches(0));
2046
2047 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2048 EXPECT_TRUE(m.Matches(0));
2049 EXPECT_TRUE(m.Matches(1));
2050 EXPECT_FALSE(m.Matches(3));
zhanyong.wan02c15052010-06-09 19:21:30 +00002051
2052 // The following tests for varying number of sub-matchers. Due to the way
2053 // the sub-matchers are handled it is enough to test every sub-matcher once
2054 // with sub-matchers using the same matcher type. Varying matcher types are
2055 // checked for above.
2056 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2057 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2058 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2059 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2060 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2061 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2062 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2063 Ne(8)));
2064 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2065 Ne(8), Ne(9)));
2066 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2067 Ne(9), Ne(10)));
shiqiane35fdd92008-12-10 05:08:54 +00002068}
2069
zhanyong.wan616180e2013-06-18 18:49:51 +00002070#if GTEST_LANG_CXX11
2071// Tests the variadic version of the AllOfMatcher.
2072TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
2073 // Make sure AllOf is defined in the right namespace and does not depend on
2074 // ADL.
2075 ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2076 Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2077 Ne(9), Ne(10), Ne(11));
2078 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))"));
2079 AllOfMatches(11, m);
2080 AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2081 Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
2082 Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22),
2083 Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29),
2084 Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36),
2085 Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43),
2086 Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2087 Ne(50)));
2088}
2089
2090#endif // GTEST_LANG_CXX11
2091
shiqiane35fdd92008-12-10 05:08:54 +00002092// Tests that AllOf(m1, ..., mn) describes itself properly.
2093TEST(AllOfTest, CanDescribeSelf) {
2094 Matcher<int> m;
2095 m = AllOf(Le(2), Ge(1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002096 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002097
2098 m = AllOf(Gt(0), Ne(1), Ne(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002099 EXPECT_EQ("(is > 0) and "
2100 "((isn't equal to 1) and "
2101 "(isn't equal to 2))",
shiqiane35fdd92008-12-10 05:08:54 +00002102 Describe(m));
2103
2104
2105 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002106 EXPECT_EQ("((is > 0) and "
2107 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002108 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002109 "(isn't equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002110 Describe(m));
2111
2112
2113 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002114 EXPECT_EQ("((is >= 0) and "
2115 "(is < 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002116 "((isn't equal to 3) and "
2117 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002118 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002119 Describe(m));
2120}
2121
2122// Tests that AllOf(m1, ..., mn) describes its negation properly.
2123TEST(AllOfTest, CanDescribeNegation) {
2124 Matcher<int> m;
2125 m = AllOf(Le(2), Ge(1));
2126 EXPECT_EQ("(isn't <= 2) or "
2127 "(isn't >= 1)",
2128 DescribeNegation(m));
2129
2130 m = AllOf(Gt(0), Ne(1), Ne(2));
2131 EXPECT_EQ("(isn't > 0) or "
2132 "((is equal to 1) or "
2133 "(is equal to 2))",
2134 DescribeNegation(m));
2135
2136
2137 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002138 EXPECT_EQ("((isn't > 0) or "
2139 "(is equal to 1)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002140 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002141 "(is equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002142 DescribeNegation(m));
2143
2144
2145 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002146 EXPECT_EQ("((isn't >= 0) or "
2147 "(isn't < 10)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002148 "((is equal to 3) or "
2149 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002150 "(is equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002151 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00002152}
2153
zhanyong.wan18490652009-05-11 18:54:08 +00002154// Tests that monomorphic matchers are safely cast by the AllOf matcher.
2155TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2156 // greater_than_5 and less_than_10 are monomorphic matchers.
2157 Matcher<int> greater_than_5 = Gt(5);
2158 Matcher<int> less_than_10 = Lt(10);
2159
2160 Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2161 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2162 Matcher<int&> m3 = AllOf(greater_than_5, m2);
2163
2164 // Tests that BothOf works when composing itself.
2165 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2166 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2167}
2168
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002169TEST(AllOfTest, ExplainsResult) {
2170 Matcher<int> m;
2171
2172 // Successful match. Both matchers need to explain. The second
2173 // matcher doesn't give an explanation, so only the first matcher's
2174 // explanation is printed.
2175 m = AllOf(GreaterThan(10), Lt(30));
2176 EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2177
2178 // Successful match. Both matchers need to explain.
2179 m = AllOf(GreaterThan(10), GreaterThan(20));
2180 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2181 Explain(m, 30));
2182
2183 // Successful match. All matchers need to explain. The second
2184 // matcher doesn't given an explanation.
2185 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2186 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2187 Explain(m, 25));
2188
2189 // Successful match. All matchers need to explain.
2190 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2191 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2192 "and which is 10 more than 30",
2193 Explain(m, 40));
2194
2195 // Failed match. The first matcher, which failed, needs to
2196 // explain.
2197 m = AllOf(GreaterThan(10), GreaterThan(20));
2198 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2199
2200 // Failed match. The second matcher, which failed, needs to
2201 // explain. Since it doesn't given an explanation, nothing is
2202 // printed.
2203 m = AllOf(GreaterThan(10), Lt(30));
2204 EXPECT_EQ("", Explain(m, 40));
2205
2206 // Failed match. The second matcher, which failed, needs to
2207 // explain.
2208 m = AllOf(GreaterThan(10), GreaterThan(20));
2209 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2210}
2211
zhanyong.wan02c15052010-06-09 19:21:30 +00002212// Helper to allow easy testing of AnyOf matchers with num parameters.
2213void AnyOfMatches(int num, const Matcher<int>& m) {
2214 SCOPED_TRACE(Describe(m));
2215 EXPECT_FALSE(m.Matches(0));
2216 for (int i = 1; i <= num; ++i) {
2217 EXPECT_TRUE(m.Matches(i));
2218 }
2219 EXPECT_FALSE(m.Matches(num + 1));
2220}
2221
shiqiane35fdd92008-12-10 05:08:54 +00002222// Tests that AnyOf(m1, ..., mn) matches any value that matches at
2223// least one of the given matchers.
2224TEST(AnyOfTest, MatchesWhenAnyMatches) {
2225 Matcher<int> m;
2226 m = AnyOf(Le(1), Ge(3));
2227 EXPECT_TRUE(m.Matches(1));
2228 EXPECT_TRUE(m.Matches(4));
2229 EXPECT_FALSE(m.Matches(2));
2230
2231 m = AnyOf(Lt(0), Eq(1), Eq(2));
2232 EXPECT_TRUE(m.Matches(-1));
2233 EXPECT_TRUE(m.Matches(1));
2234 EXPECT_TRUE(m.Matches(2));
2235 EXPECT_FALSE(m.Matches(0));
2236
2237 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2238 EXPECT_TRUE(m.Matches(-1));
2239 EXPECT_TRUE(m.Matches(1));
2240 EXPECT_TRUE(m.Matches(2));
2241 EXPECT_TRUE(m.Matches(3));
2242 EXPECT_FALSE(m.Matches(0));
2243
2244 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2245 EXPECT_TRUE(m.Matches(0));
2246 EXPECT_TRUE(m.Matches(11));
2247 EXPECT_TRUE(m.Matches(3));
2248 EXPECT_FALSE(m.Matches(2));
zhanyong.wan02c15052010-06-09 19:21:30 +00002249
2250 // The following tests for varying number of sub-matchers. Due to the way
2251 // the sub-matchers are handled it is enough to test every sub-matcher once
2252 // with sub-matchers using the same matcher type. Varying matcher types are
2253 // checked for above.
2254 AnyOfMatches(2, AnyOf(1, 2));
2255 AnyOfMatches(3, AnyOf(1, 2, 3));
2256 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2257 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2258 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2259 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2260 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2261 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2262 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
shiqiane35fdd92008-12-10 05:08:54 +00002263}
2264
zhanyong.wan616180e2013-06-18 18:49:51 +00002265#if GTEST_LANG_CXX11
2266// Tests the variadic version of the AnyOfMatcher.
2267TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2268 // Also make sure AnyOf is defined in the right namespace and does not depend
2269 // on ADL.
2270 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2271
2272 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))"));
2273 AnyOfMatches(11, m);
2274 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2275 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2276 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2277 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2278 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2279}
2280
2281#endif // GTEST_LANG_CXX11
2282
shiqiane35fdd92008-12-10 05:08:54 +00002283// Tests that AnyOf(m1, ..., mn) describes itself properly.
2284TEST(AnyOfTest, CanDescribeSelf) {
2285 Matcher<int> m;
2286 m = AnyOf(Le(1), Ge(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002287 EXPECT_EQ("(is <= 1) or (is >= 3)",
shiqiane35fdd92008-12-10 05:08:54 +00002288 Describe(m));
2289
2290 m = AnyOf(Lt(0), Eq(1), Eq(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002291 EXPECT_EQ("(is < 0) or "
shiqiane35fdd92008-12-10 05:08:54 +00002292 "((is equal to 1) or (is equal to 2))",
2293 Describe(m));
2294
2295 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002296 EXPECT_EQ("((is < 0) or "
2297 "(is equal to 1)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002298 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002299 "(is equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002300 Describe(m));
2301
2302 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002303 EXPECT_EQ("((is <= 0) or "
2304 "(is > 10)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002305 "((is equal to 3) or "
2306 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002307 "(is equal to 7)))",
shiqiane35fdd92008-12-10 05:08:54 +00002308 Describe(m));
2309}
2310
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002311// Tests that AnyOf(m1, ..., mn) describes its negation properly.
2312TEST(AnyOfTest, CanDescribeNegation) {
2313 Matcher<int> m;
2314 m = AnyOf(Le(1), Ge(3));
2315 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2316 DescribeNegation(m));
2317
2318 m = AnyOf(Lt(0), Eq(1), Eq(2));
2319 EXPECT_EQ("(isn't < 0) and "
2320 "((isn't equal to 1) and (isn't equal to 2))",
2321 DescribeNegation(m));
2322
2323 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002324 EXPECT_EQ("((isn't < 0) and "
2325 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002326 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002327 "(isn't equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002328 DescribeNegation(m));
2329
2330 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002331 EXPECT_EQ("((isn't <= 0) and "
2332 "(isn't > 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002333 "((isn't equal to 3) and "
2334 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002335 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002336 DescribeNegation(m));
2337}
2338
zhanyong.wan18490652009-05-11 18:54:08 +00002339// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2340TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2341 // greater_than_5 and less_than_10 are monomorphic matchers.
2342 Matcher<int> greater_than_5 = Gt(5);
2343 Matcher<int> less_than_10 = Lt(10);
2344
2345 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2346 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2347 Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2348
2349 // Tests that EitherOf works when composing itself.
2350 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2351 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2352}
2353
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002354TEST(AnyOfTest, ExplainsResult) {
2355 Matcher<int> m;
2356
2357 // Failed match. Both matchers need to explain. The second
2358 // matcher doesn't give an explanation, so only the first matcher's
2359 // explanation is printed.
2360 m = AnyOf(GreaterThan(10), Lt(0));
2361 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2362
2363 // Failed match. Both matchers need to explain.
2364 m = AnyOf(GreaterThan(10), GreaterThan(20));
2365 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2366 Explain(m, 5));
2367
2368 // Failed match. All matchers need to explain. The second
2369 // matcher doesn't given an explanation.
2370 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2371 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2372 Explain(m, 5));
2373
2374 // Failed match. All matchers need to explain.
2375 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2376 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2377 "and which is 25 less than 30",
2378 Explain(m, 5));
2379
2380 // Successful match. The first matcher, which succeeded, needs to
2381 // explain.
2382 m = AnyOf(GreaterThan(10), GreaterThan(20));
2383 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2384
2385 // Successful match. The second matcher, which succeeded, needs to
2386 // explain. Since it doesn't given an explanation, nothing is
2387 // printed.
2388 m = AnyOf(GreaterThan(10), Lt(30));
2389 EXPECT_EQ("", Explain(m, 0));
2390
2391 // Successful match. The second matcher, which succeeded, needs to
2392 // explain.
2393 m = AnyOf(GreaterThan(30), GreaterThan(20));
2394 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2395}
2396
shiqiane35fdd92008-12-10 05:08:54 +00002397// The following predicate function and predicate functor are for
2398// testing the Truly(predicate) matcher.
2399
2400// Returns non-zero if the input is positive. Note that the return
2401// type of this function is not bool. It's OK as Truly() accepts any
2402// unary function or functor whose return type can be implicitly
2403// converted to bool.
2404int IsPositive(double x) {
2405 return x > 0 ? 1 : 0;
2406}
2407
2408// This functor returns true if the input is greater than the given
2409// number.
2410class IsGreaterThan {
2411 public:
2412 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2413
2414 bool operator()(int n) const { return n > threshold_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002415
shiqiane35fdd92008-12-10 05:08:54 +00002416 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002417 int threshold_;
shiqiane35fdd92008-12-10 05:08:54 +00002418};
2419
2420// For testing Truly().
2421const int foo = 0;
2422
2423// This predicate returns true iff the argument references foo and has
2424// a zero value.
2425bool ReferencesFooAndIsZero(const int& n) {
2426 return (&n == &foo) && (n == 0);
2427}
2428
2429// Tests that Truly(predicate) matches what satisfies the given
2430// predicate.
2431TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2432 Matcher<double> m = Truly(IsPositive);
2433 EXPECT_TRUE(m.Matches(2.0));
2434 EXPECT_FALSE(m.Matches(-1.5));
2435}
2436
2437// Tests that Truly(predicate_functor) works too.
2438TEST(TrulyTest, CanBeUsedWithFunctor) {
2439 Matcher<int> m = Truly(IsGreaterThan(5));
2440 EXPECT_TRUE(m.Matches(6));
2441 EXPECT_FALSE(m.Matches(4));
2442}
2443
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00002444// A class that can be implicitly converted to bool.
2445class ConvertibleToBool {
2446 public:
2447 explicit ConvertibleToBool(int number) : number_(number) {}
2448 operator bool() const { return number_ != 0; }
2449
2450 private:
2451 int number_;
2452};
2453
2454ConvertibleToBool IsNotZero(int number) {
2455 return ConvertibleToBool(number);
2456}
2457
2458// Tests that the predicate used in Truly() may return a class that's
2459// implicitly convertible to bool, even when the class has no
2460// operator!().
2461TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2462 Matcher<int> m = Truly(IsNotZero);
2463 EXPECT_TRUE(m.Matches(1));
2464 EXPECT_FALSE(m.Matches(0));
2465}
2466
shiqiane35fdd92008-12-10 05:08:54 +00002467// Tests that Truly(predicate) can describe itself properly.
2468TEST(TrulyTest, CanDescribeSelf) {
2469 Matcher<double> m = Truly(IsPositive);
2470 EXPECT_EQ("satisfies the given predicate",
2471 Describe(m));
2472}
2473
2474// Tests that Truly(predicate) works when the matcher takes its
2475// argument by reference.
2476TEST(TrulyTest, WorksForByRefArguments) {
2477 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2478 EXPECT_TRUE(m.Matches(foo));
2479 int n = 0;
2480 EXPECT_FALSE(m.Matches(n));
2481}
2482
2483// Tests that Matches(m) is a predicate satisfied by whatever that
2484// matches matcher m.
2485TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2486 EXPECT_TRUE(Matches(Ge(0))(1));
2487 EXPECT_FALSE(Matches(Eq('a'))('b'));
2488}
2489
2490// Tests that Matches(m) works when the matcher takes its argument by
2491// reference.
2492TEST(MatchesTest, WorksOnByRefArguments) {
2493 int m = 0, n = 0;
2494 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2495 EXPECT_FALSE(Matches(Ref(m))(n));
2496}
2497
2498// Tests that a Matcher on non-reference type can be used in
2499// Matches().
2500TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
2501 Matcher<int> eq5 = Eq(5);
2502 EXPECT_TRUE(Matches(eq5)(5));
2503 EXPECT_FALSE(Matches(eq5)(2));
2504}
2505
zhanyong.wanb8243162009-06-04 05:48:20 +00002506// Tests Value(value, matcher). Since Value() is a simple wrapper for
2507// Matches(), which has been tested already, we don't spend a lot of
2508// effort on testing Value().
2509TEST(ValueTest, WorksWithPolymorphicMatcher) {
2510 EXPECT_TRUE(Value("hi", StartsWith("h")));
2511 EXPECT_FALSE(Value(5, Gt(10)));
2512}
2513
2514TEST(ValueTest, WorksWithMonomorphicMatcher) {
2515 const Matcher<int> is_zero = Eq(0);
2516 EXPECT_TRUE(Value(0, is_zero));
2517 EXPECT_FALSE(Value('a', is_zero));
2518
2519 int n = 0;
2520 const Matcher<const int&> ref_n = Ref(n);
2521 EXPECT_TRUE(Value(n, ref_n));
2522 EXPECT_FALSE(Value(1, ref_n));
2523}
2524
zhanyong.wana862f1d2010-03-15 21:23:04 +00002525TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002526 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002527 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002528 EXPECT_EQ("% 2 == 0", listener1.str());
2529
2530 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002531 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002532 EXPECT_EQ("", listener2.str());
2533}
2534
zhanyong.wana862f1d2010-03-15 21:23:04 +00002535TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002536 const Matcher<int> is_even = PolymorphicIsEven();
2537 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002538 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002539 EXPECT_EQ("% 2 == 0", listener1.str());
2540
2541 const Matcher<const double&> is_zero = Eq(0);
2542 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002543 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002544 EXPECT_EQ("", listener2.str());
2545}
2546
zhanyong.wana862f1d2010-03-15 21:23:04 +00002547MATCHER_P(Really, inner_matcher, "") {
2548 return ExplainMatchResult(inner_matcher, arg, result_listener);
2549}
2550
2551TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
2552 EXPECT_THAT(0, Really(Eq(0)));
2553}
2554
zhanyong.wanbf550852009-06-09 06:09:53 +00002555TEST(AllArgsTest, WorksForTuple) {
2556 EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
2557 EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
2558}
2559
2560TEST(AllArgsTest, WorksForNonTuple) {
2561 EXPECT_THAT(42, AllArgs(Gt(0)));
2562 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
2563}
2564
2565class AllArgsHelper {
2566 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002567 AllArgsHelper() {}
2568
zhanyong.wanbf550852009-06-09 06:09:53 +00002569 MOCK_METHOD2(Helper, int(char x, int y));
zhanyong.wan32de5f52009-12-23 00:13:23 +00002570
2571 private:
2572 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
zhanyong.wanbf550852009-06-09 06:09:53 +00002573};
2574
2575TEST(AllArgsTest, WorksInWithClause) {
2576 AllArgsHelper helper;
2577 ON_CALL(helper, Helper(_, _))
2578 .With(AllArgs(Lt()))
2579 .WillByDefault(Return(1));
2580 EXPECT_CALL(helper, Helper(_, _));
2581 EXPECT_CALL(helper, Helper(_, _))
2582 .With(AllArgs(Gt()))
2583 .WillOnce(Return(2));
2584
2585 EXPECT_EQ(1, helper.Helper('\1', 2));
2586 EXPECT_EQ(2, helper.Helper('a', 1));
2587}
2588
shiqiane35fdd92008-12-10 05:08:54 +00002589// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2590// matches the matcher.
2591TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
2592 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
2593 ASSERT_THAT("Foo", EndsWith("oo"));
2594 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
2595 EXPECT_THAT("Hello", StartsWith("Hell"));
2596}
2597
2598// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2599// doesn't match the matcher.
2600TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
2601 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
2602 // which cannot reference auto variables.
zhanyong.wan736baa82010-09-27 17:44:16 +00002603 static unsigned short n; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00002604 n = 5;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002605
2606 // VC++ prior to version 8.0 SP1 has a bug where it will not see any
2607 // functions declared in the namespace scope from within nested classes.
2608 // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
2609 // namespace-level functions invoked inside them need to be explicitly
2610 // resolved.
2611 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
shiqiane35fdd92008-12-10 05:08:54 +00002612 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002613 "Expected: is > 10\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002614 " Actual: 5" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002615 n = 0;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002616 EXPECT_NONFATAL_FAILURE(
2617 EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
2618 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002619 "Expected: (is <= 7) and (is >= 5)\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002620 " Actual: 0" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002621}
2622
2623// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
2624// has a reference type.
2625TEST(MatcherAssertionTest, WorksForByRefArguments) {
2626 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
2627 // reference auto variables.
2628 static int n;
2629 n = 0;
2630 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002631 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
shiqiane35fdd92008-12-10 05:08:54 +00002632 "Value of: n\n"
2633 "Expected: does not reference the variable @");
2634 // Tests the "Actual" part.
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002635 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
zhanyong.wan736baa82010-09-27 17:44:16 +00002636 "Actual: 0" + OfType("int") + ", which is located @");
shiqiane35fdd92008-12-10 05:08:54 +00002637}
2638
zhanyong.wan95b12332009-09-25 18:55:50 +00002639#if !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002640// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
2641// monomorphic.
zhanyong.wan95b12332009-09-25 18:55:50 +00002642
2643// ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
2644// Symbian compiler: it tries to compile
2645// template<T, U> class MatcherCastImpl { ...
zhanyong.wandb22c222010-01-28 21:52:29 +00002646// virtual bool MatchAndExplain(T x, ...) const {
2647// return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
zhanyong.wan95b12332009-09-25 18:55:50 +00002648// with U == string and T == const char*
2649// With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
2650// the compiler silently crashes with no output.
2651// If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
2652// the code compiles but the converted string is bogus.
shiqiane35fdd92008-12-10 05:08:54 +00002653TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
2654 Matcher<const char*> starts_with_he = StartsWith("he");
2655 ASSERT_THAT("hello", starts_with_he);
2656
2657 Matcher<const string&> ends_with_ok = EndsWith("ok");
2658 ASSERT_THAT("book", ends_with_ok);
zhanyong.wan736baa82010-09-27 17:44:16 +00002659 const string bad = "bad";
2660 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
2661 "Value of: bad\n"
2662 "Expected: ends with \"ok\"\n"
2663 " Actual: \"bad\"");
shiqiane35fdd92008-12-10 05:08:54 +00002664 Matcher<int> is_greater_than_5 = Gt(5);
2665 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
2666 "Value of: 5\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002667 "Expected: is > 5\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002668 " Actual: 5" + OfType("int"));
shiqiane35fdd92008-12-10 05:08:54 +00002669}
zhanyong.wan95b12332009-09-25 18:55:50 +00002670#endif // !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002671
2672// Tests floating-point matchers.
2673template <typename RawType>
2674class FloatingPointTest : public testing::Test {
2675 protected:
zhanyong.wan35877b72013-09-18 17:51:08 +00002676 typedef testing::internal::FloatingPoint<RawType> Floating;
shiqiane35fdd92008-12-10 05:08:54 +00002677 typedef typename Floating::Bits Bits;
2678
zhanyong.wan35877b72013-09-18 17:51:08 +00002679 FloatingPointTest()
2680 : max_ulps_(Floating::kMaxUlps),
2681 zero_bits_(Floating(0).bits()),
2682 one_bits_(Floating(1).bits()),
2683 infinity_bits_(Floating(Floating::Infinity()).bits()),
2684 close_to_positive_zero_(
2685 Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
2686 close_to_negative_zero_(
2687 -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
2688 further_from_negative_zero_(-Floating::ReinterpretBits(
2689 zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
2690 close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
2691 further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
2692 infinity_(Floating::Infinity()),
2693 close_to_infinity_(
2694 Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
2695 further_from_infinity_(
2696 Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
2697 max_(Floating::Max()),
2698 nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
2699 nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
shiqiane35fdd92008-12-10 05:08:54 +00002700 }
2701
2702 void TestSize() {
2703 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2704 }
2705
2706 // A battery of tests for FloatingEqMatcher::Matches.
2707 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2708 void TestMatches(
2709 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
2710 Matcher<RawType> m1 = matcher_maker(0.0);
2711 EXPECT_TRUE(m1.Matches(-0.0));
2712 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
2713 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
2714 EXPECT_FALSE(m1.Matches(1.0));
2715
2716 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
2717 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
2718
2719 Matcher<RawType> m3 = matcher_maker(1.0);
2720 EXPECT_TRUE(m3.Matches(close_to_one_));
2721 EXPECT_FALSE(m3.Matches(further_from_one_));
2722
2723 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
2724 EXPECT_FALSE(m3.Matches(0.0));
2725
2726 Matcher<RawType> m4 = matcher_maker(-infinity_);
2727 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
2728
2729 Matcher<RawType> m5 = matcher_maker(infinity_);
2730 EXPECT_TRUE(m5.Matches(close_to_infinity_));
2731
2732 // This is interesting as the representations of infinity_ and nan1_
2733 // are only 1 DLP apart.
2734 EXPECT_FALSE(m5.Matches(nan1_));
2735
2736 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2737 // some cases.
2738 Matcher<const RawType&> m6 = matcher_maker(0.0);
2739 EXPECT_TRUE(m6.Matches(-0.0));
2740 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
2741 EXPECT_FALSE(m6.Matches(1.0));
2742
2743 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2744 // cases.
2745 Matcher<RawType&> m7 = matcher_maker(0.0);
2746 RawType x = 0.0;
2747 EXPECT_TRUE(m7.Matches(x));
2748 x = 0.01f;
2749 EXPECT_FALSE(m7.Matches(x));
2750 }
2751
2752 // Pre-calculated numbers to be used by the tests.
2753
zhanyong.wan35877b72013-09-18 17:51:08 +00002754 const size_t max_ulps_;
shiqiane35fdd92008-12-10 05:08:54 +00002755
zhanyong.wan35877b72013-09-18 17:51:08 +00002756 const Bits zero_bits_; // The bits that represent 0.0.
2757 const Bits one_bits_; // The bits that represent 1.0.
2758 const Bits infinity_bits_; // The bits that represent +infinity.
shiqiane35fdd92008-12-10 05:08:54 +00002759
zhanyong.wan35877b72013-09-18 17:51:08 +00002760 // Some numbers close to 0.0.
2761 const RawType close_to_positive_zero_;
2762 const RawType close_to_negative_zero_;
2763 const RawType further_from_negative_zero_;
shiqiane35fdd92008-12-10 05:08:54 +00002764
zhanyong.wan35877b72013-09-18 17:51:08 +00002765 // Some numbers close to 1.0.
2766 const RawType close_to_one_;
2767 const RawType further_from_one_;
2768
2769 // Some numbers close to +infinity.
2770 const RawType infinity_;
2771 const RawType close_to_infinity_;
2772 const RawType further_from_infinity_;
2773
2774 // Maximum representable value that's not infinity.
2775 const RawType max_;
2776
2777 // Some NaNs.
2778 const RawType nan1_;
2779 const RawType nan2_;
shiqiane35fdd92008-12-10 05:08:54 +00002780};
2781
zhanyong.wan616180e2013-06-18 18:49:51 +00002782// Tests floating-point matchers with fixed epsilons.
2783template <typename RawType>
2784class FloatingPointNearTest : public FloatingPointTest<RawType> {
2785 protected:
2786 typedef FloatingPointTest<RawType> ParentType;
2787
2788 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
2789 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2790 void TestNearMatches(
2791 testing::internal::FloatingEqMatcher<RawType>
2792 (*matcher_maker)(RawType, RawType)) {
2793 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
2794 EXPECT_TRUE(m1.Matches(0.0));
2795 EXPECT_TRUE(m1.Matches(-0.0));
2796 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
2797 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
2798 EXPECT_FALSE(m1.Matches(1.0));
2799
2800 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
2801 EXPECT_TRUE(m2.Matches(0.0));
2802 EXPECT_TRUE(m2.Matches(-0.0));
2803 EXPECT_TRUE(m2.Matches(1.0));
2804 EXPECT_TRUE(m2.Matches(-1.0));
2805 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
2806 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
2807
2808 // Check that inf matches inf, regardless of the of the specified max
2809 // absolute error.
2810 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
2811 EXPECT_TRUE(m3.Matches(ParentType::infinity_));
2812 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
2813 EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
2814
2815 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
2816 EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
2817 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
2818 EXPECT_FALSE(m4.Matches(ParentType::infinity_));
2819
2820 // Test various overflow scenarios.
zhanyong.wan35877b72013-09-18 17:51:08 +00002821 Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
2822 EXPECT_TRUE(m5.Matches(ParentType::max_));
2823 EXPECT_FALSE(m5.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002824
zhanyong.wan35877b72013-09-18 17:51:08 +00002825 Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
2826 EXPECT_FALSE(m6.Matches(ParentType::max_));
2827 EXPECT_TRUE(m6.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002828
zhanyong.wan35877b72013-09-18 17:51:08 +00002829 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
2830 EXPECT_TRUE(m7.Matches(ParentType::max_));
2831 EXPECT_FALSE(m7.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002832
zhanyong.wan35877b72013-09-18 17:51:08 +00002833 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
2834 EXPECT_FALSE(m8.Matches(ParentType::max_));
2835 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002836
2837 // The difference between max() and -max() normally overflows to infinity,
2838 // but it should still match if the max_abs_error is also infinity.
2839 Matcher<RawType> m9 = matcher_maker(
zhanyong.wan35877b72013-09-18 17:51:08 +00002840 ParentType::max_, ParentType::infinity_);
2841 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002842
2843 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2844 // some cases.
2845 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
2846 EXPECT_TRUE(m10.Matches(-0.0));
2847 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
2848 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
2849
2850 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2851 // cases.
2852 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
2853 RawType x = 0.0;
2854 EXPECT_TRUE(m11.Matches(x));
2855 x = 1.0f;
2856 EXPECT_TRUE(m11.Matches(x));
2857 x = -1.0f;
2858 EXPECT_TRUE(m11.Matches(x));
2859 x = 1.1f;
2860 EXPECT_FALSE(m11.Matches(x));
2861 x = -1.1f;
2862 EXPECT_FALSE(m11.Matches(x));
2863 }
2864};
2865
shiqiane35fdd92008-12-10 05:08:54 +00002866// Instantiate FloatingPointTest for testing floats.
2867typedef FloatingPointTest<float> FloatTest;
2868
2869TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
2870 TestMatches(&FloatEq);
2871}
2872
2873TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
2874 TestMatches(&NanSensitiveFloatEq);
2875}
2876
2877TEST_F(FloatTest, FloatEqCannotMatchNaN) {
2878 // FloatEq never matches NaN.
2879 Matcher<float> m = FloatEq(nan1_);
2880 EXPECT_FALSE(m.Matches(nan1_));
2881 EXPECT_FALSE(m.Matches(nan2_));
2882 EXPECT_FALSE(m.Matches(1.0));
2883}
2884
2885TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
2886 // NanSensitiveFloatEq will match NaN.
2887 Matcher<float> m = NanSensitiveFloatEq(nan1_);
2888 EXPECT_TRUE(m.Matches(nan1_));
2889 EXPECT_TRUE(m.Matches(nan2_));
2890 EXPECT_FALSE(m.Matches(1.0));
2891}
2892
2893TEST_F(FloatTest, FloatEqCanDescribeSelf) {
2894 Matcher<float> m1 = FloatEq(2.0f);
2895 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002896 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002897
2898 Matcher<float> m2 = FloatEq(0.5f);
2899 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002900 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002901
2902 Matcher<float> m3 = FloatEq(nan1_);
2903 EXPECT_EQ("never matches", Describe(m3));
2904 EXPECT_EQ("is anything", DescribeNegation(m3));
2905}
2906
2907TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
2908 Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
2909 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002910 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002911
2912 Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
2913 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002914 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002915
2916 Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
2917 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002918 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00002919}
2920
zhanyong.wan616180e2013-06-18 18:49:51 +00002921// Instantiate FloatingPointTest for testing floats with a user-specified
2922// max absolute error.
2923typedef FloatingPointNearTest<float> FloatNearTest;
2924
2925TEST_F(FloatNearTest, FloatNearMatches) {
2926 TestNearMatches(&FloatNear);
2927}
2928
2929TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
2930 TestNearMatches(&NanSensitiveFloatNear);
2931}
2932
2933TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
2934 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
2935 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2936 EXPECT_EQ(
2937 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2938
2939 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
2940 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2941 EXPECT_EQ(
2942 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2943
2944 Matcher<float> m3 = FloatNear(nan1_, 0.0);
2945 EXPECT_EQ("never matches", Describe(m3));
2946 EXPECT_EQ("is anything", DescribeNegation(m3));
2947}
2948
2949TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
2950 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
2951 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2952 EXPECT_EQ(
2953 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2954
2955 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
2956 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2957 EXPECT_EQ(
2958 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2959
2960 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
2961 EXPECT_EQ("is NaN", Describe(m3));
2962 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
2963}
2964
2965TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
2966 // FloatNear never matches NaN.
2967 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
2968 EXPECT_FALSE(m.Matches(nan1_));
2969 EXPECT_FALSE(m.Matches(nan2_));
2970 EXPECT_FALSE(m.Matches(1.0));
2971}
2972
2973TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
2974 // NanSensitiveFloatNear will match NaN.
2975 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
2976 EXPECT_TRUE(m.Matches(nan1_));
2977 EXPECT_TRUE(m.Matches(nan2_));
2978 EXPECT_FALSE(m.Matches(1.0));
2979}
2980
shiqiane35fdd92008-12-10 05:08:54 +00002981// Instantiate FloatingPointTest for testing doubles.
2982typedef FloatingPointTest<double> DoubleTest;
2983
2984TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
2985 TestMatches(&DoubleEq);
2986}
2987
2988TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
2989 TestMatches(&NanSensitiveDoubleEq);
2990}
2991
2992TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
2993 // DoubleEq never matches NaN.
2994 Matcher<double> m = DoubleEq(nan1_);
2995 EXPECT_FALSE(m.Matches(nan1_));
2996 EXPECT_FALSE(m.Matches(nan2_));
2997 EXPECT_FALSE(m.Matches(1.0));
2998}
2999
3000TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3001 // NanSensitiveDoubleEq will match NaN.
3002 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
3003 EXPECT_TRUE(m.Matches(nan1_));
3004 EXPECT_TRUE(m.Matches(nan2_));
3005 EXPECT_FALSE(m.Matches(1.0));
3006}
3007
3008TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3009 Matcher<double> m1 = DoubleEq(2.0);
3010 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003011 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003012
3013 Matcher<double> m2 = DoubleEq(0.5);
3014 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003015 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003016
3017 Matcher<double> m3 = DoubleEq(nan1_);
3018 EXPECT_EQ("never matches", Describe(m3));
3019 EXPECT_EQ("is anything", DescribeNegation(m3));
3020}
3021
3022TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3023 Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3024 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003025 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003026
3027 Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3028 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003029 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003030
3031 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3032 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003033 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00003034}
3035
zhanyong.wan616180e2013-06-18 18:49:51 +00003036// Instantiate FloatingPointTest for testing floats with a user-specified
3037// max absolute error.
3038typedef FloatingPointNearTest<double> DoubleNearTest;
3039
3040TEST_F(DoubleNearTest, DoubleNearMatches) {
3041 TestNearMatches(&DoubleNear);
3042}
3043
3044TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3045 TestNearMatches(&NanSensitiveDoubleNear);
3046}
3047
3048TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3049 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3050 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3051 EXPECT_EQ(
3052 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3053
3054 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3055 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3056 EXPECT_EQ(
3057 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3058
3059 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3060 EXPECT_EQ("never matches", Describe(m3));
3061 EXPECT_EQ("is anything", DescribeNegation(m3));
3062}
3063
3064TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3065 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3066 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3067 EXPECT_EQ(
3068 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3069
3070 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3071 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3072 EXPECT_EQ(
3073 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3074
3075 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3076 EXPECT_EQ("is NaN", Describe(m3));
3077 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3078}
3079
3080TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3081 // DoubleNear never matches NaN.
3082 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3083 EXPECT_FALSE(m.Matches(nan1_));
3084 EXPECT_FALSE(m.Matches(nan2_));
3085 EXPECT_FALSE(m.Matches(1.0));
3086}
3087
3088TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3089 // NanSensitiveDoubleNear will match NaN.
3090 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3091 EXPECT_TRUE(m.Matches(nan1_));
3092 EXPECT_TRUE(m.Matches(nan2_));
3093 EXPECT_FALSE(m.Matches(1.0));
3094}
3095
shiqiane35fdd92008-12-10 05:08:54 +00003096TEST(PointeeTest, RawPointer) {
3097 const Matcher<int*> m = Pointee(Ge(0));
3098
3099 int n = 1;
3100 EXPECT_TRUE(m.Matches(&n));
3101 n = -1;
3102 EXPECT_FALSE(m.Matches(&n));
3103 EXPECT_FALSE(m.Matches(NULL));
3104}
3105
3106TEST(PointeeTest, RawPointerToConst) {
3107 const Matcher<const double*> m = Pointee(Ge(0));
3108
3109 double x = 1;
3110 EXPECT_TRUE(m.Matches(&x));
3111 x = -1;
3112 EXPECT_FALSE(m.Matches(&x));
3113 EXPECT_FALSE(m.Matches(NULL));
3114}
3115
3116TEST(PointeeTest, ReferenceToConstRawPointer) {
3117 const Matcher<int* const &> m = Pointee(Ge(0));
3118
3119 int n = 1;
3120 EXPECT_TRUE(m.Matches(&n));
3121 n = -1;
3122 EXPECT_FALSE(m.Matches(&n));
3123 EXPECT_FALSE(m.Matches(NULL));
3124}
3125
3126TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3127 const Matcher<double* &> m = Pointee(Ge(0));
3128
3129 double x = 1.0;
3130 double* p = &x;
3131 EXPECT_TRUE(m.Matches(p));
3132 x = -1;
3133 EXPECT_FALSE(m.Matches(p));
3134 p = NULL;
3135 EXPECT_FALSE(m.Matches(p));
3136}
3137
vladlosevada23472012-08-14 15:38:49 +00003138// Minimal const-propagating pointer.
3139template <typename T>
3140class ConstPropagatingPtr {
3141 public:
3142 typedef T element_type;
3143
3144 ConstPropagatingPtr() : val_() {}
3145 explicit ConstPropagatingPtr(T* t) : val_(t) {}
3146 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3147
3148 T* get() { return val_; }
3149 T& operator*() { return *val_; }
3150 // Most smart pointers return non-const T* and T& from the next methods.
3151 const T* get() const { return val_; }
3152 const T& operator*() const { return *val_; }
3153
3154 private:
3155 T* val_;
3156};
3157
3158TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3159 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3160 int three = 3;
3161 const ConstPropagatingPtr<int> co(&three);
3162 ConstPropagatingPtr<int> o(&three);
3163 EXPECT_TRUE(m.Matches(o));
3164 EXPECT_TRUE(m.Matches(co));
3165 *o = 6;
3166 EXPECT_FALSE(m.Matches(o));
3167 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3168}
3169
shiqiane35fdd92008-12-10 05:08:54 +00003170TEST(PointeeTest, NeverMatchesNull) {
3171 const Matcher<const char*> m = Pointee(_);
3172 EXPECT_FALSE(m.Matches(NULL));
3173}
3174
3175// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3176TEST(PointeeTest, MatchesAgainstAValue) {
3177 const Matcher<int*> m = Pointee(5);
3178
3179 int n = 5;
3180 EXPECT_TRUE(m.Matches(&n));
3181 n = -1;
3182 EXPECT_FALSE(m.Matches(&n));
3183 EXPECT_FALSE(m.Matches(NULL));
3184}
3185
3186TEST(PointeeTest, CanDescribeSelf) {
3187 const Matcher<int*> m = Pointee(Gt(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003188 EXPECT_EQ("points to a value that is > 3", Describe(m));
3189 EXPECT_EQ("does not point to a value that is > 3",
shiqiane35fdd92008-12-10 05:08:54 +00003190 DescribeNegation(m));
3191}
3192
shiqiane35fdd92008-12-10 05:08:54 +00003193TEST(PointeeTest, CanExplainMatchResult) {
3194 const Matcher<const string*> m = Pointee(StartsWith("Hi"));
3195
3196 EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL)));
3197
zhanyong.wan736baa82010-09-27 17:44:16 +00003198 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
3199 long n = 3; // NOLINT
3200 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003201 Explain(m2, &n));
3202}
3203
3204TEST(PointeeTest, AlwaysExplainsPointee) {
3205 const Matcher<int*> m = Pointee(0);
3206 int n = 42;
zhanyong.wan736baa82010-09-27 17:44:16 +00003207 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
shiqiane35fdd92008-12-10 05:08:54 +00003208}
3209
3210// An uncopyable class.
3211class Uncopyable {
3212 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003213 explicit Uncopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003214
3215 int value() const { return value_; }
3216 private:
3217 const int value_;
3218 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3219};
3220
3221// Returns true iff x.value() is positive.
3222bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3223
3224// A user-defined struct for testing Field().
3225struct AStruct {
3226 AStruct() : x(0), y(1.0), z(5), p(NULL) {}
3227 AStruct(const AStruct& rhs)
3228 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3229
3230 int x; // A non-const field.
3231 const double y; // A const field.
3232 Uncopyable z; // An uncopyable field.
3233 const char* p; // A pointer field.
zhanyong.wan32de5f52009-12-23 00:13:23 +00003234
3235 private:
3236 GTEST_DISALLOW_ASSIGN_(AStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003237};
3238
3239// A derived struct for testing Field().
3240struct DerivedStruct : public AStruct {
3241 char ch;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003242
3243 private:
3244 GTEST_DISALLOW_ASSIGN_(DerivedStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003245};
3246
3247// Tests that Field(&Foo::field, ...) works when field is non-const.
3248TEST(FieldTest, WorksForNonConstField) {
3249 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
3250
3251 AStruct a;
3252 EXPECT_TRUE(m.Matches(a));
3253 a.x = -1;
3254 EXPECT_FALSE(m.Matches(a));
3255}
3256
3257// Tests that Field(&Foo::field, ...) works when field is const.
3258TEST(FieldTest, WorksForConstField) {
3259 AStruct a;
3260
3261 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
3262 EXPECT_TRUE(m.Matches(a));
3263 m = Field(&AStruct::y, Le(0.0));
3264 EXPECT_FALSE(m.Matches(a));
3265}
3266
3267// Tests that Field(&Foo::field, ...) works when field is not copyable.
3268TEST(FieldTest, WorksForUncopyableField) {
3269 AStruct a;
3270
3271 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3272 EXPECT_TRUE(m.Matches(a));
3273 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3274 EXPECT_FALSE(m.Matches(a));
3275}
3276
3277// Tests that Field(&Foo::field, ...) works when field is a pointer.
3278TEST(FieldTest, WorksForPointerField) {
3279 // Matching against NULL.
3280 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
3281 AStruct a;
3282 EXPECT_TRUE(m.Matches(a));
3283 a.p = "hi";
3284 EXPECT_FALSE(m.Matches(a));
3285
3286 // Matching a pointer that is not NULL.
3287 m = Field(&AStruct::p, StartsWith("hi"));
3288 a.p = "hill";
3289 EXPECT_TRUE(m.Matches(a));
3290 a.p = "hole";
3291 EXPECT_FALSE(m.Matches(a));
3292}
3293
3294// Tests that Field() works when the object is passed by reference.
3295TEST(FieldTest, WorksForByRefArgument) {
3296 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3297
3298 AStruct a;
3299 EXPECT_TRUE(m.Matches(a));
3300 a.x = -1;
3301 EXPECT_FALSE(m.Matches(a));
3302}
3303
3304// Tests that Field(&Foo::field, ...) works when the argument's type
3305// is a sub-type of Foo.
3306TEST(FieldTest, WorksForArgumentOfSubType) {
3307 // Note that the matcher expects DerivedStruct but we say AStruct
3308 // inside Field().
3309 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
3310
3311 DerivedStruct d;
3312 EXPECT_TRUE(m.Matches(d));
3313 d.x = -1;
3314 EXPECT_FALSE(m.Matches(d));
3315}
3316
3317// Tests that Field(&Foo::field, m) works when field's type and m's
3318// argument type are compatible but not the same.
3319TEST(FieldTest, WorksForCompatibleMatcherType) {
3320 // The field is an int, but the inner matcher expects a signed char.
3321 Matcher<const AStruct&> m = Field(&AStruct::x,
3322 Matcher<signed char>(Ge(0)));
3323
3324 AStruct a;
3325 EXPECT_TRUE(m.Matches(a));
3326 a.x = -1;
3327 EXPECT_FALSE(m.Matches(a));
3328}
3329
3330// Tests that Field() can describe itself.
3331TEST(FieldTest, CanDescribeSelf) {
3332 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3333
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003334 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3335 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003336}
3337
3338// Tests that Field() can explain the match result.
3339TEST(FieldTest, CanExplainMatchResult) {
3340 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3341
3342 AStruct a;
3343 a.x = 1;
zhanyong.wan736baa82010-09-27 17:44:16 +00003344 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003345
3346 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003347 EXPECT_EQ(
3348 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
3349 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003350}
3351
3352// Tests that Field() works when the argument is a pointer to const.
3353TEST(FieldForPointerTest, WorksForPointerToConst) {
3354 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3355
3356 AStruct a;
3357 EXPECT_TRUE(m.Matches(&a));
3358 a.x = -1;
3359 EXPECT_FALSE(m.Matches(&a));
3360}
3361
3362// Tests that Field() works when the argument is a pointer to non-const.
3363TEST(FieldForPointerTest, WorksForPointerToNonConst) {
3364 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
3365
3366 AStruct a;
3367 EXPECT_TRUE(m.Matches(&a));
3368 a.x = -1;
3369 EXPECT_FALSE(m.Matches(&a));
3370}
3371
zhanyong.wan6953a722010-01-13 05:15:07 +00003372// Tests that Field() works when the argument is a reference to a const pointer.
3373TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
3374 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
3375
3376 AStruct a;
3377 EXPECT_TRUE(m.Matches(&a));
3378 a.x = -1;
3379 EXPECT_FALSE(m.Matches(&a));
3380}
3381
shiqiane35fdd92008-12-10 05:08:54 +00003382// Tests that Field() does not match the NULL pointer.
3383TEST(FieldForPointerTest, DoesNotMatchNull) {
3384 Matcher<const AStruct*> m = Field(&AStruct::x, _);
3385 EXPECT_FALSE(m.Matches(NULL));
3386}
3387
3388// Tests that Field(&Foo::field, ...) works when the argument's type
3389// is a sub-type of const Foo*.
3390TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
3391 // Note that the matcher expects DerivedStruct but we say AStruct
3392 // inside Field().
3393 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
3394
3395 DerivedStruct d;
3396 EXPECT_TRUE(m.Matches(&d));
3397 d.x = -1;
3398 EXPECT_FALSE(m.Matches(&d));
3399}
3400
3401// Tests that Field() can describe itself when used to match a pointer.
3402TEST(FieldForPointerTest, CanDescribeSelf) {
3403 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3404
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003405 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3406 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003407}
3408
3409// Tests that Field() can explain the result of matching a pointer.
3410TEST(FieldForPointerTest, CanExplainMatchResult) {
3411 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3412
3413 AStruct a;
3414 a.x = 1;
3415 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003416 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
3417 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003418
3419 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003420 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
3421 ", which is 1 more than 0", Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003422}
3423
3424// A user-defined class for testing Property().
3425class AClass {
3426 public:
3427 AClass() : n_(0) {}
3428
3429 // A getter that returns a non-reference.
3430 int n() const { return n_; }
3431
3432 void set_n(int new_n) { n_ = new_n; }
3433
3434 // A getter that returns a reference to const.
3435 const string& s() const { return s_; }
3436
3437 void set_s(const string& new_s) { s_ = new_s; }
3438
3439 // A getter that returns a reference to non-const.
3440 double& x() const { return x_; }
3441 private:
3442 int n_;
3443 string s_;
3444
3445 static double x_;
3446};
3447
3448double AClass::x_ = 0.0;
3449
3450// A derived class for testing Property().
3451class DerivedClass : public AClass {
kosak6414d802013-12-03 23:19:36 +00003452 public:
3453 int k() const { return k_; }
shiqiane35fdd92008-12-10 05:08:54 +00003454 private:
3455 int k_;
3456};
3457
3458// Tests that Property(&Foo::property, ...) works when property()
3459// returns a non-reference.
3460TEST(PropertyTest, WorksForNonReferenceProperty) {
3461 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3462
3463 AClass a;
3464 a.set_n(1);
3465 EXPECT_TRUE(m.Matches(a));
3466
3467 a.set_n(-1);
3468 EXPECT_FALSE(m.Matches(a));
3469}
3470
3471// Tests that Property(&Foo::property, ...) works when property()
3472// returns a reference to const.
3473TEST(PropertyTest, WorksForReferenceToConstProperty) {
3474 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
3475
3476 AClass a;
3477 a.set_s("hill");
3478 EXPECT_TRUE(m.Matches(a));
3479
3480 a.set_s("hole");
3481 EXPECT_FALSE(m.Matches(a));
3482}
3483
3484// Tests that Property(&Foo::property, ...) works when property()
3485// returns a reference to non-const.
3486TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
3487 double x = 0.0;
3488 AClass a;
3489
3490 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
3491 EXPECT_FALSE(m.Matches(a));
3492
3493 m = Property(&AClass::x, Not(Ref(x)));
3494 EXPECT_TRUE(m.Matches(a));
3495}
3496
3497// Tests that Property(&Foo::property, ...) works when the argument is
3498// passed by value.
3499TEST(PropertyTest, WorksForByValueArgument) {
3500 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
3501
3502 AClass a;
3503 a.set_s("hill");
3504 EXPECT_TRUE(m.Matches(a));
3505
3506 a.set_s("hole");
3507 EXPECT_FALSE(m.Matches(a));
3508}
3509
3510// Tests that Property(&Foo::property, ...) works when the argument's
3511// type is a sub-type of Foo.
3512TEST(PropertyTest, WorksForArgumentOfSubType) {
3513 // The matcher expects a DerivedClass, but inside the Property() we
3514 // say AClass.
3515 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
3516
3517 DerivedClass d;
3518 d.set_n(1);
3519 EXPECT_TRUE(m.Matches(d));
3520
3521 d.set_n(-1);
3522 EXPECT_FALSE(m.Matches(d));
3523}
3524
3525// Tests that Property(&Foo::property, m) works when property()'s type
3526// and m's argument type are compatible but different.
3527TEST(PropertyTest, WorksForCompatibleMatcherType) {
3528 // n() returns an int but the inner matcher expects a signed char.
3529 Matcher<const AClass&> m = Property(&AClass::n,
3530 Matcher<signed char>(Ge(0)));
3531
3532 AClass a;
3533 EXPECT_TRUE(m.Matches(a));
3534 a.set_n(-1);
3535 EXPECT_FALSE(m.Matches(a));
3536}
3537
3538// Tests that Property() can describe itself.
3539TEST(PropertyTest, CanDescribeSelf) {
3540 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3541
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003542 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3543 EXPECT_EQ("is an object whose given property isn't >= 0",
3544 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003545}
3546
3547// Tests that Property() can explain the match result.
3548TEST(PropertyTest, CanExplainMatchResult) {
3549 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3550
3551 AClass a;
3552 a.set_n(1);
zhanyong.wan736baa82010-09-27 17:44:16 +00003553 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003554
3555 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003556 EXPECT_EQ(
3557 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
3558 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003559}
3560
3561// Tests that Property() works when the argument is a pointer to const.
3562TEST(PropertyForPointerTest, WorksForPointerToConst) {
3563 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3564
3565 AClass a;
3566 a.set_n(1);
3567 EXPECT_TRUE(m.Matches(&a));
3568
3569 a.set_n(-1);
3570 EXPECT_FALSE(m.Matches(&a));
3571}
3572
3573// Tests that Property() works when the argument is a pointer to non-const.
3574TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
3575 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
3576
3577 AClass a;
3578 a.set_s("hill");
3579 EXPECT_TRUE(m.Matches(&a));
3580
3581 a.set_s("hole");
3582 EXPECT_FALSE(m.Matches(&a));
3583}
3584
zhanyong.wan6953a722010-01-13 05:15:07 +00003585// Tests that Property() works when the argument is a reference to a
3586// const pointer.
3587TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
3588 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
3589
3590 AClass a;
3591 a.set_s("hill");
3592 EXPECT_TRUE(m.Matches(&a));
3593
3594 a.set_s("hole");
3595 EXPECT_FALSE(m.Matches(&a));
3596}
3597
shiqiane35fdd92008-12-10 05:08:54 +00003598// Tests that Property() does not match the NULL pointer.
3599TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
3600 Matcher<const AClass*> m = Property(&AClass::x, _);
3601 EXPECT_FALSE(m.Matches(NULL));
3602}
3603
3604// Tests that Property(&Foo::property, ...) works when the argument's
3605// type is a sub-type of const Foo*.
3606TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
3607 // The matcher expects a DerivedClass, but inside the Property() we
3608 // say AClass.
3609 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
3610
3611 DerivedClass d;
3612 d.set_n(1);
3613 EXPECT_TRUE(m.Matches(&d));
3614
3615 d.set_n(-1);
3616 EXPECT_FALSE(m.Matches(&d));
3617}
3618
3619// Tests that Property() can describe itself when used to match a pointer.
3620TEST(PropertyForPointerTest, CanDescribeSelf) {
3621 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3622
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003623 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3624 EXPECT_EQ("is an object whose given property isn't >= 0",
3625 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003626}
3627
3628// Tests that Property() can explain the result of matching a pointer.
3629TEST(PropertyForPointerTest, CanExplainMatchResult) {
3630 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3631
3632 AClass a;
3633 a.set_n(1);
3634 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003635 EXPECT_EQ(
3636 "which points to an object whose given property is 1" + OfType("int"),
3637 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003638
3639 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003640 EXPECT_EQ("which points to an object whose given property is 1" +
3641 OfType("int") + ", which is 1 more than 0",
3642 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003643}
3644
3645// Tests ResultOf.
3646
3647// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3648// function pointer.
3649string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; }
3650
3651TEST(ResultOfTest, WorksForFunctionPointers) {
3652 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo")));
3653
3654 EXPECT_TRUE(matcher.Matches(1));
3655 EXPECT_FALSE(matcher.Matches(2));
3656}
3657
3658// Tests that ResultOf() can describe itself.
3659TEST(ResultOfTest, CanDescribeItself) {
3660 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
3661
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003662 EXPECT_EQ("is mapped by the given callable to a value that "
3663 "is equal to \"foo\"", Describe(matcher));
3664 EXPECT_EQ("is mapped by the given callable to a value that "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003665 "isn't equal to \"foo\"", DescribeNegation(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00003666}
3667
3668// Tests that ResultOf() can explain the match result.
3669int IntFunction(int input) { return input == 42 ? 80 : 90; }
3670
3671TEST(ResultOfTest, CanExplainMatchResult) {
3672 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003673 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003674 Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003675
3676 matcher = ResultOf(&IntFunction, GreaterThan(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003677 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
3678 ", which is 5 more than 85", Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003679}
3680
3681// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3682// returns a non-reference.
3683TEST(ResultOfTest, WorksForNonReferenceResults) {
3684 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
3685
3686 EXPECT_TRUE(matcher.Matches(42));
3687 EXPECT_FALSE(matcher.Matches(36));
3688}
3689
3690// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3691// returns a reference to non-const.
zhanyong.wan736baa82010-09-27 17:44:16 +00003692double& DoubleFunction(double& input) { return input; } // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003693
zhanyong.wan736baa82010-09-27 17:44:16 +00003694Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003695 return obj;
3696}
3697
3698TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
3699 double x = 3.14;
3700 double x2 = x;
3701 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
3702
3703 EXPECT_TRUE(matcher.Matches(x));
3704 EXPECT_FALSE(matcher.Matches(x2));
3705
3706 // Test that ResultOf works with uncopyable objects
3707 Uncopyable obj(0);
3708 Uncopyable obj2(0);
3709 Matcher<Uncopyable&> matcher2 =
3710 ResultOf(&RefUncopyableFunction, Ref(obj));
3711
3712 EXPECT_TRUE(matcher2.Matches(obj));
3713 EXPECT_FALSE(matcher2.Matches(obj2));
3714}
3715
3716// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3717// returns a reference to const.
3718const string& StringFunction(const string& input) { return input; }
3719
3720TEST(ResultOfTest, WorksForReferenceToConstResults) {
3721 string s = "foo";
3722 string s2 = s;
3723 Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s));
3724
3725 EXPECT_TRUE(matcher.Matches(s));
3726 EXPECT_FALSE(matcher.Matches(s2));
3727}
3728
3729// Tests that ResultOf(f, m) works when f(x) and m's
3730// argument types are compatible but different.
3731TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
3732 // IntFunction() returns int but the inner matcher expects a signed char.
3733 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
3734
3735 EXPECT_TRUE(matcher.Matches(36));
3736 EXPECT_FALSE(matcher.Matches(42));
3737}
3738
shiqiane35fdd92008-12-10 05:08:54 +00003739// Tests that the program aborts when ResultOf is passed
3740// a NULL function pointer.
3741TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
zhanyong.wan04d6ed82009-09-11 07:01:08 +00003742 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan736baa82010-09-27 17:44:16 +00003743 ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))),
shiqiane35fdd92008-12-10 05:08:54 +00003744 "NULL function pointer is passed into ResultOf\\(\\)\\.");
3745}
shiqiane35fdd92008-12-10 05:08:54 +00003746
3747// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3748// function reference.
3749TEST(ResultOfTest, WorksForFunctionReferences) {
3750 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
3751 EXPECT_TRUE(matcher.Matches(1));
3752 EXPECT_FALSE(matcher.Matches(2));
3753}
3754
3755// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3756// function object.
3757struct Functor : public ::std::unary_function<int, string> {
3758 result_type operator()(argument_type input) const {
3759 return IntToStringFunction(input);
3760 }
3761};
3762
3763TEST(ResultOfTest, WorksForFunctors) {
3764 Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo")));
3765
3766 EXPECT_TRUE(matcher.Matches(1));
3767 EXPECT_FALSE(matcher.Matches(2));
3768}
3769
3770// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3771// functor with more then one operator() defined. ResultOf() must work
3772// for each defined operator().
3773struct PolymorphicFunctor {
3774 typedef int result_type;
3775 int operator()(int n) { return n; }
3776 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
3777};
3778
3779TEST(ResultOfTest, WorksForPolymorphicFunctors) {
3780 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
3781
3782 EXPECT_TRUE(matcher_int.Matches(10));
3783 EXPECT_FALSE(matcher_int.Matches(2));
3784
3785 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
3786
3787 EXPECT_TRUE(matcher_string.Matches("long string"));
3788 EXPECT_FALSE(matcher_string.Matches("shrt"));
3789}
3790
3791const int* ReferencingFunction(const int& n) { return &n; }
3792
3793struct ReferencingFunctor {
3794 typedef const int* result_type;
3795 result_type operator()(const int& n) { return &n; }
3796};
3797
3798TEST(ResultOfTest, WorksForReferencingCallables) {
3799 const int n = 1;
3800 const int n2 = 1;
3801 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
3802 EXPECT_TRUE(matcher2.Matches(n));
3803 EXPECT_FALSE(matcher2.Matches(n2));
3804
3805 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
3806 EXPECT_TRUE(matcher3.Matches(n));
3807 EXPECT_FALSE(matcher3.Matches(n2));
3808}
3809
shiqiane35fdd92008-12-10 05:08:54 +00003810class DivisibleByImpl {
3811 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003812 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
shiqiane35fdd92008-12-10 05:08:54 +00003813
zhanyong.wandb22c222010-01-28 21:52:29 +00003814 // For testing using ExplainMatchResultTo() with polymorphic matchers.
shiqiane35fdd92008-12-10 05:08:54 +00003815 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00003816 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003817 *listener << "which is " << (n % divider_) << " modulo "
zhanyong.wandb22c222010-01-28 21:52:29 +00003818 << divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003819 return (n % divider_) == 0;
3820 }
3821
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003822 void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003823 *os << "is divisible by " << divider_;
3824 }
3825
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003826 void DescribeNegationTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003827 *os << "is not divisible by " << divider_;
3828 }
3829
zhanyong.wan32de5f52009-12-23 00:13:23 +00003830 void set_divider(int a_divider) { divider_ = a_divider; }
shiqiane35fdd92008-12-10 05:08:54 +00003831 int divider() const { return divider_; }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003832
shiqiane35fdd92008-12-10 05:08:54 +00003833 private:
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003834 int divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003835};
3836
shiqiane35fdd92008-12-10 05:08:54 +00003837PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
3838 return MakePolymorphicMatcher(DivisibleByImpl(n));
3839}
3840
3841// Tests that when AllOf() fails, only the first failing matcher is
3842// asked to explain why.
3843TEST(ExplainMatchResultTest, AllOf_False_False) {
3844 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003845 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00003846}
3847
3848// Tests that when AllOf() fails, only the first failing matcher is
3849// asked to explain why.
3850TEST(ExplainMatchResultTest, AllOf_False_True) {
3851 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003852 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003853}
3854
3855// Tests that when AllOf() fails, only the first failing matcher is
3856// asked to explain why.
3857TEST(ExplainMatchResultTest, AllOf_True_False) {
3858 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003859 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00003860}
3861
3862// Tests that when AllOf() succeeds, all matchers are asked to explain
3863// why.
3864TEST(ExplainMatchResultTest, AllOf_True_True) {
3865 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003866 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003867}
3868
3869TEST(ExplainMatchResultTest, AllOf_True_True_2) {
3870 const Matcher<int> m = AllOf(Ge(2), Le(3));
3871 EXPECT_EQ("", Explain(m, 2));
3872}
3873
3874TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
3875 const Matcher<int> m = GreaterThan(5);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003876 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003877}
3878
3879// The following two tests verify that values without a public copy
3880// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
3881// with the help of ByRef().
3882
3883class NotCopyable {
3884 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003885 explicit NotCopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003886
3887 int value() const { return value_; }
3888
3889 bool operator==(const NotCopyable& rhs) const {
3890 return value() == rhs.value();
3891 }
3892
3893 bool operator>=(const NotCopyable& rhs) const {
3894 return value() >= rhs.value();
3895 }
3896 private:
3897 int value_;
3898
3899 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
3900};
3901
3902TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
3903 const NotCopyable const_value1(1);
3904 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
3905
3906 const NotCopyable n1(1), n2(2);
3907 EXPECT_TRUE(m.Matches(n1));
3908 EXPECT_FALSE(m.Matches(n2));
3909}
3910
3911TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
3912 NotCopyable value2(2);
3913 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
3914
3915 NotCopyable n1(1), n2(2);
3916 EXPECT_FALSE(m.Matches(n1));
3917 EXPECT_TRUE(m.Matches(n2));
3918}
3919
zhanyong.wan320814a2013-03-01 00:20:30 +00003920TEST(IsEmptyTest, ImplementsIsEmpty) {
3921 vector<int> container;
3922 EXPECT_THAT(container, IsEmpty());
3923 container.push_back(0);
3924 EXPECT_THAT(container, Not(IsEmpty()));
3925 container.push_back(1);
3926 EXPECT_THAT(container, Not(IsEmpty()));
3927}
3928
3929TEST(IsEmptyTest, WorksWithString) {
3930 string text;
3931 EXPECT_THAT(text, IsEmpty());
3932 text = "foo";
3933 EXPECT_THAT(text, Not(IsEmpty()));
3934 text = string("\0", 1);
3935 EXPECT_THAT(text, Not(IsEmpty()));
3936}
3937
3938TEST(IsEmptyTest, CanDescribeSelf) {
3939 Matcher<vector<int> > m = IsEmpty();
3940 EXPECT_EQ("is empty", Describe(m));
3941 EXPECT_EQ("isn't empty", DescribeNegation(m));
3942}
3943
3944TEST(IsEmptyTest, ExplainsResult) {
3945 Matcher<vector<int> > m = IsEmpty();
3946 vector<int> container;
3947 EXPECT_EQ("", Explain(m, container));
3948 container.push_back(0);
3949 EXPECT_EQ("whose size is 1", Explain(m, container));
3950}
3951
zhanyong.wana31d9ce2013-03-01 01:50:17 +00003952TEST(SizeIsTest, ImplementsSizeIs) {
3953 vector<int> container;
3954 EXPECT_THAT(container, SizeIs(0));
3955 EXPECT_THAT(container, Not(SizeIs(1)));
3956 container.push_back(0);
3957 EXPECT_THAT(container, Not(SizeIs(0)));
3958 EXPECT_THAT(container, SizeIs(1));
3959 container.push_back(0);
3960 EXPECT_THAT(container, Not(SizeIs(0)));
3961 EXPECT_THAT(container, SizeIs(2));
3962}
3963
3964TEST(SizeIsTest, WorksWithMap) {
3965 map<string, int> container;
3966 EXPECT_THAT(container, SizeIs(0));
3967 EXPECT_THAT(container, Not(SizeIs(1)));
3968 container.insert(make_pair("foo", 1));
3969 EXPECT_THAT(container, Not(SizeIs(0)));
3970 EXPECT_THAT(container, SizeIs(1));
3971 container.insert(make_pair("bar", 2));
3972 EXPECT_THAT(container, Not(SizeIs(0)));
3973 EXPECT_THAT(container, SizeIs(2));
3974}
3975
3976TEST(SizeIsTest, WorksWithReferences) {
3977 vector<int> container;
3978 Matcher<const vector<int>&> m = SizeIs(1);
3979 EXPECT_THAT(container, Not(m));
3980 container.push_back(0);
3981 EXPECT_THAT(container, m);
3982}
3983
3984TEST(SizeIsTest, CanDescribeSelf) {
3985 Matcher<vector<int> > m = SizeIs(2);
3986 EXPECT_EQ("size is equal to 2", Describe(m));
3987 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
3988}
3989
3990TEST(SizeIsTest, ExplainsResult) {
3991 Matcher<vector<int> > m1 = SizeIs(2);
3992 Matcher<vector<int> > m2 = SizeIs(Lt(2u));
3993 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
3994 Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
3995 vector<int> container;
3996 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
3997 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
3998 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
3999 EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
4000 Explain(m4, container));
4001 container.push_back(0);
4002 container.push_back(0);
4003 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
4004 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
4005 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
4006 EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
4007 Explain(m4, container));
4008}
4009
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004010#if GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004011// Tests ContainerEq with different container types, and
4012// different element types.
4013
4014template <typename T>
zhanyong.wanb8243162009-06-04 05:48:20 +00004015class ContainerEqTest : public testing::Test {};
zhanyong.wan6a896b52009-01-16 01:13:50 +00004016
4017typedef testing::Types<
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004018 set<int>,
4019 vector<size_t>,
4020 multiset<size_t>,
4021 list<int> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004022 ContainerEqTestTypes;
4023
4024TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
4025
4026// Tests that the filled container is equal to itself.
4027TYPED_TEST(ContainerEqTest, EqualsSelf) {
4028 static const int vals[] = {1, 1, 2, 3, 5, 8};
4029 TypeParam my_set(vals, vals + 6);
4030 const Matcher<TypeParam> m = ContainerEq(my_set);
4031 EXPECT_TRUE(m.Matches(my_set));
4032 EXPECT_EQ("", Explain(m, my_set));
4033}
4034
4035// Tests that missing values are reported.
4036TYPED_TEST(ContainerEqTest, ValueMissing) {
4037 static const int vals[] = {1, 1, 2, 3, 5, 8};
4038 static const int test_vals[] = {2, 1, 8, 5};
4039 TypeParam my_set(vals, vals + 6);
4040 TypeParam test_set(test_vals, test_vals + 4);
4041 const Matcher<TypeParam> m = ContainerEq(my_set);
4042 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004043 EXPECT_EQ("which doesn't have these expected elements: 3",
4044 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004045}
4046
4047// Tests that added values are reported.
4048TYPED_TEST(ContainerEqTest, ValueAdded) {
4049 static const int vals[] = {1, 1, 2, 3, 5, 8};
4050 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4051 TypeParam my_set(vals, vals + 6);
4052 TypeParam test_set(test_vals, test_vals + 6);
4053 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4054 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004055 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004056}
4057
4058// Tests that added and missing values are reported together.
4059TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4060 static const int vals[] = {1, 1, 2, 3, 5, 8};
4061 static const int test_vals[] = {1, 2, 3, 8, 46};
4062 TypeParam my_set(vals, vals + 6);
4063 TypeParam test_set(test_vals, test_vals + 5);
4064 const Matcher<TypeParam> m = ContainerEq(my_set);
4065 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004066 EXPECT_EQ("which has these unexpected elements: 46,\n"
4067 "and doesn't have these expected elements: 5",
4068 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004069}
4070
4071// Tests duplicated value -- expect no explanation.
4072TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4073 static const int vals[] = {1, 1, 2, 3, 5, 8};
4074 static const int test_vals[] = {1, 2, 3, 5, 8};
4075 TypeParam my_set(vals, vals + 6);
4076 TypeParam test_set(test_vals, test_vals + 5);
4077 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4078 // Depending on the container, match may be true or false
4079 // But in any case there should be no explanation.
4080 EXPECT_EQ("", Explain(m, test_set));
4081}
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004082#endif // GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004083
4084// Tests that mutliple missing values are reported.
4085// Using just vector here, so order is predicatble.
4086TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4087 static const int vals[] = {1, 1, 2, 3, 5, 8};
4088 static const int test_vals[] = {2, 1, 5};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004089 vector<int> my_set(vals, vals + 6);
4090 vector<int> test_set(test_vals, test_vals + 3);
4091 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004092 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004093 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4094 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004095}
4096
4097// Tests that added values are reported.
4098// Using just vector here, so order is predicatble.
4099TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4100 static const int vals[] = {1, 1, 2, 3, 5, 8};
4101 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004102 list<size_t> my_set(vals, vals + 6);
4103 list<size_t> test_set(test_vals, test_vals + 7);
4104 const Matcher<const list<size_t>&> m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004105 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004106 EXPECT_EQ("which has these unexpected elements: 92, 46",
4107 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004108}
4109
4110// Tests that added and missing values are reported together.
4111TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
4112 static const int vals[] = {1, 1, 2, 3, 5, 8};
4113 static const int test_vals[] = {1, 2, 3, 92, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004114 list<size_t> my_set(vals, vals + 6);
4115 list<size_t> test_set(test_vals, test_vals + 5);
4116 const Matcher<const list<size_t> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004117 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004118 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4119 "and doesn't have these expected elements: 5, 8",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004120 Explain(m, test_set));
4121}
4122
4123// Tests to see that duplicate elements are detected,
4124// but (as above) not reported in the explanation.
4125TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
4126 static const int vals[] = {1, 1, 2, 3, 5, 8};
4127 static const int test_vals[] = {1, 2, 3, 5, 8};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004128 vector<int> my_set(vals, vals + 6);
4129 vector<int> test_set(test_vals, test_vals + 5);
4130 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004131 EXPECT_TRUE(m.Matches(my_set));
4132 EXPECT_FALSE(m.Matches(test_set));
4133 // There is nothing to report when both sets contain all the same values.
4134 EXPECT_EQ("", Explain(m, test_set));
4135}
4136
4137// Tests that ContainerEq works for non-trivial associative containers,
4138// like maps.
4139TEST(ContainerEqExtraTest, WorksForMaps) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004140 map<int, std::string> my_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004141 my_map[0] = "a";
4142 my_map[1] = "b";
4143
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004144 map<int, std::string> test_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004145 test_map[0] = "aa";
4146 test_map[1] = "b";
4147
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004148 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004149 EXPECT_TRUE(m.Matches(my_map));
4150 EXPECT_FALSE(m.Matches(test_map));
4151
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004152 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
4153 "and doesn't have these expected elements: (0, \"a\")",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004154 Explain(m, test_map));
4155}
4156
zhanyong.wanb8243162009-06-04 05:48:20 +00004157TEST(ContainerEqExtraTest, WorksForNativeArray) {
4158 int a1[] = { 1, 2, 3 };
4159 int a2[] = { 1, 2, 3 };
4160 int b[] = { 1, 2, 4 };
4161
4162 EXPECT_THAT(a1, ContainerEq(a2));
4163 EXPECT_THAT(a1, Not(ContainerEq(b)));
4164}
4165
4166TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
4167 const char a1[][3] = { "hi", "lo" };
4168 const char a2[][3] = { "hi", "lo" };
4169 const char b[][3] = { "lo", "hi" };
4170
4171 // Tests using ContainerEq() in the first dimension.
4172 EXPECT_THAT(a1, ContainerEq(a2));
4173 EXPECT_THAT(a1, Not(ContainerEq(b)));
4174
4175 // Tests using ContainerEq() in the second dimension.
4176 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
4177 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
4178}
4179
4180TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
4181 const int a1[] = { 1, 2, 3 };
4182 const int a2[] = { 1, 2, 3 };
4183 const int b[] = { 1, 2, 3, 4 };
4184
zhanyong.wan2661c682009-06-09 05:42:12 +00004185 const int* const p1 = a1;
4186 EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
4187 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004188
4189 const int c[] = { 1, 3, 2 };
zhanyong.wan2661c682009-06-09 05:42:12 +00004190 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004191}
4192
4193TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
4194 std::string a1[][3] = {
4195 { "hi", "hello", "ciao" },
4196 { "bye", "see you", "ciao" }
4197 };
4198
4199 std::string a2[][3] = {
4200 { "hi", "hello", "ciao" },
4201 { "bye", "see you", "ciao" }
4202 };
4203
4204 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
4205 EXPECT_THAT(a1, m);
4206
4207 a2[0][0] = "ha";
4208 EXPECT_THAT(a1, m);
4209}
4210
zhanyong.wan898725c2011-09-16 16:45:39 +00004211TEST(WhenSortedByTest, WorksForEmptyContainer) {
4212 const vector<int> numbers;
4213 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
4214 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
4215}
4216
4217TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
4218 vector<unsigned> numbers;
4219 numbers.push_back(3);
4220 numbers.push_back(1);
4221 numbers.push_back(2);
4222 numbers.push_back(2);
4223 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
4224 ElementsAre(3, 2, 2, 1)));
4225 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
4226 ElementsAre(1, 2, 2, 3))));
4227}
4228
4229TEST(WhenSortedByTest, WorksForNonVectorContainer) {
4230 list<string> words;
4231 words.push_back("say");
4232 words.push_back("hello");
4233 words.push_back("world");
4234 EXPECT_THAT(words, WhenSortedBy(less<string>(),
4235 ElementsAre("hello", "say", "world")));
4236 EXPECT_THAT(words, Not(WhenSortedBy(less<string>(),
4237 ElementsAre("say", "hello", "world"))));
4238}
4239
4240TEST(WhenSortedByTest, WorksForNativeArray) {
4241 const int numbers[] = { 1, 3, 2, 4 };
4242 const int sorted_numbers[] = { 1, 2, 3, 4 };
4243 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
4244 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
4245 ElementsAreArray(sorted_numbers)));
4246 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
4247}
4248
4249TEST(WhenSortedByTest, CanDescribeSelf) {
4250 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
4251 EXPECT_EQ("(when sorted) has 2 elements where\n"
4252 "element #0 is equal to 1,\n"
4253 "element #1 is equal to 2",
4254 Describe(m));
4255 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
4256 "element #0 isn't equal to 1, or\n"
4257 "element #1 isn't equal to 2",
4258 DescribeNegation(m));
4259}
4260
4261TEST(WhenSortedByTest, ExplainsMatchResult) {
4262 const int a[] = { 2, 1 };
4263 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
4264 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
4265 EXPECT_EQ("which is { 1, 2 } when sorted",
4266 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
4267}
4268
4269// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
4270// need to test it as exhaustively as we test the latter.
4271
4272TEST(WhenSortedTest, WorksForEmptyContainer) {
4273 const vector<int> numbers;
4274 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
4275 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
4276}
4277
4278TEST(WhenSortedTest, WorksForNonEmptyContainer) {
4279 list<string> words;
4280 words.push_back("3");
4281 words.push_back("1");
4282 words.push_back("2");
4283 words.push_back("2");
4284 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
4285 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
4286}
4287
zhanyong.wana9a59e02013-03-27 16:14:55 +00004288TEST(WhenSortedTest, WorksForMapTypes) {
4289 map<string, int> word_counts;
4290 word_counts["and"] = 1;
4291 word_counts["the"] = 1;
4292 word_counts["buffalo"] = 2;
4293 EXPECT_THAT(word_counts, WhenSorted(ElementsAre(
4294 Pair("and", 1), Pair("buffalo", 2), Pair("the", 1))));
4295 EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre(
4296 Pair("and", 1), Pair("the", 1), Pair("buffalo", 2)))));
4297}
4298
4299TEST(WhenSortedTest, WorksForMultiMapTypes) {
4300 multimap<int, int> ifib;
4301 ifib.insert(make_pair(8, 6));
4302 ifib.insert(make_pair(2, 3));
4303 ifib.insert(make_pair(1, 1));
4304 ifib.insert(make_pair(3, 4));
4305 ifib.insert(make_pair(1, 2));
4306 ifib.insert(make_pair(5, 5));
4307 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
4308 Pair(1, 2),
4309 Pair(2, 3),
4310 Pair(3, 4),
4311 Pair(5, 5),
4312 Pair(8, 6))));
4313 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
4314 Pair(2, 3),
4315 Pair(1, 1),
4316 Pair(3, 4),
4317 Pair(1, 2),
4318 Pair(5, 5)))));
4319}
4320
4321TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
4322 std::deque<int> d;
4323 d.push_back(2);
4324 d.push_back(1);
4325 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
4326 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
4327}
4328
4329TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
4330 std::deque<int> d;
4331 d.push_back(2);
4332 d.push_back(1);
4333 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
4334 EXPECT_THAT(d, WhenSorted(vector_match));
4335 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
4336 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
4337}
4338
4339// Deliberately bare pseudo-container.
4340// Offers only begin() and end() accessors, yielding InputIterator.
4341template <typename T>
4342class Streamlike {
4343 private:
4344 class ConstIter;
4345 public:
4346 typedef ConstIter const_iterator;
4347 typedef T value_type;
4348
4349 template <typename InIter>
4350 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
4351
4352 const_iterator begin() const {
4353 return const_iterator(this, remainder_.begin());
4354 }
4355 const_iterator end() const {
4356 return const_iterator(this, remainder_.end());
4357 }
4358
4359 private:
4360 class ConstIter : public std::iterator<std::input_iterator_tag,
4361 value_type,
4362 ptrdiff_t,
4363 const value_type&,
4364 const value_type*> {
4365 public:
4366 ConstIter(const Streamlike* s,
4367 typename std::list<value_type>::iterator pos)
4368 : s_(s), pos_(pos) {}
4369
4370 const value_type& operator*() const { return *pos_; }
4371 const value_type* operator->() const { return &*pos_; }
4372 ConstIter& operator++() {
4373 s_->remainder_.erase(pos_++);
4374 return *this;
4375 }
4376
4377 // *iter++ is required to work (see std::istreambuf_iterator).
4378 // (void)iter++ is also required to work.
4379 class PostIncrProxy {
4380 public:
4381 explicit PostIncrProxy(const value_type& value) : value_(value) {}
4382 value_type operator*() const { return value_; }
4383 private:
4384 value_type value_;
4385 };
4386 PostIncrProxy operator++(int) {
4387 PostIncrProxy proxy(**this);
4388 ++(*this);
4389 return proxy;
4390 }
4391
4392 friend bool operator==(const ConstIter& a, const ConstIter& b) {
4393 return a.s_ == b.s_ && a.pos_ == b.pos_;
4394 }
4395 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
4396 return !(a == b);
4397 }
4398
4399 private:
4400 const Streamlike* s_;
4401 typename std::list<value_type>::iterator pos_;
4402 };
4403
4404 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
4405 os << "[";
4406 typedef typename std::list<value_type>::const_iterator Iter;
4407 const char* sep = "";
4408 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
4409 os << sep << *it;
4410 sep = ",";
4411 }
4412 os << "]";
4413 return os;
4414 }
4415
4416 mutable std::list<value_type> remainder_; // modified by iteration
4417};
4418
4419TEST(StreamlikeTest, Iteration) {
4420 const int a[5] = { 2, 1, 4, 5, 3 };
4421 Streamlike<int> s(a, a + 5);
4422 Streamlike<int>::const_iterator it = s.begin();
4423 const int* ip = a;
4424 while (it != s.end()) {
4425 SCOPED_TRACE(ip - a);
4426 EXPECT_EQ(*ip++, *it++);
4427 }
4428}
4429
kosakb6a34882014-03-12 21:06:46 +00004430#if GTEST_LANG_CXX11
4431TEST(BeginEndDistanceIsTest, WorksWithForwardList) {
4432 std::forward_list<int> container;
4433 EXPECT_THAT(container, BeginEndDistanceIs(0));
4434 EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));
4435 container.push_front(0);
4436 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4437 EXPECT_THAT(container, BeginEndDistanceIs(1));
4438 container.push_front(0);
4439 EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));
4440 EXPECT_THAT(container, BeginEndDistanceIs(2));
4441}
4442#endif // GTEST_LANG_CXX11
4443
4444TEST(BeginEndDistanceIsTest, WorksWithNonStdList) {
4445 const int a[5] = { 1, 2, 3, 4, 5 };
4446 Streamlike<int> s(a, a + 5);
4447 EXPECT_THAT(s, BeginEndDistanceIs(5));
4448}
4449
4450TEST(BeginEndDistanceIsTest, CanDescribeSelf) {
4451 Matcher<vector<int> > m = BeginEndDistanceIs(2);
4452 EXPECT_EQ("distance between begin() and end() is equal to 2", Describe(m));
4453 EXPECT_EQ("distance between begin() and end() isn't equal to 2",
4454 DescribeNegation(m));
4455}
4456
4457TEST(BeginEndDistanceIsTest, ExplainsResult) {
4458 Matcher<vector<int> > m1 = BeginEndDistanceIs(2);
4459 Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2));
4460 Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3));
4461 Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1));
4462 vector<int> container;
4463 EXPECT_EQ("whose distance between begin() and end() 0 doesn't match",
4464 Explain(m1, container));
4465 EXPECT_EQ("whose distance between begin() and end() 0 matches",
4466 Explain(m2, container));
4467 EXPECT_EQ("whose distance between begin() and end() 0 matches",
4468 Explain(m3, container));
4469 EXPECT_EQ(
4470 "whose distance between begin() and end() 0 doesn't match, which is 1 "
4471 "less than 1",
4472 Explain(m4, container));
4473 container.push_back(0);
4474 container.push_back(0);
4475 EXPECT_EQ("whose distance between begin() and end() 2 matches",
4476 Explain(m1, container));
4477 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4478 Explain(m2, container));
4479 EXPECT_EQ("whose distance between begin() and end() 2 doesn't match",
4480 Explain(m3, container));
4481 EXPECT_EQ(
4482 "whose distance between begin() and end() 2 matches, which is 1 more "
4483 "than 1",
4484 Explain(m4, container));
4485}
4486
zhanyong.wana9a59e02013-03-27 16:14:55 +00004487TEST(WhenSortedTest, WorksForStreamlike) {
4488 // Streamlike 'container' provides only minimal iterator support.
4489 // Its iterators are tagged with input_iterator_tag.
4490 const int a[5] = { 2, 1, 4, 5, 3 };
kosak6414d802013-12-03 23:19:36 +00004491 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004492 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
4493 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4494}
4495
4496TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00004497 const int a[] = { 2, 1, 4, 5, 3 };
kosak6414d802013-12-03 23:19:36 +00004498 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004499 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
4500 EXPECT_THAT(s, WhenSorted(vector_match));
4501 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4502}
4503
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004504// Tests using ElementsAre() and ElementsAreArray() with stream-like
4505// "containers".
4506
4507TEST(ElemensAreStreamTest, WorksForStreamlike) {
4508 const int a[5] = { 1, 2, 3, 4, 5 };
kosak6414d802013-12-03 23:19:36 +00004509 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004510 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
4511 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
4512}
4513
4514TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
4515 const int a[5] = { 1, 2, 3, 4, 5 };
kosak6414d802013-12-03 23:19:36 +00004516 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004517
4518 vector<int> expected;
4519 expected.push_back(1);
4520 expected.push_back(2);
4521 expected.push_back(3);
4522 expected.push_back(4);
4523 expected.push_back(5);
4524 EXPECT_THAT(s, ElementsAreArray(expected));
4525
4526 expected[3] = 0;
4527 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
4528}
4529
zhanyong.wanfb25d532013-07-28 08:24:00 +00004530// Tests for UnorderedElementsAreArray()
4531
4532TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
4533 const int a[] = { 0, 1, 2, 3, 4 };
kosak6414d802013-12-03 23:19:36 +00004534 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004535 do {
4536 StringMatchResultListener listener;
4537 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
4538 s, &listener)) << listener.str();
4539 } while (std::next_permutation(s.begin(), s.end()));
4540}
4541
4542TEST(UnorderedElementsAreArrayTest, VectorBool) {
4543 const bool a[] = { 0, 1, 0, 1, 1 };
4544 const bool b[] = { 1, 0, 1, 1, 0 };
kosak6414d802013-12-03 23:19:36 +00004545 std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a));
4546 std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004547 StringMatchResultListener listener;
4548 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
4549 actual, &listener)) << listener.str();
4550}
4551
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004552TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
4553 // Streamlike 'container' provides only minimal iterator support.
4554 // Its iterators are tagged with input_iterator_tag, and it has no
4555 // size() or empty() methods.
4556 const int a[5] = { 2, 1, 4, 5, 3 };
kosak6414d802013-12-03 23:19:36 +00004557 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004558
4559 ::std::vector<int> expected;
4560 expected.push_back(1);
4561 expected.push_back(2);
4562 expected.push_back(3);
4563 expected.push_back(4);
4564 expected.push_back(5);
4565 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
4566
4567 expected.push_back(6);
4568 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
4569}
4570
kosak18489fa2013-12-04 23:49:07 +00004571#if GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004572
4573TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
4574 const int a[5] = { 2, 1, 4, 5, 3 };
4575 EXPECT_THAT(a, UnorderedElementsAreArray({ 1, 2, 3, 4, 5 }));
4576 EXPECT_THAT(a, Not(UnorderedElementsAreArray({ 1, 2, 3, 4, 6 })));
4577}
4578
4579TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
4580 const string a[5] = { "a", "b", "c", "d", "e" };
4581 EXPECT_THAT(a, UnorderedElementsAreArray({ "a", "b", "c", "d", "e" }));
4582 EXPECT_THAT(a, Not(UnorderedElementsAreArray({ "a", "b", "c", "d", "ef" })));
4583}
4584
4585TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
4586 const int a[5] = { 2, 1, 4, 5, 3 };
4587 EXPECT_THAT(a, UnorderedElementsAreArray(
4588 { Eq(1), Eq(2), Eq(3), Eq(4), Eq(5) }));
4589 EXPECT_THAT(a, Not(UnorderedElementsAreArray(
4590 { Eq(1), Eq(2), Eq(3), Eq(4), Eq(6) })));
4591}
4592
4593TEST(UnorderedElementsAreArrayTest,
4594 TakesInitializerListOfDifferentTypedMatchers) {
4595 const int a[5] = { 2, 1, 4, 5, 3 };
4596 // The compiler cannot infer the type of the initializer list if its
4597 // elements have different types. We must explicitly specify the
4598 // unified element type in this case.
4599 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
4600 { Eq(1), Ne(-2), Ge(3), Le(4), Eq(5) }));
4601 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
4602 { Eq(1), Ne(-2), Ge(3), Le(4), Eq(6) })));
4603}
4604
kosak18489fa2013-12-04 23:49:07 +00004605#endif // GTEST_HAS_STD_INITIALIZER_LIST_
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004606
zhanyong.wanfb25d532013-07-28 08:24:00 +00004607class UnorderedElementsAreTest : public testing::Test {
4608 protected:
4609 typedef std::vector<int> IntVec;
4610};
4611
4612TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
4613 const int a[] = { 1, 2, 3 };
kosak6414d802013-12-03 23:19:36 +00004614 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004615 do {
4616 StringMatchResultListener listener;
4617 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4618 s, &listener)) << listener.str();
4619 } while (std::next_permutation(s.begin(), s.end()));
4620}
4621
4622TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
4623 const int a[] = { 1, 2, 3 };
kosak6414d802013-12-03 23:19:36 +00004624 std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wanfb25d532013-07-28 08:24:00 +00004625 std::vector<Matcher<int> > mv;
4626 mv.push_back(1);
4627 mv.push_back(2);
4628 mv.push_back(2);
4629 // The element with value '3' matches nothing: fail fast.
4630 StringMatchResultListener listener;
4631 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4632 s, &listener)) << listener.str();
4633}
4634
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004635TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
4636 // Streamlike 'container' provides only minimal iterator support.
4637 // Its iterators are tagged with input_iterator_tag, and it has no
4638 // size() or empty() methods.
4639 const int a[5] = { 2, 1, 4, 5, 3 };
kosak6414d802013-12-03 23:19:36 +00004640 Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a));
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004641
4642 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
4643 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
4644}
4645
zhanyong.wanfb25d532013-07-28 08:24:00 +00004646// One naive implementation of the matcher runs in O(N!) time, which is too
4647// slow for many real-world inputs. This test shows that our matcher can match
4648// 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
4649// iterations and obviously effectively incomputable.
4650// [ RUN ] UnorderedElementsAreTest.Performance
4651// [ OK ] UnorderedElementsAreTest.Performance (4 ms)
4652TEST_F(UnorderedElementsAreTest, Performance) {
4653 std::vector<int> s;
4654 std::vector<Matcher<int> > mv;
4655 for (int i = 0; i < 100; ++i) {
4656 s.push_back(i);
4657 mv.push_back(_);
4658 }
4659 mv[50] = Eq(0);
4660 StringMatchResultListener listener;
4661 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4662 s, &listener)) << listener.str();
4663}
4664
4665// Another variant of 'Performance' with similar expectations.
4666// [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
4667// [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
4668TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
4669 std::vector<int> s;
4670 std::vector<Matcher<int> > mv;
4671 for (int i = 0; i < 100; ++i) {
4672 s.push_back(i);
4673 if (i & 1) {
4674 mv.push_back(_);
4675 } else {
4676 mv.push_back(i);
4677 }
4678 }
4679 StringMatchResultListener listener;
4680 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4681 s, &listener)) << listener.str();
4682}
4683
4684TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
4685 std::vector<int> v;
4686 v.push_back(4);
4687 StringMatchResultListener listener;
4688 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4689 v, &listener)) << listener.str();
4690 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
4691}
4692
4693TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
4694 std::vector<int> v;
4695 StringMatchResultListener listener;
4696 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4697 v, &listener)) << listener.str();
4698 EXPECT_THAT(listener.str(), Eq(""));
4699}
4700
4701TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
4702 std::vector<int> v;
4703 v.push_back(1);
4704 v.push_back(1);
4705 StringMatchResultListener listener;
4706 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4707 v, &listener)) << listener.str();
4708 EXPECT_THAT(
4709 listener.str(),
4710 Eq("where the following matchers don't match any elements:\n"
4711 "matcher #1: is equal to 2"));
4712}
4713
4714TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
4715 std::vector<int> v;
4716 v.push_back(1);
4717 v.push_back(2);
4718 StringMatchResultListener listener;
4719 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
4720 v, &listener)) << listener.str();
4721 EXPECT_THAT(
4722 listener.str(),
4723 Eq("where the following elements don't match any matchers:\n"
4724 "element #1: 2"));
4725}
4726
4727TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
4728 std::vector<int> v;
4729 v.push_back(2);
4730 v.push_back(3);
4731 StringMatchResultListener listener;
4732 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4733 v, &listener)) << listener.str();
4734 EXPECT_THAT(
4735 listener.str(),
4736 Eq("where"
4737 " the following matchers don't match any elements:\n"
4738 "matcher #0: is equal to 1\n"
4739 "and"
4740 " where"
4741 " the following elements don't match any matchers:\n"
4742 "element #1: 3"));
4743}
4744
4745// Test helper for formatting element, matcher index pairs in expectations.
4746static string EMString(int element, int matcher) {
4747 stringstream ss;
4748 ss << "(element #" << element << ", matcher #" << matcher << ")";
4749 return ss.str();
4750}
4751
4752TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
4753 // A situation where all elements and matchers have a match
4754 // associated with them, but the max matching is not perfect.
4755 std::vector<string> v;
4756 v.push_back("a");
4757 v.push_back("b");
4758 v.push_back("c");
4759 StringMatchResultListener listener;
4760 EXPECT_FALSE(ExplainMatchResult(
4761 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
4762 << listener.str();
4763
4764 string prefix =
4765 "where no permutation of the elements can satisfy all matchers, "
4766 "and the closest match is 2 of 3 matchers with the "
4767 "pairings:\n";
4768
4769 // We have to be a bit loose here, because there are 4 valid max matches.
4770 EXPECT_THAT(
4771 listener.str(),
4772 AnyOf(prefix + "{\n " + EMString(0, 0) +
4773 ",\n " + EMString(1, 2) + "\n}",
4774 prefix + "{\n " + EMString(0, 1) +
4775 ",\n " + EMString(1, 2) + "\n}",
4776 prefix + "{\n " + EMString(0, 0) +
4777 ",\n " + EMString(2, 2) + "\n}",
4778 prefix + "{\n " + EMString(0, 1) +
4779 ",\n " + EMString(2, 2) + "\n}"));
4780}
4781
4782TEST_F(UnorderedElementsAreTest, Describe) {
4783 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
4784 Eq("is empty"));
4785 EXPECT_THAT(
4786 Describe<IntVec>(UnorderedElementsAre(345)),
4787 Eq("has 1 element and that element is equal to 345"));
4788 EXPECT_THAT(
4789 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
4790 Eq("has 3 elements and there exists some permutation "
4791 "of elements such that:\n"
4792 " - element #0 is equal to 111, and\n"
4793 " - element #1 is equal to 222, and\n"
4794 " - element #2 is equal to 333"));
4795}
4796
4797TEST_F(UnorderedElementsAreTest, DescribeNegation) {
4798 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
4799 Eq("isn't empty"));
4800 EXPECT_THAT(
4801 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
4802 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
4803 EXPECT_THAT(
4804 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
4805 Eq("doesn't have 3 elements, or there exists no permutation "
4806 "of elements such that:\n"
4807 " - element #0 is equal to 123, and\n"
4808 " - element #1 is equal to 234, and\n"
4809 " - element #2 is equal to 345"));
4810}
4811
4812namespace {
4813
4814// Used as a check on the more complex max flow method used in the
4815// real testing::internal::FindMaxBipartiteMatching. This method is
4816// compatible but runs in worst-case factorial time, so we only
4817// use it in testing for small problem sizes.
4818template <typename Graph>
4819class BacktrackingMaxBPMState {
4820 public:
4821 // Does not take ownership of 'g'.
4822 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
4823
4824 ElementMatcherPairs Compute() {
4825 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
4826 return best_so_far_;
4827 }
4828 lhs_used_.assign(graph_->LhsSize(), kUnused);
4829 rhs_used_.assign(graph_->RhsSize(), kUnused);
4830 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
4831 matches_.clear();
4832 RecurseInto(irhs);
4833 if (best_so_far_.size() == graph_->RhsSize())
4834 break;
4835 }
4836 return best_so_far_;
4837 }
4838
4839 private:
4840 static const size_t kUnused = static_cast<size_t>(-1);
4841
4842 void PushMatch(size_t lhs, size_t rhs) {
4843 matches_.push_back(ElementMatcherPair(lhs, rhs));
4844 lhs_used_[lhs] = rhs;
4845 rhs_used_[rhs] = lhs;
4846 if (matches_.size() > best_so_far_.size()) {
4847 best_so_far_ = matches_;
4848 }
4849 }
4850
4851 void PopMatch() {
4852 const ElementMatcherPair& back = matches_.back();
4853 lhs_used_[back.first] = kUnused;
4854 rhs_used_[back.second] = kUnused;
4855 matches_.pop_back();
4856 }
4857
4858 bool RecurseInto(size_t irhs) {
4859 if (rhs_used_[irhs] != kUnused) {
4860 return true;
4861 }
4862 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
4863 if (lhs_used_[ilhs] != kUnused) {
4864 continue;
4865 }
4866 if (!graph_->HasEdge(ilhs, irhs)) {
4867 continue;
4868 }
4869 PushMatch(ilhs, irhs);
4870 if (best_so_far_.size() == graph_->RhsSize()) {
4871 return false;
4872 }
4873 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
4874 if (!RecurseInto(mi)) return false;
4875 }
4876 PopMatch();
4877 }
4878 return true;
4879 }
4880
4881 const Graph* graph_; // not owned
4882 std::vector<size_t> lhs_used_;
4883 std::vector<size_t> rhs_used_;
4884 ElementMatcherPairs matches_;
4885 ElementMatcherPairs best_so_far_;
4886};
4887
4888template <typename Graph>
4889const size_t BacktrackingMaxBPMState<Graph>::kUnused;
4890
4891} // namespace
4892
4893// Implement a simple backtracking algorithm to determine if it is possible
4894// to find one element per matcher, without reusing elements.
4895template <typename Graph>
4896ElementMatcherPairs
4897FindBacktrackingMaxBPM(const Graph& g) {
4898 return BacktrackingMaxBPMState<Graph>(&g).Compute();
4899}
4900
4901class BacktrackingBPMTest : public ::testing::Test { };
4902
4903// Tests the MaxBipartiteMatching algorithm with square matrices.
4904// The single int param is the # of nodes on each of the left and right sides.
4905class BipartiteTest : public ::testing::TestWithParam<int> { };
4906
4907// Verify all match graphs up to some moderate number of edges.
4908TEST_P(BipartiteTest, Exhaustive) {
4909 int nodes = GetParam();
4910 MatchMatrix graph(nodes, nodes);
4911 do {
4912 ElementMatcherPairs matches =
4913 internal::FindMaxBipartiteMatching(graph);
4914 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
4915 << "graph: " << graph.DebugString();
4916 // Check that all elements of matches are in the graph.
4917 // Check that elements of first and second are unique.
4918 std::vector<bool> seen_element(graph.LhsSize());
4919 std::vector<bool> seen_matcher(graph.RhsSize());
4920 SCOPED_TRACE(PrintToString(matches));
4921 for (size_t i = 0; i < matches.size(); ++i) {
4922 size_t ilhs = matches[i].first;
4923 size_t irhs = matches[i].second;
4924 EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
4925 EXPECT_FALSE(seen_element[ilhs]);
4926 EXPECT_FALSE(seen_matcher[irhs]);
4927 seen_element[ilhs] = true;
4928 seen_matcher[irhs] = true;
4929 }
4930 } while (graph.NextGraph());
4931}
4932
4933INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest,
4934 ::testing::Range(0, 5));
4935
4936// Parameterized by a pair interpreted as (LhsSize, RhsSize).
4937class BipartiteNonSquareTest
4938 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
4939};
4940
4941TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
4942 // .......
4943 // 0:-----\ :
4944 // 1:---\ | :
4945 // 2:---\ | :
4946 // 3:-\ | | :
4947 // :.......:
4948 // 0 1 2
4949 MatchMatrix g(4, 3);
4950 static const int kEdges[][2] = { {0, 2}, {1, 1}, {2, 1}, {3, 0} };
kosak6414d802013-12-03 23:19:36 +00004951 for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00004952 g.SetEdge(kEdges[i][0], kEdges[i][1], true);
4953 }
4954 EXPECT_THAT(FindBacktrackingMaxBPM(g),
4955 ElementsAre(Pair(3, 0),
4956 Pair(AnyOf(1, 2), 1),
4957 Pair(0, 2))) << g.DebugString();
4958}
4959
4960// Verify a few nonsquare matrices.
4961TEST_P(BipartiteNonSquareTest, Exhaustive) {
4962 size_t nlhs = GetParam().first;
4963 size_t nrhs = GetParam().second;
4964 MatchMatrix graph(nlhs, nrhs);
4965 do {
4966 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
4967 internal::FindMaxBipartiteMatching(graph).size())
4968 << "graph: " << graph.DebugString()
4969 << "\nbacktracking: "
4970 << PrintToString(FindBacktrackingMaxBPM(graph))
4971 << "\nmax flow: "
4972 << PrintToString(internal::FindMaxBipartiteMatching(graph));
4973 } while (graph.NextGraph());
4974}
4975
4976INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest,
4977 testing::Values(
4978 std::make_pair(1, 2),
4979 std::make_pair(2, 1),
4980 std::make_pair(3, 2),
4981 std::make_pair(2, 3),
4982 std::make_pair(4, 1),
4983 std::make_pair(1, 4),
4984 std::make_pair(4, 3),
4985 std::make_pair(3, 4)));
4986
4987class BipartiteRandomTest
4988 : public ::testing::TestWithParam<std::pair<int, int> > {
4989};
4990
4991// Verifies a large sample of larger graphs.
4992TEST_P(BipartiteRandomTest, LargerNets) {
4993 int nodes = GetParam().first;
4994 int iters = GetParam().second;
4995 MatchMatrix graph(nodes, nodes);
4996
4997 testing::internal::Int32 seed = GTEST_FLAG(random_seed);
4998 if (seed == 0) {
4999 seed = static_cast<testing::internal::Int32>(time(NULL));
5000 }
5001
5002 for (; iters > 0; --iters, ++seed) {
5003 srand(static_cast<int>(seed));
5004 graph.Randomize();
5005 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
5006 internal::FindMaxBipartiteMatching(graph).size())
5007 << " graph: " << graph.DebugString()
5008 << "\nTo reproduce the failure, rerun the test with the flag"
5009 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
5010 }
5011}
5012
5013// Test argument is a std::pair<int, int> representing (nodes, iters).
5014INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest,
5015 testing::Values(
5016 std::make_pair(5, 10000),
5017 std::make_pair(6, 5000),
5018 std::make_pair(7, 2000),
5019 std::make_pair(8, 500),
5020 std::make_pair(9, 100)));
5021
zhanyong.wan736baa82010-09-27 17:44:16 +00005022// Tests IsReadableTypeName().
5023
5024TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
5025 EXPECT_TRUE(IsReadableTypeName("int"));
5026 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
5027 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
5028 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
5029}
5030
5031TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
5032 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
5033 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
5034 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
5035}
5036
5037TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
5038 EXPECT_FALSE(
5039 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
5040 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
5041}
5042
5043TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
5044 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
5045}
5046
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005047// Tests JoinAsTuple().
5048
5049TEST(JoinAsTupleTest, JoinsEmptyTuple) {
5050 EXPECT_EQ("", JoinAsTuple(Strings()));
5051}
5052
5053TEST(JoinAsTupleTest, JoinsOneTuple) {
5054 const char* fields[] = { "1" };
5055 EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
5056}
5057
5058TEST(JoinAsTupleTest, JoinsTwoTuple) {
5059 const char* fields[] = { "1", "a" };
5060 EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
5061}
5062
5063TEST(JoinAsTupleTest, JoinsTenTuple) {
5064 const char* fields[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
5065 EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
5066 JoinAsTuple(Strings(fields, fields + 10)));
5067}
5068
5069// Tests FormatMatcherDescription().
5070
5071TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
5072 EXPECT_EQ("is even",
zhanyong.wanb4140802010-06-08 22:53:57 +00005073 FormatMatcherDescription(false, "IsEven", Strings()));
5074 EXPECT_EQ("not (is even)",
5075 FormatMatcherDescription(true, "IsEven", Strings()));
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005076
5077 const char* params[] = { "5" };
5078 EXPECT_EQ("equals 5",
zhanyong.wanb4140802010-06-08 22:53:57 +00005079 FormatMatcherDescription(false, "Equals",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005080 Strings(params, params + 1)));
5081
5082 const char* params2[] = { "5", "8" };
5083 EXPECT_EQ("is in range (5, 8)",
zhanyong.wanb4140802010-06-08 22:53:57 +00005084 FormatMatcherDescription(false, "IsInRange",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005085 Strings(params2, params2 + 2)));
5086}
5087
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00005088// Tests PolymorphicMatcher::mutable_impl().
5089TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
5090 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5091 DivisibleByImpl& impl = m.mutable_impl();
5092 EXPECT_EQ(42, impl.divider());
5093
5094 impl.set_divider(0);
5095 EXPECT_EQ(0, m.mutable_impl().divider());
5096}
5097
5098// Tests PolymorphicMatcher::impl().
5099TEST(PolymorphicMatcherTest, CanAccessImpl) {
5100 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5101 const DivisibleByImpl& impl = m.impl();
5102 EXPECT_EQ(42, impl.divider());
5103}
5104
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005105TEST(MatcherTupleTest, ExplainsMatchFailure) {
5106 stringstream ss1;
5107 ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
5108 make_tuple('a', 10), &ss1);
5109 EXPECT_EQ("", ss1.str()); // Successful match.
5110
5111 stringstream ss2;
5112 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5113 make_tuple(2, 'b'), &ss2);
5114 EXPECT_EQ(" Expected arg #0: is > 5\n"
5115 " Actual: 2, which is 3 less than 5\n"
zhanyong.wand60c5f42010-07-21 22:21:07 +00005116 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
5117 " Actual: 'b' (98, 0x62)\n",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005118 ss2.str()); // Failed match where both arguments need explanation.
5119
5120 stringstream ss3;
5121 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5122 make_tuple(2, 'a'), &ss3);
5123 EXPECT_EQ(" Expected arg #0: is > 5\n"
5124 " Actual: 2, which is 3 less than 5\n",
5125 ss3.str()); // Failed match where only one argument needs
5126 // explanation.
5127}
5128
zhanyong.wan33605ba2010-04-22 23:37:47 +00005129// Tests Each().
5130
5131TEST(EachTest, ExplainsMatchResultCorrectly) {
5132 set<int> a; // empty
5133
5134 Matcher<set<int> > m = Each(2);
5135 EXPECT_EQ("", Explain(m, a));
5136
zhanyong.wan736baa82010-09-27 17:44:16 +00005137 Matcher<const int(&)[1]> n = Each(1); // NOLINT
zhanyong.wan33605ba2010-04-22 23:37:47 +00005138
5139 const int b[1] = { 1 };
5140 EXPECT_EQ("", Explain(n, b));
5141
5142 n = Each(3);
5143 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
5144
5145 a.insert(1);
5146 a.insert(2);
5147 a.insert(3);
5148 m = Each(GreaterThan(0));
5149 EXPECT_EQ("", Explain(m, a));
5150
5151 m = Each(GreaterThan(10));
5152 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
5153 Explain(m, a));
5154}
5155
5156TEST(EachTest, DescribesItselfCorrectly) {
5157 Matcher<vector<int> > m = Each(1);
5158 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
5159
5160 Matcher<vector<int> > m2 = Not(m);
5161 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
5162}
5163
5164TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
5165 vector<int> some_vector;
5166 EXPECT_THAT(some_vector, Each(1));
5167 some_vector.push_back(3);
5168 EXPECT_THAT(some_vector, Not(Each(1)));
5169 EXPECT_THAT(some_vector, Each(3));
5170 some_vector.push_back(1);
5171 some_vector.push_back(2);
5172 EXPECT_THAT(some_vector, Not(Each(3)));
5173 EXPECT_THAT(some_vector, Each(Lt(3.5)));
5174
5175 vector<string> another_vector;
5176 another_vector.push_back("fee");
5177 EXPECT_THAT(another_vector, Each(string("fee")));
5178 another_vector.push_back("fie");
5179 another_vector.push_back("foe");
5180 another_vector.push_back("fum");
5181 EXPECT_THAT(another_vector, Not(Each(string("fee"))));
5182}
5183
5184TEST(EachTest, MatchesMapWhenAllElementsMatch) {
5185 map<const char*, int> my_map;
5186 const char* bar = "a string";
5187 my_map[bar] = 2;
5188 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
5189
5190 map<string, int> another_map;
5191 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5192 another_map["fee"] = 1;
5193 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5194 another_map["fie"] = 2;
5195 another_map["foe"] = 3;
5196 another_map["fum"] = 4;
5197 EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1))));
5198 EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1))));
5199 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
5200}
5201
5202TEST(EachTest, AcceptsMatcher) {
5203 const int a[] = { 1, 2, 3 };
5204 EXPECT_THAT(a, Each(Gt(0)));
5205 EXPECT_THAT(a, Not(Each(Gt(1))));
5206}
5207
5208TEST(EachTest, WorksForNativeArrayAsTuple) {
5209 const int a[] = { 1, 2 };
5210 const int* const pointer = a;
5211 EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
5212 EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
5213}
5214
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005215// For testing Pointwise().
5216class IsHalfOfMatcher {
5217 public:
5218 template <typename T1, typename T2>
5219 bool MatchAndExplain(const tuple<T1, T2>& a_pair,
5220 MatchResultListener* listener) const {
5221 if (get<0>(a_pair) == get<1>(a_pair)/2) {
5222 *listener << "where the second is " << get<1>(a_pair);
5223 return true;
5224 } else {
5225 *listener << "where the second/2 is " << get<1>(a_pair)/2;
5226 return false;
5227 }
5228 }
5229
5230 void DescribeTo(ostream* os) const {
5231 *os << "are a pair where the first is half of the second";
5232 }
5233
5234 void DescribeNegationTo(ostream* os) const {
5235 *os << "are a pair where the first isn't half of the second";
5236 }
5237};
5238
5239PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
5240 return MakePolymorphicMatcher(IsHalfOfMatcher());
5241}
5242
5243TEST(PointwiseTest, DescribesSelf) {
5244 vector<int> rhs;
5245 rhs.push_back(1);
5246 rhs.push_back(2);
5247 rhs.push_back(3);
5248 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
5249 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
5250 "in { 1, 2, 3 } are a pair where the first is half of the second",
5251 Describe(m));
5252 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
5253 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
5254 "where the first isn't half of the second",
5255 DescribeNegation(m));
5256}
5257
5258TEST(PointwiseTest, MakesCopyOfRhs) {
5259 list<signed char> rhs;
5260 rhs.push_back(2);
5261 rhs.push_back(4);
5262
5263 int lhs[] = { 1, 2 };
5264 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
5265 EXPECT_THAT(lhs, m);
5266
5267 // Changing rhs now shouldn't affect m, which made a copy of rhs.
5268 rhs.push_back(6);
5269 EXPECT_THAT(lhs, m);
5270}
5271
5272TEST(PointwiseTest, WorksForLhsNativeArray) {
5273 const int lhs[] = { 1, 2, 3 };
5274 vector<int> rhs;
5275 rhs.push_back(2);
5276 rhs.push_back(4);
5277 rhs.push_back(6);
5278 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
5279 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5280}
5281
5282TEST(PointwiseTest, WorksForRhsNativeArray) {
5283 const int rhs[] = { 1, 2, 3 };
5284 vector<int> lhs;
5285 lhs.push_back(2);
5286 lhs.push_back(4);
5287 lhs.push_back(6);
5288 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
5289 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
5290}
5291
5292TEST(PointwiseTest, RejectsWrongSize) {
5293 const double lhs[2] = { 1, 2 };
5294 const int rhs[1] = { 0 };
5295 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5296 EXPECT_EQ("which contains 2 values",
5297 Explain(Pointwise(Gt(), rhs), lhs));
5298
5299 const int rhs2[3] = { 0, 1, 2 };
5300 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
5301}
5302
5303TEST(PointwiseTest, RejectsWrongContent) {
5304 const double lhs[3] = { 1, 2, 3 };
5305 const int rhs[3] = { 2, 6, 4 };
5306 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
5307 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
5308 "where the second/2 is 3",
5309 Explain(Pointwise(IsHalfOf(), rhs), lhs));
5310}
5311
5312TEST(PointwiseTest, AcceptsCorrectContent) {
5313 const double lhs[3] = { 1, 2, 3 };
5314 const int rhs[3] = { 2, 4, 6 };
5315 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
5316 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
5317}
5318
5319TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
5320 const double lhs[3] = { 1, 2, 3 };
5321 const int rhs[3] = { 2, 4, 6 };
5322 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5323 EXPECT_THAT(lhs, Pointwise(m1, rhs));
5324 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
5325
5326 // This type works as a tuple<const double&, const int&> can be
5327 // implicitly cast to tuple<double, int>.
5328 const Matcher<tuple<double, int> > m2 = IsHalfOf();
5329 EXPECT_THAT(lhs, Pointwise(m2, rhs));
5330 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
5331}
5332
shiqiane35fdd92008-12-10 05:08:54 +00005333} // namespace gmock_matchers_test
5334} // namespace testing