blob: 4644f91f4e4d4ff86c6e62e656ec94319292f930 [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
zhanyong.wan18490652009-05-11 18:54:08 +0000639class Base {};
640class Derived : public Base {};
641
642// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.
643TEST(SafeMatcherCastTest, FromPolymorphicMatcher) {
644 Matcher<char> m2 = SafeMatcherCast<char>(Eq(32));
645 EXPECT_TRUE(m2.Matches(' '));
646 EXPECT_FALSE(m2.Matches('\n'));
647}
648
zhanyong.wan16cf4732009-05-14 20:55:30 +0000649// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where
650// T and U are arithmetic types and T can be losslessly converted to
651// U.
652TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {
zhanyong.wan18490652009-05-11 18:54:08 +0000653 Matcher<double> m1 = DoubleEq(1.0);
zhanyong.wan16cf4732009-05-14 20:55:30 +0000654 Matcher<float> m2 = SafeMatcherCast<float>(m1);
655 EXPECT_TRUE(m2.Matches(1.0f));
656 EXPECT_FALSE(m2.Matches(2.0f));
657
658 Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));
659 EXPECT_TRUE(m3.Matches('a'));
660 EXPECT_FALSE(m3.Matches('b'));
zhanyong.wan18490652009-05-11 18:54:08 +0000661}
662
663// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U
664// are pointers or references to a derived and a base class, correspondingly.
665TEST(SafeMatcherCastTest, FromBaseClass) {
666 Derived d, d2;
667 Matcher<Base*> m1 = Eq(&d);
668 Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);
669 EXPECT_TRUE(m2.Matches(&d));
670 EXPECT_FALSE(m2.Matches(&d2));
671
672 Matcher<Base&> m3 = Ref(d);
673 Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);
674 EXPECT_TRUE(m4.Matches(d));
675 EXPECT_FALSE(m4.Matches(d2));
676}
677
678// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.
679TEST(SafeMatcherCastTest, FromConstReferenceToReference) {
680 int n = 0;
681 Matcher<const int&> m1 = Ref(n);
682 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
683 int n1 = 0;
684 EXPECT_TRUE(m2.Matches(n));
685 EXPECT_FALSE(m2.Matches(n1));
686}
687
688// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.
689TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {
690 Matcher<int> m1 = Eq(0);
691 Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1);
692 EXPECT_TRUE(m2.Matches(0));
693 EXPECT_FALSE(m2.Matches(1));
694}
695
696// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.
697TEST(SafeMatcherCastTest, FromNonReferenceToReference) {
698 Matcher<int> m1 = Eq(0);
699 Matcher<int&> m2 = SafeMatcherCast<int&>(m1);
700 int n = 0;
701 EXPECT_TRUE(m2.Matches(n));
702 n = 1;
703 EXPECT_FALSE(m2.Matches(n));
704}
705
706// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.
707TEST(SafeMatcherCastTest, FromSameType) {
708 Matcher<int> m1 = Eq(0);
709 Matcher<int> m2 = SafeMatcherCast<int>(m1);
710 EXPECT_TRUE(m2.Matches(0));
711 EXPECT_FALSE(m2.Matches(1));
712}
713
jgm79a367e2012-04-10 16:02:11 +0000714TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {
715 Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);
716 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
717 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
718}
719
720TEST(SafeMatcherCastTest, FromConvertibleFromAny) {
721 Matcher<ConvertibleFromAny> m =
722 SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));
723 EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));
724 EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));
725}
726
shiqiane35fdd92008-12-10 05:08:54 +0000727// Tests that A<T>() matches any value of type T.
728TEST(ATest, MatchesAnyValue) {
729 // Tests a matcher for a value type.
730 Matcher<double> m1 = A<double>();
731 EXPECT_TRUE(m1.Matches(91.43));
732 EXPECT_TRUE(m1.Matches(-15.32));
733
734 // Tests a matcher for a reference type.
735 int a = 2;
736 int b = -6;
737 Matcher<int&> m2 = A<int&>();
738 EXPECT_TRUE(m2.Matches(a));
739 EXPECT_TRUE(m2.Matches(b));
740}
741
zhanyong.wanf4274522013-04-24 02:49:43 +0000742TEST(ATest, WorksForDerivedClass) {
743 Base base;
744 Derived derived;
745 EXPECT_THAT(&base, A<Base*>());
746 // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());
747 EXPECT_THAT(&derived, A<Base*>());
748 EXPECT_THAT(&derived, A<Derived*>());
749}
750
shiqiane35fdd92008-12-10 05:08:54 +0000751// Tests that A<T>() describes itself properly.
752TEST(ATest, CanDescribeSelf) {
753 EXPECT_EQ("is anything", Describe(A<bool>()));
754}
755
756// Tests that An<T>() matches any value of type T.
757TEST(AnTest, MatchesAnyValue) {
758 // Tests a matcher for a value type.
759 Matcher<int> m1 = An<int>();
760 EXPECT_TRUE(m1.Matches(9143));
761 EXPECT_TRUE(m1.Matches(-1532));
762
763 // Tests a matcher for a reference type.
764 int a = 2;
765 int b = -6;
766 Matcher<int&> m2 = An<int&>();
767 EXPECT_TRUE(m2.Matches(a));
768 EXPECT_TRUE(m2.Matches(b));
769}
770
771// Tests that An<T>() describes itself properly.
772TEST(AnTest, CanDescribeSelf) {
773 EXPECT_EQ("is anything", Describe(An<int>()));
774}
775
776// Tests that _ can be used as a matcher for any type and matches any
777// value of that type.
778TEST(UnderscoreTest, MatchesAnyValue) {
779 // Uses _ as a matcher for a value type.
780 Matcher<int> m1 = _;
781 EXPECT_TRUE(m1.Matches(123));
782 EXPECT_TRUE(m1.Matches(-242));
783
784 // Uses _ as a matcher for a reference type.
785 bool a = false;
786 const bool b = true;
787 Matcher<const bool&> m2 = _;
788 EXPECT_TRUE(m2.Matches(a));
789 EXPECT_TRUE(m2.Matches(b));
790}
791
792// Tests that _ describes itself properly.
793TEST(UnderscoreTest, CanDescribeSelf) {
794 Matcher<int> m = _;
795 EXPECT_EQ("is anything", Describe(m));
796}
797
798// Tests that Eq(x) matches any value equal to x.
799TEST(EqTest, MatchesEqualValue) {
800 // 2 C-strings with same content but different addresses.
801 const char a1[] = "hi";
802 const char a2[] = "hi";
803
804 Matcher<const char*> m1 = Eq(a1);
805 EXPECT_TRUE(m1.Matches(a1));
806 EXPECT_FALSE(m1.Matches(a2));
807}
808
809// Tests that Eq(v) describes itself properly.
810
811class Unprintable {
812 public:
813 Unprintable() : c_('a') {}
814
zhanyong.wan32de5f52009-12-23 00:13:23 +0000815 bool operator==(const Unprintable& /* rhs */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000816 private:
817 char c_;
818};
819
820TEST(EqTest, CanDescribeSelf) {
821 Matcher<Unprintable> m = Eq(Unprintable());
822 EXPECT_EQ("is equal to 1-byte object <61>", Describe(m));
823}
824
825// Tests that Eq(v) can be used to match any type that supports
826// comparing with type T, where T is v's type.
827TEST(EqTest, IsPolymorphic) {
828 Matcher<int> m1 = Eq(1);
829 EXPECT_TRUE(m1.Matches(1));
830 EXPECT_FALSE(m1.Matches(2));
831
832 Matcher<char> m2 = Eq(1);
833 EXPECT_TRUE(m2.Matches('\1'));
834 EXPECT_FALSE(m2.Matches('a'));
835}
836
837// Tests that TypedEq<T>(v) matches values of type T that's equal to v.
838TEST(TypedEqTest, ChecksEqualityForGivenType) {
839 Matcher<char> m1 = TypedEq<char>('a');
840 EXPECT_TRUE(m1.Matches('a'));
841 EXPECT_FALSE(m1.Matches('b'));
842
843 Matcher<int> m2 = TypedEq<int>(6);
844 EXPECT_TRUE(m2.Matches(6));
845 EXPECT_FALSE(m2.Matches(7));
846}
847
848// Tests that TypedEq(v) describes itself properly.
849TEST(TypedEqTest, CanDescribeSelf) {
850 EXPECT_EQ("is equal to 2", Describe(TypedEq<int>(2)));
851}
852
853// Tests that TypedEq<T>(v) has type Matcher<T>.
854
855// Type<T>::IsTypeOf(v) compiles iff the type of value v is T, where T
856// is a "bare" type (i.e. not in the form of const U or U&). If v's
857// type is not T, the compiler will generate a message about
858// "undefined referece".
859template <typename T>
860struct Type {
zhanyong.wan32de5f52009-12-23 00:13:23 +0000861 static bool IsTypeOf(const T& /* v */) { return true; }
shiqiane35fdd92008-12-10 05:08:54 +0000862
863 template <typename T2>
864 static void IsTypeOf(T2 v);
865};
866
867TEST(TypedEqTest, HasSpecifiedType) {
868 // Verfies that the type of TypedEq<T>(v) is Matcher<T>.
869 Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5));
870 Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5));
871}
872
873// Tests that Ge(v) matches anything >= v.
874TEST(GeTest, ImplementsGreaterThanOrEqual) {
875 Matcher<int> m1 = Ge(0);
876 EXPECT_TRUE(m1.Matches(1));
877 EXPECT_TRUE(m1.Matches(0));
878 EXPECT_FALSE(m1.Matches(-1));
879}
880
881// Tests that Ge(v) describes itself properly.
882TEST(GeTest, CanDescribeSelf) {
883 Matcher<int> m = Ge(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000884 EXPECT_EQ("is >= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000885}
886
887// Tests that Gt(v) matches anything > v.
888TEST(GtTest, ImplementsGreaterThan) {
889 Matcher<double> m1 = Gt(0);
890 EXPECT_TRUE(m1.Matches(1.0));
891 EXPECT_FALSE(m1.Matches(0.0));
892 EXPECT_FALSE(m1.Matches(-1.0));
893}
894
895// Tests that Gt(v) describes itself properly.
896TEST(GtTest, CanDescribeSelf) {
897 Matcher<int> m = Gt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000898 EXPECT_EQ("is > 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000899}
900
901// Tests that Le(v) matches anything <= v.
902TEST(LeTest, ImplementsLessThanOrEqual) {
903 Matcher<char> m1 = Le('b');
904 EXPECT_TRUE(m1.Matches('a'));
905 EXPECT_TRUE(m1.Matches('b'));
906 EXPECT_FALSE(m1.Matches('c'));
907}
908
909// Tests that Le(v) describes itself properly.
910TEST(LeTest, CanDescribeSelf) {
911 Matcher<int> m = Le(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000912 EXPECT_EQ("is <= 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000913}
914
915// Tests that Lt(v) matches anything < v.
916TEST(LtTest, ImplementsLessThan) {
917 Matcher<const string&> m1 = Lt("Hello");
918 EXPECT_TRUE(m1.Matches("Abc"));
919 EXPECT_FALSE(m1.Matches("Hello"));
920 EXPECT_FALSE(m1.Matches("Hello, world!"));
921}
922
923// Tests that Lt(v) describes itself properly.
924TEST(LtTest, CanDescribeSelf) {
925 Matcher<int> m = Lt(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000926 EXPECT_EQ("is < 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000927}
928
929// Tests that Ne(v) matches anything != v.
930TEST(NeTest, ImplementsNotEqual) {
931 Matcher<int> m1 = Ne(0);
932 EXPECT_TRUE(m1.Matches(1));
933 EXPECT_TRUE(m1.Matches(-1));
934 EXPECT_FALSE(m1.Matches(0));
935}
936
937// Tests that Ne(v) describes itself properly.
938TEST(NeTest, CanDescribeSelf) {
939 Matcher<int> m = Ne(5);
zhanyong.wanb1c7f932010-03-24 17:35:11 +0000940 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +0000941}
942
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000943// Tests that IsNull() matches any NULL pointer of any type.
944TEST(IsNullTest, MatchesNullPointer) {
945 Matcher<int*> m1 = IsNull();
946 int* p1 = NULL;
947 int n = 0;
948 EXPECT_TRUE(m1.Matches(p1));
949 EXPECT_FALSE(m1.Matches(&n));
950
951 Matcher<const char*> m2 = IsNull();
952 const char* p2 = NULL;
953 EXPECT_TRUE(m2.Matches(p2));
954 EXPECT_FALSE(m2.Matches("hi"));
955
zhanyong.wan95b12332009-09-25 18:55:50 +0000956#if !GTEST_OS_SYMBIAN
957 // Nokia's Symbian compiler generates:
958 // gmock-matchers.h: ambiguous access to overloaded function
959 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(void *)'
960 // gmock-matchers.h: 'testing::Matcher<void *>::Matcher(const testing::
961 // MatcherInterface<void *> *)'
962 // gmock-matchers.h: (point of instantiation: 'testing::
963 // gmock_matchers_test::IsNullTest_MatchesNullPointer_Test::TestBody()')
964 // gmock-matchers.h: (instantiating: 'testing::PolymorphicMatc
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000965 Matcher<void*> m3 = IsNull();
966 void* p3 = NULL;
967 EXPECT_TRUE(m3.Matches(p3));
968 EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));
zhanyong.wan95b12332009-09-25 18:55:50 +0000969#endif
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000970}
971
vladlosev79b83502009-11-18 00:43:37 +0000972TEST(IsNullTest, LinkedPtr) {
973 const Matcher<linked_ptr<int> > m = IsNull();
974 const linked_ptr<int> null_p;
975 const linked_ptr<int> non_null_p(new int);
976
977 EXPECT_TRUE(m.Matches(null_p));
978 EXPECT_FALSE(m.Matches(non_null_p));
979}
980
981TEST(IsNullTest, ReferenceToConstLinkedPtr) {
982 const Matcher<const linked_ptr<double>&> m = IsNull();
983 const linked_ptr<double> null_p;
984 const linked_ptr<double> non_null_p(new double);
985
986 EXPECT_TRUE(m.Matches(null_p));
987 EXPECT_FALSE(m.Matches(non_null_p));
988}
989
vladloseve56daa72009-11-18 01:08:08 +0000990TEST(IsNullTest, ReferenceToConstScopedPtr) {
991 const Matcher<const scoped_ptr<double>&> m = IsNull();
992 const scoped_ptr<double> null_p;
993 const scoped_ptr<double> non_null_p(new double);
994
995 EXPECT_TRUE(m.Matches(null_p));
996 EXPECT_FALSE(m.Matches(non_null_p));
997}
998
zhanyong.wan2d970ee2009-09-24 21:41:36 +0000999// Tests that IsNull() describes itself properly.
1000TEST(IsNullTest, CanDescribeSelf) {
1001 Matcher<int*> m = IsNull();
1002 EXPECT_EQ("is NULL", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001003 EXPECT_EQ("isn't NULL", DescribeNegation(m));
zhanyong.wan2d970ee2009-09-24 21:41:36 +00001004}
1005
shiqiane35fdd92008-12-10 05:08:54 +00001006// Tests that NotNull() matches any non-NULL pointer of any type.
1007TEST(NotNullTest, MatchesNonNullPointer) {
1008 Matcher<int*> m1 = NotNull();
1009 int* p1 = NULL;
1010 int n = 0;
1011 EXPECT_FALSE(m1.Matches(p1));
1012 EXPECT_TRUE(m1.Matches(&n));
1013
1014 Matcher<const char*> m2 = NotNull();
1015 const char* p2 = NULL;
1016 EXPECT_FALSE(m2.Matches(p2));
1017 EXPECT_TRUE(m2.Matches("hi"));
1018}
1019
vladlosev79b83502009-11-18 00:43:37 +00001020TEST(NotNullTest, LinkedPtr) {
1021 const Matcher<linked_ptr<int> > m = NotNull();
1022 const linked_ptr<int> null_p;
1023 const linked_ptr<int> non_null_p(new int);
1024
1025 EXPECT_FALSE(m.Matches(null_p));
1026 EXPECT_TRUE(m.Matches(non_null_p));
1027}
1028
1029TEST(NotNullTest, ReferenceToConstLinkedPtr) {
1030 const Matcher<const linked_ptr<double>&> m = NotNull();
1031 const linked_ptr<double> null_p;
1032 const linked_ptr<double> non_null_p(new double);
1033
1034 EXPECT_FALSE(m.Matches(null_p));
1035 EXPECT_TRUE(m.Matches(non_null_p));
1036}
1037
vladloseve56daa72009-11-18 01:08:08 +00001038TEST(NotNullTest, ReferenceToConstScopedPtr) {
1039 const Matcher<const scoped_ptr<double>&> m = NotNull();
1040 const scoped_ptr<double> null_p;
1041 const scoped_ptr<double> non_null_p(new double);
1042
1043 EXPECT_FALSE(m.Matches(null_p));
1044 EXPECT_TRUE(m.Matches(non_null_p));
1045}
1046
shiqiane35fdd92008-12-10 05:08:54 +00001047// Tests that NotNull() describes itself properly.
1048TEST(NotNullTest, CanDescribeSelf) {
1049 Matcher<int*> m = NotNull();
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001050 EXPECT_EQ("isn't NULL", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001051}
1052
1053// Tests that Ref(variable) matches an argument that references
1054// 'variable'.
1055TEST(RefTest, MatchesSameVariable) {
1056 int a = 0;
1057 int b = 0;
1058 Matcher<int&> m = Ref(a);
1059 EXPECT_TRUE(m.Matches(a));
1060 EXPECT_FALSE(m.Matches(b));
1061}
1062
1063// Tests that Ref(variable) describes itself properly.
1064TEST(RefTest, CanDescribeSelf) {
1065 int n = 5;
1066 Matcher<int&> m = Ref(n);
1067 stringstream ss;
1068 ss << "references the variable @" << &n << " 5";
1069 EXPECT_EQ(string(ss.str()), Describe(m));
1070}
1071
1072// Test that Ref(non_const_varialbe) can be used as a matcher for a
1073// const reference.
1074TEST(RefTest, CanBeUsedAsMatcherForConstReference) {
1075 int a = 0;
1076 int b = 0;
1077 Matcher<const int&> m = Ref(a);
1078 EXPECT_TRUE(m.Matches(a));
1079 EXPECT_FALSE(m.Matches(b));
1080}
1081
1082// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be
1083// used wherever Ref(base) can be used (Ref(derived) is a sub-type
1084// of Ref(base), but not vice versa.
1085
shiqiane35fdd92008-12-10 05:08:54 +00001086TEST(RefTest, IsCovariant) {
1087 Base base, base2;
1088 Derived derived;
1089 Matcher<const Base&> m1 = Ref(base);
1090 EXPECT_TRUE(m1.Matches(base));
1091 EXPECT_FALSE(m1.Matches(base2));
1092 EXPECT_FALSE(m1.Matches(derived));
1093
1094 m1 = Ref(derived);
1095 EXPECT_TRUE(m1.Matches(derived));
1096 EXPECT_FALSE(m1.Matches(base));
1097 EXPECT_FALSE(m1.Matches(base2));
1098}
1099
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001100TEST(RefTest, ExplainsResult) {
1101 int n = 0;
1102 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),
1103 StartsWith("which is located @"));
1104
1105 int m = 0;
1106 EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),
1107 StartsWith("which is located @"));
1108}
1109
shiqiane35fdd92008-12-10 05:08:54 +00001110// Tests string comparison matchers.
1111
1112TEST(StrEqTest, MatchesEqualString) {
1113 Matcher<const char*> m = StrEq(string("Hello"));
1114 EXPECT_TRUE(m.Matches("Hello"));
1115 EXPECT_FALSE(m.Matches("hello"));
1116 EXPECT_FALSE(m.Matches(NULL));
1117
1118 Matcher<const string&> m2 = StrEq("Hello");
1119 EXPECT_TRUE(m2.Matches("Hello"));
1120 EXPECT_FALSE(m2.Matches("Hi"));
1121}
1122
1123TEST(StrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001124 Matcher<string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3");
1125 EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"",
shiqiane35fdd92008-12-10 05:08:54 +00001126 Describe(m));
1127
1128 string str("01204500800");
1129 str[3] = '\0';
1130 Matcher<string> m2 = StrEq(str);
1131 EXPECT_EQ("is equal to \"012\\04500800\"", Describe(m2));
1132 str[0] = str[6] = str[7] = str[9] = str[10] = '\0';
1133 Matcher<string> m3 = StrEq(str);
1134 EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"", Describe(m3));
1135}
1136
1137TEST(StrNeTest, MatchesUnequalString) {
1138 Matcher<const char*> m = StrNe("Hello");
1139 EXPECT_TRUE(m.Matches(""));
1140 EXPECT_TRUE(m.Matches(NULL));
1141 EXPECT_FALSE(m.Matches("Hello"));
1142
1143 Matcher<string> m2 = StrNe(string("Hello"));
1144 EXPECT_TRUE(m2.Matches("hello"));
1145 EXPECT_FALSE(m2.Matches("Hello"));
1146}
1147
1148TEST(StrNeTest, CanDescribeSelf) {
1149 Matcher<const char*> m = StrNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001150 EXPECT_EQ("isn't equal to \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001151}
1152
1153TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {
1154 Matcher<const char*> m = StrCaseEq(string("Hello"));
1155 EXPECT_TRUE(m.Matches("Hello"));
1156 EXPECT_TRUE(m.Matches("hello"));
1157 EXPECT_FALSE(m.Matches("Hi"));
1158 EXPECT_FALSE(m.Matches(NULL));
1159
1160 Matcher<const string&> m2 = StrCaseEq("Hello");
1161 EXPECT_TRUE(m2.Matches("hello"));
1162 EXPECT_FALSE(m2.Matches("Hi"));
1163}
1164
1165TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1166 string str1("oabocdooeoo");
1167 string str2("OABOCDOOEOO");
1168 Matcher<const string&> m0 = StrCaseEq(str1);
1169 EXPECT_FALSE(m0.Matches(str2 + string(1, '\0')));
1170
1171 str1[3] = str2[3] = '\0';
1172 Matcher<const string&> m1 = StrCaseEq(str1);
1173 EXPECT_TRUE(m1.Matches(str2));
1174
1175 str1[0] = str1[6] = str1[7] = str1[10] = '\0';
1176 str2[0] = str2[6] = str2[7] = str2[10] = '\0';
1177 Matcher<const string&> m2 = StrCaseEq(str1);
1178 str1[9] = str2[9] = '\0';
1179 EXPECT_FALSE(m2.Matches(str2));
1180
1181 Matcher<const string&> m3 = StrCaseEq(str1);
1182 EXPECT_TRUE(m3.Matches(str2));
1183
1184 EXPECT_FALSE(m3.Matches(str2 + "x"));
1185 str2.append(1, '\0');
1186 EXPECT_FALSE(m3.Matches(str2));
1187 EXPECT_FALSE(m3.Matches(string(str2, 0, 9)));
1188}
1189
1190TEST(StrCaseEqTest, CanDescribeSelf) {
1191 Matcher<string> m = StrCaseEq("Hi");
1192 EXPECT_EQ("is equal to (ignoring case) \"Hi\"", Describe(m));
1193}
1194
1195TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1196 Matcher<const char*> m = StrCaseNe("Hello");
1197 EXPECT_TRUE(m.Matches("Hi"));
1198 EXPECT_TRUE(m.Matches(NULL));
1199 EXPECT_FALSE(m.Matches("Hello"));
1200 EXPECT_FALSE(m.Matches("hello"));
1201
1202 Matcher<string> m2 = StrCaseNe(string("Hello"));
1203 EXPECT_TRUE(m2.Matches(""));
1204 EXPECT_FALSE(m2.Matches("Hello"));
1205}
1206
1207TEST(StrCaseNeTest, CanDescribeSelf) {
1208 Matcher<const char*> m = StrCaseNe("Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001209 EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001210}
1211
1212// Tests that HasSubstr() works for matching string-typed values.
1213TEST(HasSubstrTest, WorksForStringClasses) {
1214 const Matcher<string> m1 = HasSubstr("foo");
1215 EXPECT_TRUE(m1.Matches(string("I love food.")));
1216 EXPECT_FALSE(m1.Matches(string("tofo")));
1217
1218 const Matcher<const std::string&> m2 = HasSubstr("foo");
1219 EXPECT_TRUE(m2.Matches(std::string("I love food.")));
1220 EXPECT_FALSE(m2.Matches(std::string("tofo")));
1221}
1222
1223// Tests that HasSubstr() works for matching C-string-typed values.
1224TEST(HasSubstrTest, WorksForCStrings) {
1225 const Matcher<char*> m1 = HasSubstr("foo");
1226 EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food.")));
1227 EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo")));
1228 EXPECT_FALSE(m1.Matches(NULL));
1229
1230 const Matcher<const char*> m2 = HasSubstr("foo");
1231 EXPECT_TRUE(m2.Matches("I love food."));
1232 EXPECT_FALSE(m2.Matches("tofo"));
1233 EXPECT_FALSE(m2.Matches(NULL));
1234}
1235
1236// Tests that HasSubstr(s) describes itself properly.
1237TEST(HasSubstrTest, CanDescribeSelf) {
1238 Matcher<string> m = HasSubstr("foo\n\"");
1239 EXPECT_EQ("has substring \"foo\\n\\\"\"", Describe(m));
1240}
1241
zhanyong.wanb5937da2009-07-16 20:26:41 +00001242TEST(KeyTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001243 Matcher<const pair<std::string, int>&> m = Key("foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001244 EXPECT_EQ("has a key that is equal to \"foo\"", Describe(m));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001245 EXPECT_EQ("doesn't have a key that is equal to \"foo\"", DescribeNegation(m));
1246}
1247
1248TEST(KeyTest, ExplainsResult) {
1249 Matcher<pair<int, bool> > m = Key(GreaterThan(10));
1250 EXPECT_EQ("whose first field is a value which is 5 less than 10",
1251 Explain(m, make_pair(5, true)));
1252 EXPECT_EQ("whose first field is a value which is 5 more than 10",
1253 Explain(m, make_pair(15, true)));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001254}
1255
1256TEST(KeyTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001257 pair<int, std::string> p(25, "foo");
zhanyong.wanb5937da2009-07-16 20:26:41 +00001258 EXPECT_THAT(p, Key(25));
1259 EXPECT_THAT(p, Not(Key(42)));
1260 EXPECT_THAT(p, Key(Ge(20)));
1261 EXPECT_THAT(p, Not(Key(Lt(25))));
1262}
1263
1264TEST(KeyTest, SafelyCastsInnerMatcher) {
1265 Matcher<int> is_positive = Gt(0);
1266 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001267 pair<char, bool> p('a', true);
zhanyong.wanb5937da2009-07-16 20:26:41 +00001268 EXPECT_THAT(p, Key(is_positive));
1269 EXPECT_THAT(p, Not(Key(is_negative)));
1270}
1271
1272TEST(KeyTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001273 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001274 container.insert(make_pair(1, 'a'));
1275 container.insert(make_pair(2, 'b'));
1276 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001277 EXPECT_THAT(container, Contains(Key(1)));
1278 EXPECT_THAT(container, Not(Contains(Key(3))));
1279}
1280
1281TEST(KeyTest, InsideContainsUsingMultimap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001282 multimap<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001283 container.insert(make_pair(1, 'a'));
1284 container.insert(make_pair(2, 'b'));
1285 container.insert(make_pair(4, 'c'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001286
1287 EXPECT_THAT(container, Not(Contains(Key(25))));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001288 container.insert(make_pair(25, 'd'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001289 EXPECT_THAT(container, Contains(Key(25)));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001290 container.insert(make_pair(25, 'e'));
zhanyong.wanb5937da2009-07-16 20:26:41 +00001291 EXPECT_THAT(container, Contains(Key(25)));
1292
1293 EXPECT_THAT(container, Contains(Key(1)));
1294 EXPECT_THAT(container, Not(Contains(Key(3))));
1295}
1296
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001297TEST(PairTest, Typing) {
1298 // Test verifies the following type conversions can be compiled.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001299 Matcher<const pair<const char*, int>&> m1 = Pair("foo", 42);
1300 Matcher<const pair<const char*, int> > m2 = Pair("foo", 42);
1301 Matcher<pair<const char*, int> > m3 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001302
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001303 Matcher<pair<int, const std::string> > m4 = Pair(25, "42");
1304 Matcher<pair<const std::string, int> > m5 = Pair("25", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001305}
1306
1307TEST(PairTest, CanDescribeSelf) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001308 Matcher<const pair<std::string, int>&> m1 = Pair("foo", 42);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001309 EXPECT_EQ("has a first field that is equal to \"foo\""
1310 ", and has a second field that is equal to 42",
1311 Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001312 EXPECT_EQ("has a first field that isn't equal to \"foo\""
1313 ", or has a second field that isn't equal to 42",
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001314 DescribeNegation(m1));
1315 // Double and triple negation (1 or 2 times not and description of negation).
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001316 Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));
1317 EXPECT_EQ("has a first field that isn't equal to 13"
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001318 ", and has a second field that is equal to 42",
1319 DescribeNegation(m2));
1320}
1321
1322TEST(PairTest, CanExplainMatchResultTo) {
zhanyong.wan82113312010-01-08 21:55:40 +00001323 // If neither field matches, Pair() should explain about the first
1324 // field.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001325 const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001326 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001327 Explain(m, make_pair(-1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001328
zhanyong.wan82113312010-01-08 21:55:40 +00001329 // If the first field matches but the second doesn't, Pair() should
1330 // explain about the second field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001331 EXPECT_EQ("whose second field does not match, which is 2 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001332 Explain(m, make_pair(1, -2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001333
zhanyong.wan82113312010-01-08 21:55:40 +00001334 // If the first field doesn't match but the second does, Pair()
1335 // should explain about the first field.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001336 EXPECT_EQ("whose first field does not match, which is 1 less than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001337 Explain(m, make_pair(-1, 2)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001338
zhanyong.wan82113312010-01-08 21:55:40 +00001339 // If both fields match, Pair() should explain about them both.
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001340 EXPECT_EQ("whose both fields match, where the first field is a value "
1341 "which is 1 more than 0, and the second field is a value "
1342 "which is 2 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001343 Explain(m, make_pair(1, 2)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001344
1345 // If only the first match has an explanation, only this explanation should
1346 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001347 const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001348 EXPECT_EQ("whose both fields match, where the first field is a value "
1349 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001350 Explain(explain_first, make_pair(1, 0)));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001351
1352 // If only the second match has an explanation, only this explanation should
1353 // be printed.
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001354 const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0));
zhanyong.wan676e8cc2010-03-16 20:01:51 +00001355 EXPECT_EQ("whose both fields match, where the second field is a value "
1356 "which is 1 more than 0",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001357 Explain(explain_second, make_pair(0, 1)));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001358}
1359
1360TEST(PairTest, MatchesCorrectly) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001361 pair<int, std::string> p(25, "foo");
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001362
1363 // Both fields match.
1364 EXPECT_THAT(p, Pair(25, "foo"));
1365 EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o")));
1366
1367 // 'first' doesnt' match, but 'second' matches.
1368 EXPECT_THAT(p, Not(Pair(42, "foo")));
1369 EXPECT_THAT(p, Not(Pair(Lt(25), "foo")));
1370
1371 // 'first' matches, but 'second' doesn't match.
1372 EXPECT_THAT(p, Not(Pair(25, "bar")));
1373 EXPECT_THAT(p, Not(Pair(25, Not("foo"))));
1374
1375 // Neither field matches.
1376 EXPECT_THAT(p, Not(Pair(13, "bar")));
1377 EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a"))));
1378}
1379
1380TEST(PairTest, SafelyCastsInnerMatchers) {
1381 Matcher<int> is_positive = Gt(0);
1382 Matcher<int> is_negative = Lt(0);
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001383 pair<char, bool> p('a', true);
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001384 EXPECT_THAT(p, Pair(is_positive, _));
1385 EXPECT_THAT(p, Not(Pair(is_negative, _)));
1386 EXPECT_THAT(p, Pair(_, is_positive));
1387 EXPECT_THAT(p, Not(Pair(_, is_negative)));
1388}
1389
1390TEST(PairTest, InsideContainsUsingMap) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001391 map<int, char> container;
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001392 container.insert(make_pair(1, 'a'));
1393 container.insert(make_pair(2, 'b'));
1394 container.insert(make_pair(4, 'c'));
zhanyong.wan95b12332009-09-25 18:55:50 +00001395 EXPECT_THAT(container, Contains(Pair(1, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001396 EXPECT_THAT(container, Contains(Pair(1, _)));
zhanyong.wan95b12332009-09-25 18:55:50 +00001397 EXPECT_THAT(container, Contains(Pair(_, 'a')));
zhanyong.wanf5e1ce52009-09-16 07:02:02 +00001398 EXPECT_THAT(container, Not(Contains(Pair(3, _))));
1399}
1400
shiqiane35fdd92008-12-10 05:08:54 +00001401// Tests StartsWith(s).
1402
1403TEST(StartsWithTest, MatchesStringWithGivenPrefix) {
1404 const Matcher<const char*> m1 = StartsWith(string(""));
1405 EXPECT_TRUE(m1.Matches("Hi"));
1406 EXPECT_TRUE(m1.Matches(""));
1407 EXPECT_FALSE(m1.Matches(NULL));
1408
1409 const Matcher<const string&> m2 = StartsWith("Hi");
1410 EXPECT_TRUE(m2.Matches("Hi"));
1411 EXPECT_TRUE(m2.Matches("Hi Hi!"));
1412 EXPECT_TRUE(m2.Matches("High"));
1413 EXPECT_FALSE(m2.Matches("H"));
1414 EXPECT_FALSE(m2.Matches(" Hi"));
1415}
1416
1417TEST(StartsWithTest, CanDescribeSelf) {
1418 Matcher<const std::string> m = StartsWith("Hi");
1419 EXPECT_EQ("starts with \"Hi\"", Describe(m));
1420}
1421
1422// Tests EndsWith(s).
1423
1424TEST(EndsWithTest, MatchesStringWithGivenSuffix) {
1425 const Matcher<const char*> m1 = EndsWith("");
1426 EXPECT_TRUE(m1.Matches("Hi"));
1427 EXPECT_TRUE(m1.Matches(""));
1428 EXPECT_FALSE(m1.Matches(NULL));
1429
1430 const Matcher<const string&> m2 = EndsWith(string("Hi"));
1431 EXPECT_TRUE(m2.Matches("Hi"));
1432 EXPECT_TRUE(m2.Matches("Wow Hi Hi"));
1433 EXPECT_TRUE(m2.Matches("Super Hi"));
1434 EXPECT_FALSE(m2.Matches("i"));
1435 EXPECT_FALSE(m2.Matches("Hi "));
1436}
1437
1438TEST(EndsWithTest, CanDescribeSelf) {
1439 Matcher<const std::string> m = EndsWith("Hi");
1440 EXPECT_EQ("ends with \"Hi\"", Describe(m));
1441}
1442
shiqiane35fdd92008-12-10 05:08:54 +00001443// Tests MatchesRegex().
1444
1445TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {
1446 const Matcher<const char*> m1 = MatchesRegex("a.*z");
1447 EXPECT_TRUE(m1.Matches("az"));
1448 EXPECT_TRUE(m1.Matches("abcz"));
1449 EXPECT_FALSE(m1.Matches(NULL));
1450
1451 const Matcher<const string&> m2 = MatchesRegex(new RE("a.*z"));
1452 EXPECT_TRUE(m2.Matches("azbz"));
1453 EXPECT_FALSE(m2.Matches("az1"));
1454 EXPECT_FALSE(m2.Matches("1az"));
1455}
1456
1457TEST(MatchesRegexTest, CanDescribeSelf) {
1458 Matcher<const std::string> m1 = MatchesRegex(string("Hi.*"));
1459 EXPECT_EQ("matches regular expression \"Hi.*\"", Describe(m1));
1460
zhanyong.wand14aaed2010-01-14 05:36:32 +00001461 Matcher<const char*> m2 = MatchesRegex(new RE("a.*"));
1462 EXPECT_EQ("matches regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001463}
1464
1465// Tests ContainsRegex().
1466
1467TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {
1468 const Matcher<const char*> m1 = ContainsRegex(string("a.*z"));
1469 EXPECT_TRUE(m1.Matches("az"));
1470 EXPECT_TRUE(m1.Matches("0abcz1"));
1471 EXPECT_FALSE(m1.Matches(NULL));
1472
1473 const Matcher<const string&> m2 = ContainsRegex(new RE("a.*z"));
1474 EXPECT_TRUE(m2.Matches("azbz"));
1475 EXPECT_TRUE(m2.Matches("az1"));
1476 EXPECT_FALSE(m2.Matches("1a"));
1477}
1478
1479TEST(ContainsRegexTest, CanDescribeSelf) {
1480 Matcher<const std::string> m1 = ContainsRegex("Hi.*");
1481 EXPECT_EQ("contains regular expression \"Hi.*\"", Describe(m1));
1482
zhanyong.wand14aaed2010-01-14 05:36:32 +00001483 Matcher<const char*> m2 = ContainsRegex(new RE("a.*"));
1484 EXPECT_EQ("contains regular expression \"a.*\"", Describe(m2));
shiqiane35fdd92008-12-10 05:08:54 +00001485}
shiqiane35fdd92008-12-10 05:08:54 +00001486
1487// Tests for wide strings.
1488#if GTEST_HAS_STD_WSTRING
1489TEST(StdWideStrEqTest, MatchesEqual) {
1490 Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello"));
1491 EXPECT_TRUE(m.Matches(L"Hello"));
1492 EXPECT_FALSE(m.Matches(L"hello"));
1493 EXPECT_FALSE(m.Matches(NULL));
1494
1495 Matcher<const ::std::wstring&> m2 = StrEq(L"Hello");
1496 EXPECT_TRUE(m2.Matches(L"Hello"));
1497 EXPECT_FALSE(m2.Matches(L"Hi"));
1498
1499 Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1500 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1501 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1502
1503 ::std::wstring str(L"01204500800");
1504 str[3] = L'\0';
1505 Matcher<const ::std::wstring&> m4 = StrEq(str);
1506 EXPECT_TRUE(m4.Matches(str));
1507 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1508 Matcher<const ::std::wstring&> m5 = StrEq(str);
1509 EXPECT_TRUE(m5.Matches(str));
1510}
1511
1512TEST(StdWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001513 Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1514 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001515 Describe(m));
1516
1517 Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1518 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1519 Describe(m2));
1520
1521 ::std::wstring str(L"01204500800");
1522 str[3] = L'\0';
1523 Matcher<const ::std::wstring&> m4 = StrEq(str);
1524 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1525 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1526 Matcher<const ::std::wstring&> m5 = StrEq(str);
1527 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1528}
1529
1530TEST(StdWideStrNeTest, MatchesUnequalString) {
1531 Matcher<const wchar_t*> m = StrNe(L"Hello");
1532 EXPECT_TRUE(m.Matches(L""));
1533 EXPECT_TRUE(m.Matches(NULL));
1534 EXPECT_FALSE(m.Matches(L"Hello"));
1535
1536 Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello"));
1537 EXPECT_TRUE(m2.Matches(L"hello"));
1538 EXPECT_FALSE(m2.Matches(L"Hello"));
1539}
1540
1541TEST(StdWideStrNeTest, CanDescribeSelf) {
1542 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001543 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001544}
1545
1546TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1547 Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello"));
1548 EXPECT_TRUE(m.Matches(L"Hello"));
1549 EXPECT_TRUE(m.Matches(L"hello"));
1550 EXPECT_FALSE(m.Matches(L"Hi"));
1551 EXPECT_FALSE(m.Matches(NULL));
1552
1553 Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello");
1554 EXPECT_TRUE(m2.Matches(L"hello"));
1555 EXPECT_FALSE(m2.Matches(L"Hi"));
1556}
1557
1558TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1559 ::std::wstring str1(L"oabocdooeoo");
1560 ::std::wstring str2(L"OABOCDOOEOO");
1561 Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);
1562 EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0')));
1563
1564 str1[3] = str2[3] = L'\0';
1565 Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);
1566 EXPECT_TRUE(m1.Matches(str2));
1567
1568 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1569 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1570 Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);
1571 str1[9] = str2[9] = L'\0';
1572 EXPECT_FALSE(m2.Matches(str2));
1573
1574 Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);
1575 EXPECT_TRUE(m3.Matches(str2));
1576
1577 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1578 str2.append(1, L'\0');
1579 EXPECT_FALSE(m3.Matches(str2));
1580 EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));
1581}
1582
1583TEST(StdWideStrCaseEqTest, CanDescribeSelf) {
1584 Matcher< ::std::wstring> m = StrCaseEq(L"Hi");
1585 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1586}
1587
1588TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1589 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1590 EXPECT_TRUE(m.Matches(L"Hi"));
1591 EXPECT_TRUE(m.Matches(NULL));
1592 EXPECT_FALSE(m.Matches(L"Hello"));
1593 EXPECT_FALSE(m.Matches(L"hello"));
1594
1595 Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello"));
1596 EXPECT_TRUE(m2.Matches(L""));
1597 EXPECT_FALSE(m2.Matches(L"Hello"));
1598}
1599
1600TEST(StdWideStrCaseNeTest, CanDescribeSelf) {
1601 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001602 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001603}
1604
1605// Tests that HasSubstr() works for matching wstring-typed values.
1606TEST(StdWideHasSubstrTest, WorksForStringClasses) {
1607 const Matcher< ::std::wstring> m1 = HasSubstr(L"foo");
1608 EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food.")));
1609 EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo")));
1610
1611 const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo");
1612 EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food.")));
1613 EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo")));
1614}
1615
1616// Tests that HasSubstr() works for matching C-wide-string-typed values.
1617TEST(StdWideHasSubstrTest, WorksForCStrings) {
1618 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1619 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1620 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1621 EXPECT_FALSE(m1.Matches(NULL));
1622
1623 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1624 EXPECT_TRUE(m2.Matches(L"I love food."));
1625 EXPECT_FALSE(m2.Matches(L"tofo"));
1626 EXPECT_FALSE(m2.Matches(NULL));
1627}
1628
1629// Tests that HasSubstr(s) describes itself properly.
1630TEST(StdWideHasSubstrTest, CanDescribeSelf) {
1631 Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"");
1632 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1633}
1634
1635// Tests StartsWith(s).
1636
1637TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {
1638 const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L""));
1639 EXPECT_TRUE(m1.Matches(L"Hi"));
1640 EXPECT_TRUE(m1.Matches(L""));
1641 EXPECT_FALSE(m1.Matches(NULL));
1642
1643 const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi");
1644 EXPECT_TRUE(m2.Matches(L"Hi"));
1645 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1646 EXPECT_TRUE(m2.Matches(L"High"));
1647 EXPECT_FALSE(m2.Matches(L"H"));
1648 EXPECT_FALSE(m2.Matches(L" Hi"));
1649}
1650
1651TEST(StdWideStartsWithTest, CanDescribeSelf) {
1652 Matcher<const ::std::wstring> m = StartsWith(L"Hi");
1653 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1654}
1655
1656// Tests EndsWith(s).
1657
1658TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {
1659 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1660 EXPECT_TRUE(m1.Matches(L"Hi"));
1661 EXPECT_TRUE(m1.Matches(L""));
1662 EXPECT_FALSE(m1.Matches(NULL));
1663
1664 const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi"));
1665 EXPECT_TRUE(m2.Matches(L"Hi"));
1666 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1667 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1668 EXPECT_FALSE(m2.Matches(L"i"));
1669 EXPECT_FALSE(m2.Matches(L"Hi "));
1670}
1671
1672TEST(StdWideEndsWithTest, CanDescribeSelf) {
1673 Matcher<const ::std::wstring> m = EndsWith(L"Hi");
1674 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1675}
1676
1677#endif // GTEST_HAS_STD_WSTRING
1678
1679#if GTEST_HAS_GLOBAL_WSTRING
1680TEST(GlobalWideStrEqTest, MatchesEqual) {
1681 Matcher<const wchar_t*> m = StrEq(::wstring(L"Hello"));
1682 EXPECT_TRUE(m.Matches(L"Hello"));
1683 EXPECT_FALSE(m.Matches(L"hello"));
1684 EXPECT_FALSE(m.Matches(NULL));
1685
1686 Matcher<const ::wstring&> m2 = StrEq(L"Hello");
1687 EXPECT_TRUE(m2.Matches(L"Hello"));
1688 EXPECT_FALSE(m2.Matches(L"Hi"));
1689
1690 Matcher<const ::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D");
1691 EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D"));
1692 EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E"));
1693
1694 ::wstring str(L"01204500800");
1695 str[3] = L'\0';
1696 Matcher<const ::wstring&> m4 = StrEq(str);
1697 EXPECT_TRUE(m4.Matches(str));
1698 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1699 Matcher<const ::wstring&> m5 = StrEq(str);
1700 EXPECT_TRUE(m5.Matches(str));
1701}
1702
1703TEST(GlobalWideStrEqTest, CanDescribeSelf) {
vladlosevaa432202011-04-01 21:58:42 +00001704 Matcher< ::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v");
1705 EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"",
shiqiane35fdd92008-12-10 05:08:54 +00001706 Describe(m));
1707
1708 Matcher< ::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D");
1709 EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"",
1710 Describe(m2));
1711
1712 ::wstring str(L"01204500800");
1713 str[3] = L'\0';
1714 Matcher<const ::wstring&> m4 = StrEq(str);
1715 EXPECT_EQ("is equal to L\"012\\04500800\"", Describe(m4));
1716 str[0] = str[6] = str[7] = str[9] = str[10] = L'\0';
1717 Matcher<const ::wstring&> m5 = StrEq(str);
1718 EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"", Describe(m5));
1719}
1720
1721TEST(GlobalWideStrNeTest, MatchesUnequalString) {
1722 Matcher<const wchar_t*> m = StrNe(L"Hello");
1723 EXPECT_TRUE(m.Matches(L""));
1724 EXPECT_TRUE(m.Matches(NULL));
1725 EXPECT_FALSE(m.Matches(L"Hello"));
1726
1727 Matcher< ::wstring> m2 = StrNe(::wstring(L"Hello"));
1728 EXPECT_TRUE(m2.Matches(L"hello"));
1729 EXPECT_FALSE(m2.Matches(L"Hello"));
1730}
1731
1732TEST(GlobalWideStrNeTest, CanDescribeSelf) {
1733 Matcher<const wchar_t*> m = StrNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001734 EXPECT_EQ("isn't equal to L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001735}
1736
1737TEST(GlobalWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {
1738 Matcher<const wchar_t*> m = StrCaseEq(::wstring(L"Hello"));
1739 EXPECT_TRUE(m.Matches(L"Hello"));
1740 EXPECT_TRUE(m.Matches(L"hello"));
1741 EXPECT_FALSE(m.Matches(L"Hi"));
1742 EXPECT_FALSE(m.Matches(NULL));
1743
1744 Matcher<const ::wstring&> m2 = StrCaseEq(L"Hello");
1745 EXPECT_TRUE(m2.Matches(L"hello"));
1746 EXPECT_FALSE(m2.Matches(L"Hi"));
1747}
1748
1749TEST(GlobalWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {
1750 ::wstring str1(L"oabocdooeoo");
1751 ::wstring str2(L"OABOCDOOEOO");
1752 Matcher<const ::wstring&> m0 = StrCaseEq(str1);
1753 EXPECT_FALSE(m0.Matches(str2 + ::wstring(1, L'\0')));
1754
1755 str1[3] = str2[3] = L'\0';
1756 Matcher<const ::wstring&> m1 = StrCaseEq(str1);
1757 EXPECT_TRUE(m1.Matches(str2));
1758
1759 str1[0] = str1[6] = str1[7] = str1[10] = L'\0';
1760 str2[0] = str2[6] = str2[7] = str2[10] = L'\0';
1761 Matcher<const ::wstring&> m2 = StrCaseEq(str1);
1762 str1[9] = str2[9] = L'\0';
1763 EXPECT_FALSE(m2.Matches(str2));
1764
1765 Matcher<const ::wstring&> m3 = StrCaseEq(str1);
1766 EXPECT_TRUE(m3.Matches(str2));
1767
1768 EXPECT_FALSE(m3.Matches(str2 + L"x"));
1769 str2.append(1, L'\0');
1770 EXPECT_FALSE(m3.Matches(str2));
1771 EXPECT_FALSE(m3.Matches(::wstring(str2, 0, 9)));
1772}
1773
1774TEST(GlobalWideStrCaseEqTest, CanDescribeSelf) {
1775 Matcher< ::wstring> m = StrCaseEq(L"Hi");
1776 EXPECT_EQ("is equal to (ignoring case) L\"Hi\"", Describe(m));
1777}
1778
1779TEST(GlobalWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {
1780 Matcher<const wchar_t*> m = StrCaseNe(L"Hello");
1781 EXPECT_TRUE(m.Matches(L"Hi"));
1782 EXPECT_TRUE(m.Matches(NULL));
1783 EXPECT_FALSE(m.Matches(L"Hello"));
1784 EXPECT_FALSE(m.Matches(L"hello"));
1785
1786 Matcher< ::wstring> m2 = StrCaseNe(::wstring(L"Hello"));
1787 EXPECT_TRUE(m2.Matches(L""));
1788 EXPECT_FALSE(m2.Matches(L"Hello"));
1789}
1790
1791TEST(GlobalWideStrCaseNeTest, CanDescribeSelf) {
1792 Matcher<const wchar_t*> m = StrCaseNe(L"Hi");
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001793 EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001794}
1795
1796// Tests that HasSubstr() works for matching wstring-typed values.
1797TEST(GlobalWideHasSubstrTest, WorksForStringClasses) {
1798 const Matcher< ::wstring> m1 = HasSubstr(L"foo");
1799 EXPECT_TRUE(m1.Matches(::wstring(L"I love food.")));
1800 EXPECT_FALSE(m1.Matches(::wstring(L"tofo")));
1801
1802 const Matcher<const ::wstring&> m2 = HasSubstr(L"foo");
1803 EXPECT_TRUE(m2.Matches(::wstring(L"I love food.")));
1804 EXPECT_FALSE(m2.Matches(::wstring(L"tofo")));
1805}
1806
1807// Tests that HasSubstr() works for matching C-wide-string-typed values.
1808TEST(GlobalWideHasSubstrTest, WorksForCStrings) {
1809 const Matcher<wchar_t*> m1 = HasSubstr(L"foo");
1810 EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food.")));
1811 EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo")));
1812 EXPECT_FALSE(m1.Matches(NULL));
1813
1814 const Matcher<const wchar_t*> m2 = HasSubstr(L"foo");
1815 EXPECT_TRUE(m2.Matches(L"I love food."));
1816 EXPECT_FALSE(m2.Matches(L"tofo"));
1817 EXPECT_FALSE(m2.Matches(NULL));
1818}
1819
1820// Tests that HasSubstr(s) describes itself properly.
1821TEST(GlobalWideHasSubstrTest, CanDescribeSelf) {
1822 Matcher< ::wstring> m = HasSubstr(L"foo\n\"");
1823 EXPECT_EQ("has substring L\"foo\\n\\\"\"", Describe(m));
1824}
1825
1826// Tests StartsWith(s).
1827
1828TEST(GlobalWideStartsWithTest, MatchesStringWithGivenPrefix) {
1829 const Matcher<const wchar_t*> m1 = StartsWith(::wstring(L""));
1830 EXPECT_TRUE(m1.Matches(L"Hi"));
1831 EXPECT_TRUE(m1.Matches(L""));
1832 EXPECT_FALSE(m1.Matches(NULL));
1833
1834 const Matcher<const ::wstring&> m2 = StartsWith(L"Hi");
1835 EXPECT_TRUE(m2.Matches(L"Hi"));
1836 EXPECT_TRUE(m2.Matches(L"Hi Hi!"));
1837 EXPECT_TRUE(m2.Matches(L"High"));
1838 EXPECT_FALSE(m2.Matches(L"H"));
1839 EXPECT_FALSE(m2.Matches(L" Hi"));
1840}
1841
1842TEST(GlobalWideStartsWithTest, CanDescribeSelf) {
1843 Matcher<const ::wstring> m = StartsWith(L"Hi");
1844 EXPECT_EQ("starts with L\"Hi\"", Describe(m));
1845}
1846
1847// Tests EndsWith(s).
1848
1849TEST(GlobalWideEndsWithTest, MatchesStringWithGivenSuffix) {
1850 const Matcher<const wchar_t*> m1 = EndsWith(L"");
1851 EXPECT_TRUE(m1.Matches(L"Hi"));
1852 EXPECT_TRUE(m1.Matches(L""));
1853 EXPECT_FALSE(m1.Matches(NULL));
1854
1855 const Matcher<const ::wstring&> m2 = EndsWith(::wstring(L"Hi"));
1856 EXPECT_TRUE(m2.Matches(L"Hi"));
1857 EXPECT_TRUE(m2.Matches(L"Wow Hi Hi"));
1858 EXPECT_TRUE(m2.Matches(L"Super Hi"));
1859 EXPECT_FALSE(m2.Matches(L"i"));
1860 EXPECT_FALSE(m2.Matches(L"Hi "));
1861}
1862
1863TEST(GlobalWideEndsWithTest, CanDescribeSelf) {
1864 Matcher<const ::wstring> m = EndsWith(L"Hi");
1865 EXPECT_EQ("ends with L\"Hi\"", Describe(m));
1866}
1867
1868#endif // GTEST_HAS_GLOBAL_WSTRING
1869
1870
1871typedef ::std::tr1::tuple<long, int> Tuple2; // NOLINT
1872
1873// Tests that Eq() matches a 2-tuple where the first field == the
1874// second field.
1875TEST(Eq2Test, MatchesEqualArguments) {
1876 Matcher<const Tuple2&> m = Eq();
1877 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1878 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1879}
1880
1881// Tests that Eq() describes itself properly.
1882TEST(Eq2Test, CanDescribeSelf) {
1883 Matcher<const Tuple2&> m = Eq();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001884 EXPECT_EQ("are an equal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001885}
1886
1887// Tests that Ge() matches a 2-tuple where the first field >= the
1888// second field.
1889TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {
1890 Matcher<const Tuple2&> m = Ge();
1891 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1892 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1893 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1894}
1895
1896// Tests that Ge() describes itself properly.
1897TEST(Ge2Test, CanDescribeSelf) {
1898 Matcher<const Tuple2&> m = Ge();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001899 EXPECT_EQ("are a pair where the first >= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001900}
1901
1902// Tests that Gt() matches a 2-tuple where the first field > the
1903// second field.
1904TEST(Gt2Test, MatchesGreaterThanArguments) {
1905 Matcher<const Tuple2&> m = Gt();
1906 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1907 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1908 EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));
1909}
1910
1911// Tests that Gt() describes itself properly.
1912TEST(Gt2Test, CanDescribeSelf) {
1913 Matcher<const Tuple2&> m = Gt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001914 EXPECT_EQ("are a pair where the first > the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001915}
1916
1917// Tests that Le() matches a 2-tuple where the first field <= the
1918// second field.
1919TEST(Le2Test, MatchesLessThanOrEqualArguments) {
1920 Matcher<const Tuple2&> m = Le();
1921 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1922 EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));
1923 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1924}
1925
1926// Tests that Le() describes itself properly.
1927TEST(Le2Test, CanDescribeSelf) {
1928 Matcher<const Tuple2&> m = Le();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001929 EXPECT_EQ("are a pair where the first <= the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001930}
1931
1932// Tests that Lt() matches a 2-tuple where the first field < the
1933// second field.
1934TEST(Lt2Test, MatchesLessThanArguments) {
1935 Matcher<const Tuple2&> m = Lt();
1936 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1937 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1938 EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));
1939}
1940
1941// Tests that Lt() describes itself properly.
1942TEST(Lt2Test, CanDescribeSelf) {
1943 Matcher<const Tuple2&> m = Lt();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001944 EXPECT_EQ("are a pair where the first < the second", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001945}
1946
1947// Tests that Ne() matches a 2-tuple where the first field != the
1948// second field.
1949TEST(Ne2Test, MatchesUnequalArguments) {
1950 Matcher<const Tuple2&> m = Ne();
1951 EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));
1952 EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));
1953 EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));
1954}
1955
1956// Tests that Ne() describes itself properly.
1957TEST(Ne2Test, CanDescribeSelf) {
1958 Matcher<const Tuple2&> m = Ne();
zhanyong.wanab5b77c2010-05-17 19:32:48 +00001959 EXPECT_EQ("are an unequal pair", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001960}
1961
1962// Tests that Not(m) matches any value that doesn't match m.
1963TEST(NotTest, NegatesMatcher) {
1964 Matcher<int> m;
1965 m = Not(Eq(2));
1966 EXPECT_TRUE(m.Matches(3));
1967 EXPECT_FALSE(m.Matches(2));
1968}
1969
1970// Tests that Not(m) describes itself properly.
1971TEST(NotTest, CanDescribeSelf) {
1972 Matcher<int> m = Not(Eq(5));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001973 EXPECT_EQ("isn't equal to 5", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00001974}
1975
zhanyong.wan18490652009-05-11 18:54:08 +00001976// Tests that monomorphic matchers are safely cast by the Not matcher.
1977TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {
1978 // greater_than_5 is a monomorphic matcher.
1979 Matcher<int> greater_than_5 = Gt(5);
1980
1981 Matcher<const int&> m = Not(greater_than_5);
1982 Matcher<int&> m2 = Not(greater_than_5);
1983 Matcher<int&> m3 = Not(m);
1984}
1985
zhanyong.wan02c15052010-06-09 19:21:30 +00001986// Helper to allow easy testing of AllOf matchers with num parameters.
1987void AllOfMatches(int num, const Matcher<int>& m) {
1988 SCOPED_TRACE(Describe(m));
1989 EXPECT_TRUE(m.Matches(0));
1990 for (int i = 1; i <= num; ++i) {
1991 EXPECT_FALSE(m.Matches(i));
1992 }
1993 EXPECT_TRUE(m.Matches(num + 1));
1994}
1995
shiqiane35fdd92008-12-10 05:08:54 +00001996// Tests that AllOf(m1, ..., mn) matches any value that matches all of
1997// the given matchers.
1998TEST(AllOfTest, MatchesWhenAllMatch) {
1999 Matcher<int> m;
2000 m = AllOf(Le(2), Ge(1));
2001 EXPECT_TRUE(m.Matches(1));
2002 EXPECT_TRUE(m.Matches(2));
2003 EXPECT_FALSE(m.Matches(0));
2004 EXPECT_FALSE(m.Matches(3));
2005
2006 m = AllOf(Gt(0), Ne(1), Ne(2));
2007 EXPECT_TRUE(m.Matches(3));
2008 EXPECT_FALSE(m.Matches(2));
2009 EXPECT_FALSE(m.Matches(1));
2010 EXPECT_FALSE(m.Matches(0));
2011
2012 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
2013 EXPECT_TRUE(m.Matches(4));
2014 EXPECT_FALSE(m.Matches(3));
2015 EXPECT_FALSE(m.Matches(2));
2016 EXPECT_FALSE(m.Matches(1));
2017 EXPECT_FALSE(m.Matches(0));
2018
2019 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
2020 EXPECT_TRUE(m.Matches(0));
2021 EXPECT_TRUE(m.Matches(1));
2022 EXPECT_FALSE(m.Matches(3));
zhanyong.wan02c15052010-06-09 19:21:30 +00002023
2024 // The following tests for varying number of sub-matchers. Due to the way
2025 // the sub-matchers are handled it is enough to test every sub-matcher once
2026 // with sub-matchers using the same matcher type. Varying matcher types are
2027 // checked for above.
2028 AllOfMatches(2, AllOf(Ne(1), Ne(2)));
2029 AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));
2030 AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));
2031 AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));
2032 AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));
2033 AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));
2034 AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2035 Ne(8)));
2036 AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7),
2037 Ne(8), Ne(9)));
2038 AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2039 Ne(9), Ne(10)));
shiqiane35fdd92008-12-10 05:08:54 +00002040}
2041
zhanyong.wan616180e2013-06-18 18:49:51 +00002042#if GTEST_LANG_CXX11
2043// Tests the variadic version of the AllOfMatcher.
2044TEST(AllOfTest, VariadicMatchesWhenAllMatch) {
2045 // Make sure AllOf is defined in the right namespace and does not depend on
2046 // ADL.
2047 ::testing::AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2048 Matcher<int> m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2049 Ne(9), Ne(10), Ne(11));
2050 EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11))))))))))"));
2051 AllOfMatches(11, m);
2052 AllOfMatches(50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),
2053 Ne(9), Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15),
2054 Ne(16), Ne(17), Ne(18), Ne(19), Ne(20), Ne(21), Ne(22),
2055 Ne(23), Ne(24), Ne(25), Ne(26), Ne(27), Ne(28), Ne(29),
2056 Ne(30), Ne(31), Ne(32), Ne(33), Ne(34), Ne(35), Ne(36),
2057 Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), Ne(42), Ne(43),
2058 Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),
2059 Ne(50)));
2060}
2061
2062#endif // GTEST_LANG_CXX11
2063
shiqiane35fdd92008-12-10 05:08:54 +00002064// Tests that AllOf(m1, ..., mn) describes itself properly.
2065TEST(AllOfTest, CanDescribeSelf) {
2066 Matcher<int> m;
2067 m = AllOf(Le(2), Ge(1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002068 EXPECT_EQ("(is <= 2) and (is >= 1)", Describe(m));
shiqiane35fdd92008-12-10 05:08:54 +00002069
2070 m = AllOf(Gt(0), Ne(1), Ne(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002071 EXPECT_EQ("(is > 0) and "
2072 "((isn't equal to 1) and "
2073 "(isn't equal to 2))",
shiqiane35fdd92008-12-10 05:08:54 +00002074 Describe(m));
2075
2076
2077 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002078 EXPECT_EQ("((is > 0) and "
2079 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002080 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002081 "(isn't equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002082 Describe(m));
2083
2084
2085 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002086 EXPECT_EQ("((is >= 0) and "
2087 "(is < 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002088 "((isn't equal to 3) and "
2089 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002090 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002091 Describe(m));
2092}
2093
2094// Tests that AllOf(m1, ..., mn) describes its negation properly.
2095TEST(AllOfTest, CanDescribeNegation) {
2096 Matcher<int> m;
2097 m = AllOf(Le(2), Ge(1));
2098 EXPECT_EQ("(isn't <= 2) or "
2099 "(isn't >= 1)",
2100 DescribeNegation(m));
2101
2102 m = AllOf(Gt(0), Ne(1), Ne(2));
2103 EXPECT_EQ("(isn't > 0) or "
2104 "((is equal to 1) or "
2105 "(is equal to 2))",
2106 DescribeNegation(m));
2107
2108
2109 m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));
jgm79a367e2012-04-10 16:02:11 +00002110 EXPECT_EQ("((isn't > 0) or "
2111 "(is equal to 1)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002112 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002113 "(is equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002114 DescribeNegation(m));
2115
2116
2117 m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));
jgm79a367e2012-04-10 16:02:11 +00002118 EXPECT_EQ("((isn't >= 0) or "
2119 "(isn't < 10)) or "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002120 "((is equal to 3) or "
2121 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002122 "(is equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002123 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00002124}
2125
zhanyong.wan18490652009-05-11 18:54:08 +00002126// Tests that monomorphic matchers are safely cast by the AllOf matcher.
2127TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {
2128 // greater_than_5 and less_than_10 are monomorphic matchers.
2129 Matcher<int> greater_than_5 = Gt(5);
2130 Matcher<int> less_than_10 = Lt(10);
2131
2132 Matcher<const int&> m = AllOf(greater_than_5, less_than_10);
2133 Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);
2134 Matcher<int&> m3 = AllOf(greater_than_5, m2);
2135
2136 // Tests that BothOf works when composing itself.
2137 Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);
2138 Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);
2139}
2140
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002141TEST(AllOfTest, ExplainsResult) {
2142 Matcher<int> m;
2143
2144 // Successful match. Both matchers need to explain. The second
2145 // matcher doesn't give an explanation, so only the first matcher's
2146 // explanation is printed.
2147 m = AllOf(GreaterThan(10), Lt(30));
2148 EXPECT_EQ("which is 15 more than 10", Explain(m, 25));
2149
2150 // Successful match. Both matchers need to explain.
2151 m = AllOf(GreaterThan(10), GreaterThan(20));
2152 EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20",
2153 Explain(m, 30));
2154
2155 // Successful match. All matchers need to explain. The second
2156 // matcher doesn't given an explanation.
2157 m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));
2158 EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20",
2159 Explain(m, 25));
2160
2161 // Successful match. All matchers need to explain.
2162 m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2163 EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, "
2164 "and which is 10 more than 30",
2165 Explain(m, 40));
2166
2167 // Failed match. The first matcher, which failed, needs to
2168 // explain.
2169 m = AllOf(GreaterThan(10), GreaterThan(20));
2170 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2171
2172 // Failed match. The second matcher, which failed, needs to
2173 // explain. Since it doesn't given an explanation, nothing is
2174 // printed.
2175 m = AllOf(GreaterThan(10), Lt(30));
2176 EXPECT_EQ("", Explain(m, 40));
2177
2178 // Failed match. The second matcher, which failed, needs to
2179 // explain.
2180 m = AllOf(GreaterThan(10), GreaterThan(20));
2181 EXPECT_EQ("which is 5 less than 20", Explain(m, 15));
2182}
2183
zhanyong.wan02c15052010-06-09 19:21:30 +00002184// Helper to allow easy testing of AnyOf matchers with num parameters.
2185void AnyOfMatches(int num, const Matcher<int>& m) {
2186 SCOPED_TRACE(Describe(m));
2187 EXPECT_FALSE(m.Matches(0));
2188 for (int i = 1; i <= num; ++i) {
2189 EXPECT_TRUE(m.Matches(i));
2190 }
2191 EXPECT_FALSE(m.Matches(num + 1));
2192}
2193
shiqiane35fdd92008-12-10 05:08:54 +00002194// Tests that AnyOf(m1, ..., mn) matches any value that matches at
2195// least one of the given matchers.
2196TEST(AnyOfTest, MatchesWhenAnyMatches) {
2197 Matcher<int> m;
2198 m = AnyOf(Le(1), Ge(3));
2199 EXPECT_TRUE(m.Matches(1));
2200 EXPECT_TRUE(m.Matches(4));
2201 EXPECT_FALSE(m.Matches(2));
2202
2203 m = AnyOf(Lt(0), Eq(1), Eq(2));
2204 EXPECT_TRUE(m.Matches(-1));
2205 EXPECT_TRUE(m.Matches(1));
2206 EXPECT_TRUE(m.Matches(2));
2207 EXPECT_FALSE(m.Matches(0));
2208
2209 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
2210 EXPECT_TRUE(m.Matches(-1));
2211 EXPECT_TRUE(m.Matches(1));
2212 EXPECT_TRUE(m.Matches(2));
2213 EXPECT_TRUE(m.Matches(3));
2214 EXPECT_FALSE(m.Matches(0));
2215
2216 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
2217 EXPECT_TRUE(m.Matches(0));
2218 EXPECT_TRUE(m.Matches(11));
2219 EXPECT_TRUE(m.Matches(3));
2220 EXPECT_FALSE(m.Matches(2));
zhanyong.wan02c15052010-06-09 19:21:30 +00002221
2222 // The following tests for varying number of sub-matchers. Due to the way
2223 // the sub-matchers are handled it is enough to test every sub-matcher once
2224 // with sub-matchers using the same matcher type. Varying matcher types are
2225 // checked for above.
2226 AnyOfMatches(2, AnyOf(1, 2));
2227 AnyOfMatches(3, AnyOf(1, 2, 3));
2228 AnyOfMatches(4, AnyOf(1, 2, 3, 4));
2229 AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));
2230 AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));
2231 AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));
2232 AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));
2233 AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));
2234 AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
shiqiane35fdd92008-12-10 05:08:54 +00002235}
2236
zhanyong.wan616180e2013-06-18 18:49:51 +00002237#if GTEST_LANG_CXX11
2238// Tests the variadic version of the AnyOfMatcher.
2239TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {
2240 // Also make sure AnyOf is defined in the right namespace and does not depend
2241 // on ADL.
2242 Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
2243
2244 EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11))))))))))"));
2245 AnyOfMatches(11, m);
2246 AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2247 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
2248 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
2249 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
2250 41, 42, 43, 44, 45, 46, 47, 48, 49, 50));
2251}
2252
2253#endif // GTEST_LANG_CXX11
2254
shiqiane35fdd92008-12-10 05:08:54 +00002255// Tests that AnyOf(m1, ..., mn) describes itself properly.
2256TEST(AnyOfTest, CanDescribeSelf) {
2257 Matcher<int> m;
2258 m = AnyOf(Le(1), Ge(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002259 EXPECT_EQ("(is <= 1) or (is >= 3)",
shiqiane35fdd92008-12-10 05:08:54 +00002260 Describe(m));
2261
2262 m = AnyOf(Lt(0), Eq(1), Eq(2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002263 EXPECT_EQ("(is < 0) or "
shiqiane35fdd92008-12-10 05:08:54 +00002264 "((is equal to 1) or (is equal to 2))",
2265 Describe(m));
2266
2267 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002268 EXPECT_EQ("((is < 0) or "
2269 "(is equal to 1)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002270 "((is equal to 2) or "
jgm79a367e2012-04-10 16:02:11 +00002271 "(is equal to 3))",
shiqiane35fdd92008-12-10 05:08:54 +00002272 Describe(m));
2273
2274 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002275 EXPECT_EQ("((is <= 0) or "
2276 "(is > 10)) or "
shiqiane35fdd92008-12-10 05:08:54 +00002277 "((is equal to 3) or "
2278 "((is equal to 5) or "
jgm79a367e2012-04-10 16:02:11 +00002279 "(is equal to 7)))",
shiqiane35fdd92008-12-10 05:08:54 +00002280 Describe(m));
2281}
2282
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002283// Tests that AnyOf(m1, ..., mn) describes its negation properly.
2284TEST(AnyOfTest, CanDescribeNegation) {
2285 Matcher<int> m;
2286 m = AnyOf(Le(1), Ge(3));
2287 EXPECT_EQ("(isn't <= 1) and (isn't >= 3)",
2288 DescribeNegation(m));
2289
2290 m = AnyOf(Lt(0), Eq(1), Eq(2));
2291 EXPECT_EQ("(isn't < 0) and "
2292 "((isn't equal to 1) and (isn't equal to 2))",
2293 DescribeNegation(m));
2294
2295 m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));
jgm79a367e2012-04-10 16:02:11 +00002296 EXPECT_EQ("((isn't < 0) and "
2297 "(isn't equal to 1)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002298 "((isn't equal to 2) and "
jgm79a367e2012-04-10 16:02:11 +00002299 "(isn't equal to 3))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002300 DescribeNegation(m));
2301
2302 m = AnyOf(Le(0), Gt(10), 3, 5, 7);
jgm79a367e2012-04-10 16:02:11 +00002303 EXPECT_EQ("((isn't <= 0) and "
2304 "(isn't > 10)) and "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002305 "((isn't equal to 3) and "
2306 "((isn't equal to 5) and "
jgm79a367e2012-04-10 16:02:11 +00002307 "(isn't equal to 7)))",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002308 DescribeNegation(m));
2309}
2310
zhanyong.wan18490652009-05-11 18:54:08 +00002311// Tests that monomorphic matchers are safely cast by the AnyOf matcher.
2312TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {
2313 // greater_than_5 and less_than_10 are monomorphic matchers.
2314 Matcher<int> greater_than_5 = Gt(5);
2315 Matcher<int> less_than_10 = Lt(10);
2316
2317 Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);
2318 Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);
2319 Matcher<int&> m3 = AnyOf(greater_than_5, m2);
2320
2321 // Tests that EitherOf works when composing itself.
2322 Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);
2323 Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);
2324}
2325
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002326TEST(AnyOfTest, ExplainsResult) {
2327 Matcher<int> m;
2328
2329 // Failed match. Both matchers need to explain. The second
2330 // matcher doesn't give an explanation, so only the first matcher's
2331 // explanation is printed.
2332 m = AnyOf(GreaterThan(10), Lt(0));
2333 EXPECT_EQ("which is 5 less than 10", Explain(m, 5));
2334
2335 // Failed match. Both matchers need to explain.
2336 m = AnyOf(GreaterThan(10), GreaterThan(20));
2337 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20",
2338 Explain(m, 5));
2339
2340 // Failed match. All matchers need to explain. The second
2341 // matcher doesn't given an explanation.
2342 m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));
2343 EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30",
2344 Explain(m, 5));
2345
2346 // Failed match. All matchers need to explain.
2347 m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));
2348 EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, "
2349 "and which is 25 less than 30",
2350 Explain(m, 5));
2351
2352 // Successful match. The first matcher, which succeeded, needs to
2353 // explain.
2354 m = AnyOf(GreaterThan(10), GreaterThan(20));
2355 EXPECT_EQ("which is 5 more than 10", Explain(m, 15));
2356
2357 // Successful match. The second matcher, which succeeded, needs to
2358 // explain. Since it doesn't given an explanation, nothing is
2359 // printed.
2360 m = AnyOf(GreaterThan(10), Lt(30));
2361 EXPECT_EQ("", Explain(m, 0));
2362
2363 // Successful match. The second matcher, which succeeded, needs to
2364 // explain.
2365 m = AnyOf(GreaterThan(30), GreaterThan(20));
2366 EXPECT_EQ("which is 5 more than 20", Explain(m, 25));
2367}
2368
shiqiane35fdd92008-12-10 05:08:54 +00002369// The following predicate function and predicate functor are for
2370// testing the Truly(predicate) matcher.
2371
2372// Returns non-zero if the input is positive. Note that the return
2373// type of this function is not bool. It's OK as Truly() accepts any
2374// unary function or functor whose return type can be implicitly
2375// converted to bool.
2376int IsPositive(double x) {
2377 return x > 0 ? 1 : 0;
2378}
2379
2380// This functor returns true if the input is greater than the given
2381// number.
2382class IsGreaterThan {
2383 public:
2384 explicit IsGreaterThan(int threshold) : threshold_(threshold) {}
2385
2386 bool operator()(int n) const { return n > threshold_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +00002387
shiqiane35fdd92008-12-10 05:08:54 +00002388 private:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002389 int threshold_;
shiqiane35fdd92008-12-10 05:08:54 +00002390};
2391
2392// For testing Truly().
2393const int foo = 0;
2394
2395// This predicate returns true iff the argument references foo and has
2396// a zero value.
2397bool ReferencesFooAndIsZero(const int& n) {
2398 return (&n == &foo) && (n == 0);
2399}
2400
2401// Tests that Truly(predicate) matches what satisfies the given
2402// predicate.
2403TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {
2404 Matcher<double> m = Truly(IsPositive);
2405 EXPECT_TRUE(m.Matches(2.0));
2406 EXPECT_FALSE(m.Matches(-1.5));
2407}
2408
2409// Tests that Truly(predicate_functor) works too.
2410TEST(TrulyTest, CanBeUsedWithFunctor) {
2411 Matcher<int> m = Truly(IsGreaterThan(5));
2412 EXPECT_TRUE(m.Matches(6));
2413 EXPECT_FALSE(m.Matches(4));
2414}
2415
zhanyong.wan8d3dc0c2011-04-14 19:37:06 +00002416// A class that can be implicitly converted to bool.
2417class ConvertibleToBool {
2418 public:
2419 explicit ConvertibleToBool(int number) : number_(number) {}
2420 operator bool() const { return number_ != 0; }
2421
2422 private:
2423 int number_;
2424};
2425
2426ConvertibleToBool IsNotZero(int number) {
2427 return ConvertibleToBool(number);
2428}
2429
2430// Tests that the predicate used in Truly() may return a class that's
2431// implicitly convertible to bool, even when the class has no
2432// operator!().
2433TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {
2434 Matcher<int> m = Truly(IsNotZero);
2435 EXPECT_TRUE(m.Matches(1));
2436 EXPECT_FALSE(m.Matches(0));
2437}
2438
shiqiane35fdd92008-12-10 05:08:54 +00002439// Tests that Truly(predicate) can describe itself properly.
2440TEST(TrulyTest, CanDescribeSelf) {
2441 Matcher<double> m = Truly(IsPositive);
2442 EXPECT_EQ("satisfies the given predicate",
2443 Describe(m));
2444}
2445
2446// Tests that Truly(predicate) works when the matcher takes its
2447// argument by reference.
2448TEST(TrulyTest, WorksForByRefArguments) {
2449 Matcher<const int&> m = Truly(ReferencesFooAndIsZero);
2450 EXPECT_TRUE(m.Matches(foo));
2451 int n = 0;
2452 EXPECT_FALSE(m.Matches(n));
2453}
2454
2455// Tests that Matches(m) is a predicate satisfied by whatever that
2456// matches matcher m.
2457TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {
2458 EXPECT_TRUE(Matches(Ge(0))(1));
2459 EXPECT_FALSE(Matches(Eq('a'))('b'));
2460}
2461
2462// Tests that Matches(m) works when the matcher takes its argument by
2463// reference.
2464TEST(MatchesTest, WorksOnByRefArguments) {
2465 int m = 0, n = 0;
2466 EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));
2467 EXPECT_FALSE(Matches(Ref(m))(n));
2468}
2469
2470// Tests that a Matcher on non-reference type can be used in
2471// Matches().
2472TEST(MatchesTest, WorksWithMatcherOnNonRefType) {
2473 Matcher<int> eq5 = Eq(5);
2474 EXPECT_TRUE(Matches(eq5)(5));
2475 EXPECT_FALSE(Matches(eq5)(2));
2476}
2477
zhanyong.wanb8243162009-06-04 05:48:20 +00002478// Tests Value(value, matcher). Since Value() is a simple wrapper for
2479// Matches(), which has been tested already, we don't spend a lot of
2480// effort on testing Value().
2481TEST(ValueTest, WorksWithPolymorphicMatcher) {
2482 EXPECT_TRUE(Value("hi", StartsWith("h")));
2483 EXPECT_FALSE(Value(5, Gt(10)));
2484}
2485
2486TEST(ValueTest, WorksWithMonomorphicMatcher) {
2487 const Matcher<int> is_zero = Eq(0);
2488 EXPECT_TRUE(Value(0, is_zero));
2489 EXPECT_FALSE(Value('a', is_zero));
2490
2491 int n = 0;
2492 const Matcher<const int&> ref_n = Ref(n);
2493 EXPECT_TRUE(Value(n, ref_n));
2494 EXPECT_FALSE(Value(1, ref_n));
2495}
2496
zhanyong.wana862f1d2010-03-15 21:23:04 +00002497TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002498 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002499 EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002500 EXPECT_EQ("% 2 == 0", listener1.str());
2501
2502 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002503 EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002504 EXPECT_EQ("", listener2.str());
2505}
2506
zhanyong.wana862f1d2010-03-15 21:23:04 +00002507TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {
zhanyong.wan34b034c2010-03-05 21:23:23 +00002508 const Matcher<int> is_even = PolymorphicIsEven();
2509 StringMatchResultListener listener1;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002510 EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002511 EXPECT_EQ("% 2 == 0", listener1.str());
2512
2513 const Matcher<const double&> is_zero = Eq(0);
2514 StringMatchResultListener listener2;
zhanyong.wana862f1d2010-03-15 21:23:04 +00002515 EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));
zhanyong.wan34b034c2010-03-05 21:23:23 +00002516 EXPECT_EQ("", listener2.str());
2517}
2518
zhanyong.wana862f1d2010-03-15 21:23:04 +00002519MATCHER_P(Really, inner_matcher, "") {
2520 return ExplainMatchResult(inner_matcher, arg, result_listener);
2521}
2522
2523TEST(ExplainMatchResultTest, WorksInsideMATCHER) {
2524 EXPECT_THAT(0, Really(Eq(0)));
2525}
2526
zhanyong.wanbf550852009-06-09 06:09:53 +00002527TEST(AllArgsTest, WorksForTuple) {
2528 EXPECT_THAT(make_tuple(1, 2L), AllArgs(Lt()));
2529 EXPECT_THAT(make_tuple(2L, 1), Not(AllArgs(Lt())));
2530}
2531
2532TEST(AllArgsTest, WorksForNonTuple) {
2533 EXPECT_THAT(42, AllArgs(Gt(0)));
2534 EXPECT_THAT('a', Not(AllArgs(Eq('b'))));
2535}
2536
2537class AllArgsHelper {
2538 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00002539 AllArgsHelper() {}
2540
zhanyong.wanbf550852009-06-09 06:09:53 +00002541 MOCK_METHOD2(Helper, int(char x, int y));
zhanyong.wan32de5f52009-12-23 00:13:23 +00002542
2543 private:
2544 GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper);
zhanyong.wanbf550852009-06-09 06:09:53 +00002545};
2546
2547TEST(AllArgsTest, WorksInWithClause) {
2548 AllArgsHelper helper;
2549 ON_CALL(helper, Helper(_, _))
2550 .With(AllArgs(Lt()))
2551 .WillByDefault(Return(1));
2552 EXPECT_CALL(helper, Helper(_, _));
2553 EXPECT_CALL(helper, Helper(_, _))
2554 .With(AllArgs(Gt()))
2555 .WillOnce(Return(2));
2556
2557 EXPECT_EQ(1, helper.Helper('\1', 2));
2558 EXPECT_EQ(2, helper.Helper('a', 1));
2559}
2560
shiqiane35fdd92008-12-10 05:08:54 +00002561// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2562// matches the matcher.
2563TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {
2564 ASSERT_THAT(5, Ge(2)) << "This should succeed.";
2565 ASSERT_THAT("Foo", EndsWith("oo"));
2566 EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too.";
2567 EXPECT_THAT("Hello", StartsWith("Hell"));
2568}
2569
2570// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value
2571// doesn't match the matcher.
2572TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {
2573 // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),
2574 // which cannot reference auto variables.
zhanyong.wan736baa82010-09-27 17:44:16 +00002575 static unsigned short n; // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00002576 n = 5;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002577
2578 // VC++ prior to version 8.0 SP1 has a bug where it will not see any
2579 // functions declared in the namespace scope from within nested classes.
2580 // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all
2581 // namespace-level functions invoked inside them need to be explicitly
2582 // resolved.
2583 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)),
shiqiane35fdd92008-12-10 05:08:54 +00002584 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002585 "Expected: is > 10\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002586 " Actual: 5" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002587 n = 0;
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002588 EXPECT_NONFATAL_FAILURE(
2589 EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))),
2590 "Value of: n\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002591 "Expected: (is <= 7) and (is >= 5)\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002592 " Actual: 0" + OfType("unsigned short"));
shiqiane35fdd92008-12-10 05:08:54 +00002593}
2594
2595// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument
2596// has a reference type.
2597TEST(MatcherAssertionTest, WorksForByRefArguments) {
2598 // We use a static variable here as EXPECT_FATAL_FAILURE() cannot
2599 // reference auto variables.
2600 static int n;
2601 n = 0;
2602 EXPECT_THAT(n, AllOf(Le(7), Ref(n)));
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002603 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
shiqiane35fdd92008-12-10 05:08:54 +00002604 "Value of: n\n"
2605 "Expected: does not reference the variable @");
2606 // Tests the "Actual" part.
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00002607 EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))),
zhanyong.wan736baa82010-09-27 17:44:16 +00002608 "Actual: 0" + OfType("int") + ", which is located @");
shiqiane35fdd92008-12-10 05:08:54 +00002609}
2610
zhanyong.wan95b12332009-09-25 18:55:50 +00002611#if !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002612// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is
2613// monomorphic.
zhanyong.wan95b12332009-09-25 18:55:50 +00002614
2615// ASSERT_THAT("hello", starts_with_he) fails to compile with Nokia's
2616// Symbian compiler: it tries to compile
2617// template<T, U> class MatcherCastImpl { ...
zhanyong.wandb22c222010-01-28 21:52:29 +00002618// virtual bool MatchAndExplain(T x, ...) const {
2619// return source_matcher_.MatchAndExplain(static_cast<U>(x), ...);
zhanyong.wan95b12332009-09-25 18:55:50 +00002620// with U == string and T == const char*
2621// With ASSERT_THAT("hello"...) changed to ASSERT_THAT(string("hello") ... )
2622// the compiler silently crashes with no output.
2623// If MatcherCastImpl is changed to use U(x) instead of static_cast<U>(x)
2624// the code compiles but the converted string is bogus.
shiqiane35fdd92008-12-10 05:08:54 +00002625TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {
2626 Matcher<const char*> starts_with_he = StartsWith("he");
2627 ASSERT_THAT("hello", starts_with_he);
2628
2629 Matcher<const string&> ends_with_ok = EndsWith("ok");
2630 ASSERT_THAT("book", ends_with_ok);
zhanyong.wan736baa82010-09-27 17:44:16 +00002631 const string bad = "bad";
2632 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),
2633 "Value of: bad\n"
2634 "Expected: ends with \"ok\"\n"
2635 " Actual: \"bad\"");
shiqiane35fdd92008-12-10 05:08:54 +00002636 Matcher<int> is_greater_than_5 = Gt(5);
2637 EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),
2638 "Value of: 5\n"
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002639 "Expected: is > 5\n"
zhanyong.wan736baa82010-09-27 17:44:16 +00002640 " Actual: 5" + OfType("int"));
shiqiane35fdd92008-12-10 05:08:54 +00002641}
zhanyong.wan95b12332009-09-25 18:55:50 +00002642#endif // !GTEST_OS_SYMBIAN
shiqiane35fdd92008-12-10 05:08:54 +00002643
2644// Tests floating-point matchers.
2645template <typename RawType>
2646class FloatingPointTest : public testing::Test {
2647 protected:
2648 typedef typename testing::internal::FloatingPoint<RawType> Floating;
2649 typedef typename Floating::Bits Bits;
2650
2651 virtual void SetUp() {
2652 const size_t max_ulps = Floating::kMaxUlps;
2653
2654 // The bits that represent 0.0.
2655 const Bits zero_bits = Floating(0).bits();
2656
2657 // Makes some numbers close to 0.0.
2658 close_to_positive_zero_ = Floating::ReinterpretBits(zero_bits + max_ulps/2);
2659 close_to_negative_zero_ = -Floating::ReinterpretBits(
2660 zero_bits + max_ulps - max_ulps/2);
2661 further_from_negative_zero_ = -Floating::ReinterpretBits(
2662 zero_bits + max_ulps + 1 - max_ulps/2);
2663
2664 // The bits that represent 1.0.
2665 const Bits one_bits = Floating(1).bits();
2666
2667 // Makes some numbers close to 1.0.
2668 close_to_one_ = Floating::ReinterpretBits(one_bits + max_ulps);
2669 further_from_one_ = Floating::ReinterpretBits(one_bits + max_ulps + 1);
2670
2671 // +infinity.
2672 infinity_ = Floating::Infinity();
2673
2674 // The bits that represent +infinity.
2675 const Bits infinity_bits = Floating(infinity_).bits();
2676
2677 // Makes some numbers close to infinity.
2678 close_to_infinity_ = Floating::ReinterpretBits(infinity_bits - max_ulps);
2679 further_from_infinity_ = Floating::ReinterpretBits(
2680 infinity_bits - max_ulps - 1);
2681
2682 // Makes some NAN's.
2683 nan1_ = Floating::ReinterpretBits(Floating::kExponentBitMask | 1);
2684 nan2_ = Floating::ReinterpretBits(Floating::kExponentBitMask | 200);
2685 }
2686
2687 void TestSize() {
2688 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2689 }
2690
2691 // A battery of tests for FloatingEqMatcher::Matches.
2692 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2693 void TestMatches(
2694 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
2695 Matcher<RawType> m1 = matcher_maker(0.0);
2696 EXPECT_TRUE(m1.Matches(-0.0));
2697 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
2698 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
2699 EXPECT_FALSE(m1.Matches(1.0));
2700
2701 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
2702 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
2703
2704 Matcher<RawType> m3 = matcher_maker(1.0);
2705 EXPECT_TRUE(m3.Matches(close_to_one_));
2706 EXPECT_FALSE(m3.Matches(further_from_one_));
2707
2708 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
2709 EXPECT_FALSE(m3.Matches(0.0));
2710
2711 Matcher<RawType> m4 = matcher_maker(-infinity_);
2712 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
2713
2714 Matcher<RawType> m5 = matcher_maker(infinity_);
2715 EXPECT_TRUE(m5.Matches(close_to_infinity_));
2716
2717 // This is interesting as the representations of infinity_ and nan1_
2718 // are only 1 DLP apart.
2719 EXPECT_FALSE(m5.Matches(nan1_));
2720
2721 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2722 // some cases.
2723 Matcher<const RawType&> m6 = matcher_maker(0.0);
2724 EXPECT_TRUE(m6.Matches(-0.0));
2725 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
2726 EXPECT_FALSE(m6.Matches(1.0));
2727
2728 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2729 // cases.
2730 Matcher<RawType&> m7 = matcher_maker(0.0);
2731 RawType x = 0.0;
2732 EXPECT_TRUE(m7.Matches(x));
2733 x = 0.01f;
2734 EXPECT_FALSE(m7.Matches(x));
2735 }
2736
2737 // Pre-calculated numbers to be used by the tests.
2738
2739 static RawType close_to_positive_zero_;
2740 static RawType close_to_negative_zero_;
2741 static RawType further_from_negative_zero_;
2742
2743 static RawType close_to_one_;
2744 static RawType further_from_one_;
2745
2746 static RawType infinity_;
2747 static RawType close_to_infinity_;
2748 static RawType further_from_infinity_;
2749
2750 static RawType nan1_;
2751 static RawType nan2_;
2752};
2753
2754template <typename RawType>
2755RawType FloatingPointTest<RawType>::close_to_positive_zero_;
2756
2757template <typename RawType>
2758RawType FloatingPointTest<RawType>::close_to_negative_zero_;
2759
2760template <typename RawType>
2761RawType FloatingPointTest<RawType>::further_from_negative_zero_;
2762
2763template <typename RawType>
2764RawType FloatingPointTest<RawType>::close_to_one_;
2765
2766template <typename RawType>
2767RawType FloatingPointTest<RawType>::further_from_one_;
2768
2769template <typename RawType>
2770RawType FloatingPointTest<RawType>::infinity_;
2771
2772template <typename RawType>
2773RawType FloatingPointTest<RawType>::close_to_infinity_;
2774
2775template <typename RawType>
2776RawType FloatingPointTest<RawType>::further_from_infinity_;
2777
2778template <typename RawType>
2779RawType FloatingPointTest<RawType>::nan1_;
2780
2781template <typename RawType>
2782RawType FloatingPointTest<RawType>::nan2_;
2783
zhanyong.wan616180e2013-06-18 18:49:51 +00002784// Tests floating-point matchers with fixed epsilons.
2785template <typename RawType>
2786class FloatingPointNearTest : public FloatingPointTest<RawType> {
2787 protected:
2788 typedef FloatingPointTest<RawType> ParentType;
2789
2790 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
2791 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2792 void TestNearMatches(
2793 testing::internal::FloatingEqMatcher<RawType>
2794 (*matcher_maker)(RawType, RawType)) {
2795 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
2796 EXPECT_TRUE(m1.Matches(0.0));
2797 EXPECT_TRUE(m1.Matches(-0.0));
2798 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
2799 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
2800 EXPECT_FALSE(m1.Matches(1.0));
2801
2802 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
2803 EXPECT_TRUE(m2.Matches(0.0));
2804 EXPECT_TRUE(m2.Matches(-0.0));
2805 EXPECT_TRUE(m2.Matches(1.0));
2806 EXPECT_TRUE(m2.Matches(-1.0));
2807 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
2808 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
2809
2810 // Check that inf matches inf, regardless of the of the specified max
2811 // absolute error.
2812 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
2813 EXPECT_TRUE(m3.Matches(ParentType::infinity_));
2814 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
2815 EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
2816
2817 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
2818 EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
2819 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
2820 EXPECT_FALSE(m4.Matches(ParentType::infinity_));
2821
2822 // Test various overflow scenarios.
2823 Matcher<RawType> m5 = matcher_maker(
2824 std::numeric_limits<RawType>::max(),
2825 std::numeric_limits<RawType>::max());
2826 EXPECT_TRUE(m5.Matches(std::numeric_limits<RawType>::max()));
2827 EXPECT_FALSE(m5.Matches(-std::numeric_limits<RawType>::max()));
2828
2829 Matcher<RawType> m6 = matcher_maker(
2830 -std::numeric_limits<RawType>::max(),
2831 std::numeric_limits<RawType>::max());
2832 EXPECT_FALSE(m6.Matches(std::numeric_limits<RawType>::max()));
2833 EXPECT_TRUE(m6.Matches(-std::numeric_limits<RawType>::max()));
2834
2835 Matcher<RawType> m7 = matcher_maker(std::numeric_limits<RawType>::max(), 0);
2836 EXPECT_TRUE(m7.Matches(std::numeric_limits<RawType>::max()));
2837 EXPECT_FALSE(m7.Matches(-std::numeric_limits<RawType>::max()));
2838
2839 Matcher<RawType> m8 = matcher_maker(
2840 -std::numeric_limits<RawType>::max(), 0);
2841 EXPECT_FALSE(m8.Matches(std::numeric_limits<RawType>::max()));
2842 EXPECT_TRUE(m8.Matches(-std::numeric_limits<RawType>::max()));
2843
2844 // The difference between max() and -max() normally overflows to infinity,
2845 // but it should still match if the max_abs_error is also infinity.
2846 Matcher<RawType> m9 = matcher_maker(
2847 std::numeric_limits<RawType>::max(), ParentType::infinity_);
2848 EXPECT_TRUE(m8.Matches(-std::numeric_limits<RawType>::max()));
2849
2850 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2851 // some cases.
2852 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
2853 EXPECT_TRUE(m10.Matches(-0.0));
2854 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
2855 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
2856
2857 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2858 // cases.
2859 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
2860 RawType x = 0.0;
2861 EXPECT_TRUE(m11.Matches(x));
2862 x = 1.0f;
2863 EXPECT_TRUE(m11.Matches(x));
2864 x = -1.0f;
2865 EXPECT_TRUE(m11.Matches(x));
2866 x = 1.1f;
2867 EXPECT_FALSE(m11.Matches(x));
2868 x = -1.1f;
2869 EXPECT_FALSE(m11.Matches(x));
2870 }
2871};
2872
shiqiane35fdd92008-12-10 05:08:54 +00002873// Instantiate FloatingPointTest for testing floats.
2874typedef FloatingPointTest<float> FloatTest;
2875
2876TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
2877 TestMatches(&FloatEq);
2878}
2879
2880TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
2881 TestMatches(&NanSensitiveFloatEq);
2882}
2883
2884TEST_F(FloatTest, FloatEqCannotMatchNaN) {
2885 // FloatEq never matches NaN.
2886 Matcher<float> m = FloatEq(nan1_);
2887 EXPECT_FALSE(m.Matches(nan1_));
2888 EXPECT_FALSE(m.Matches(nan2_));
2889 EXPECT_FALSE(m.Matches(1.0));
2890}
2891
2892TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
2893 // NanSensitiveFloatEq will match NaN.
2894 Matcher<float> m = NanSensitiveFloatEq(nan1_);
2895 EXPECT_TRUE(m.Matches(nan1_));
2896 EXPECT_TRUE(m.Matches(nan2_));
2897 EXPECT_FALSE(m.Matches(1.0));
2898}
2899
2900TEST_F(FloatTest, FloatEqCanDescribeSelf) {
2901 Matcher<float> m1 = FloatEq(2.0f);
2902 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002903 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002904
2905 Matcher<float> m2 = FloatEq(0.5f);
2906 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002907 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002908
2909 Matcher<float> m3 = FloatEq(nan1_);
2910 EXPECT_EQ("never matches", Describe(m3));
2911 EXPECT_EQ("is anything", DescribeNegation(m3));
2912}
2913
2914TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
2915 Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
2916 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002917 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002918
2919 Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
2920 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002921 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002922
2923 Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
2924 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002925 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00002926}
2927
zhanyong.wan616180e2013-06-18 18:49:51 +00002928// Instantiate FloatingPointTest for testing floats with a user-specified
2929// max absolute error.
2930typedef FloatingPointNearTest<float> FloatNearTest;
2931
2932TEST_F(FloatNearTest, FloatNearMatches) {
2933 TestNearMatches(&FloatNear);
2934}
2935
2936TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
2937 TestNearMatches(&NanSensitiveFloatNear);
2938}
2939
2940TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
2941 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
2942 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2943 EXPECT_EQ(
2944 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2945
2946 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
2947 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2948 EXPECT_EQ(
2949 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2950
2951 Matcher<float> m3 = FloatNear(nan1_, 0.0);
2952 EXPECT_EQ("never matches", Describe(m3));
2953 EXPECT_EQ("is anything", DescribeNegation(m3));
2954}
2955
2956TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
2957 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
2958 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2959 EXPECT_EQ(
2960 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2961
2962 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
2963 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2964 EXPECT_EQ(
2965 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2966
2967 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
2968 EXPECT_EQ("is NaN", Describe(m3));
2969 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
2970}
2971
2972TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
2973 // FloatNear never matches NaN.
2974 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
2975 EXPECT_FALSE(m.Matches(nan1_));
2976 EXPECT_FALSE(m.Matches(nan2_));
2977 EXPECT_FALSE(m.Matches(1.0));
2978}
2979
2980TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
2981 // NanSensitiveFloatNear will match NaN.
2982 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
2983 EXPECT_TRUE(m.Matches(nan1_));
2984 EXPECT_TRUE(m.Matches(nan2_));
2985 EXPECT_FALSE(m.Matches(1.0));
2986}
2987
shiqiane35fdd92008-12-10 05:08:54 +00002988// Instantiate FloatingPointTest for testing doubles.
2989typedef FloatingPointTest<double> DoubleTest;
2990
2991TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
2992 TestMatches(&DoubleEq);
2993}
2994
2995TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
2996 TestMatches(&NanSensitiveDoubleEq);
2997}
2998
2999TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
3000 // DoubleEq never matches NaN.
3001 Matcher<double> m = DoubleEq(nan1_);
3002 EXPECT_FALSE(m.Matches(nan1_));
3003 EXPECT_FALSE(m.Matches(nan2_));
3004 EXPECT_FALSE(m.Matches(1.0));
3005}
3006
3007TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
3008 // NanSensitiveDoubleEq will match NaN.
3009 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
3010 EXPECT_TRUE(m.Matches(nan1_));
3011 EXPECT_TRUE(m.Matches(nan2_));
3012 EXPECT_FALSE(m.Matches(1.0));
3013}
3014
3015TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
3016 Matcher<double> m1 = DoubleEq(2.0);
3017 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003018 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003019
3020 Matcher<double> m2 = DoubleEq(0.5);
3021 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003022 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003023
3024 Matcher<double> m3 = DoubleEq(nan1_);
3025 EXPECT_EQ("never matches", Describe(m3));
3026 EXPECT_EQ("is anything", DescribeNegation(m3));
3027}
3028
3029TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
3030 Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
3031 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003032 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00003033
3034 Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3035 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003036 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003037
3038 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3039 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003040 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00003041}
3042
zhanyong.wan616180e2013-06-18 18:49:51 +00003043// Instantiate FloatingPointTest for testing floats with a user-specified
3044// max absolute error.
3045typedef FloatingPointNearTest<double> DoubleNearTest;
3046
3047TEST_F(DoubleNearTest, DoubleNearMatches) {
3048 TestNearMatches(&DoubleNear);
3049}
3050
3051TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3052 TestNearMatches(&NanSensitiveDoubleNear);
3053}
3054
3055TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3056 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3057 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3058 EXPECT_EQ(
3059 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3060
3061 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3062 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3063 EXPECT_EQ(
3064 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3065
3066 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3067 EXPECT_EQ("never matches", Describe(m3));
3068 EXPECT_EQ("is anything", DescribeNegation(m3));
3069}
3070
3071TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3072 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3073 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3074 EXPECT_EQ(
3075 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3076
3077 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3078 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3079 EXPECT_EQ(
3080 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3081
3082 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3083 EXPECT_EQ("is NaN", Describe(m3));
3084 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3085}
3086
3087TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3088 // DoubleNear never matches NaN.
3089 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3090 EXPECT_FALSE(m.Matches(nan1_));
3091 EXPECT_FALSE(m.Matches(nan2_));
3092 EXPECT_FALSE(m.Matches(1.0));
3093}
3094
3095TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3096 // NanSensitiveDoubleNear will match NaN.
3097 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3098 EXPECT_TRUE(m.Matches(nan1_));
3099 EXPECT_TRUE(m.Matches(nan2_));
3100 EXPECT_FALSE(m.Matches(1.0));
3101}
3102
shiqiane35fdd92008-12-10 05:08:54 +00003103TEST(PointeeTest, RawPointer) {
3104 const Matcher<int*> m = Pointee(Ge(0));
3105
3106 int n = 1;
3107 EXPECT_TRUE(m.Matches(&n));
3108 n = -1;
3109 EXPECT_FALSE(m.Matches(&n));
3110 EXPECT_FALSE(m.Matches(NULL));
3111}
3112
3113TEST(PointeeTest, RawPointerToConst) {
3114 const Matcher<const double*> m = Pointee(Ge(0));
3115
3116 double x = 1;
3117 EXPECT_TRUE(m.Matches(&x));
3118 x = -1;
3119 EXPECT_FALSE(m.Matches(&x));
3120 EXPECT_FALSE(m.Matches(NULL));
3121}
3122
3123TEST(PointeeTest, ReferenceToConstRawPointer) {
3124 const Matcher<int* const &> m = Pointee(Ge(0));
3125
3126 int n = 1;
3127 EXPECT_TRUE(m.Matches(&n));
3128 n = -1;
3129 EXPECT_FALSE(m.Matches(&n));
3130 EXPECT_FALSE(m.Matches(NULL));
3131}
3132
3133TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3134 const Matcher<double* &> m = Pointee(Ge(0));
3135
3136 double x = 1.0;
3137 double* p = &x;
3138 EXPECT_TRUE(m.Matches(p));
3139 x = -1;
3140 EXPECT_FALSE(m.Matches(p));
3141 p = NULL;
3142 EXPECT_FALSE(m.Matches(p));
3143}
3144
vladlosevada23472012-08-14 15:38:49 +00003145// Minimal const-propagating pointer.
3146template <typename T>
3147class ConstPropagatingPtr {
3148 public:
3149 typedef T element_type;
3150
3151 ConstPropagatingPtr() : val_() {}
3152 explicit ConstPropagatingPtr(T* t) : val_(t) {}
3153 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3154
3155 T* get() { return val_; }
3156 T& operator*() { return *val_; }
3157 // Most smart pointers return non-const T* and T& from the next methods.
3158 const T* get() const { return val_; }
3159 const T& operator*() const { return *val_; }
3160
3161 private:
3162 T* val_;
3163};
3164
3165TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3166 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3167 int three = 3;
3168 const ConstPropagatingPtr<int> co(&three);
3169 ConstPropagatingPtr<int> o(&three);
3170 EXPECT_TRUE(m.Matches(o));
3171 EXPECT_TRUE(m.Matches(co));
3172 *o = 6;
3173 EXPECT_FALSE(m.Matches(o));
3174 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3175}
3176
shiqiane35fdd92008-12-10 05:08:54 +00003177TEST(PointeeTest, NeverMatchesNull) {
3178 const Matcher<const char*> m = Pointee(_);
3179 EXPECT_FALSE(m.Matches(NULL));
3180}
3181
3182// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3183TEST(PointeeTest, MatchesAgainstAValue) {
3184 const Matcher<int*> m = Pointee(5);
3185
3186 int n = 5;
3187 EXPECT_TRUE(m.Matches(&n));
3188 n = -1;
3189 EXPECT_FALSE(m.Matches(&n));
3190 EXPECT_FALSE(m.Matches(NULL));
3191}
3192
3193TEST(PointeeTest, CanDescribeSelf) {
3194 const Matcher<int*> m = Pointee(Gt(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003195 EXPECT_EQ("points to a value that is > 3", Describe(m));
3196 EXPECT_EQ("does not point to a value that is > 3",
shiqiane35fdd92008-12-10 05:08:54 +00003197 DescribeNegation(m));
3198}
3199
shiqiane35fdd92008-12-10 05:08:54 +00003200TEST(PointeeTest, CanExplainMatchResult) {
3201 const Matcher<const string*> m = Pointee(StartsWith("Hi"));
3202
3203 EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL)));
3204
zhanyong.wan736baa82010-09-27 17:44:16 +00003205 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
3206 long n = 3; // NOLINT
3207 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003208 Explain(m2, &n));
3209}
3210
3211TEST(PointeeTest, AlwaysExplainsPointee) {
3212 const Matcher<int*> m = Pointee(0);
3213 int n = 42;
zhanyong.wan736baa82010-09-27 17:44:16 +00003214 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
shiqiane35fdd92008-12-10 05:08:54 +00003215}
3216
3217// An uncopyable class.
3218class Uncopyable {
3219 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003220 explicit Uncopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003221
3222 int value() const { return value_; }
3223 private:
3224 const int value_;
3225 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3226};
3227
3228// Returns true iff x.value() is positive.
3229bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3230
3231// A user-defined struct for testing Field().
3232struct AStruct {
3233 AStruct() : x(0), y(1.0), z(5), p(NULL) {}
3234 AStruct(const AStruct& rhs)
3235 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3236
3237 int x; // A non-const field.
3238 const double y; // A const field.
3239 Uncopyable z; // An uncopyable field.
3240 const char* p; // A pointer field.
zhanyong.wan32de5f52009-12-23 00:13:23 +00003241
3242 private:
3243 GTEST_DISALLOW_ASSIGN_(AStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003244};
3245
3246// A derived struct for testing Field().
3247struct DerivedStruct : public AStruct {
3248 char ch;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003249
3250 private:
3251 GTEST_DISALLOW_ASSIGN_(DerivedStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003252};
3253
3254// Tests that Field(&Foo::field, ...) works when field is non-const.
3255TEST(FieldTest, WorksForNonConstField) {
3256 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
3257
3258 AStruct a;
3259 EXPECT_TRUE(m.Matches(a));
3260 a.x = -1;
3261 EXPECT_FALSE(m.Matches(a));
3262}
3263
3264// Tests that Field(&Foo::field, ...) works when field is const.
3265TEST(FieldTest, WorksForConstField) {
3266 AStruct a;
3267
3268 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
3269 EXPECT_TRUE(m.Matches(a));
3270 m = Field(&AStruct::y, Le(0.0));
3271 EXPECT_FALSE(m.Matches(a));
3272}
3273
3274// Tests that Field(&Foo::field, ...) works when field is not copyable.
3275TEST(FieldTest, WorksForUncopyableField) {
3276 AStruct a;
3277
3278 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3279 EXPECT_TRUE(m.Matches(a));
3280 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3281 EXPECT_FALSE(m.Matches(a));
3282}
3283
3284// Tests that Field(&Foo::field, ...) works when field is a pointer.
3285TEST(FieldTest, WorksForPointerField) {
3286 // Matching against NULL.
3287 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
3288 AStruct a;
3289 EXPECT_TRUE(m.Matches(a));
3290 a.p = "hi";
3291 EXPECT_FALSE(m.Matches(a));
3292
3293 // Matching a pointer that is not NULL.
3294 m = Field(&AStruct::p, StartsWith("hi"));
3295 a.p = "hill";
3296 EXPECT_TRUE(m.Matches(a));
3297 a.p = "hole";
3298 EXPECT_FALSE(m.Matches(a));
3299}
3300
3301// Tests that Field() works when the object is passed by reference.
3302TEST(FieldTest, WorksForByRefArgument) {
3303 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3304
3305 AStruct a;
3306 EXPECT_TRUE(m.Matches(a));
3307 a.x = -1;
3308 EXPECT_FALSE(m.Matches(a));
3309}
3310
3311// Tests that Field(&Foo::field, ...) works when the argument's type
3312// is a sub-type of Foo.
3313TEST(FieldTest, WorksForArgumentOfSubType) {
3314 // Note that the matcher expects DerivedStruct but we say AStruct
3315 // inside Field().
3316 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
3317
3318 DerivedStruct d;
3319 EXPECT_TRUE(m.Matches(d));
3320 d.x = -1;
3321 EXPECT_FALSE(m.Matches(d));
3322}
3323
3324// Tests that Field(&Foo::field, m) works when field's type and m's
3325// argument type are compatible but not the same.
3326TEST(FieldTest, WorksForCompatibleMatcherType) {
3327 // The field is an int, but the inner matcher expects a signed char.
3328 Matcher<const AStruct&> m = Field(&AStruct::x,
3329 Matcher<signed char>(Ge(0)));
3330
3331 AStruct a;
3332 EXPECT_TRUE(m.Matches(a));
3333 a.x = -1;
3334 EXPECT_FALSE(m.Matches(a));
3335}
3336
3337// Tests that Field() can describe itself.
3338TEST(FieldTest, CanDescribeSelf) {
3339 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3340
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003341 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3342 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003343}
3344
3345// Tests that Field() can explain the match result.
3346TEST(FieldTest, CanExplainMatchResult) {
3347 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3348
3349 AStruct a;
3350 a.x = 1;
zhanyong.wan736baa82010-09-27 17:44:16 +00003351 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003352
3353 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003354 EXPECT_EQ(
3355 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
3356 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003357}
3358
3359// Tests that Field() works when the argument is a pointer to const.
3360TEST(FieldForPointerTest, WorksForPointerToConst) {
3361 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3362
3363 AStruct a;
3364 EXPECT_TRUE(m.Matches(&a));
3365 a.x = -1;
3366 EXPECT_FALSE(m.Matches(&a));
3367}
3368
3369// Tests that Field() works when the argument is a pointer to non-const.
3370TEST(FieldForPointerTest, WorksForPointerToNonConst) {
3371 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
3372
3373 AStruct a;
3374 EXPECT_TRUE(m.Matches(&a));
3375 a.x = -1;
3376 EXPECT_FALSE(m.Matches(&a));
3377}
3378
zhanyong.wan6953a722010-01-13 05:15:07 +00003379// Tests that Field() works when the argument is a reference to a const pointer.
3380TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
3381 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
3382
3383 AStruct a;
3384 EXPECT_TRUE(m.Matches(&a));
3385 a.x = -1;
3386 EXPECT_FALSE(m.Matches(&a));
3387}
3388
shiqiane35fdd92008-12-10 05:08:54 +00003389// Tests that Field() does not match the NULL pointer.
3390TEST(FieldForPointerTest, DoesNotMatchNull) {
3391 Matcher<const AStruct*> m = Field(&AStruct::x, _);
3392 EXPECT_FALSE(m.Matches(NULL));
3393}
3394
3395// Tests that Field(&Foo::field, ...) works when the argument's type
3396// is a sub-type of const Foo*.
3397TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
3398 // Note that the matcher expects DerivedStruct but we say AStruct
3399 // inside Field().
3400 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
3401
3402 DerivedStruct d;
3403 EXPECT_TRUE(m.Matches(&d));
3404 d.x = -1;
3405 EXPECT_FALSE(m.Matches(&d));
3406}
3407
3408// Tests that Field() can describe itself when used to match a pointer.
3409TEST(FieldForPointerTest, CanDescribeSelf) {
3410 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3411
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003412 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3413 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003414}
3415
3416// Tests that Field() can explain the result of matching a pointer.
3417TEST(FieldForPointerTest, CanExplainMatchResult) {
3418 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3419
3420 AStruct a;
3421 a.x = 1;
3422 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003423 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
3424 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003425
3426 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003427 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
3428 ", which is 1 more than 0", Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003429}
3430
3431// A user-defined class for testing Property().
3432class AClass {
3433 public:
3434 AClass() : n_(0) {}
3435
3436 // A getter that returns a non-reference.
3437 int n() const { return n_; }
3438
3439 void set_n(int new_n) { n_ = new_n; }
3440
3441 // A getter that returns a reference to const.
3442 const string& s() const { return s_; }
3443
3444 void set_s(const string& new_s) { s_ = new_s; }
3445
3446 // A getter that returns a reference to non-const.
3447 double& x() const { return x_; }
3448 private:
3449 int n_;
3450 string s_;
3451
3452 static double x_;
3453};
3454
3455double AClass::x_ = 0.0;
3456
3457// A derived class for testing Property().
3458class DerivedClass : public AClass {
3459 private:
3460 int k_;
3461};
3462
3463// Tests that Property(&Foo::property, ...) works when property()
3464// returns a non-reference.
3465TEST(PropertyTest, WorksForNonReferenceProperty) {
3466 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3467
3468 AClass a;
3469 a.set_n(1);
3470 EXPECT_TRUE(m.Matches(a));
3471
3472 a.set_n(-1);
3473 EXPECT_FALSE(m.Matches(a));
3474}
3475
3476// Tests that Property(&Foo::property, ...) works when property()
3477// returns a reference to const.
3478TEST(PropertyTest, WorksForReferenceToConstProperty) {
3479 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
3480
3481 AClass a;
3482 a.set_s("hill");
3483 EXPECT_TRUE(m.Matches(a));
3484
3485 a.set_s("hole");
3486 EXPECT_FALSE(m.Matches(a));
3487}
3488
3489// Tests that Property(&Foo::property, ...) works when property()
3490// returns a reference to non-const.
3491TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
3492 double x = 0.0;
3493 AClass a;
3494
3495 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
3496 EXPECT_FALSE(m.Matches(a));
3497
3498 m = Property(&AClass::x, Not(Ref(x)));
3499 EXPECT_TRUE(m.Matches(a));
3500}
3501
3502// Tests that Property(&Foo::property, ...) works when the argument is
3503// passed by value.
3504TEST(PropertyTest, WorksForByValueArgument) {
3505 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
3506
3507 AClass a;
3508 a.set_s("hill");
3509 EXPECT_TRUE(m.Matches(a));
3510
3511 a.set_s("hole");
3512 EXPECT_FALSE(m.Matches(a));
3513}
3514
3515// Tests that Property(&Foo::property, ...) works when the argument's
3516// type is a sub-type of Foo.
3517TEST(PropertyTest, WorksForArgumentOfSubType) {
3518 // The matcher expects a DerivedClass, but inside the Property() we
3519 // say AClass.
3520 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
3521
3522 DerivedClass d;
3523 d.set_n(1);
3524 EXPECT_TRUE(m.Matches(d));
3525
3526 d.set_n(-1);
3527 EXPECT_FALSE(m.Matches(d));
3528}
3529
3530// Tests that Property(&Foo::property, m) works when property()'s type
3531// and m's argument type are compatible but different.
3532TEST(PropertyTest, WorksForCompatibleMatcherType) {
3533 // n() returns an int but the inner matcher expects a signed char.
3534 Matcher<const AClass&> m = Property(&AClass::n,
3535 Matcher<signed char>(Ge(0)));
3536
3537 AClass a;
3538 EXPECT_TRUE(m.Matches(a));
3539 a.set_n(-1);
3540 EXPECT_FALSE(m.Matches(a));
3541}
3542
3543// Tests that Property() can describe itself.
3544TEST(PropertyTest, CanDescribeSelf) {
3545 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3546
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003547 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3548 EXPECT_EQ("is an object whose given property isn't >= 0",
3549 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003550}
3551
3552// Tests that Property() can explain the match result.
3553TEST(PropertyTest, CanExplainMatchResult) {
3554 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3555
3556 AClass a;
3557 a.set_n(1);
zhanyong.wan736baa82010-09-27 17:44:16 +00003558 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003559
3560 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003561 EXPECT_EQ(
3562 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
3563 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003564}
3565
3566// Tests that Property() works when the argument is a pointer to const.
3567TEST(PropertyForPointerTest, WorksForPointerToConst) {
3568 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3569
3570 AClass a;
3571 a.set_n(1);
3572 EXPECT_TRUE(m.Matches(&a));
3573
3574 a.set_n(-1);
3575 EXPECT_FALSE(m.Matches(&a));
3576}
3577
3578// Tests that Property() works when the argument is a pointer to non-const.
3579TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
3580 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
3581
3582 AClass a;
3583 a.set_s("hill");
3584 EXPECT_TRUE(m.Matches(&a));
3585
3586 a.set_s("hole");
3587 EXPECT_FALSE(m.Matches(&a));
3588}
3589
zhanyong.wan6953a722010-01-13 05:15:07 +00003590// Tests that Property() works when the argument is a reference to a
3591// const pointer.
3592TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
3593 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
3594
3595 AClass a;
3596 a.set_s("hill");
3597 EXPECT_TRUE(m.Matches(&a));
3598
3599 a.set_s("hole");
3600 EXPECT_FALSE(m.Matches(&a));
3601}
3602
shiqiane35fdd92008-12-10 05:08:54 +00003603// Tests that Property() does not match the NULL pointer.
3604TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
3605 Matcher<const AClass*> m = Property(&AClass::x, _);
3606 EXPECT_FALSE(m.Matches(NULL));
3607}
3608
3609// Tests that Property(&Foo::property, ...) works when the argument's
3610// type is a sub-type of const Foo*.
3611TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
3612 // The matcher expects a DerivedClass, but inside the Property() we
3613 // say AClass.
3614 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
3615
3616 DerivedClass d;
3617 d.set_n(1);
3618 EXPECT_TRUE(m.Matches(&d));
3619
3620 d.set_n(-1);
3621 EXPECT_FALSE(m.Matches(&d));
3622}
3623
3624// Tests that Property() can describe itself when used to match a pointer.
3625TEST(PropertyForPointerTest, CanDescribeSelf) {
3626 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3627
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003628 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3629 EXPECT_EQ("is an object whose given property isn't >= 0",
3630 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003631}
3632
3633// Tests that Property() can explain the result of matching a pointer.
3634TEST(PropertyForPointerTest, CanExplainMatchResult) {
3635 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3636
3637 AClass a;
3638 a.set_n(1);
3639 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003640 EXPECT_EQ(
3641 "which points to an object whose given property is 1" + OfType("int"),
3642 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003643
3644 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003645 EXPECT_EQ("which points to an object whose given property is 1" +
3646 OfType("int") + ", which is 1 more than 0",
3647 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003648}
3649
3650// Tests ResultOf.
3651
3652// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3653// function pointer.
3654string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; }
3655
3656TEST(ResultOfTest, WorksForFunctionPointers) {
3657 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo")));
3658
3659 EXPECT_TRUE(matcher.Matches(1));
3660 EXPECT_FALSE(matcher.Matches(2));
3661}
3662
3663// Tests that ResultOf() can describe itself.
3664TEST(ResultOfTest, CanDescribeItself) {
3665 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
3666
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003667 EXPECT_EQ("is mapped by the given callable to a value that "
3668 "is equal to \"foo\"", Describe(matcher));
3669 EXPECT_EQ("is mapped by the given callable to a value that "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003670 "isn't equal to \"foo\"", DescribeNegation(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00003671}
3672
3673// Tests that ResultOf() can explain the match result.
3674int IntFunction(int input) { return input == 42 ? 80 : 90; }
3675
3676TEST(ResultOfTest, CanExplainMatchResult) {
3677 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003678 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003679 Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003680
3681 matcher = ResultOf(&IntFunction, GreaterThan(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003682 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
3683 ", which is 5 more than 85", Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003684}
3685
3686// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3687// returns a non-reference.
3688TEST(ResultOfTest, WorksForNonReferenceResults) {
3689 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
3690
3691 EXPECT_TRUE(matcher.Matches(42));
3692 EXPECT_FALSE(matcher.Matches(36));
3693}
3694
3695// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3696// returns a reference to non-const.
zhanyong.wan736baa82010-09-27 17:44:16 +00003697double& DoubleFunction(double& input) { return input; } // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003698
zhanyong.wan736baa82010-09-27 17:44:16 +00003699Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003700 return obj;
3701}
3702
3703TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
3704 double x = 3.14;
3705 double x2 = x;
3706 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
3707
3708 EXPECT_TRUE(matcher.Matches(x));
3709 EXPECT_FALSE(matcher.Matches(x2));
3710
3711 // Test that ResultOf works with uncopyable objects
3712 Uncopyable obj(0);
3713 Uncopyable obj2(0);
3714 Matcher<Uncopyable&> matcher2 =
3715 ResultOf(&RefUncopyableFunction, Ref(obj));
3716
3717 EXPECT_TRUE(matcher2.Matches(obj));
3718 EXPECT_FALSE(matcher2.Matches(obj2));
3719}
3720
3721// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3722// returns a reference to const.
3723const string& StringFunction(const string& input) { return input; }
3724
3725TEST(ResultOfTest, WorksForReferenceToConstResults) {
3726 string s = "foo";
3727 string s2 = s;
3728 Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s));
3729
3730 EXPECT_TRUE(matcher.Matches(s));
3731 EXPECT_FALSE(matcher.Matches(s2));
3732}
3733
3734// Tests that ResultOf(f, m) works when f(x) and m's
3735// argument types are compatible but different.
3736TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
3737 // IntFunction() returns int but the inner matcher expects a signed char.
3738 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
3739
3740 EXPECT_TRUE(matcher.Matches(36));
3741 EXPECT_FALSE(matcher.Matches(42));
3742}
3743
shiqiane35fdd92008-12-10 05:08:54 +00003744// Tests that the program aborts when ResultOf is passed
3745// a NULL function pointer.
3746TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
zhanyong.wan04d6ed82009-09-11 07:01:08 +00003747 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan736baa82010-09-27 17:44:16 +00003748 ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))),
shiqiane35fdd92008-12-10 05:08:54 +00003749 "NULL function pointer is passed into ResultOf\\(\\)\\.");
3750}
shiqiane35fdd92008-12-10 05:08:54 +00003751
3752// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3753// function reference.
3754TEST(ResultOfTest, WorksForFunctionReferences) {
3755 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
3756 EXPECT_TRUE(matcher.Matches(1));
3757 EXPECT_FALSE(matcher.Matches(2));
3758}
3759
3760// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3761// function object.
3762struct Functor : public ::std::unary_function<int, string> {
3763 result_type operator()(argument_type input) const {
3764 return IntToStringFunction(input);
3765 }
3766};
3767
3768TEST(ResultOfTest, WorksForFunctors) {
3769 Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo")));
3770
3771 EXPECT_TRUE(matcher.Matches(1));
3772 EXPECT_FALSE(matcher.Matches(2));
3773}
3774
3775// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3776// functor with more then one operator() defined. ResultOf() must work
3777// for each defined operator().
3778struct PolymorphicFunctor {
3779 typedef int result_type;
3780 int operator()(int n) { return n; }
3781 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
3782};
3783
3784TEST(ResultOfTest, WorksForPolymorphicFunctors) {
3785 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
3786
3787 EXPECT_TRUE(matcher_int.Matches(10));
3788 EXPECT_FALSE(matcher_int.Matches(2));
3789
3790 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
3791
3792 EXPECT_TRUE(matcher_string.Matches("long string"));
3793 EXPECT_FALSE(matcher_string.Matches("shrt"));
3794}
3795
3796const int* ReferencingFunction(const int& n) { return &n; }
3797
3798struct ReferencingFunctor {
3799 typedef const int* result_type;
3800 result_type operator()(const int& n) { return &n; }
3801};
3802
3803TEST(ResultOfTest, WorksForReferencingCallables) {
3804 const int n = 1;
3805 const int n2 = 1;
3806 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
3807 EXPECT_TRUE(matcher2.Matches(n));
3808 EXPECT_FALSE(matcher2.Matches(n2));
3809
3810 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
3811 EXPECT_TRUE(matcher3.Matches(n));
3812 EXPECT_FALSE(matcher3.Matches(n2));
3813}
3814
shiqiane35fdd92008-12-10 05:08:54 +00003815class DivisibleByImpl {
3816 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003817 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
shiqiane35fdd92008-12-10 05:08:54 +00003818
zhanyong.wandb22c222010-01-28 21:52:29 +00003819 // For testing using ExplainMatchResultTo() with polymorphic matchers.
shiqiane35fdd92008-12-10 05:08:54 +00003820 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00003821 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003822 *listener << "which is " << (n % divider_) << " modulo "
zhanyong.wandb22c222010-01-28 21:52:29 +00003823 << divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003824 return (n % divider_) == 0;
3825 }
3826
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003827 void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003828 *os << "is divisible by " << divider_;
3829 }
3830
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003831 void DescribeNegationTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003832 *os << "is not divisible by " << divider_;
3833 }
3834
zhanyong.wan32de5f52009-12-23 00:13:23 +00003835 void set_divider(int a_divider) { divider_ = a_divider; }
shiqiane35fdd92008-12-10 05:08:54 +00003836 int divider() const { return divider_; }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003837
shiqiane35fdd92008-12-10 05:08:54 +00003838 private:
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003839 int divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003840};
3841
shiqiane35fdd92008-12-10 05:08:54 +00003842PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
3843 return MakePolymorphicMatcher(DivisibleByImpl(n));
3844}
3845
3846// Tests that when AllOf() fails, only the first failing matcher is
3847// asked to explain why.
3848TEST(ExplainMatchResultTest, AllOf_False_False) {
3849 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003850 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00003851}
3852
3853// Tests that when AllOf() fails, only the first failing matcher is
3854// asked to explain why.
3855TEST(ExplainMatchResultTest, AllOf_False_True) {
3856 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003857 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003858}
3859
3860// Tests that when AllOf() fails, only the first failing matcher is
3861// asked to explain why.
3862TEST(ExplainMatchResultTest, AllOf_True_False) {
3863 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003864 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00003865}
3866
3867// Tests that when AllOf() succeeds, all matchers are asked to explain
3868// why.
3869TEST(ExplainMatchResultTest, AllOf_True_True) {
3870 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003871 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003872}
3873
3874TEST(ExplainMatchResultTest, AllOf_True_True_2) {
3875 const Matcher<int> m = AllOf(Ge(2), Le(3));
3876 EXPECT_EQ("", Explain(m, 2));
3877}
3878
3879TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
3880 const Matcher<int> m = GreaterThan(5);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003881 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003882}
3883
3884// The following two tests verify that values without a public copy
3885// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
3886// with the help of ByRef().
3887
3888class NotCopyable {
3889 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003890 explicit NotCopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003891
3892 int value() const { return value_; }
3893
3894 bool operator==(const NotCopyable& rhs) const {
3895 return value() == rhs.value();
3896 }
3897
3898 bool operator>=(const NotCopyable& rhs) const {
3899 return value() >= rhs.value();
3900 }
3901 private:
3902 int value_;
3903
3904 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
3905};
3906
3907TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
3908 const NotCopyable const_value1(1);
3909 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
3910
3911 const NotCopyable n1(1), n2(2);
3912 EXPECT_TRUE(m.Matches(n1));
3913 EXPECT_FALSE(m.Matches(n2));
3914}
3915
3916TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
3917 NotCopyable value2(2);
3918 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
3919
3920 NotCopyable n1(1), n2(2);
3921 EXPECT_FALSE(m.Matches(n1));
3922 EXPECT_TRUE(m.Matches(n2));
3923}
3924
zhanyong.wan320814a2013-03-01 00:20:30 +00003925TEST(IsEmptyTest, ImplementsIsEmpty) {
3926 vector<int> container;
3927 EXPECT_THAT(container, IsEmpty());
3928 container.push_back(0);
3929 EXPECT_THAT(container, Not(IsEmpty()));
3930 container.push_back(1);
3931 EXPECT_THAT(container, Not(IsEmpty()));
3932}
3933
3934TEST(IsEmptyTest, WorksWithString) {
3935 string text;
3936 EXPECT_THAT(text, IsEmpty());
3937 text = "foo";
3938 EXPECT_THAT(text, Not(IsEmpty()));
3939 text = string("\0", 1);
3940 EXPECT_THAT(text, Not(IsEmpty()));
3941}
3942
3943TEST(IsEmptyTest, CanDescribeSelf) {
3944 Matcher<vector<int> > m = IsEmpty();
3945 EXPECT_EQ("is empty", Describe(m));
3946 EXPECT_EQ("isn't empty", DescribeNegation(m));
3947}
3948
3949TEST(IsEmptyTest, ExplainsResult) {
3950 Matcher<vector<int> > m = IsEmpty();
3951 vector<int> container;
3952 EXPECT_EQ("", Explain(m, container));
3953 container.push_back(0);
3954 EXPECT_EQ("whose size is 1", Explain(m, container));
3955}
3956
zhanyong.wana31d9ce2013-03-01 01:50:17 +00003957TEST(SizeIsTest, ImplementsSizeIs) {
3958 vector<int> container;
3959 EXPECT_THAT(container, SizeIs(0));
3960 EXPECT_THAT(container, Not(SizeIs(1)));
3961 container.push_back(0);
3962 EXPECT_THAT(container, Not(SizeIs(0)));
3963 EXPECT_THAT(container, SizeIs(1));
3964 container.push_back(0);
3965 EXPECT_THAT(container, Not(SizeIs(0)));
3966 EXPECT_THAT(container, SizeIs(2));
3967}
3968
3969TEST(SizeIsTest, WorksWithMap) {
3970 map<string, int> container;
3971 EXPECT_THAT(container, SizeIs(0));
3972 EXPECT_THAT(container, Not(SizeIs(1)));
3973 container.insert(make_pair("foo", 1));
3974 EXPECT_THAT(container, Not(SizeIs(0)));
3975 EXPECT_THAT(container, SizeIs(1));
3976 container.insert(make_pair("bar", 2));
3977 EXPECT_THAT(container, Not(SizeIs(0)));
3978 EXPECT_THAT(container, SizeIs(2));
3979}
3980
3981TEST(SizeIsTest, WorksWithReferences) {
3982 vector<int> container;
3983 Matcher<const vector<int>&> m = SizeIs(1);
3984 EXPECT_THAT(container, Not(m));
3985 container.push_back(0);
3986 EXPECT_THAT(container, m);
3987}
3988
3989TEST(SizeIsTest, CanDescribeSelf) {
3990 Matcher<vector<int> > m = SizeIs(2);
3991 EXPECT_EQ("size is equal to 2", Describe(m));
3992 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
3993}
3994
3995TEST(SizeIsTest, ExplainsResult) {
3996 Matcher<vector<int> > m1 = SizeIs(2);
3997 Matcher<vector<int> > m2 = SizeIs(Lt(2u));
3998 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
3999 Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
4000 vector<int> container;
4001 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
4002 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
4003 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
4004 EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
4005 Explain(m4, container));
4006 container.push_back(0);
4007 container.push_back(0);
4008 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
4009 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
4010 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
4011 EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
4012 Explain(m4, container));
4013}
4014
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004015#if GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004016// Tests ContainerEq with different container types, and
4017// different element types.
4018
4019template <typename T>
zhanyong.wanb8243162009-06-04 05:48:20 +00004020class ContainerEqTest : public testing::Test {};
zhanyong.wan6a896b52009-01-16 01:13:50 +00004021
4022typedef testing::Types<
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004023 set<int>,
4024 vector<size_t>,
4025 multiset<size_t>,
4026 list<int> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00004027 ContainerEqTestTypes;
4028
4029TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
4030
4031// Tests that the filled container is equal to itself.
4032TYPED_TEST(ContainerEqTest, EqualsSelf) {
4033 static const int vals[] = {1, 1, 2, 3, 5, 8};
4034 TypeParam my_set(vals, vals + 6);
4035 const Matcher<TypeParam> m = ContainerEq(my_set);
4036 EXPECT_TRUE(m.Matches(my_set));
4037 EXPECT_EQ("", Explain(m, my_set));
4038}
4039
4040// Tests that missing values are reported.
4041TYPED_TEST(ContainerEqTest, ValueMissing) {
4042 static const int vals[] = {1, 1, 2, 3, 5, 8};
4043 static const int test_vals[] = {2, 1, 8, 5};
4044 TypeParam my_set(vals, vals + 6);
4045 TypeParam test_set(test_vals, test_vals + 4);
4046 const Matcher<TypeParam> m = ContainerEq(my_set);
4047 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004048 EXPECT_EQ("which doesn't have these expected elements: 3",
4049 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004050}
4051
4052// Tests that added values are reported.
4053TYPED_TEST(ContainerEqTest, ValueAdded) {
4054 static const int vals[] = {1, 1, 2, 3, 5, 8};
4055 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4056 TypeParam my_set(vals, vals + 6);
4057 TypeParam test_set(test_vals, test_vals + 6);
4058 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4059 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004060 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004061}
4062
4063// Tests that added and missing values are reported together.
4064TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4065 static const int vals[] = {1, 1, 2, 3, 5, 8};
4066 static const int test_vals[] = {1, 2, 3, 8, 46};
4067 TypeParam my_set(vals, vals + 6);
4068 TypeParam test_set(test_vals, test_vals + 5);
4069 const Matcher<TypeParam> m = ContainerEq(my_set);
4070 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004071 EXPECT_EQ("which has these unexpected elements: 46,\n"
4072 "and doesn't have these expected elements: 5",
4073 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004074}
4075
4076// Tests duplicated value -- expect no explanation.
4077TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4078 static const int vals[] = {1, 1, 2, 3, 5, 8};
4079 static const int test_vals[] = {1, 2, 3, 5, 8};
4080 TypeParam my_set(vals, vals + 6);
4081 TypeParam test_set(test_vals, test_vals + 5);
4082 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4083 // Depending on the container, match may be true or false
4084 // But in any case there should be no explanation.
4085 EXPECT_EQ("", Explain(m, test_set));
4086}
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004087#endif // GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004088
4089// Tests that mutliple missing values are reported.
4090// Using just vector here, so order is predicatble.
4091TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4092 static const int vals[] = {1, 1, 2, 3, 5, 8};
4093 static const int test_vals[] = {2, 1, 5};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004094 vector<int> my_set(vals, vals + 6);
4095 vector<int> test_set(test_vals, test_vals + 3);
4096 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004097 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004098 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4099 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004100}
4101
4102// Tests that added values are reported.
4103// Using just vector here, so order is predicatble.
4104TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4105 static const int vals[] = {1, 1, 2, 3, 5, 8};
4106 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 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 + 7);
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",
4112 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004113}
4114
4115// Tests that added and missing values are reported together.
4116TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
4117 static const int vals[] = {1, 1, 2, 3, 5, 8};
4118 static const int test_vals[] = {1, 2, 3, 92, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004119 list<size_t> my_set(vals, vals + 6);
4120 list<size_t> test_set(test_vals, test_vals + 5);
4121 const Matcher<const list<size_t> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004122 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004123 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4124 "and doesn't have these expected elements: 5, 8",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004125 Explain(m, test_set));
4126}
4127
4128// Tests to see that duplicate elements are detected,
4129// but (as above) not reported in the explanation.
4130TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
4131 static const int vals[] = {1, 1, 2, 3, 5, 8};
4132 static const int test_vals[] = {1, 2, 3, 5, 8};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004133 vector<int> my_set(vals, vals + 6);
4134 vector<int> test_set(test_vals, test_vals + 5);
4135 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004136 EXPECT_TRUE(m.Matches(my_set));
4137 EXPECT_FALSE(m.Matches(test_set));
4138 // There is nothing to report when both sets contain all the same values.
4139 EXPECT_EQ("", Explain(m, test_set));
4140}
4141
4142// Tests that ContainerEq works for non-trivial associative containers,
4143// like maps.
4144TEST(ContainerEqExtraTest, WorksForMaps) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004145 map<int, std::string> my_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004146 my_map[0] = "a";
4147 my_map[1] = "b";
4148
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004149 map<int, std::string> test_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004150 test_map[0] = "aa";
4151 test_map[1] = "b";
4152
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004153 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004154 EXPECT_TRUE(m.Matches(my_map));
4155 EXPECT_FALSE(m.Matches(test_map));
4156
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004157 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
4158 "and doesn't have these expected elements: (0, \"a\")",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004159 Explain(m, test_map));
4160}
4161
zhanyong.wanb8243162009-06-04 05:48:20 +00004162TEST(ContainerEqExtraTest, WorksForNativeArray) {
4163 int a1[] = { 1, 2, 3 };
4164 int a2[] = { 1, 2, 3 };
4165 int b[] = { 1, 2, 4 };
4166
4167 EXPECT_THAT(a1, ContainerEq(a2));
4168 EXPECT_THAT(a1, Not(ContainerEq(b)));
4169}
4170
4171TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
4172 const char a1[][3] = { "hi", "lo" };
4173 const char a2[][3] = { "hi", "lo" };
4174 const char b[][3] = { "lo", "hi" };
4175
4176 // Tests using ContainerEq() in the first dimension.
4177 EXPECT_THAT(a1, ContainerEq(a2));
4178 EXPECT_THAT(a1, Not(ContainerEq(b)));
4179
4180 // Tests using ContainerEq() in the second dimension.
4181 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
4182 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
4183}
4184
4185TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
4186 const int a1[] = { 1, 2, 3 };
4187 const int a2[] = { 1, 2, 3 };
4188 const int b[] = { 1, 2, 3, 4 };
4189
zhanyong.wan2661c682009-06-09 05:42:12 +00004190 const int* const p1 = a1;
4191 EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
4192 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004193
4194 const int c[] = { 1, 3, 2 };
zhanyong.wan2661c682009-06-09 05:42:12 +00004195 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004196}
4197
4198TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
4199 std::string a1[][3] = {
4200 { "hi", "hello", "ciao" },
4201 { "bye", "see you", "ciao" }
4202 };
4203
4204 std::string a2[][3] = {
4205 { "hi", "hello", "ciao" },
4206 { "bye", "see you", "ciao" }
4207 };
4208
4209 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
4210 EXPECT_THAT(a1, m);
4211
4212 a2[0][0] = "ha";
4213 EXPECT_THAT(a1, m);
4214}
4215
zhanyong.wan898725c2011-09-16 16:45:39 +00004216TEST(WhenSortedByTest, WorksForEmptyContainer) {
4217 const vector<int> numbers;
4218 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
4219 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
4220}
4221
4222TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
4223 vector<unsigned> numbers;
4224 numbers.push_back(3);
4225 numbers.push_back(1);
4226 numbers.push_back(2);
4227 numbers.push_back(2);
4228 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
4229 ElementsAre(3, 2, 2, 1)));
4230 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
4231 ElementsAre(1, 2, 2, 3))));
4232}
4233
4234TEST(WhenSortedByTest, WorksForNonVectorContainer) {
4235 list<string> words;
4236 words.push_back("say");
4237 words.push_back("hello");
4238 words.push_back("world");
4239 EXPECT_THAT(words, WhenSortedBy(less<string>(),
4240 ElementsAre("hello", "say", "world")));
4241 EXPECT_THAT(words, Not(WhenSortedBy(less<string>(),
4242 ElementsAre("say", "hello", "world"))));
4243}
4244
4245TEST(WhenSortedByTest, WorksForNativeArray) {
4246 const int numbers[] = { 1, 3, 2, 4 };
4247 const int sorted_numbers[] = { 1, 2, 3, 4 };
4248 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
4249 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
4250 ElementsAreArray(sorted_numbers)));
4251 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
4252}
4253
4254TEST(WhenSortedByTest, CanDescribeSelf) {
4255 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
4256 EXPECT_EQ("(when sorted) has 2 elements where\n"
4257 "element #0 is equal to 1,\n"
4258 "element #1 is equal to 2",
4259 Describe(m));
4260 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
4261 "element #0 isn't equal to 1, or\n"
4262 "element #1 isn't equal to 2",
4263 DescribeNegation(m));
4264}
4265
4266TEST(WhenSortedByTest, ExplainsMatchResult) {
4267 const int a[] = { 2, 1 };
4268 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
4269 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
4270 EXPECT_EQ("which is { 1, 2 } when sorted",
4271 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
4272}
4273
4274// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
4275// need to test it as exhaustively as we test the latter.
4276
4277TEST(WhenSortedTest, WorksForEmptyContainer) {
4278 const vector<int> numbers;
4279 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
4280 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
4281}
4282
4283TEST(WhenSortedTest, WorksForNonEmptyContainer) {
4284 list<string> words;
4285 words.push_back("3");
4286 words.push_back("1");
4287 words.push_back("2");
4288 words.push_back("2");
4289 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
4290 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
4291}
4292
zhanyong.wana9a59e02013-03-27 16:14:55 +00004293TEST(WhenSortedTest, WorksForMapTypes) {
4294 map<string, int> word_counts;
4295 word_counts["and"] = 1;
4296 word_counts["the"] = 1;
4297 word_counts["buffalo"] = 2;
4298 EXPECT_THAT(word_counts, WhenSorted(ElementsAre(
4299 Pair("and", 1), Pair("buffalo", 2), Pair("the", 1))));
4300 EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre(
4301 Pair("and", 1), Pair("the", 1), Pair("buffalo", 2)))));
4302}
4303
4304TEST(WhenSortedTest, WorksForMultiMapTypes) {
4305 multimap<int, int> ifib;
4306 ifib.insert(make_pair(8, 6));
4307 ifib.insert(make_pair(2, 3));
4308 ifib.insert(make_pair(1, 1));
4309 ifib.insert(make_pair(3, 4));
4310 ifib.insert(make_pair(1, 2));
4311 ifib.insert(make_pair(5, 5));
4312 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
4313 Pair(1, 2),
4314 Pair(2, 3),
4315 Pair(3, 4),
4316 Pair(5, 5),
4317 Pair(8, 6))));
4318 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
4319 Pair(2, 3),
4320 Pair(1, 1),
4321 Pair(3, 4),
4322 Pair(1, 2),
4323 Pair(5, 5)))));
4324}
4325
4326TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
4327 std::deque<int> d;
4328 d.push_back(2);
4329 d.push_back(1);
4330 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
4331 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
4332}
4333
4334TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
4335 std::deque<int> d;
4336 d.push_back(2);
4337 d.push_back(1);
4338 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
4339 EXPECT_THAT(d, WhenSorted(vector_match));
4340 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
4341 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
4342}
4343
4344// Deliberately bare pseudo-container.
4345// Offers only begin() and end() accessors, yielding InputIterator.
4346template <typename T>
4347class Streamlike {
4348 private:
4349 class ConstIter;
4350 public:
4351 typedef ConstIter const_iterator;
4352 typedef T value_type;
4353
4354 template <typename InIter>
4355 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
4356
4357 const_iterator begin() const {
4358 return const_iterator(this, remainder_.begin());
4359 }
4360 const_iterator end() const {
4361 return const_iterator(this, remainder_.end());
4362 }
4363
4364 private:
4365 class ConstIter : public std::iterator<std::input_iterator_tag,
4366 value_type,
4367 ptrdiff_t,
4368 const value_type&,
4369 const value_type*> {
4370 public:
4371 ConstIter(const Streamlike* s,
4372 typename std::list<value_type>::iterator pos)
4373 : s_(s), pos_(pos) {}
4374
4375 const value_type& operator*() const { return *pos_; }
4376 const value_type* operator->() const { return &*pos_; }
4377 ConstIter& operator++() {
4378 s_->remainder_.erase(pos_++);
4379 return *this;
4380 }
4381
4382 // *iter++ is required to work (see std::istreambuf_iterator).
4383 // (void)iter++ is also required to work.
4384 class PostIncrProxy {
4385 public:
4386 explicit PostIncrProxy(const value_type& value) : value_(value) {}
4387 value_type operator*() const { return value_; }
4388 private:
4389 value_type value_;
4390 };
4391 PostIncrProxy operator++(int) {
4392 PostIncrProxy proxy(**this);
4393 ++(*this);
4394 return proxy;
4395 }
4396
4397 friend bool operator==(const ConstIter& a, const ConstIter& b) {
4398 return a.s_ == b.s_ && a.pos_ == b.pos_;
4399 }
4400 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
4401 return !(a == b);
4402 }
4403
4404 private:
4405 const Streamlike* s_;
4406 typename std::list<value_type>::iterator pos_;
4407 };
4408
4409 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
4410 os << "[";
4411 typedef typename std::list<value_type>::const_iterator Iter;
4412 const char* sep = "";
4413 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
4414 os << sep << *it;
4415 sep = ",";
4416 }
4417 os << "]";
4418 return os;
4419 }
4420
4421 mutable std::list<value_type> remainder_; // modified by iteration
4422};
4423
4424TEST(StreamlikeTest, Iteration) {
4425 const int a[5] = { 2, 1, 4, 5, 3 };
4426 Streamlike<int> s(a, a + 5);
4427 Streamlike<int>::const_iterator it = s.begin();
4428 const int* ip = a;
4429 while (it != s.end()) {
4430 SCOPED_TRACE(ip - a);
4431 EXPECT_EQ(*ip++, *it++);
4432 }
4433}
4434
4435TEST(WhenSortedTest, WorksForStreamlike) {
4436 // Streamlike 'container' provides only minimal iterator support.
4437 // Its iterators are tagged with input_iterator_tag.
4438 const int a[5] = { 2, 1, 4, 5, 3 };
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004439 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004440 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
4441 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4442}
4443
4444TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00004445 const int a[] = { 2, 1, 4, 5, 3 };
4446 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004447 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
4448 EXPECT_THAT(s, WhenSorted(vector_match));
4449 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4450}
4451
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004452// Tests using ElementsAre() and ElementsAreArray() with stream-like
4453// "containers".
4454
4455TEST(ElemensAreStreamTest, WorksForStreamlike) {
4456 const int a[5] = { 1, 2, 3, 4, 5 };
4457 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4458 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
4459 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
4460}
4461
4462TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
4463 const int a[5] = { 1, 2, 3, 4, 5 };
4464 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4465
4466 vector<int> expected;
4467 expected.push_back(1);
4468 expected.push_back(2);
4469 expected.push_back(3);
4470 expected.push_back(4);
4471 expected.push_back(5);
4472 EXPECT_THAT(s, ElementsAreArray(expected));
4473
4474 expected[3] = 0;
4475 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
4476}
4477
zhanyong.wanfb25d532013-07-28 08:24:00 +00004478// Tests for UnorderedElementsAreArray()
4479
4480TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
4481 const int a[] = { 0, 1, 2, 3, 4 };
4482 std::vector<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4483 do {
4484 StringMatchResultListener listener;
4485 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
4486 s, &listener)) << listener.str();
4487 } while (std::next_permutation(s.begin(), s.end()));
4488}
4489
4490TEST(UnorderedElementsAreArrayTest, VectorBool) {
4491 const bool a[] = { 0, 1, 0, 1, 1 };
4492 const bool b[] = { 1, 0, 1, 1, 0 };
4493 std::vector<bool> expected(a, a + GMOCK_ARRAY_SIZE_(a));
4494 std::vector<bool> actual(b, b + GMOCK_ARRAY_SIZE_(b));
4495 StringMatchResultListener listener;
4496 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
4497 actual, &listener)) << listener.str();
4498}
4499
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004500TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
4501 // Streamlike 'container' provides only minimal iterator support.
4502 // Its iterators are tagged with input_iterator_tag, and it has no
4503 // size() or empty() methods.
4504 const int a[5] = { 2, 1, 4, 5, 3 };
4505 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4506
4507 ::std::vector<int> expected;
4508 expected.push_back(1);
4509 expected.push_back(2);
4510 expected.push_back(3);
4511 expected.push_back(4);
4512 expected.push_back(5);
4513 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
4514
4515 expected.push_back(6);
4516 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
4517}
4518
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004519#if GTEST_LANG_CXX11
4520
4521TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
4522 const int a[5] = { 2, 1, 4, 5, 3 };
4523 EXPECT_THAT(a, UnorderedElementsAreArray({ 1, 2, 3, 4, 5 }));
4524 EXPECT_THAT(a, Not(UnorderedElementsAreArray({ 1, 2, 3, 4, 6 })));
4525}
4526
4527TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
4528 const string a[5] = { "a", "b", "c", "d", "e" };
4529 EXPECT_THAT(a, UnorderedElementsAreArray({ "a", "b", "c", "d", "e" }));
4530 EXPECT_THAT(a, Not(UnorderedElementsAreArray({ "a", "b", "c", "d", "ef" })));
4531}
4532
4533TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
4534 const int a[5] = { 2, 1, 4, 5, 3 };
4535 EXPECT_THAT(a, UnorderedElementsAreArray(
4536 { Eq(1), Eq(2), Eq(3), Eq(4), Eq(5) }));
4537 EXPECT_THAT(a, Not(UnorderedElementsAreArray(
4538 { Eq(1), Eq(2), Eq(3), Eq(4), Eq(6) })));
4539}
4540
4541TEST(UnorderedElementsAreArrayTest,
4542 TakesInitializerListOfDifferentTypedMatchers) {
4543 const int a[5] = { 2, 1, 4, 5, 3 };
4544 // The compiler cannot infer the type of the initializer list if its
4545 // elements have different types. We must explicitly specify the
4546 // unified element type in this case.
4547 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
4548 { Eq(1), Ne(-2), Ge(3), Le(4), Eq(5) }));
4549 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
4550 { Eq(1), Ne(-2), Ge(3), Le(4), Eq(6) })));
4551}
4552
4553#endif // GTEST_LANG_CXX11
4554
zhanyong.wanfb25d532013-07-28 08:24:00 +00004555class UnorderedElementsAreTest : public testing::Test {
4556 protected:
4557 typedef std::vector<int> IntVec;
4558};
4559
4560TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
4561 const int a[] = { 1, 2, 3 };
4562 std::vector<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4563 do {
4564 StringMatchResultListener listener;
4565 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4566 s, &listener)) << listener.str();
4567 } while (std::next_permutation(s.begin(), s.end()));
4568}
4569
4570TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
4571 const int a[] = { 1, 2, 3 };
4572 std::vector<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4573 std::vector<Matcher<int> > mv;
4574 mv.push_back(1);
4575 mv.push_back(2);
4576 mv.push_back(2);
4577 // The element with value '3' matches nothing: fail fast.
4578 StringMatchResultListener listener;
4579 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4580 s, &listener)) << listener.str();
4581}
4582
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004583TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
4584 // Streamlike 'container' provides only minimal iterator support.
4585 // Its iterators are tagged with input_iterator_tag, and it has no
4586 // size() or empty() methods.
4587 const int a[5] = { 2, 1, 4, 5, 3 };
4588 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4589
4590 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
4591 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
4592}
4593
zhanyong.wanfb25d532013-07-28 08:24:00 +00004594// One naive implementation of the matcher runs in O(N!) time, which is too
4595// slow for many real-world inputs. This test shows that our matcher can match
4596// 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
4597// iterations and obviously effectively incomputable.
4598// [ RUN ] UnorderedElementsAreTest.Performance
4599// [ OK ] UnorderedElementsAreTest.Performance (4 ms)
4600TEST_F(UnorderedElementsAreTest, Performance) {
4601 std::vector<int> s;
4602 std::vector<Matcher<int> > mv;
4603 for (int i = 0; i < 100; ++i) {
4604 s.push_back(i);
4605 mv.push_back(_);
4606 }
4607 mv[50] = Eq(0);
4608 StringMatchResultListener listener;
4609 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4610 s, &listener)) << listener.str();
4611}
4612
4613// Another variant of 'Performance' with similar expectations.
4614// [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
4615// [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
4616TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
4617 std::vector<int> s;
4618 std::vector<Matcher<int> > mv;
4619 for (int i = 0; i < 100; ++i) {
4620 s.push_back(i);
4621 if (i & 1) {
4622 mv.push_back(_);
4623 } else {
4624 mv.push_back(i);
4625 }
4626 }
4627 StringMatchResultListener listener;
4628 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4629 s, &listener)) << listener.str();
4630}
4631
4632TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
4633 std::vector<int> v;
4634 v.push_back(4);
4635 StringMatchResultListener listener;
4636 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4637 v, &listener)) << listener.str();
4638 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
4639}
4640
4641TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
4642 std::vector<int> v;
4643 StringMatchResultListener listener;
4644 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4645 v, &listener)) << listener.str();
4646 EXPECT_THAT(listener.str(), Eq(""));
4647}
4648
4649TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
4650 std::vector<int> v;
4651 v.push_back(1);
4652 v.push_back(1);
4653 StringMatchResultListener listener;
4654 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4655 v, &listener)) << listener.str();
4656 EXPECT_THAT(
4657 listener.str(),
4658 Eq("where the following matchers don't match any elements:\n"
4659 "matcher #1: is equal to 2"));
4660}
4661
4662TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
4663 std::vector<int> v;
4664 v.push_back(1);
4665 v.push_back(2);
4666 StringMatchResultListener listener;
4667 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
4668 v, &listener)) << listener.str();
4669 EXPECT_THAT(
4670 listener.str(),
4671 Eq("where the following elements don't match any matchers:\n"
4672 "element #1: 2"));
4673}
4674
4675TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
4676 std::vector<int> v;
4677 v.push_back(2);
4678 v.push_back(3);
4679 StringMatchResultListener listener;
4680 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4681 v, &listener)) << listener.str();
4682 EXPECT_THAT(
4683 listener.str(),
4684 Eq("where"
4685 " the following matchers don't match any elements:\n"
4686 "matcher #0: is equal to 1\n"
4687 "and"
4688 " where"
4689 " the following elements don't match any matchers:\n"
4690 "element #1: 3"));
4691}
4692
4693// Test helper for formatting element, matcher index pairs in expectations.
4694static string EMString(int element, int matcher) {
4695 stringstream ss;
4696 ss << "(element #" << element << ", matcher #" << matcher << ")";
4697 return ss.str();
4698}
4699
4700TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
4701 // A situation where all elements and matchers have a match
4702 // associated with them, but the max matching is not perfect.
4703 std::vector<string> v;
4704 v.push_back("a");
4705 v.push_back("b");
4706 v.push_back("c");
4707 StringMatchResultListener listener;
4708 EXPECT_FALSE(ExplainMatchResult(
4709 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
4710 << listener.str();
4711
4712 string prefix =
4713 "where no permutation of the elements can satisfy all matchers, "
4714 "and the closest match is 2 of 3 matchers with the "
4715 "pairings:\n";
4716
4717 // We have to be a bit loose here, because there are 4 valid max matches.
4718 EXPECT_THAT(
4719 listener.str(),
4720 AnyOf(prefix + "{\n " + EMString(0, 0) +
4721 ",\n " + EMString(1, 2) + "\n}",
4722 prefix + "{\n " + EMString(0, 1) +
4723 ",\n " + EMString(1, 2) + "\n}",
4724 prefix + "{\n " + EMString(0, 0) +
4725 ",\n " + EMString(2, 2) + "\n}",
4726 prefix + "{\n " + EMString(0, 1) +
4727 ",\n " + EMString(2, 2) + "\n}"));
4728}
4729
4730TEST_F(UnorderedElementsAreTest, Describe) {
4731 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
4732 Eq("is empty"));
4733 EXPECT_THAT(
4734 Describe<IntVec>(UnorderedElementsAre(345)),
4735 Eq("has 1 element and that element is equal to 345"));
4736 EXPECT_THAT(
4737 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
4738 Eq("has 3 elements and there exists some permutation "
4739 "of elements such that:\n"
4740 " - element #0 is equal to 111, and\n"
4741 " - element #1 is equal to 222, and\n"
4742 " - element #2 is equal to 333"));
4743}
4744
4745TEST_F(UnorderedElementsAreTest, DescribeNegation) {
4746 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
4747 Eq("isn't empty"));
4748 EXPECT_THAT(
4749 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
4750 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
4751 EXPECT_THAT(
4752 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
4753 Eq("doesn't have 3 elements, or there exists no permutation "
4754 "of elements such that:\n"
4755 " - element #0 is equal to 123, and\n"
4756 " - element #1 is equal to 234, and\n"
4757 " - element #2 is equal to 345"));
4758}
4759
4760namespace {
4761
4762// Used as a check on the more complex max flow method used in the
4763// real testing::internal::FindMaxBipartiteMatching. This method is
4764// compatible but runs in worst-case factorial time, so we only
4765// use it in testing for small problem sizes.
4766template <typename Graph>
4767class BacktrackingMaxBPMState {
4768 public:
4769 // Does not take ownership of 'g'.
4770 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
4771
4772 ElementMatcherPairs Compute() {
4773 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
4774 return best_so_far_;
4775 }
4776 lhs_used_.assign(graph_->LhsSize(), kUnused);
4777 rhs_used_.assign(graph_->RhsSize(), kUnused);
4778 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
4779 matches_.clear();
4780 RecurseInto(irhs);
4781 if (best_so_far_.size() == graph_->RhsSize())
4782 break;
4783 }
4784 return best_so_far_;
4785 }
4786
4787 private:
4788 static const size_t kUnused = static_cast<size_t>(-1);
4789
4790 void PushMatch(size_t lhs, size_t rhs) {
4791 matches_.push_back(ElementMatcherPair(lhs, rhs));
4792 lhs_used_[lhs] = rhs;
4793 rhs_used_[rhs] = lhs;
4794 if (matches_.size() > best_so_far_.size()) {
4795 best_so_far_ = matches_;
4796 }
4797 }
4798
4799 void PopMatch() {
4800 const ElementMatcherPair& back = matches_.back();
4801 lhs_used_[back.first] = kUnused;
4802 rhs_used_[back.second] = kUnused;
4803 matches_.pop_back();
4804 }
4805
4806 bool RecurseInto(size_t irhs) {
4807 if (rhs_used_[irhs] != kUnused) {
4808 return true;
4809 }
4810 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
4811 if (lhs_used_[ilhs] != kUnused) {
4812 continue;
4813 }
4814 if (!graph_->HasEdge(ilhs, irhs)) {
4815 continue;
4816 }
4817 PushMatch(ilhs, irhs);
4818 if (best_so_far_.size() == graph_->RhsSize()) {
4819 return false;
4820 }
4821 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
4822 if (!RecurseInto(mi)) return false;
4823 }
4824 PopMatch();
4825 }
4826 return true;
4827 }
4828
4829 const Graph* graph_; // not owned
4830 std::vector<size_t> lhs_used_;
4831 std::vector<size_t> rhs_used_;
4832 ElementMatcherPairs matches_;
4833 ElementMatcherPairs best_so_far_;
4834};
4835
4836template <typename Graph>
4837const size_t BacktrackingMaxBPMState<Graph>::kUnused;
4838
4839} // namespace
4840
4841// Implement a simple backtracking algorithm to determine if it is possible
4842// to find one element per matcher, without reusing elements.
4843template <typename Graph>
4844ElementMatcherPairs
4845FindBacktrackingMaxBPM(const Graph& g) {
4846 return BacktrackingMaxBPMState<Graph>(&g).Compute();
4847}
4848
4849class BacktrackingBPMTest : public ::testing::Test { };
4850
4851// Tests the MaxBipartiteMatching algorithm with square matrices.
4852// The single int param is the # of nodes on each of the left and right sides.
4853class BipartiteTest : public ::testing::TestWithParam<int> { };
4854
4855// Verify all match graphs up to some moderate number of edges.
4856TEST_P(BipartiteTest, Exhaustive) {
4857 int nodes = GetParam();
4858 MatchMatrix graph(nodes, nodes);
4859 do {
4860 ElementMatcherPairs matches =
4861 internal::FindMaxBipartiteMatching(graph);
4862 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
4863 << "graph: " << graph.DebugString();
4864 // Check that all elements of matches are in the graph.
4865 // Check that elements of first and second are unique.
4866 std::vector<bool> seen_element(graph.LhsSize());
4867 std::vector<bool> seen_matcher(graph.RhsSize());
4868 SCOPED_TRACE(PrintToString(matches));
4869 for (size_t i = 0; i < matches.size(); ++i) {
4870 size_t ilhs = matches[i].first;
4871 size_t irhs = matches[i].second;
4872 EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
4873 EXPECT_FALSE(seen_element[ilhs]);
4874 EXPECT_FALSE(seen_matcher[irhs]);
4875 seen_element[ilhs] = true;
4876 seen_matcher[irhs] = true;
4877 }
4878 } while (graph.NextGraph());
4879}
4880
4881INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest,
4882 ::testing::Range(0, 5));
4883
4884// Parameterized by a pair interpreted as (LhsSize, RhsSize).
4885class BipartiteNonSquareTest
4886 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
4887};
4888
4889TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
4890 // .......
4891 // 0:-----\ :
4892 // 1:---\ | :
4893 // 2:---\ | :
4894 // 3:-\ | | :
4895 // :.......:
4896 // 0 1 2
4897 MatchMatrix g(4, 3);
4898 static const int kEdges[][2] = { {0, 2}, {1, 1}, {2, 1}, {3, 0} };
4899 for (size_t i = 0; i < GMOCK_ARRAY_SIZE_(kEdges); ++i) {
4900 g.SetEdge(kEdges[i][0], kEdges[i][1], true);
4901 }
4902 EXPECT_THAT(FindBacktrackingMaxBPM(g),
4903 ElementsAre(Pair(3, 0),
4904 Pair(AnyOf(1, 2), 1),
4905 Pair(0, 2))) << g.DebugString();
4906}
4907
4908// Verify a few nonsquare matrices.
4909TEST_P(BipartiteNonSquareTest, Exhaustive) {
4910 size_t nlhs = GetParam().first;
4911 size_t nrhs = GetParam().second;
4912 MatchMatrix graph(nlhs, nrhs);
4913 do {
4914 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
4915 internal::FindMaxBipartiteMatching(graph).size())
4916 << "graph: " << graph.DebugString()
4917 << "\nbacktracking: "
4918 << PrintToString(FindBacktrackingMaxBPM(graph))
4919 << "\nmax flow: "
4920 << PrintToString(internal::FindMaxBipartiteMatching(graph));
4921 } while (graph.NextGraph());
4922}
4923
4924INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest,
4925 testing::Values(
4926 std::make_pair(1, 2),
4927 std::make_pair(2, 1),
4928 std::make_pair(3, 2),
4929 std::make_pair(2, 3),
4930 std::make_pair(4, 1),
4931 std::make_pair(1, 4),
4932 std::make_pair(4, 3),
4933 std::make_pair(3, 4)));
4934
4935class BipartiteRandomTest
4936 : public ::testing::TestWithParam<std::pair<int, int> > {
4937};
4938
4939// Verifies a large sample of larger graphs.
4940TEST_P(BipartiteRandomTest, LargerNets) {
4941 int nodes = GetParam().first;
4942 int iters = GetParam().second;
4943 MatchMatrix graph(nodes, nodes);
4944
4945 testing::internal::Int32 seed = GTEST_FLAG(random_seed);
4946 if (seed == 0) {
4947 seed = static_cast<testing::internal::Int32>(time(NULL));
4948 }
4949
4950 for (; iters > 0; --iters, ++seed) {
4951 srand(static_cast<int>(seed));
4952 graph.Randomize();
4953 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
4954 internal::FindMaxBipartiteMatching(graph).size())
4955 << " graph: " << graph.DebugString()
4956 << "\nTo reproduce the failure, rerun the test with the flag"
4957 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
4958 }
4959}
4960
4961// Test argument is a std::pair<int, int> representing (nodes, iters).
4962INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest,
4963 testing::Values(
4964 std::make_pair(5, 10000),
4965 std::make_pair(6, 5000),
4966 std::make_pair(7, 2000),
4967 std::make_pair(8, 500),
4968 std::make_pair(9, 100)));
4969
zhanyong.wan736baa82010-09-27 17:44:16 +00004970// Tests IsReadableTypeName().
4971
4972TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
4973 EXPECT_TRUE(IsReadableTypeName("int"));
4974 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
4975 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
4976 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
4977}
4978
4979TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
4980 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
4981 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
4982 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
4983}
4984
4985TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
4986 EXPECT_FALSE(
4987 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
4988 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
4989}
4990
4991TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
4992 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
4993}
4994
zhanyong.wan4a5330d2009-02-19 00:36:44 +00004995// Tests JoinAsTuple().
4996
4997TEST(JoinAsTupleTest, JoinsEmptyTuple) {
4998 EXPECT_EQ("", JoinAsTuple(Strings()));
4999}
5000
5001TEST(JoinAsTupleTest, JoinsOneTuple) {
5002 const char* fields[] = { "1" };
5003 EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
5004}
5005
5006TEST(JoinAsTupleTest, JoinsTwoTuple) {
5007 const char* fields[] = { "1", "a" };
5008 EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
5009}
5010
5011TEST(JoinAsTupleTest, JoinsTenTuple) {
5012 const char* fields[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
5013 EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
5014 JoinAsTuple(Strings(fields, fields + 10)));
5015}
5016
5017// Tests FormatMatcherDescription().
5018
5019TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
5020 EXPECT_EQ("is even",
zhanyong.wanb4140802010-06-08 22:53:57 +00005021 FormatMatcherDescription(false, "IsEven", Strings()));
5022 EXPECT_EQ("not (is even)",
5023 FormatMatcherDescription(true, "IsEven", Strings()));
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005024
5025 const char* params[] = { "5" };
5026 EXPECT_EQ("equals 5",
zhanyong.wanb4140802010-06-08 22:53:57 +00005027 FormatMatcherDescription(false, "Equals",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005028 Strings(params, params + 1)));
5029
5030 const char* params2[] = { "5", "8" };
5031 EXPECT_EQ("is in range (5, 8)",
zhanyong.wanb4140802010-06-08 22:53:57 +00005032 FormatMatcherDescription(false, "IsInRange",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00005033 Strings(params2, params2 + 2)));
5034}
5035
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00005036// Tests PolymorphicMatcher::mutable_impl().
5037TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
5038 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5039 DivisibleByImpl& impl = m.mutable_impl();
5040 EXPECT_EQ(42, impl.divider());
5041
5042 impl.set_divider(0);
5043 EXPECT_EQ(0, m.mutable_impl().divider());
5044}
5045
5046// Tests PolymorphicMatcher::impl().
5047TEST(PolymorphicMatcherTest, CanAccessImpl) {
5048 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5049 const DivisibleByImpl& impl = m.impl();
5050 EXPECT_EQ(42, impl.divider());
5051}
5052
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005053TEST(MatcherTupleTest, ExplainsMatchFailure) {
5054 stringstream ss1;
5055 ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
5056 make_tuple('a', 10), &ss1);
5057 EXPECT_EQ("", ss1.str()); // Successful match.
5058
5059 stringstream ss2;
5060 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5061 make_tuple(2, 'b'), &ss2);
5062 EXPECT_EQ(" Expected arg #0: is > 5\n"
5063 " Actual: 2, which is 3 less than 5\n"
zhanyong.wand60c5f42010-07-21 22:21:07 +00005064 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
5065 " Actual: 'b' (98, 0x62)\n",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005066 ss2.str()); // Failed match where both arguments need explanation.
5067
5068 stringstream ss3;
5069 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5070 make_tuple(2, 'a'), &ss3);
5071 EXPECT_EQ(" Expected arg #0: is > 5\n"
5072 " Actual: 2, which is 3 less than 5\n",
5073 ss3.str()); // Failed match where only one argument needs
5074 // explanation.
5075}
5076
zhanyong.wan33605ba2010-04-22 23:37:47 +00005077// Tests Each().
5078
5079TEST(EachTest, ExplainsMatchResultCorrectly) {
5080 set<int> a; // empty
5081
5082 Matcher<set<int> > m = Each(2);
5083 EXPECT_EQ("", Explain(m, a));
5084
zhanyong.wan736baa82010-09-27 17:44:16 +00005085 Matcher<const int(&)[1]> n = Each(1); // NOLINT
zhanyong.wan33605ba2010-04-22 23:37:47 +00005086
5087 const int b[1] = { 1 };
5088 EXPECT_EQ("", Explain(n, b));
5089
5090 n = Each(3);
5091 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
5092
5093 a.insert(1);
5094 a.insert(2);
5095 a.insert(3);
5096 m = Each(GreaterThan(0));
5097 EXPECT_EQ("", Explain(m, a));
5098
5099 m = Each(GreaterThan(10));
5100 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
5101 Explain(m, a));
5102}
5103
5104TEST(EachTest, DescribesItselfCorrectly) {
5105 Matcher<vector<int> > m = Each(1);
5106 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
5107
5108 Matcher<vector<int> > m2 = Not(m);
5109 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
5110}
5111
5112TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
5113 vector<int> some_vector;
5114 EXPECT_THAT(some_vector, Each(1));
5115 some_vector.push_back(3);
5116 EXPECT_THAT(some_vector, Not(Each(1)));
5117 EXPECT_THAT(some_vector, Each(3));
5118 some_vector.push_back(1);
5119 some_vector.push_back(2);
5120 EXPECT_THAT(some_vector, Not(Each(3)));
5121 EXPECT_THAT(some_vector, Each(Lt(3.5)));
5122
5123 vector<string> another_vector;
5124 another_vector.push_back("fee");
5125 EXPECT_THAT(another_vector, Each(string("fee")));
5126 another_vector.push_back("fie");
5127 another_vector.push_back("foe");
5128 another_vector.push_back("fum");
5129 EXPECT_THAT(another_vector, Not(Each(string("fee"))));
5130}
5131
5132TEST(EachTest, MatchesMapWhenAllElementsMatch) {
5133 map<const char*, int> my_map;
5134 const char* bar = "a string";
5135 my_map[bar] = 2;
5136 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
5137
5138 map<string, int> another_map;
5139 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5140 another_map["fee"] = 1;
5141 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5142 another_map["fie"] = 2;
5143 another_map["foe"] = 3;
5144 another_map["fum"] = 4;
5145 EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1))));
5146 EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1))));
5147 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
5148}
5149
5150TEST(EachTest, AcceptsMatcher) {
5151 const int a[] = { 1, 2, 3 };
5152 EXPECT_THAT(a, Each(Gt(0)));
5153 EXPECT_THAT(a, Not(Each(Gt(1))));
5154}
5155
5156TEST(EachTest, WorksForNativeArrayAsTuple) {
5157 const int a[] = { 1, 2 };
5158 const int* const pointer = a;
5159 EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
5160 EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
5161}
5162
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005163// For testing Pointwise().
5164class IsHalfOfMatcher {
5165 public:
5166 template <typename T1, typename T2>
5167 bool MatchAndExplain(const tuple<T1, T2>& a_pair,
5168 MatchResultListener* listener) const {
5169 if (get<0>(a_pair) == get<1>(a_pair)/2) {
5170 *listener << "where the second is " << get<1>(a_pair);
5171 return true;
5172 } else {
5173 *listener << "where the second/2 is " << get<1>(a_pair)/2;
5174 return false;
5175 }
5176 }
5177
5178 void DescribeTo(ostream* os) const {
5179 *os << "are a pair where the first is half of the second";
5180 }
5181
5182 void DescribeNegationTo(ostream* os) const {
5183 *os << "are a pair where the first isn't half of the second";
5184 }
5185};
5186
5187PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
5188 return MakePolymorphicMatcher(IsHalfOfMatcher());
5189}
5190
5191TEST(PointwiseTest, DescribesSelf) {
5192 vector<int> rhs;
5193 rhs.push_back(1);
5194 rhs.push_back(2);
5195 rhs.push_back(3);
5196 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
5197 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
5198 "in { 1, 2, 3 } are a pair where the first is half of the second",
5199 Describe(m));
5200 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
5201 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
5202 "where the first isn't half of the second",
5203 DescribeNegation(m));
5204}
5205
5206TEST(PointwiseTest, MakesCopyOfRhs) {
5207 list<signed char> rhs;
5208 rhs.push_back(2);
5209 rhs.push_back(4);
5210
5211 int lhs[] = { 1, 2 };
5212 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
5213 EXPECT_THAT(lhs, m);
5214
5215 // Changing rhs now shouldn't affect m, which made a copy of rhs.
5216 rhs.push_back(6);
5217 EXPECT_THAT(lhs, m);
5218}
5219
5220TEST(PointwiseTest, WorksForLhsNativeArray) {
5221 const int lhs[] = { 1, 2, 3 };
5222 vector<int> rhs;
5223 rhs.push_back(2);
5224 rhs.push_back(4);
5225 rhs.push_back(6);
5226 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
5227 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5228}
5229
5230TEST(PointwiseTest, WorksForRhsNativeArray) {
5231 const int rhs[] = { 1, 2, 3 };
5232 vector<int> lhs;
5233 lhs.push_back(2);
5234 lhs.push_back(4);
5235 lhs.push_back(6);
5236 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
5237 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
5238}
5239
5240TEST(PointwiseTest, RejectsWrongSize) {
5241 const double lhs[2] = { 1, 2 };
5242 const int rhs[1] = { 0 };
5243 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5244 EXPECT_EQ("which contains 2 values",
5245 Explain(Pointwise(Gt(), rhs), lhs));
5246
5247 const int rhs2[3] = { 0, 1, 2 };
5248 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
5249}
5250
5251TEST(PointwiseTest, RejectsWrongContent) {
5252 const double lhs[3] = { 1, 2, 3 };
5253 const int rhs[3] = { 2, 6, 4 };
5254 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
5255 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
5256 "where the second/2 is 3",
5257 Explain(Pointwise(IsHalfOf(), rhs), lhs));
5258}
5259
5260TEST(PointwiseTest, AcceptsCorrectContent) {
5261 const double lhs[3] = { 1, 2, 3 };
5262 const int rhs[3] = { 2, 4, 6 };
5263 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
5264 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
5265}
5266
5267TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
5268 const double lhs[3] = { 1, 2, 3 };
5269 const int rhs[3] = { 2, 4, 6 };
5270 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5271 EXPECT_THAT(lhs, Pointwise(m1, rhs));
5272 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
5273
5274 // This type works as a tuple<const double&, const int&> can be
5275 // implicitly cast to tuple<double, int>.
5276 const Matcher<tuple<double, int> > m2 = IsHalfOf();
5277 EXPECT_THAT(lhs, Pointwise(m2, rhs));
5278 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
5279}
5280
shiqiane35fdd92008-12-10 05:08:54 +00005281} // namespace gmock_matchers_test
5282} // namespace testing