blob: 1c43ecb4323260dfee7be177d4b3bc904db451d5 [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29//
30// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file tests some commonly used argument matchers.
35
zhanyong.wan53e08c42010-09-14 05:38:21 +000036#include "gmock/gmock-matchers.h"
zhanyong.wan320814a2013-03-01 00:20:30 +000037#include "gmock/gmock-more-matchers.h"
shiqiane35fdd92008-12-10 05:08:54 +000038
39#include <string.h>
zhanyong.wanfb25d532013-07-28 08:24:00 +000040#include <time.h>
zhanyong.wana9a59e02013-03-27 16:14:55 +000041#include <deque>
shiqiane35fdd92008-12-10 05:08:54 +000042#include <functional>
zhanyong.wana862f1d2010-03-15 21:23:04 +000043#include <iostream>
zhanyong.wana9a59e02013-03-27 16:14:55 +000044#include <iterator>
zhanyong.wan616180e2013-06-18 18:49:51 +000045#include <limits>
zhanyong.wan6a896b52009-01-16 01:13:50 +000046#include <list>
47#include <map>
48#include <set>
shiqiane35fdd92008-12-10 05:08:54 +000049#include <sstream>
zhanyong.wan6a896b52009-01-16 01:13:50 +000050#include <string>
zhanyong.wanf5e1ce52009-09-16 07:02:02 +000051#include <utility>
zhanyong.wan6a896b52009-01-16 01:13:50 +000052#include <vector>
zhanyong.wan53e08c42010-09-14 05:38:21 +000053#include "gmock/gmock.h"
54#include "gtest/gtest.h"
55#include "gtest/gtest-spi.h"
shiqiane35fdd92008-12-10 05:08:54 +000056
57namespace testing {
zhanyong.wan4a5330d2009-02-19 00:36:44 +000058
59namespace internal {
vladlosev587c1b32011-05-20 00:42:22 +000060GTEST_API_ string JoinAsTuple(const Strings& fields);
zhanyong.wan4a5330d2009-02-19 00:36:44 +000061} // namespace internal
62
shiqiane35fdd92008-12-10 05:08:54 +000063namespace gmock_matchers_test {
64
zhanyong.wan898725c2011-09-16 16:45:39 +000065using std::greater;
66using std::less;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000067using std::list;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000068using std::make_pair;
zhanyong.wanb5937da2009-07-16 20:26:41 +000069using std::map;
70using std::multimap;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000071using std::multiset;
72using std::ostream;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000073using std::pair;
zhanyong.wan33605ba2010-04-22 23:37:47 +000074using std::set;
shiqiane35fdd92008-12-10 05:08:54 +000075using std::stringstream;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000076using std::tr1::get;
zhanyong.wanb8243162009-06-04 05:48:20 +000077using std::tr1::make_tuple;
zhanyong.wanab5b77c2010-05-17 19:32:48 +000078using std::tr1::tuple;
zhanyong.wan33605ba2010-04-22 23:37:47 +000079using std::vector;
shiqiane35fdd92008-12-10 05:08:54 +000080using testing::A;
zhanyong.wanbf550852009-06-09 06:09:53 +000081using testing::AllArgs;
shiqiane35fdd92008-12-10 05:08:54 +000082using testing::AllOf;
83using testing::An;
84using testing::AnyOf;
85using testing::ByRef;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000086using testing::ContainsRegex;
shiqiane35fdd92008-12-10 05:08:54 +000087using testing::DoubleEq;
zhanyong.wan616180e2013-06-18 18:49:51 +000088using testing::DoubleNear;
shiqiane35fdd92008-12-10 05:08:54 +000089using testing::EndsWith;
90using testing::Eq;
zhanyong.wanb1c7f932010-03-24 17:35:11 +000091using testing::ExplainMatchResult;
shiqiane35fdd92008-12-10 05:08:54 +000092using testing::Field;
93using testing::FloatEq;
zhanyong.wan616180e2013-06-18 18:49:51 +000094using testing::FloatNear;
shiqiane35fdd92008-12-10 05:08:54 +000095using testing::Ge;
96using testing::Gt;
97using testing::HasSubstr;
zhanyong.wan320814a2013-03-01 00:20:30 +000098using testing::IsEmpty;
zhanyong.wan2d970ee2009-09-24 21:41:36 +000099using testing::IsNull;
zhanyong.wanb5937da2009-07-16 20:26:41 +0000100using testing::Key;
shiqiane35fdd92008-12-10 05:08:54 +0000101using testing::Le;
102using testing::Lt;
103using testing::MakeMatcher;
104using testing::MakePolymorphicMatcher;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000105using testing::MatchResultListener;
shiqiane35fdd92008-12-10 05:08:54 +0000106using testing::Matcher;
107using testing::MatcherCast;
108using testing::MatcherInterface;
109using testing::Matches;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000110using testing::MatchesRegex;
shiqiane35fdd92008-12-10 05:08:54 +0000111using testing::NanSensitiveDoubleEq;
zhanyong.wan616180e2013-06-18 18:49:51 +0000112using testing::NanSensitiveDoubleNear;
shiqiane35fdd92008-12-10 05:08:54 +0000113using testing::NanSensitiveFloatEq;
zhanyong.wan616180e2013-06-18 18:49:51 +0000114using testing::NanSensitiveFloatNear;
shiqiane35fdd92008-12-10 05:08:54 +0000115using testing::Ne;
116using testing::Not;
117using testing::NotNull;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000118using testing::Pair;
shiqiane35fdd92008-12-10 05:08:54 +0000119using testing::Pointee;
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000120using testing::Pointwise;
shiqiane35fdd92008-12-10 05:08:54 +0000121using testing::PolymorphicMatcher;
122using testing::Property;
123using testing::Ref;
124using testing::ResultOf;
zhanyong.wana31d9ce2013-03-01 01:50:17 +0000125using testing::SizeIs;
shiqiane35fdd92008-12-10 05:08:54 +0000126using testing::StartsWith;
127using testing::StrCaseEq;
128using testing::StrCaseNe;
129using testing::StrEq;
130using testing::StrNe;
131using testing::Truly;
132using testing::TypedEq;
zhanyong.wanb8243162009-06-04 05:48:20 +0000133using testing::Value;
zhanyong.wan898725c2011-09-16 16:45:39 +0000134using testing::WhenSorted;
135using testing::WhenSortedBy;
shiqiane35fdd92008-12-10 05:08:54 +0000136using testing::_;
zhanyong.wana862f1d2010-03-15 21:23:04 +0000137using testing::internal::DummyMatchResultListener;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000138using testing::internal::ElementMatcherPair;
139using testing::internal::ElementMatcherPairs;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000140using testing::internal::ExplainMatchFailureTupleTo;
shiqiane35fdd92008-12-10 05:08:54 +0000141using testing::internal::FloatingEqMatcher;
zhanyong.wanb4140802010-06-08 22:53:57 +0000142using testing::internal::FormatMatcherDescription;
zhanyong.wan736baa82010-09-27 17:44:16 +0000143using testing::internal::IsReadableTypeName;
zhanyong.wan4a5330d2009-02-19 00:36:44 +0000144using testing::internal::JoinAsTuple;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000145using testing::internal::MatchMatrix;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000146using testing::internal::RE;
zhanyong.wana862f1d2010-03-15 21:23:04 +0000147using testing::internal::StreamMatchResultListener;
zhanyong.wan34b034c2010-03-05 21:23:23 +0000148using testing::internal::StringMatchResultListener;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000149using testing::internal::Strings;
vladlosev79b83502009-11-18 00:43:37 +0000150using testing::internal::linked_ptr;
vladloseve56daa72009-11-18 01:08:08 +0000151using testing::internal::scoped_ptr;
shiqiane35fdd92008-12-10 05:08:54 +0000152using testing::internal::string;
153
zhanyong.wanfb25d532013-07-28 08:24:00 +0000154// Evaluates to the number of elements in 'array'.
155#define GMOCK_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0]))
156
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000157// For testing ExplainMatchResultTo().
158class GreaterThanMatcher : public MatcherInterface<int> {
159 public:
160 explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {}
161
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000162 virtual void DescribeTo(ostream* os) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000163 *os << "is > " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000164 }
165
zhanyong.wandb22c222010-01-28 21:52:29 +0000166 virtual bool MatchAndExplain(int lhs,
167 MatchResultListener* listener) const {
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000168 const int diff = lhs - rhs_;
169 if (diff > 0) {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000170 *listener << "which is " << diff << " more than " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000171 } else if (diff == 0) {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000172 *listener << "which is the same as " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000173 } else {
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000174 *listener << "which is " << -diff << " less than " << rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000175 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000176
177 return lhs > rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000178 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000179
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000180 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +0000181 int rhs_;
zhanyong.wanf5e1ce52009-09-16 07:02:02 +0000182};
183
184Matcher<int> GreaterThan(int n) {
185 return MakeMatcher(new GreaterThanMatcher(n));
186}
187
zhanyong.wan736baa82010-09-27 17:44:16 +0000188string OfType(const string& type_name) {
189#if GTEST_HAS_RTTI
190 return " (of type " + type_name + ")";
191#else
192 return "";
193#endif
194}
195
shiqiane35fdd92008-12-10 05:08:54 +0000196// Returns the description of the given matcher.
197template <typename T>
198string Describe(const Matcher<T>& m) {
199 stringstream ss;
200 m.DescribeTo(&ss);
201 return ss.str();
202}
203
204// Returns the description of the negation of the given matcher.
205template <typename T>
206string DescribeNegation(const Matcher<T>& m) {
207 stringstream ss;
208 m.DescribeNegationTo(&ss);
209 return ss.str();
210}
211
212// Returns the reason why x matches, or doesn't match, m.
213template <typename MatcherType, typename Value>
214string Explain(const MatcherType& m, const Value& x) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000215 StringMatchResultListener listener;
216 ExplainMatchResult(m, x, &listener);
217 return listener.str();
shiqiane35fdd92008-12-10 05:08:54 +0000218}
219
zhanyong.wana862f1d2010-03-15 21:23:04 +0000220TEST(MatchResultListenerTest, StreamingWorks) {
221 StringMatchResultListener listener;
222 listener << "hi" << 5;
223 EXPECT_EQ("hi5", listener.str());
224
225 // Streaming shouldn't crash when the underlying ostream is NULL.
226 DummyMatchResultListener dummy;
227 dummy << "hi" << 5;
228}
229
230TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
231 EXPECT_TRUE(DummyMatchResultListener().stream() == NULL);
232 EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL);
233
234 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
235}
236
237TEST(MatchResultListenerTest, IsInterestedWorks) {
238 EXPECT_TRUE(StringMatchResultListener().IsInterested());
239 EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
240
241 EXPECT_FALSE(DummyMatchResultListener().IsInterested());
242 EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested());
243}
244
shiqiane35fdd92008-12-10 05:08:54 +0000245// Makes sure that the MatcherInterface<T> interface doesn't
246// change.
247class EvenMatcherImpl : public MatcherInterface<int> {
248 public:
zhanyong.wandb22c222010-01-28 21:52:29 +0000249 virtual bool MatchAndExplain(int x,
250 MatchResultListener* /* listener */) const {
251 return x % 2 == 0;
252 }
shiqiane35fdd92008-12-10 05:08:54 +0000253
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000254 virtual void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +0000255 *os << "is an even number";
256 }
257
258 // We deliberately don't define DescribeNegationTo() and
259 // ExplainMatchResultTo() here, to make sure the definition of these
260 // two methods is optional.
261};
262
zhanyong.wana862f1d2010-03-15 21:23:04 +0000263// Makes sure that the MatcherInterface API doesn't change.
264TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
shiqiane35fdd92008-12-10 05:08:54 +0000265 EvenMatcherImpl m;
266}
267
zhanyong.wan82113312010-01-08 21:55:40 +0000268// Tests implementing a monomorphic matcher using MatchAndExplain().
269
270class NewEvenMatcherImpl : public MatcherInterface<int> {
271 public:
272 virtual bool MatchAndExplain(int x, MatchResultListener* listener) const {
273 const bool match = x % 2 == 0;
274 // Verifies that we can stream to a listener directly.
275 *listener << "value % " << 2;
276 if (listener->stream() != NULL) {
277 // Verifies that we can stream to a listener's underlying stream
278 // too.
279 *listener->stream() << " == " << (x % 2);
280 }
281 return match;
282 }
283
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000284 virtual void DescribeTo(ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000285 *os << "is an even number";
286 }
287};
288
289TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
290 Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
291 EXPECT_TRUE(m.Matches(2));
292 EXPECT_FALSE(m.Matches(3));
293 EXPECT_EQ("value % 2 == 0", Explain(m, 2));
294 EXPECT_EQ("value % 2 == 1", Explain(m, 3));
295}
296
shiqiane35fdd92008-12-10 05:08:54 +0000297// Tests default-constructing a matcher.
298TEST(MatcherTest, CanBeDefaultConstructed) {
299 Matcher<double> m;
300}
301
302// Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
303TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
304 const MatcherInterface<int>* impl = new EvenMatcherImpl;
305 Matcher<int> m(impl);
306 EXPECT_TRUE(m.Matches(4));
307 EXPECT_FALSE(m.Matches(5));
308}
309
310// Tests that value can be used in place of Eq(value).
311TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
312 Matcher<int> m1 = 5;
313 EXPECT_TRUE(m1.Matches(5));
314 EXPECT_FALSE(m1.Matches(6));
315}
316
317// Tests that NULL can be used in place of Eq(NULL).
318TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
319 Matcher<int*> m1 = NULL;
320 EXPECT_TRUE(m1.Matches(NULL));
321 int n = 0;
322 EXPECT_FALSE(m1.Matches(&n));
323}
324
325// Tests that matchers are copyable.
326TEST(MatcherTest, IsCopyable) {
327 // Tests the copy constructor.
328 Matcher<bool> m1 = Eq(false);
329 EXPECT_TRUE(m1.Matches(false));
330 EXPECT_FALSE(m1.Matches(true));
331
332 // Tests the assignment operator.
333 m1 = Eq(true);
334 EXPECT_TRUE(m1.Matches(true));
335 EXPECT_FALSE(m1.Matches(false));
336}
337
338// Tests that Matcher<T>::DescribeTo() calls
339// MatcherInterface<T>::DescribeTo().
340TEST(MatcherTest, CanDescribeItself) {
341 EXPECT_EQ("is an even number",
342 Describe(Matcher<int>(new EvenMatcherImpl)));
343}
344
zhanyong.wan82113312010-01-08 21:55:40 +0000345// Tests Matcher<T>::MatchAndExplain().
346TEST(MatcherTest, MatchAndExplain) {
347 Matcher<int> m = GreaterThan(0);
zhanyong.wan34b034c2010-03-05 21:23:23 +0000348 StringMatchResultListener listener1;
zhanyong.wan82113312010-01-08 21:55:40 +0000349 EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000350 EXPECT_EQ("which is 42 more than 0", listener1.str());
zhanyong.wan82113312010-01-08 21:55:40 +0000351
zhanyong.wan34b034c2010-03-05 21:23:23 +0000352 StringMatchResultListener listener2;
zhanyong.wan82113312010-01-08 21:55:40 +0000353 EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000354 EXPECT_EQ("which is 9 less than 0", listener2.str());
zhanyong.wan82113312010-01-08 21:55:40 +0000355}
356
shiqiane35fdd92008-12-10 05:08:54 +0000357// Tests that a C-string literal can be implicitly converted to a
358// Matcher<string> or Matcher<const string&>.
359TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
360 Matcher<string> m1 = "hi";
361 EXPECT_TRUE(m1.Matches("hi"));
362 EXPECT_FALSE(m1.Matches("hello"));
363
364 Matcher<const string&> m2 = "hi";
365 EXPECT_TRUE(m2.Matches("hi"));
366 EXPECT_FALSE(m2.Matches("hello"));
367}
368
369// Tests that a string object can be implicitly converted to a
370// Matcher<string> or Matcher<const string&>.
371TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
372 Matcher<string> m1 = string("hi");
373 EXPECT_TRUE(m1.Matches("hi"));
374 EXPECT_FALSE(m1.Matches("hello"));
375
376 Matcher<const string&> m2 = string("hi");
377 EXPECT_TRUE(m2.Matches("hi"));
378 EXPECT_FALSE(m2.Matches("hello"));
379}
380
zhanyong.wan1f122a02013-03-25 16:27:03 +0000381#if GTEST_HAS_STRING_PIECE_
382// Tests that a C-string literal can be implicitly converted to a
383// Matcher<StringPiece> or Matcher<const StringPiece&>.
384TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
385 Matcher<StringPiece> m1 = "cats";
386 EXPECT_TRUE(m1.Matches("cats"));
387 EXPECT_FALSE(m1.Matches("dogs"));
388
389 Matcher<const StringPiece&> m2 = "cats";
390 EXPECT_TRUE(m2.Matches("cats"));
391 EXPECT_FALSE(m2.Matches("dogs"));
392}
393
394// Tests that a string object can be implicitly converted to a
395// Matcher<StringPiece> or Matcher<const StringPiece&>.
396TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromString) {
397 Matcher<StringPiece> m1 = string("cats");
398 EXPECT_TRUE(m1.Matches("cats"));
399 EXPECT_FALSE(m1.Matches("dogs"));
400
401 Matcher<const StringPiece&> m2 = string("cats");
402 EXPECT_TRUE(m2.Matches("cats"));
403 EXPECT_FALSE(m2.Matches("dogs"));
404}
405
406// Tests that a StringPiece object can be implicitly converted to a
407// Matcher<StringPiece> or Matcher<const StringPiece&>.
408TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromStringPiece) {
409 Matcher<StringPiece> m1 = StringPiece("cats");
410 EXPECT_TRUE(m1.Matches("cats"));
411 EXPECT_FALSE(m1.Matches("dogs"));
412
413 Matcher<const StringPiece&> m2 = StringPiece("cats");
414 EXPECT_TRUE(m2.Matches("cats"));
415 EXPECT_FALSE(m2.Matches("dogs"));
416}
417#endif // GTEST_HAS_STRING_PIECE_
418
shiqiane35fdd92008-12-10 05:08:54 +0000419// Tests that MakeMatcher() constructs a Matcher<T> from a
420// MatcherInterface* without requiring the user to explicitly
421// write the type.
422TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
423 const MatcherInterface<int>* dummy_impl = NULL;
424 Matcher<int> m = MakeMatcher(dummy_impl);
425}
426
zhanyong.wan82113312010-01-08 21:55:40 +0000427// Tests that MakePolymorphicMatcher() can construct a polymorphic
428// matcher from its implementation using the old API.
zhanyong.wan33605ba2010-04-22 23:37:47 +0000429const int g_bar = 1;
shiqiane35fdd92008-12-10 05:08:54 +0000430class ReferencesBarOrIsZeroImpl {
431 public:
432 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +0000433 bool MatchAndExplain(const T& x,
434 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000435 const void* p = &x;
zhanyong.wan33605ba2010-04-22 23:37:47 +0000436 return p == &g_bar || x == 0;
shiqiane35fdd92008-12-10 05:08:54 +0000437 }
438
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000439 void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
shiqiane35fdd92008-12-10 05:08:54 +0000440
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000441 void DescribeNegationTo(ostream* os) const {
zhanyong.wan33605ba2010-04-22 23:37:47 +0000442 *os << "doesn't reference g_bar and is not zero";
shiqiane35fdd92008-12-10 05:08:54 +0000443 }
444};
445
446// This function verifies that MakePolymorphicMatcher() returns a
447// PolymorphicMatcher<T> where T is the argument's type.
448PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
449 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
450}
451
zhanyong.wan82113312010-01-08 21:55:40 +0000452TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
shiqiane35fdd92008-12-10 05:08:54 +0000453 // Using a polymorphic matcher to match a reference type.
454 Matcher<const int&> m1 = ReferencesBarOrIsZero();
455 EXPECT_TRUE(m1.Matches(0));
456 // Verifies that the identity of a by-reference argument is preserved.
zhanyong.wan33605ba2010-04-22 23:37:47 +0000457 EXPECT_TRUE(m1.Matches(g_bar));
shiqiane35fdd92008-12-10 05:08:54 +0000458 EXPECT_FALSE(m1.Matches(1));
zhanyong.wan33605ba2010-04-22 23:37:47 +0000459 EXPECT_EQ("g_bar or zero", Describe(m1));
shiqiane35fdd92008-12-10 05:08:54 +0000460
461 // Using a polymorphic matcher to match a value type.
462 Matcher<double> m2 = ReferencesBarOrIsZero();
463 EXPECT_TRUE(m2.Matches(0.0));
464 EXPECT_FALSE(m2.Matches(0.1));
zhanyong.wan33605ba2010-04-22 23:37:47 +0000465 EXPECT_EQ("g_bar or zero", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +0000466}
467
zhanyong.wan82113312010-01-08 21:55:40 +0000468// Tests implementing a polymorphic matcher using MatchAndExplain().
469
470class PolymorphicIsEvenImpl {
471 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000472 void DescribeTo(ostream* os) const { *os << "is even"; }
zhanyong.wan82113312010-01-08 21:55:40 +0000473
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000474 void DescribeNegationTo(ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000475 *os << "is odd";
476 }
zhanyong.wan82113312010-01-08 21:55:40 +0000477
zhanyong.wandb22c222010-01-28 21:52:29 +0000478 template <typename T>
479 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
480 // Verifies that we can stream to the listener directly.
481 *listener << "% " << 2;
482 if (listener->stream() != NULL) {
483 // Verifies that we can stream to the listener's underlying stream
484 // too.
485 *listener->stream() << " == " << (x % 2);
486 }
487 return (x % 2) == 0;
zhanyong.wan82113312010-01-08 21:55:40 +0000488 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000489};
zhanyong.wan82113312010-01-08 21:55:40 +0000490
491PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
492 return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
493}
494
495TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
496 // Using PolymorphicIsEven() as a Matcher<int>.
497 const Matcher<int> m1 = PolymorphicIsEven();
498 EXPECT_TRUE(m1.Matches(42));
499 EXPECT_FALSE(m1.Matches(43));
500 EXPECT_EQ("is even", Describe(m1));
501
502 const Matcher<int> not_m1 = Not(m1);
503 EXPECT_EQ("is odd", Describe(not_m1));
504
505 EXPECT_EQ("% 2 == 0", Explain(m1, 42));
506
507 // Using PolymorphicIsEven() as a Matcher<char>.
508 const Matcher<char> m2 = PolymorphicIsEven();
509 EXPECT_TRUE(m2.Matches('\x42'));
510 EXPECT_FALSE(m2.Matches('\x43'));
511 EXPECT_EQ("is even", Describe(m2));
512
513 const Matcher<char> not_m2 = Not(m2);
514 EXPECT_EQ("is odd", Describe(not_m2));
515
516 EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
517}
518
shiqiane35fdd92008-12-10 05:08:54 +0000519// Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
520TEST(MatcherCastTest, FromPolymorphicMatcher) {
521 Matcher<int> m = MatcherCast<int>(Eq(5));
522 EXPECT_TRUE(m.Matches(5));
523 EXPECT_FALSE(m.Matches(6));
524}
525
526// For testing casting matchers between compatible types.
527class IntValue {
528 public:
529 // An int can be statically (although not implicitly) cast to a
530 // IntValue.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000531 explicit IntValue(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +0000532
533 int value() const { return value_; }
534 private:
535 int value_;
536};
537
538// For testing casting matchers between compatible types.
539bool IsPositiveIntValue(const IntValue& foo) {
540 return foo.value() > 0;
541}
542
543// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
544// can be statically converted to U.
545TEST(MatcherCastTest, FromCompatibleType) {
546 Matcher<double> m1 = Eq(2.0);
547 Matcher<int> m2 = MatcherCast<int>(m1);
548 EXPECT_TRUE(m2.Matches(2));
549 EXPECT_FALSE(m2.Matches(3));
550
551 Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
552 Matcher<int> m4 = MatcherCast<int>(m3);
553 // In the following, the arguments 1 and 0 are statically converted
554 // to IntValue objects, and then tested by the IsPositiveIntValue()
555 // predicate.
556 EXPECT_TRUE(m4.Matches(1));
557 EXPECT_FALSE(m4.Matches(0));
558}
559
560// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
561TEST(MatcherCastTest, FromConstReferenceToNonReference) {
562 Matcher<const int&> m1 = Eq(0);
563 Matcher<int> m2 = MatcherCast<int>(m1);
564 EXPECT_TRUE(m2.Matches(0));
565 EXPECT_FALSE(m2.Matches(1));
566}
567
568// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
569TEST(MatcherCastTest, FromReferenceToNonReference) {
570 Matcher<int&> m1 = Eq(0);
571 Matcher<int> m2 = MatcherCast<int>(m1);
572 EXPECT_TRUE(m2.Matches(0));
573 EXPECT_FALSE(m2.Matches(1));
574}
575
576// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
577TEST(MatcherCastTest, FromNonReferenceToConstReference) {
578 Matcher<int> m1 = Eq(0);
579 Matcher<const int&> m2 = MatcherCast<const int&>(m1);
580 EXPECT_TRUE(m2.Matches(0));
581 EXPECT_FALSE(m2.Matches(1));
582}
583
584// Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
585TEST(MatcherCastTest, FromNonReferenceToReference) {
586 Matcher<int> m1 = Eq(0);
587 Matcher<int&> m2 = MatcherCast<int&>(m1);
588 int n = 0;
589 EXPECT_TRUE(m2.Matches(n));
590 n = 1;
591 EXPECT_FALSE(m2.Matches(n));
592}
593
594// Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
595TEST(MatcherCastTest, FromSameType) {
596 Matcher<int> m1 = Eq(0);
597 Matcher<int> m2 = MatcherCast<int>(m1);
598 EXPECT_TRUE(m2.Matches(0));
599 EXPECT_FALSE(m2.Matches(1));
600}
601
jgm79a367e2012-04-10 16:02:11 +0000602// Implicitly convertible form any type.
603struct ConvertibleFromAny {
604 ConvertibleFromAny(int a_value) : value(a_value) {}
605 template <typename T>
606 ConvertibleFromAny(const T& a_value) : value(-1) {
607 ADD_FAILURE() << "Conversion constructor called";
608 }
609 int value;
610};
611
612bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
613 return a.value == b.value;
614}
615
616ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
617 return os << a.value;
618}
619
620TEST(MatcherCastTest, ConversionConstructorIsUsed) {
621 Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
622 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
623 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
624}
625
626TEST(MatcherCastTest, FromConvertibleFromAny) {
627 Matcher<ConvertibleFromAny> m =
628 MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
629 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
630 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
631}
632
zhanyong.wan18490652009-05-11 18:54:08 +0000633class Base {};
634class Derived : public Base {};
635
636// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
637TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
638 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
639 EXPECT_TRUE(m2.Matches(' '));
640 EXPECT_FALSE(m2.Matches('\n'));
641}
642
zhanyong.wan16cf4732009-05-14 20:55:30 +0000643// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
644// T and U are arithmetic types and T can be losslessly converted to
645// U.
646TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
zhanyong.wan18490652009-05-11 18:54:08 +0000647 Matcher<double> m1 = DoubleEq(1.0);
zhanyong.wan16cf4732009-05-14 20:55:30 +0000648 Matcher<float> m2 = SafeMatcherCast<float>(m1);
649 EXPECT_TRUE(m2.Matches(1.0f));
650 EXPECT_FALSE(m2.Matches(2.0f));
651
652 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
653 EXPECT_TRUE(m3.Matches('a'));
654 EXPECT_FALSE(m3.Matches('b'));
zhanyong.wan18490652009-05-11 18:54:08 +0000655}
656
657// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
658// are pointers or references to a derived and a base class, correspondingly.
659TEST(SafeMatcherCastTest, FromBaseClass) {
660 Derived d, d2;
661 Matcher<Base*> m1 = Eq(&d);
662 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
663 EXPECT_TRUE(m2.Matches(&d));
664 EXPECT_FALSE(m2.Matches(&d2));
665
666 Matcher<Base&> m3 = Ref(d);
667 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
668 EXPECT_TRUE(m4.Matches(d));
669 EXPECT_FALSE(m4.Matches(d2));
670}
671
672// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
673TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
674 int n = 0;
675 Matcher<const int&> m1 = Ref(n);
676 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
677 int n1 = 0;
678 EXPECT_TRUE(m2.Matches(n));
679 EXPECT_FALSE(m2.Matches(n1));
680}
681
682// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
683TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
684 Matcher<int> m1 = Eq(0);
685 Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
686 EXPECT_TRUE(m2.Matches(0));
687 EXPECT_FALSE(m2.Matches(1));
688}
689
690// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
691TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
692 Matcher<int> m1 = Eq(0);
693 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
694 int n = 0;
695 EXPECT_TRUE(m2.Matches(n));
696 n = 1;
697 EXPECT_FALSE(m2.Matches(n));
698}
699
700// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
701TEST(SafeMatcherCastTest, FromSameType) {
702 Matcher<int> m1 = Eq(0);
703 Matcher<int> m2 = SafeMatcherCast<int>(m1);
704 EXPECT_TRUE(m2.Matches(0));
705 EXPECT_FALSE(m2.Matches(1));
706}
707
jgm79a367e2012-04-10 16:02:11 +0000708TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
709 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
710 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
711 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
712}
713
714TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
715 Matcher<ConvertibleFromAny> m =
716 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
717 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
718 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
719}
720
shiqiane35fdd92008-12-10 05:08:54 +0000721// Tests that A<T>() matches any value of type T.
722TEST(ATest, MatchesAnyValue) {
723 // Tests a matcher for a value type.
724 Matcher<double> m1 = A<double>();
725 EXPECT_TRUE(m1.Matches(91.43));
726 EXPECT_TRUE(m1.Matches(-15.32));
727
728 // Tests a matcher for a reference type.
729 int a = 2;
730 int b = -6;
731 Matcher<int&> m2 = A<int&>();
732 EXPECT_TRUE(m2.Matches(a));
733 EXPECT_TRUE(m2.Matches(b));
734}
735
zhanyong.wanf4274522013-04-24 02:49:43 +0000736TEST(ATest, WorksForDerivedClass) {
737 Base base;
738 Derived derived;
739 EXPECT_THAT(&base, A<Base*>());
740 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
741 EXPECT_THAT(&derived, A<Base*>());
742 EXPECT_THAT(&derived, A<Derived*>());
743}
744
shiqiane35fdd92008-12-10 05:08:54 +0000745// Tests that A<T>() describes itself properly.
746TEST(ATest, CanDescribeSelf) {
747 EXPECT_EQ("is anything", Describe(A<bool>()));
748}
749
750// Tests that An<T>() matches any value of type T.
751TEST(AnTest, MatchesAnyValue) {
752 // Tests a matcher for a value type.
753 Matcher<int> m1 = An<int>();
754 EXPECT_TRUE(m1.Matches(9143));
755 EXPECT_TRUE(m1.Matches(-1532));
756
757 // Tests a matcher for a reference type.
758 int a = 2;
759 int b = -6;
760 Matcher<int&> m2 = An<int&>();
761 EXPECT_TRUE(m2.Matches(a));
762 EXPECT_TRUE(m2.Matches(b));
763}
764
765// Tests that An<T>() describes itself properly.
766TEST(AnTest, CanDescribeSelf) {
767 EXPECT_EQ("is anything", Describe(An<int>()));
768}
769
770// Tests that _ can be used as a matcher for any type and matches any
771// value of that type.
772TEST(UnderscoreTest, MatchesAnyValue) {
773 // Uses _ as a matcher for a value type.
774 Matcher<int> m1 = _;
775 EXPECT_TRUE(m1.Matches(123));
776 EXPECT_TRUE(m1.Matches(-242));
777
778 // Uses _ as a matcher for a reference type.
779 bool a = false;
780 const bool b = true;
781 Matcher<const bool&> m2 = _;
782 EXPECT_TRUE(m2.Matches(a));
783 EXPECT_TRUE(m2.Matches(b));
784}
785
786// Tests that _ describes itself properly.
787TEST(UnderscoreTest, CanDescribeSelf) {
788 Matcher<int> m = _;
789 EXPECT_EQ("is anything", Describe(m));
790}
791
792// Tests that Eq(x) matches any value equal to x.
793TEST(EqTest, MatchesEqualValue) {
794 // 2 C-strings with same content but different addresses.
795 const char a1[] = "hi";
796 const char a2[] = "hi";
797
798 Matcher<const char*> m1 = Eq(a1);
799 EXPECT_TRUE(m1.Matches(a1));
800 EXPECT_FALSE(m1.Matches(a2));
801}
802
803// Tests that Eq(v) describes itself properly.
804
805class Unprintable {
806 public:
807 Unprintable() : c_('a') {}
808
zhanyong.wan32de5f52009-12-23 00:13:23 +0000809 bool operator==(const Unprintable& /* rhs */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000810 private:
811 char c_;
812};
813
814TEST(EqTest, CanDescribeSelf) {
815 Matcher<Unprintable> m = Eq(Unprintable());
816 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
817}
818
819// Tests that Eq(v) can be used to match any type that supports
820// comparing with type T, where T is v's type.
821TEST(EqTest, IsPolymorphic) {
822 Matcher<int> m1 = Eq(1);
823 EXPECT_TRUE(m1.Matches(1));
824 EXPECT_FALSE(m1.Matches(2));
825
826 Matcher<char> m2 = Eq(1);
827 EXPECT_TRUE(m2.Matches('\1'));
828 EXPECT_FALSE(m2.Matches('a'));
829}
830
831// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
832TEST(TypedEqTest, ChecksEqualityForGivenType) {
833 Matcher<char> m1 = TypedEq<char>('a');
834 EXPECT_TRUE(m1.Matches('a'));
835 EXPECT_FALSE(m1.Matches('b'));
836
837 Matcher<int> m2 = TypedEq<int>(6);
838 EXPECT_TRUE(m2.Matches(6));
839 EXPECT_FALSE(m2.Matches(7));
840}
841
842// Tests that TypedEq(v) describes itself properly.
843TEST(TypedEqTest, CanDescribeSelf) {
844 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
845}
846
847// Tests that TypedEq<T>(v) has type Matcher<T>.
848
849// Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
850// is a "bare" type (i.e. not in the form of const U or U&). If v's
851// type is not T, the compiler will generate a message about
852// "undefined referece".
853template <typename T>
854struct Type {
zhanyong.wan32de5f52009-12-23 00:13:23 +0000855 static bool IsTypeOf(const T& /* v */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000856
857 template <typename T2>
858 static void IsTypeOf(T2 v);
859};
860
861TEST(TypedEqTest, HasSpecifiedType) {
862 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
863 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
864 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
865}
866
867// Tests that Ge(v) matches anything >= v.
868TEST(GeTest, ImplementsGreaterThanOrEqual) {
869 Matcher<int> m1 = Ge(0);
870 EXPECT_TRUE(m1.Matches(1));
871 EXPECT_TRUE(m1.Matches(0));
872 EXPECT_FALSE(m1.Matches(-1));
873}
874
875// Tests that Ge(v) describes itself properly.
876TEST(GeTest, CanDescribeSelf) {
877 Matcher<int> m = Ge(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000878 EXPECT_EQ("is >= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000879}
880
881// Tests that Gt(v) matches anything > v.
882TEST(GtTest, ImplementsGreaterThan) {
883 Matcher<double> m1 = Gt(0);
884 EXPECT_TRUE(m1.Matches(1.0));
885 EXPECT_FALSE(m1.Matches(0.0));
886 EXPECT_FALSE(m1.Matches(-1.0));
887}
888
889// Tests that Gt(v) describes itself properly.
890TEST(GtTest, CanDescribeSelf) {
891 Matcher<int> m = Gt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000892 EXPECT_EQ("is > 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000893}
894
895// Tests that Le(v) matches anything <= v.
896TEST(LeTest, ImplementsLessThanOrEqual) {
897 Matcher<char> m1 = Le('b');
898 EXPECT_TRUE(m1.Matches('a'));
899 EXPECT_TRUE(m1.Matches('b'));
900 EXPECT_FALSE(m1.Matches('c'));
901}
902
903// Tests that Le(v) describes itself properly.
904TEST(LeTest, CanDescribeSelf) {
905 Matcher<int> m = Le(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000906 EXPECT_EQ("is <= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000907}
908
909// Tests that Lt(v) matches anything < v.
910TEST(LtTest, ImplementsLessThan) {
911 Matcher<const string&> m1 = Lt("Hello");
912 EXPECT_TRUE(m1.Matches("Abc"));
913 EXPECT_FALSE(m1.Matches("Hello"));
914 EXPECT_FALSE(m1.Matches("Hello, world!"));
915}
916
917// Tests that Lt(v) describes itself properly.
918TEST(LtTest, CanDescribeSelf) {
919 Matcher<int> m = Lt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000920 EXPECT_EQ("is < 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000921}
922
923// Tests that Ne(v) matches anything != v.
924TEST(NeTest, ImplementsNotEqual) {
925 Matcher<int> m1 = Ne(0);
926 EXPECT_TRUE(m1.Matches(1));
927 EXPECT_TRUE(m1.Matches(-1));
928 EXPECT_FALSE(m1.Matches(0));
929}
930
931// Tests that Ne(v) describes itself properly.
932TEST(NeTest, CanDescribeSelf) {
933 Matcher<int> m = Ne(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000934 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000935}
936
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000937// Tests that IsNull() matches any NULL pointer of any type.
938TEST(IsNullTest, MatchesNullPointer) {
939 Matcher<int*> m1 = IsNull();
940 int* p1 = NULL;
941 int n = 0;
942 EXPECT_TRUE(m1.Matches(p1));
943 EXPECT_FALSE(m1.Matches(&n));
944
945 Matcher<const char*> m2 = IsNull();
946 const char* p2 = NULL;
947 EXPECT_TRUE(m2.Matches(p2));
948 EXPECT_FALSE(m2.Matches("hi"));
949
zhanyong.wan95b12332009-09-25 18:55:50 +0000950#if !GTEST_OS_SYMBIAN
951 // Nokia's Symbian compiler generates:
952 // gmock-matchers.h: ambiguous access to overloaded function
953 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
954 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
955 // MatcherInterface<void *> *)'
956 // gmock-matchers.h: (point of instantiation: 'testing::
957 // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
958 // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000959 Matcher<void*> m3 = IsNull();
960 void* p3 = NULL;
961 EXPECT_TRUE(m3.Matches(p3));
962 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
zhanyong.wan95b12332009-09-25 18:55:50 +0000963#endif
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000964}
965
vladlosev79b83502009-11-18 00:43:37 +0000966TEST(IsNullTest, LinkedPtr) {
967 const Matcher<linked_ptr<int> > m = IsNull();
968 const linked_ptr<int> null_p;
969 const linked_ptr<int> non_null_p(new int);
970
971 EXPECT_TRUE(m.Matches(null_p));
972 EXPECT_FALSE(m.Matches(non_null_p));
973}
974
975TEST(IsNullTest, ReferenceToConstLinkedPtr) {
976 const Matcher<const linked_ptr<double>&> m = IsNull();
977 const linked_ptr<double> null_p;
978 const linked_ptr<double> non_null_p(new double);
979
980 EXPECT_TRUE(m.Matches(null_p));
981 EXPECT_FALSE(m.Matches(non_null_p));
982}
983
vladloseve56daa72009-11-18 01:08:08 +0000984TEST(IsNullTest, ReferenceToConstScopedPtr) {
985 const Matcher<const scoped_ptr<double>&> m = IsNull();
986 const scoped_ptr<double> null_p;
987 const scoped_ptr<double> non_null_p(new double);
988
989 EXPECT_TRUE(m.Matches(null_p));
990 EXPECT_FALSE(m.Matches(non_null_p));
991}
992
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000993// Tests that IsNull() describes itself properly.
994TEST(IsNullTest, CanDescribeSelf) {
995 Matcher<int*> m = IsNull();
996 EXPECT_EQ("is NULL", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000997 EXPECT_EQ("isn't NULL", DescribeNegation(m));
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000998}
999
shiqiane35fdd92008-12-10 05:08:54 +00001000// Tests that NotNull() matches any non-NULL pointer of any type.
1001TEST(NotNullTest, MatchesNonNullPointer) {
1002 Matcher<int*> m1 = NotNull();
1003 int* p1 = NULL;
1004 int n = 0;
1005 EXPECT_FALSE(m1.Matches(p1));
1006 EXPECT_TRUE(m1.Matches(&n));
1007
1008 Matcher<const char*> m2 = NotNull();
1009 const char* p2 = NULL;
1010 EXPECT_FALSE(m2.Matches(p2));
1011 EXPECT_TRUE(m2.Matches("hi"));
1012}
1013
vladlosev79b83502009-11-18 00:43:37 +00001014TEST(NotNullTest, LinkedPtr) {
1015 const Matcher<linked_ptr<int> > m = NotNull();
1016 const linked_ptr<int> null_p;
1017 const linked_ptr<int> non_null_p(new int);
1018
1019 EXPECT_FALSE(m.Matches(null_p));
1020 EXPECT_TRUE(m.Matches(non_null_p));
1021}
1022
1023TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1024 const Matcher<const linked_ptr<double>&> m = NotNull();
1025 const linked_ptr<double> null_p;
1026 const linked_ptr<double> non_null_p(new double);
1027
1028 EXPECT_FALSE(m.Matches(null_p));
1029 EXPECT_TRUE(m.Matches(non_null_p));
1030}
1031
vladloseve56daa72009-11-18 01:08:08 +00001032TEST(NotNullTest, ReferenceToConstScopedPtr) {
1033 const Matcher<const scoped_ptr<double>&> m = NotNull();
1034 const scoped_ptr<double> null_p;
1035 const scoped_ptr<double> non_null_p(new double);
1036
1037 EXPECT_FALSE(m.Matches(null_p));
1038 EXPECT_TRUE(m.Matches(non_null_p));
1039}
1040
shiqiane35fdd92008-12-10 05:08:54 +00001041// Tests that NotNull() describes itself properly.
1042TEST(NotNullTest, CanDescribeSelf) {
1043 Matcher<int*> m = NotNull();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001044 EXPECT_EQ("isn't NULL", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001045}
1046
1047// Tests that Ref(variable) matches an argument that references
1048// 'variable'.
1049TEST(RefTest, MatchesSameVariable) {
1050 int a = 0;
1051 int b = 0;
1052 Matcher<int&> m = Ref(a);
1053 EXPECT_TRUE(m.Matches(a));
1054 EXPECT_FALSE(m.Matches(b));
1055}
1056
1057// Tests that Ref(variable) describes itself properly.
1058TEST(RefTest, CanDescribeSelf) {
1059 int n = 5;
1060 Matcher<int&> m = Ref(n);
1061 stringstream ss;
1062 ss << "references the variable @" << &n << " 5";
1063 EXPECT_EQ(string(ss.str()), Describe(m));
1064}
1065
1066// Test that Ref(non_const_varialbe) can be used as a matcher for a
1067// const reference.
1068TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1069 int a = 0;
1070 int b = 0;
1071 Matcher<const int&> m = Ref(a);
1072 EXPECT_TRUE(m.Matches(a));
1073 EXPECT_FALSE(m.Matches(b));
1074}
1075
1076// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1077// used wherever Ref(base) can be used (Ref(derived) is a sub-type
1078// of Ref(base), but not vice versa.
1079
shiqiane35fdd92008-12-10 05:08:54 +00001080TEST(RefTest, IsCovariant) {
1081 Base base, base2;
1082 Derived derived;
1083 Matcher<const Base&> m1 = Ref(base);
1084 EXPECT_TRUE(m1.Matches(base));
1085 EXPECT_FALSE(m1.Matches(base2));
1086 EXPECT_FALSE(m1.Matches(derived));
1087
1088 m1 = Ref(derived);
1089 EXPECT_TRUE(m1.Matches(derived));
1090 EXPECT_FALSE(m1.Matches(base));
1091 EXPECT_FALSE(m1.Matches(base2));
1092}
1093
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001094TEST(RefTest, ExplainsResult) {
1095 int n = 0;
1096 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1097 StartsWith("which is located @"));
1098
1099 int m = 0;
1100 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1101 StartsWith("which is located @"));
1102}
1103
shiqiane35fdd92008-12-10 05:08:54 +00001104// Tests string comparison matchers.
1105
1106TEST(StrEqTest, MatchesEqualString) {
1107 Matcher<const char*> m = StrEq(string("Hello"));
1108 EXPECT_TRUE(m.Matches("Hello"));
1109 EXPECT_FALSE(m.Matches("hello"));
1110 EXPECT_FALSE(m.Matches(NULL));
1111
1112 Matcher<const string&> m2 = StrEq("Hello");
1113 EXPECT_TRUE(m2.Matches("Hello"));
1114 EXPECT_FALSE(m2.Matches("Hi"));
1115}
1116
1117TEST(StrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001118 Matcher<string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1119 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
shiqiane35fdd92008-12-10 05:08:54 +00001120 Describe(m));
1121
1122 string str("01204500800");
1123 str[3] = '\0';
1124 Matcher<string> m2 = StrEq(str);
1125 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1126 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1127 Matcher<string> m3 = StrEq(str);
1128 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1129}
1130
1131TEST(StrNeTest, MatchesUnequalString) {
1132 Matcher<const char*> m = StrNe("Hello");
1133 EXPECT_TRUE(m.Matches(""));
1134 EXPECT_TRUE(m.Matches(NULL));
1135 EXPECT_FALSE(m.Matches("Hello"));
1136
1137 Matcher<string> m2 = StrNe(string("Hello"));
1138 EXPECT_TRUE(m2.Matches("hello"));
1139 EXPECT_FALSE(m2.Matches("Hello"));
1140}
1141
1142TEST(StrNeTest, CanDescribeSelf) {
1143 Matcher<const char*> m = StrNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001144 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001145}
1146
1147TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1148 Matcher<const char*> m = StrCaseEq(string("Hello"));
1149 EXPECT_TRUE(m.Matches("Hello"));
1150 EXPECT_TRUE(m.Matches("hello"));
1151 EXPECT_FALSE(m.Matches("Hi"));
1152 EXPECT_FALSE(m.Matches(NULL));
1153
1154 Matcher<const string&> m2 = StrCaseEq("Hello");
1155 EXPECT_TRUE(m2.Matches("hello"));
1156 EXPECT_FALSE(m2.Matches("Hi"));
1157}
1158
1159TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1160 string str1("oabocdooeoo");
1161 string str2("OABOCDOOEOO");
1162 Matcher<const string&> m0 = StrCaseEq(str1);
1163 EXPECT_FALSE(m0.Matches(str2 + string(1, '\0')));
1164
1165 str1[3] = str2[3] = '\0';
1166 Matcher<const string&> m1 = StrCaseEq(str1);
1167 EXPECT_TRUE(m1.Matches(str2));
1168
1169 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1170 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1171 Matcher<const string&> m2 = StrCaseEq(str1);
1172 str1[9] = str2[9] = '\0';
1173 EXPECT_FALSE(m2.Matches(str2));
1174
1175 Matcher<const string&> m3 = StrCaseEq(str1);
1176 EXPECT_TRUE(m3.Matches(str2));
1177
1178 EXPECT_FALSE(m3.Matches(str2 + "x"));
1179 str2.append(1, '\0');
1180 EXPECT_FALSE(m3.Matches(str2));
1181 EXPECT_FALSE(m3.Matches(string(str2, 0, 9)));
1182}
1183
1184TEST(StrCaseEqTest, CanDescribeSelf) {
1185 Matcher<string> m = StrCaseEq("Hi");
1186 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1187}
1188
1189TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1190 Matcher<const char*> m = StrCaseNe("Hello");
1191 EXPECT_TRUE(m.Matches("Hi"));
1192 EXPECT_TRUE(m.Matches(NULL));
1193 EXPECT_FALSE(m.Matches("Hello"));
1194 EXPECT_FALSE(m.Matches("hello"));
1195
1196 Matcher<string> m2 = StrCaseNe(string("Hello"));
1197 EXPECT_TRUE(m2.Matches(""));
1198 EXPECT_FALSE(m2.Matches("Hello"));
1199}
1200
1201TEST(StrCaseNeTest, CanDescribeSelf) {
1202 Matcher<const char*> m = StrCaseNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001203 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001204}
1205
1206// Tests that HasSubstr() works for matching string-typed values.
1207TEST(HasSubstrTest, WorksForStringClasses) {
1208 const Matcher<string> m1 = HasSubstr("foo");
1209 EXPECT_TRUE(m1.Matches(string("I love food.")));
1210 EXPECT_FALSE(m1.Matches(string("tofo")));
1211
1212 const Matcher<const std::string&> m2 = HasSubstr("foo");
1213 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1214 EXPECT_FALSE(m2.Matches(std::string("tofo")));
1215}
1216
1217// Tests that HasSubstr() works for matching C-string-typed values.
1218TEST(HasSubstrTest, WorksForCStrings) {
1219 const Matcher<char*> m1 = HasSubstr("foo");
1220 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1221 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1222 EXPECT_FALSE(m1.Matches(NULL));
1223
1224 const Matcher<const char*> m2 = HasSubstr("foo");
1225 EXPECT_TRUE(m2.Matches("I love food."));
1226 EXPECT_FALSE(m2.Matches("tofo"));
1227 EXPECT_FALSE(m2.Matches(NULL));
1228}
1229
1230// Tests that HasSubstr(s) describes itself properly.
1231TEST(HasSubstrTest, CanDescribeSelf) {
1232 Matcher<string> m = HasSubstr("foo\n\"");
1233 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1234}
1235
zhanyong.wanb5937da2009-07-16 20:26:41 +00001236TEST(KeyTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001237 Matcher<const pair<std::string, int>&> m = Key("foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001238 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001239 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1240}
1241
1242TEST(KeyTest, ExplainsResult) {
1243 Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1244 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1245 Explain(m, make_pair(5, true)));
1246 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1247 Explain(m, make_pair(15, true)));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001248}
1249
1250TEST(KeyTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001251 pair<int, std::string> p(25, "foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001252 EXPECT_THAT(p, Key(25));
1253 EXPECT_THAT(p, Not(Key(42)));
1254 EXPECT_THAT(p, Key(Ge(20)));
1255 EXPECT_THAT(p, Not(Key(Lt(25))));
1256}
1257
1258TEST(KeyTest, SafelyCastsInnerMatcher) {
1259 Matcher<int> is_positive = Gt(0);
1260 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001261 pair<char, bool> p('a', true);
zhanyong.wanb5937da2009-07-16 20:26:41 +00001262 EXPECT_THAT(p, Key(is_positive));
1263 EXPECT_THAT(p, Not(Key(is_negative)));
1264}
1265
1266TEST(KeyTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001267 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001268 container.insert(make_pair(1, 'a'));
1269 container.insert(make_pair(2, 'b'));
1270 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001271 EXPECT_THAT(container, Contains(Key(1)));
1272 EXPECT_THAT(container, Not(Contains(Key(3))));
1273}
1274
1275TEST(KeyTest, InsideContainsUsingMultimap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001276 multimap<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001277 container.insert(make_pair(1, 'a'));
1278 container.insert(make_pair(2, 'b'));
1279 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001280
1281 EXPECT_THAT(container, Not(Contains(Key(25))));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001282 container.insert(make_pair(25, 'd'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001283 EXPECT_THAT(container, Contains(Key(25)));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001284 container.insert(make_pair(25, 'e'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001285 EXPECT_THAT(container, Contains(Key(25)));
1286
1287 EXPECT_THAT(container, Contains(Key(1)));
1288 EXPECT_THAT(container, Not(Contains(Key(3))));
1289}
1290
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001291TEST(PairTest, Typing) {
1292 // Test verifies the following type conversions can be compiled.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001293 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1294 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1295 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001296
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001297 Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1298 Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001299}
1300
1301TEST(PairTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001302 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001303 EXPECT_EQ("has a first field that is equal to \"foo\""
1304 ", and has a second field that is equal to 42",
1305 Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001306 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1307 ", or has a second field that isn't equal to 42",
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001308 DescribeNegation(m1));
1309 // Double and triple negation (1 or 2 times not and description of negation).
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001310 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1311 EXPECT_EQ("has a first field that isn't equal to 13"
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001312 ", and has a second field that is equal to 42",
1313 DescribeNegation(m2));
1314}
1315
1316TEST(PairTest, CanExplainMatchResultTo) {
zhanyong.wan82113312010-01-08 21:55:40 +00001317 // If neither field matches, Pair() should explain about the first
1318 // field.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001319 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001320 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001321 Explain(m, make_pair(-1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001322
zhanyong.wan82113312010-01-08 21:55:40 +00001323 // If the first field matches but the second doesn't, Pair() should
1324 // explain about the second field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001325 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001326 Explain(m, make_pair(1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001327
zhanyong.wan82113312010-01-08 21:55:40 +00001328 // If the first field doesn't match but the second does, Pair()
1329 // should explain about the first field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001330 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001331 Explain(m, make_pair(-1, 2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001332
zhanyong.wan82113312010-01-08 21:55:40 +00001333 // If both fields match, Pair() should explain about them both.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001334 EXPECT_EQ("whose both fields match, where the first field is a value "
1335 "which is 1 more than 0, and the second field is a value "
1336 "which is 2 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001337 Explain(m, make_pair(1, 2)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001338
1339 // If only the first match has an explanation, only this explanation should
1340 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001341 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001342 EXPECT_EQ("whose both fields match, where the first field is a value "
1343 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001344 Explain(explain_first, make_pair(1, 0)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001345
1346 // If only the second match has an explanation, only this explanation should
1347 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001348 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001349 EXPECT_EQ("whose both fields match, where the second field is a value "
1350 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001351 Explain(explain_second, make_pair(0, 1)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001352}
1353
1354TEST(PairTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001355 pair<int, std::string> p(25, "foo");
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001356
1357 // Both fields match.
1358 EXPECT_THAT(p, Pair(25, "foo"));
1359 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1360
1361 // 'first' doesnt' match, but 'second' matches.
1362 EXPECT_THAT(p, Not(Pair(42, "foo")));
1363 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1364
1365 // 'first' matches, but 'second' doesn't match.
1366 EXPECT_THAT(p, Not(Pair(25, "bar")));
1367 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1368
1369 // Neither field matches.
1370 EXPECT_THAT(p, Not(Pair(13, "bar")));
1371 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1372}
1373
1374TEST(PairTest, SafelyCastsInnerMatchers) {
1375 Matcher<int> is_positive = Gt(0);
1376 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001377 pair<char, bool> p('a', true);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001378 EXPECT_THAT(p, Pair(is_positive, _));
1379 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1380 EXPECT_THAT(p, Pair(_, is_positive));
1381 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1382}
1383
1384TEST(PairTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001385 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001386 container.insert(make_pair(1, 'a'));
1387 container.insert(make_pair(2, 'b'));
1388 container.insert(make_pair(4, 'c'));
zhanyong.wan95b12332009-09-25 18:55:50 +00001389 EXPECT_THAT(container, Contains(Pair(1, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001390 EXPECT_THAT(container, Contains(Pair(1, _)));
zhanyong.wan95b12332009-09-25 18:55:50 +00001391 EXPECT_THAT(container, Contains(Pair(_, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001392 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1393}
1394
shiqiane35fdd92008-12-10 05:08:54 +00001395// Tests StartsWith(s).
1396
1397TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1398 const Matcher<const char*> m1 = StartsWith(string(""));
1399 EXPECT_TRUE(m1.Matches("Hi"));
1400 EXPECT_TRUE(m1.Matches(""));
1401 EXPECT_FALSE(m1.Matches(NULL));
1402
1403 const Matcher<const string&> m2 = StartsWith("Hi");
1404 EXPECT_TRUE(m2.Matches("Hi"));
1405 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1406 EXPECT_TRUE(m2.Matches("High"));
1407 EXPECT_FALSE(m2.Matches("H"));
1408 EXPECT_FALSE(m2.Matches(" Hi"));
1409}
1410
1411TEST(StartsWithTest, CanDescribeSelf) {
1412 Matcher<const std::string> m = StartsWith("Hi");
1413 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1414}
1415
1416// Tests EndsWith(s).
1417
1418TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1419 const Matcher<const char*> m1 = EndsWith("");
1420 EXPECT_TRUE(m1.Matches("Hi"));
1421 EXPECT_TRUE(m1.Matches(""));
1422 EXPECT_FALSE(m1.Matches(NULL));
1423
1424 const Matcher<const string&> m2 = EndsWith(string("Hi"));
1425 EXPECT_TRUE(m2.Matches("Hi"));
1426 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1427 EXPECT_TRUE(m2.Matches("Super Hi"));
1428 EXPECT_FALSE(m2.Matches("i"));
1429 EXPECT_FALSE(m2.Matches("Hi "));
1430}
1431
1432TEST(EndsWithTest, CanDescribeSelf) {
1433 Matcher<const std::string> m = EndsWith("Hi");
1434 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1435}
1436
shiqiane35fdd92008-12-10 05:08:54 +00001437// Tests MatchesRegex().
1438
1439TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1440 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1441 EXPECT_TRUE(m1.Matches("az"));
1442 EXPECT_TRUE(m1.Matches("abcz"));
1443 EXPECT_FALSE(m1.Matches(NULL));
1444
1445 const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z"));
1446 EXPECT_TRUE(m2.Matches("azbz"));
1447 EXPECT_FALSE(m2.Matches("az1"));
1448 EXPECT_FALSE(m2.Matches("1az"));
1449}
1450
1451TEST(MatchesRegexTest, CanDescribeSelf) {
1452 Matcher<const std::string> m1 = MatchesRegex(string("Hi.*"));
1453 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1454
zhanyong.wand14aaed2010-01-14 05:36:32 +00001455 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1456 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001457}
1458
1459// Tests ContainsRegex().
1460
1461TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1462 const Matcher<const char*> m1 = ContainsRegex(string("a.*z"));
1463 EXPECT_TRUE(m1.Matches("az"));
1464 EXPECT_TRUE(m1.Matches("0abcz1"));
1465 EXPECT_FALSE(m1.Matches(NULL));
1466
1467 const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z"));
1468 EXPECT_TRUE(m2.Matches("azbz"));
1469 EXPECT_TRUE(m2.Matches("az1"));
1470 EXPECT_FALSE(m2.Matches("1a"));
1471}
1472
1473TEST(ContainsRegexTest, CanDescribeSelf) {
1474 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1475 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1476
zhanyong.wand14aaed2010-01-14 05:36:32 +00001477 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1478 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001479}
shiqiane35fdd92008-12-10 05:08:54 +00001480
1481// Tests for wide strings.
1482#if GTEST_HAS_STD_WSTRING
1483TEST(StdWideStrEqTest, MatchesEqual) {
1484 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1485 EXPECT_TRUE(m.Matches(L"Hello"));
1486 EXPECT_FALSE(m.Matches(L"hello"));
1487 EXPECT_FALSE(m.Matches(NULL));
1488
1489 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1490 EXPECT_TRUE(m2.Matches(L"Hello"));
1491 EXPECT_FALSE(m2.Matches(L"Hi"));
1492
1493 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1494 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1495 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1496
1497 ::std::wstring str(L"01204500800");
1498 str[3] = L'\0';
1499 Matcher<const ::std::wstring&> m4 = StrEq(str);
1500 EXPECT_TRUE(m4.Matches(str));
1501 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1502 Matcher<const ::std::wstring&> m5 = StrEq(str);
1503 EXPECT_TRUE(m5.Matches(str));
1504}
1505
1506TEST(StdWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001507 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1508 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001509 Describe(m));
1510
1511 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1512 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1513 Describe(m2));
1514
1515 ::std::wstring str(L"01204500800");
1516 str[3] = L'\0';
1517 Matcher<const ::std::wstring&> m4 = StrEq(str);
1518 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1519 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1520 Matcher<const ::std::wstring&> m5 = StrEq(str);
1521 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1522}
1523
1524TEST(StdWideStrNeTest, MatchesUnequalString) {
1525 Matcher<const wchar_t*> m = StrNe(L"Hello");
1526 EXPECT_TRUE(m.Matches(L""));
1527 EXPECT_TRUE(m.Matches(NULL));
1528 EXPECT_FALSE(m.Matches(L"Hello"));
1529
1530 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1531 EXPECT_TRUE(m2.Matches(L"hello"));
1532 EXPECT_FALSE(m2.Matches(L"Hello"));
1533}
1534
1535TEST(StdWideStrNeTest, CanDescribeSelf) {
1536 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001537 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001538}
1539
1540TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1541 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1542 EXPECT_TRUE(m.Matches(L"Hello"));
1543 EXPECT_TRUE(m.Matches(L"hello"));
1544 EXPECT_FALSE(m.Matches(L"Hi"));
1545 EXPECT_FALSE(m.Matches(NULL));
1546
1547 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1548 EXPECT_TRUE(m2.Matches(L"hello"));
1549 EXPECT_FALSE(m2.Matches(L"Hi"));
1550}
1551
1552TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1553 ::std::wstring str1(L"oabocdooeoo");
1554 ::std::wstring str2(L"OABOCDOOEOO");
1555 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1556 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1557
1558 str1[3] = str2[3] = L'\0';
1559 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1560 EXPECT_TRUE(m1.Matches(str2));
1561
1562 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1563 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1564 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1565 str1[9] = str2[9] = L'\0';
1566 EXPECT_FALSE(m2.Matches(str2));
1567
1568 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1569 EXPECT_TRUE(m3.Matches(str2));
1570
1571 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1572 str2.append(1, L'\0');
1573 EXPECT_FALSE(m3.Matches(str2));
1574 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1575}
1576
1577TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1578 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1579 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1580}
1581
1582TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1583 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1584 EXPECT_TRUE(m.Matches(L"Hi"));
1585 EXPECT_TRUE(m.Matches(NULL));
1586 EXPECT_FALSE(m.Matches(L"Hello"));
1587 EXPECT_FALSE(m.Matches(L"hello"));
1588
1589 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1590 EXPECT_TRUE(m2.Matches(L""));
1591 EXPECT_FALSE(m2.Matches(L"Hello"));
1592}
1593
1594TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1595 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001596 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001597}
1598
1599// Tests that HasSubstr() works for matching wstring-typed values.
1600TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1601 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1602 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1603 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1604
1605 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1606 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1607 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1608}
1609
1610// Tests that HasSubstr() works for matching C-wide-string-typed values.
1611TEST(StdWideHasSubstrTest, WorksForCStrings) {
1612 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1613 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1614 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1615 EXPECT_FALSE(m1.Matches(NULL));
1616
1617 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1618 EXPECT_TRUE(m2.Matches(L"I love food."));
1619 EXPECT_FALSE(m2.Matches(L"tofo"));
1620 EXPECT_FALSE(m2.Matches(NULL));
1621}
1622
1623// Tests that HasSubstr(s) describes itself properly.
1624TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1625 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1626 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1627}
1628
1629// Tests StartsWith(s).
1630
1631TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1632 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1633 EXPECT_TRUE(m1.Matches(L"Hi"));
1634 EXPECT_TRUE(m1.Matches(L""));
1635 EXPECT_FALSE(m1.Matches(NULL));
1636
1637 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1638 EXPECT_TRUE(m2.Matches(L"Hi"));
1639 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1640 EXPECT_TRUE(m2.Matches(L"High"));
1641 EXPECT_FALSE(m2.Matches(L"H"));
1642 EXPECT_FALSE(m2.Matches(L" Hi"));
1643}
1644
1645TEST(StdWideStartsWithTest, CanDescribeSelf) {
1646 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
1647 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1648}
1649
1650// Tests EndsWith(s).
1651
1652TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
1653 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1654 EXPECT_TRUE(m1.Matches(L"Hi"));
1655 EXPECT_TRUE(m1.Matches(L""));
1656 EXPECT_FALSE(m1.Matches(NULL));
1657
1658 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
1659 EXPECT_TRUE(m2.Matches(L"Hi"));
1660 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1661 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1662 EXPECT_FALSE(m2.Matches(L"i"));
1663 EXPECT_FALSE(m2.Matches(L"Hi "));
1664}
1665
1666TEST(StdWideEndsWithTest, CanDescribeSelf) {
1667 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
1668 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1669}
1670
1671#endif // GTEST_HAS_STD_WSTRING
1672
1673#if GTEST_HAS_GLOBAL_WSTRING
1674TEST(GlobalWideStrEqTest, MatchesEqual) {
1675 Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
1676 EXPECT_TRUE(m.Matches(L"Hello"));
1677 EXPECT_FALSE(m.Matches(L"hello"));
1678 EXPECT_FALSE(m.Matches(NULL));
1679
1680 Matcher<const ::wstring&> m2 = StrEq(L"Hello");
1681 EXPECT_TRUE(m2.Matches(L"Hello"));
1682 EXPECT_FALSE(m2.Matches(L"Hi"));
1683
1684 Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1685 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1686 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1687
1688 ::wstring str(L"01204500800");
1689 str[3] = L'\0';
1690 Matcher<const ::wstring&> m4 = StrEq(str);
1691 EXPECT_TRUE(m4.Matches(str));
1692 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1693 Matcher<const ::wstring&> m5 = StrEq(str);
1694 EXPECT_TRUE(m5.Matches(str));
1695}
1696
1697TEST(GlobalWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001698 Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1699 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001700 Describe(m));
1701
1702 Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1703 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1704 Describe(m2));
1705
1706 ::wstring str(L"01204500800");
1707 str[3] = L'\0';
1708 Matcher<const ::wstring&> m4 = StrEq(str);
1709 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1710 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1711 Matcher<const ::wstring&> m5 = StrEq(str);
1712 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1713}
1714
1715TEST(GlobalWideStrNeTest, MatchesUnequalString) {
1716 Matcher<const wchar_t*> m = StrNe(L"Hello");
1717 EXPECT_TRUE(m.Matches(L""));
1718 EXPECT_TRUE(m.Matches(NULL));
1719 EXPECT_FALSE(m.Matches(L"Hello"));
1720
1721 Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
1722 EXPECT_TRUE(m2.Matches(L"hello"));
1723 EXPECT_FALSE(m2.Matches(L"Hello"));
1724}
1725
1726TEST(GlobalWideStrNeTest, CanDescribeSelf) {
1727 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001728 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001729}
1730
1731TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1732 Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
1733 EXPECT_TRUE(m.Matches(L"Hello"));
1734 EXPECT_TRUE(m.Matches(L"hello"));
1735 EXPECT_FALSE(m.Matches(L"Hi"));
1736 EXPECT_FALSE(m.Matches(NULL));
1737
1738 Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
1739 EXPECT_TRUE(m2.Matches(L"hello"));
1740 EXPECT_FALSE(m2.Matches(L"Hi"));
1741}
1742
1743TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1744 ::wstring str1(L"oabocdooeoo");
1745 ::wstring str2(L"OABOCDOOEOO");
1746 Matcher<const ::wstring&> m0 = StrCaseEq(str1);
1747 EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
1748
1749 str1[3] = str2[3] = L'\0';
1750 Matcher<const ::wstring&> m1 = StrCaseEq(str1);
1751 EXPECT_TRUE(m1.Matches(str2));
1752
1753 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1754 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1755 Matcher<const ::wstring&> m2 = StrCaseEq(str1);
1756 str1[9] = str2[9] = L'\0';
1757 EXPECT_FALSE(m2.Matches(str2));
1758
1759 Matcher<const ::wstring&> m3 = StrCaseEq(str1);
1760 EXPECT_TRUE(m3.Matches(str2));
1761
1762 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1763 str2.append(1, L'\0');
1764 EXPECT_FALSE(m3.Matches(str2));
1765 EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
1766}
1767
1768TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
1769 Matcher< ::wstring> m = StrCaseEq(L"Hi");
1770 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1771}
1772
1773TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1774 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1775 EXPECT_TRUE(m.Matches(L"Hi"));
1776 EXPECT_TRUE(m.Matches(NULL));
1777 EXPECT_FALSE(m.Matches(L"Hello"));
1778 EXPECT_FALSE(m.Matches(L"hello"));
1779
1780 Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
1781 EXPECT_TRUE(m2.Matches(L""));
1782 EXPECT_FALSE(m2.Matches(L"Hello"));
1783}
1784
1785TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
1786 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001787 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001788}
1789
1790// Tests that HasSubstr() works for matching wstring-typed values.
1791TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
1792 const Matcher< ::wstring> m1 = HasSubstr(L"foo");
1793 EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
1794 EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
1795
1796 const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
1797 EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
1798 EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
1799}
1800
1801// Tests that HasSubstr() works for matching C-wide-string-typed values.
1802TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
1803 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1804 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1805 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1806 EXPECT_FALSE(m1.Matches(NULL));
1807
1808 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1809 EXPECT_TRUE(m2.Matches(L"I love food."));
1810 EXPECT_FALSE(m2.Matches(L"tofo"));
1811 EXPECT_FALSE(m2.Matches(NULL));
1812}
1813
1814// Tests that HasSubstr(s) describes itself properly.
1815TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
1816 Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
1817 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1818}
1819
1820// Tests StartsWith(s).
1821
1822TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
1823 const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
1824 EXPECT_TRUE(m1.Matches(L"Hi"));
1825 EXPECT_TRUE(m1.Matches(L""));
1826 EXPECT_FALSE(m1.Matches(NULL));
1827
1828 const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
1829 EXPECT_TRUE(m2.Matches(L"Hi"));
1830 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1831 EXPECT_TRUE(m2.Matches(L"High"));
1832 EXPECT_FALSE(m2.Matches(L"H"));
1833 EXPECT_FALSE(m2.Matches(L" Hi"));
1834}
1835
1836TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
1837 Matcher<const ::wstring> m = StartsWith(L"Hi");
1838 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1839}
1840
1841// Tests EndsWith(s).
1842
1843TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
1844 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1845 EXPECT_TRUE(m1.Matches(L"Hi"));
1846 EXPECT_TRUE(m1.Matches(L""));
1847 EXPECT_FALSE(m1.Matches(NULL));
1848
1849 const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
1850 EXPECT_TRUE(m2.Matches(L"Hi"));
1851 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1852 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1853 EXPECT_FALSE(m2.Matches(L"i"));
1854 EXPECT_FALSE(m2.Matches(L"Hi "));
1855}
1856
1857TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
1858 Matcher<const ::wstring> m = EndsWith(L"Hi");
1859 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1860}
1861
1862#endif // GTEST_HAS_GLOBAL_WSTRING
1863
1864
1865typedef ::std::tr1::tuple<long, int> Tuple2; // NOLINT
1866
1867// Tests that Eq() matches a 2-tuple where the first field == the
1868// second field.
1869TEST(Eq2Test, MatchesEqualArguments) {
1870 Matcher<const Tuple2&> m = Eq();
1871 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1872 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1873}
1874
1875// Tests that Eq() describes itself properly.
1876TEST(Eq2Test, CanDescribeSelf) {
1877 Matcher<const Tuple2&> m = Eq();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001878 EXPECT_EQ("are an equal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001879}
1880
1881// Tests that Ge() matches a 2-tuple where the first field >= the
1882// second field.
1883TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
1884 Matcher<const Tuple2&> m = Ge();
1885 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1886 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1887 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1888}
1889
1890// Tests that Ge() describes itself properly.
1891TEST(Ge2Test, CanDescribeSelf) {
1892 Matcher<const Tuple2&> m = Ge();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001893 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001894}
1895
1896// Tests that Gt() matches a 2-tuple where the first field > the
1897// second field.
1898TEST(Gt2Test, MatchesGreaterThanArguments) {
1899 Matcher<const Tuple2&> m = Gt();
1900 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1901 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1902 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1903}
1904
1905// Tests that Gt() describes itself properly.
1906TEST(Gt2Test, CanDescribeSelf) {
1907 Matcher<const Tuple2&> m = Gt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001908 EXPECT_EQ("are a pair where the first > the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001909}
1910
1911// Tests that Le() matches a 2-tuple where the first field <= the
1912// second field.
1913TEST(Le2Test, MatchesLessThanOrEqualArguments) {
1914 Matcher<const Tuple2&> m = Le();
1915 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1916 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1917 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1918}
1919
1920// Tests that Le() describes itself properly.
1921TEST(Le2Test, CanDescribeSelf) {
1922 Matcher<const Tuple2&> m = Le();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001923 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001924}
1925
1926// Tests that Lt() matches a 2-tuple where the first field < the
1927// second field.
1928TEST(Lt2Test, MatchesLessThanArguments) {
1929 Matcher<const Tuple2&> m = Lt();
1930 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1931 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1932 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1933}
1934
1935// Tests that Lt() describes itself properly.
1936TEST(Lt2Test, CanDescribeSelf) {
1937 Matcher<const Tuple2&> m = Lt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001938 EXPECT_EQ("are a pair where the first < the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001939}
1940
1941// Tests that Ne() matches a 2-tuple where the first field != the
1942// second field.
1943TEST(Ne2Test, MatchesUnequalArguments) {
1944 Matcher<const Tuple2&> m = Ne();
1945 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1946 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1947 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1948}
1949
1950// Tests that Ne() describes itself properly.
1951TEST(Ne2Test, CanDescribeSelf) {
1952 Matcher<const Tuple2&> m = Ne();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001953 EXPECT_EQ("are an unequal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001954}
1955
1956// Tests that Not(m) matches any value that doesn't match m.
1957TEST(NotTest, NegatesMatcher) {
1958 Matcher<int> m;
1959 m = Not(Eq(2));
1960 EXPECT_TRUE(m.Matches(3));
1961 EXPECT_FALSE(m.Matches(2));
1962}
1963
1964// Tests that Not(m) describes itself properly.
1965TEST(NotTest, CanDescribeSelf) {
1966 Matcher<int> m = Not(Eq(5));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001967 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001968}
1969
zhanyong.wan18490652009-05-11 18:54:08 +00001970// Tests that monomorphic matchers are safely cast by the Not matcher.
1971TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
1972 // greater_than_5 is a monomorphic matcher.
1973 Matcher<int> greater_than_5 = Gt(5);
1974
1975 Matcher<const int&> m = Not(greater_than_5);
1976 Matcher<int&> m2 = Not(greater_than_5);
1977 Matcher<int&> m3 = Not(m);
1978}
1979
zhanyong.wan02c15052010-06-09 19:21:30 +00001980// Helper to allow easy testing of AllOf matchers with num parameters.
1981void AllOfMatches(int num, const Matcher<int>& m) {
1982 SCOPED_TRACE(Describe(m));
1983 EXPECT_TRUE(m.Matches(0));
1984 for (int i = 1; i <= num; ++i) {
1985 EXPECT_FALSE(m.Matches(i));
1986 }
1987 EXPECT_TRUE(m.Matches(num + 1));
1988}
1989
shiqiane35fdd92008-12-10 05:08:54 +00001990// Tests that AllOf(m1, ..., mn) matches any value that matches all of
1991// the given matchers.
1992TEST(AllOfTest, MatchesWhenAllMatch) {
1993 Matcher<int> m;
1994 m = AllOf(Le(2), Ge(1));
1995 EXPECT_TRUE(m.Matches(1));
1996 EXPECT_TRUE(m.Matches(2));
1997 EXPECT_FALSE(m.Matches(0));
1998 EXPECT_FALSE(m.Matches(3));
1999
2000 m = AllOf(Gt(0), Ne(1), Ne(2));
2001 EXPECT_TRUE(m.Matches(3));
2002 EXPECT_FALSE(m.Matches(2));
2003 EXPECT_FALSE(m.Matches(1));
2004 EXPECT_FALSE(m.Matches(0));
2005
2006 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2007 EXPECT_TRUE(m.Matches(4));
2008 EXPECT_FALSE(m.Matches(3));
2009 EXPECT_FALSE(m.Matches(2));
2010 EXPECT_FALSE(m.Matches(1));
2011 EXPECT_FALSE(m.Matches(0));
2012
2013 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2014 EXPECT_TRUE(m.Matches(0));
2015 EXPECT_TRUE(m.Matches(1));
2016 EXPECT_FALSE(m.Matches(3));
zhanyong.wan02c15052010-06-09 19:21:30 +00002017
2018 // The following tests for varying number of sub-matchers. Due to the way
2019 // the sub-matchers are handled it is enough to test every sub-matcher once
2020 // with sub-matchers using the same matcher type. Varying matcher types are
2021 // checked for above.
2022 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2023 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2024 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2025 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2026 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2027 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2028 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2029 Ne(8)));
2030 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2031 Ne(8), Ne(9)));
2032 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2033 Ne(9), Ne(10)));
shiqiane35fdd92008-12-10 05:08:54 +00002034}
2035
zhanyong.wan616180e2013-06-18 18:49:51 +00002036#if GTEST_LANG_CXX11
2037// Tests the variadic version of the AllOfMatcher.
2038TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
2039 // Make sure AllOf is defined in the right namespace and does not depend on
2040 // ADL.
2041 ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2042 Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2043 Ne(9), Ne(10), Ne(11));
2044 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))"));
2045 AllOfMatches(11, m);
2046 AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2047 Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
2048 Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22),
2049 Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29),
2050 Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36),
2051 Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43),
2052 Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2053 Ne(50)));
2054}
2055
2056#endif // GTEST_LANG_CXX11
2057
shiqiane35fdd92008-12-10 05:08:54 +00002058// Tests that AllOf(m1, ..., mn) describes itself properly.
2059TEST(AllOfTest, CanDescribeSelf) {
2060 Matcher<int> m;
2061 m = AllOf(Le(2), Ge(1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002062 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002063
2064 m = AllOf(Gt(0), Ne(1), Ne(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002065 EXPECT_EQ("(is > 0) and "
2066 "((isn't equal to 1) and "
2067 "(isn't equal to 2))",
shiqiane35fdd92008-12-10 05:08:54 +00002068 Describe(m));
2069
2070
2071 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002072 EXPECT_EQ("((is > 0) and "
2073 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002074 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002075 "(isn't equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002076 Describe(m));
2077
2078
2079 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002080 EXPECT_EQ("((is >= 0) and "
2081 "(is < 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002082 "((isn't equal to 3) and "
2083 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002084 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002085 Describe(m));
2086}
2087
2088// Tests that AllOf(m1, ..., mn) describes its negation properly.
2089TEST(AllOfTest, CanDescribeNegation) {
2090 Matcher<int> m;
2091 m = AllOf(Le(2), Ge(1));
2092 EXPECT_EQ("(isn't <= 2) or "
2093 "(isn't >= 1)",
2094 DescribeNegation(m));
2095
2096 m = AllOf(Gt(0), Ne(1), Ne(2));
2097 EXPECT_EQ("(isn't > 0) or "
2098 "((is equal to 1) or "
2099 "(is equal to 2))",
2100 DescribeNegation(m));
2101
2102
2103 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002104 EXPECT_EQ("((isn't > 0) or "
2105 "(is equal to 1)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002106 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002107 "(is equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002108 DescribeNegation(m));
2109
2110
2111 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002112 EXPECT_EQ("((isn't >= 0) or "
2113 "(isn't < 10)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002114 "((is equal to 3) or "
2115 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002116 "(is equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002117 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00002118}
2119
zhanyong.wan18490652009-05-11 18:54:08 +00002120// Tests that monomorphic matchers are safely cast by the AllOf matcher.
2121TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2122 // greater_than_5 and less_than_10 are monomorphic matchers.
2123 Matcher<int> greater_than_5 = Gt(5);
2124 Matcher<int> less_than_10 = Lt(10);
2125
2126 Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2127 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2128 Matcher<int&> m3 = AllOf(greater_than_5, m2);
2129
2130 // Tests that BothOf works when composing itself.
2131 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2132 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2133}
2134
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002135TEST(AllOfTest, ExplainsResult) {
2136 Matcher<int> m;
2137
2138 // Successful match. Both matchers need to explain. The second
2139 // matcher doesn't give an explanation, so only the first matcher's
2140 // explanation is printed.
2141 m = AllOf(GreaterThan(10), Lt(30));
2142 EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2143
2144 // Successful match. Both matchers need to explain.
2145 m = AllOf(GreaterThan(10), GreaterThan(20));
2146 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2147 Explain(m, 30));
2148
2149 // Successful match. All matchers need to explain. The second
2150 // matcher doesn't given an explanation.
2151 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2152 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2153 Explain(m, 25));
2154
2155 // Successful match. All matchers need to explain.
2156 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2157 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2158 "and which is 10 more than 30",
2159 Explain(m, 40));
2160
2161 // Failed match. The first matcher, which failed, needs to
2162 // explain.
2163 m = AllOf(GreaterThan(10), GreaterThan(20));
2164 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2165
2166 // Failed match. The second matcher, which failed, needs to
2167 // explain. Since it doesn't given an explanation, nothing is
2168 // printed.
2169 m = AllOf(GreaterThan(10), Lt(30));
2170 EXPECT_EQ("", Explain(m, 40));
2171
2172 // Failed match. The second matcher, which failed, needs to
2173 // explain.
2174 m = AllOf(GreaterThan(10), GreaterThan(20));
2175 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2176}
2177
zhanyong.wan02c15052010-06-09 19:21:30 +00002178// Helper to allow easy testing of AnyOf matchers with num parameters.
2179void AnyOfMatches(int num, const Matcher<int>& m) {
2180 SCOPED_TRACE(Describe(m));
2181 EXPECT_FALSE(m.Matches(0));
2182 for (int i = 1; i <= num; ++i) {
2183 EXPECT_TRUE(m.Matches(i));
2184 }
2185 EXPECT_FALSE(m.Matches(num + 1));
2186}
2187
shiqiane35fdd92008-12-10 05:08:54 +00002188// Tests that AnyOf(m1, ..., mn) matches any value that matches at
2189// least one of the given matchers.
2190TEST(AnyOfTest, MatchesWhenAnyMatches) {
2191 Matcher<int> m;
2192 m = AnyOf(Le(1), Ge(3));
2193 EXPECT_TRUE(m.Matches(1));
2194 EXPECT_TRUE(m.Matches(4));
2195 EXPECT_FALSE(m.Matches(2));
2196
2197 m = AnyOf(Lt(0), Eq(1), Eq(2));
2198 EXPECT_TRUE(m.Matches(-1));
2199 EXPECT_TRUE(m.Matches(1));
2200 EXPECT_TRUE(m.Matches(2));
2201 EXPECT_FALSE(m.Matches(0));
2202
2203 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2204 EXPECT_TRUE(m.Matches(-1));
2205 EXPECT_TRUE(m.Matches(1));
2206 EXPECT_TRUE(m.Matches(2));
2207 EXPECT_TRUE(m.Matches(3));
2208 EXPECT_FALSE(m.Matches(0));
2209
2210 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2211 EXPECT_TRUE(m.Matches(0));
2212 EXPECT_TRUE(m.Matches(11));
2213 EXPECT_TRUE(m.Matches(3));
2214 EXPECT_FALSE(m.Matches(2));
zhanyong.wan02c15052010-06-09 19:21:30 +00002215
2216 // The following tests for varying number of sub-matchers. Due to the way
2217 // the sub-matchers are handled it is enough to test every sub-matcher once
2218 // with sub-matchers using the same matcher type. Varying matcher types are
2219 // checked for above.
2220 AnyOfMatches(2, AnyOf(1, 2));
2221 AnyOfMatches(3, AnyOf(1, 2, 3));
2222 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2223 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2224 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2225 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2226 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2227 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2228 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
shiqiane35fdd92008-12-10 05:08:54 +00002229}
2230
zhanyong.wan616180e2013-06-18 18:49:51 +00002231#if GTEST_LANG_CXX11
2232// Tests the variadic version of the AnyOfMatcher.
2233TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2234 // Also make sure AnyOf is defined in the right namespace and does not depend
2235 // on ADL.
2236 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2237
2238 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))"));
2239 AnyOfMatches(11, m);
2240 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2241 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2242 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2243 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2244 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2245}
2246
2247#endif // GTEST_LANG_CXX11
2248
shiqiane35fdd92008-12-10 05:08:54 +00002249// Tests that AnyOf(m1, ..., mn) describes itself properly.
2250TEST(AnyOfTest, CanDescribeSelf) {
2251 Matcher<int> m;
2252 m = AnyOf(Le(1), Ge(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002253 EXPECT_EQ("(is <= 1) or (is >= 3)",
shiqiane35fdd92008-12-10 05:08:54 +00002254 Describe(m));
2255
2256 m = AnyOf(Lt(0), Eq(1), Eq(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002257 EXPECT_EQ("(is < 0) or "
shiqiane35fdd92008-12-10 05:08:54 +00002258 "((is equal to 1) or (is equal to 2))",
2259 Describe(m));
2260
2261 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002262 EXPECT_EQ("((is < 0) or "
2263 "(is equal to 1)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002264 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002265 "(is equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002266 Describe(m));
2267
2268 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002269 EXPECT_EQ("((is <= 0) or "
2270 "(is > 10)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002271 "((is equal to 3) or "
2272 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002273 "(is equal to 7)))",
shiqiane35fdd92008-12-10 05:08:54 +00002274 Describe(m));
2275}
2276
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002277// Tests that AnyOf(m1, ..., mn) describes its negation properly.
2278TEST(AnyOfTest, CanDescribeNegation) {
2279 Matcher<int> m;
2280 m = AnyOf(Le(1), Ge(3));
2281 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2282 DescribeNegation(m));
2283
2284 m = AnyOf(Lt(0), Eq(1), Eq(2));
2285 EXPECT_EQ("(isn't < 0) and "
2286 "((isn't equal to 1) and (isn't equal to 2))",
2287 DescribeNegation(m));
2288
2289 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002290 EXPECT_EQ("((isn't < 0) and "
2291 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002292 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002293 "(isn't equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002294 DescribeNegation(m));
2295
2296 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002297 EXPECT_EQ("((isn't <= 0) and "
2298 "(isn't > 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002299 "((isn't equal to 3) and "
2300 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002301 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002302 DescribeNegation(m));
2303}
2304
zhanyong.wan18490652009-05-11 18:54:08 +00002305// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2306TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2307 // greater_than_5 and less_than_10 are monomorphic matchers.
2308 Matcher<int> greater_than_5 = Gt(5);
2309 Matcher<int> less_than_10 = Lt(10);
2310
2311 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2312 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2313 Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2314
2315 // Tests that EitherOf works when composing itself.
2316 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2317 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2318}
2319
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002320TEST(AnyOfTest, ExplainsResult) {
2321 Matcher<int> m;
2322
2323 // Failed match. Both matchers need to explain. The second
2324 // matcher doesn't give an explanation, so only the first matcher's
2325 // explanation is printed.
2326 m = AnyOf(GreaterThan(10), Lt(0));
2327 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2328
2329 // Failed match. Both matchers need to explain.
2330 m = AnyOf(GreaterThan(10), GreaterThan(20));
2331 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2332 Explain(m, 5));
2333
2334 // Failed match. All matchers need to explain. The second
2335 // matcher doesn't given an explanation.
2336 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2337 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2338 Explain(m, 5));
2339
2340 // Failed match. All matchers need to explain.
2341 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2342 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2343 "and which is 25 less than 30",
2344 Explain(m, 5));
2345
2346 // Successful match. The first matcher, which succeeded, needs to
2347 // explain.
2348 m = AnyOf(GreaterThan(10), GreaterThan(20));
2349 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2350
2351 // Successful match. The second matcher, which succeeded, needs to
2352 // explain. Since it doesn't given an explanation, nothing is
2353 // printed.
2354 m = AnyOf(GreaterThan(10), Lt(30));
2355 EXPECT_EQ("", Explain(m, 0));
2356
2357 // Successful match. The second matcher, which succeeded, needs to
2358 // explain.
2359 m = AnyOf(GreaterThan(30), GreaterThan(20));
2360 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2361}
2362
shiqiane35fdd92008-12-10 05:08:54 +00002363// The following predicate function and predicate functor are for
2364// testing the Truly(predicate) matcher.
2365
2366// Returns non-zero if the input is positive. Note that the return
2367// type of this function is not bool. It's OK as Truly() accepts any
2368// unary function or functor whose return type can be implicitly
2369// converted to bool.
2370int IsPositive(double x) {
2371 return x > 0 ? 1 : 0;
2372}
2373
2374// This functor returns true if the input is greater than the given
2375// number.
2376class IsGreaterThan {
2377 public:
2378 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2379
2380 bool operator()(int n) const { return n > threshold_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002381
shiqiane35fdd92008-12-10 05:08:54 +00002382 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002383 int threshold_;
shiqiane35fdd92008-12-10 05:08:54 +00002384};
2385
2386// For testing Truly().
2387const int foo = 0;
2388
2389// This predicate returns true iff the argument references foo and has
2390// a zero value.
2391bool ReferencesFooAndIsZero(const int& n) {
2392 return (&n == &foo) && (n == 0);
2393}
2394
2395// Tests that Truly(predicate) matches what satisfies the given
2396// predicate.
2397TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2398 Matcher<double> m = Truly(IsPositive);
2399 EXPECT_TRUE(m.Matches(2.0));
2400 EXPECT_FALSE(m.Matches(-1.5));
2401}
2402
2403// Tests that Truly(predicate_functor) works too.
2404TEST(TrulyTest, CanBeUsedWithFunctor) {
2405 Matcher<int> m = Truly(IsGreaterThan(5));
2406 EXPECT_TRUE(m.Matches(6));
2407 EXPECT_FALSE(m.Matches(4));
2408}
2409
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00002410// A class that can be implicitly converted to bool.
2411class ConvertibleToBool {
2412 public:
2413 explicit ConvertibleToBool(int number) : number_(number) {}
2414 operator bool() const { return number_ != 0; }
2415
2416 private:
2417 int number_;
2418};
2419
2420ConvertibleToBool IsNotZero(int number) {
2421 return ConvertibleToBool(number);
2422}
2423
2424// Tests that the predicate used in Truly() may return a class that's
2425// implicitly convertible to bool, even when the class has no
2426// operator!().
2427TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2428 Matcher<int> m = Truly(IsNotZero);
2429 EXPECT_TRUE(m.Matches(1));
2430 EXPECT_FALSE(m.Matches(0));
2431}
2432
shiqiane35fdd92008-12-10 05:08:54 +00002433// Tests that Truly(predicate) can describe itself properly.
2434TEST(TrulyTest, CanDescribeSelf) {
2435 Matcher<double> m = Truly(IsPositive);
2436 EXPECT_EQ("satisfies the given predicate",
2437 Describe(m));
2438}
2439
2440// Tests that Truly(predicate) works when the matcher takes its
2441// argument by reference.
2442TEST(TrulyTest, WorksForByRefArguments) {
2443 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2444 EXPECT_TRUE(m.Matches(foo));
2445 int n = 0;
2446 EXPECT_FALSE(m.Matches(n));
2447}
2448
2449// Tests that Matches(m) is a predicate satisfied by whatever that
2450// matches matcher m.
2451TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2452 EXPECT_TRUE(Matches(Ge(0))(1));
2453 EXPECT_FALSE(Matches(Eq('a'))('b'));
2454}
2455
2456// Tests that Matches(m) works when the matcher takes its argument by
2457// reference.
2458TEST(MatchesTest, WorksOnByRefArguments) {
2459 int m = 0, n = 0;
2460 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2461 EXPECT_FALSE(Matches(Ref(m))(n));
2462}
2463
2464// Tests that a Matcher on non-reference type can be used in
2465// Matches().
2466TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
2467 Matcher<int> eq5 = Eq(5);
2468 EXPECT_TRUE(Matches(eq5)(5));
2469 EXPECT_FALSE(Matches(eq5)(2));
2470}
2471
zhanyong.wanb8243162009-06-04 05:48:20 +00002472// Tests Value(value, matcher). Since Value() is a simple wrapper for
2473// Matches(), which has been tested already, we don't spend a lot of
2474// effort on testing Value().
2475TEST(ValueTest, WorksWithPolymorphicMatcher) {
2476 EXPECT_TRUE(Value("hi", StartsWith("h")));
2477 EXPECT_FALSE(Value(5, Gt(10)));
2478}
2479
2480TEST(ValueTest, WorksWithMonomorphicMatcher) {
2481 const Matcher<int> is_zero = Eq(0);
2482 EXPECT_TRUE(Value(0, is_zero));
2483 EXPECT_FALSE(Value('a', is_zero));
2484
2485 int n = 0;
2486 const Matcher<const int&> ref_n = Ref(n);
2487 EXPECT_TRUE(Value(n, ref_n));
2488 EXPECT_FALSE(Value(1, ref_n));
2489}
2490
zhanyong.wana862f1d2010-03-15 21:23:04 +00002491TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002492 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002493 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002494 EXPECT_EQ("% 2 == 0", listener1.str());
2495
2496 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002497 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002498 EXPECT_EQ("", listener2.str());
2499}
2500
zhanyong.wana862f1d2010-03-15 21:23:04 +00002501TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002502 const Matcher<int> is_even = PolymorphicIsEven();
2503 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002504 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002505 EXPECT_EQ("% 2 == 0", listener1.str());
2506
2507 const Matcher<const double&> is_zero = Eq(0);
2508 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002509 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002510 EXPECT_EQ("", listener2.str());
2511}
2512
zhanyong.wana862f1d2010-03-15 21:23:04 +00002513MATCHER_P(Really, inner_matcher, "") {
2514 return ExplainMatchResult(inner_matcher, arg, result_listener);
2515}
2516
2517TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
2518 EXPECT_THAT(0, Really(Eq(0)));
2519}
2520
zhanyong.wanbf550852009-06-09 06:09:53 +00002521TEST(AllArgsTest, WorksForTuple) {
2522 EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
2523 EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
2524}
2525
2526TEST(AllArgsTest, WorksForNonTuple) {
2527 EXPECT_THAT(42, AllArgs(Gt(0)));
2528 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
2529}
2530
2531class AllArgsHelper {
2532 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002533 AllArgsHelper() {}
2534
zhanyong.wanbf550852009-06-09 06:09:53 +00002535 MOCK_METHOD2(Helper, int(char x, int y));
zhanyong.wan32de5f52009-12-23 00:13:23 +00002536
2537 private:
2538 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
zhanyong.wanbf550852009-06-09 06:09:53 +00002539};
2540
2541TEST(AllArgsTest, WorksInWithClause) {
2542 AllArgsHelper helper;
2543 ON_CALL(helper, Helper(_, _))
2544 .With(AllArgs(Lt()))
2545 .WillByDefault(Return(1));
2546 EXPECT_CALL(helper, Helper(_, _));
2547 EXPECT_CALL(helper, Helper(_, _))
2548 .With(AllArgs(Gt()))
2549 .WillOnce(Return(2));
2550
2551 EXPECT_EQ(1, helper.Helper('\1', 2));
2552 EXPECT_EQ(2, helper.Helper('a', 1));
2553}
2554
shiqiane35fdd92008-12-10 05:08:54 +00002555// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2556// matches the matcher.
2557TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
2558 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
2559 ASSERT_THAT("Foo", EndsWith("oo"));
2560 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
2561 EXPECT_THAT("Hello", StartsWith("Hell"));
2562}
2563
2564// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2565// doesn't match the matcher.
2566TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
2567 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
2568 // which cannot reference auto variables.
zhanyong.wan736baa82010-09-27 17:44:16 +00002569 static unsigned short n; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00002570 n = 5;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002571
2572 // VC++ prior to version 8.0 SP1 has a bug where it will not see any
2573 // functions declared in the namespace scope from within nested classes.
2574 // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
2575 // namespace-level functions invoked inside them need to be explicitly
2576 // resolved.
2577 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
shiqiane35fdd92008-12-10 05:08:54 +00002578 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002579 "Expected: is > 10\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002580 " Actual: 5" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002581 n = 0;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002582 EXPECT_NONFATAL_FAILURE(
2583 EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
2584 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002585 "Expected: (is <= 7) and (is >= 5)\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002586 " Actual: 0" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002587}
2588
2589// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
2590// has a reference type.
2591TEST(MatcherAssertionTest, WorksForByRefArguments) {
2592 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
2593 // reference auto variables.
2594 static int n;
2595 n = 0;
2596 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002597 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
shiqiane35fdd92008-12-10 05:08:54 +00002598 "Value of: n\n"
2599 "Expected: does not reference the variable @");
2600 // Tests the "Actual" part.
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002601 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
zhanyong.wan736baa82010-09-27 17:44:16 +00002602 "Actual: 0" + OfType("int") + ", which is located @");
shiqiane35fdd92008-12-10 05:08:54 +00002603}
2604
zhanyong.wan95b12332009-09-25 18:55:50 +00002605#if !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002606// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
2607// monomorphic.
zhanyong.wan95b12332009-09-25 18:55:50 +00002608
2609// ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
2610// Symbian compiler: it tries to compile
2611// template<T, U> class MatcherCastImpl { ...
zhanyong.wandb22c222010-01-28 21:52:29 +00002612// virtual bool MatchAndExplain(T x, ...) const {
2613// return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
zhanyong.wan95b12332009-09-25 18:55:50 +00002614// with U == string and T == const char*
2615// With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
2616// the compiler silently crashes with no output.
2617// If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
2618// the code compiles but the converted string is bogus.
shiqiane35fdd92008-12-10 05:08:54 +00002619TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
2620 Matcher<const char*> starts_with_he = StartsWith("he");
2621 ASSERT_THAT("hello", starts_with_he);
2622
2623 Matcher<const string&> ends_with_ok = EndsWith("ok");
2624 ASSERT_THAT("book", ends_with_ok);
zhanyong.wan736baa82010-09-27 17:44:16 +00002625 const string bad = "bad";
2626 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
2627 "Value of: bad\n"
2628 "Expected: ends with \"ok\"\n"
2629 " Actual: \"bad\"");
shiqiane35fdd92008-12-10 05:08:54 +00002630 Matcher<int> is_greater_than_5 = Gt(5);
2631 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
2632 "Value of: 5\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002633 "Expected: is > 5\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002634 " Actual: 5" + OfType("int"));
shiqiane35fdd92008-12-10 05:08:54 +00002635}
zhanyong.wan95b12332009-09-25 18:55:50 +00002636#endif // !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002637
2638// Tests floating-point matchers.
2639template <typename RawType>
2640class FloatingPointTest : public testing::Test {
2641 protected:
2642 typedef typename testing::internal::FloatingPoint<RawType> Floating;
2643 typedef typename Floating::Bits Bits;
2644
2645 virtual void SetUp() {
2646 const size_t max_ulps = Floating::kMaxUlps;
2647
2648 // The bits that represent 0.0.
2649 const Bits zero_bits = Floating(0).bits();
2650
2651 // Makes some numbers close to 0.0.
2652 close_to_positive_zero_ = Floating::ReinterpretBits(zero_bits + max_ulps/2);
2653 close_to_negative_zero_ = -Floating::ReinterpretBits(
2654 zero_bits + max_ulps - max_ulps/2);
2655 further_from_negative_zero_ = -Floating::ReinterpretBits(
2656 zero_bits + max_ulps + 1 - max_ulps/2);
2657
2658 // The bits that represent 1.0.
2659 const Bits one_bits = Floating(1).bits();
2660
2661 // Makes some numbers close to 1.0.
2662 close_to_one_ = Floating::ReinterpretBits(one_bits + max_ulps);
2663 further_from_one_ = Floating::ReinterpretBits(one_bits + max_ulps + 1);
2664
2665 // +infinity.
2666 infinity_ = Floating::Infinity();
2667
2668 // The bits that represent +infinity.
2669 const Bits infinity_bits = Floating(infinity_).bits();
2670
2671 // Makes some numbers close to infinity.
2672 close_to_infinity_ = Floating::ReinterpretBits(infinity_bits - max_ulps);
2673 further_from_infinity_ = Floating::ReinterpretBits(
2674 infinity_bits - max_ulps - 1);
2675
2676 // Makes some NAN's.
2677 nan1_ = Floating::ReinterpretBits(Floating::kExponentBitMask | 1);
2678 nan2_ = Floating::ReinterpretBits(Floating::kExponentBitMask | 200);
2679 }
2680
2681 void TestSize() {
2682 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2683 }
2684
2685 // A battery of tests for FloatingEqMatcher::Matches.
2686 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2687 void TestMatches(
2688 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
2689 Matcher<RawType> m1 = matcher_maker(0.0);
2690 EXPECT_TRUE(m1.Matches(-0.0));
2691 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
2692 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
2693 EXPECT_FALSE(m1.Matches(1.0));
2694
2695 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
2696 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
2697
2698 Matcher<RawType> m3 = matcher_maker(1.0);
2699 EXPECT_TRUE(m3.Matches(close_to_one_));
2700 EXPECT_FALSE(m3.Matches(further_from_one_));
2701
2702 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
2703 EXPECT_FALSE(m3.Matches(0.0));
2704
2705 Matcher<RawType> m4 = matcher_maker(-infinity_);
2706 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
2707
2708 Matcher<RawType> m5 = matcher_maker(infinity_);
2709 EXPECT_TRUE(m5.Matches(close_to_infinity_));
2710
2711 // This is interesting as the representations of infinity_ and nan1_
2712 // are only 1 DLP apart.
2713 EXPECT_FALSE(m5.Matches(nan1_));
2714
2715 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2716 // some cases.
2717 Matcher<const RawType&> m6 = matcher_maker(0.0);
2718 EXPECT_TRUE(m6.Matches(-0.0));
2719 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
2720 EXPECT_FALSE(m6.Matches(1.0));
2721
2722 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2723 // cases.
2724 Matcher<RawType&> m7 = matcher_maker(0.0);
2725 RawType x = 0.0;
2726 EXPECT_TRUE(m7.Matches(x));
2727 x = 0.01f;
2728 EXPECT_FALSE(m7.Matches(x));
2729 }
2730
2731 // Pre-calculated numbers to be used by the tests.
2732
2733 static RawType close_to_positive_zero_;
2734 static RawType close_to_negative_zero_;
2735 static RawType further_from_negative_zero_;
2736
2737 static RawType close_to_one_;
2738 static RawType further_from_one_;
2739
2740 static RawType infinity_;
2741 static RawType close_to_infinity_;
2742 static RawType further_from_infinity_;
2743
2744 static RawType nan1_;
2745 static RawType nan2_;
2746};
2747
2748template <typename RawType>
2749RawType FloatingPointTest<RawType>::close_to_positive_zero_;
2750
2751template <typename RawType>
2752RawType FloatingPointTest<RawType>::close_to_negative_zero_;
2753
2754template <typename RawType>
2755RawType FloatingPointTest<RawType>::further_from_negative_zero_;
2756
2757template <typename RawType>
2758RawType FloatingPointTest<RawType>::close_to_one_;
2759
2760template <typename RawType>
2761RawType FloatingPointTest<RawType>::further_from_one_;
2762
2763template <typename RawType>
2764RawType FloatingPointTest<RawType>::infinity_;
2765
2766template <typename RawType>
2767RawType FloatingPointTest<RawType>::close_to_infinity_;
2768
2769template <typename RawType>
2770RawType FloatingPointTest<RawType>::further_from_infinity_;
2771
2772template <typename RawType>
2773RawType FloatingPointTest<RawType>::nan1_;
2774
2775template <typename RawType>
2776RawType FloatingPointTest<RawType>::nan2_;
2777
zhanyong.wan616180e2013-06-18 18:49:51 +00002778// Tests floating-point matchers with fixed epsilons.
2779template <typename RawType>
2780class FloatingPointNearTest : public FloatingPointTest<RawType> {
2781 protected:
2782 typedef FloatingPointTest<RawType> ParentType;
2783
2784 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
2785 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2786 void TestNearMatches(
2787 testing::internal::FloatingEqMatcher<RawType>
2788 (*matcher_maker)(RawType, RawType)) {
2789 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
2790 EXPECT_TRUE(m1.Matches(0.0));
2791 EXPECT_TRUE(m1.Matches(-0.0));
2792 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
2793 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
2794 EXPECT_FALSE(m1.Matches(1.0));
2795
2796 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
2797 EXPECT_TRUE(m2.Matches(0.0));
2798 EXPECT_TRUE(m2.Matches(-0.0));
2799 EXPECT_TRUE(m2.Matches(1.0));
2800 EXPECT_TRUE(m2.Matches(-1.0));
2801 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
2802 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
2803
2804 // Check that inf matches inf, regardless of the of the specified max
2805 // absolute error.
2806 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
2807 EXPECT_TRUE(m3.Matches(ParentType::infinity_));
2808 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
2809 EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
2810
2811 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
2812 EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
2813 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
2814 EXPECT_FALSE(m4.Matches(ParentType::infinity_));
2815
2816 // Test various overflow scenarios.
2817 Matcher<RawType> m5 = matcher_maker(
2818 std::numeric_limits<RawType>::max(),
2819 std::numeric_limits<RawType>::max());
2820 EXPECT_TRUE(m5.Matches(std::numeric_limits<RawType>::max()));
2821 EXPECT_FALSE(m5.Matches(-std::numeric_limits<RawType>::max()));
2822
2823 Matcher<RawType> m6 = matcher_maker(
2824 -std::numeric_limits<RawType>::max(),
2825 std::numeric_limits<RawType>::max());
2826 EXPECT_FALSE(m6.Matches(std::numeric_limits<RawType>::max()));
2827 EXPECT_TRUE(m6.Matches(-std::numeric_limits<RawType>::max()));
2828
2829 Matcher<RawType> m7 = matcher_maker(std::numeric_limits<RawType>::max(), 0);
2830 EXPECT_TRUE(m7.Matches(std::numeric_limits<RawType>::max()));
2831 EXPECT_FALSE(m7.Matches(-std::numeric_limits<RawType>::max()));
2832
2833 Matcher<RawType> m8 = matcher_maker(
2834 -std::numeric_limits<RawType>::max(), 0);
2835 EXPECT_FALSE(m8.Matches(std::numeric_limits<RawType>::max()));
2836 EXPECT_TRUE(m8.Matches(-std::numeric_limits<RawType>::max()));
2837
2838 // The difference between max() and -max() normally overflows to infinity,
2839 // but it should still match if the max_abs_error is also infinity.
2840 Matcher<RawType> m9 = matcher_maker(
2841 std::numeric_limits<RawType>::max(), ParentType::infinity_);
2842 EXPECT_TRUE(m8.Matches(-std::numeric_limits<RawType>::max()));
2843
2844 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2845 // some cases.
2846 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
2847 EXPECT_TRUE(m10.Matches(-0.0));
2848 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
2849 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
2850
2851 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2852 // cases.
2853 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
2854 RawType x = 0.0;
2855 EXPECT_TRUE(m11.Matches(x));
2856 x = 1.0f;
2857 EXPECT_TRUE(m11.Matches(x));
2858 x = -1.0f;
2859 EXPECT_TRUE(m11.Matches(x));
2860 x = 1.1f;
2861 EXPECT_FALSE(m11.Matches(x));
2862 x = -1.1f;
2863 EXPECT_FALSE(m11.Matches(x));
2864 }
2865};
2866
shiqiane35fdd92008-12-10 05:08:54 +00002867// Instantiate FloatingPointTest for testing floats.
2868typedef FloatingPointTest<float> FloatTest;
2869
2870TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
2871 TestMatches(&FloatEq);
2872}
2873
2874TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
2875 TestMatches(&NanSensitiveFloatEq);
2876}
2877
2878TEST_F(FloatTest, FloatEqCannotMatchNaN) {
2879 // FloatEq never matches NaN.
2880 Matcher<float> m = FloatEq(nan1_);
2881 EXPECT_FALSE(m.Matches(nan1_));
2882 EXPECT_FALSE(m.Matches(nan2_));
2883 EXPECT_FALSE(m.Matches(1.0));
2884}
2885
2886TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
2887 // NanSensitiveFloatEq will match NaN.
2888 Matcher<float> m = NanSensitiveFloatEq(nan1_);
2889 EXPECT_TRUE(m.Matches(nan1_));
2890 EXPECT_TRUE(m.Matches(nan2_));
2891 EXPECT_FALSE(m.Matches(1.0));
2892}
2893
2894TEST_F(FloatTest, FloatEqCanDescribeSelf) {
2895 Matcher<float> m1 = FloatEq(2.0f);
2896 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002897 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002898
2899 Matcher<float> m2 = FloatEq(0.5f);
2900 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002901 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002902
2903 Matcher<float> m3 = FloatEq(nan1_);
2904 EXPECT_EQ("never matches", Describe(m3));
2905 EXPECT_EQ("is anything", DescribeNegation(m3));
2906}
2907
2908TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
2909 Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
2910 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002911 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002912
2913 Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
2914 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002915 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002916
2917 Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
2918 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002919 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00002920}
2921
zhanyong.wan616180e2013-06-18 18:49:51 +00002922// Instantiate FloatingPointTest for testing floats with a user-specified
2923// max absolute error.
2924typedef FloatingPointNearTest<float> FloatNearTest;
2925
2926TEST_F(FloatNearTest, FloatNearMatches) {
2927 TestNearMatches(&FloatNear);
2928}
2929
2930TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
2931 TestNearMatches(&NanSensitiveFloatNear);
2932}
2933
2934TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
2935 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
2936 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2937 EXPECT_EQ(
2938 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2939
2940 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
2941 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2942 EXPECT_EQ(
2943 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2944
2945 Matcher<float> m3 = FloatNear(nan1_, 0.0);
2946 EXPECT_EQ("never matches", Describe(m3));
2947 EXPECT_EQ("is anything", DescribeNegation(m3));
2948}
2949
2950TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
2951 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
2952 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2953 EXPECT_EQ(
2954 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2955
2956 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
2957 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2958 EXPECT_EQ(
2959 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2960
2961 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
2962 EXPECT_EQ("is NaN", Describe(m3));
2963 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
2964}
2965
2966TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
2967 // FloatNear never matches NaN.
2968 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
2969 EXPECT_FALSE(m.Matches(nan1_));
2970 EXPECT_FALSE(m.Matches(nan2_));
2971 EXPECT_FALSE(m.Matches(1.0));
2972}
2973
2974TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
2975 // NanSensitiveFloatNear will match NaN.
2976 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
2977 EXPECT_TRUE(m.Matches(nan1_));
2978 EXPECT_TRUE(m.Matches(nan2_));
2979 EXPECT_FALSE(m.Matches(1.0));
2980}
2981
shiqiane35fdd92008-12-10 05:08:54 +00002982// Instantiate FloatingPointTest for testing doubles.
2983typedef FloatingPointTest<double> DoubleTest;
2984
2985TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
2986 TestMatches(&DoubleEq);
2987}
2988
2989TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
2990 TestMatches(&NanSensitiveDoubleEq);
2991}
2992
2993TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
2994 // DoubleEq never matches NaN.
2995 Matcher<double> m = DoubleEq(nan1_);
2996 EXPECT_FALSE(m.Matches(nan1_));
2997 EXPECT_FALSE(m.Matches(nan2_));
2998 EXPECT_FALSE(m.Matches(1.0));
2999}
3000
3001TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3002 // NanSensitiveDoubleEq will match NaN.
3003 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
3004 EXPECT_TRUE(m.Matches(nan1_));
3005 EXPECT_TRUE(m.Matches(nan2_));
3006 EXPECT_FALSE(m.Matches(1.0));
3007}
3008
3009TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3010 Matcher<double> m1 = DoubleEq(2.0);
3011 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003012 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003013
3014 Matcher<double> m2 = DoubleEq(0.5);
3015 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003016 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003017
3018 Matcher<double> m3 = DoubleEq(nan1_);
3019 EXPECT_EQ("never matches", Describe(m3));
3020 EXPECT_EQ("is anything", DescribeNegation(m3));
3021}
3022
3023TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3024 Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3025 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003026 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003027
3028 Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3029 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003030 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003031
3032 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3033 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003034 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00003035}
3036
zhanyong.wan616180e2013-06-18 18:49:51 +00003037// Instantiate FloatingPointTest for testing floats with a user-specified
3038// max absolute error.
3039typedef FloatingPointNearTest<double> DoubleNearTest;
3040
3041TEST_F(DoubleNearTest, DoubleNearMatches) {
3042 TestNearMatches(&DoubleNear);
3043}
3044
3045TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3046 TestNearMatches(&NanSensitiveDoubleNear);
3047}
3048
3049TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3050 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3051 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3052 EXPECT_EQ(
3053 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3054
3055 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3056 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3057 EXPECT_EQ(
3058 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3059
3060 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3061 EXPECT_EQ("never matches", Describe(m3));
3062 EXPECT_EQ("is anything", DescribeNegation(m3));
3063}
3064
3065TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3066 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3067 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3068 EXPECT_EQ(
3069 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3070
3071 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3072 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3073 EXPECT_EQ(
3074 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3075
3076 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3077 EXPECT_EQ("is NaN", Describe(m3));
3078 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3079}
3080
3081TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3082 // DoubleNear never matches NaN.
3083 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3084 EXPECT_FALSE(m.Matches(nan1_));
3085 EXPECT_FALSE(m.Matches(nan2_));
3086 EXPECT_FALSE(m.Matches(1.0));
3087}
3088
3089TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3090 // NanSensitiveDoubleNear will match NaN.
3091 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3092 EXPECT_TRUE(m.Matches(nan1_));
3093 EXPECT_TRUE(m.Matches(nan2_));
3094 EXPECT_FALSE(m.Matches(1.0));
3095}
3096
shiqiane35fdd92008-12-10 05:08:54 +00003097TEST(PointeeTest, RawPointer) {
3098 const Matcher<int*> m = Pointee(Ge(0));
3099
3100 int n = 1;
3101 EXPECT_TRUE(m.Matches(&n));
3102 n = -1;
3103 EXPECT_FALSE(m.Matches(&n));
3104 EXPECT_FALSE(m.Matches(NULL));
3105}
3106
3107TEST(PointeeTest, RawPointerToConst) {
3108 const Matcher<const double*> m = Pointee(Ge(0));
3109
3110 double x = 1;
3111 EXPECT_TRUE(m.Matches(&x));
3112 x = -1;
3113 EXPECT_FALSE(m.Matches(&x));
3114 EXPECT_FALSE(m.Matches(NULL));
3115}
3116
3117TEST(PointeeTest, ReferenceToConstRawPointer) {
3118 const Matcher<int* const &> m = Pointee(Ge(0));
3119
3120 int n = 1;
3121 EXPECT_TRUE(m.Matches(&n));
3122 n = -1;
3123 EXPECT_FALSE(m.Matches(&n));
3124 EXPECT_FALSE(m.Matches(NULL));
3125}
3126
3127TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3128 const Matcher<double* &> m = Pointee(Ge(0));
3129
3130 double x = 1.0;
3131 double* p = &x;
3132 EXPECT_TRUE(m.Matches(p));
3133 x = -1;
3134 EXPECT_FALSE(m.Matches(p));
3135 p = NULL;
3136 EXPECT_FALSE(m.Matches(p));
3137}
3138
vladlosevada23472012-08-14 15:38:49 +00003139// Minimal const-propagating pointer.
3140template <typename T>
3141class ConstPropagatingPtr {
3142 public:
3143 typedef T element_type;
3144
3145 ConstPropagatingPtr() : val_() {}
3146 explicit ConstPropagatingPtr(T* t) : val_(t) {}
3147 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3148
3149 T* get() { return val_; }
3150 T& operator*() { return *val_; }
3151 // Most smart pointers return non-const T* and T& from the next methods.
3152 const T* get() const { return val_; }
3153 const T& operator*() const { return *val_; }
3154
3155 private:
3156 T* val_;
3157};
3158
3159TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3160 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3161 int three = 3;
3162 const ConstPropagatingPtr<int> co(&three);
3163 ConstPropagatingPtr<int> o(&three);
3164 EXPECT_TRUE(m.Matches(o));
3165 EXPECT_TRUE(m.Matches(co));
3166 *o = 6;
3167 EXPECT_FALSE(m.Matches(o));
3168 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3169}
3170
shiqiane35fdd92008-12-10 05:08:54 +00003171TEST(PointeeTest, NeverMatchesNull) {
3172 const Matcher<const char*> m = Pointee(_);
3173 EXPECT_FALSE(m.Matches(NULL));
3174}
3175
3176// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3177TEST(PointeeTest, MatchesAgainstAValue) {
3178 const Matcher<int*> m = Pointee(5);
3179
3180 int n = 5;
3181 EXPECT_TRUE(m.Matches(&n));
3182 n = -1;
3183 EXPECT_FALSE(m.Matches(&n));
3184 EXPECT_FALSE(m.Matches(NULL));
3185}
3186
3187TEST(PointeeTest, CanDescribeSelf) {
3188 const Matcher<int*> m = Pointee(Gt(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003189 EXPECT_EQ("points to a value that is > 3", Describe(m));
3190 EXPECT_EQ("does not point to a value that is > 3",
shiqiane35fdd92008-12-10 05:08:54 +00003191 DescribeNegation(m));
3192}
3193
shiqiane35fdd92008-12-10 05:08:54 +00003194TEST(PointeeTest, CanExplainMatchResult) {
3195 const Matcher<const string*> m = Pointee(StartsWith("Hi"));
3196
3197 EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL)));
3198
zhanyong.wan736baa82010-09-27 17:44:16 +00003199 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
3200 long n = 3; // NOLINT
3201 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003202 Explain(m2, &n));
3203}
3204
3205TEST(PointeeTest, AlwaysExplainsPointee) {
3206 const Matcher<int*> m = Pointee(0);
3207 int n = 42;
zhanyong.wan736baa82010-09-27 17:44:16 +00003208 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
shiqiane35fdd92008-12-10 05:08:54 +00003209}
3210
3211// An uncopyable class.
3212class Uncopyable {
3213 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003214 explicit Uncopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003215
3216 int value() const { return value_; }
3217 private:
3218 const int value_;
3219 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3220};
3221
3222// Returns true iff x.value() is positive.
3223bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3224
3225// A user-defined struct for testing Field().
3226struct AStruct {
3227 AStruct() : x(0), y(1.0), z(5), p(NULL) {}
3228 AStruct(const AStruct& rhs)
3229 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3230
3231 int x; // A non-const field.
3232 const double y; // A const field.
3233 Uncopyable z; // An uncopyable field.
3234 const char* p; // A pointer field.
zhanyong.wan32de5f52009-12-23 00:13:23 +00003235
3236 private:
3237 GTEST_DISALLOW_ASSIGN_(AStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003238};
3239
3240// A derived struct for testing Field().
3241struct DerivedStruct : public AStruct {
3242 char ch;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003243
3244 private:
3245 GTEST_DISALLOW_ASSIGN_(DerivedStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003246};
3247
3248// Tests that Field(&Foo::field, ...) works when field is non-const.
3249TEST(FieldTest, WorksForNonConstField) {
3250 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
3251
3252 AStruct a;
3253 EXPECT_TRUE(m.Matches(a));
3254 a.x = -1;
3255 EXPECT_FALSE(m.Matches(a));
3256}
3257
3258// Tests that Field(&Foo::field, ...) works when field is const.
3259TEST(FieldTest, WorksForConstField) {
3260 AStruct a;
3261
3262 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
3263 EXPECT_TRUE(m.Matches(a));
3264 m = Field(&AStruct::y, Le(0.0));
3265 EXPECT_FALSE(m.Matches(a));
3266}
3267
3268// Tests that Field(&Foo::field, ...) works when field is not copyable.
3269TEST(FieldTest, WorksForUncopyableField) {
3270 AStruct a;
3271
3272 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3273 EXPECT_TRUE(m.Matches(a));
3274 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3275 EXPECT_FALSE(m.Matches(a));
3276}
3277
3278// Tests that Field(&Foo::field, ...) works when field is a pointer.
3279TEST(FieldTest, WorksForPointerField) {
3280 // Matching against NULL.
3281 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
3282 AStruct a;
3283 EXPECT_TRUE(m.Matches(a));
3284 a.p = "hi";
3285 EXPECT_FALSE(m.Matches(a));
3286
3287 // Matching a pointer that is not NULL.
3288 m = Field(&AStruct::p, StartsWith("hi"));
3289 a.p = "hill";
3290 EXPECT_TRUE(m.Matches(a));
3291 a.p = "hole";
3292 EXPECT_FALSE(m.Matches(a));
3293}
3294
3295// Tests that Field() works when the object is passed by reference.
3296TEST(FieldTest, WorksForByRefArgument) {
3297 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3298
3299 AStruct a;
3300 EXPECT_TRUE(m.Matches(a));
3301 a.x = -1;
3302 EXPECT_FALSE(m.Matches(a));
3303}
3304
3305// Tests that Field(&Foo::field, ...) works when the argument's type
3306// is a sub-type of Foo.
3307TEST(FieldTest, WorksForArgumentOfSubType) {
3308 // Note that the matcher expects DerivedStruct but we say AStruct
3309 // inside Field().
3310 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
3311
3312 DerivedStruct d;
3313 EXPECT_TRUE(m.Matches(d));
3314 d.x = -1;
3315 EXPECT_FALSE(m.Matches(d));
3316}
3317
3318// Tests that Field(&Foo::field, m) works when field's type and m's
3319// argument type are compatible but not the same.
3320TEST(FieldTest, WorksForCompatibleMatcherType) {
3321 // The field is an int, but the inner matcher expects a signed char.
3322 Matcher<const AStruct&> m = Field(&AStruct::x,
3323 Matcher<signed char>(Ge(0)));
3324
3325 AStruct a;
3326 EXPECT_TRUE(m.Matches(a));
3327 a.x = -1;
3328 EXPECT_FALSE(m.Matches(a));
3329}
3330
3331// Tests that Field() can describe itself.
3332TEST(FieldTest, CanDescribeSelf) {
3333 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3334
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003335 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3336 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003337}
3338
3339// Tests that Field() can explain the match result.
3340TEST(FieldTest, CanExplainMatchResult) {
3341 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3342
3343 AStruct a;
3344 a.x = 1;
zhanyong.wan736baa82010-09-27 17:44:16 +00003345 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003346
3347 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003348 EXPECT_EQ(
3349 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
3350 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003351}
3352
3353// Tests that Field() works when the argument is a pointer to const.
3354TEST(FieldForPointerTest, WorksForPointerToConst) {
3355 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3356
3357 AStruct a;
3358 EXPECT_TRUE(m.Matches(&a));
3359 a.x = -1;
3360 EXPECT_FALSE(m.Matches(&a));
3361}
3362
3363// Tests that Field() works when the argument is a pointer to non-const.
3364TEST(FieldForPointerTest, WorksForPointerToNonConst) {
3365 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
3366
3367 AStruct a;
3368 EXPECT_TRUE(m.Matches(&a));
3369 a.x = -1;
3370 EXPECT_FALSE(m.Matches(&a));
3371}
3372
zhanyong.wan6953a722010-01-13 05:15:07 +00003373// Tests that Field() works when the argument is a reference to a const pointer.
3374TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
3375 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
3376
3377 AStruct a;
3378 EXPECT_TRUE(m.Matches(&a));
3379 a.x = -1;
3380 EXPECT_FALSE(m.Matches(&a));
3381}
3382
shiqiane35fdd92008-12-10 05:08:54 +00003383// Tests that Field() does not match the NULL pointer.
3384TEST(FieldForPointerTest, DoesNotMatchNull) {
3385 Matcher<const AStruct*> m = Field(&AStruct::x, _);
3386 EXPECT_FALSE(m.Matches(NULL));
3387}
3388
3389// Tests that Field(&Foo::field, ...) works when the argument's type
3390// is a sub-type of const Foo*.
3391TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
3392 // Note that the matcher expects DerivedStruct but we say AStruct
3393 // inside Field().
3394 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
3395
3396 DerivedStruct d;
3397 EXPECT_TRUE(m.Matches(&d));
3398 d.x = -1;
3399 EXPECT_FALSE(m.Matches(&d));
3400}
3401
3402// Tests that Field() can describe itself when used to match a pointer.
3403TEST(FieldForPointerTest, CanDescribeSelf) {
3404 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3405
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003406 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3407 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003408}
3409
3410// Tests that Field() can explain the result of matching a pointer.
3411TEST(FieldForPointerTest, CanExplainMatchResult) {
3412 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3413
3414 AStruct a;
3415 a.x = 1;
3416 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003417 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
3418 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003419
3420 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003421 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
3422 ", which is 1 more than 0", Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003423}
3424
3425// A user-defined class for testing Property().
3426class AClass {
3427 public:
3428 AClass() : n_(0) {}
3429
3430 // A getter that returns a non-reference.
3431 int n() const { return n_; }
3432
3433 void set_n(int new_n) { n_ = new_n; }
3434
3435 // A getter that returns a reference to const.
3436 const string& s() const { return s_; }
3437
3438 void set_s(const string& new_s) { s_ = new_s; }
3439
3440 // A getter that returns a reference to non-const.
3441 double& x() const { return x_; }
3442 private:
3443 int n_;
3444 string s_;
3445
3446 static double x_;
3447};
3448
3449double AClass::x_ = 0.0;
3450
3451// A derived class for testing Property().
3452class DerivedClass : public AClass {
3453 private:
3454 int k_;
3455};
3456
3457// Tests that Property(&Foo::property, ...) works when property()
3458// returns a non-reference.
3459TEST(PropertyTest, WorksForNonReferenceProperty) {
3460 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3461
3462 AClass a;
3463 a.set_n(1);
3464 EXPECT_TRUE(m.Matches(a));
3465
3466 a.set_n(-1);
3467 EXPECT_FALSE(m.Matches(a));
3468}
3469
3470// Tests that Property(&Foo::property, ...) works when property()
3471// returns a reference to const.
3472TEST(PropertyTest, WorksForReferenceToConstProperty) {
3473 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
3474
3475 AClass a;
3476 a.set_s("hill");
3477 EXPECT_TRUE(m.Matches(a));
3478
3479 a.set_s("hole");
3480 EXPECT_FALSE(m.Matches(a));
3481}
3482
3483// Tests that Property(&Foo::property, ...) works when property()
3484// returns a reference to non-const.
3485TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
3486 double x = 0.0;
3487 AClass a;
3488
3489 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
3490 EXPECT_FALSE(m.Matches(a));
3491
3492 m = Property(&AClass::x, Not(Ref(x)));
3493 EXPECT_TRUE(m.Matches(a));
3494}
3495
3496// Tests that Property(&Foo::property, ...) works when the argument is
3497// passed by value.
3498TEST(PropertyTest, WorksForByValueArgument) {
3499 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
3500
3501 AClass a;
3502 a.set_s("hill");
3503 EXPECT_TRUE(m.Matches(a));
3504
3505 a.set_s("hole");
3506 EXPECT_FALSE(m.Matches(a));
3507}
3508
3509// Tests that Property(&Foo::property, ...) works when the argument's
3510// type is a sub-type of Foo.
3511TEST(PropertyTest, WorksForArgumentOfSubType) {
3512 // The matcher expects a DerivedClass, but inside the Property() we
3513 // say AClass.
3514 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
3515
3516 DerivedClass d;
3517 d.set_n(1);
3518 EXPECT_TRUE(m.Matches(d));
3519
3520 d.set_n(-1);
3521 EXPECT_FALSE(m.Matches(d));
3522}
3523
3524// Tests that Property(&Foo::property, m) works when property()'s type
3525// and m's argument type are compatible but different.
3526TEST(PropertyTest, WorksForCompatibleMatcherType) {
3527 // n() returns an int but the inner matcher expects a signed char.
3528 Matcher<const AClass&> m = Property(&AClass::n,
3529 Matcher<signed char>(Ge(0)));
3530
3531 AClass a;
3532 EXPECT_TRUE(m.Matches(a));
3533 a.set_n(-1);
3534 EXPECT_FALSE(m.Matches(a));
3535}
3536
3537// Tests that Property() can describe itself.
3538TEST(PropertyTest, CanDescribeSelf) {
3539 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3540
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003541 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3542 EXPECT_EQ("is an object whose given property isn't >= 0",
3543 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003544}
3545
3546// Tests that Property() can explain the match result.
3547TEST(PropertyTest, CanExplainMatchResult) {
3548 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3549
3550 AClass a;
3551 a.set_n(1);
zhanyong.wan736baa82010-09-27 17:44:16 +00003552 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003553
3554 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003555 EXPECT_EQ(
3556 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
3557 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003558}
3559
3560// Tests that Property() works when the argument is a pointer to const.
3561TEST(PropertyForPointerTest, WorksForPointerToConst) {
3562 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3563
3564 AClass a;
3565 a.set_n(1);
3566 EXPECT_TRUE(m.Matches(&a));
3567
3568 a.set_n(-1);
3569 EXPECT_FALSE(m.Matches(&a));
3570}
3571
3572// Tests that Property() works when the argument is a pointer to non-const.
3573TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
3574 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
3575
3576 AClass a;
3577 a.set_s("hill");
3578 EXPECT_TRUE(m.Matches(&a));
3579
3580 a.set_s("hole");
3581 EXPECT_FALSE(m.Matches(&a));
3582}
3583
zhanyong.wan6953a722010-01-13 05:15:07 +00003584// Tests that Property() works when the argument is a reference to a
3585// const pointer.
3586TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
3587 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
3588
3589 AClass a;
3590 a.set_s("hill");
3591 EXPECT_TRUE(m.Matches(&a));
3592
3593 a.set_s("hole");
3594 EXPECT_FALSE(m.Matches(&a));
3595}
3596
shiqiane35fdd92008-12-10 05:08:54 +00003597// Tests that Property() does not match the NULL pointer.
3598TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
3599 Matcher<const AClass*> m = Property(&AClass::x, _);
3600 EXPECT_FALSE(m.Matches(NULL));
3601}
3602
3603// Tests that Property(&Foo::property, ...) works when the argument's
3604// type is a sub-type of const Foo*.
3605TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
3606 // The matcher expects a DerivedClass, but inside the Property() we
3607 // say AClass.
3608 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
3609
3610 DerivedClass d;
3611 d.set_n(1);
3612 EXPECT_TRUE(m.Matches(&d));
3613
3614 d.set_n(-1);
3615 EXPECT_FALSE(m.Matches(&d));
3616}
3617
3618// Tests that Property() can describe itself when used to match a pointer.
3619TEST(PropertyForPointerTest, CanDescribeSelf) {
3620 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3621
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003622 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3623 EXPECT_EQ("is an object whose given property isn't >= 0",
3624 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003625}
3626
3627// Tests that Property() can explain the result of matching a pointer.
3628TEST(PropertyForPointerTest, CanExplainMatchResult) {
3629 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3630
3631 AClass a;
3632 a.set_n(1);
3633 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003634 EXPECT_EQ(
3635 "which points to an object whose given property is 1" + OfType("int"),
3636 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003637
3638 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003639 EXPECT_EQ("which points to an object whose given property is 1" +
3640 OfType("int") + ", which is 1 more than 0",
3641 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003642}
3643
3644// Tests ResultOf.
3645
3646// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3647// function pointer.
3648string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; }
3649
3650TEST(ResultOfTest, WorksForFunctionPointers) {
3651 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo")));
3652
3653 EXPECT_TRUE(matcher.Matches(1));
3654 EXPECT_FALSE(matcher.Matches(2));
3655}
3656
3657// Tests that ResultOf() can describe itself.
3658TEST(ResultOfTest, CanDescribeItself) {
3659 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
3660
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003661 EXPECT_EQ("is mapped by the given callable to a value that "
3662 "is equal to \"foo\"", Describe(matcher));
3663 EXPECT_EQ("is mapped by the given callable to a value that "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003664 "isn't equal to \"foo\"", DescribeNegation(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00003665}
3666
3667// Tests that ResultOf() can explain the match result.
3668int IntFunction(int input) { return input == 42 ? 80 : 90; }
3669
3670TEST(ResultOfTest, CanExplainMatchResult) {
3671 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003672 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003673 Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003674
3675 matcher = ResultOf(&IntFunction, GreaterThan(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003676 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
3677 ", which is 5 more than 85", Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003678}
3679
3680// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3681// returns a non-reference.
3682TEST(ResultOfTest, WorksForNonReferenceResults) {
3683 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
3684
3685 EXPECT_TRUE(matcher.Matches(42));
3686 EXPECT_FALSE(matcher.Matches(36));
3687}
3688
3689// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3690// returns a reference to non-const.
zhanyong.wan736baa82010-09-27 17:44:16 +00003691double& DoubleFunction(double& input) { return input; } // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003692
zhanyong.wan736baa82010-09-27 17:44:16 +00003693Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003694 return obj;
3695}
3696
3697TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
3698 double x = 3.14;
3699 double x2 = x;
3700 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
3701
3702 EXPECT_TRUE(matcher.Matches(x));
3703 EXPECT_FALSE(matcher.Matches(x2));
3704
3705 // Test that ResultOf works with uncopyable objects
3706 Uncopyable obj(0);
3707 Uncopyable obj2(0);
3708 Matcher<Uncopyable&> matcher2 =
3709 ResultOf(&RefUncopyableFunction, Ref(obj));
3710
3711 EXPECT_TRUE(matcher2.Matches(obj));
3712 EXPECT_FALSE(matcher2.Matches(obj2));
3713}
3714
3715// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3716// returns a reference to const.
3717const string& StringFunction(const string& input) { return input; }
3718
3719TEST(ResultOfTest, WorksForReferenceToConstResults) {
3720 string s = "foo";
3721 string s2 = s;
3722 Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s));
3723
3724 EXPECT_TRUE(matcher.Matches(s));
3725 EXPECT_FALSE(matcher.Matches(s2));
3726}
3727
3728// Tests that ResultOf(f, m) works when f(x) and m's
3729// argument types are compatible but different.
3730TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
3731 // IntFunction() returns int but the inner matcher expects a signed char.
3732 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
3733
3734 EXPECT_TRUE(matcher.Matches(36));
3735 EXPECT_FALSE(matcher.Matches(42));
3736}
3737
shiqiane35fdd92008-12-10 05:08:54 +00003738// Tests that the program aborts when ResultOf is passed
3739// a NULL function pointer.
3740TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
zhanyong.wan04d6ed82009-09-11 07:01:08 +00003741 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan736baa82010-09-27 17:44:16 +00003742 ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))),
shiqiane35fdd92008-12-10 05:08:54 +00003743 "NULL function pointer is passed into ResultOf\\(\\)\\.");
3744}
shiqiane35fdd92008-12-10 05:08:54 +00003745
3746// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3747// function reference.
3748TEST(ResultOfTest, WorksForFunctionReferences) {
3749 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
3750 EXPECT_TRUE(matcher.Matches(1));
3751 EXPECT_FALSE(matcher.Matches(2));
3752}
3753
3754// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3755// function object.
3756struct Functor : public ::std::unary_function<int, string> {
3757 result_type operator()(argument_type input) const {
3758 return IntToStringFunction(input);
3759 }
3760};
3761
3762TEST(ResultOfTest, WorksForFunctors) {
3763 Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo")));
3764
3765 EXPECT_TRUE(matcher.Matches(1));
3766 EXPECT_FALSE(matcher.Matches(2));
3767}
3768
3769// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3770// functor with more then one operator() defined. ResultOf() must work
3771// for each defined operator().
3772struct PolymorphicFunctor {
3773 typedef int result_type;
3774 int operator()(int n) { return n; }
3775 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
3776};
3777
3778TEST(ResultOfTest, WorksForPolymorphicFunctors) {
3779 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
3780
3781 EXPECT_TRUE(matcher_int.Matches(10));
3782 EXPECT_FALSE(matcher_int.Matches(2));
3783
3784 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
3785
3786 EXPECT_TRUE(matcher_string.Matches("long string"));
3787 EXPECT_FALSE(matcher_string.Matches("shrt"));
3788}
3789
3790const int* ReferencingFunction(const int& n) { return &n; }
3791
3792struct ReferencingFunctor {
3793 typedef const int* result_type;
3794 result_type operator()(const int& n) { return &n; }
3795};
3796
3797TEST(ResultOfTest, WorksForReferencingCallables) {
3798 const int n = 1;
3799 const int n2 = 1;
3800 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
3801 EXPECT_TRUE(matcher2.Matches(n));
3802 EXPECT_FALSE(matcher2.Matches(n2));
3803
3804 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
3805 EXPECT_TRUE(matcher3.Matches(n));
3806 EXPECT_FALSE(matcher3.Matches(n2));
3807}
3808
shiqiane35fdd92008-12-10 05:08:54 +00003809class DivisibleByImpl {
3810 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003811 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
shiqiane35fdd92008-12-10 05:08:54 +00003812
zhanyong.wandb22c222010-01-28 21:52:29 +00003813 // For testing using ExplainMatchResultTo() with polymorphic matchers.
shiqiane35fdd92008-12-10 05:08:54 +00003814 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00003815 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003816 *listener << "which is " << (n % divider_) << " modulo "
zhanyong.wandb22c222010-01-28 21:52:29 +00003817 << divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003818 return (n % divider_) == 0;
3819 }
3820
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003821 void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003822 *os << "is divisible by " << divider_;
3823 }
3824
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003825 void DescribeNegationTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003826 *os << "is not divisible by " << divider_;
3827 }
3828
zhanyong.wan32de5f52009-12-23 00:13:23 +00003829 void set_divider(int a_divider) { divider_ = a_divider; }
shiqiane35fdd92008-12-10 05:08:54 +00003830 int divider() const { return divider_; }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003831
shiqiane35fdd92008-12-10 05:08:54 +00003832 private:
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003833 int divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003834};
3835
shiqiane35fdd92008-12-10 05:08:54 +00003836PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
3837 return MakePolymorphicMatcher(DivisibleByImpl(n));
3838}
3839
3840// Tests that when AllOf() fails, only the first failing matcher is
3841// asked to explain why.
3842TEST(ExplainMatchResultTest, AllOf_False_False) {
3843 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003844 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00003845}
3846
3847// Tests that when AllOf() fails, only the first failing matcher is
3848// asked to explain why.
3849TEST(ExplainMatchResultTest, AllOf_False_True) {
3850 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003851 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003852}
3853
3854// Tests that when AllOf() fails, only the first failing matcher is
3855// asked to explain why.
3856TEST(ExplainMatchResultTest, AllOf_True_False) {
3857 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003858 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00003859}
3860
3861// Tests that when AllOf() succeeds, all matchers are asked to explain
3862// why.
3863TEST(ExplainMatchResultTest, AllOf_True_True) {
3864 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003865 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003866}
3867
3868TEST(ExplainMatchResultTest, AllOf_True_True_2) {
3869 const Matcher<int> m = AllOf(Ge(2), Le(3));
3870 EXPECT_EQ("", Explain(m, 2));
3871}
3872
3873TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
3874 const Matcher<int> m = GreaterThan(5);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003875 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003876}
3877
3878// The following two tests verify that values without a public copy
3879// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
3880// with the help of ByRef().
3881
3882class NotCopyable {
3883 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003884 explicit NotCopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003885
3886 int value() const { return value_; }
3887
3888 bool operator==(const NotCopyable& rhs) const {
3889 return value() == rhs.value();
3890 }
3891
3892 bool operator>=(const NotCopyable& rhs) const {
3893 return value() >= rhs.value();
3894 }
3895 private:
3896 int value_;
3897
3898 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
3899};
3900
3901TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
3902 const NotCopyable const_value1(1);
3903 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
3904
3905 const NotCopyable n1(1), n2(2);
3906 EXPECT_TRUE(m.Matches(n1));
3907 EXPECT_FALSE(m.Matches(n2));
3908}
3909
3910TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
3911 NotCopyable value2(2);
3912 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
3913
3914 NotCopyable n1(1), n2(2);
3915 EXPECT_FALSE(m.Matches(n1));
3916 EXPECT_TRUE(m.Matches(n2));
3917}
3918
zhanyong.wan320814a2013-03-01 00:20:30 +00003919TEST(IsEmptyTest, ImplementsIsEmpty) {
3920 vector<int> container;
3921 EXPECT_THAT(container, IsEmpty());
3922 container.push_back(0);
3923 EXPECT_THAT(container, Not(IsEmpty()));
3924 container.push_back(1);
3925 EXPECT_THAT(container, Not(IsEmpty()));
3926}
3927
3928TEST(IsEmptyTest, WorksWithString) {
3929 string text;
3930 EXPECT_THAT(text, IsEmpty());
3931 text = "foo";
3932 EXPECT_THAT(text, Not(IsEmpty()));
3933 text = string("\0", 1);
3934 EXPECT_THAT(text, Not(IsEmpty()));
3935}
3936
3937TEST(IsEmptyTest, CanDescribeSelf) {
3938 Matcher<vector<int> > m = IsEmpty();
3939 EXPECT_EQ("is empty", Describe(m));
3940 EXPECT_EQ("isn't empty", DescribeNegation(m));
3941}
3942
3943TEST(IsEmptyTest, ExplainsResult) {
3944 Matcher<vector<int> > m = IsEmpty();
3945 vector<int> container;
3946 EXPECT_EQ("", Explain(m, container));
3947 container.push_back(0);
3948 EXPECT_EQ("whose size is 1", Explain(m, container));
3949}
3950
zhanyong.wana31d9ce2013-03-01 01:50:17 +00003951TEST(SizeIsTest, ImplementsSizeIs) {
3952 vector<int> container;
3953 EXPECT_THAT(container, SizeIs(0));
3954 EXPECT_THAT(container, Not(SizeIs(1)));
3955 container.push_back(0);
3956 EXPECT_THAT(container, Not(SizeIs(0)));
3957 EXPECT_THAT(container, SizeIs(1));
3958 container.push_back(0);
3959 EXPECT_THAT(container, Not(SizeIs(0)));
3960 EXPECT_THAT(container, SizeIs(2));
3961}
3962
3963TEST(SizeIsTest, WorksWithMap) {
3964 map<string, int> container;
3965 EXPECT_THAT(container, SizeIs(0));
3966 EXPECT_THAT(container, Not(SizeIs(1)));
3967 container.insert(make_pair("foo", 1));
3968 EXPECT_THAT(container, Not(SizeIs(0)));
3969 EXPECT_THAT(container, SizeIs(1));
3970 container.insert(make_pair("bar", 2));
3971 EXPECT_THAT(container, Not(SizeIs(0)));
3972 EXPECT_THAT(container, SizeIs(2));
3973}
3974
3975TEST(SizeIsTest, WorksWithReferences) {
3976 vector<int> container;
3977 Matcher<const vector<int>&> m = SizeIs(1);
3978 EXPECT_THAT(container, Not(m));
3979 container.push_back(0);
3980 EXPECT_THAT(container, m);
3981}
3982
3983TEST(SizeIsTest, CanDescribeSelf) {
3984 Matcher<vector<int> > m = SizeIs(2);
3985 EXPECT_EQ("size is equal to 2", Describe(m));
3986 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
3987}
3988
3989TEST(SizeIsTest, ExplainsResult) {
3990 Matcher<vector<int> > m1 = SizeIs(2);
3991 Matcher<vector<int> > m2 = SizeIs(Lt(2u));
3992 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
3993 Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
3994 vector<int> container;
3995 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
3996 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
3997 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
3998 EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
3999 Explain(m4, container));
4000 container.push_back(0);
4001 container.push_back(0);
4002 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
4003 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
4004 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
4005 EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
4006 Explain(m4, container));
4007}
4008
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004009#if GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004010// Tests ContainerEq with different container types, and
4011// different element types.
4012
4013template <typename T>
zhanyong.wanb8243162009-06-04 05:48:20 +00004014class ContainerEqTest : public testing::Test {};
zhanyong.wan6a896b52009-01-16 01:13:50 +00004015
4016typedef testing::Types<
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004017 set<int>,
4018 vector<size_t>,
4019 multiset<size_t>,
4020 list<int> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004021 ContainerEqTestTypes;
4022
4023TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
4024
4025// Tests that the filled container is equal to itself.
4026TYPED_TEST(ContainerEqTest, EqualsSelf) {
4027 static const int vals[] = {1, 1, 2, 3, 5, 8};
4028 TypeParam my_set(vals, vals + 6);
4029 const Matcher<TypeParam> m = ContainerEq(my_set);
4030 EXPECT_TRUE(m.Matches(my_set));
4031 EXPECT_EQ("", Explain(m, my_set));
4032}
4033
4034// Tests that missing values are reported.
4035TYPED_TEST(ContainerEqTest, ValueMissing) {
4036 static const int vals[] = {1, 1, 2, 3, 5, 8};
4037 static const int test_vals[] = {2, 1, 8, 5};
4038 TypeParam my_set(vals, vals + 6);
4039 TypeParam test_set(test_vals, test_vals + 4);
4040 const Matcher<TypeParam> m = ContainerEq(my_set);
4041 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004042 EXPECT_EQ("which doesn't have these expected elements: 3",
4043 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004044}
4045
4046// Tests that added values are reported.
4047TYPED_TEST(ContainerEqTest, ValueAdded) {
4048 static const int vals[] = {1, 1, 2, 3, 5, 8};
4049 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4050 TypeParam my_set(vals, vals + 6);
4051 TypeParam test_set(test_vals, test_vals + 6);
4052 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4053 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004054 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004055}
4056
4057// Tests that added and missing values are reported together.
4058TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4059 static const int vals[] = {1, 1, 2, 3, 5, 8};
4060 static const int test_vals[] = {1, 2, 3, 8, 46};
4061 TypeParam my_set(vals, vals + 6);
4062 TypeParam test_set(test_vals, test_vals + 5);
4063 const Matcher<TypeParam> m = ContainerEq(my_set);
4064 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004065 EXPECT_EQ("which has these unexpected elements: 46,\n"
4066 "and doesn't have these expected elements: 5",
4067 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004068}
4069
4070// Tests duplicated value -- expect no explanation.
4071TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4072 static const int vals[] = {1, 1, 2, 3, 5, 8};
4073 static const int test_vals[] = {1, 2, 3, 5, 8};
4074 TypeParam my_set(vals, vals + 6);
4075 TypeParam test_set(test_vals, test_vals + 5);
4076 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4077 // Depending on the container, match may be true or false
4078 // But in any case there should be no explanation.
4079 EXPECT_EQ("", Explain(m, test_set));
4080}
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004081#endif // GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004082
4083// Tests that mutliple missing values are reported.
4084// Using just vector here, so order is predicatble.
4085TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4086 static const int vals[] = {1, 1, 2, 3, 5, 8};
4087 static const int test_vals[] = {2, 1, 5};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004088 vector<int> my_set(vals, vals + 6);
4089 vector<int> test_set(test_vals, test_vals + 3);
4090 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004091 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004092 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4093 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004094}
4095
4096// Tests that added values are reported.
4097// Using just vector here, so order is predicatble.
4098TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4099 static const int vals[] = {1, 1, 2, 3, 5, 8};
4100 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004101 list<size_t> my_set(vals, vals + 6);
4102 list<size_t> test_set(test_vals, test_vals + 7);
4103 const Matcher<const list<size_t>&> m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004104 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004105 EXPECT_EQ("which has these unexpected elements: 92, 46",
4106 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004107}
4108
4109// Tests that added and missing values are reported together.
4110TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
4111 static const int vals[] = {1, 1, 2, 3, 5, 8};
4112 static const int test_vals[] = {1, 2, 3, 92, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004113 list<size_t> my_set(vals, vals + 6);
4114 list<size_t> test_set(test_vals, test_vals + 5);
4115 const Matcher<const list<size_t> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004116 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004117 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4118 "and doesn't have these expected elements: 5, 8",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004119 Explain(m, test_set));
4120}
4121
4122// Tests to see that duplicate elements are detected,
4123// but (as above) not reported in the explanation.
4124TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
4125 static const int vals[] = {1, 1, 2, 3, 5, 8};
4126 static const int test_vals[] = {1, 2, 3, 5, 8};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004127 vector<int> my_set(vals, vals + 6);
4128 vector<int> test_set(test_vals, test_vals + 5);
4129 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004130 EXPECT_TRUE(m.Matches(my_set));
4131 EXPECT_FALSE(m.Matches(test_set));
4132 // There is nothing to report when both sets contain all the same values.
4133 EXPECT_EQ("", Explain(m, test_set));
4134}
4135
4136// Tests that ContainerEq works for non-trivial associative containers,
4137// like maps.
4138TEST(ContainerEqExtraTest, WorksForMaps) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004139 map<int, std::string> my_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004140 my_map[0] = "a";
4141 my_map[1] = "b";
4142
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004143 map<int, std::string> test_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004144 test_map[0] = "aa";
4145 test_map[1] = "b";
4146
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004147 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004148 EXPECT_TRUE(m.Matches(my_map));
4149 EXPECT_FALSE(m.Matches(test_map));
4150
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004151 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
4152 "and doesn't have these expected elements: (0, \"a\")",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004153 Explain(m, test_map));
4154}
4155
zhanyong.wanb8243162009-06-04 05:48:20 +00004156TEST(ContainerEqExtraTest, WorksForNativeArray) {
4157 int a1[] = { 1, 2, 3 };
4158 int a2[] = { 1, 2, 3 };
4159 int b[] = { 1, 2, 4 };
4160
4161 EXPECT_THAT(a1, ContainerEq(a2));
4162 EXPECT_THAT(a1, Not(ContainerEq(b)));
4163}
4164
4165TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
4166 const char a1[][3] = { "hi", "lo" };
4167 const char a2[][3] = { "hi", "lo" };
4168 const char b[][3] = { "lo", "hi" };
4169
4170 // Tests using ContainerEq() in the first dimension.
4171 EXPECT_THAT(a1, ContainerEq(a2));
4172 EXPECT_THAT(a1, Not(ContainerEq(b)));
4173
4174 // Tests using ContainerEq() in the second dimension.
4175 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
4176 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
4177}
4178
4179TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
4180 const int a1[] = { 1, 2, 3 };
4181 const int a2[] = { 1, 2, 3 };
4182 const int b[] = { 1, 2, 3, 4 };
4183
zhanyong.wan2661c682009-06-09 05:42:12 +00004184 const int* const p1 = a1;
4185 EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
4186 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004187
4188 const int c[] = { 1, 3, 2 };
zhanyong.wan2661c682009-06-09 05:42:12 +00004189 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004190}
4191
4192TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
4193 std::string a1[][3] = {
4194 { "hi", "hello", "ciao" },
4195 { "bye", "see you", "ciao" }
4196 };
4197
4198 std::string a2[][3] = {
4199 { "hi", "hello", "ciao" },
4200 { "bye", "see you", "ciao" }
4201 };
4202
4203 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
4204 EXPECT_THAT(a1, m);
4205
4206 a2[0][0] = "ha";
4207 EXPECT_THAT(a1, m);
4208}
4209
zhanyong.wan898725c2011-09-16 16:45:39 +00004210TEST(WhenSortedByTest, WorksForEmptyContainer) {
4211 const vector<int> numbers;
4212 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
4213 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
4214}
4215
4216TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
4217 vector<unsigned> numbers;
4218 numbers.push_back(3);
4219 numbers.push_back(1);
4220 numbers.push_back(2);
4221 numbers.push_back(2);
4222 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
4223 ElementsAre(3, 2, 2, 1)));
4224 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
4225 ElementsAre(1, 2, 2, 3))));
4226}
4227
4228TEST(WhenSortedByTest, WorksForNonVectorContainer) {
4229 list<string> words;
4230 words.push_back("say");
4231 words.push_back("hello");
4232 words.push_back("world");
4233 EXPECT_THAT(words, WhenSortedBy(less<string>(),
4234 ElementsAre("hello", "say", "world")));
4235 EXPECT_THAT(words, Not(WhenSortedBy(less<string>(),
4236 ElementsAre("say", "hello", "world"))));
4237}
4238
4239TEST(WhenSortedByTest, WorksForNativeArray) {
4240 const int numbers[] = { 1, 3, 2, 4 };
4241 const int sorted_numbers[] = { 1, 2, 3, 4 };
4242 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
4243 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
4244 ElementsAreArray(sorted_numbers)));
4245 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
4246}
4247
4248TEST(WhenSortedByTest, CanDescribeSelf) {
4249 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
4250 EXPECT_EQ("(when sorted) has 2 elements where\n"
4251 "element #0 is equal to 1,\n"
4252 "element #1 is equal to 2",
4253 Describe(m));
4254 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
4255 "element #0 isn't equal to 1, or\n"
4256 "element #1 isn't equal to 2",
4257 DescribeNegation(m));
4258}
4259
4260TEST(WhenSortedByTest, ExplainsMatchResult) {
4261 const int a[] = { 2, 1 };
4262 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
4263 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
4264 EXPECT_EQ("which is { 1, 2 } when sorted",
4265 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
4266}
4267
4268// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
4269// need to test it as exhaustively as we test the latter.
4270
4271TEST(WhenSortedTest, WorksForEmptyContainer) {
4272 const vector<int> numbers;
4273 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
4274 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
4275}
4276
4277TEST(WhenSortedTest, WorksForNonEmptyContainer) {
4278 list<string> words;
4279 words.push_back("3");
4280 words.push_back("1");
4281 words.push_back("2");
4282 words.push_back("2");
4283 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
4284 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
4285}
4286
zhanyong.wana9a59e02013-03-27 16:14:55 +00004287TEST(WhenSortedTest, WorksForMapTypes) {
4288 map<string, int> word_counts;
4289 word_counts["and"] = 1;
4290 word_counts["the"] = 1;
4291 word_counts["buffalo"] = 2;
4292 EXPECT_THAT(word_counts, WhenSorted(ElementsAre(
4293 Pair("and", 1), Pair("buffalo", 2), Pair("the", 1))));
4294 EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre(
4295 Pair("and", 1), Pair("the", 1), Pair("buffalo", 2)))));
4296}
4297
4298TEST(WhenSortedTest, WorksForMultiMapTypes) {
4299 multimap<int, int> ifib;
4300 ifib.insert(make_pair(8, 6));
4301 ifib.insert(make_pair(2, 3));
4302 ifib.insert(make_pair(1, 1));
4303 ifib.insert(make_pair(3, 4));
4304 ifib.insert(make_pair(1, 2));
4305 ifib.insert(make_pair(5, 5));
4306 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
4307 Pair(1, 2),
4308 Pair(2, 3),
4309 Pair(3, 4),
4310 Pair(5, 5),
4311 Pair(8, 6))));
4312 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
4313 Pair(2, 3),
4314 Pair(1, 1),
4315 Pair(3, 4),
4316 Pair(1, 2),
4317 Pair(5, 5)))));
4318}
4319
4320TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
4321 std::deque<int> d;
4322 d.push_back(2);
4323 d.push_back(1);
4324 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
4325 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
4326}
4327
4328TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
4329 std::deque<int> d;
4330 d.push_back(2);
4331 d.push_back(1);
4332 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
4333 EXPECT_THAT(d, WhenSorted(vector_match));
4334 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
4335 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
4336}
4337
4338// Deliberately bare pseudo-container.
4339// Offers only begin() and end() accessors, yielding InputIterator.
4340template <typename T>
4341class Streamlike {
4342 private:
4343 class ConstIter;
4344 public:
4345 typedef ConstIter const_iterator;
4346 typedef T value_type;
4347
4348 template <typename InIter>
4349 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
4350
4351 const_iterator begin() const {
4352 return const_iterator(this, remainder_.begin());
4353 }
4354 const_iterator end() const {
4355 return const_iterator(this, remainder_.end());
4356 }
4357
4358 private:
4359 class ConstIter : public std::iterator<std::input_iterator_tag,
4360 value_type,
4361 ptrdiff_t,
4362 const value_type&,
4363 const value_type*> {
4364 public:
4365 ConstIter(const Streamlike* s,
4366 typename std::list<value_type>::iterator pos)
4367 : s_(s), pos_(pos) {}
4368
4369 const value_type& operator*() const { return *pos_; }
4370 const value_type* operator->() const { return &*pos_; }
4371 ConstIter& operator++() {
4372 s_->remainder_.erase(pos_++);
4373 return *this;
4374 }
4375
4376 // *iter++ is required to work (see std::istreambuf_iterator).
4377 // (void)iter++ is also required to work.
4378 class PostIncrProxy {
4379 public:
4380 explicit PostIncrProxy(const value_type& value) : value_(value) {}
4381 value_type operator*() const { return value_; }
4382 private:
4383 value_type value_;
4384 };
4385 PostIncrProxy operator++(int) {
4386 PostIncrProxy proxy(**this);
4387 ++(*this);
4388 return proxy;
4389 }
4390
4391 friend bool operator==(const ConstIter& a, const ConstIter& b) {
4392 return a.s_ == b.s_ && a.pos_ == b.pos_;
4393 }
4394 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
4395 return !(a == b);
4396 }
4397
4398 private:
4399 const Streamlike* s_;
4400 typename std::list<value_type>::iterator pos_;
4401 };
4402
4403 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
4404 os << "[";
4405 typedef typename std::list<value_type>::const_iterator Iter;
4406 const char* sep = "";
4407 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
4408 os << sep << *it;
4409 sep = ",";
4410 }
4411 os << "]";
4412 return os;
4413 }
4414
4415 mutable std::list<value_type> remainder_; // modified by iteration
4416};
4417
4418TEST(StreamlikeTest, Iteration) {
4419 const int a[5] = { 2, 1, 4, 5, 3 };
4420 Streamlike<int> s(a, a + 5);
4421 Streamlike<int>::const_iterator it = s.begin();
4422 const int* ip = a;
4423 while (it != s.end()) {
4424 SCOPED_TRACE(ip - a);
4425 EXPECT_EQ(*ip++, *it++);
4426 }
4427}
4428
4429TEST(WhenSortedTest, WorksForStreamlike) {
4430 // Streamlike 'container' provides only minimal iterator support.
4431 // Its iterators are tagged with input_iterator_tag.
4432 const int a[5] = { 2, 1, 4, 5, 3 };
4433 Streamlike<int> s(a, a + 5);
4434 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
4435 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4436}
4437
4438TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00004439 const int a[] = { 2, 1, 4, 5, 3 };
4440 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004441 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
4442 EXPECT_THAT(s, WhenSorted(vector_match));
4443 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4444}
4445
zhanyong.wanfb25d532013-07-28 08:24:00 +00004446// Tests for UnorderedElementsAreArray()
4447
4448TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
4449 const int a[] = { 0, 1, 2, 3, 4 };
4450 std::vector<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4451 do {
4452 StringMatchResultListener listener;
4453 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
4454 s, &listener)) << listener.str();
4455 } while (std::next_permutation(s.begin(), s.end()));
4456}
4457
4458TEST(UnorderedElementsAreArrayTest, VectorBool) {
4459 const bool a[] = { 0, 1, 0, 1, 1 };
4460 const bool b[] = { 1, 0, 1, 1, 0 };
4461 std::vector<bool> expected(a, a + GMOCK_ARRAY_SIZE_(a));
4462 std::vector<bool> actual(b, b + GMOCK_ARRAY_SIZE_(b));
4463 StringMatchResultListener listener;
4464 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
4465 actual, &listener)) << listener.str();
4466}
4467
4468class UnorderedElementsAreTest : public testing::Test {
4469 protected:
4470 typedef std::vector<int> IntVec;
4471};
4472
4473TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
4474 const int a[] = { 1, 2, 3 };
4475 std::vector<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4476 do {
4477 StringMatchResultListener listener;
4478 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4479 s, &listener)) << listener.str();
4480 } while (std::next_permutation(s.begin(), s.end()));
4481}
4482
4483TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
4484 const int a[] = { 1, 2, 3 };
4485 std::vector<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4486 std::vector<Matcher<int> > mv;
4487 mv.push_back(1);
4488 mv.push_back(2);
4489 mv.push_back(2);
4490 // The element with value '3' matches nothing: fail fast.
4491 StringMatchResultListener listener;
4492 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4493 s, &listener)) << listener.str();
4494}
4495
4496// One naive implementation of the matcher runs in O(N!) time, which is too
4497// slow for many real-world inputs. This test shows that our matcher can match
4498// 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
4499// iterations and obviously effectively incomputable.
4500// [ RUN ] UnorderedElementsAreTest.Performance
4501// [ OK ] UnorderedElementsAreTest.Performance (4 ms)
4502TEST_F(UnorderedElementsAreTest, Performance) {
4503 std::vector<int> s;
4504 std::vector<Matcher<int> > mv;
4505 for (int i = 0; i < 100; ++i) {
4506 s.push_back(i);
4507 mv.push_back(_);
4508 }
4509 mv[50] = Eq(0);
4510 StringMatchResultListener listener;
4511 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4512 s, &listener)) << listener.str();
4513}
4514
4515// Another variant of 'Performance' with similar expectations.
4516// [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
4517// [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
4518TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
4519 std::vector<int> s;
4520 std::vector<Matcher<int> > mv;
4521 for (int i = 0; i < 100; ++i) {
4522 s.push_back(i);
4523 if (i & 1) {
4524 mv.push_back(_);
4525 } else {
4526 mv.push_back(i);
4527 }
4528 }
4529 StringMatchResultListener listener;
4530 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4531 s, &listener)) << listener.str();
4532}
4533
4534TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
4535 std::vector<int> v;
4536 v.push_back(4);
4537 StringMatchResultListener listener;
4538 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4539 v, &listener)) << listener.str();
4540 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
4541}
4542
4543TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
4544 std::vector<int> v;
4545 StringMatchResultListener listener;
4546 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4547 v, &listener)) << listener.str();
4548 EXPECT_THAT(listener.str(), Eq(""));
4549}
4550
4551TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
4552 std::vector<int> v;
4553 v.push_back(1);
4554 v.push_back(1);
4555 StringMatchResultListener listener;
4556 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4557 v, &listener)) << listener.str();
4558 EXPECT_THAT(
4559 listener.str(),
4560 Eq("where the following matchers don't match any elements:\n"
4561 "matcher #1: is equal to 2"));
4562}
4563
4564TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
4565 std::vector<int> v;
4566 v.push_back(1);
4567 v.push_back(2);
4568 StringMatchResultListener listener;
4569 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
4570 v, &listener)) << listener.str();
4571 EXPECT_THAT(
4572 listener.str(),
4573 Eq("where the following elements don't match any matchers:\n"
4574 "element #1: 2"));
4575}
4576
4577TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
4578 std::vector<int> v;
4579 v.push_back(2);
4580 v.push_back(3);
4581 StringMatchResultListener listener;
4582 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4583 v, &listener)) << listener.str();
4584 EXPECT_THAT(
4585 listener.str(),
4586 Eq("where"
4587 " the following matchers don't match any elements:\n"
4588 "matcher #0: is equal to 1\n"
4589 "and"
4590 " where"
4591 " the following elements don't match any matchers:\n"
4592 "element #1: 3"));
4593}
4594
4595// Test helper for formatting element, matcher index pairs in expectations.
4596static string EMString(int element, int matcher) {
4597 stringstream ss;
4598 ss << "(element #" << element << ", matcher #" << matcher << ")";
4599 return ss.str();
4600}
4601
4602TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
4603 // A situation where all elements and matchers have a match
4604 // associated with them, but the max matching is not perfect.
4605 std::vector<string> v;
4606 v.push_back("a");
4607 v.push_back("b");
4608 v.push_back("c");
4609 StringMatchResultListener listener;
4610 EXPECT_FALSE(ExplainMatchResult(
4611 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
4612 << listener.str();
4613
4614 string prefix =
4615 "where no permutation of the elements can satisfy all matchers, "
4616 "and the closest match is 2 of 3 matchers with the "
4617 "pairings:\n";
4618
4619 // We have to be a bit loose here, because there are 4 valid max matches.
4620 EXPECT_THAT(
4621 listener.str(),
4622 AnyOf(prefix + "{\n " + EMString(0, 0) +
4623 ",\n " + EMString(1, 2) + "\n}",
4624 prefix + "{\n " + EMString(0, 1) +
4625 ",\n " + EMString(1, 2) + "\n}",
4626 prefix + "{\n " + EMString(0, 0) +
4627 ",\n " + EMString(2, 2) + "\n}",
4628 prefix + "{\n " + EMString(0, 1) +
4629 ",\n " + EMString(2, 2) + "\n}"));
4630}
4631
4632TEST_F(UnorderedElementsAreTest, Describe) {
4633 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
4634 Eq("is empty"));
4635 EXPECT_THAT(
4636 Describe<IntVec>(UnorderedElementsAre(345)),
4637 Eq("has 1 element and that element is equal to 345"));
4638 EXPECT_THAT(
4639 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
4640 Eq("has 3 elements and there exists some permutation "
4641 "of elements such that:\n"
4642 " - element #0 is equal to 111, and\n"
4643 " - element #1 is equal to 222, and\n"
4644 " - element #2 is equal to 333"));
4645}
4646
4647TEST_F(UnorderedElementsAreTest, DescribeNegation) {
4648 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
4649 Eq("isn't empty"));
4650 EXPECT_THAT(
4651 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
4652 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
4653 EXPECT_THAT(
4654 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
4655 Eq("doesn't have 3 elements, or there exists no permutation "
4656 "of elements such that:\n"
4657 " - element #0 is equal to 123, and\n"
4658 " - element #1 is equal to 234, and\n"
4659 " - element #2 is equal to 345"));
4660}
4661
4662namespace {
4663
4664// Used as a check on the more complex max flow method used in the
4665// real testing::internal::FindMaxBipartiteMatching. This method is
4666// compatible but runs in worst-case factorial time, so we only
4667// use it in testing for small problem sizes.
4668template <typename Graph>
4669class BacktrackingMaxBPMState {
4670 public:
4671 // Does not take ownership of 'g'.
4672 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
4673
4674 ElementMatcherPairs Compute() {
4675 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
4676 return best_so_far_;
4677 }
4678 lhs_used_.assign(graph_->LhsSize(), kUnused);
4679 rhs_used_.assign(graph_->RhsSize(), kUnused);
4680 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
4681 matches_.clear();
4682 RecurseInto(irhs);
4683 if (best_so_far_.size() == graph_->RhsSize())
4684 break;
4685 }
4686 return best_so_far_;
4687 }
4688
4689 private:
4690 static const size_t kUnused = static_cast<size_t>(-1);
4691
4692 void PushMatch(size_t lhs, size_t rhs) {
4693 matches_.push_back(ElementMatcherPair(lhs, rhs));
4694 lhs_used_[lhs] = rhs;
4695 rhs_used_[rhs] = lhs;
4696 if (matches_.size() > best_so_far_.size()) {
4697 best_so_far_ = matches_;
4698 }
4699 }
4700
4701 void PopMatch() {
4702 const ElementMatcherPair& back = matches_.back();
4703 lhs_used_[back.first] = kUnused;
4704 rhs_used_[back.second] = kUnused;
4705 matches_.pop_back();
4706 }
4707
4708 bool RecurseInto(size_t irhs) {
4709 if (rhs_used_[irhs] != kUnused) {
4710 return true;
4711 }
4712 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
4713 if (lhs_used_[ilhs] != kUnused) {
4714 continue;
4715 }
4716 if (!graph_->HasEdge(ilhs, irhs)) {
4717 continue;
4718 }
4719 PushMatch(ilhs, irhs);
4720 if (best_so_far_.size() == graph_->RhsSize()) {
4721 return false;
4722 }
4723 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
4724 if (!RecurseInto(mi)) return false;
4725 }
4726 PopMatch();
4727 }
4728 return true;
4729 }
4730
4731 const Graph* graph_; // not owned
4732 std::vector<size_t> lhs_used_;
4733 std::vector<size_t> rhs_used_;
4734 ElementMatcherPairs matches_;
4735 ElementMatcherPairs best_so_far_;
4736};
4737
4738template <typename Graph>
4739const size_t BacktrackingMaxBPMState<Graph>::kUnused;
4740
4741} // namespace
4742
4743// Implement a simple backtracking algorithm to determine if it is possible
4744// to find one element per matcher, without reusing elements.
4745template <typename Graph>
4746ElementMatcherPairs
4747FindBacktrackingMaxBPM(const Graph& g) {
4748 return BacktrackingMaxBPMState<Graph>(&g).Compute();
4749}
4750
4751class BacktrackingBPMTest : public ::testing::Test { };
4752
4753// Tests the MaxBipartiteMatching algorithm with square matrices.
4754// The single int param is the # of nodes on each of the left and right sides.
4755class BipartiteTest : public ::testing::TestWithParam<int> { };
4756
4757// Verify all match graphs up to some moderate number of edges.
4758TEST_P(BipartiteTest, Exhaustive) {
4759 int nodes = GetParam();
4760 MatchMatrix graph(nodes, nodes);
4761 do {
4762 ElementMatcherPairs matches =
4763 internal::FindMaxBipartiteMatching(graph);
4764 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
4765 << "graph: " << graph.DebugString();
4766 // Check that all elements of matches are in the graph.
4767 // Check that elements of first and second are unique.
4768 std::vector<bool> seen_element(graph.LhsSize());
4769 std::vector<bool> seen_matcher(graph.RhsSize());
4770 SCOPED_TRACE(PrintToString(matches));
4771 for (size_t i = 0; i < matches.size(); ++i) {
4772 size_t ilhs = matches[i].first;
4773 size_t irhs = matches[i].second;
4774 EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
4775 EXPECT_FALSE(seen_element[ilhs]);
4776 EXPECT_FALSE(seen_matcher[irhs]);
4777 seen_element[ilhs] = true;
4778 seen_matcher[irhs] = true;
4779 }
4780 } while (graph.NextGraph());
4781}
4782
4783INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest,
4784 ::testing::Range(0, 5));
4785
4786// Parameterized by a pair interpreted as (LhsSize, RhsSize).
4787class BipartiteNonSquareTest
4788 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
4789};
4790
4791TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
4792 // .......
4793 // 0:-----\ :
4794 // 1:---\ | :
4795 // 2:---\ | :
4796 // 3:-\ | | :
4797 // :.......:
4798 // 0 1 2
4799 MatchMatrix g(4, 3);
4800 static const int kEdges[][2] = { {0, 2}, {1, 1}, {2, 1}, {3, 0} };
4801 for (size_t i = 0; i < GMOCK_ARRAY_SIZE_(kEdges); ++i) {
4802 g.SetEdge(kEdges[i][0], kEdges[i][1], true);
4803 }
4804 EXPECT_THAT(FindBacktrackingMaxBPM(g),
4805 ElementsAre(Pair(3, 0),
4806 Pair(AnyOf(1, 2), 1),
4807 Pair(0, 2))) << g.DebugString();
4808}
4809
4810// Verify a few nonsquare matrices.
4811TEST_P(BipartiteNonSquareTest, Exhaustive) {
4812 size_t nlhs = GetParam().first;
4813 size_t nrhs = GetParam().second;
4814 MatchMatrix graph(nlhs, nrhs);
4815 do {
4816 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
4817 internal::FindMaxBipartiteMatching(graph).size())
4818 << "graph: " << graph.DebugString()
4819 << "\nbacktracking: "
4820 << PrintToString(FindBacktrackingMaxBPM(graph))
4821 << "\nmax flow: "
4822 << PrintToString(internal::FindMaxBipartiteMatching(graph));
4823 } while (graph.NextGraph());
4824}
4825
4826INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest,
4827 testing::Values(
4828 std::make_pair(1, 2),
4829 std::make_pair(2, 1),
4830 std::make_pair(3, 2),
4831 std::make_pair(2, 3),
4832 std::make_pair(4, 1),
4833 std::make_pair(1, 4),
4834 std::make_pair(4, 3),
4835 std::make_pair(3, 4)));
4836
4837class BipartiteRandomTest
4838 : public ::testing::TestWithParam<std::pair<int, int> > {
4839};
4840
4841// Verifies a large sample of larger graphs.
4842TEST_P(BipartiteRandomTest, LargerNets) {
4843 int nodes = GetParam().first;
4844 int iters = GetParam().second;
4845 MatchMatrix graph(nodes, nodes);
4846
4847 testing::internal::Int32 seed = GTEST_FLAG(random_seed);
4848 if (seed == 0) {
4849 seed = static_cast<testing::internal::Int32>(time(NULL));
4850 }
4851
4852 for (; iters > 0; --iters, ++seed) {
4853 srand(static_cast<int>(seed));
4854 graph.Randomize();
4855 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
4856 internal::FindMaxBipartiteMatching(graph).size())
4857 << " graph: " << graph.DebugString()
4858 << "\nTo reproduce the failure, rerun the test with the flag"
4859 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
4860 }
4861}
4862
4863// Test argument is a std::pair<int, int> representing (nodes, iters).
4864INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest,
4865 testing::Values(
4866 std::make_pair(5, 10000),
4867 std::make_pair(6, 5000),
4868 std::make_pair(7, 2000),
4869 std::make_pair(8, 500),
4870 std::make_pair(9, 100)));
4871
zhanyong.wan736baa82010-09-27 17:44:16 +00004872// Tests IsReadableTypeName().
4873
4874TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
4875 EXPECT_TRUE(IsReadableTypeName("int"));
4876 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
4877 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
4878 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
4879}
4880
4881TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
4882 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
4883 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
4884 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
4885}
4886
4887TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
4888 EXPECT_FALSE(
4889 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
4890 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
4891}
4892
4893TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
4894 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
4895}
4896
zhanyong.wan4a5330d2009-02-19 00:36:44 +00004897// Tests JoinAsTuple().
4898
4899TEST(JoinAsTupleTest, JoinsEmptyTuple) {
4900 EXPECT_EQ("", JoinAsTuple(Strings()));
4901}
4902
4903TEST(JoinAsTupleTest, JoinsOneTuple) {
4904 const char* fields[] = { "1" };
4905 EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
4906}
4907
4908TEST(JoinAsTupleTest, JoinsTwoTuple) {
4909 const char* fields[] = { "1", "a" };
4910 EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
4911}
4912
4913TEST(JoinAsTupleTest, JoinsTenTuple) {
4914 const char* fields[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
4915 EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
4916 JoinAsTuple(Strings(fields, fields + 10)));
4917}
4918
4919// Tests FormatMatcherDescription().
4920
4921TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
4922 EXPECT_EQ("is even",
zhanyong.wanb4140802010-06-08 22:53:57 +00004923 FormatMatcherDescription(false, "IsEven", Strings()));
4924 EXPECT_EQ("not (is even)",
4925 FormatMatcherDescription(true, "IsEven", Strings()));
zhanyong.wan4a5330d2009-02-19 00:36:44 +00004926
4927 const char* params[] = { "5" };
4928 EXPECT_EQ("equals 5",
zhanyong.wanb4140802010-06-08 22:53:57 +00004929 FormatMatcherDescription(false, "Equals",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00004930 Strings(params, params + 1)));
4931
4932 const char* params2[] = { "5", "8" };
4933 EXPECT_EQ("is in range (5, 8)",
zhanyong.wanb4140802010-06-08 22:53:57 +00004934 FormatMatcherDescription(false, "IsInRange",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00004935 Strings(params2, params2 + 2)));
4936}
4937
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004938// Tests PolymorphicMatcher::mutable_impl().
4939TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
4940 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
4941 DivisibleByImpl& impl = m.mutable_impl();
4942 EXPECT_EQ(42, impl.divider());
4943
4944 impl.set_divider(0);
4945 EXPECT_EQ(0, m.mutable_impl().divider());
4946}
4947
4948// Tests PolymorphicMatcher::impl().
4949TEST(PolymorphicMatcherTest, CanAccessImpl) {
4950 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
4951 const DivisibleByImpl& impl = m.impl();
4952 EXPECT_EQ(42, impl.divider());
4953}
4954
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004955TEST(MatcherTupleTest, ExplainsMatchFailure) {
4956 stringstream ss1;
4957 ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
4958 make_tuple('a', 10), &ss1);
4959 EXPECT_EQ("", ss1.str()); // Successful match.
4960
4961 stringstream ss2;
4962 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
4963 make_tuple(2, 'b'), &ss2);
4964 EXPECT_EQ(" Expected arg #0: is > 5\n"
4965 " Actual: 2, which is 3 less than 5\n"
zhanyong.wand60c5f42010-07-21 22:21:07 +00004966 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
4967 " Actual: 'b' (98, 0x62)\n",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004968 ss2.str()); // Failed match where both arguments need explanation.
4969
4970 stringstream ss3;
4971 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
4972 make_tuple(2, 'a'), &ss3);
4973 EXPECT_EQ(" Expected arg #0: is > 5\n"
4974 " Actual: 2, which is 3 less than 5\n",
4975 ss3.str()); // Failed match where only one argument needs
4976 // explanation.
4977}
4978
zhanyong.wan33605ba2010-04-22 23:37:47 +00004979// Tests Each().
4980
4981TEST(EachTest, ExplainsMatchResultCorrectly) {
4982 set<int> a; // empty
4983
4984 Matcher<set<int> > m = Each(2);
4985 EXPECT_EQ("", Explain(m, a));
4986
zhanyong.wan736baa82010-09-27 17:44:16 +00004987 Matcher<const int(&)[1]> n = Each(1); // NOLINT
zhanyong.wan33605ba2010-04-22 23:37:47 +00004988
4989 const int b[1] = { 1 };
4990 EXPECT_EQ("", Explain(n, b));
4991
4992 n = Each(3);
4993 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
4994
4995 a.insert(1);
4996 a.insert(2);
4997 a.insert(3);
4998 m = Each(GreaterThan(0));
4999 EXPECT_EQ("", Explain(m, a));
5000
5001 m = Each(GreaterThan(10));
5002 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
5003 Explain(m, a));
5004}
5005
5006TEST(EachTest, DescribesItselfCorrectly) {
5007 Matcher<vector<int> > m = Each(1);
5008 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
5009
5010 Matcher<vector<int> > m2 = Not(m);
5011 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
5012}
5013
5014TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
5015 vector<int> some_vector;
5016 EXPECT_THAT(some_vector, Each(1));
5017 some_vector.push_back(3);
5018 EXPECT_THAT(some_vector, Not(Each(1)));
5019 EXPECT_THAT(some_vector, Each(3));
5020 some_vector.push_back(1);
5021 some_vector.push_back(2);
5022 EXPECT_THAT(some_vector, Not(Each(3)));
5023 EXPECT_THAT(some_vector, Each(Lt(3.5)));
5024
5025 vector<string> another_vector;
5026 another_vector.push_back("fee");
5027 EXPECT_THAT(another_vector, Each(string("fee")));
5028 another_vector.push_back("fie");
5029 another_vector.push_back("foe");
5030 another_vector.push_back("fum");
5031 EXPECT_THAT(another_vector, Not(Each(string("fee"))));
5032}
5033
5034TEST(EachTest, MatchesMapWhenAllElementsMatch) {
5035 map<const char*, int> my_map;
5036 const char* bar = "a string";
5037 my_map[bar] = 2;
5038 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
5039
5040 map<string, int> another_map;
5041 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5042 another_map["fee"] = 1;
5043 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5044 another_map["fie"] = 2;
5045 another_map["foe"] = 3;
5046 another_map["fum"] = 4;
5047 EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1))));
5048 EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1))));
5049 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
5050}
5051
5052TEST(EachTest, AcceptsMatcher) {
5053 const int a[] = { 1, 2, 3 };
5054 EXPECT_THAT(a, Each(Gt(0)));
5055 EXPECT_THAT(a, Not(Each(Gt(1))));
5056}
5057
5058TEST(EachTest, WorksForNativeArrayAsTuple) {
5059 const int a[] = { 1, 2 };
5060 const int* const pointer = a;
5061 EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
5062 EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
5063}
5064
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005065// For testing Pointwise().
5066class IsHalfOfMatcher {
5067 public:
5068 template <typename T1, typename T2>
5069 bool MatchAndExplain(const tuple<T1, T2>& a_pair,
5070 MatchResultListener* listener) const {
5071 if (get<0>(a_pair) == get<1>(a_pair)/2) {
5072 *listener << "where the second is " << get<1>(a_pair);
5073 return true;
5074 } else {
5075 *listener << "where the second/2 is " << get<1>(a_pair)/2;
5076 return false;
5077 }
5078 }
5079
5080 void DescribeTo(ostream* os) const {
5081 *os << "are a pair where the first is half of the second";
5082 }
5083
5084 void DescribeNegationTo(ostream* os) const {
5085 *os << "are a pair where the first isn't half of the second";
5086 }
5087};
5088
5089PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
5090 return MakePolymorphicMatcher(IsHalfOfMatcher());
5091}
5092
5093TEST(PointwiseTest, DescribesSelf) {
5094 vector<int> rhs;
5095 rhs.push_back(1);
5096 rhs.push_back(2);
5097 rhs.push_back(3);
5098 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
5099 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
5100 "in { 1, 2, 3 } are a pair where the first is half of the second",
5101 Describe(m));
5102 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
5103 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
5104 "where the first isn't half of the second",
5105 DescribeNegation(m));
5106}
5107
5108TEST(PointwiseTest, MakesCopyOfRhs) {
5109 list<signed char> rhs;
5110 rhs.push_back(2);
5111 rhs.push_back(4);
5112
5113 int lhs[] = { 1, 2 };
5114 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
5115 EXPECT_THAT(lhs, m);
5116
5117 // Changing rhs now shouldn't affect m, which made a copy of rhs.
5118 rhs.push_back(6);
5119 EXPECT_THAT(lhs, m);
5120}
5121
5122TEST(PointwiseTest, WorksForLhsNativeArray) {
5123 const int lhs[] = { 1, 2, 3 };
5124 vector<int> rhs;
5125 rhs.push_back(2);
5126 rhs.push_back(4);
5127 rhs.push_back(6);
5128 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
5129 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5130}
5131
5132TEST(PointwiseTest, WorksForRhsNativeArray) {
5133 const int rhs[] = { 1, 2, 3 };
5134 vector<int> lhs;
5135 lhs.push_back(2);
5136 lhs.push_back(4);
5137 lhs.push_back(6);
5138 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
5139 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
5140}
5141
5142TEST(PointwiseTest, RejectsWrongSize) {
5143 const double lhs[2] = { 1, 2 };
5144 const int rhs[1] = { 0 };
5145 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5146 EXPECT_EQ("which contains 2 values",
5147 Explain(Pointwise(Gt(), rhs), lhs));
5148
5149 const int rhs2[3] = { 0, 1, 2 };
5150 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
5151}
5152
5153TEST(PointwiseTest, RejectsWrongContent) {
5154 const double lhs[3] = { 1, 2, 3 };
5155 const int rhs[3] = { 2, 6, 4 };
5156 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
5157 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
5158 "where the second/2 is 3",
5159 Explain(Pointwise(IsHalfOf(), rhs), lhs));
5160}
5161
5162TEST(PointwiseTest, AcceptsCorrectContent) {
5163 const double lhs[3] = { 1, 2, 3 };
5164 const int rhs[3] = { 2, 4, 6 };
5165 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
5166 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
5167}
5168
5169TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
5170 const double lhs[3] = { 1, 2, 3 };
5171 const int rhs[3] = { 2, 4, 6 };
5172 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5173 EXPECT_THAT(lhs, Pointwise(m1, rhs));
5174 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
5175
5176 // This type works as a tuple<const double&, const int&> can be
5177 // implicitly cast to tuple<double, int>.
5178 const Matcher<tuple<double, int> > m2 = IsHalfOf();
5179 EXPECT_THAT(lhs, Pointwise(m2, rhs));
5180 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
5181}
5182
shiqiane35fdd92008-12-10 05:08:54 +00005183} // namespace gmock_matchers_test
5184} // namespace testing