blob: 5de45c78cfe47bac26a7352b21843bb998ae0ba0 [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;
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000127using testing::StringMatchResultListener;
shiqiane35fdd92008-12-10 05:08:54 +0000128using testing::StrCaseEq;
129using testing::StrCaseNe;
130using testing::StrEq;
131using testing::StrNe;
132using testing::Truly;
133using testing::TypedEq;
zhanyong.wanb8243162009-06-04 05:48:20 +0000134using testing::Value;
zhanyong.wan898725c2011-09-16 16:45:39 +0000135using testing::WhenSorted;
136using testing::WhenSortedBy;
shiqiane35fdd92008-12-10 05:08:54 +0000137using testing::_;
zhanyong.wana862f1d2010-03-15 21:23:04 +0000138using testing::internal::DummyMatchResultListener;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000139using testing::internal::ElementMatcherPair;
140using testing::internal::ElementMatcherPairs;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000141using testing::internal::ExplainMatchFailureTupleTo;
shiqiane35fdd92008-12-10 05:08:54 +0000142using testing::internal::FloatingEqMatcher;
zhanyong.wanb4140802010-06-08 22:53:57 +0000143using testing::internal::FormatMatcherDescription;
zhanyong.wan736baa82010-09-27 17:44:16 +0000144using testing::internal::IsReadableTypeName;
zhanyong.wan4a5330d2009-02-19 00:36:44 +0000145using testing::internal::JoinAsTuple;
zhanyong.wanfb25d532013-07-28 08:24:00 +0000146using testing::internal::MatchMatrix;
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000147using testing::internal::RE;
zhanyong.wana862f1d2010-03-15 21:23:04 +0000148using testing::internal::StreamMatchResultListener;
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
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +0000225 listener.Clear();
226 EXPECT_EQ("", listener.str());
227
228 listener << 42;
229 EXPECT_EQ("42", listener.str());
230
zhanyong.wana862f1d2010-03-15 21:23:04 +0000231 // Streaming shouldn't crash when the underlying ostream is NULL.
232 DummyMatchResultListener dummy;
233 dummy << "hi" << 5;
234}
235
236TEST(MatchResultListenerTest, CanAccessUnderlyingStream) {
237 EXPECT_TRUE(DummyMatchResultListener().stream() == NULL);
238 EXPECT_TRUE(StreamMatchResultListener(NULL).stream() == NULL);
239
240 EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());
241}
242
243TEST(MatchResultListenerTest, IsInterestedWorks) {
244 EXPECT_TRUE(StringMatchResultListener().IsInterested());
245 EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());
246
247 EXPECT_FALSE(DummyMatchResultListener().IsInterested());
248 EXPECT_FALSE(StreamMatchResultListener(NULL).IsInterested());
249}
250
shiqiane35fdd92008-12-10 05:08:54 +0000251// Makes sure that the MatcherInterface<T> interface doesn't
252// change.
253class EvenMatcherImpl : public MatcherInterface<int> {
254 public:
zhanyong.wandb22c222010-01-28 21:52:29 +0000255 virtual bool MatchAndExplain(int x,
256 MatchResultListener* /* listener */) const {
257 return x % 2 == 0;
258 }
shiqiane35fdd92008-12-10 05:08:54 +0000259
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000260 virtual void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +0000261 *os << "is an even number";
262 }
263
264 // We deliberately don't define DescribeNegationTo() and
265 // ExplainMatchResultTo() here, to make sure the definition of these
266 // two methods is optional.
267};
268
zhanyong.wana862f1d2010-03-15 21:23:04 +0000269// Makes sure that the MatcherInterface API doesn't change.
270TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {
shiqiane35fdd92008-12-10 05:08:54 +0000271 EvenMatcherImpl m;
272}
273
zhanyong.wan82113312010-01-08 21:55:40 +0000274// Tests implementing a monomorphic matcher using MatchAndExplain().
275
276class NewEvenMatcherImpl : public MatcherInterface<int> {
277 public:
278 virtual bool MatchAndExplain(int x, MatchResultListener* listener) const {
279 const bool match = x % 2 == 0;
280 // Verifies that we can stream to a listener directly.
281 *listener << "value % " << 2;
282 if (listener->stream() != NULL) {
283 // Verifies that we can stream to a listener's underlying stream
284 // too.
285 *listener->stream() << " == " << (x % 2);
286 }
287 return match;
288 }
289
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000290 virtual void DescribeTo(ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000291 *os << "is an even number";
292 }
293};
294
295TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {
296 Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);
297 EXPECT_TRUE(m.Matches(2));
298 EXPECT_FALSE(m.Matches(3));
299 EXPECT_EQ("value % 2 == 0", Explain(m, 2));
300 EXPECT_EQ("value % 2 == 1", Explain(m, 3));
301}
302
shiqiane35fdd92008-12-10 05:08:54 +0000303// Tests default-constructing a matcher.
304TEST(MatcherTest, CanBeDefaultConstructed) {
305 Matcher<double> m;
306}
307
308// Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.
309TEST(MatcherTest, CanBeConstructedFromMatcherInterface) {
310 const MatcherInterface<int>* impl = new EvenMatcherImpl;
311 Matcher<int> m(impl);
312 EXPECT_TRUE(m.Matches(4));
313 EXPECT_FALSE(m.Matches(5));
314}
315
316// Tests that value can be used in place of Eq(value).
317TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
318 Matcher<int> m1 = 5;
319 EXPECT_TRUE(m1.Matches(5));
320 EXPECT_FALSE(m1.Matches(6));
321}
322
323// Tests that NULL can be used in place of Eq(NULL).
324TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
325 Matcher<int*> m1 = NULL;
326 EXPECT_TRUE(m1.Matches(NULL));
327 int n = 0;
328 EXPECT_FALSE(m1.Matches(&n));
329}
330
331// Tests that matchers are copyable.
332TEST(MatcherTest, IsCopyable) {
333 // Tests the copy constructor.
334 Matcher<bool> m1 = Eq(false);
335 EXPECT_TRUE(m1.Matches(false));
336 EXPECT_FALSE(m1.Matches(true));
337
338 // Tests the assignment operator.
339 m1 = Eq(true);
340 EXPECT_TRUE(m1.Matches(true));
341 EXPECT_FALSE(m1.Matches(false));
342}
343
344// Tests that Matcher<T>::DescribeTo() calls
345// MatcherInterface<T>::DescribeTo().
346TEST(MatcherTest, CanDescribeItself) {
347 EXPECT_EQ("is an even number",
348 Describe(Matcher<int>(new EvenMatcherImpl)));
349}
350
zhanyong.wan82113312010-01-08 21:55:40 +0000351// Tests Matcher<T>::MatchAndExplain().
352TEST(MatcherTest, MatchAndExplain) {
353 Matcher<int> m = GreaterThan(0);
zhanyong.wan34b034c2010-03-05 21:23:23 +0000354 StringMatchResultListener listener1;
zhanyong.wan82113312010-01-08 21:55:40 +0000355 EXPECT_TRUE(m.MatchAndExplain(42, &listener1));
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000356 EXPECT_EQ("which is 42 more than 0", listener1.str());
zhanyong.wan82113312010-01-08 21:55:40 +0000357
zhanyong.wan34b034c2010-03-05 21:23:23 +0000358 StringMatchResultListener listener2;
zhanyong.wan82113312010-01-08 21:55:40 +0000359 EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));
zhanyong.wan676e8cc2010-03-16 20:01:51 +0000360 EXPECT_EQ("which is 9 less than 0", listener2.str());
zhanyong.wan82113312010-01-08 21:55:40 +0000361}
362
shiqiane35fdd92008-12-10 05:08:54 +0000363// Tests that a C-string literal can be implicitly converted to a
364// Matcher<string> or Matcher<const string&>.
365TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
366 Matcher<string> m1 = "hi";
367 EXPECT_TRUE(m1.Matches("hi"));
368 EXPECT_FALSE(m1.Matches("hello"));
369
370 Matcher<const string&> m2 = "hi";
371 EXPECT_TRUE(m2.Matches("hi"));
372 EXPECT_FALSE(m2.Matches("hello"));
373}
374
375// Tests that a string object can be implicitly converted to a
376// Matcher<string> or Matcher<const string&>.
377TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {
378 Matcher<string> m1 = string("hi");
379 EXPECT_TRUE(m1.Matches("hi"));
380 EXPECT_FALSE(m1.Matches("hello"));
381
382 Matcher<const string&> m2 = string("hi");
383 EXPECT_TRUE(m2.Matches("hi"));
384 EXPECT_FALSE(m2.Matches("hello"));
385}
386
zhanyong.wan1f122a02013-03-25 16:27:03 +0000387#if GTEST_HAS_STRING_PIECE_
388// Tests that a C-string literal can be implicitly converted to a
389// Matcher<StringPiece> or Matcher<const StringPiece&>.
390TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {
391 Matcher<StringPiece> m1 = "cats";
392 EXPECT_TRUE(m1.Matches("cats"));
393 EXPECT_FALSE(m1.Matches("dogs"));
394
395 Matcher<const StringPiece&> m2 = "cats";
396 EXPECT_TRUE(m2.Matches("cats"));
397 EXPECT_FALSE(m2.Matches("dogs"));
398}
399
400// Tests that a string object can be implicitly converted to a
401// Matcher<StringPiece> or Matcher<const StringPiece&>.
402TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromString) {
403 Matcher<StringPiece> m1 = string("cats");
404 EXPECT_TRUE(m1.Matches("cats"));
405 EXPECT_FALSE(m1.Matches("dogs"));
406
407 Matcher<const StringPiece&> m2 = string("cats");
408 EXPECT_TRUE(m2.Matches("cats"));
409 EXPECT_FALSE(m2.Matches("dogs"));
410}
411
412// Tests that a StringPiece object can be implicitly converted to a
413// Matcher<StringPiece> or Matcher<const StringPiece&>.
414TEST(StringPieceMatcherTest, CanBeImplicitlyConstructedFromStringPiece) {
415 Matcher<StringPiece> m1 = StringPiece("cats");
416 EXPECT_TRUE(m1.Matches("cats"));
417 EXPECT_FALSE(m1.Matches("dogs"));
418
419 Matcher<const StringPiece&> m2 = StringPiece("cats");
420 EXPECT_TRUE(m2.Matches("cats"));
421 EXPECT_FALSE(m2.Matches("dogs"));
422}
423#endif // GTEST_HAS_STRING_PIECE_
424
shiqiane35fdd92008-12-10 05:08:54 +0000425// Tests that MakeMatcher() constructs a Matcher<T> from a
426// MatcherInterface* without requiring the user to explicitly
427// write the type.
428TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {
429 const MatcherInterface<int>* dummy_impl = NULL;
430 Matcher<int> m = MakeMatcher(dummy_impl);
431}
432
zhanyong.wan82113312010-01-08 21:55:40 +0000433// Tests that MakePolymorphicMatcher() can construct a polymorphic
434// matcher from its implementation using the old API.
zhanyong.wan33605ba2010-04-22 23:37:47 +0000435const int g_bar = 1;
shiqiane35fdd92008-12-10 05:08:54 +0000436class ReferencesBarOrIsZeroImpl {
437 public:
438 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +0000439 bool MatchAndExplain(const T& x,
440 MatchResultListener* /* listener */) const {
shiqiane35fdd92008-12-10 05:08:54 +0000441 const void* p = &x;
zhanyong.wan33605ba2010-04-22 23:37:47 +0000442 return p == &g_bar || x == 0;
shiqiane35fdd92008-12-10 05:08:54 +0000443 }
444
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000445 void DescribeTo(ostream* os) const { *os << "g_bar or zero"; }
shiqiane35fdd92008-12-10 05:08:54 +0000446
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000447 void DescribeNegationTo(ostream* os) const {
zhanyong.wan33605ba2010-04-22 23:37:47 +0000448 *os << "doesn't reference g_bar and is not zero";
shiqiane35fdd92008-12-10 05:08:54 +0000449 }
450};
451
452// This function verifies that MakePolymorphicMatcher() returns a
453// PolymorphicMatcher<T> where T is the argument's type.
454PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {
455 return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());
456}
457
zhanyong.wan82113312010-01-08 21:55:40 +0000458TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {
shiqiane35fdd92008-12-10 05:08:54 +0000459 // Using a polymorphic matcher to match a reference type.
460 Matcher<const int&> m1 = ReferencesBarOrIsZero();
461 EXPECT_TRUE(m1.Matches(0));
462 // Verifies that the identity of a by-reference argument is preserved.
zhanyong.wan33605ba2010-04-22 23:37:47 +0000463 EXPECT_TRUE(m1.Matches(g_bar));
shiqiane35fdd92008-12-10 05:08:54 +0000464 EXPECT_FALSE(m1.Matches(1));
zhanyong.wan33605ba2010-04-22 23:37:47 +0000465 EXPECT_EQ("g_bar or zero", Describe(m1));
shiqiane35fdd92008-12-10 05:08:54 +0000466
467 // Using a polymorphic matcher to match a value type.
468 Matcher<double> m2 = ReferencesBarOrIsZero();
469 EXPECT_TRUE(m2.Matches(0.0));
470 EXPECT_FALSE(m2.Matches(0.1));
zhanyong.wan33605ba2010-04-22 23:37:47 +0000471 EXPECT_EQ("g_bar or zero", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +0000472}
473
zhanyong.wan82113312010-01-08 21:55:40 +0000474// Tests implementing a polymorphic matcher using MatchAndExplain().
475
476class PolymorphicIsEvenImpl {
477 public:
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000478 void DescribeTo(ostream* os) const { *os << "is even"; }
zhanyong.wan82113312010-01-08 21:55:40 +0000479
zhanyong.wanab5b77c2010-05-17 19:32:48 +0000480 void DescribeNegationTo(ostream* os) const {
zhanyong.wan82113312010-01-08 21:55:40 +0000481 *os << "is odd";
482 }
zhanyong.wan82113312010-01-08 21:55:40 +0000483
zhanyong.wandb22c222010-01-28 21:52:29 +0000484 template <typename T>
485 bool MatchAndExplain(const T& x, MatchResultListener* listener) const {
486 // Verifies that we can stream to the listener directly.
487 *listener << "% " << 2;
488 if (listener->stream() != NULL) {
489 // Verifies that we can stream to the listener's underlying stream
490 // too.
491 *listener->stream() << " == " << (x % 2);
492 }
493 return (x % 2) == 0;
zhanyong.wan82113312010-01-08 21:55:40 +0000494 }
zhanyong.wandb22c222010-01-28 21:52:29 +0000495};
zhanyong.wan82113312010-01-08 21:55:40 +0000496
497PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {
498 return MakePolymorphicMatcher(PolymorphicIsEvenImpl());
499}
500
501TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {
502 // Using PolymorphicIsEven() as a Matcher<int>.
503 const Matcher<int> m1 = PolymorphicIsEven();
504 EXPECT_TRUE(m1.Matches(42));
505 EXPECT_FALSE(m1.Matches(43));
506 EXPECT_EQ("is even", Describe(m1));
507
508 const Matcher<int> not_m1 = Not(m1);
509 EXPECT_EQ("is odd", Describe(not_m1));
510
511 EXPECT_EQ("% 2 == 0", Explain(m1, 42));
512
513 // Using PolymorphicIsEven() as a Matcher<char>.
514 const Matcher<char> m2 = PolymorphicIsEven();
515 EXPECT_TRUE(m2.Matches('\x42'));
516 EXPECT_FALSE(m2.Matches('\x43'));
517 EXPECT_EQ("is even", Describe(m2));
518
519 const Matcher<char> not_m2 = Not(m2);
520 EXPECT_EQ("is odd", Describe(not_m2));
521
522 EXPECT_EQ("% 2 == 0", Explain(m2, '\x42'));
523}
524
shiqiane35fdd92008-12-10 05:08:54 +0000525// Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.
526TEST(MatcherCastTest, FromPolymorphicMatcher) {
527 Matcher<int> m = MatcherCast<int>(Eq(5));
528 EXPECT_TRUE(m.Matches(5));
529 EXPECT_FALSE(m.Matches(6));
530}
531
532// For testing casting matchers between compatible types.
533class IntValue {
534 public:
535 // An int can be statically (although not implicitly) cast to a
536 // IntValue.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000537 explicit IntValue(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +0000538
539 int value() const { return value_; }
540 private:
541 int value_;
542};
543
544// For testing casting matchers between compatible types.
545bool IsPositiveIntValue(const IntValue& foo) {
546 return foo.value() > 0;
547}
548
549// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T
550// can be statically converted to U.
551TEST(MatcherCastTest, FromCompatibleType) {
552 Matcher<double> m1 = Eq(2.0);
553 Matcher<int> m2 = MatcherCast<int>(m1);
554 EXPECT_TRUE(m2.Matches(2));
555 EXPECT_FALSE(m2.Matches(3));
556
557 Matcher<IntValue> m3 = Truly(IsPositiveIntValue);
558 Matcher<int> m4 = MatcherCast<int>(m3);
559 // In the following, the arguments 1 and 0 are statically converted
560 // to IntValue objects, and then tested by the IsPositiveIntValue()
561 // predicate.
562 EXPECT_TRUE(m4.Matches(1));
563 EXPECT_FALSE(m4.Matches(0));
564}
565
566// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.
567TEST(MatcherCastTest, FromConstReferenceToNonReference) {
568 Matcher<const int&> m1 = Eq(0);
569 Matcher<int> m2 = MatcherCast<int>(m1);
570 EXPECT_TRUE(m2.Matches(0));
571 EXPECT_FALSE(m2.Matches(1));
572}
573
574// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.
575TEST(MatcherCastTest, FromReferenceToNonReference) {
576 Matcher<int&> m1 = Eq(0);
577 Matcher<int> m2 = MatcherCast<int>(m1);
578 EXPECT_TRUE(m2.Matches(0));
579 EXPECT_FALSE(m2.Matches(1));
580}
581
582// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
583TEST(MatcherCastTest, FromNonReferenceToConstReference) {
584 Matcher<int> m1 = Eq(0);
585 Matcher<const int&> m2 = MatcherCast<const int&>(m1);
586 EXPECT_TRUE(m2.Matches(0));
587 EXPECT_FALSE(m2.Matches(1));
588}
589
590// Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.
591TEST(MatcherCastTest, FromNonReferenceToReference) {
592 Matcher<int> m1 = Eq(0);
593 Matcher<int&> m2 = MatcherCast<int&>(m1);
594 int n = 0;
595 EXPECT_TRUE(m2.Matches(n));
596 n = 1;
597 EXPECT_FALSE(m2.Matches(n));
598}
599
600// Tests that MatcherCast<T>(m) works when m is a Matcher<T>.
601TEST(MatcherCastTest, FromSameType) {
602 Matcher<int> m1 = Eq(0);
603 Matcher<int> m2 = MatcherCast<int>(m1);
604 EXPECT_TRUE(m2.Matches(0));
605 EXPECT_FALSE(m2.Matches(1));
606}
607
jgm79a367e2012-04-10 16:02:11 +0000608// Implicitly convertible form any type.
609struct ConvertibleFromAny {
610 ConvertibleFromAny(int a_value) : value(a_value) {}
611 template <typename T>
612 ConvertibleFromAny(const T& a_value) : value(-1) {
613 ADD_FAILURE() << "Conversion constructor called";
614 }
615 int value;
616};
617
618bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {
619 return a.value == b.value;
620}
621
622ostream& operator<<(ostream& os, const ConvertibleFromAny& a) {
623 return os << a.value;
624}
625
626TEST(MatcherCastTest, ConversionConstructorIsUsed) {
627 Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);
628 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
629 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
630}
631
632TEST(MatcherCastTest, FromConvertibleFromAny) {
633 Matcher<ConvertibleFromAny> m =
634 MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
635 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
636 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
637}
638
kosak5f2a6ca2013-12-03 01:43:07 +0000639struct IntReferenceWrapper {
640 IntReferenceWrapper(const int& a_value) : value(&a_value) {}
641 const int* value;
642};
643
644bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {
645 return a.value == b.value;
646}
647
648TEST(MatcherCastTest, ValueIsNotCopied) {
649 int n = 42;
650 Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);
651 // Verify that the matcher holds a reference to n, not to its temporary copy.
652 EXPECT_TRUE(m.Matches(n));
653}
654
zhanyong.wan18490652009-05-11 18:54:08 +0000655class Base {};
656class Derived : public Base {};
657
658// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
659TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
660 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
661 EXPECT_TRUE(m2.Matches(' '));
662 EXPECT_FALSE(m2.Matches('\n'));
663}
664
zhanyong.wan16cf4732009-05-14 20:55:30 +0000665// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
666// T and U are arithmetic types and T can be losslessly converted to
667// U.
668TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
zhanyong.wan18490652009-05-11 18:54:08 +0000669 Matcher<double> m1 = DoubleEq(1.0);
zhanyong.wan16cf4732009-05-14 20:55:30 +0000670 Matcher<float> m2 = SafeMatcherCast<float>(m1);
671 EXPECT_TRUE(m2.Matches(1.0f));
672 EXPECT_FALSE(m2.Matches(2.0f));
673
674 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
675 EXPECT_TRUE(m3.Matches('a'));
676 EXPECT_FALSE(m3.Matches('b'));
zhanyong.wan18490652009-05-11 18:54:08 +0000677}
678
679// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
680// are pointers or references to a derived and a base class, correspondingly.
681TEST(SafeMatcherCastTest, FromBaseClass) {
682 Derived d, d2;
683 Matcher<Base*> m1 = Eq(&d);
684 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
685 EXPECT_TRUE(m2.Matches(&d));
686 EXPECT_FALSE(m2.Matches(&d2));
687
688 Matcher<Base&> m3 = Ref(d);
689 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
690 EXPECT_TRUE(m4.Matches(d));
691 EXPECT_FALSE(m4.Matches(d2));
692}
693
694// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
695TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
696 int n = 0;
697 Matcher<const int&> m1 = Ref(n);
698 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
699 int n1 = 0;
700 EXPECT_TRUE(m2.Matches(n));
701 EXPECT_FALSE(m2.Matches(n1));
702}
703
704// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
705TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
706 Matcher<int> m1 = Eq(0);
707 Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
708 EXPECT_TRUE(m2.Matches(0));
709 EXPECT_FALSE(m2.Matches(1));
710}
711
712// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
713TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
714 Matcher<int> m1 = Eq(0);
715 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
716 int n = 0;
717 EXPECT_TRUE(m2.Matches(n));
718 n = 1;
719 EXPECT_FALSE(m2.Matches(n));
720}
721
722// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
723TEST(SafeMatcherCastTest, FromSameType) {
724 Matcher<int> m1 = Eq(0);
725 Matcher<int> m2 = SafeMatcherCast<int>(m1);
726 EXPECT_TRUE(m2.Matches(0));
727 EXPECT_FALSE(m2.Matches(1));
728}
729
jgm79a367e2012-04-10 16:02:11 +0000730TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
731 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
732 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
733 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
734}
735
736TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
737 Matcher<ConvertibleFromAny> m =
738 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
739 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
740 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
741}
742
kosak5f2a6ca2013-12-03 01:43:07 +0000743TEST(SafeMatcherCastTest, ValueIsNotCopied) {
744 int n = 42;
745 Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);
746 // Verify that the matcher holds a reference to n, not to its temporary copy.
747 EXPECT_TRUE(m.Matches(n));
748}
749
shiqiane35fdd92008-12-10 05:08:54 +0000750// Tests that A<T>() matches any value of type T.
751TEST(ATest, MatchesAnyValue) {
752 // Tests a matcher for a value type.
753 Matcher<double> m1 = A<double>();
754 EXPECT_TRUE(m1.Matches(91.43));
755 EXPECT_TRUE(m1.Matches(-15.32));
756
757 // Tests a matcher for a reference type.
758 int a = 2;
759 int b = -6;
760 Matcher<int&> m2 = A<int&>();
761 EXPECT_TRUE(m2.Matches(a));
762 EXPECT_TRUE(m2.Matches(b));
763}
764
zhanyong.wanf4274522013-04-24 02:49:43 +0000765TEST(ATest, WorksForDerivedClass) {
766 Base base;
767 Derived derived;
768 EXPECT_THAT(&base, A<Base*>());
769 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
770 EXPECT_THAT(&derived, A<Base*>());
771 EXPECT_THAT(&derived, A<Derived*>());
772}
773
shiqiane35fdd92008-12-10 05:08:54 +0000774// Tests that A<T>() describes itself properly.
775TEST(ATest, CanDescribeSelf) {
776 EXPECT_EQ("is anything", Describe(A<bool>()));
777}
778
779// Tests that An<T>() matches any value of type T.
780TEST(AnTest, MatchesAnyValue) {
781 // Tests a matcher for a value type.
782 Matcher<int> m1 = An<int>();
783 EXPECT_TRUE(m1.Matches(9143));
784 EXPECT_TRUE(m1.Matches(-1532));
785
786 // Tests a matcher for a reference type.
787 int a = 2;
788 int b = -6;
789 Matcher<int&> m2 = An<int&>();
790 EXPECT_TRUE(m2.Matches(a));
791 EXPECT_TRUE(m2.Matches(b));
792}
793
794// Tests that An<T>() describes itself properly.
795TEST(AnTest, CanDescribeSelf) {
796 EXPECT_EQ("is anything", Describe(An<int>()));
797}
798
799// Tests that _ can be used as a matcher for any type and matches any
800// value of that type.
801TEST(UnderscoreTest, MatchesAnyValue) {
802 // Uses _ as a matcher for a value type.
803 Matcher<int> m1 = _;
804 EXPECT_TRUE(m1.Matches(123));
805 EXPECT_TRUE(m1.Matches(-242));
806
807 // Uses _ as a matcher for a reference type.
808 bool a = false;
809 const bool b = true;
810 Matcher<const bool&> m2 = _;
811 EXPECT_TRUE(m2.Matches(a));
812 EXPECT_TRUE(m2.Matches(b));
813}
814
815// Tests that _ describes itself properly.
816TEST(UnderscoreTest, CanDescribeSelf) {
817 Matcher<int> m = _;
818 EXPECT_EQ("is anything", Describe(m));
819}
820
821// Tests that Eq(x) matches any value equal to x.
822TEST(EqTest, MatchesEqualValue) {
823 // 2 C-strings with same content but different addresses.
824 const char a1[] = "hi";
825 const char a2[] = "hi";
826
827 Matcher<const char*> m1 = Eq(a1);
828 EXPECT_TRUE(m1.Matches(a1));
829 EXPECT_FALSE(m1.Matches(a2));
830}
831
832// Tests that Eq(v) describes itself properly.
833
834class Unprintable {
835 public:
836 Unprintable() : c_('a') {}
837
zhanyong.wan32de5f52009-12-23 00:13:23 +0000838 bool operator==(const Unprintable& /* rhs */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000839 private:
840 char c_;
841};
842
843TEST(EqTest, CanDescribeSelf) {
844 Matcher<Unprintable> m = Eq(Unprintable());
845 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
846}
847
848// Tests that Eq(v) can be used to match any type that supports
849// comparing with type T, where T is v's type.
850TEST(EqTest, IsPolymorphic) {
851 Matcher<int> m1 = Eq(1);
852 EXPECT_TRUE(m1.Matches(1));
853 EXPECT_FALSE(m1.Matches(2));
854
855 Matcher<char> m2 = Eq(1);
856 EXPECT_TRUE(m2.Matches('\1'));
857 EXPECT_FALSE(m2.Matches('a'));
858}
859
860// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
861TEST(TypedEqTest, ChecksEqualityForGivenType) {
862 Matcher<char> m1 = TypedEq<char>('a');
863 EXPECT_TRUE(m1.Matches('a'));
864 EXPECT_FALSE(m1.Matches('b'));
865
866 Matcher<int> m2 = TypedEq<int>(6);
867 EXPECT_TRUE(m2.Matches(6));
868 EXPECT_FALSE(m2.Matches(7));
869}
870
871// Tests that TypedEq(v) describes itself properly.
872TEST(TypedEqTest, CanDescribeSelf) {
873 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
874}
875
876// Tests that TypedEq<T>(v) has type Matcher<T>.
877
878// Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
879// is a "bare" type (i.e. not in the form of const U or U&). If v's
880// type is not T, the compiler will generate a message about
881// "undefined referece".
882template <typename T>
883struct Type {
zhanyong.wan32de5f52009-12-23 00:13:23 +0000884 static bool IsTypeOf(const T& /* v */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000885
886 template <typename T2>
887 static void IsTypeOf(T2 v);
888};
889
890TEST(TypedEqTest, HasSpecifiedType) {
891 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
892 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
893 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
894}
895
896// Tests that Ge(v) matches anything >= v.
897TEST(GeTest, ImplementsGreaterThanOrEqual) {
898 Matcher<int> m1 = Ge(0);
899 EXPECT_TRUE(m1.Matches(1));
900 EXPECT_TRUE(m1.Matches(0));
901 EXPECT_FALSE(m1.Matches(-1));
902}
903
904// Tests that Ge(v) describes itself properly.
905TEST(GeTest, CanDescribeSelf) {
906 Matcher<int> m = Ge(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000907 EXPECT_EQ("is >= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000908}
909
910// Tests that Gt(v) matches anything > v.
911TEST(GtTest, ImplementsGreaterThan) {
912 Matcher<double> m1 = Gt(0);
913 EXPECT_TRUE(m1.Matches(1.0));
914 EXPECT_FALSE(m1.Matches(0.0));
915 EXPECT_FALSE(m1.Matches(-1.0));
916}
917
918// Tests that Gt(v) describes itself properly.
919TEST(GtTest, CanDescribeSelf) {
920 Matcher<int> m = Gt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000921 EXPECT_EQ("is > 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000922}
923
924// Tests that Le(v) matches anything <= v.
925TEST(LeTest, ImplementsLessThanOrEqual) {
926 Matcher<char> m1 = Le('b');
927 EXPECT_TRUE(m1.Matches('a'));
928 EXPECT_TRUE(m1.Matches('b'));
929 EXPECT_FALSE(m1.Matches('c'));
930}
931
932// Tests that Le(v) describes itself properly.
933TEST(LeTest, CanDescribeSelf) {
934 Matcher<int> m = Le(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000935 EXPECT_EQ("is <= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000936}
937
938// Tests that Lt(v) matches anything < v.
939TEST(LtTest, ImplementsLessThan) {
940 Matcher<const string&> m1 = Lt("Hello");
941 EXPECT_TRUE(m1.Matches("Abc"));
942 EXPECT_FALSE(m1.Matches("Hello"));
943 EXPECT_FALSE(m1.Matches("Hello, world!"));
944}
945
946// Tests that Lt(v) describes itself properly.
947TEST(LtTest, CanDescribeSelf) {
948 Matcher<int> m = Lt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000949 EXPECT_EQ("is < 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000950}
951
952// Tests that Ne(v) matches anything != v.
953TEST(NeTest, ImplementsNotEqual) {
954 Matcher<int> m1 = Ne(0);
955 EXPECT_TRUE(m1.Matches(1));
956 EXPECT_TRUE(m1.Matches(-1));
957 EXPECT_FALSE(m1.Matches(0));
958}
959
960// Tests that Ne(v) describes itself properly.
961TEST(NeTest, CanDescribeSelf) {
962 Matcher<int> m = Ne(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000963 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000964}
965
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000966// Tests that IsNull() matches any NULL pointer of any type.
967TEST(IsNullTest, MatchesNullPointer) {
968 Matcher<int*> m1 = IsNull();
969 int* p1 = NULL;
970 int n = 0;
971 EXPECT_TRUE(m1.Matches(p1));
972 EXPECT_FALSE(m1.Matches(&n));
973
974 Matcher<const char*> m2 = IsNull();
975 const char* p2 = NULL;
976 EXPECT_TRUE(m2.Matches(p2));
977 EXPECT_FALSE(m2.Matches("hi"));
978
zhanyong.wan95b12332009-09-25 18:55:50 +0000979#if !GTEST_OS_SYMBIAN
980 // Nokia's Symbian compiler generates:
981 // gmock-matchers.h: ambiguous access to overloaded function
982 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
983 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
984 // MatcherInterface<void *> *)'
985 // gmock-matchers.h: (point of instantiation: 'testing::
986 // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
987 // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000988 Matcher<void*> m3 = IsNull();
989 void* p3 = NULL;
990 EXPECT_TRUE(m3.Matches(p3));
991 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
zhanyong.wan95b12332009-09-25 18:55:50 +0000992#endif
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000993}
994
vladlosev79b83502009-11-18 00:43:37 +0000995TEST(IsNullTest, LinkedPtr) {
996 const Matcher<linked_ptr<int> > m = IsNull();
997 const linked_ptr<int> null_p;
998 const linked_ptr<int> non_null_p(new int);
999
1000 EXPECT_TRUE(m.Matches(null_p));
1001 EXPECT_FALSE(m.Matches(non_null_p));
1002}
1003
1004TEST(IsNullTest, ReferenceToConstLinkedPtr) {
1005 const Matcher<const linked_ptr<double>&> m = IsNull();
1006 const linked_ptr<double> null_p;
1007 const linked_ptr<double> non_null_p(new double);
1008
1009 EXPECT_TRUE(m.Matches(null_p));
1010 EXPECT_FALSE(m.Matches(non_null_p));
1011}
1012
vladloseve56daa72009-11-18 01:08:08 +00001013TEST(IsNullTest, ReferenceToConstScopedPtr) {
1014 const Matcher<const scoped_ptr<double>&> m = IsNull();
1015 const scoped_ptr<double> null_p;
1016 const scoped_ptr<double> non_null_p(new double);
1017
1018 EXPECT_TRUE(m.Matches(null_p));
1019 EXPECT_FALSE(m.Matches(non_null_p));
1020}
1021
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001022// Tests that IsNull() describes itself properly.
1023TEST(IsNullTest, CanDescribeSelf) {
1024 Matcher<int*> m = IsNull();
1025 EXPECT_EQ("is NULL", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001026 EXPECT_EQ("isn't NULL", DescribeNegation(m));
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001027}
1028
shiqiane35fdd92008-12-10 05:08:54 +00001029// Tests that NotNull() matches any non-NULL pointer of any type.
1030TEST(NotNullTest, MatchesNonNullPointer) {
1031 Matcher<int*> m1 = NotNull();
1032 int* p1 = NULL;
1033 int n = 0;
1034 EXPECT_FALSE(m1.Matches(p1));
1035 EXPECT_TRUE(m1.Matches(&n));
1036
1037 Matcher<const char*> m2 = NotNull();
1038 const char* p2 = NULL;
1039 EXPECT_FALSE(m2.Matches(p2));
1040 EXPECT_TRUE(m2.Matches("hi"));
1041}
1042
vladlosev79b83502009-11-18 00:43:37 +00001043TEST(NotNullTest, LinkedPtr) {
1044 const Matcher<linked_ptr<int> > m = NotNull();
1045 const linked_ptr<int> null_p;
1046 const linked_ptr<int> non_null_p(new int);
1047
1048 EXPECT_FALSE(m.Matches(null_p));
1049 EXPECT_TRUE(m.Matches(non_null_p));
1050}
1051
1052TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1053 const Matcher<const linked_ptr<double>&> m = NotNull();
1054 const linked_ptr<double> null_p;
1055 const linked_ptr<double> non_null_p(new double);
1056
1057 EXPECT_FALSE(m.Matches(null_p));
1058 EXPECT_TRUE(m.Matches(non_null_p));
1059}
1060
vladloseve56daa72009-11-18 01:08:08 +00001061TEST(NotNullTest, ReferenceToConstScopedPtr) {
1062 const Matcher<const scoped_ptr<double>&> m = NotNull();
1063 const scoped_ptr<double> null_p;
1064 const scoped_ptr<double> non_null_p(new double);
1065
1066 EXPECT_FALSE(m.Matches(null_p));
1067 EXPECT_TRUE(m.Matches(non_null_p));
1068}
1069
shiqiane35fdd92008-12-10 05:08:54 +00001070// Tests that NotNull() describes itself properly.
1071TEST(NotNullTest, CanDescribeSelf) {
1072 Matcher<int*> m = NotNull();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001073 EXPECT_EQ("isn't NULL", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001074}
1075
1076// Tests that Ref(variable) matches an argument that references
1077// 'variable'.
1078TEST(RefTest, MatchesSameVariable) {
1079 int a = 0;
1080 int b = 0;
1081 Matcher<int&> m = Ref(a);
1082 EXPECT_TRUE(m.Matches(a));
1083 EXPECT_FALSE(m.Matches(b));
1084}
1085
1086// Tests that Ref(variable) describes itself properly.
1087TEST(RefTest, CanDescribeSelf) {
1088 int n = 5;
1089 Matcher<int&> m = Ref(n);
1090 stringstream ss;
1091 ss << "references the variable @" << &n << " 5";
1092 EXPECT_EQ(string(ss.str()), Describe(m));
1093}
1094
1095// Test that Ref(non_const_varialbe) can be used as a matcher for a
1096// const reference.
1097TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1098 int a = 0;
1099 int b = 0;
1100 Matcher<const int&> m = Ref(a);
1101 EXPECT_TRUE(m.Matches(a));
1102 EXPECT_FALSE(m.Matches(b));
1103}
1104
1105// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1106// used wherever Ref(base) can be used (Ref(derived) is a sub-type
1107// of Ref(base), but not vice versa.
1108
shiqiane35fdd92008-12-10 05:08:54 +00001109TEST(RefTest, IsCovariant) {
1110 Base base, base2;
1111 Derived derived;
1112 Matcher<const Base&> m1 = Ref(base);
1113 EXPECT_TRUE(m1.Matches(base));
1114 EXPECT_FALSE(m1.Matches(base2));
1115 EXPECT_FALSE(m1.Matches(derived));
1116
1117 m1 = Ref(derived);
1118 EXPECT_TRUE(m1.Matches(derived));
1119 EXPECT_FALSE(m1.Matches(base));
1120 EXPECT_FALSE(m1.Matches(base2));
1121}
1122
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001123TEST(RefTest, ExplainsResult) {
1124 int n = 0;
1125 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1126 StartsWith("which is located @"));
1127
1128 int m = 0;
1129 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1130 StartsWith("which is located @"));
1131}
1132
shiqiane35fdd92008-12-10 05:08:54 +00001133// Tests string comparison matchers.
1134
1135TEST(StrEqTest, MatchesEqualString) {
1136 Matcher<const char*> m = StrEq(string("Hello"));
1137 EXPECT_TRUE(m.Matches("Hello"));
1138 EXPECT_FALSE(m.Matches("hello"));
1139 EXPECT_FALSE(m.Matches(NULL));
1140
1141 Matcher<const string&> m2 = StrEq("Hello");
1142 EXPECT_TRUE(m2.Matches("Hello"));
1143 EXPECT_FALSE(m2.Matches("Hi"));
1144}
1145
1146TEST(StrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001147 Matcher<string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1148 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
shiqiane35fdd92008-12-10 05:08:54 +00001149 Describe(m));
1150
1151 string str("01204500800");
1152 str[3] = '\0';
1153 Matcher<string> m2 = StrEq(str);
1154 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1155 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1156 Matcher<string> m3 = StrEq(str);
1157 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1158}
1159
1160TEST(StrNeTest, MatchesUnequalString) {
1161 Matcher<const char*> m = StrNe("Hello");
1162 EXPECT_TRUE(m.Matches(""));
1163 EXPECT_TRUE(m.Matches(NULL));
1164 EXPECT_FALSE(m.Matches("Hello"));
1165
1166 Matcher<string> m2 = StrNe(string("Hello"));
1167 EXPECT_TRUE(m2.Matches("hello"));
1168 EXPECT_FALSE(m2.Matches("Hello"));
1169}
1170
1171TEST(StrNeTest, CanDescribeSelf) {
1172 Matcher<const char*> m = StrNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001173 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001174}
1175
1176TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1177 Matcher<const char*> m = StrCaseEq(string("Hello"));
1178 EXPECT_TRUE(m.Matches("Hello"));
1179 EXPECT_TRUE(m.Matches("hello"));
1180 EXPECT_FALSE(m.Matches("Hi"));
1181 EXPECT_FALSE(m.Matches(NULL));
1182
1183 Matcher<const string&> m2 = StrCaseEq("Hello");
1184 EXPECT_TRUE(m2.Matches("hello"));
1185 EXPECT_FALSE(m2.Matches("Hi"));
1186}
1187
1188TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1189 string str1("oabocdooeoo");
1190 string str2("OABOCDOOEOO");
1191 Matcher<const string&> m0 = StrCaseEq(str1);
1192 EXPECT_FALSE(m0.Matches(str2 + string(1, '\0')));
1193
1194 str1[3] = str2[3] = '\0';
1195 Matcher<const string&> m1 = StrCaseEq(str1);
1196 EXPECT_TRUE(m1.Matches(str2));
1197
1198 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1199 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1200 Matcher<const string&> m2 = StrCaseEq(str1);
1201 str1[9] = str2[9] = '\0';
1202 EXPECT_FALSE(m2.Matches(str2));
1203
1204 Matcher<const string&> m3 = StrCaseEq(str1);
1205 EXPECT_TRUE(m3.Matches(str2));
1206
1207 EXPECT_FALSE(m3.Matches(str2 + "x"));
1208 str2.append(1, '\0');
1209 EXPECT_FALSE(m3.Matches(str2));
1210 EXPECT_FALSE(m3.Matches(string(str2, 0, 9)));
1211}
1212
1213TEST(StrCaseEqTest, CanDescribeSelf) {
1214 Matcher<string> m = StrCaseEq("Hi");
1215 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1216}
1217
1218TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1219 Matcher<const char*> m = StrCaseNe("Hello");
1220 EXPECT_TRUE(m.Matches("Hi"));
1221 EXPECT_TRUE(m.Matches(NULL));
1222 EXPECT_FALSE(m.Matches("Hello"));
1223 EXPECT_FALSE(m.Matches("hello"));
1224
1225 Matcher<string> m2 = StrCaseNe(string("Hello"));
1226 EXPECT_TRUE(m2.Matches(""));
1227 EXPECT_FALSE(m2.Matches("Hello"));
1228}
1229
1230TEST(StrCaseNeTest, CanDescribeSelf) {
1231 Matcher<const char*> m = StrCaseNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001232 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001233}
1234
1235// Tests that HasSubstr() works for matching string-typed values.
1236TEST(HasSubstrTest, WorksForStringClasses) {
1237 const Matcher<string> m1 = HasSubstr("foo");
1238 EXPECT_TRUE(m1.Matches(string("I love food.")));
1239 EXPECT_FALSE(m1.Matches(string("tofo")));
1240
1241 const Matcher<const std::string&> m2 = HasSubstr("foo");
1242 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1243 EXPECT_FALSE(m2.Matches(std::string("tofo")));
1244}
1245
1246// Tests that HasSubstr() works for matching C-string-typed values.
1247TEST(HasSubstrTest, WorksForCStrings) {
1248 const Matcher<char*> m1 = HasSubstr("foo");
1249 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1250 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1251 EXPECT_FALSE(m1.Matches(NULL));
1252
1253 const Matcher<const char*> m2 = HasSubstr("foo");
1254 EXPECT_TRUE(m2.Matches("I love food."));
1255 EXPECT_FALSE(m2.Matches("tofo"));
1256 EXPECT_FALSE(m2.Matches(NULL));
1257}
1258
1259// Tests that HasSubstr(s) describes itself properly.
1260TEST(HasSubstrTest, CanDescribeSelf) {
1261 Matcher<string> m = HasSubstr("foo\n\"");
1262 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1263}
1264
zhanyong.wanb5937da2009-07-16 20:26:41 +00001265TEST(KeyTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001266 Matcher<const pair<std::string, int>&> m = Key("foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001267 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001268 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1269}
1270
1271TEST(KeyTest, ExplainsResult) {
1272 Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1273 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1274 Explain(m, make_pair(5, true)));
1275 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1276 Explain(m, make_pair(15, true)));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001277}
1278
1279TEST(KeyTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001280 pair<int, std::string> p(25, "foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001281 EXPECT_THAT(p, Key(25));
1282 EXPECT_THAT(p, Not(Key(42)));
1283 EXPECT_THAT(p, Key(Ge(20)));
1284 EXPECT_THAT(p, Not(Key(Lt(25))));
1285}
1286
1287TEST(KeyTest, SafelyCastsInnerMatcher) {
1288 Matcher<int> is_positive = Gt(0);
1289 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001290 pair<char, bool> p('a', true);
zhanyong.wanb5937da2009-07-16 20:26:41 +00001291 EXPECT_THAT(p, Key(is_positive));
1292 EXPECT_THAT(p, Not(Key(is_negative)));
1293}
1294
1295TEST(KeyTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001296 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001297 container.insert(make_pair(1, 'a'));
1298 container.insert(make_pair(2, 'b'));
1299 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001300 EXPECT_THAT(container, Contains(Key(1)));
1301 EXPECT_THAT(container, Not(Contains(Key(3))));
1302}
1303
1304TEST(KeyTest, InsideContainsUsingMultimap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001305 multimap<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001306 container.insert(make_pair(1, 'a'));
1307 container.insert(make_pair(2, 'b'));
1308 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001309
1310 EXPECT_THAT(container, Not(Contains(Key(25))));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001311 container.insert(make_pair(25, 'd'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001312 EXPECT_THAT(container, Contains(Key(25)));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001313 container.insert(make_pair(25, 'e'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001314 EXPECT_THAT(container, Contains(Key(25)));
1315
1316 EXPECT_THAT(container, Contains(Key(1)));
1317 EXPECT_THAT(container, Not(Contains(Key(3))));
1318}
1319
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001320TEST(PairTest, Typing) {
1321 // Test verifies the following type conversions can be compiled.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001322 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1323 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1324 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001325
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001326 Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1327 Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001328}
1329
1330TEST(PairTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001331 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001332 EXPECT_EQ("has a first field that is equal to \"foo\""
1333 ", and has a second field that is equal to 42",
1334 Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001335 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1336 ", or has a second field that isn't equal to 42",
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001337 DescribeNegation(m1));
1338 // Double and triple negation (1 or 2 times not and description of negation).
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001339 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1340 EXPECT_EQ("has a first field that isn't equal to 13"
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001341 ", and has a second field that is equal to 42",
1342 DescribeNegation(m2));
1343}
1344
1345TEST(PairTest, CanExplainMatchResultTo) {
zhanyong.wan82113312010-01-08 21:55:40 +00001346 // If neither field matches, Pair() should explain about the first
1347 // field.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001348 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001349 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001350 Explain(m, make_pair(-1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001351
zhanyong.wan82113312010-01-08 21:55:40 +00001352 // If the first field matches but the second doesn't, Pair() should
1353 // explain about the second field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001354 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001355 Explain(m, make_pair(1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001356
zhanyong.wan82113312010-01-08 21:55:40 +00001357 // If the first field doesn't match but the second does, Pair()
1358 // should explain about the first field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001359 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001360 Explain(m, make_pair(-1, 2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001361
zhanyong.wan82113312010-01-08 21:55:40 +00001362 // If both fields match, Pair() should explain about them both.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001363 EXPECT_EQ("whose both fields match, where the first field is a value "
1364 "which is 1 more than 0, and the second field is a value "
1365 "which is 2 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001366 Explain(m, make_pair(1, 2)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001367
1368 // If only the first match has an explanation, only this explanation should
1369 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001370 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001371 EXPECT_EQ("whose both fields match, where the first field is a value "
1372 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001373 Explain(explain_first, make_pair(1, 0)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001374
1375 // If only the second match has an explanation, only this explanation should
1376 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001377 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001378 EXPECT_EQ("whose both fields match, where the second field is a value "
1379 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001380 Explain(explain_second, make_pair(0, 1)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001381}
1382
1383TEST(PairTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001384 pair<int, std::string> p(25, "foo");
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001385
1386 // Both fields match.
1387 EXPECT_THAT(p, Pair(25, "foo"));
1388 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1389
1390 // 'first' doesnt' match, but 'second' matches.
1391 EXPECT_THAT(p, Not(Pair(42, "foo")));
1392 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1393
1394 // 'first' matches, but 'second' doesn't match.
1395 EXPECT_THAT(p, Not(Pair(25, "bar")));
1396 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1397
1398 // Neither field matches.
1399 EXPECT_THAT(p, Not(Pair(13, "bar")));
1400 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1401}
1402
1403TEST(PairTest, SafelyCastsInnerMatchers) {
1404 Matcher<int> is_positive = Gt(0);
1405 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001406 pair<char, bool> p('a', true);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001407 EXPECT_THAT(p, Pair(is_positive, _));
1408 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1409 EXPECT_THAT(p, Pair(_, is_positive));
1410 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1411}
1412
1413TEST(PairTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001414 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001415 container.insert(make_pair(1, 'a'));
1416 container.insert(make_pair(2, 'b'));
1417 container.insert(make_pair(4, 'c'));
zhanyong.wan95b12332009-09-25 18:55:50 +00001418 EXPECT_THAT(container, Contains(Pair(1, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001419 EXPECT_THAT(container, Contains(Pair(1, _)));
zhanyong.wan95b12332009-09-25 18:55:50 +00001420 EXPECT_THAT(container, Contains(Pair(_, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001421 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1422}
1423
shiqiane35fdd92008-12-10 05:08:54 +00001424// Tests StartsWith(s).
1425
1426TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1427 const Matcher<const char*> m1 = StartsWith(string(""));
1428 EXPECT_TRUE(m1.Matches("Hi"));
1429 EXPECT_TRUE(m1.Matches(""));
1430 EXPECT_FALSE(m1.Matches(NULL));
1431
1432 const Matcher<const string&> m2 = StartsWith("Hi");
1433 EXPECT_TRUE(m2.Matches("Hi"));
1434 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1435 EXPECT_TRUE(m2.Matches("High"));
1436 EXPECT_FALSE(m2.Matches("H"));
1437 EXPECT_FALSE(m2.Matches(" Hi"));
1438}
1439
1440TEST(StartsWithTest, CanDescribeSelf) {
1441 Matcher<const std::string> m = StartsWith("Hi");
1442 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1443}
1444
1445// Tests EndsWith(s).
1446
1447TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1448 const Matcher<const char*> m1 = EndsWith("");
1449 EXPECT_TRUE(m1.Matches("Hi"));
1450 EXPECT_TRUE(m1.Matches(""));
1451 EXPECT_FALSE(m1.Matches(NULL));
1452
1453 const Matcher<const string&> m2 = EndsWith(string("Hi"));
1454 EXPECT_TRUE(m2.Matches("Hi"));
1455 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1456 EXPECT_TRUE(m2.Matches("Super Hi"));
1457 EXPECT_FALSE(m2.Matches("i"));
1458 EXPECT_FALSE(m2.Matches("Hi "));
1459}
1460
1461TEST(EndsWithTest, CanDescribeSelf) {
1462 Matcher<const std::string> m = EndsWith("Hi");
1463 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1464}
1465
shiqiane35fdd92008-12-10 05:08:54 +00001466// Tests MatchesRegex().
1467
1468TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1469 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1470 EXPECT_TRUE(m1.Matches("az"));
1471 EXPECT_TRUE(m1.Matches("abcz"));
1472 EXPECT_FALSE(m1.Matches(NULL));
1473
1474 const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z"));
1475 EXPECT_TRUE(m2.Matches("azbz"));
1476 EXPECT_FALSE(m2.Matches("az1"));
1477 EXPECT_FALSE(m2.Matches("1az"));
1478}
1479
1480TEST(MatchesRegexTest, CanDescribeSelf) {
1481 Matcher<const std::string> m1 = MatchesRegex(string("Hi.*"));
1482 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1483
zhanyong.wand14aaed2010-01-14 05:36:32 +00001484 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1485 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001486}
1487
1488// Tests ContainsRegex().
1489
1490TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1491 const Matcher<const char*> m1 = ContainsRegex(string("a.*z"));
1492 EXPECT_TRUE(m1.Matches("az"));
1493 EXPECT_TRUE(m1.Matches("0abcz1"));
1494 EXPECT_FALSE(m1.Matches(NULL));
1495
1496 const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z"));
1497 EXPECT_TRUE(m2.Matches("azbz"));
1498 EXPECT_TRUE(m2.Matches("az1"));
1499 EXPECT_FALSE(m2.Matches("1a"));
1500}
1501
1502TEST(ContainsRegexTest, CanDescribeSelf) {
1503 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1504 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1505
zhanyong.wand14aaed2010-01-14 05:36:32 +00001506 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1507 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001508}
shiqiane35fdd92008-12-10 05:08:54 +00001509
1510// Tests for wide strings.
1511#if GTEST_HAS_STD_WSTRING
1512TEST(StdWideStrEqTest, MatchesEqual) {
1513 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1514 EXPECT_TRUE(m.Matches(L"Hello"));
1515 EXPECT_FALSE(m.Matches(L"hello"));
1516 EXPECT_FALSE(m.Matches(NULL));
1517
1518 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1519 EXPECT_TRUE(m2.Matches(L"Hello"));
1520 EXPECT_FALSE(m2.Matches(L"Hi"));
1521
1522 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1523 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1524 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1525
1526 ::std::wstring str(L"01204500800");
1527 str[3] = L'\0';
1528 Matcher<const ::std::wstring&> m4 = StrEq(str);
1529 EXPECT_TRUE(m4.Matches(str));
1530 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1531 Matcher<const ::std::wstring&> m5 = StrEq(str);
1532 EXPECT_TRUE(m5.Matches(str));
1533}
1534
1535TEST(StdWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001536 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1537 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001538 Describe(m));
1539
1540 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1541 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1542 Describe(m2));
1543
1544 ::std::wstring str(L"01204500800");
1545 str[3] = L'\0';
1546 Matcher<const ::std::wstring&> m4 = StrEq(str);
1547 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1548 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1549 Matcher<const ::std::wstring&> m5 = StrEq(str);
1550 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1551}
1552
1553TEST(StdWideStrNeTest, MatchesUnequalString) {
1554 Matcher<const wchar_t*> m = StrNe(L"Hello");
1555 EXPECT_TRUE(m.Matches(L""));
1556 EXPECT_TRUE(m.Matches(NULL));
1557 EXPECT_FALSE(m.Matches(L"Hello"));
1558
1559 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1560 EXPECT_TRUE(m2.Matches(L"hello"));
1561 EXPECT_FALSE(m2.Matches(L"Hello"));
1562}
1563
1564TEST(StdWideStrNeTest, CanDescribeSelf) {
1565 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001566 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001567}
1568
1569TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1570 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1571 EXPECT_TRUE(m.Matches(L"Hello"));
1572 EXPECT_TRUE(m.Matches(L"hello"));
1573 EXPECT_FALSE(m.Matches(L"Hi"));
1574 EXPECT_FALSE(m.Matches(NULL));
1575
1576 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1577 EXPECT_TRUE(m2.Matches(L"hello"));
1578 EXPECT_FALSE(m2.Matches(L"Hi"));
1579}
1580
1581TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1582 ::std::wstring str1(L"oabocdooeoo");
1583 ::std::wstring str2(L"OABOCDOOEOO");
1584 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1585 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1586
1587 str1[3] = str2[3] = L'\0';
1588 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1589 EXPECT_TRUE(m1.Matches(str2));
1590
1591 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1592 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1593 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1594 str1[9] = str2[9] = L'\0';
1595 EXPECT_FALSE(m2.Matches(str2));
1596
1597 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1598 EXPECT_TRUE(m3.Matches(str2));
1599
1600 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1601 str2.append(1, L'\0');
1602 EXPECT_FALSE(m3.Matches(str2));
1603 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1604}
1605
1606TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1607 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1608 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1609}
1610
1611TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1612 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1613 EXPECT_TRUE(m.Matches(L"Hi"));
1614 EXPECT_TRUE(m.Matches(NULL));
1615 EXPECT_FALSE(m.Matches(L"Hello"));
1616 EXPECT_FALSE(m.Matches(L"hello"));
1617
1618 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1619 EXPECT_TRUE(m2.Matches(L""));
1620 EXPECT_FALSE(m2.Matches(L"Hello"));
1621}
1622
1623TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1624 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001625 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001626}
1627
1628// Tests that HasSubstr() works for matching wstring-typed values.
1629TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1630 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1631 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1632 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1633
1634 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1635 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1636 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1637}
1638
1639// Tests that HasSubstr() works for matching C-wide-string-typed values.
1640TEST(StdWideHasSubstrTest, WorksForCStrings) {
1641 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1642 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1643 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1644 EXPECT_FALSE(m1.Matches(NULL));
1645
1646 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1647 EXPECT_TRUE(m2.Matches(L"I love food."));
1648 EXPECT_FALSE(m2.Matches(L"tofo"));
1649 EXPECT_FALSE(m2.Matches(NULL));
1650}
1651
1652// Tests that HasSubstr(s) describes itself properly.
1653TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1654 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1655 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1656}
1657
1658// Tests StartsWith(s).
1659
1660TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1661 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1662 EXPECT_TRUE(m1.Matches(L"Hi"));
1663 EXPECT_TRUE(m1.Matches(L""));
1664 EXPECT_FALSE(m1.Matches(NULL));
1665
1666 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1667 EXPECT_TRUE(m2.Matches(L"Hi"));
1668 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1669 EXPECT_TRUE(m2.Matches(L"High"));
1670 EXPECT_FALSE(m2.Matches(L"H"));
1671 EXPECT_FALSE(m2.Matches(L" Hi"));
1672}
1673
1674TEST(StdWideStartsWithTest, CanDescribeSelf) {
1675 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
1676 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1677}
1678
1679// Tests EndsWith(s).
1680
1681TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
1682 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1683 EXPECT_TRUE(m1.Matches(L"Hi"));
1684 EXPECT_TRUE(m1.Matches(L""));
1685 EXPECT_FALSE(m1.Matches(NULL));
1686
1687 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
1688 EXPECT_TRUE(m2.Matches(L"Hi"));
1689 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1690 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1691 EXPECT_FALSE(m2.Matches(L"i"));
1692 EXPECT_FALSE(m2.Matches(L"Hi "));
1693}
1694
1695TEST(StdWideEndsWithTest, CanDescribeSelf) {
1696 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
1697 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1698}
1699
1700#endif // GTEST_HAS_STD_WSTRING
1701
1702#if GTEST_HAS_GLOBAL_WSTRING
1703TEST(GlobalWideStrEqTest, MatchesEqual) {
1704 Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
1705 EXPECT_TRUE(m.Matches(L"Hello"));
1706 EXPECT_FALSE(m.Matches(L"hello"));
1707 EXPECT_FALSE(m.Matches(NULL));
1708
1709 Matcher<const ::wstring&> m2 = StrEq(L"Hello");
1710 EXPECT_TRUE(m2.Matches(L"Hello"));
1711 EXPECT_FALSE(m2.Matches(L"Hi"));
1712
1713 Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1714 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1715 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1716
1717 ::wstring str(L"01204500800");
1718 str[3] = L'\0';
1719 Matcher<const ::wstring&> m4 = StrEq(str);
1720 EXPECT_TRUE(m4.Matches(str));
1721 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1722 Matcher<const ::wstring&> m5 = StrEq(str);
1723 EXPECT_TRUE(m5.Matches(str));
1724}
1725
1726TEST(GlobalWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001727 Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1728 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001729 Describe(m));
1730
1731 Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1732 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1733 Describe(m2));
1734
1735 ::wstring str(L"01204500800");
1736 str[3] = L'\0';
1737 Matcher<const ::wstring&> m4 = StrEq(str);
1738 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1739 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1740 Matcher<const ::wstring&> m5 = StrEq(str);
1741 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1742}
1743
1744TEST(GlobalWideStrNeTest, MatchesUnequalString) {
1745 Matcher<const wchar_t*> m = StrNe(L"Hello");
1746 EXPECT_TRUE(m.Matches(L""));
1747 EXPECT_TRUE(m.Matches(NULL));
1748 EXPECT_FALSE(m.Matches(L"Hello"));
1749
1750 Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
1751 EXPECT_TRUE(m2.Matches(L"hello"));
1752 EXPECT_FALSE(m2.Matches(L"Hello"));
1753}
1754
1755TEST(GlobalWideStrNeTest, CanDescribeSelf) {
1756 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001757 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001758}
1759
1760TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1761 Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
1762 EXPECT_TRUE(m.Matches(L"Hello"));
1763 EXPECT_TRUE(m.Matches(L"hello"));
1764 EXPECT_FALSE(m.Matches(L"Hi"));
1765 EXPECT_FALSE(m.Matches(NULL));
1766
1767 Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
1768 EXPECT_TRUE(m2.Matches(L"hello"));
1769 EXPECT_FALSE(m2.Matches(L"Hi"));
1770}
1771
1772TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1773 ::wstring str1(L"oabocdooeoo");
1774 ::wstring str2(L"OABOCDOOEOO");
1775 Matcher<const ::wstring&> m0 = StrCaseEq(str1);
1776 EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
1777
1778 str1[3] = str2[3] = L'\0';
1779 Matcher<const ::wstring&> m1 = StrCaseEq(str1);
1780 EXPECT_TRUE(m1.Matches(str2));
1781
1782 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1783 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1784 Matcher<const ::wstring&> m2 = StrCaseEq(str1);
1785 str1[9] = str2[9] = L'\0';
1786 EXPECT_FALSE(m2.Matches(str2));
1787
1788 Matcher<const ::wstring&> m3 = StrCaseEq(str1);
1789 EXPECT_TRUE(m3.Matches(str2));
1790
1791 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1792 str2.append(1, L'\0');
1793 EXPECT_FALSE(m3.Matches(str2));
1794 EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
1795}
1796
1797TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
1798 Matcher< ::wstring> m = StrCaseEq(L"Hi");
1799 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1800}
1801
1802TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1803 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1804 EXPECT_TRUE(m.Matches(L"Hi"));
1805 EXPECT_TRUE(m.Matches(NULL));
1806 EXPECT_FALSE(m.Matches(L"Hello"));
1807 EXPECT_FALSE(m.Matches(L"hello"));
1808
1809 Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
1810 EXPECT_TRUE(m2.Matches(L""));
1811 EXPECT_FALSE(m2.Matches(L"Hello"));
1812}
1813
1814TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
1815 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001816 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001817}
1818
1819// Tests that HasSubstr() works for matching wstring-typed values.
1820TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
1821 const Matcher< ::wstring> m1 = HasSubstr(L"foo");
1822 EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
1823 EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
1824
1825 const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
1826 EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
1827 EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
1828}
1829
1830// Tests that HasSubstr() works for matching C-wide-string-typed values.
1831TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
1832 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1833 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1834 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1835 EXPECT_FALSE(m1.Matches(NULL));
1836
1837 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1838 EXPECT_TRUE(m2.Matches(L"I love food."));
1839 EXPECT_FALSE(m2.Matches(L"tofo"));
1840 EXPECT_FALSE(m2.Matches(NULL));
1841}
1842
1843// Tests that HasSubstr(s) describes itself properly.
1844TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
1845 Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
1846 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1847}
1848
1849// Tests StartsWith(s).
1850
1851TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
1852 const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
1853 EXPECT_TRUE(m1.Matches(L"Hi"));
1854 EXPECT_TRUE(m1.Matches(L""));
1855 EXPECT_FALSE(m1.Matches(NULL));
1856
1857 const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
1858 EXPECT_TRUE(m2.Matches(L"Hi"));
1859 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1860 EXPECT_TRUE(m2.Matches(L"High"));
1861 EXPECT_FALSE(m2.Matches(L"H"));
1862 EXPECT_FALSE(m2.Matches(L" Hi"));
1863}
1864
1865TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
1866 Matcher<const ::wstring> m = StartsWith(L"Hi");
1867 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1868}
1869
1870// Tests EndsWith(s).
1871
1872TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
1873 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1874 EXPECT_TRUE(m1.Matches(L"Hi"));
1875 EXPECT_TRUE(m1.Matches(L""));
1876 EXPECT_FALSE(m1.Matches(NULL));
1877
1878 const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
1879 EXPECT_TRUE(m2.Matches(L"Hi"));
1880 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1881 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1882 EXPECT_FALSE(m2.Matches(L"i"));
1883 EXPECT_FALSE(m2.Matches(L"Hi "));
1884}
1885
1886TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
1887 Matcher<const ::wstring> m = EndsWith(L"Hi");
1888 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1889}
1890
1891#endif // GTEST_HAS_GLOBAL_WSTRING
1892
1893
1894typedef ::std::tr1::tuple<long, int> Tuple2; // NOLINT
1895
1896// Tests that Eq() matches a 2-tuple where the first field == the
1897// second field.
1898TEST(Eq2Test, MatchesEqualArguments) {
1899 Matcher<const Tuple2&> m = Eq();
1900 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1901 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1902}
1903
1904// Tests that Eq() describes itself properly.
1905TEST(Eq2Test, CanDescribeSelf) {
1906 Matcher<const Tuple2&> m = Eq();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001907 EXPECT_EQ("are an equal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001908}
1909
1910// Tests that Ge() matches a 2-tuple where the first field >= the
1911// second field.
1912TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
1913 Matcher<const Tuple2&> m = Ge();
1914 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1915 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1916 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1917}
1918
1919// Tests that Ge() describes itself properly.
1920TEST(Ge2Test, CanDescribeSelf) {
1921 Matcher<const Tuple2&> m = Ge();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001922 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001923}
1924
1925// Tests that Gt() matches a 2-tuple where the first field > the
1926// second field.
1927TEST(Gt2Test, MatchesGreaterThanArguments) {
1928 Matcher<const Tuple2&> m = Gt();
1929 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1930 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1931 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1932}
1933
1934// Tests that Gt() describes itself properly.
1935TEST(Gt2Test, CanDescribeSelf) {
1936 Matcher<const Tuple2&> m = Gt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001937 EXPECT_EQ("are a pair where the first > the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001938}
1939
1940// Tests that Le() matches a 2-tuple where the first field <= the
1941// second field.
1942TEST(Le2Test, MatchesLessThanOrEqualArguments) {
1943 Matcher<const Tuple2&> m = Le();
1944 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1945 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1946 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1947}
1948
1949// Tests that Le() describes itself properly.
1950TEST(Le2Test, CanDescribeSelf) {
1951 Matcher<const Tuple2&> m = Le();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001952 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001953}
1954
1955// Tests that Lt() matches a 2-tuple where the first field < the
1956// second field.
1957TEST(Lt2Test, MatchesLessThanArguments) {
1958 Matcher<const Tuple2&> m = Lt();
1959 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1960 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1961 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1962}
1963
1964// Tests that Lt() describes itself properly.
1965TEST(Lt2Test, CanDescribeSelf) {
1966 Matcher<const Tuple2&> m = Lt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001967 EXPECT_EQ("are a pair where the first < the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001968}
1969
1970// Tests that Ne() matches a 2-tuple where the first field != the
1971// second field.
1972TEST(Ne2Test, MatchesUnequalArguments) {
1973 Matcher<const Tuple2&> m = Ne();
1974 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1975 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1976 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1977}
1978
1979// Tests that Ne() describes itself properly.
1980TEST(Ne2Test, CanDescribeSelf) {
1981 Matcher<const Tuple2&> m = Ne();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001982 EXPECT_EQ("are an unequal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001983}
1984
1985// Tests that Not(m) matches any value that doesn't match m.
1986TEST(NotTest, NegatesMatcher) {
1987 Matcher<int> m;
1988 m = Not(Eq(2));
1989 EXPECT_TRUE(m.Matches(3));
1990 EXPECT_FALSE(m.Matches(2));
1991}
1992
1993// Tests that Not(m) describes itself properly.
1994TEST(NotTest, CanDescribeSelf) {
1995 Matcher<int> m = Not(Eq(5));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001996 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001997}
1998
zhanyong.wan18490652009-05-11 18:54:08 +00001999// Tests that monomorphic matchers are safely cast by the Not matcher.
2000TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
2001 // greater_than_5 is a monomorphic matcher.
2002 Matcher<int> greater_than_5 = Gt(5);
2003
2004 Matcher<const int&> m = Not(greater_than_5);
2005 Matcher<int&> m2 = Not(greater_than_5);
2006 Matcher<int&> m3 = Not(m);
2007}
2008
zhanyong.wan02c15052010-06-09 19:21:30 +00002009// Helper to allow easy testing of AllOf matchers with num parameters.
2010void AllOfMatches(int num, const Matcher<int>& m) {
2011 SCOPED_TRACE(Describe(m));
2012 EXPECT_TRUE(m.Matches(0));
2013 for (int i = 1; i <= num; ++i) {
2014 EXPECT_FALSE(m.Matches(i));
2015 }
2016 EXPECT_TRUE(m.Matches(num + 1));
2017}
2018
shiqiane35fdd92008-12-10 05:08:54 +00002019// Tests that AllOf(m1, ..., mn) matches any value that matches all of
2020// the given matchers.
2021TEST(AllOfTest, MatchesWhenAllMatch) {
2022 Matcher<int> m;
2023 m = AllOf(Le(2), Ge(1));
2024 EXPECT_TRUE(m.Matches(1));
2025 EXPECT_TRUE(m.Matches(2));
2026 EXPECT_FALSE(m.Matches(0));
2027 EXPECT_FALSE(m.Matches(3));
2028
2029 m = AllOf(Gt(0), Ne(1), Ne(2));
2030 EXPECT_TRUE(m.Matches(3));
2031 EXPECT_FALSE(m.Matches(2));
2032 EXPECT_FALSE(m.Matches(1));
2033 EXPECT_FALSE(m.Matches(0));
2034
2035 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2036 EXPECT_TRUE(m.Matches(4));
2037 EXPECT_FALSE(m.Matches(3));
2038 EXPECT_FALSE(m.Matches(2));
2039 EXPECT_FALSE(m.Matches(1));
2040 EXPECT_FALSE(m.Matches(0));
2041
2042 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2043 EXPECT_TRUE(m.Matches(0));
2044 EXPECT_TRUE(m.Matches(1));
2045 EXPECT_FALSE(m.Matches(3));
zhanyong.wan02c15052010-06-09 19:21:30 +00002046
2047 // The following tests for varying number of sub-matchers. Due to the way
2048 // the sub-matchers are handled it is enough to test every sub-matcher once
2049 // with sub-matchers using the same matcher type. Varying matcher types are
2050 // checked for above.
2051 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2052 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2053 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2054 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2055 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2056 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2057 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2058 Ne(8)));
2059 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2060 Ne(8), Ne(9)));
2061 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2062 Ne(9), Ne(10)));
shiqiane35fdd92008-12-10 05:08:54 +00002063}
2064
zhanyong.wan616180e2013-06-18 18:49:51 +00002065#if GTEST_LANG_CXX11
2066// Tests the variadic version of the AllOfMatcher.
2067TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
2068 // Make sure AllOf is defined in the right namespace and does not depend on
2069 // ADL.
2070 ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2071 Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2072 Ne(9), Ne(10), Ne(11));
2073 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))"));
2074 AllOfMatches(11, m);
2075 AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2076 Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
2077 Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22),
2078 Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29),
2079 Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36),
2080 Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43),
2081 Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2082 Ne(50)));
2083}
2084
2085#endif // GTEST_LANG_CXX11
2086
shiqiane35fdd92008-12-10 05:08:54 +00002087// Tests that AllOf(m1, ..., mn) describes itself properly.
2088TEST(AllOfTest, CanDescribeSelf) {
2089 Matcher<int> m;
2090 m = AllOf(Le(2), Ge(1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002091 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002092
2093 m = AllOf(Gt(0), Ne(1), Ne(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002094 EXPECT_EQ("(is > 0) and "
2095 "((isn't equal to 1) and "
2096 "(isn't equal to 2))",
shiqiane35fdd92008-12-10 05:08:54 +00002097 Describe(m));
2098
2099
2100 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002101 EXPECT_EQ("((is > 0) and "
2102 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002103 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002104 "(isn't equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002105 Describe(m));
2106
2107
2108 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002109 EXPECT_EQ("((is >= 0) and "
2110 "(is < 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002111 "((isn't equal to 3) and "
2112 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002113 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002114 Describe(m));
2115}
2116
2117// Tests that AllOf(m1, ..., mn) describes its negation properly.
2118TEST(AllOfTest, CanDescribeNegation) {
2119 Matcher<int> m;
2120 m = AllOf(Le(2), Ge(1));
2121 EXPECT_EQ("(isn't <= 2) or "
2122 "(isn't >= 1)",
2123 DescribeNegation(m));
2124
2125 m = AllOf(Gt(0), Ne(1), Ne(2));
2126 EXPECT_EQ("(isn't > 0) or "
2127 "((is equal to 1) or "
2128 "(is equal to 2))",
2129 DescribeNegation(m));
2130
2131
2132 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002133 EXPECT_EQ("((isn't > 0) or "
2134 "(is equal to 1)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002135 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002136 "(is equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002137 DescribeNegation(m));
2138
2139
2140 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002141 EXPECT_EQ("((isn't >= 0) or "
2142 "(isn't < 10)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002143 "((is equal to 3) or "
2144 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002145 "(is equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002146 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00002147}
2148
zhanyong.wan18490652009-05-11 18:54:08 +00002149// Tests that monomorphic matchers are safely cast by the AllOf matcher.
2150TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2151 // greater_than_5 and less_than_10 are monomorphic matchers.
2152 Matcher<int> greater_than_5 = Gt(5);
2153 Matcher<int> less_than_10 = Lt(10);
2154
2155 Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2156 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2157 Matcher<int&> m3 = AllOf(greater_than_5, m2);
2158
2159 // Tests that BothOf works when composing itself.
2160 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2161 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2162}
2163
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002164TEST(AllOfTest, ExplainsResult) {
2165 Matcher<int> m;
2166
2167 // Successful match. Both matchers need to explain. The second
2168 // matcher doesn't give an explanation, so only the first matcher's
2169 // explanation is printed.
2170 m = AllOf(GreaterThan(10), Lt(30));
2171 EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2172
2173 // Successful match. Both matchers need to explain.
2174 m = AllOf(GreaterThan(10), GreaterThan(20));
2175 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2176 Explain(m, 30));
2177
2178 // Successful match. All matchers need to explain. The second
2179 // matcher doesn't given an explanation.
2180 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2181 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2182 Explain(m, 25));
2183
2184 // Successful match. All matchers need to explain.
2185 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2186 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2187 "and which is 10 more than 30",
2188 Explain(m, 40));
2189
2190 // Failed match. The first matcher, which failed, needs to
2191 // explain.
2192 m = AllOf(GreaterThan(10), GreaterThan(20));
2193 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2194
2195 // Failed match. The second matcher, which failed, needs to
2196 // explain. Since it doesn't given an explanation, nothing is
2197 // printed.
2198 m = AllOf(GreaterThan(10), Lt(30));
2199 EXPECT_EQ("", Explain(m, 40));
2200
2201 // Failed match. The second matcher, which failed, needs to
2202 // explain.
2203 m = AllOf(GreaterThan(10), GreaterThan(20));
2204 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2205}
2206
zhanyong.wan02c15052010-06-09 19:21:30 +00002207// Helper to allow easy testing of AnyOf matchers with num parameters.
2208void AnyOfMatches(int num, const Matcher<int>& m) {
2209 SCOPED_TRACE(Describe(m));
2210 EXPECT_FALSE(m.Matches(0));
2211 for (int i = 1; i <= num; ++i) {
2212 EXPECT_TRUE(m.Matches(i));
2213 }
2214 EXPECT_FALSE(m.Matches(num + 1));
2215}
2216
shiqiane35fdd92008-12-10 05:08:54 +00002217// Tests that AnyOf(m1, ..., mn) matches any value that matches at
2218// least one of the given matchers.
2219TEST(AnyOfTest, MatchesWhenAnyMatches) {
2220 Matcher<int> m;
2221 m = AnyOf(Le(1), Ge(3));
2222 EXPECT_TRUE(m.Matches(1));
2223 EXPECT_TRUE(m.Matches(4));
2224 EXPECT_FALSE(m.Matches(2));
2225
2226 m = AnyOf(Lt(0), Eq(1), Eq(2));
2227 EXPECT_TRUE(m.Matches(-1));
2228 EXPECT_TRUE(m.Matches(1));
2229 EXPECT_TRUE(m.Matches(2));
2230 EXPECT_FALSE(m.Matches(0));
2231
2232 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2233 EXPECT_TRUE(m.Matches(-1));
2234 EXPECT_TRUE(m.Matches(1));
2235 EXPECT_TRUE(m.Matches(2));
2236 EXPECT_TRUE(m.Matches(3));
2237 EXPECT_FALSE(m.Matches(0));
2238
2239 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2240 EXPECT_TRUE(m.Matches(0));
2241 EXPECT_TRUE(m.Matches(11));
2242 EXPECT_TRUE(m.Matches(3));
2243 EXPECT_FALSE(m.Matches(2));
zhanyong.wan02c15052010-06-09 19:21:30 +00002244
2245 // The following tests for varying number of sub-matchers. Due to the way
2246 // the sub-matchers are handled it is enough to test every sub-matcher once
2247 // with sub-matchers using the same matcher type. Varying matcher types are
2248 // checked for above.
2249 AnyOfMatches(2, AnyOf(1, 2));
2250 AnyOfMatches(3, AnyOf(1, 2, 3));
2251 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2252 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2253 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2254 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2255 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2256 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2257 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
shiqiane35fdd92008-12-10 05:08:54 +00002258}
2259
zhanyong.wan616180e2013-06-18 18:49:51 +00002260#if GTEST_LANG_CXX11
2261// Tests the variadic version of the AnyOfMatcher.
2262TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2263 // Also make sure AnyOf is defined in the right namespace and does not depend
2264 // on ADL.
2265 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2266
2267 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))"));
2268 AnyOfMatches(11, m);
2269 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2270 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2271 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2272 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2273 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2274}
2275
2276#endif // GTEST_LANG_CXX11
2277
shiqiane35fdd92008-12-10 05:08:54 +00002278// Tests that AnyOf(m1, ..., mn) describes itself properly.
2279TEST(AnyOfTest, CanDescribeSelf) {
2280 Matcher<int> m;
2281 m = AnyOf(Le(1), Ge(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002282 EXPECT_EQ("(is <= 1) or (is >= 3)",
shiqiane35fdd92008-12-10 05:08:54 +00002283 Describe(m));
2284
2285 m = AnyOf(Lt(0), Eq(1), Eq(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002286 EXPECT_EQ("(is < 0) or "
shiqiane35fdd92008-12-10 05:08:54 +00002287 "((is equal to 1) or (is equal to 2))",
2288 Describe(m));
2289
2290 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002291 EXPECT_EQ("((is < 0) or "
2292 "(is equal to 1)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002293 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002294 "(is equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002295 Describe(m));
2296
2297 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002298 EXPECT_EQ("((is <= 0) or "
2299 "(is > 10)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002300 "((is equal to 3) or "
2301 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002302 "(is equal to 7)))",
shiqiane35fdd92008-12-10 05:08:54 +00002303 Describe(m));
2304}
2305
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002306// Tests that AnyOf(m1, ..., mn) describes its negation properly.
2307TEST(AnyOfTest, CanDescribeNegation) {
2308 Matcher<int> m;
2309 m = AnyOf(Le(1), Ge(3));
2310 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2311 DescribeNegation(m));
2312
2313 m = AnyOf(Lt(0), Eq(1), Eq(2));
2314 EXPECT_EQ("(isn't < 0) and "
2315 "((isn't equal to 1) and (isn't equal to 2))",
2316 DescribeNegation(m));
2317
2318 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002319 EXPECT_EQ("((isn't < 0) and "
2320 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002321 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002322 "(isn't equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002323 DescribeNegation(m));
2324
2325 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002326 EXPECT_EQ("((isn't <= 0) and "
2327 "(isn't > 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002328 "((isn't equal to 3) and "
2329 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002330 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002331 DescribeNegation(m));
2332}
2333
zhanyong.wan18490652009-05-11 18:54:08 +00002334// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2335TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2336 // greater_than_5 and less_than_10 are monomorphic matchers.
2337 Matcher<int> greater_than_5 = Gt(5);
2338 Matcher<int> less_than_10 = Lt(10);
2339
2340 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2341 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2342 Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2343
2344 // Tests that EitherOf works when composing itself.
2345 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2346 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2347}
2348
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002349TEST(AnyOfTest, ExplainsResult) {
2350 Matcher<int> m;
2351
2352 // Failed match. Both matchers need to explain. The second
2353 // matcher doesn't give an explanation, so only the first matcher's
2354 // explanation is printed.
2355 m = AnyOf(GreaterThan(10), Lt(0));
2356 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2357
2358 // Failed match. Both matchers need to explain.
2359 m = AnyOf(GreaterThan(10), GreaterThan(20));
2360 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2361 Explain(m, 5));
2362
2363 // Failed match. All matchers need to explain. The second
2364 // matcher doesn't given an explanation.
2365 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2366 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2367 Explain(m, 5));
2368
2369 // Failed match. All matchers need to explain.
2370 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2371 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2372 "and which is 25 less than 30",
2373 Explain(m, 5));
2374
2375 // Successful match. The first matcher, which succeeded, needs to
2376 // explain.
2377 m = AnyOf(GreaterThan(10), GreaterThan(20));
2378 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2379
2380 // Successful match. The second matcher, which succeeded, needs to
2381 // explain. Since it doesn't given an explanation, nothing is
2382 // printed.
2383 m = AnyOf(GreaterThan(10), Lt(30));
2384 EXPECT_EQ("", Explain(m, 0));
2385
2386 // Successful match. The second matcher, which succeeded, needs to
2387 // explain.
2388 m = AnyOf(GreaterThan(30), GreaterThan(20));
2389 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2390}
2391
shiqiane35fdd92008-12-10 05:08:54 +00002392// The following predicate function and predicate functor are for
2393// testing the Truly(predicate) matcher.
2394
2395// Returns non-zero if the input is positive. Note that the return
2396// type of this function is not bool. It's OK as Truly() accepts any
2397// unary function or functor whose return type can be implicitly
2398// converted to bool.
2399int IsPositive(double x) {
2400 return x > 0 ? 1 : 0;
2401}
2402
2403// This functor returns true if the input is greater than the given
2404// number.
2405class IsGreaterThan {
2406 public:
2407 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2408
2409 bool operator()(int n) const { return n > threshold_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002410
shiqiane35fdd92008-12-10 05:08:54 +00002411 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002412 int threshold_;
shiqiane35fdd92008-12-10 05:08:54 +00002413};
2414
2415// For testing Truly().
2416const int foo = 0;
2417
2418// This predicate returns true iff the argument references foo and has
2419// a zero value.
2420bool ReferencesFooAndIsZero(const int& n) {
2421 return (&n == &foo) && (n == 0);
2422}
2423
2424// Tests that Truly(predicate) matches what satisfies the given
2425// predicate.
2426TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2427 Matcher<double> m = Truly(IsPositive);
2428 EXPECT_TRUE(m.Matches(2.0));
2429 EXPECT_FALSE(m.Matches(-1.5));
2430}
2431
2432// Tests that Truly(predicate_functor) works too.
2433TEST(TrulyTest, CanBeUsedWithFunctor) {
2434 Matcher<int> m = Truly(IsGreaterThan(5));
2435 EXPECT_TRUE(m.Matches(6));
2436 EXPECT_FALSE(m.Matches(4));
2437}
2438
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00002439// A class that can be implicitly converted to bool.
2440class ConvertibleToBool {
2441 public:
2442 explicit ConvertibleToBool(int number) : number_(number) {}
2443 operator bool() const { return number_ != 0; }
2444
2445 private:
2446 int number_;
2447};
2448
2449ConvertibleToBool IsNotZero(int number) {
2450 return ConvertibleToBool(number);
2451}
2452
2453// Tests that the predicate used in Truly() may return a class that's
2454// implicitly convertible to bool, even when the class has no
2455// operator!().
2456TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2457 Matcher<int> m = Truly(IsNotZero);
2458 EXPECT_TRUE(m.Matches(1));
2459 EXPECT_FALSE(m.Matches(0));
2460}
2461
shiqiane35fdd92008-12-10 05:08:54 +00002462// Tests that Truly(predicate) can describe itself properly.
2463TEST(TrulyTest, CanDescribeSelf) {
2464 Matcher<double> m = Truly(IsPositive);
2465 EXPECT_EQ("satisfies the given predicate",
2466 Describe(m));
2467}
2468
2469// Tests that Truly(predicate) works when the matcher takes its
2470// argument by reference.
2471TEST(TrulyTest, WorksForByRefArguments) {
2472 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2473 EXPECT_TRUE(m.Matches(foo));
2474 int n = 0;
2475 EXPECT_FALSE(m.Matches(n));
2476}
2477
2478// Tests that Matches(m) is a predicate satisfied by whatever that
2479// matches matcher m.
2480TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2481 EXPECT_TRUE(Matches(Ge(0))(1));
2482 EXPECT_FALSE(Matches(Eq('a'))('b'));
2483}
2484
2485// Tests that Matches(m) works when the matcher takes its argument by
2486// reference.
2487TEST(MatchesTest, WorksOnByRefArguments) {
2488 int m = 0, n = 0;
2489 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2490 EXPECT_FALSE(Matches(Ref(m))(n));
2491}
2492
2493// Tests that a Matcher on non-reference type can be used in
2494// Matches().
2495TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
2496 Matcher<int> eq5 = Eq(5);
2497 EXPECT_TRUE(Matches(eq5)(5));
2498 EXPECT_FALSE(Matches(eq5)(2));
2499}
2500
zhanyong.wanb8243162009-06-04 05:48:20 +00002501// Tests Value(value, matcher). Since Value() is a simple wrapper for
2502// Matches(), which has been tested already, we don't spend a lot of
2503// effort on testing Value().
2504TEST(ValueTest, WorksWithPolymorphicMatcher) {
2505 EXPECT_TRUE(Value("hi", StartsWith("h")));
2506 EXPECT_FALSE(Value(5, Gt(10)));
2507}
2508
2509TEST(ValueTest, WorksWithMonomorphicMatcher) {
2510 const Matcher<int> is_zero = Eq(0);
2511 EXPECT_TRUE(Value(0, is_zero));
2512 EXPECT_FALSE(Value('a', is_zero));
2513
2514 int n = 0;
2515 const Matcher<const int&> ref_n = Ref(n);
2516 EXPECT_TRUE(Value(n, ref_n));
2517 EXPECT_FALSE(Value(1, ref_n));
2518}
2519
zhanyong.wana862f1d2010-03-15 21:23:04 +00002520TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002521 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002522 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002523 EXPECT_EQ("% 2 == 0", listener1.str());
2524
2525 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002526 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002527 EXPECT_EQ("", listener2.str());
2528}
2529
zhanyong.wana862f1d2010-03-15 21:23:04 +00002530TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002531 const Matcher<int> is_even = PolymorphicIsEven();
2532 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002533 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002534 EXPECT_EQ("% 2 == 0", listener1.str());
2535
2536 const Matcher<const double&> is_zero = Eq(0);
2537 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002538 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002539 EXPECT_EQ("", listener2.str());
2540}
2541
zhanyong.wana862f1d2010-03-15 21:23:04 +00002542MATCHER_P(Really, inner_matcher, "") {
2543 return ExplainMatchResult(inner_matcher, arg, result_listener);
2544}
2545
2546TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
2547 EXPECT_THAT(0, Really(Eq(0)));
2548}
2549
zhanyong.wanbf550852009-06-09 06:09:53 +00002550TEST(AllArgsTest, WorksForTuple) {
2551 EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
2552 EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
2553}
2554
2555TEST(AllArgsTest, WorksForNonTuple) {
2556 EXPECT_THAT(42, AllArgs(Gt(0)));
2557 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
2558}
2559
2560class AllArgsHelper {
2561 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002562 AllArgsHelper() {}
2563
zhanyong.wanbf550852009-06-09 06:09:53 +00002564 MOCK_METHOD2(Helper, int(char x, int y));
zhanyong.wan32de5f52009-12-23 00:13:23 +00002565
2566 private:
2567 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
zhanyong.wanbf550852009-06-09 06:09:53 +00002568};
2569
2570TEST(AllArgsTest, WorksInWithClause) {
2571 AllArgsHelper helper;
2572 ON_CALL(helper, Helper(_, _))
2573 .With(AllArgs(Lt()))
2574 .WillByDefault(Return(1));
2575 EXPECT_CALL(helper, Helper(_, _));
2576 EXPECT_CALL(helper, Helper(_, _))
2577 .With(AllArgs(Gt()))
2578 .WillOnce(Return(2));
2579
2580 EXPECT_EQ(1, helper.Helper('\1', 2));
2581 EXPECT_EQ(2, helper.Helper('a', 1));
2582}
2583
shiqiane35fdd92008-12-10 05:08:54 +00002584// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2585// matches the matcher.
2586TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
2587 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
2588 ASSERT_THAT("Foo", EndsWith("oo"));
2589 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
2590 EXPECT_THAT("Hello", StartsWith("Hell"));
2591}
2592
2593// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2594// doesn't match the matcher.
2595TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
2596 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
2597 // which cannot reference auto variables.
zhanyong.wan736baa82010-09-27 17:44:16 +00002598 static unsigned short n; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00002599 n = 5;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002600
2601 // VC++ prior to version 8.0 SP1 has a bug where it will not see any
2602 // functions declared in the namespace scope from within nested classes.
2603 // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
2604 // namespace-level functions invoked inside them need to be explicitly
2605 // resolved.
2606 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
shiqiane35fdd92008-12-10 05:08:54 +00002607 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002608 "Expected: is > 10\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002609 " Actual: 5" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002610 n = 0;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002611 EXPECT_NONFATAL_FAILURE(
2612 EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
2613 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002614 "Expected: (is <= 7) and (is >= 5)\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002615 " Actual: 0" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002616}
2617
2618// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
2619// has a reference type.
2620TEST(MatcherAssertionTest, WorksForByRefArguments) {
2621 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
2622 // reference auto variables.
2623 static int n;
2624 n = 0;
2625 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002626 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
shiqiane35fdd92008-12-10 05:08:54 +00002627 "Value of: n\n"
2628 "Expected: does not reference the variable @");
2629 // Tests the "Actual" part.
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002630 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
zhanyong.wan736baa82010-09-27 17:44:16 +00002631 "Actual: 0" + OfType("int") + ", which is located @");
shiqiane35fdd92008-12-10 05:08:54 +00002632}
2633
zhanyong.wan95b12332009-09-25 18:55:50 +00002634#if !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002635// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
2636// monomorphic.
zhanyong.wan95b12332009-09-25 18:55:50 +00002637
2638// ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
2639// Symbian compiler: it tries to compile
2640// template<T, U> class MatcherCastImpl { ...
zhanyong.wandb22c222010-01-28 21:52:29 +00002641// virtual bool MatchAndExplain(T x, ...) const {
2642// return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
zhanyong.wan95b12332009-09-25 18:55:50 +00002643// with U == string and T == const char*
2644// With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
2645// the compiler silently crashes with no output.
2646// If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
2647// the code compiles but the converted string is bogus.
shiqiane35fdd92008-12-10 05:08:54 +00002648TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
2649 Matcher<const char*> starts_with_he = StartsWith("he");
2650 ASSERT_THAT("hello", starts_with_he);
2651
2652 Matcher<const string&> ends_with_ok = EndsWith("ok");
2653 ASSERT_THAT("book", ends_with_ok);
zhanyong.wan736baa82010-09-27 17:44:16 +00002654 const string bad = "bad";
2655 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
2656 "Value of: bad\n"
2657 "Expected: ends with \"ok\"\n"
2658 " Actual: \"bad\"");
shiqiane35fdd92008-12-10 05:08:54 +00002659 Matcher<int> is_greater_than_5 = Gt(5);
2660 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
2661 "Value of: 5\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002662 "Expected: is > 5\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002663 " Actual: 5" + OfType("int"));
shiqiane35fdd92008-12-10 05:08:54 +00002664}
zhanyong.wan95b12332009-09-25 18:55:50 +00002665#endif // !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002666
2667// Tests floating-point matchers.
2668template <typename RawType>
2669class FloatingPointTest : public testing::Test {
2670 protected:
zhanyong.wan35877b72013-09-18 17:51:08 +00002671 typedef testing::internal::FloatingPoint<RawType> Floating;
shiqiane35fdd92008-12-10 05:08:54 +00002672 typedef typename Floating::Bits Bits;
2673
zhanyong.wan35877b72013-09-18 17:51:08 +00002674 FloatingPointTest()
2675 : max_ulps_(Floating::kMaxUlps),
2676 zero_bits_(Floating(0).bits()),
2677 one_bits_(Floating(1).bits()),
2678 infinity_bits_(Floating(Floating::Infinity()).bits()),
2679 close_to_positive_zero_(
2680 Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
2681 close_to_negative_zero_(
2682 -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
2683 further_from_negative_zero_(-Floating::ReinterpretBits(
2684 zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
2685 close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
2686 further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
2687 infinity_(Floating::Infinity()),
2688 close_to_infinity_(
2689 Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
2690 further_from_infinity_(
2691 Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
2692 max_(Floating::Max()),
2693 nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
2694 nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
shiqiane35fdd92008-12-10 05:08:54 +00002695 }
2696
2697 void TestSize() {
2698 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2699 }
2700
2701 // A battery of tests for FloatingEqMatcher::Matches.
2702 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2703 void TestMatches(
2704 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
2705 Matcher<RawType> m1 = matcher_maker(0.0);
2706 EXPECT_TRUE(m1.Matches(-0.0));
2707 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
2708 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
2709 EXPECT_FALSE(m1.Matches(1.0));
2710
2711 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
2712 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
2713
2714 Matcher<RawType> m3 = matcher_maker(1.0);
2715 EXPECT_TRUE(m3.Matches(close_to_one_));
2716 EXPECT_FALSE(m3.Matches(further_from_one_));
2717
2718 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
2719 EXPECT_FALSE(m3.Matches(0.0));
2720
2721 Matcher<RawType> m4 = matcher_maker(-infinity_);
2722 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
2723
2724 Matcher<RawType> m5 = matcher_maker(infinity_);
2725 EXPECT_TRUE(m5.Matches(close_to_infinity_));
2726
2727 // This is interesting as the representations of infinity_ and nan1_
2728 // are only 1 DLP apart.
2729 EXPECT_FALSE(m5.Matches(nan1_));
2730
2731 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2732 // some cases.
2733 Matcher<const RawType&> m6 = matcher_maker(0.0);
2734 EXPECT_TRUE(m6.Matches(-0.0));
2735 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
2736 EXPECT_FALSE(m6.Matches(1.0));
2737
2738 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2739 // cases.
2740 Matcher<RawType&> m7 = matcher_maker(0.0);
2741 RawType x = 0.0;
2742 EXPECT_TRUE(m7.Matches(x));
2743 x = 0.01f;
2744 EXPECT_FALSE(m7.Matches(x));
2745 }
2746
2747 // Pre-calculated numbers to be used by the tests.
2748
zhanyong.wan35877b72013-09-18 17:51:08 +00002749 const size_t max_ulps_;
shiqiane35fdd92008-12-10 05:08:54 +00002750
zhanyong.wan35877b72013-09-18 17:51:08 +00002751 const Bits zero_bits_; // The bits that represent 0.0.
2752 const Bits one_bits_; // The bits that represent 1.0.
2753 const Bits infinity_bits_; // The bits that represent +infinity.
shiqiane35fdd92008-12-10 05:08:54 +00002754
zhanyong.wan35877b72013-09-18 17:51:08 +00002755 // Some numbers close to 0.0.
2756 const RawType close_to_positive_zero_;
2757 const RawType close_to_negative_zero_;
2758 const RawType further_from_negative_zero_;
shiqiane35fdd92008-12-10 05:08:54 +00002759
zhanyong.wan35877b72013-09-18 17:51:08 +00002760 // Some numbers close to 1.0.
2761 const RawType close_to_one_;
2762 const RawType further_from_one_;
2763
2764 // Some numbers close to +infinity.
2765 const RawType infinity_;
2766 const RawType close_to_infinity_;
2767 const RawType further_from_infinity_;
2768
2769 // Maximum representable value that's not infinity.
2770 const RawType max_;
2771
2772 // Some NaNs.
2773 const RawType nan1_;
2774 const RawType nan2_;
shiqiane35fdd92008-12-10 05:08:54 +00002775};
2776
zhanyong.wan616180e2013-06-18 18:49:51 +00002777// Tests floating-point matchers with fixed epsilons.
2778template <typename RawType>
2779class FloatingPointNearTest : public FloatingPointTest<RawType> {
2780 protected:
2781 typedef FloatingPointTest<RawType> ParentType;
2782
2783 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
2784 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2785 void TestNearMatches(
2786 testing::internal::FloatingEqMatcher<RawType>
2787 (*matcher_maker)(RawType, RawType)) {
2788 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
2789 EXPECT_TRUE(m1.Matches(0.0));
2790 EXPECT_TRUE(m1.Matches(-0.0));
2791 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
2792 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
2793 EXPECT_FALSE(m1.Matches(1.0));
2794
2795 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
2796 EXPECT_TRUE(m2.Matches(0.0));
2797 EXPECT_TRUE(m2.Matches(-0.0));
2798 EXPECT_TRUE(m2.Matches(1.0));
2799 EXPECT_TRUE(m2.Matches(-1.0));
2800 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
2801 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
2802
2803 // Check that inf matches inf, regardless of the of the specified max
2804 // absolute error.
2805 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
2806 EXPECT_TRUE(m3.Matches(ParentType::infinity_));
2807 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
2808 EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
2809
2810 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
2811 EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
2812 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
2813 EXPECT_FALSE(m4.Matches(ParentType::infinity_));
2814
2815 // Test various overflow scenarios.
zhanyong.wan35877b72013-09-18 17:51:08 +00002816 Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
2817 EXPECT_TRUE(m5.Matches(ParentType::max_));
2818 EXPECT_FALSE(m5.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002819
zhanyong.wan35877b72013-09-18 17:51:08 +00002820 Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
2821 EXPECT_FALSE(m6.Matches(ParentType::max_));
2822 EXPECT_TRUE(m6.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002823
zhanyong.wan35877b72013-09-18 17:51:08 +00002824 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
2825 EXPECT_TRUE(m7.Matches(ParentType::max_));
2826 EXPECT_FALSE(m7.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002827
zhanyong.wan35877b72013-09-18 17:51:08 +00002828 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
2829 EXPECT_FALSE(m8.Matches(ParentType::max_));
2830 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002831
2832 // The difference between max() and -max() normally overflows to infinity,
2833 // but it should still match if the max_abs_error is also infinity.
2834 Matcher<RawType> m9 = matcher_maker(
zhanyong.wan35877b72013-09-18 17:51:08 +00002835 ParentType::max_, ParentType::infinity_);
2836 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002837
2838 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2839 // some cases.
2840 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
2841 EXPECT_TRUE(m10.Matches(-0.0));
2842 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
2843 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
2844
2845 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2846 // cases.
2847 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
2848 RawType x = 0.0;
2849 EXPECT_TRUE(m11.Matches(x));
2850 x = 1.0f;
2851 EXPECT_TRUE(m11.Matches(x));
2852 x = -1.0f;
2853 EXPECT_TRUE(m11.Matches(x));
2854 x = 1.1f;
2855 EXPECT_FALSE(m11.Matches(x));
2856 x = -1.1f;
2857 EXPECT_FALSE(m11.Matches(x));
2858 }
2859};
2860
shiqiane35fdd92008-12-10 05:08:54 +00002861// Instantiate FloatingPointTest for testing floats.
2862typedef FloatingPointTest<float> FloatTest;
2863
2864TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
2865 TestMatches(&FloatEq);
2866}
2867
2868TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
2869 TestMatches(&NanSensitiveFloatEq);
2870}
2871
2872TEST_F(FloatTest, FloatEqCannotMatchNaN) {
2873 // FloatEq never matches NaN.
2874 Matcher<float> m = FloatEq(nan1_);
2875 EXPECT_FALSE(m.Matches(nan1_));
2876 EXPECT_FALSE(m.Matches(nan2_));
2877 EXPECT_FALSE(m.Matches(1.0));
2878}
2879
2880TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
2881 // NanSensitiveFloatEq will match NaN.
2882 Matcher<float> m = NanSensitiveFloatEq(nan1_);
2883 EXPECT_TRUE(m.Matches(nan1_));
2884 EXPECT_TRUE(m.Matches(nan2_));
2885 EXPECT_FALSE(m.Matches(1.0));
2886}
2887
2888TEST_F(FloatTest, FloatEqCanDescribeSelf) {
2889 Matcher<float> m1 = FloatEq(2.0f);
2890 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002891 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002892
2893 Matcher<float> m2 = FloatEq(0.5f);
2894 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002895 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002896
2897 Matcher<float> m3 = FloatEq(nan1_);
2898 EXPECT_EQ("never matches", Describe(m3));
2899 EXPECT_EQ("is anything", DescribeNegation(m3));
2900}
2901
2902TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
2903 Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
2904 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002905 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002906
2907 Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
2908 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002909 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002910
2911 Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
2912 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002913 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00002914}
2915
zhanyong.wan616180e2013-06-18 18:49:51 +00002916// Instantiate FloatingPointTest for testing floats with a user-specified
2917// max absolute error.
2918typedef FloatingPointNearTest<float> FloatNearTest;
2919
2920TEST_F(FloatNearTest, FloatNearMatches) {
2921 TestNearMatches(&FloatNear);
2922}
2923
2924TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
2925 TestNearMatches(&NanSensitiveFloatNear);
2926}
2927
2928TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
2929 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
2930 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2931 EXPECT_EQ(
2932 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2933
2934 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
2935 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2936 EXPECT_EQ(
2937 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2938
2939 Matcher<float> m3 = FloatNear(nan1_, 0.0);
2940 EXPECT_EQ("never matches", Describe(m3));
2941 EXPECT_EQ("is anything", DescribeNegation(m3));
2942}
2943
2944TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
2945 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
2946 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2947 EXPECT_EQ(
2948 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2949
2950 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
2951 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2952 EXPECT_EQ(
2953 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2954
2955 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
2956 EXPECT_EQ("is NaN", Describe(m3));
2957 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
2958}
2959
2960TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
2961 // FloatNear never matches NaN.
2962 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
2963 EXPECT_FALSE(m.Matches(nan1_));
2964 EXPECT_FALSE(m.Matches(nan2_));
2965 EXPECT_FALSE(m.Matches(1.0));
2966}
2967
2968TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
2969 // NanSensitiveFloatNear will match NaN.
2970 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
2971 EXPECT_TRUE(m.Matches(nan1_));
2972 EXPECT_TRUE(m.Matches(nan2_));
2973 EXPECT_FALSE(m.Matches(1.0));
2974}
2975
shiqiane35fdd92008-12-10 05:08:54 +00002976// Instantiate FloatingPointTest for testing doubles.
2977typedef FloatingPointTest<double> DoubleTest;
2978
2979TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
2980 TestMatches(&DoubleEq);
2981}
2982
2983TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
2984 TestMatches(&NanSensitiveDoubleEq);
2985}
2986
2987TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
2988 // DoubleEq never matches NaN.
2989 Matcher<double> m = DoubleEq(nan1_);
2990 EXPECT_FALSE(m.Matches(nan1_));
2991 EXPECT_FALSE(m.Matches(nan2_));
2992 EXPECT_FALSE(m.Matches(1.0));
2993}
2994
2995TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
2996 // NanSensitiveDoubleEq will match NaN.
2997 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
2998 EXPECT_TRUE(m.Matches(nan1_));
2999 EXPECT_TRUE(m.Matches(nan2_));
3000 EXPECT_FALSE(m.Matches(1.0));
3001}
3002
3003TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3004 Matcher<double> m1 = DoubleEq(2.0);
3005 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003006 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003007
3008 Matcher<double> m2 = DoubleEq(0.5);
3009 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003010 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003011
3012 Matcher<double> m3 = DoubleEq(nan1_);
3013 EXPECT_EQ("never matches", Describe(m3));
3014 EXPECT_EQ("is anything", DescribeNegation(m3));
3015}
3016
3017TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3018 Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3019 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003020 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003021
3022 Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3023 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003024 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003025
3026 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3027 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003028 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00003029}
3030
zhanyong.wan616180e2013-06-18 18:49:51 +00003031// Instantiate FloatingPointTest for testing floats with a user-specified
3032// max absolute error.
3033typedef FloatingPointNearTest<double> DoubleNearTest;
3034
3035TEST_F(DoubleNearTest, DoubleNearMatches) {
3036 TestNearMatches(&DoubleNear);
3037}
3038
3039TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3040 TestNearMatches(&NanSensitiveDoubleNear);
3041}
3042
3043TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3044 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3045 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3046 EXPECT_EQ(
3047 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3048
3049 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3050 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3051 EXPECT_EQ(
3052 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3053
3054 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3055 EXPECT_EQ("never matches", Describe(m3));
3056 EXPECT_EQ("is anything", DescribeNegation(m3));
3057}
3058
3059TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3060 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3061 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3062 EXPECT_EQ(
3063 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3064
3065 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3066 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3067 EXPECT_EQ(
3068 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3069
3070 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3071 EXPECT_EQ("is NaN", Describe(m3));
3072 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3073}
3074
3075TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3076 // DoubleNear never matches NaN.
3077 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3078 EXPECT_FALSE(m.Matches(nan1_));
3079 EXPECT_FALSE(m.Matches(nan2_));
3080 EXPECT_FALSE(m.Matches(1.0));
3081}
3082
3083TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3084 // NanSensitiveDoubleNear will match NaN.
3085 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3086 EXPECT_TRUE(m.Matches(nan1_));
3087 EXPECT_TRUE(m.Matches(nan2_));
3088 EXPECT_FALSE(m.Matches(1.0));
3089}
3090
shiqiane35fdd92008-12-10 05:08:54 +00003091TEST(PointeeTest, RawPointer) {
3092 const Matcher<int*> m = Pointee(Ge(0));
3093
3094 int n = 1;
3095 EXPECT_TRUE(m.Matches(&n));
3096 n = -1;
3097 EXPECT_FALSE(m.Matches(&n));
3098 EXPECT_FALSE(m.Matches(NULL));
3099}
3100
3101TEST(PointeeTest, RawPointerToConst) {
3102 const Matcher<const double*> m = Pointee(Ge(0));
3103
3104 double x = 1;
3105 EXPECT_TRUE(m.Matches(&x));
3106 x = -1;
3107 EXPECT_FALSE(m.Matches(&x));
3108 EXPECT_FALSE(m.Matches(NULL));
3109}
3110
3111TEST(PointeeTest, ReferenceToConstRawPointer) {
3112 const Matcher<int* const &> m = Pointee(Ge(0));
3113
3114 int n = 1;
3115 EXPECT_TRUE(m.Matches(&n));
3116 n = -1;
3117 EXPECT_FALSE(m.Matches(&n));
3118 EXPECT_FALSE(m.Matches(NULL));
3119}
3120
3121TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3122 const Matcher<double* &> m = Pointee(Ge(0));
3123
3124 double x = 1.0;
3125 double* p = &x;
3126 EXPECT_TRUE(m.Matches(p));
3127 x = -1;
3128 EXPECT_FALSE(m.Matches(p));
3129 p = NULL;
3130 EXPECT_FALSE(m.Matches(p));
3131}
3132
vladlosevada23472012-08-14 15:38:49 +00003133// Minimal const-propagating pointer.
3134template <typename T>
3135class ConstPropagatingPtr {
3136 public:
3137 typedef T element_type;
3138
3139 ConstPropagatingPtr() : val_() {}
3140 explicit ConstPropagatingPtr(T* t) : val_(t) {}
3141 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3142
3143 T* get() { return val_; }
3144 T& operator*() { return *val_; }
3145 // Most smart pointers return non-const T* and T& from the next methods.
3146 const T* get() const { return val_; }
3147 const T& operator*() const { return *val_; }
3148
3149 private:
3150 T* val_;
3151};
3152
3153TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3154 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3155 int three = 3;
3156 const ConstPropagatingPtr<int> co(&three);
3157 ConstPropagatingPtr<int> o(&three);
3158 EXPECT_TRUE(m.Matches(o));
3159 EXPECT_TRUE(m.Matches(co));
3160 *o = 6;
3161 EXPECT_FALSE(m.Matches(o));
3162 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3163}
3164
shiqiane35fdd92008-12-10 05:08:54 +00003165TEST(PointeeTest, NeverMatchesNull) {
3166 const Matcher<const char*> m = Pointee(_);
3167 EXPECT_FALSE(m.Matches(NULL));
3168}
3169
3170// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3171TEST(PointeeTest, MatchesAgainstAValue) {
3172 const Matcher<int*> m = Pointee(5);
3173
3174 int n = 5;
3175 EXPECT_TRUE(m.Matches(&n));
3176 n = -1;
3177 EXPECT_FALSE(m.Matches(&n));
3178 EXPECT_FALSE(m.Matches(NULL));
3179}
3180
3181TEST(PointeeTest, CanDescribeSelf) {
3182 const Matcher<int*> m = Pointee(Gt(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003183 EXPECT_EQ("points to a value that is > 3", Describe(m));
3184 EXPECT_EQ("does not point to a value that is > 3",
shiqiane35fdd92008-12-10 05:08:54 +00003185 DescribeNegation(m));
3186}
3187
shiqiane35fdd92008-12-10 05:08:54 +00003188TEST(PointeeTest, CanExplainMatchResult) {
3189 const Matcher<const string*> m = Pointee(StartsWith("Hi"));
3190
3191 EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL)));
3192
zhanyong.wan736baa82010-09-27 17:44:16 +00003193 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
3194 long n = 3; // NOLINT
3195 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003196 Explain(m2, &n));
3197}
3198
3199TEST(PointeeTest, AlwaysExplainsPointee) {
3200 const Matcher<int*> m = Pointee(0);
3201 int n = 42;
zhanyong.wan736baa82010-09-27 17:44:16 +00003202 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
shiqiane35fdd92008-12-10 05:08:54 +00003203}
3204
3205// An uncopyable class.
3206class Uncopyable {
3207 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003208 explicit Uncopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003209
3210 int value() const { return value_; }
3211 private:
3212 const int value_;
3213 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3214};
3215
3216// Returns true iff x.value() is positive.
3217bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3218
3219// A user-defined struct for testing Field().
3220struct AStruct {
3221 AStruct() : x(0), y(1.0), z(5), p(NULL) {}
3222 AStruct(const AStruct& rhs)
3223 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3224
3225 int x; // A non-const field.
3226 const double y; // A const field.
3227 Uncopyable z; // An uncopyable field.
3228 const char* p; // A pointer field.
zhanyong.wan32de5f52009-12-23 00:13:23 +00003229
3230 private:
3231 GTEST_DISALLOW_ASSIGN_(AStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003232};
3233
3234// A derived struct for testing Field().
3235struct DerivedStruct : public AStruct {
3236 char ch;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003237
3238 private:
3239 GTEST_DISALLOW_ASSIGN_(DerivedStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003240};
3241
3242// Tests that Field(&Foo::field, ...) works when field is non-const.
3243TEST(FieldTest, WorksForNonConstField) {
3244 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
3245
3246 AStruct a;
3247 EXPECT_TRUE(m.Matches(a));
3248 a.x = -1;
3249 EXPECT_FALSE(m.Matches(a));
3250}
3251
3252// Tests that Field(&Foo::field, ...) works when field is const.
3253TEST(FieldTest, WorksForConstField) {
3254 AStruct a;
3255
3256 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
3257 EXPECT_TRUE(m.Matches(a));
3258 m = Field(&AStruct::y, Le(0.0));
3259 EXPECT_FALSE(m.Matches(a));
3260}
3261
3262// Tests that Field(&Foo::field, ...) works when field is not copyable.
3263TEST(FieldTest, WorksForUncopyableField) {
3264 AStruct a;
3265
3266 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3267 EXPECT_TRUE(m.Matches(a));
3268 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3269 EXPECT_FALSE(m.Matches(a));
3270}
3271
3272// Tests that Field(&Foo::field, ...) works when field is a pointer.
3273TEST(FieldTest, WorksForPointerField) {
3274 // Matching against NULL.
3275 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
3276 AStruct a;
3277 EXPECT_TRUE(m.Matches(a));
3278 a.p = "hi";
3279 EXPECT_FALSE(m.Matches(a));
3280
3281 // Matching a pointer that is not NULL.
3282 m = Field(&AStruct::p, StartsWith("hi"));
3283 a.p = "hill";
3284 EXPECT_TRUE(m.Matches(a));
3285 a.p = "hole";
3286 EXPECT_FALSE(m.Matches(a));
3287}
3288
3289// Tests that Field() works when the object is passed by reference.
3290TEST(FieldTest, WorksForByRefArgument) {
3291 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3292
3293 AStruct a;
3294 EXPECT_TRUE(m.Matches(a));
3295 a.x = -1;
3296 EXPECT_FALSE(m.Matches(a));
3297}
3298
3299// Tests that Field(&Foo::field, ...) works when the argument's type
3300// is a sub-type of Foo.
3301TEST(FieldTest, WorksForArgumentOfSubType) {
3302 // Note that the matcher expects DerivedStruct but we say AStruct
3303 // inside Field().
3304 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
3305
3306 DerivedStruct d;
3307 EXPECT_TRUE(m.Matches(d));
3308 d.x = -1;
3309 EXPECT_FALSE(m.Matches(d));
3310}
3311
3312// Tests that Field(&Foo::field, m) works when field's type and m's
3313// argument type are compatible but not the same.
3314TEST(FieldTest, WorksForCompatibleMatcherType) {
3315 // The field is an int, but the inner matcher expects a signed char.
3316 Matcher<const AStruct&> m = Field(&AStruct::x,
3317 Matcher<signed char>(Ge(0)));
3318
3319 AStruct a;
3320 EXPECT_TRUE(m.Matches(a));
3321 a.x = -1;
3322 EXPECT_FALSE(m.Matches(a));
3323}
3324
3325// Tests that Field() can describe itself.
3326TEST(FieldTest, CanDescribeSelf) {
3327 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3328
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003329 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3330 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003331}
3332
3333// Tests that Field() can explain the match result.
3334TEST(FieldTest, CanExplainMatchResult) {
3335 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3336
3337 AStruct a;
3338 a.x = 1;
zhanyong.wan736baa82010-09-27 17:44:16 +00003339 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003340
3341 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003342 EXPECT_EQ(
3343 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
3344 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003345}
3346
3347// Tests that Field() works when the argument is a pointer to const.
3348TEST(FieldForPointerTest, WorksForPointerToConst) {
3349 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3350
3351 AStruct a;
3352 EXPECT_TRUE(m.Matches(&a));
3353 a.x = -1;
3354 EXPECT_FALSE(m.Matches(&a));
3355}
3356
3357// Tests that Field() works when the argument is a pointer to non-const.
3358TEST(FieldForPointerTest, WorksForPointerToNonConst) {
3359 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
3360
3361 AStruct a;
3362 EXPECT_TRUE(m.Matches(&a));
3363 a.x = -1;
3364 EXPECT_FALSE(m.Matches(&a));
3365}
3366
zhanyong.wan6953a722010-01-13 05:15:07 +00003367// Tests that Field() works when the argument is a reference to a const pointer.
3368TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
3369 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
3370
3371 AStruct a;
3372 EXPECT_TRUE(m.Matches(&a));
3373 a.x = -1;
3374 EXPECT_FALSE(m.Matches(&a));
3375}
3376
shiqiane35fdd92008-12-10 05:08:54 +00003377// Tests that Field() does not match the NULL pointer.
3378TEST(FieldForPointerTest, DoesNotMatchNull) {
3379 Matcher<const AStruct*> m = Field(&AStruct::x, _);
3380 EXPECT_FALSE(m.Matches(NULL));
3381}
3382
3383// Tests that Field(&Foo::field, ...) works when the argument's type
3384// is a sub-type of const Foo*.
3385TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
3386 // Note that the matcher expects DerivedStruct but we say AStruct
3387 // inside Field().
3388 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
3389
3390 DerivedStruct d;
3391 EXPECT_TRUE(m.Matches(&d));
3392 d.x = -1;
3393 EXPECT_FALSE(m.Matches(&d));
3394}
3395
3396// Tests that Field() can describe itself when used to match a pointer.
3397TEST(FieldForPointerTest, CanDescribeSelf) {
3398 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3399
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003400 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3401 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003402}
3403
3404// Tests that Field() can explain the result of matching a pointer.
3405TEST(FieldForPointerTest, CanExplainMatchResult) {
3406 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3407
3408 AStruct a;
3409 a.x = 1;
3410 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003411 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
3412 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003413
3414 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003415 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
3416 ", which is 1 more than 0", Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003417}
3418
3419// A user-defined class for testing Property().
3420class AClass {
3421 public:
3422 AClass() : n_(0) {}
3423
3424 // A getter that returns a non-reference.
3425 int n() const { return n_; }
3426
3427 void set_n(int new_n) { n_ = new_n; }
3428
3429 // A getter that returns a reference to const.
3430 const string& s() const { return s_; }
3431
3432 void set_s(const string& new_s) { s_ = new_s; }
3433
3434 // A getter that returns a reference to non-const.
3435 double& x() const { return x_; }
3436 private:
3437 int n_;
3438 string s_;
3439
3440 static double x_;
3441};
3442
3443double AClass::x_ = 0.0;
3444
3445// A derived class for testing Property().
3446class DerivedClass : public AClass {
3447 private:
3448 int k_;
3449};
3450
3451// Tests that Property(&Foo::property, ...) works when property()
3452// returns a non-reference.
3453TEST(PropertyTest, WorksForNonReferenceProperty) {
3454 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3455
3456 AClass a;
3457 a.set_n(1);
3458 EXPECT_TRUE(m.Matches(a));
3459
3460 a.set_n(-1);
3461 EXPECT_FALSE(m.Matches(a));
3462}
3463
3464// Tests that Property(&Foo::property, ...) works when property()
3465// returns a reference to const.
3466TEST(PropertyTest, WorksForReferenceToConstProperty) {
3467 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
3468
3469 AClass a;
3470 a.set_s("hill");
3471 EXPECT_TRUE(m.Matches(a));
3472
3473 a.set_s("hole");
3474 EXPECT_FALSE(m.Matches(a));
3475}
3476
3477// Tests that Property(&Foo::property, ...) works when property()
3478// returns a reference to non-const.
3479TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
3480 double x = 0.0;
3481 AClass a;
3482
3483 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
3484 EXPECT_FALSE(m.Matches(a));
3485
3486 m = Property(&AClass::x, Not(Ref(x)));
3487 EXPECT_TRUE(m.Matches(a));
3488}
3489
3490// Tests that Property(&Foo::property, ...) works when the argument is
3491// passed by value.
3492TEST(PropertyTest, WorksForByValueArgument) {
3493 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
3494
3495 AClass a;
3496 a.set_s("hill");
3497 EXPECT_TRUE(m.Matches(a));
3498
3499 a.set_s("hole");
3500 EXPECT_FALSE(m.Matches(a));
3501}
3502
3503// Tests that Property(&Foo::property, ...) works when the argument's
3504// type is a sub-type of Foo.
3505TEST(PropertyTest, WorksForArgumentOfSubType) {
3506 // The matcher expects a DerivedClass, but inside the Property() we
3507 // say AClass.
3508 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
3509
3510 DerivedClass d;
3511 d.set_n(1);
3512 EXPECT_TRUE(m.Matches(d));
3513
3514 d.set_n(-1);
3515 EXPECT_FALSE(m.Matches(d));
3516}
3517
3518// Tests that Property(&Foo::property, m) works when property()'s type
3519// and m's argument type are compatible but different.
3520TEST(PropertyTest, WorksForCompatibleMatcherType) {
3521 // n() returns an int but the inner matcher expects a signed char.
3522 Matcher<const AClass&> m = Property(&AClass::n,
3523 Matcher<signed char>(Ge(0)));
3524
3525 AClass a;
3526 EXPECT_TRUE(m.Matches(a));
3527 a.set_n(-1);
3528 EXPECT_FALSE(m.Matches(a));
3529}
3530
3531// Tests that Property() can describe itself.
3532TEST(PropertyTest, CanDescribeSelf) {
3533 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3534
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003535 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3536 EXPECT_EQ("is an object whose given property isn't >= 0",
3537 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003538}
3539
3540// Tests that Property() can explain the match result.
3541TEST(PropertyTest, CanExplainMatchResult) {
3542 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3543
3544 AClass a;
3545 a.set_n(1);
zhanyong.wan736baa82010-09-27 17:44:16 +00003546 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003547
3548 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003549 EXPECT_EQ(
3550 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
3551 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003552}
3553
3554// Tests that Property() works when the argument is a pointer to const.
3555TEST(PropertyForPointerTest, WorksForPointerToConst) {
3556 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3557
3558 AClass a;
3559 a.set_n(1);
3560 EXPECT_TRUE(m.Matches(&a));
3561
3562 a.set_n(-1);
3563 EXPECT_FALSE(m.Matches(&a));
3564}
3565
3566// Tests that Property() works when the argument is a pointer to non-const.
3567TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
3568 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
3569
3570 AClass a;
3571 a.set_s("hill");
3572 EXPECT_TRUE(m.Matches(&a));
3573
3574 a.set_s("hole");
3575 EXPECT_FALSE(m.Matches(&a));
3576}
3577
zhanyong.wan6953a722010-01-13 05:15:07 +00003578// Tests that Property() works when the argument is a reference to a
3579// const pointer.
3580TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
3581 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
3582
3583 AClass a;
3584 a.set_s("hill");
3585 EXPECT_TRUE(m.Matches(&a));
3586
3587 a.set_s("hole");
3588 EXPECT_FALSE(m.Matches(&a));
3589}
3590
shiqiane35fdd92008-12-10 05:08:54 +00003591// Tests that Property() does not match the NULL pointer.
3592TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
3593 Matcher<const AClass*> m = Property(&AClass::x, _);
3594 EXPECT_FALSE(m.Matches(NULL));
3595}
3596
3597// Tests that Property(&Foo::property, ...) works when the argument's
3598// type is a sub-type of const Foo*.
3599TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
3600 // The matcher expects a DerivedClass, but inside the Property() we
3601 // say AClass.
3602 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
3603
3604 DerivedClass d;
3605 d.set_n(1);
3606 EXPECT_TRUE(m.Matches(&d));
3607
3608 d.set_n(-1);
3609 EXPECT_FALSE(m.Matches(&d));
3610}
3611
3612// Tests that Property() can describe itself when used to match a pointer.
3613TEST(PropertyForPointerTest, CanDescribeSelf) {
3614 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3615
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003616 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3617 EXPECT_EQ("is an object whose given property isn't >= 0",
3618 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003619}
3620
3621// Tests that Property() can explain the result of matching a pointer.
3622TEST(PropertyForPointerTest, CanExplainMatchResult) {
3623 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3624
3625 AClass a;
3626 a.set_n(1);
3627 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003628 EXPECT_EQ(
3629 "which points to an object whose given property is 1" + OfType("int"),
3630 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003631
3632 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003633 EXPECT_EQ("which points to an object whose given property is 1" +
3634 OfType("int") + ", which is 1 more than 0",
3635 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003636}
3637
3638// Tests ResultOf.
3639
3640// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3641// function pointer.
3642string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; }
3643
3644TEST(ResultOfTest, WorksForFunctionPointers) {
3645 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo")));
3646
3647 EXPECT_TRUE(matcher.Matches(1));
3648 EXPECT_FALSE(matcher.Matches(2));
3649}
3650
3651// Tests that ResultOf() can describe itself.
3652TEST(ResultOfTest, CanDescribeItself) {
3653 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
3654
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003655 EXPECT_EQ("is mapped by the given callable to a value that "
3656 "is equal to \"foo\"", Describe(matcher));
3657 EXPECT_EQ("is mapped by the given callable to a value that "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003658 "isn't equal to \"foo\"", DescribeNegation(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00003659}
3660
3661// Tests that ResultOf() can explain the match result.
3662int IntFunction(int input) { return input == 42 ? 80 : 90; }
3663
3664TEST(ResultOfTest, CanExplainMatchResult) {
3665 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003666 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003667 Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003668
3669 matcher = ResultOf(&IntFunction, GreaterThan(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003670 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
3671 ", which is 5 more than 85", Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003672}
3673
3674// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3675// returns a non-reference.
3676TEST(ResultOfTest, WorksForNonReferenceResults) {
3677 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
3678
3679 EXPECT_TRUE(matcher.Matches(42));
3680 EXPECT_FALSE(matcher.Matches(36));
3681}
3682
3683// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3684// returns a reference to non-const.
zhanyong.wan736baa82010-09-27 17:44:16 +00003685double& DoubleFunction(double& input) { return input; } // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003686
zhanyong.wan736baa82010-09-27 17:44:16 +00003687Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003688 return obj;
3689}
3690
3691TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
3692 double x = 3.14;
3693 double x2 = x;
3694 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
3695
3696 EXPECT_TRUE(matcher.Matches(x));
3697 EXPECT_FALSE(matcher.Matches(x2));
3698
3699 // Test that ResultOf works with uncopyable objects
3700 Uncopyable obj(0);
3701 Uncopyable obj2(0);
3702 Matcher<Uncopyable&> matcher2 =
3703 ResultOf(&RefUncopyableFunction, Ref(obj));
3704
3705 EXPECT_TRUE(matcher2.Matches(obj));
3706 EXPECT_FALSE(matcher2.Matches(obj2));
3707}
3708
3709// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3710// returns a reference to const.
3711const string& StringFunction(const string& input) { return input; }
3712
3713TEST(ResultOfTest, WorksForReferenceToConstResults) {
3714 string s = "foo";
3715 string s2 = s;
3716 Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s));
3717
3718 EXPECT_TRUE(matcher.Matches(s));
3719 EXPECT_FALSE(matcher.Matches(s2));
3720}
3721
3722// Tests that ResultOf(f, m) works when f(x) and m's
3723// argument types are compatible but different.
3724TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
3725 // IntFunction() returns int but the inner matcher expects a signed char.
3726 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
3727
3728 EXPECT_TRUE(matcher.Matches(36));
3729 EXPECT_FALSE(matcher.Matches(42));
3730}
3731
shiqiane35fdd92008-12-10 05:08:54 +00003732// Tests that the program aborts when ResultOf is passed
3733// a NULL function pointer.
3734TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
zhanyong.wan04d6ed82009-09-11 07:01:08 +00003735 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan736baa82010-09-27 17:44:16 +00003736 ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))),
shiqiane35fdd92008-12-10 05:08:54 +00003737 "NULL function pointer is passed into ResultOf\\(\\)\\.");
3738}
shiqiane35fdd92008-12-10 05:08:54 +00003739
3740// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3741// function reference.
3742TEST(ResultOfTest, WorksForFunctionReferences) {
3743 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
3744 EXPECT_TRUE(matcher.Matches(1));
3745 EXPECT_FALSE(matcher.Matches(2));
3746}
3747
3748// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3749// function object.
3750struct Functor : public ::std::unary_function<int, string> {
3751 result_type operator()(argument_type input) const {
3752 return IntToStringFunction(input);
3753 }
3754};
3755
3756TEST(ResultOfTest, WorksForFunctors) {
3757 Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo")));
3758
3759 EXPECT_TRUE(matcher.Matches(1));
3760 EXPECT_FALSE(matcher.Matches(2));
3761}
3762
3763// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3764// functor with more then one operator() defined. ResultOf() must work
3765// for each defined operator().
3766struct PolymorphicFunctor {
3767 typedef int result_type;
3768 int operator()(int n) { return n; }
3769 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
3770};
3771
3772TEST(ResultOfTest, WorksForPolymorphicFunctors) {
3773 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
3774
3775 EXPECT_TRUE(matcher_int.Matches(10));
3776 EXPECT_FALSE(matcher_int.Matches(2));
3777
3778 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
3779
3780 EXPECT_TRUE(matcher_string.Matches("long string"));
3781 EXPECT_FALSE(matcher_string.Matches("shrt"));
3782}
3783
3784const int* ReferencingFunction(const int& n) { return &n; }
3785
3786struct ReferencingFunctor {
3787 typedef const int* result_type;
3788 result_type operator()(const int& n) { return &n; }
3789};
3790
3791TEST(ResultOfTest, WorksForReferencingCallables) {
3792 const int n = 1;
3793 const int n2 = 1;
3794 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
3795 EXPECT_TRUE(matcher2.Matches(n));
3796 EXPECT_FALSE(matcher2.Matches(n2));
3797
3798 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
3799 EXPECT_TRUE(matcher3.Matches(n));
3800 EXPECT_FALSE(matcher3.Matches(n2));
3801}
3802
shiqiane35fdd92008-12-10 05:08:54 +00003803class DivisibleByImpl {
3804 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003805 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
shiqiane35fdd92008-12-10 05:08:54 +00003806
zhanyong.wandb22c222010-01-28 21:52:29 +00003807 // For testing using ExplainMatchResultTo() with polymorphic matchers.
shiqiane35fdd92008-12-10 05:08:54 +00003808 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00003809 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003810 *listener << "which is " << (n % divider_) << " modulo "
zhanyong.wandb22c222010-01-28 21:52:29 +00003811 << divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003812 return (n % divider_) == 0;
3813 }
3814
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003815 void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003816 *os << "is divisible by " << divider_;
3817 }
3818
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003819 void DescribeNegationTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003820 *os << "is not divisible by " << divider_;
3821 }
3822
zhanyong.wan32de5f52009-12-23 00:13:23 +00003823 void set_divider(int a_divider) { divider_ = a_divider; }
shiqiane35fdd92008-12-10 05:08:54 +00003824 int divider() const { return divider_; }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003825
shiqiane35fdd92008-12-10 05:08:54 +00003826 private:
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003827 int divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003828};
3829
shiqiane35fdd92008-12-10 05:08:54 +00003830PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
3831 return MakePolymorphicMatcher(DivisibleByImpl(n));
3832}
3833
3834// Tests that when AllOf() fails, only the first failing matcher is
3835// asked to explain why.
3836TEST(ExplainMatchResultTest, AllOf_False_False) {
3837 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003838 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00003839}
3840
3841// Tests that when AllOf() fails, only the first failing matcher is
3842// asked to explain why.
3843TEST(ExplainMatchResultTest, AllOf_False_True) {
3844 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003845 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003846}
3847
3848// Tests that when AllOf() fails, only the first failing matcher is
3849// asked to explain why.
3850TEST(ExplainMatchResultTest, AllOf_True_False) {
3851 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003852 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00003853}
3854
3855// Tests that when AllOf() succeeds, all matchers are asked to explain
3856// why.
3857TEST(ExplainMatchResultTest, AllOf_True_True) {
3858 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003859 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003860}
3861
3862TEST(ExplainMatchResultTest, AllOf_True_True_2) {
3863 const Matcher<int> m = AllOf(Ge(2), Le(3));
3864 EXPECT_EQ("", Explain(m, 2));
3865}
3866
3867TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
3868 const Matcher<int> m = GreaterThan(5);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003869 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003870}
3871
3872// The following two tests verify that values without a public copy
3873// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
3874// with the help of ByRef().
3875
3876class NotCopyable {
3877 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003878 explicit NotCopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003879
3880 int value() const { return value_; }
3881
3882 bool operator==(const NotCopyable& rhs) const {
3883 return value() == rhs.value();
3884 }
3885
3886 bool operator>=(const NotCopyable& rhs) const {
3887 return value() >= rhs.value();
3888 }
3889 private:
3890 int value_;
3891
3892 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
3893};
3894
3895TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
3896 const NotCopyable const_value1(1);
3897 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
3898
3899 const NotCopyable n1(1), n2(2);
3900 EXPECT_TRUE(m.Matches(n1));
3901 EXPECT_FALSE(m.Matches(n2));
3902}
3903
3904TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
3905 NotCopyable value2(2);
3906 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
3907
3908 NotCopyable n1(1), n2(2);
3909 EXPECT_FALSE(m.Matches(n1));
3910 EXPECT_TRUE(m.Matches(n2));
3911}
3912
zhanyong.wan320814a2013-03-01 00:20:30 +00003913TEST(IsEmptyTest, ImplementsIsEmpty) {
3914 vector<int> container;
3915 EXPECT_THAT(container, IsEmpty());
3916 container.push_back(0);
3917 EXPECT_THAT(container, Not(IsEmpty()));
3918 container.push_back(1);
3919 EXPECT_THAT(container, Not(IsEmpty()));
3920}
3921
3922TEST(IsEmptyTest, WorksWithString) {
3923 string text;
3924 EXPECT_THAT(text, IsEmpty());
3925 text = "foo";
3926 EXPECT_THAT(text, Not(IsEmpty()));
3927 text = string("\0", 1);
3928 EXPECT_THAT(text, Not(IsEmpty()));
3929}
3930
3931TEST(IsEmptyTest, CanDescribeSelf) {
3932 Matcher<vector<int> > m = IsEmpty();
3933 EXPECT_EQ("is empty", Describe(m));
3934 EXPECT_EQ("isn't empty", DescribeNegation(m));
3935}
3936
3937TEST(IsEmptyTest, ExplainsResult) {
3938 Matcher<vector<int> > m = IsEmpty();
3939 vector<int> container;
3940 EXPECT_EQ("", Explain(m, container));
3941 container.push_back(0);
3942 EXPECT_EQ("whose size is 1", Explain(m, container));
3943}
3944
zhanyong.wana31d9ce2013-03-01 01:50:17 +00003945TEST(SizeIsTest, ImplementsSizeIs) {
3946 vector<int> container;
3947 EXPECT_THAT(container, SizeIs(0));
3948 EXPECT_THAT(container, Not(SizeIs(1)));
3949 container.push_back(0);
3950 EXPECT_THAT(container, Not(SizeIs(0)));
3951 EXPECT_THAT(container, SizeIs(1));
3952 container.push_back(0);
3953 EXPECT_THAT(container, Not(SizeIs(0)));
3954 EXPECT_THAT(container, SizeIs(2));
3955}
3956
3957TEST(SizeIsTest, WorksWithMap) {
3958 map<string, int> container;
3959 EXPECT_THAT(container, SizeIs(0));
3960 EXPECT_THAT(container, Not(SizeIs(1)));
3961 container.insert(make_pair("foo", 1));
3962 EXPECT_THAT(container, Not(SizeIs(0)));
3963 EXPECT_THAT(container, SizeIs(1));
3964 container.insert(make_pair("bar", 2));
3965 EXPECT_THAT(container, Not(SizeIs(0)));
3966 EXPECT_THAT(container, SizeIs(2));
3967}
3968
3969TEST(SizeIsTest, WorksWithReferences) {
3970 vector<int> container;
3971 Matcher<const vector<int>&> m = SizeIs(1);
3972 EXPECT_THAT(container, Not(m));
3973 container.push_back(0);
3974 EXPECT_THAT(container, m);
3975}
3976
3977TEST(SizeIsTest, CanDescribeSelf) {
3978 Matcher<vector<int> > m = SizeIs(2);
3979 EXPECT_EQ("size is equal to 2", Describe(m));
3980 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
3981}
3982
3983TEST(SizeIsTest, ExplainsResult) {
3984 Matcher<vector<int> > m1 = SizeIs(2);
3985 Matcher<vector<int> > m2 = SizeIs(Lt(2u));
3986 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
3987 Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
3988 vector<int> container;
3989 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
3990 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
3991 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
3992 EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
3993 Explain(m4, container));
3994 container.push_back(0);
3995 container.push_back(0);
3996 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
3997 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
3998 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
3999 EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
4000 Explain(m4, container));
4001}
4002
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004003#if GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004004// Tests ContainerEq with different container types, and
4005// different element types.
4006
4007template <typename T>
zhanyong.wanb8243162009-06-04 05:48:20 +00004008class ContainerEqTest : public testing::Test {};
zhanyong.wan6a896b52009-01-16 01:13:50 +00004009
4010typedef testing::Types<
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004011 set<int>,
4012 vector<size_t>,
4013 multiset<size_t>,
4014 list<int> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004015 ContainerEqTestTypes;
4016
4017TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
4018
4019// Tests that the filled container is equal to itself.
4020TYPED_TEST(ContainerEqTest, EqualsSelf) {
4021 static const int vals[] = {1, 1, 2, 3, 5, 8};
4022 TypeParam my_set(vals, vals + 6);
4023 const Matcher<TypeParam> m = ContainerEq(my_set);
4024 EXPECT_TRUE(m.Matches(my_set));
4025 EXPECT_EQ("", Explain(m, my_set));
4026}
4027
4028// Tests that missing values are reported.
4029TYPED_TEST(ContainerEqTest, ValueMissing) {
4030 static const int vals[] = {1, 1, 2, 3, 5, 8};
4031 static const int test_vals[] = {2, 1, 8, 5};
4032 TypeParam my_set(vals, vals + 6);
4033 TypeParam test_set(test_vals, test_vals + 4);
4034 const Matcher<TypeParam> m = ContainerEq(my_set);
4035 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004036 EXPECT_EQ("which doesn't have these expected elements: 3",
4037 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004038}
4039
4040// Tests that added values are reported.
4041TYPED_TEST(ContainerEqTest, ValueAdded) {
4042 static const int vals[] = {1, 1, 2, 3, 5, 8};
4043 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4044 TypeParam my_set(vals, vals + 6);
4045 TypeParam test_set(test_vals, test_vals + 6);
4046 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4047 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004048 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004049}
4050
4051// Tests that added and missing values are reported together.
4052TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4053 static const int vals[] = {1, 1, 2, 3, 5, 8};
4054 static const int test_vals[] = {1, 2, 3, 8, 46};
4055 TypeParam my_set(vals, vals + 6);
4056 TypeParam test_set(test_vals, test_vals + 5);
4057 const Matcher<TypeParam> m = ContainerEq(my_set);
4058 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004059 EXPECT_EQ("which has these unexpected elements: 46,\n"
4060 "and doesn't have these expected elements: 5",
4061 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004062}
4063
4064// Tests duplicated value -- expect no explanation.
4065TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4066 static const int vals[] = {1, 1, 2, 3, 5, 8};
4067 static const int test_vals[] = {1, 2, 3, 5, 8};
4068 TypeParam my_set(vals, vals + 6);
4069 TypeParam test_set(test_vals, test_vals + 5);
4070 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4071 // Depending on the container, match may be true or false
4072 // But in any case there should be no explanation.
4073 EXPECT_EQ("", Explain(m, test_set));
4074}
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004075#endif // GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004076
4077// Tests that mutliple missing values are reported.
4078// Using just vector here, so order is predicatble.
4079TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4080 static const int vals[] = {1, 1, 2, 3, 5, 8};
4081 static const int test_vals[] = {2, 1, 5};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004082 vector<int> my_set(vals, vals + 6);
4083 vector<int> test_set(test_vals, test_vals + 3);
4084 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004085 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004086 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4087 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004088}
4089
4090// Tests that added values are reported.
4091// Using just vector here, so order is predicatble.
4092TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4093 static const int vals[] = {1, 1, 2, 3, 5, 8};
4094 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004095 list<size_t> my_set(vals, vals + 6);
4096 list<size_t> test_set(test_vals, test_vals + 7);
4097 const Matcher<const list<size_t>&> m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004098 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004099 EXPECT_EQ("which has these unexpected elements: 92, 46",
4100 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004101}
4102
4103// Tests that added and missing values are reported together.
4104TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
4105 static const int vals[] = {1, 1, 2, 3, 5, 8};
4106 static const int test_vals[] = {1, 2, 3, 92, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004107 list<size_t> my_set(vals, vals + 6);
4108 list<size_t> test_set(test_vals, test_vals + 5);
4109 const Matcher<const list<size_t> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004110 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004111 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4112 "and doesn't have these expected elements: 5, 8",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004113 Explain(m, test_set));
4114}
4115
4116// Tests to see that duplicate elements are detected,
4117// but (as above) not reported in the explanation.
4118TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
4119 static const int vals[] = {1, 1, 2, 3, 5, 8};
4120 static const int test_vals[] = {1, 2, 3, 5, 8};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004121 vector<int> my_set(vals, vals + 6);
4122 vector<int> test_set(test_vals, test_vals + 5);
4123 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004124 EXPECT_TRUE(m.Matches(my_set));
4125 EXPECT_FALSE(m.Matches(test_set));
4126 // There is nothing to report when both sets contain all the same values.
4127 EXPECT_EQ("", Explain(m, test_set));
4128}
4129
4130// Tests that ContainerEq works for non-trivial associative containers,
4131// like maps.
4132TEST(ContainerEqExtraTest, WorksForMaps) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004133 map<int, std::string> my_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004134 my_map[0] = "a";
4135 my_map[1] = "b";
4136
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004137 map<int, std::string> test_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004138 test_map[0] = "aa";
4139 test_map[1] = "b";
4140
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004141 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004142 EXPECT_TRUE(m.Matches(my_map));
4143 EXPECT_FALSE(m.Matches(test_map));
4144
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004145 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
4146 "and doesn't have these expected elements: (0, \"a\")",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004147 Explain(m, test_map));
4148}
4149
zhanyong.wanb8243162009-06-04 05:48:20 +00004150TEST(ContainerEqExtraTest, WorksForNativeArray) {
4151 int a1[] = { 1, 2, 3 };
4152 int a2[] = { 1, 2, 3 };
4153 int b[] = { 1, 2, 4 };
4154
4155 EXPECT_THAT(a1, ContainerEq(a2));
4156 EXPECT_THAT(a1, Not(ContainerEq(b)));
4157}
4158
4159TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
4160 const char a1[][3] = { "hi", "lo" };
4161 const char a2[][3] = { "hi", "lo" };
4162 const char b[][3] = { "lo", "hi" };
4163
4164 // Tests using ContainerEq() in the first dimension.
4165 EXPECT_THAT(a1, ContainerEq(a2));
4166 EXPECT_THAT(a1, Not(ContainerEq(b)));
4167
4168 // Tests using ContainerEq() in the second dimension.
4169 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
4170 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
4171}
4172
4173TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
4174 const int a1[] = { 1, 2, 3 };
4175 const int a2[] = { 1, 2, 3 };
4176 const int b[] = { 1, 2, 3, 4 };
4177
zhanyong.wan2661c682009-06-09 05:42:12 +00004178 const int* const p1 = a1;
4179 EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
4180 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004181
4182 const int c[] = { 1, 3, 2 };
zhanyong.wan2661c682009-06-09 05:42:12 +00004183 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004184}
4185
4186TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
4187 std::string a1[][3] = {
4188 { "hi", "hello", "ciao" },
4189 { "bye", "see you", "ciao" }
4190 };
4191
4192 std::string a2[][3] = {
4193 { "hi", "hello", "ciao" },
4194 { "bye", "see you", "ciao" }
4195 };
4196
4197 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
4198 EXPECT_THAT(a1, m);
4199
4200 a2[0][0] = "ha";
4201 EXPECT_THAT(a1, m);
4202}
4203
zhanyong.wan898725c2011-09-16 16:45:39 +00004204TEST(WhenSortedByTest, WorksForEmptyContainer) {
4205 const vector<int> numbers;
4206 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
4207 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
4208}
4209
4210TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
4211 vector<unsigned> numbers;
4212 numbers.push_back(3);
4213 numbers.push_back(1);
4214 numbers.push_back(2);
4215 numbers.push_back(2);
4216 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
4217 ElementsAre(3, 2, 2, 1)));
4218 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
4219 ElementsAre(1, 2, 2, 3))));
4220}
4221
4222TEST(WhenSortedByTest, WorksForNonVectorContainer) {
4223 list<string> words;
4224 words.push_back("say");
4225 words.push_back("hello");
4226 words.push_back("world");
4227 EXPECT_THAT(words, WhenSortedBy(less<string>(),
4228 ElementsAre("hello", "say", "world")));
4229 EXPECT_THAT(words, Not(WhenSortedBy(less<string>(),
4230 ElementsAre("say", "hello", "world"))));
4231}
4232
4233TEST(WhenSortedByTest, WorksForNativeArray) {
4234 const int numbers[] = { 1, 3, 2, 4 };
4235 const int sorted_numbers[] = { 1, 2, 3, 4 };
4236 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
4237 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
4238 ElementsAreArray(sorted_numbers)));
4239 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
4240}
4241
4242TEST(WhenSortedByTest, CanDescribeSelf) {
4243 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
4244 EXPECT_EQ("(when sorted) has 2 elements where\n"
4245 "element #0 is equal to 1,\n"
4246 "element #1 is equal to 2",
4247 Describe(m));
4248 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
4249 "element #0 isn't equal to 1, or\n"
4250 "element #1 isn't equal to 2",
4251 DescribeNegation(m));
4252}
4253
4254TEST(WhenSortedByTest, ExplainsMatchResult) {
4255 const int a[] = { 2, 1 };
4256 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
4257 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
4258 EXPECT_EQ("which is { 1, 2 } when sorted",
4259 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
4260}
4261
4262// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
4263// need to test it as exhaustively as we test the latter.
4264
4265TEST(WhenSortedTest, WorksForEmptyContainer) {
4266 const vector<int> numbers;
4267 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
4268 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
4269}
4270
4271TEST(WhenSortedTest, WorksForNonEmptyContainer) {
4272 list<string> words;
4273 words.push_back("3");
4274 words.push_back("1");
4275 words.push_back("2");
4276 words.push_back("2");
4277 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
4278 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
4279}
4280
zhanyong.wana9a59e02013-03-27 16:14:55 +00004281TEST(WhenSortedTest, WorksForMapTypes) {
4282 map<string, int> word_counts;
4283 word_counts["and"] = 1;
4284 word_counts["the"] = 1;
4285 word_counts["buffalo"] = 2;
4286 EXPECT_THAT(word_counts, WhenSorted(ElementsAre(
4287 Pair("and", 1), Pair("buffalo", 2), Pair("the", 1))));
4288 EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre(
4289 Pair("and", 1), Pair("the", 1), Pair("buffalo", 2)))));
4290}
4291
4292TEST(WhenSortedTest, WorksForMultiMapTypes) {
4293 multimap<int, int> ifib;
4294 ifib.insert(make_pair(8, 6));
4295 ifib.insert(make_pair(2, 3));
4296 ifib.insert(make_pair(1, 1));
4297 ifib.insert(make_pair(3, 4));
4298 ifib.insert(make_pair(1, 2));
4299 ifib.insert(make_pair(5, 5));
4300 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
4301 Pair(1, 2),
4302 Pair(2, 3),
4303 Pair(3, 4),
4304 Pair(5, 5),
4305 Pair(8, 6))));
4306 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
4307 Pair(2, 3),
4308 Pair(1, 1),
4309 Pair(3, 4),
4310 Pair(1, 2),
4311 Pair(5, 5)))));
4312}
4313
4314TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
4315 std::deque<int> d;
4316 d.push_back(2);
4317 d.push_back(1);
4318 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
4319 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
4320}
4321
4322TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
4323 std::deque<int> d;
4324 d.push_back(2);
4325 d.push_back(1);
4326 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
4327 EXPECT_THAT(d, WhenSorted(vector_match));
4328 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
4329 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
4330}
4331
4332// Deliberately bare pseudo-container.
4333// Offers only begin() and end() accessors, yielding InputIterator.
4334template <typename T>
4335class Streamlike {
4336 private:
4337 class ConstIter;
4338 public:
4339 typedef ConstIter const_iterator;
4340 typedef T value_type;
4341
4342 template <typename InIter>
4343 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
4344
4345 const_iterator begin() const {
4346 return const_iterator(this, remainder_.begin());
4347 }
4348 const_iterator end() const {
4349 return const_iterator(this, remainder_.end());
4350 }
4351
4352 private:
4353 class ConstIter : public std::iterator<std::input_iterator_tag,
4354 value_type,
4355 ptrdiff_t,
4356 const value_type&,
4357 const value_type*> {
4358 public:
4359 ConstIter(const Streamlike* s,
4360 typename std::list<value_type>::iterator pos)
4361 : s_(s), pos_(pos) {}
4362
4363 const value_type& operator*() const { return *pos_; }
4364 const value_type* operator->() const { return &*pos_; }
4365 ConstIter& operator++() {
4366 s_->remainder_.erase(pos_++);
4367 return *this;
4368 }
4369
4370 // *iter++ is required to work (see std::istreambuf_iterator).
4371 // (void)iter++ is also required to work.
4372 class PostIncrProxy {
4373 public:
4374 explicit PostIncrProxy(const value_type& value) : value_(value) {}
4375 value_type operator*() const { return value_; }
4376 private:
4377 value_type value_;
4378 };
4379 PostIncrProxy operator++(int) {
4380 PostIncrProxy proxy(**this);
4381 ++(*this);
4382 return proxy;
4383 }
4384
4385 friend bool operator==(const ConstIter& a, const ConstIter& b) {
4386 return a.s_ == b.s_ && a.pos_ == b.pos_;
4387 }
4388 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
4389 return !(a == b);
4390 }
4391
4392 private:
4393 const Streamlike* s_;
4394 typename std::list<value_type>::iterator pos_;
4395 };
4396
4397 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
4398 os << "[";
4399 typedef typename std::list<value_type>::const_iterator Iter;
4400 const char* sep = "";
4401 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
4402 os << sep << *it;
4403 sep = ",";
4404 }
4405 os << "]";
4406 return os;
4407 }
4408
4409 mutable std::list<value_type> remainder_; // modified by iteration
4410};
4411
4412TEST(StreamlikeTest, Iteration) {
4413 const int a[5] = { 2, 1, 4, 5, 3 };
4414 Streamlike<int> s(a, a + 5);
4415 Streamlike<int>::const_iterator it = s.begin();
4416 const int* ip = a;
4417 while (it != s.end()) {
4418 SCOPED_TRACE(ip - a);
4419 EXPECT_EQ(*ip++, *it++);
4420 }
4421}
4422
4423TEST(WhenSortedTest, WorksForStreamlike) {
4424 // Streamlike 'container' provides only minimal iterator support.
4425 // Its iterators are tagged with input_iterator_tag.
4426 const int a[5] = { 2, 1, 4, 5, 3 };
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004427 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004428 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
4429 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4430}
4431
4432TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00004433 const int a[] = { 2, 1, 4, 5, 3 };
4434 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004435 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
4436 EXPECT_THAT(s, WhenSorted(vector_match));
4437 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4438}
4439
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004440// Tests using ElementsAre() and ElementsAreArray() with stream-like
4441// "containers".
4442
4443TEST(ElemensAreStreamTest, WorksForStreamlike) {
4444 const int a[5] = { 1, 2, 3, 4, 5 };
4445 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4446 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
4447 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
4448}
4449
4450TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
4451 const int a[5] = { 1, 2, 3, 4, 5 };
4452 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4453
4454 vector<int> expected;
4455 expected.push_back(1);
4456 expected.push_back(2);
4457 expected.push_back(3);
4458 expected.push_back(4);
4459 expected.push_back(5);
4460 EXPECT_THAT(s, ElementsAreArray(expected));
4461
4462 expected[3] = 0;
4463 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
4464}
4465
zhanyong.wanfb25d532013-07-28 08:24:00 +00004466// Tests for UnorderedElementsAreArray()
4467
4468TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
4469 const int a[] = { 0, 1, 2, 3, 4 };
4470 std::vector<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4471 do {
4472 StringMatchResultListener listener;
4473 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
4474 s, &listener)) << listener.str();
4475 } while (std::next_permutation(s.begin(), s.end()));
4476}
4477
4478TEST(UnorderedElementsAreArrayTest, VectorBool) {
4479 const bool a[] = { 0, 1, 0, 1, 1 };
4480 const bool b[] = { 1, 0, 1, 1, 0 };
4481 std::vector<bool> expected(a, a + GMOCK_ARRAY_SIZE_(a));
4482 std::vector<bool> actual(b, b + GMOCK_ARRAY_SIZE_(b));
4483 StringMatchResultListener listener;
4484 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
4485 actual, &listener)) << listener.str();
4486}
4487
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004488TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
4489 // Streamlike 'container' provides only minimal iterator support.
4490 // Its iterators are tagged with input_iterator_tag, and it has no
4491 // size() or empty() methods.
4492 const int a[5] = { 2, 1, 4, 5, 3 };
4493 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4494
4495 ::std::vector<int> expected;
4496 expected.push_back(1);
4497 expected.push_back(2);
4498 expected.push_back(3);
4499 expected.push_back(4);
4500 expected.push_back(5);
4501 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
4502
4503 expected.push_back(6);
4504 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
4505}
4506
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004507#if GTEST_LANG_CXX11
4508
4509TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
4510 const int a[5] = { 2, 1, 4, 5, 3 };
4511 EXPECT_THAT(a, UnorderedElementsAreArray({ 1, 2, 3, 4, 5 }));
4512 EXPECT_THAT(a, Not(UnorderedElementsAreArray({ 1, 2, 3, 4, 6 })));
4513}
4514
4515TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
4516 const string a[5] = { "a", "b", "c", "d", "e" };
4517 EXPECT_THAT(a, UnorderedElementsAreArray({ "a", "b", "c", "d", "e" }));
4518 EXPECT_THAT(a, Not(UnorderedElementsAreArray({ "a", "b", "c", "d", "ef" })));
4519}
4520
4521TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
4522 const int a[5] = { 2, 1, 4, 5, 3 };
4523 EXPECT_THAT(a, UnorderedElementsAreArray(
4524 { Eq(1), Eq(2), Eq(3), Eq(4), Eq(5) }));
4525 EXPECT_THAT(a, Not(UnorderedElementsAreArray(
4526 { Eq(1), Eq(2), Eq(3), Eq(4), Eq(6) })));
4527}
4528
4529TEST(UnorderedElementsAreArrayTest,
4530 TakesInitializerListOfDifferentTypedMatchers) {
4531 const int a[5] = { 2, 1, 4, 5, 3 };
4532 // The compiler cannot infer the type of the initializer list if its
4533 // elements have different types. We must explicitly specify the
4534 // unified element type in this case.
4535 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
4536 { Eq(1), Ne(-2), Ge(3), Le(4), Eq(5) }));
4537 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
4538 { Eq(1), Ne(-2), Ge(3), Le(4), Eq(6) })));
4539}
4540
4541#endif // GTEST_LANG_CXX11
4542
zhanyong.wanfb25d532013-07-28 08:24:00 +00004543class UnorderedElementsAreTest : public testing::Test {
4544 protected:
4545 typedef std::vector<int> IntVec;
4546};
4547
4548TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
4549 const int a[] = { 1, 2, 3 };
4550 std::vector<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4551 do {
4552 StringMatchResultListener listener;
4553 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4554 s, &listener)) << listener.str();
4555 } while (std::next_permutation(s.begin(), s.end()));
4556}
4557
4558TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
4559 const int a[] = { 1, 2, 3 };
4560 std::vector<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4561 std::vector<Matcher<int> > mv;
4562 mv.push_back(1);
4563 mv.push_back(2);
4564 mv.push_back(2);
4565 // The element with value '3' matches nothing: fail fast.
4566 StringMatchResultListener listener;
4567 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4568 s, &listener)) << listener.str();
4569}
4570
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004571TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
4572 // Streamlike 'container' provides only minimal iterator support.
4573 // Its iterators are tagged with input_iterator_tag, and it has no
4574 // size() or empty() methods.
4575 const int a[5] = { 2, 1, 4, 5, 3 };
4576 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4577
4578 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
4579 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
4580}
4581
zhanyong.wanfb25d532013-07-28 08:24:00 +00004582// One naive implementation of the matcher runs in O(N!) time, which is too
4583// slow for many real-world inputs. This test shows that our matcher can match
4584// 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
4585// iterations and obviously effectively incomputable.
4586// [ RUN ] UnorderedElementsAreTest.Performance
4587// [ OK ] UnorderedElementsAreTest.Performance (4 ms)
4588TEST_F(UnorderedElementsAreTest, Performance) {
4589 std::vector<int> s;
4590 std::vector<Matcher<int> > mv;
4591 for (int i = 0; i < 100; ++i) {
4592 s.push_back(i);
4593 mv.push_back(_);
4594 }
4595 mv[50] = Eq(0);
4596 StringMatchResultListener listener;
4597 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4598 s, &listener)) << listener.str();
4599}
4600
4601// Another variant of 'Performance' with similar expectations.
4602// [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
4603// [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
4604TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
4605 std::vector<int> s;
4606 std::vector<Matcher<int> > mv;
4607 for (int i = 0; i < 100; ++i) {
4608 s.push_back(i);
4609 if (i & 1) {
4610 mv.push_back(_);
4611 } else {
4612 mv.push_back(i);
4613 }
4614 }
4615 StringMatchResultListener listener;
4616 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4617 s, &listener)) << listener.str();
4618}
4619
4620TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
4621 std::vector<int> v;
4622 v.push_back(4);
4623 StringMatchResultListener listener;
4624 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4625 v, &listener)) << listener.str();
4626 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
4627}
4628
4629TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
4630 std::vector<int> v;
4631 StringMatchResultListener listener;
4632 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4633 v, &listener)) << listener.str();
4634 EXPECT_THAT(listener.str(), Eq(""));
4635}
4636
4637TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
4638 std::vector<int> v;
4639 v.push_back(1);
4640 v.push_back(1);
4641 StringMatchResultListener listener;
4642 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4643 v, &listener)) << listener.str();
4644 EXPECT_THAT(
4645 listener.str(),
4646 Eq("where the following matchers don't match any elements:\n"
4647 "matcher #1: is equal to 2"));
4648}
4649
4650TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
4651 std::vector<int> v;
4652 v.push_back(1);
4653 v.push_back(2);
4654 StringMatchResultListener listener;
4655 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
4656 v, &listener)) << listener.str();
4657 EXPECT_THAT(
4658 listener.str(),
4659 Eq("where the following elements don't match any matchers:\n"
4660 "element #1: 2"));
4661}
4662
4663TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
4664 std::vector<int> v;
4665 v.push_back(2);
4666 v.push_back(3);
4667 StringMatchResultListener listener;
4668 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4669 v, &listener)) << listener.str();
4670 EXPECT_THAT(
4671 listener.str(),
4672 Eq("where"
4673 " the following matchers don't match any elements:\n"
4674 "matcher #0: is equal to 1\n"
4675 "and"
4676 " where"
4677 " the following elements don't match any matchers:\n"
4678 "element #1: 3"));
4679}
4680
4681// Test helper for formatting element, matcher index pairs in expectations.
4682static string EMString(int element, int matcher) {
4683 stringstream ss;
4684 ss << "(element #" << element << ", matcher #" << matcher << ")";
4685 return ss.str();
4686}
4687
4688TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
4689 // A situation where all elements and matchers have a match
4690 // associated with them, but the max matching is not perfect.
4691 std::vector<string> v;
4692 v.push_back("a");
4693 v.push_back("b");
4694 v.push_back("c");
4695 StringMatchResultListener listener;
4696 EXPECT_FALSE(ExplainMatchResult(
4697 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
4698 << listener.str();
4699
4700 string prefix =
4701 "where no permutation of the elements can satisfy all matchers, "
4702 "and the closest match is 2 of 3 matchers with the "
4703 "pairings:\n";
4704
4705 // We have to be a bit loose here, because there are 4 valid max matches.
4706 EXPECT_THAT(
4707 listener.str(),
4708 AnyOf(prefix + "{\n " + EMString(0, 0) +
4709 ",\n " + EMString(1, 2) + "\n}",
4710 prefix + "{\n " + EMString(0, 1) +
4711 ",\n " + EMString(1, 2) + "\n}",
4712 prefix + "{\n " + EMString(0, 0) +
4713 ",\n " + EMString(2, 2) + "\n}",
4714 prefix + "{\n " + EMString(0, 1) +
4715 ",\n " + EMString(2, 2) + "\n}"));
4716}
4717
4718TEST_F(UnorderedElementsAreTest, Describe) {
4719 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
4720 Eq("is empty"));
4721 EXPECT_THAT(
4722 Describe<IntVec>(UnorderedElementsAre(345)),
4723 Eq("has 1 element and that element is equal to 345"));
4724 EXPECT_THAT(
4725 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
4726 Eq("has 3 elements and there exists some permutation "
4727 "of elements such that:\n"
4728 " - element #0 is equal to 111, and\n"
4729 " - element #1 is equal to 222, and\n"
4730 " - element #2 is equal to 333"));
4731}
4732
4733TEST_F(UnorderedElementsAreTest, DescribeNegation) {
4734 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
4735 Eq("isn't empty"));
4736 EXPECT_THAT(
4737 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
4738 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
4739 EXPECT_THAT(
4740 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
4741 Eq("doesn't have 3 elements, or there exists no permutation "
4742 "of elements such that:\n"
4743 " - element #0 is equal to 123, and\n"
4744 " - element #1 is equal to 234, and\n"
4745 " - element #2 is equal to 345"));
4746}
4747
4748namespace {
4749
4750// Used as a check on the more complex max flow method used in the
4751// real testing::internal::FindMaxBipartiteMatching. This method is
4752// compatible but runs in worst-case factorial time, so we only
4753// use it in testing for small problem sizes.
4754template <typename Graph>
4755class BacktrackingMaxBPMState {
4756 public:
4757 // Does not take ownership of 'g'.
4758 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
4759
4760 ElementMatcherPairs Compute() {
4761 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
4762 return best_so_far_;
4763 }
4764 lhs_used_.assign(graph_->LhsSize(), kUnused);
4765 rhs_used_.assign(graph_->RhsSize(), kUnused);
4766 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
4767 matches_.clear();
4768 RecurseInto(irhs);
4769 if (best_so_far_.size() == graph_->RhsSize())
4770 break;
4771 }
4772 return best_so_far_;
4773 }
4774
4775 private:
4776 static const size_t kUnused = static_cast<size_t>(-1);
4777
4778 void PushMatch(size_t lhs, size_t rhs) {
4779 matches_.push_back(ElementMatcherPair(lhs, rhs));
4780 lhs_used_[lhs] = rhs;
4781 rhs_used_[rhs] = lhs;
4782 if (matches_.size() > best_so_far_.size()) {
4783 best_so_far_ = matches_;
4784 }
4785 }
4786
4787 void PopMatch() {
4788 const ElementMatcherPair& back = matches_.back();
4789 lhs_used_[back.first] = kUnused;
4790 rhs_used_[back.second] = kUnused;
4791 matches_.pop_back();
4792 }
4793
4794 bool RecurseInto(size_t irhs) {
4795 if (rhs_used_[irhs] != kUnused) {
4796 return true;
4797 }
4798 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
4799 if (lhs_used_[ilhs] != kUnused) {
4800 continue;
4801 }
4802 if (!graph_->HasEdge(ilhs, irhs)) {
4803 continue;
4804 }
4805 PushMatch(ilhs, irhs);
4806 if (best_so_far_.size() == graph_->RhsSize()) {
4807 return false;
4808 }
4809 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
4810 if (!RecurseInto(mi)) return false;
4811 }
4812 PopMatch();
4813 }
4814 return true;
4815 }
4816
4817 const Graph* graph_; // not owned
4818 std::vector<size_t> lhs_used_;
4819 std::vector<size_t> rhs_used_;
4820 ElementMatcherPairs matches_;
4821 ElementMatcherPairs best_so_far_;
4822};
4823
4824template <typename Graph>
4825const size_t BacktrackingMaxBPMState<Graph>::kUnused;
4826
4827} // namespace
4828
4829// Implement a simple backtracking algorithm to determine if it is possible
4830// to find one element per matcher, without reusing elements.
4831template <typename Graph>
4832ElementMatcherPairs
4833FindBacktrackingMaxBPM(const Graph& g) {
4834 return BacktrackingMaxBPMState<Graph>(&g).Compute();
4835}
4836
4837class BacktrackingBPMTest : public ::testing::Test { };
4838
4839// Tests the MaxBipartiteMatching algorithm with square matrices.
4840// The single int param is the # of nodes on each of the left and right sides.
4841class BipartiteTest : public ::testing::TestWithParam<int> { };
4842
4843// Verify all match graphs up to some moderate number of edges.
4844TEST_P(BipartiteTest, Exhaustive) {
4845 int nodes = GetParam();
4846 MatchMatrix graph(nodes, nodes);
4847 do {
4848 ElementMatcherPairs matches =
4849 internal::FindMaxBipartiteMatching(graph);
4850 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
4851 << "graph: " << graph.DebugString();
4852 // Check that all elements of matches are in the graph.
4853 // Check that elements of first and second are unique.
4854 std::vector<bool> seen_element(graph.LhsSize());
4855 std::vector<bool> seen_matcher(graph.RhsSize());
4856 SCOPED_TRACE(PrintToString(matches));
4857 for (size_t i = 0; i < matches.size(); ++i) {
4858 size_t ilhs = matches[i].first;
4859 size_t irhs = matches[i].second;
4860 EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
4861 EXPECT_FALSE(seen_element[ilhs]);
4862 EXPECT_FALSE(seen_matcher[irhs]);
4863 seen_element[ilhs] = true;
4864 seen_matcher[irhs] = true;
4865 }
4866 } while (graph.NextGraph());
4867}
4868
4869INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest,
4870 ::testing::Range(0, 5));
4871
4872// Parameterized by a pair interpreted as (LhsSize, RhsSize).
4873class BipartiteNonSquareTest
4874 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
4875};
4876
4877TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
4878 // .......
4879 // 0:-----\ :
4880 // 1:---\ | :
4881 // 2:---\ | :
4882 // 3:-\ | | :
4883 // :.......:
4884 // 0 1 2
4885 MatchMatrix g(4, 3);
4886 static const int kEdges[][2] = { {0, 2}, {1, 1}, {2, 1}, {3, 0} };
4887 for (size_t i = 0; i < GMOCK_ARRAY_SIZE_(kEdges); ++i) {
4888 g.SetEdge(kEdges[i][0], kEdges[i][1], true);
4889 }
4890 EXPECT_THAT(FindBacktrackingMaxBPM(g),
4891 ElementsAre(Pair(3, 0),
4892 Pair(AnyOf(1, 2), 1),
4893 Pair(0, 2))) << g.DebugString();
4894}
4895
4896// Verify a few nonsquare matrices.
4897TEST_P(BipartiteNonSquareTest, Exhaustive) {
4898 size_t nlhs = GetParam().first;
4899 size_t nrhs = GetParam().second;
4900 MatchMatrix graph(nlhs, nrhs);
4901 do {
4902 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
4903 internal::FindMaxBipartiteMatching(graph).size())
4904 << "graph: " << graph.DebugString()
4905 << "\nbacktracking: "
4906 << PrintToString(FindBacktrackingMaxBPM(graph))
4907 << "\nmax flow: "
4908 << PrintToString(internal::FindMaxBipartiteMatching(graph));
4909 } while (graph.NextGraph());
4910}
4911
4912INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest,
4913 testing::Values(
4914 std::make_pair(1, 2),
4915 std::make_pair(2, 1),
4916 std::make_pair(3, 2),
4917 std::make_pair(2, 3),
4918 std::make_pair(4, 1),
4919 std::make_pair(1, 4),
4920 std::make_pair(4, 3),
4921 std::make_pair(3, 4)));
4922
4923class BipartiteRandomTest
4924 : public ::testing::TestWithParam<std::pair<int, int> > {
4925};
4926
4927// Verifies a large sample of larger graphs.
4928TEST_P(BipartiteRandomTest, LargerNets) {
4929 int nodes = GetParam().first;
4930 int iters = GetParam().second;
4931 MatchMatrix graph(nodes, nodes);
4932
4933 testing::internal::Int32 seed = GTEST_FLAG(random_seed);
4934 if (seed == 0) {
4935 seed = static_cast<testing::internal::Int32>(time(NULL));
4936 }
4937
4938 for (; iters > 0; --iters, ++seed) {
4939 srand(static_cast<int>(seed));
4940 graph.Randomize();
4941 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
4942 internal::FindMaxBipartiteMatching(graph).size())
4943 << " graph: " << graph.DebugString()
4944 << "\nTo reproduce the failure, rerun the test with the flag"
4945 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
4946 }
4947}
4948
4949// Test argument is a std::pair<int, int> representing (nodes, iters).
4950INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest,
4951 testing::Values(
4952 std::make_pair(5, 10000),
4953 std::make_pair(6, 5000),
4954 std::make_pair(7, 2000),
4955 std::make_pair(8, 500),
4956 std::make_pair(9, 100)));
4957
zhanyong.wan736baa82010-09-27 17:44:16 +00004958// Tests IsReadableTypeName().
4959
4960TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
4961 EXPECT_TRUE(IsReadableTypeName("int"));
4962 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
4963 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
4964 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
4965}
4966
4967TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
4968 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
4969 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
4970 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
4971}
4972
4973TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
4974 EXPECT_FALSE(
4975 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
4976 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
4977}
4978
4979TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
4980 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
4981}
4982
zhanyong.wan4a5330d2009-02-19 00:36:44 +00004983// Tests JoinAsTuple().
4984
4985TEST(JoinAsTupleTest, JoinsEmptyTuple) {
4986 EXPECT_EQ("", JoinAsTuple(Strings()));
4987}
4988
4989TEST(JoinAsTupleTest, JoinsOneTuple) {
4990 const char* fields[] = { "1" };
4991 EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
4992}
4993
4994TEST(JoinAsTupleTest, JoinsTwoTuple) {
4995 const char* fields[] = { "1", "a" };
4996 EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
4997}
4998
4999TEST(JoinAsTupleTest, JoinsTenTuple) {
5000 const char* fields[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
5001 EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
5002 JoinAsTuple(Strings(fields, fields + 10)));
5003}
5004
5005// Tests FormatMatcherDescription().
5006
5007TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
5008 EXPECT_EQ("is even",
zhanyong.wanb4140802010-06-08 22:53:57 +00005009 FormatMatcherDescription(false, "IsEven", Strings()));
5010 EXPECT_EQ("not (is even)",
5011 FormatMatcherDescription(true, "IsEven", Strings()));
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005012
5013 const char* params[] = { "5" };
5014 EXPECT_EQ("equals 5",
zhanyong.wanb4140802010-06-08 22:53:57 +00005015 FormatMatcherDescription(false, "Equals",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005016 Strings(params, params + 1)));
5017
5018 const char* params2[] = { "5", "8" };
5019 EXPECT_EQ("is in range (5, 8)",
zhanyong.wanb4140802010-06-08 22:53:57 +00005020 FormatMatcherDescription(false, "IsInRange",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005021 Strings(params2, params2 + 2)));
5022}
5023
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00005024// Tests PolymorphicMatcher::mutable_impl().
5025TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
5026 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5027 DivisibleByImpl& impl = m.mutable_impl();
5028 EXPECT_EQ(42, impl.divider());
5029
5030 impl.set_divider(0);
5031 EXPECT_EQ(0, m.mutable_impl().divider());
5032}
5033
5034// Tests PolymorphicMatcher::impl().
5035TEST(PolymorphicMatcherTest, CanAccessImpl) {
5036 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5037 const DivisibleByImpl& impl = m.impl();
5038 EXPECT_EQ(42, impl.divider());
5039}
5040
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005041TEST(MatcherTupleTest, ExplainsMatchFailure) {
5042 stringstream ss1;
5043 ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
5044 make_tuple('a', 10), &ss1);
5045 EXPECT_EQ("", ss1.str()); // Successful match.
5046
5047 stringstream ss2;
5048 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5049 make_tuple(2, 'b'), &ss2);
5050 EXPECT_EQ(" Expected arg #0: is > 5\n"
5051 " Actual: 2, which is 3 less than 5\n"
zhanyong.wand60c5f42010-07-21 22:21:07 +00005052 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
5053 " Actual: 'b' (98, 0x62)\n",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005054 ss2.str()); // Failed match where both arguments need explanation.
5055
5056 stringstream ss3;
5057 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5058 make_tuple(2, 'a'), &ss3);
5059 EXPECT_EQ(" Expected arg #0: is > 5\n"
5060 " Actual: 2, which is 3 less than 5\n",
5061 ss3.str()); // Failed match where only one argument needs
5062 // explanation.
5063}
5064
zhanyong.wan33605ba2010-04-22 23:37:47 +00005065// Tests Each().
5066
5067TEST(EachTest, ExplainsMatchResultCorrectly) {
5068 set<int> a; // empty
5069
5070 Matcher<set<int> > m = Each(2);
5071 EXPECT_EQ("", Explain(m, a));
5072
zhanyong.wan736baa82010-09-27 17:44:16 +00005073 Matcher<const int(&)[1]> n = Each(1); // NOLINT
zhanyong.wan33605ba2010-04-22 23:37:47 +00005074
5075 const int b[1] = { 1 };
5076 EXPECT_EQ("", Explain(n, b));
5077
5078 n = Each(3);
5079 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
5080
5081 a.insert(1);
5082 a.insert(2);
5083 a.insert(3);
5084 m = Each(GreaterThan(0));
5085 EXPECT_EQ("", Explain(m, a));
5086
5087 m = Each(GreaterThan(10));
5088 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
5089 Explain(m, a));
5090}
5091
5092TEST(EachTest, DescribesItselfCorrectly) {
5093 Matcher<vector<int> > m = Each(1);
5094 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
5095
5096 Matcher<vector<int> > m2 = Not(m);
5097 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
5098}
5099
5100TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
5101 vector<int> some_vector;
5102 EXPECT_THAT(some_vector, Each(1));
5103 some_vector.push_back(3);
5104 EXPECT_THAT(some_vector, Not(Each(1)));
5105 EXPECT_THAT(some_vector, Each(3));
5106 some_vector.push_back(1);
5107 some_vector.push_back(2);
5108 EXPECT_THAT(some_vector, Not(Each(3)));
5109 EXPECT_THAT(some_vector, Each(Lt(3.5)));
5110
5111 vector<string> another_vector;
5112 another_vector.push_back("fee");
5113 EXPECT_THAT(another_vector, Each(string("fee")));
5114 another_vector.push_back("fie");
5115 another_vector.push_back("foe");
5116 another_vector.push_back("fum");
5117 EXPECT_THAT(another_vector, Not(Each(string("fee"))));
5118}
5119
5120TEST(EachTest, MatchesMapWhenAllElementsMatch) {
5121 map<const char*, int> my_map;
5122 const char* bar = "a string";
5123 my_map[bar] = 2;
5124 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
5125
5126 map<string, int> another_map;
5127 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5128 another_map["fee"] = 1;
5129 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5130 another_map["fie"] = 2;
5131 another_map["foe"] = 3;
5132 another_map["fum"] = 4;
5133 EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1))));
5134 EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1))));
5135 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
5136}
5137
5138TEST(EachTest, AcceptsMatcher) {
5139 const int a[] = { 1, 2, 3 };
5140 EXPECT_THAT(a, Each(Gt(0)));
5141 EXPECT_THAT(a, Not(Each(Gt(1))));
5142}
5143
5144TEST(EachTest, WorksForNativeArrayAsTuple) {
5145 const int a[] = { 1, 2 };
5146 const int* const pointer = a;
5147 EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
5148 EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
5149}
5150
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005151// For testing Pointwise().
5152class IsHalfOfMatcher {
5153 public:
5154 template <typename T1, typename T2>
5155 bool MatchAndExplain(const tuple<T1, T2>& a_pair,
5156 MatchResultListener* listener) const {
5157 if (get<0>(a_pair) == get<1>(a_pair)/2) {
5158 *listener << "where the second is " << get<1>(a_pair);
5159 return true;
5160 } else {
5161 *listener << "where the second/2 is " << get<1>(a_pair)/2;
5162 return false;
5163 }
5164 }
5165
5166 void DescribeTo(ostream* os) const {
5167 *os << "are a pair where the first is half of the second";
5168 }
5169
5170 void DescribeNegationTo(ostream* os) const {
5171 *os << "are a pair where the first isn't half of the second";
5172 }
5173};
5174
5175PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
5176 return MakePolymorphicMatcher(IsHalfOfMatcher());
5177}
5178
5179TEST(PointwiseTest, DescribesSelf) {
5180 vector<int> rhs;
5181 rhs.push_back(1);
5182 rhs.push_back(2);
5183 rhs.push_back(3);
5184 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
5185 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
5186 "in { 1, 2, 3 } are a pair where the first is half of the second",
5187 Describe(m));
5188 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
5189 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
5190 "where the first isn't half of the second",
5191 DescribeNegation(m));
5192}
5193
5194TEST(PointwiseTest, MakesCopyOfRhs) {
5195 list<signed char> rhs;
5196 rhs.push_back(2);
5197 rhs.push_back(4);
5198
5199 int lhs[] = { 1, 2 };
5200 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
5201 EXPECT_THAT(lhs, m);
5202
5203 // Changing rhs now shouldn't affect m, which made a copy of rhs.
5204 rhs.push_back(6);
5205 EXPECT_THAT(lhs, m);
5206}
5207
5208TEST(PointwiseTest, WorksForLhsNativeArray) {
5209 const int lhs[] = { 1, 2, 3 };
5210 vector<int> rhs;
5211 rhs.push_back(2);
5212 rhs.push_back(4);
5213 rhs.push_back(6);
5214 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
5215 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5216}
5217
5218TEST(PointwiseTest, WorksForRhsNativeArray) {
5219 const int rhs[] = { 1, 2, 3 };
5220 vector<int> lhs;
5221 lhs.push_back(2);
5222 lhs.push_back(4);
5223 lhs.push_back(6);
5224 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
5225 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
5226}
5227
5228TEST(PointwiseTest, RejectsWrongSize) {
5229 const double lhs[2] = { 1, 2 };
5230 const int rhs[1] = { 0 };
5231 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5232 EXPECT_EQ("which contains 2 values",
5233 Explain(Pointwise(Gt(), rhs), lhs));
5234
5235 const int rhs2[3] = { 0, 1, 2 };
5236 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
5237}
5238
5239TEST(PointwiseTest, RejectsWrongContent) {
5240 const double lhs[3] = { 1, 2, 3 };
5241 const int rhs[3] = { 2, 6, 4 };
5242 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
5243 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
5244 "where the second/2 is 3",
5245 Explain(Pointwise(IsHalfOf(), rhs), lhs));
5246}
5247
5248TEST(PointwiseTest, AcceptsCorrectContent) {
5249 const double lhs[3] = { 1, 2, 3 };
5250 const int rhs[3] = { 2, 4, 6 };
5251 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
5252 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
5253}
5254
5255TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
5256 const double lhs[3] = { 1, 2, 3 };
5257 const int rhs[3] = { 2, 4, 6 };
5258 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5259 EXPECT_THAT(lhs, Pointwise(m1, rhs));
5260 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
5261
5262 // This type works as a tuple<const double&, const int&> can be
5263 // implicitly cast to tuple<double, int>.
5264 const Matcher<tuple<double, int> > m2 = IsHalfOf();
5265 EXPECT_THAT(lhs, Pointwise(m2, rhs));
5266 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
5267}
5268
shiqiane35fdd92008-12-10 05:08:54 +00005269} // namespace gmock_matchers_test
5270} // namespace testing