blob: 4ce1e4a5224bfd0f4a4942df320f5f81660addec [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:
zhanyong.wan35877b72013-09-18 17:51:08 +00002648 typedef testing::internal::FloatingPoint<RawType> Floating;
shiqiane35fdd92008-12-10 05:08:54 +00002649 typedef typename Floating::Bits Bits;
2650
zhanyong.wan35877b72013-09-18 17:51:08 +00002651 FloatingPointTest()
2652 : max_ulps_(Floating::kMaxUlps),
2653 zero_bits_(Floating(0).bits()),
2654 one_bits_(Floating(1).bits()),
2655 infinity_bits_(Floating(Floating::Infinity()).bits()),
2656 close_to_positive_zero_(
2657 Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)),
2658 close_to_negative_zero_(
2659 -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)),
2660 further_from_negative_zero_(-Floating::ReinterpretBits(
2661 zero_bits_ + max_ulps_ + 1 - max_ulps_/2)),
2662 close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),
2663 further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),
2664 infinity_(Floating::Infinity()),
2665 close_to_infinity_(
2666 Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),
2667 further_from_infinity_(
2668 Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),
2669 max_(Floating::Max()),
2670 nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),
2671 nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {
shiqiane35fdd92008-12-10 05:08:54 +00002672 }
2673
2674 void TestSize() {
2675 EXPECT_EQ(sizeof(RawType), sizeof(Bits));
2676 }
2677
2678 // A battery of tests for FloatingEqMatcher::Matches.
2679 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2680 void TestMatches(
2681 testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {
2682 Matcher<RawType> m1 = matcher_maker(0.0);
2683 EXPECT_TRUE(m1.Matches(-0.0));
2684 EXPECT_TRUE(m1.Matches(close_to_positive_zero_));
2685 EXPECT_TRUE(m1.Matches(close_to_negative_zero_));
2686 EXPECT_FALSE(m1.Matches(1.0));
2687
2688 Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);
2689 EXPECT_FALSE(m2.Matches(further_from_negative_zero_));
2690
2691 Matcher<RawType> m3 = matcher_maker(1.0);
2692 EXPECT_TRUE(m3.Matches(close_to_one_));
2693 EXPECT_FALSE(m3.Matches(further_from_one_));
2694
2695 // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.
2696 EXPECT_FALSE(m3.Matches(0.0));
2697
2698 Matcher<RawType> m4 = matcher_maker(-infinity_);
2699 EXPECT_TRUE(m4.Matches(-close_to_infinity_));
2700
2701 Matcher<RawType> m5 = matcher_maker(infinity_);
2702 EXPECT_TRUE(m5.Matches(close_to_infinity_));
2703
2704 // This is interesting as the representations of infinity_ and nan1_
2705 // are only 1 DLP apart.
2706 EXPECT_FALSE(m5.Matches(nan1_));
2707
2708 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2709 // some cases.
2710 Matcher<const RawType&> m6 = matcher_maker(0.0);
2711 EXPECT_TRUE(m6.Matches(-0.0));
2712 EXPECT_TRUE(m6.Matches(close_to_positive_zero_));
2713 EXPECT_FALSE(m6.Matches(1.0));
2714
2715 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2716 // cases.
2717 Matcher<RawType&> m7 = matcher_maker(0.0);
2718 RawType x = 0.0;
2719 EXPECT_TRUE(m7.Matches(x));
2720 x = 0.01f;
2721 EXPECT_FALSE(m7.Matches(x));
2722 }
2723
2724 // Pre-calculated numbers to be used by the tests.
2725
zhanyong.wan35877b72013-09-18 17:51:08 +00002726 const size_t max_ulps_;
shiqiane35fdd92008-12-10 05:08:54 +00002727
zhanyong.wan35877b72013-09-18 17:51:08 +00002728 const Bits zero_bits_; // The bits that represent 0.0.
2729 const Bits one_bits_; // The bits that represent 1.0.
2730 const Bits infinity_bits_; // The bits that represent +infinity.
shiqiane35fdd92008-12-10 05:08:54 +00002731
zhanyong.wan35877b72013-09-18 17:51:08 +00002732 // Some numbers close to 0.0.
2733 const RawType close_to_positive_zero_;
2734 const RawType close_to_negative_zero_;
2735 const RawType further_from_negative_zero_;
shiqiane35fdd92008-12-10 05:08:54 +00002736
zhanyong.wan35877b72013-09-18 17:51:08 +00002737 // Some numbers close to 1.0.
2738 const RawType close_to_one_;
2739 const RawType further_from_one_;
2740
2741 // Some numbers close to +infinity.
2742 const RawType infinity_;
2743 const RawType close_to_infinity_;
2744 const RawType further_from_infinity_;
2745
2746 // Maximum representable value that's not infinity.
2747 const RawType max_;
2748
2749 // Some NaNs.
2750 const RawType nan1_;
2751 const RawType nan2_;
shiqiane35fdd92008-12-10 05:08:54 +00002752};
2753
zhanyong.wan616180e2013-06-18 18:49:51 +00002754// Tests floating-point matchers with fixed epsilons.
2755template <typename RawType>
2756class FloatingPointNearTest : public FloatingPointTest<RawType> {
2757 protected:
2758 typedef FloatingPointTest<RawType> ParentType;
2759
2760 // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.
2761 // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.
2762 void TestNearMatches(
2763 testing::internal::FloatingEqMatcher<RawType>
2764 (*matcher_maker)(RawType, RawType)) {
2765 Matcher<RawType> m1 = matcher_maker(0.0, 0.0);
2766 EXPECT_TRUE(m1.Matches(0.0));
2767 EXPECT_TRUE(m1.Matches(-0.0));
2768 EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));
2769 EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));
2770 EXPECT_FALSE(m1.Matches(1.0));
2771
2772 Matcher<RawType> m2 = matcher_maker(0.0, 1.0);
2773 EXPECT_TRUE(m2.Matches(0.0));
2774 EXPECT_TRUE(m2.Matches(-0.0));
2775 EXPECT_TRUE(m2.Matches(1.0));
2776 EXPECT_TRUE(m2.Matches(-1.0));
2777 EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));
2778 EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));
2779
2780 // Check that inf matches inf, regardless of the of the specified max
2781 // absolute error.
2782 Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);
2783 EXPECT_TRUE(m3.Matches(ParentType::infinity_));
2784 EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));
2785 EXPECT_FALSE(m3.Matches(-ParentType::infinity_));
2786
2787 Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);
2788 EXPECT_TRUE(m4.Matches(-ParentType::infinity_));
2789 EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));
2790 EXPECT_FALSE(m4.Matches(ParentType::infinity_));
2791
2792 // Test various overflow scenarios.
zhanyong.wan35877b72013-09-18 17:51:08 +00002793 Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);
2794 EXPECT_TRUE(m5.Matches(ParentType::max_));
2795 EXPECT_FALSE(m5.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002796
zhanyong.wan35877b72013-09-18 17:51:08 +00002797 Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);
2798 EXPECT_FALSE(m6.Matches(ParentType::max_));
2799 EXPECT_TRUE(m6.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002800
zhanyong.wan35877b72013-09-18 17:51:08 +00002801 Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);
2802 EXPECT_TRUE(m7.Matches(ParentType::max_));
2803 EXPECT_FALSE(m7.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002804
zhanyong.wan35877b72013-09-18 17:51:08 +00002805 Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);
2806 EXPECT_FALSE(m8.Matches(ParentType::max_));
2807 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002808
2809 // The difference between max() and -max() normally overflows to infinity,
2810 // but it should still match if the max_abs_error is also infinity.
2811 Matcher<RawType> m9 = matcher_maker(
zhanyong.wan35877b72013-09-18 17:51:08 +00002812 ParentType::max_, ParentType::infinity_);
2813 EXPECT_TRUE(m8.Matches(-ParentType::max_));
zhanyong.wan616180e2013-06-18 18:49:51 +00002814
2815 // matcher_maker can produce a Matcher<const RawType&>, which is needed in
2816 // some cases.
2817 Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);
2818 EXPECT_TRUE(m10.Matches(-0.0));
2819 EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));
2820 EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));
2821
2822 // matcher_maker can produce a Matcher<RawType&>, which is needed in some
2823 // cases.
2824 Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);
2825 RawType x = 0.0;
2826 EXPECT_TRUE(m11.Matches(x));
2827 x = 1.0f;
2828 EXPECT_TRUE(m11.Matches(x));
2829 x = -1.0f;
2830 EXPECT_TRUE(m11.Matches(x));
2831 x = 1.1f;
2832 EXPECT_FALSE(m11.Matches(x));
2833 x = -1.1f;
2834 EXPECT_FALSE(m11.Matches(x));
2835 }
2836};
2837
shiqiane35fdd92008-12-10 05:08:54 +00002838// Instantiate FloatingPointTest for testing floats.
2839typedef FloatingPointTest<float> FloatTest;
2840
2841TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) {
2842 TestMatches(&FloatEq);
2843}
2844
2845TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {
2846 TestMatches(&NanSensitiveFloatEq);
2847}
2848
2849TEST_F(FloatTest, FloatEqCannotMatchNaN) {
2850 // FloatEq never matches NaN.
2851 Matcher<float> m = FloatEq(nan1_);
2852 EXPECT_FALSE(m.Matches(nan1_));
2853 EXPECT_FALSE(m.Matches(nan2_));
2854 EXPECT_FALSE(m.Matches(1.0));
2855}
2856
2857TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {
2858 // NanSensitiveFloatEq will match NaN.
2859 Matcher<float> m = NanSensitiveFloatEq(nan1_);
2860 EXPECT_TRUE(m.Matches(nan1_));
2861 EXPECT_TRUE(m.Matches(nan2_));
2862 EXPECT_FALSE(m.Matches(1.0));
2863}
2864
2865TEST_F(FloatTest, FloatEqCanDescribeSelf) {
2866 Matcher<float> m1 = FloatEq(2.0f);
2867 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002868 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002869
2870 Matcher<float> m2 = FloatEq(0.5f);
2871 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002872 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002873
2874 Matcher<float> m3 = FloatEq(nan1_);
2875 EXPECT_EQ("never matches", Describe(m3));
2876 EXPECT_EQ("is anything", DescribeNegation(m3));
2877}
2878
2879TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {
2880 Matcher<float> m1 = NanSensitiveFloatEq(2.0f);
2881 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002882 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002883
2884 Matcher<float> m2 = NanSensitiveFloatEq(0.5f);
2885 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002886 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002887
2888 Matcher<float> m3 = NanSensitiveFloatEq(nan1_);
2889 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002890 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00002891}
2892
zhanyong.wan616180e2013-06-18 18:49:51 +00002893// Instantiate FloatingPointTest for testing floats with a user-specified
2894// max absolute error.
2895typedef FloatingPointNearTest<float> FloatNearTest;
2896
2897TEST_F(FloatNearTest, FloatNearMatches) {
2898 TestNearMatches(&FloatNear);
2899}
2900
2901TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {
2902 TestNearMatches(&NanSensitiveFloatNear);
2903}
2904
2905TEST_F(FloatNearTest, FloatNearCanDescribeSelf) {
2906 Matcher<float> m1 = FloatNear(2.0f, 0.5f);
2907 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2908 EXPECT_EQ(
2909 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2910
2911 Matcher<float> m2 = FloatNear(0.5f, 0.5f);
2912 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2913 EXPECT_EQ(
2914 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2915
2916 Matcher<float> m3 = FloatNear(nan1_, 0.0);
2917 EXPECT_EQ("never matches", Describe(m3));
2918 EXPECT_EQ("is anything", DescribeNegation(m3));
2919}
2920
2921TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {
2922 Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);
2923 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
2924 EXPECT_EQ(
2925 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
2926
2927 Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);
2928 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
2929 EXPECT_EQ(
2930 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
2931
2932 Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);
2933 EXPECT_EQ("is NaN", Describe(m3));
2934 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
2935}
2936
2937TEST_F(FloatNearTest, FloatNearCannotMatchNaN) {
2938 // FloatNear never matches NaN.
2939 Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);
2940 EXPECT_FALSE(m.Matches(nan1_));
2941 EXPECT_FALSE(m.Matches(nan2_));
2942 EXPECT_FALSE(m.Matches(1.0));
2943}
2944
2945TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {
2946 // NanSensitiveFloatNear will match NaN.
2947 Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);
2948 EXPECT_TRUE(m.Matches(nan1_));
2949 EXPECT_TRUE(m.Matches(nan2_));
2950 EXPECT_FALSE(m.Matches(1.0));
2951}
2952
shiqiane35fdd92008-12-10 05:08:54 +00002953// Instantiate FloatingPointTest for testing doubles.
2954typedef FloatingPointTest<double> DoubleTest;
2955
2956TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {
2957 TestMatches(&DoubleEq);
2958}
2959
2960TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {
2961 TestMatches(&NanSensitiveDoubleEq);
2962}
2963
2964TEST_F(DoubleTest, DoubleEqCannotMatchNaN) {
2965 // DoubleEq never matches NaN.
2966 Matcher<double> m = DoubleEq(nan1_);
2967 EXPECT_FALSE(m.Matches(nan1_));
2968 EXPECT_FALSE(m.Matches(nan2_));
2969 EXPECT_FALSE(m.Matches(1.0));
2970}
2971
2972TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {
2973 // NanSensitiveDoubleEq will match NaN.
2974 Matcher<double> m = NanSensitiveDoubleEq(nan1_);
2975 EXPECT_TRUE(m.Matches(nan1_));
2976 EXPECT_TRUE(m.Matches(nan2_));
2977 EXPECT_FALSE(m.Matches(1.0));
2978}
2979
2980TEST_F(DoubleTest, DoubleEqCanDescribeSelf) {
2981 Matcher<double> m1 = DoubleEq(2.0);
2982 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002983 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002984
2985 Matcher<double> m2 = DoubleEq(0.5);
2986 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002987 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00002988
2989 Matcher<double> m3 = DoubleEq(nan1_);
2990 EXPECT_EQ("never matches", Describe(m3));
2991 EXPECT_EQ("is anything", DescribeNegation(m3));
2992}
2993
2994TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {
2995 Matcher<double> m1 = NanSensitiveDoubleEq(2.0);
2996 EXPECT_EQ("is approximately 2", Describe(m1));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00002997 EXPECT_EQ("isn't approximately 2", DescribeNegation(m1));
shiqiane35fdd92008-12-10 05:08:54 +00002998
2999 Matcher<double> m2 = NanSensitiveDoubleEq(0.5);
3000 EXPECT_EQ("is approximately 0.5", Describe(m2));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003001 EXPECT_EQ("isn't approximately 0.5", DescribeNegation(m2));
shiqiane35fdd92008-12-10 05:08:54 +00003002
3003 Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);
3004 EXPECT_EQ("is NaN", Describe(m3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003005 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
shiqiane35fdd92008-12-10 05:08:54 +00003006}
3007
zhanyong.wan616180e2013-06-18 18:49:51 +00003008// Instantiate FloatingPointTest for testing floats with a user-specified
3009// max absolute error.
3010typedef FloatingPointNearTest<double> DoubleNearTest;
3011
3012TEST_F(DoubleNearTest, DoubleNearMatches) {
3013 TestNearMatches(&DoubleNear);
3014}
3015
3016TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {
3017 TestNearMatches(&NanSensitiveDoubleNear);
3018}
3019
3020TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {
3021 Matcher<double> m1 = DoubleNear(2.0, 0.5);
3022 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3023 EXPECT_EQ(
3024 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3025
3026 Matcher<double> m2 = DoubleNear(0.5, 0.5);
3027 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3028 EXPECT_EQ(
3029 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3030
3031 Matcher<double> m3 = DoubleNear(nan1_, 0.0);
3032 EXPECT_EQ("never matches", Describe(m3));
3033 EXPECT_EQ("is anything", DescribeNegation(m3));
3034}
3035
3036TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {
3037 Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);
3038 EXPECT_EQ("is approximately 2 (absolute error <= 0.5)", Describe(m1));
3039 EXPECT_EQ(
3040 "isn't approximately 2 (absolute error > 0.5)", DescribeNegation(m1));
3041
3042 Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);
3043 EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)", Describe(m2));
3044 EXPECT_EQ(
3045 "isn't approximately 0.5 (absolute error > 0.5)", DescribeNegation(m2));
3046
3047 Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);
3048 EXPECT_EQ("is NaN", Describe(m3));
3049 EXPECT_EQ("isn't NaN", DescribeNegation(m3));
3050}
3051
3052TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {
3053 // DoubleNear never matches NaN.
3054 Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);
3055 EXPECT_FALSE(m.Matches(nan1_));
3056 EXPECT_FALSE(m.Matches(nan2_));
3057 EXPECT_FALSE(m.Matches(1.0));
3058}
3059
3060TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {
3061 // NanSensitiveDoubleNear will match NaN.
3062 Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);
3063 EXPECT_TRUE(m.Matches(nan1_));
3064 EXPECT_TRUE(m.Matches(nan2_));
3065 EXPECT_FALSE(m.Matches(1.0));
3066}
3067
shiqiane35fdd92008-12-10 05:08:54 +00003068TEST(PointeeTest, RawPointer) {
3069 const Matcher<int*> m = Pointee(Ge(0));
3070
3071 int n = 1;
3072 EXPECT_TRUE(m.Matches(&n));
3073 n = -1;
3074 EXPECT_FALSE(m.Matches(&n));
3075 EXPECT_FALSE(m.Matches(NULL));
3076}
3077
3078TEST(PointeeTest, RawPointerToConst) {
3079 const Matcher<const double*> m = Pointee(Ge(0));
3080
3081 double x = 1;
3082 EXPECT_TRUE(m.Matches(&x));
3083 x = -1;
3084 EXPECT_FALSE(m.Matches(&x));
3085 EXPECT_FALSE(m.Matches(NULL));
3086}
3087
3088TEST(PointeeTest, ReferenceToConstRawPointer) {
3089 const Matcher<int* const &> m = Pointee(Ge(0));
3090
3091 int n = 1;
3092 EXPECT_TRUE(m.Matches(&n));
3093 n = -1;
3094 EXPECT_FALSE(m.Matches(&n));
3095 EXPECT_FALSE(m.Matches(NULL));
3096}
3097
3098TEST(PointeeTest, ReferenceToNonConstRawPointer) {
3099 const Matcher<double* &> m = Pointee(Ge(0));
3100
3101 double x = 1.0;
3102 double* p = &x;
3103 EXPECT_TRUE(m.Matches(p));
3104 x = -1;
3105 EXPECT_FALSE(m.Matches(p));
3106 p = NULL;
3107 EXPECT_FALSE(m.Matches(p));
3108}
3109
vladlosevada23472012-08-14 15:38:49 +00003110// Minimal const-propagating pointer.
3111template <typename T>
3112class ConstPropagatingPtr {
3113 public:
3114 typedef T element_type;
3115
3116 ConstPropagatingPtr() : val_() {}
3117 explicit ConstPropagatingPtr(T* t) : val_(t) {}
3118 ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}
3119
3120 T* get() { return val_; }
3121 T& operator*() { return *val_; }
3122 // Most smart pointers return non-const T* and T& from the next methods.
3123 const T* get() const { return val_; }
3124 const T& operator*() const { return *val_; }
3125
3126 private:
3127 T* val_;
3128};
3129
3130TEST(PointeeTest, WorksWithConstPropagatingPointers) {
3131 const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5));
3132 int three = 3;
3133 const ConstPropagatingPtr<int> co(&three);
3134 ConstPropagatingPtr<int> o(&three);
3135 EXPECT_TRUE(m.Matches(o));
3136 EXPECT_TRUE(m.Matches(co));
3137 *o = 6;
3138 EXPECT_FALSE(m.Matches(o));
3139 EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));
3140}
3141
shiqiane35fdd92008-12-10 05:08:54 +00003142TEST(PointeeTest, NeverMatchesNull) {
3143 const Matcher<const char*> m = Pointee(_);
3144 EXPECT_FALSE(m.Matches(NULL));
3145}
3146
3147// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).
3148TEST(PointeeTest, MatchesAgainstAValue) {
3149 const Matcher<int*> m = Pointee(5);
3150
3151 int n = 5;
3152 EXPECT_TRUE(m.Matches(&n));
3153 n = -1;
3154 EXPECT_FALSE(m.Matches(&n));
3155 EXPECT_FALSE(m.Matches(NULL));
3156}
3157
3158TEST(PointeeTest, CanDescribeSelf) {
3159 const Matcher<int*> m = Pointee(Gt(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003160 EXPECT_EQ("points to a value that is > 3", Describe(m));
3161 EXPECT_EQ("does not point to a value that is > 3",
shiqiane35fdd92008-12-10 05:08:54 +00003162 DescribeNegation(m));
3163}
3164
shiqiane35fdd92008-12-10 05:08:54 +00003165TEST(PointeeTest, CanExplainMatchResult) {
3166 const Matcher<const string*> m = Pointee(StartsWith("Hi"));
3167
3168 EXPECT_EQ("", Explain(m, static_cast<const string*>(NULL)));
3169
zhanyong.wan736baa82010-09-27 17:44:16 +00003170 const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT
3171 long n = 3; // NOLINT
3172 EXPECT_EQ("which points to 3" + OfType("long") + ", which is 2 more than 1",
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003173 Explain(m2, &n));
3174}
3175
3176TEST(PointeeTest, AlwaysExplainsPointee) {
3177 const Matcher<int*> m = Pointee(0);
3178 int n = 42;
zhanyong.wan736baa82010-09-27 17:44:16 +00003179 EXPECT_EQ("which points to 42" + OfType("int"), Explain(m, &n));
shiqiane35fdd92008-12-10 05:08:54 +00003180}
3181
3182// An uncopyable class.
3183class Uncopyable {
3184 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003185 explicit Uncopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003186
3187 int value() const { return value_; }
3188 private:
3189 const int value_;
3190 GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable);
3191};
3192
3193// Returns true iff x.value() is positive.
3194bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }
3195
3196// A user-defined struct for testing Field().
3197struct AStruct {
3198 AStruct() : x(0), y(1.0), z(5), p(NULL) {}
3199 AStruct(const AStruct& rhs)
3200 : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}
3201
3202 int x; // A non-const field.
3203 const double y; // A const field.
3204 Uncopyable z; // An uncopyable field.
3205 const char* p; // A pointer field.
zhanyong.wan32de5f52009-12-23 00:13:23 +00003206
3207 private:
3208 GTEST_DISALLOW_ASSIGN_(AStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003209};
3210
3211// A derived struct for testing Field().
3212struct DerivedStruct : public AStruct {
3213 char ch;
zhanyong.wan32de5f52009-12-23 00:13:23 +00003214
3215 private:
3216 GTEST_DISALLOW_ASSIGN_(DerivedStruct);
shiqiane35fdd92008-12-10 05:08:54 +00003217};
3218
3219// Tests that Field(&Foo::field, ...) works when field is non-const.
3220TEST(FieldTest, WorksForNonConstField) {
3221 Matcher<AStruct> m = Field(&AStruct::x, Ge(0));
3222
3223 AStruct a;
3224 EXPECT_TRUE(m.Matches(a));
3225 a.x = -1;
3226 EXPECT_FALSE(m.Matches(a));
3227}
3228
3229// Tests that Field(&Foo::field, ...) works when field is const.
3230TEST(FieldTest, WorksForConstField) {
3231 AStruct a;
3232
3233 Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));
3234 EXPECT_TRUE(m.Matches(a));
3235 m = Field(&AStruct::y, Le(0.0));
3236 EXPECT_FALSE(m.Matches(a));
3237}
3238
3239// Tests that Field(&Foo::field, ...) works when field is not copyable.
3240TEST(FieldTest, WorksForUncopyableField) {
3241 AStruct a;
3242
3243 Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));
3244 EXPECT_TRUE(m.Matches(a));
3245 m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));
3246 EXPECT_FALSE(m.Matches(a));
3247}
3248
3249// Tests that Field(&Foo::field, ...) works when field is a pointer.
3250TEST(FieldTest, WorksForPointerField) {
3251 // Matching against NULL.
3252 Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(NULL));
3253 AStruct a;
3254 EXPECT_TRUE(m.Matches(a));
3255 a.p = "hi";
3256 EXPECT_FALSE(m.Matches(a));
3257
3258 // Matching a pointer that is not NULL.
3259 m = Field(&AStruct::p, StartsWith("hi"));
3260 a.p = "hill";
3261 EXPECT_TRUE(m.Matches(a));
3262 a.p = "hole";
3263 EXPECT_FALSE(m.Matches(a));
3264}
3265
3266// Tests that Field() works when the object is passed by reference.
3267TEST(FieldTest, WorksForByRefArgument) {
3268 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3269
3270 AStruct a;
3271 EXPECT_TRUE(m.Matches(a));
3272 a.x = -1;
3273 EXPECT_FALSE(m.Matches(a));
3274}
3275
3276// Tests that Field(&Foo::field, ...) works when the argument's type
3277// is a sub-type of Foo.
3278TEST(FieldTest, WorksForArgumentOfSubType) {
3279 // Note that the matcher expects DerivedStruct but we say AStruct
3280 // inside Field().
3281 Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));
3282
3283 DerivedStruct d;
3284 EXPECT_TRUE(m.Matches(d));
3285 d.x = -1;
3286 EXPECT_FALSE(m.Matches(d));
3287}
3288
3289// Tests that Field(&Foo::field, m) works when field's type and m's
3290// argument type are compatible but not the same.
3291TEST(FieldTest, WorksForCompatibleMatcherType) {
3292 // The field is an int, but the inner matcher expects a signed char.
3293 Matcher<const AStruct&> m = Field(&AStruct::x,
3294 Matcher<signed char>(Ge(0)));
3295
3296 AStruct a;
3297 EXPECT_TRUE(m.Matches(a));
3298 a.x = -1;
3299 EXPECT_FALSE(m.Matches(a));
3300}
3301
3302// Tests that Field() can describe itself.
3303TEST(FieldTest, CanDescribeSelf) {
3304 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3305
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003306 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3307 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003308}
3309
3310// Tests that Field() can explain the match result.
3311TEST(FieldTest, CanExplainMatchResult) {
3312 Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));
3313
3314 AStruct a;
3315 a.x = 1;
zhanyong.wan736baa82010-09-27 17:44:16 +00003316 EXPECT_EQ("whose given field is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003317
3318 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003319 EXPECT_EQ(
3320 "whose given field is 1" + OfType("int") + ", which is 1 more than 0",
3321 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003322}
3323
3324// Tests that Field() works when the argument is a pointer to const.
3325TEST(FieldForPointerTest, WorksForPointerToConst) {
3326 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3327
3328 AStruct a;
3329 EXPECT_TRUE(m.Matches(&a));
3330 a.x = -1;
3331 EXPECT_FALSE(m.Matches(&a));
3332}
3333
3334// Tests that Field() works when the argument is a pointer to non-const.
3335TEST(FieldForPointerTest, WorksForPointerToNonConst) {
3336 Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));
3337
3338 AStruct a;
3339 EXPECT_TRUE(m.Matches(&a));
3340 a.x = -1;
3341 EXPECT_FALSE(m.Matches(&a));
3342}
3343
zhanyong.wan6953a722010-01-13 05:15:07 +00003344// Tests that Field() works when the argument is a reference to a const pointer.
3345TEST(FieldForPointerTest, WorksForReferenceToConstPointer) {
3346 Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));
3347
3348 AStruct a;
3349 EXPECT_TRUE(m.Matches(&a));
3350 a.x = -1;
3351 EXPECT_FALSE(m.Matches(&a));
3352}
3353
shiqiane35fdd92008-12-10 05:08:54 +00003354// Tests that Field() does not match the NULL pointer.
3355TEST(FieldForPointerTest, DoesNotMatchNull) {
3356 Matcher<const AStruct*> m = Field(&AStruct::x, _);
3357 EXPECT_FALSE(m.Matches(NULL));
3358}
3359
3360// Tests that Field(&Foo::field, ...) works when the argument's type
3361// is a sub-type of const Foo*.
3362TEST(FieldForPointerTest, WorksForArgumentOfSubType) {
3363 // Note that the matcher expects DerivedStruct but we say AStruct
3364 // inside Field().
3365 Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));
3366
3367 DerivedStruct d;
3368 EXPECT_TRUE(m.Matches(&d));
3369 d.x = -1;
3370 EXPECT_FALSE(m.Matches(&d));
3371}
3372
3373// Tests that Field() can describe itself when used to match a pointer.
3374TEST(FieldForPointerTest, CanDescribeSelf) {
3375 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3376
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003377 EXPECT_EQ("is an object whose given field is >= 0", Describe(m));
3378 EXPECT_EQ("is an object whose given field isn't >= 0", DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003379}
3380
3381// Tests that Field() can explain the result of matching a pointer.
3382TEST(FieldForPointerTest, CanExplainMatchResult) {
3383 Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));
3384
3385 AStruct a;
3386 a.x = 1;
3387 EXPECT_EQ("", Explain(m, static_cast<const AStruct*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003388 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int"),
3389 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003390
3391 m = Field(&AStruct::x, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003392 EXPECT_EQ("which points to an object whose given field is 1" + OfType("int") +
3393 ", which is 1 more than 0", Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003394}
3395
3396// A user-defined class for testing Property().
3397class AClass {
3398 public:
3399 AClass() : n_(0) {}
3400
3401 // A getter that returns a non-reference.
3402 int n() const { return n_; }
3403
3404 void set_n(int new_n) { n_ = new_n; }
3405
3406 // A getter that returns a reference to const.
3407 const string& s() const { return s_; }
3408
3409 void set_s(const string& new_s) { s_ = new_s; }
3410
3411 // A getter that returns a reference to non-const.
3412 double& x() const { return x_; }
3413 private:
3414 int n_;
3415 string s_;
3416
3417 static double x_;
3418};
3419
3420double AClass::x_ = 0.0;
3421
3422// A derived class for testing Property().
3423class DerivedClass : public AClass {
3424 private:
3425 int k_;
3426};
3427
3428// Tests that Property(&Foo::property, ...) works when property()
3429// returns a non-reference.
3430TEST(PropertyTest, WorksForNonReferenceProperty) {
3431 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3432
3433 AClass a;
3434 a.set_n(1);
3435 EXPECT_TRUE(m.Matches(a));
3436
3437 a.set_n(-1);
3438 EXPECT_FALSE(m.Matches(a));
3439}
3440
3441// Tests that Property(&Foo::property, ...) works when property()
3442// returns a reference to const.
3443TEST(PropertyTest, WorksForReferenceToConstProperty) {
3444 Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi"));
3445
3446 AClass a;
3447 a.set_s("hill");
3448 EXPECT_TRUE(m.Matches(a));
3449
3450 a.set_s("hole");
3451 EXPECT_FALSE(m.Matches(a));
3452}
3453
3454// Tests that Property(&Foo::property, ...) works when property()
3455// returns a reference to non-const.
3456TEST(PropertyTest, WorksForReferenceToNonConstProperty) {
3457 double x = 0.0;
3458 AClass a;
3459
3460 Matcher<const AClass&> m = Property(&AClass::x, Ref(x));
3461 EXPECT_FALSE(m.Matches(a));
3462
3463 m = Property(&AClass::x, Not(Ref(x)));
3464 EXPECT_TRUE(m.Matches(a));
3465}
3466
3467// Tests that Property(&Foo::property, ...) works when the argument is
3468// passed by value.
3469TEST(PropertyTest, WorksForByValueArgument) {
3470 Matcher<AClass> m = Property(&AClass::s, StartsWith("hi"));
3471
3472 AClass a;
3473 a.set_s("hill");
3474 EXPECT_TRUE(m.Matches(a));
3475
3476 a.set_s("hole");
3477 EXPECT_FALSE(m.Matches(a));
3478}
3479
3480// Tests that Property(&Foo::property, ...) works when the argument's
3481// type is a sub-type of Foo.
3482TEST(PropertyTest, WorksForArgumentOfSubType) {
3483 // The matcher expects a DerivedClass, but inside the Property() we
3484 // say AClass.
3485 Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));
3486
3487 DerivedClass d;
3488 d.set_n(1);
3489 EXPECT_TRUE(m.Matches(d));
3490
3491 d.set_n(-1);
3492 EXPECT_FALSE(m.Matches(d));
3493}
3494
3495// Tests that Property(&Foo::property, m) works when property()'s type
3496// and m's argument type are compatible but different.
3497TEST(PropertyTest, WorksForCompatibleMatcherType) {
3498 // n() returns an int but the inner matcher expects a signed char.
3499 Matcher<const AClass&> m = Property(&AClass::n,
3500 Matcher<signed char>(Ge(0)));
3501
3502 AClass a;
3503 EXPECT_TRUE(m.Matches(a));
3504 a.set_n(-1);
3505 EXPECT_FALSE(m.Matches(a));
3506}
3507
3508// Tests that Property() can describe itself.
3509TEST(PropertyTest, CanDescribeSelf) {
3510 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3511
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003512 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3513 EXPECT_EQ("is an object whose given property isn't >= 0",
3514 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003515}
3516
3517// Tests that Property() can explain the match result.
3518TEST(PropertyTest, CanExplainMatchResult) {
3519 Matcher<const AClass&> m = Property(&AClass::n, Ge(0));
3520
3521 AClass a;
3522 a.set_n(1);
zhanyong.wan736baa82010-09-27 17:44:16 +00003523 EXPECT_EQ("whose given property is 1" + OfType("int"), Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003524
3525 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003526 EXPECT_EQ(
3527 "whose given property is 1" + OfType("int") + ", which is 1 more than 0",
3528 Explain(m, a));
shiqiane35fdd92008-12-10 05:08:54 +00003529}
3530
3531// Tests that Property() works when the argument is a pointer to const.
3532TEST(PropertyForPointerTest, WorksForPointerToConst) {
3533 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3534
3535 AClass a;
3536 a.set_n(1);
3537 EXPECT_TRUE(m.Matches(&a));
3538
3539 a.set_n(-1);
3540 EXPECT_FALSE(m.Matches(&a));
3541}
3542
3543// Tests that Property() works when the argument is a pointer to non-const.
3544TEST(PropertyForPointerTest, WorksForPointerToNonConst) {
3545 Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi"));
3546
3547 AClass a;
3548 a.set_s("hill");
3549 EXPECT_TRUE(m.Matches(&a));
3550
3551 a.set_s("hole");
3552 EXPECT_FALSE(m.Matches(&a));
3553}
3554
zhanyong.wan6953a722010-01-13 05:15:07 +00003555// Tests that Property() works when the argument is a reference to a
3556// const pointer.
3557TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {
3558 Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi"));
3559
3560 AClass a;
3561 a.set_s("hill");
3562 EXPECT_TRUE(m.Matches(&a));
3563
3564 a.set_s("hole");
3565 EXPECT_FALSE(m.Matches(&a));
3566}
3567
shiqiane35fdd92008-12-10 05:08:54 +00003568// Tests that Property() does not match the NULL pointer.
3569TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {
3570 Matcher<const AClass*> m = Property(&AClass::x, _);
3571 EXPECT_FALSE(m.Matches(NULL));
3572}
3573
3574// Tests that Property(&Foo::property, ...) works when the argument's
3575// type is a sub-type of const Foo*.
3576TEST(PropertyForPointerTest, WorksForArgumentOfSubType) {
3577 // The matcher expects a DerivedClass, but inside the Property() we
3578 // say AClass.
3579 Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));
3580
3581 DerivedClass d;
3582 d.set_n(1);
3583 EXPECT_TRUE(m.Matches(&d));
3584
3585 d.set_n(-1);
3586 EXPECT_FALSE(m.Matches(&d));
3587}
3588
3589// Tests that Property() can describe itself when used to match a pointer.
3590TEST(PropertyForPointerTest, CanDescribeSelf) {
3591 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3592
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003593 EXPECT_EQ("is an object whose given property is >= 0", Describe(m));
3594 EXPECT_EQ("is an object whose given property isn't >= 0",
3595 DescribeNegation(m));
shiqiane35fdd92008-12-10 05:08:54 +00003596}
3597
3598// Tests that Property() can explain the result of matching a pointer.
3599TEST(PropertyForPointerTest, CanExplainMatchResult) {
3600 Matcher<const AClass*> m = Property(&AClass::n, Ge(0));
3601
3602 AClass a;
3603 a.set_n(1);
3604 EXPECT_EQ("", Explain(m, static_cast<const AClass*>(NULL)));
zhanyong.wan736baa82010-09-27 17:44:16 +00003605 EXPECT_EQ(
3606 "which points to an object whose given property is 1" + OfType("int"),
3607 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003608
3609 m = Property(&AClass::n, GreaterThan(0));
zhanyong.wan736baa82010-09-27 17:44:16 +00003610 EXPECT_EQ("which points to an object whose given property is 1" +
3611 OfType("int") + ", which is 1 more than 0",
3612 Explain(m, &a));
shiqiane35fdd92008-12-10 05:08:54 +00003613}
3614
3615// Tests ResultOf.
3616
3617// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3618// function pointer.
3619string IntToStringFunction(int input) { return input == 1 ? "foo" : "bar"; }
3620
3621TEST(ResultOfTest, WorksForFunctionPointers) {
3622 Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(string("foo")));
3623
3624 EXPECT_TRUE(matcher.Matches(1));
3625 EXPECT_FALSE(matcher.Matches(2));
3626}
3627
3628// Tests that ResultOf() can describe itself.
3629TEST(ResultOfTest, CanDescribeItself) {
3630 Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo"));
3631
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003632 EXPECT_EQ("is mapped by the given callable to a value that "
3633 "is equal to \"foo\"", Describe(matcher));
3634 EXPECT_EQ("is mapped by the given callable to a value that "
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003635 "isn't equal to \"foo\"", DescribeNegation(matcher));
shiqiane35fdd92008-12-10 05:08:54 +00003636}
3637
3638// Tests that ResultOf() can explain the match result.
3639int IntFunction(int input) { return input == 42 ? 80 : 90; }
3640
3641TEST(ResultOfTest, CanExplainMatchResult) {
3642 Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003643 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int"),
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003644 Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003645
3646 matcher = ResultOf(&IntFunction, GreaterThan(85));
zhanyong.wan736baa82010-09-27 17:44:16 +00003647 EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int") +
3648 ", which is 5 more than 85", Explain(matcher, 36));
shiqiane35fdd92008-12-10 05:08:54 +00003649}
3650
3651// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3652// returns a non-reference.
3653TEST(ResultOfTest, WorksForNonReferenceResults) {
3654 Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));
3655
3656 EXPECT_TRUE(matcher.Matches(42));
3657 EXPECT_FALSE(matcher.Matches(36));
3658}
3659
3660// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3661// returns a reference to non-const.
zhanyong.wan736baa82010-09-27 17:44:16 +00003662double& DoubleFunction(double& input) { return input; } // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003663
zhanyong.wan736baa82010-09-27 17:44:16 +00003664Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT
shiqiane35fdd92008-12-10 05:08:54 +00003665 return obj;
3666}
3667
3668TEST(ResultOfTest, WorksForReferenceToNonConstResults) {
3669 double x = 3.14;
3670 double x2 = x;
3671 Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));
3672
3673 EXPECT_TRUE(matcher.Matches(x));
3674 EXPECT_FALSE(matcher.Matches(x2));
3675
3676 // Test that ResultOf works with uncopyable objects
3677 Uncopyable obj(0);
3678 Uncopyable obj2(0);
3679 Matcher<Uncopyable&> matcher2 =
3680 ResultOf(&RefUncopyableFunction, Ref(obj));
3681
3682 EXPECT_TRUE(matcher2.Matches(obj));
3683 EXPECT_FALSE(matcher2.Matches(obj2));
3684}
3685
3686// Tests that ResultOf(f, ...) compiles and works as expected when f(x)
3687// returns a reference to const.
3688const string& StringFunction(const string& input) { return input; }
3689
3690TEST(ResultOfTest, WorksForReferenceToConstResults) {
3691 string s = "foo";
3692 string s2 = s;
3693 Matcher<const string&> matcher = ResultOf(&StringFunction, Ref(s));
3694
3695 EXPECT_TRUE(matcher.Matches(s));
3696 EXPECT_FALSE(matcher.Matches(s2));
3697}
3698
3699// Tests that ResultOf(f, m) works when f(x) and m's
3700// argument types are compatible but different.
3701TEST(ResultOfTest, WorksForCompatibleMatcherTypes) {
3702 // IntFunction() returns int but the inner matcher expects a signed char.
3703 Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));
3704
3705 EXPECT_TRUE(matcher.Matches(36));
3706 EXPECT_FALSE(matcher.Matches(42));
3707}
3708
shiqiane35fdd92008-12-10 05:08:54 +00003709// Tests that the program aborts when ResultOf is passed
3710// a NULL function pointer.
3711TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {
zhanyong.wan04d6ed82009-09-11 07:01:08 +00003712 EXPECT_DEATH_IF_SUPPORTED(
zhanyong.wan736baa82010-09-27 17:44:16 +00003713 ResultOf(static_cast<string(*)(int dummy)>(NULL), Eq(string("foo"))),
shiqiane35fdd92008-12-10 05:08:54 +00003714 "NULL function pointer is passed into ResultOf\\(\\)\\.");
3715}
shiqiane35fdd92008-12-10 05:08:54 +00003716
3717// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3718// function reference.
3719TEST(ResultOfTest, WorksForFunctionReferences) {
3720 Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo"));
3721 EXPECT_TRUE(matcher.Matches(1));
3722 EXPECT_FALSE(matcher.Matches(2));
3723}
3724
3725// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3726// function object.
3727struct Functor : public ::std::unary_function<int, string> {
3728 result_type operator()(argument_type input) const {
3729 return IntToStringFunction(input);
3730 }
3731};
3732
3733TEST(ResultOfTest, WorksForFunctors) {
3734 Matcher<int> matcher = ResultOf(Functor(), Eq(string("foo")));
3735
3736 EXPECT_TRUE(matcher.Matches(1));
3737 EXPECT_FALSE(matcher.Matches(2));
3738}
3739
3740// Tests that ResultOf(f, ...) compiles and works as expected when f is a
3741// functor with more then one operator() defined. ResultOf() must work
3742// for each defined operator().
3743struct PolymorphicFunctor {
3744 typedef int result_type;
3745 int operator()(int n) { return n; }
3746 int operator()(const char* s) { return static_cast<int>(strlen(s)); }
3747};
3748
3749TEST(ResultOfTest, WorksForPolymorphicFunctors) {
3750 Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));
3751
3752 EXPECT_TRUE(matcher_int.Matches(10));
3753 EXPECT_FALSE(matcher_int.Matches(2));
3754
3755 Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));
3756
3757 EXPECT_TRUE(matcher_string.Matches("long string"));
3758 EXPECT_FALSE(matcher_string.Matches("shrt"));
3759}
3760
3761const int* ReferencingFunction(const int& n) { return &n; }
3762
3763struct ReferencingFunctor {
3764 typedef const int* result_type;
3765 result_type operator()(const int& n) { return &n; }
3766};
3767
3768TEST(ResultOfTest, WorksForReferencingCallables) {
3769 const int n = 1;
3770 const int n2 = 1;
3771 Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));
3772 EXPECT_TRUE(matcher2.Matches(n));
3773 EXPECT_FALSE(matcher2.Matches(n2));
3774
3775 Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));
3776 EXPECT_TRUE(matcher3.Matches(n));
3777 EXPECT_FALSE(matcher3.Matches(n2));
3778}
3779
shiqiane35fdd92008-12-10 05:08:54 +00003780class DivisibleByImpl {
3781 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003782 explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}
shiqiane35fdd92008-12-10 05:08:54 +00003783
zhanyong.wandb22c222010-01-28 21:52:29 +00003784 // For testing using ExplainMatchResultTo() with polymorphic matchers.
shiqiane35fdd92008-12-10 05:08:54 +00003785 template <typename T>
zhanyong.wandb22c222010-01-28 21:52:29 +00003786 bool MatchAndExplain(const T& n, MatchResultListener* listener) const {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003787 *listener << "which is " << (n % divider_) << " modulo "
zhanyong.wandb22c222010-01-28 21:52:29 +00003788 << divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003789 return (n % divider_) == 0;
3790 }
3791
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003792 void DescribeTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003793 *os << "is divisible by " << divider_;
3794 }
3795
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003796 void DescribeNegationTo(ostream* os) const {
shiqiane35fdd92008-12-10 05:08:54 +00003797 *os << "is not divisible by " << divider_;
3798 }
3799
zhanyong.wan32de5f52009-12-23 00:13:23 +00003800 void set_divider(int a_divider) { divider_ = a_divider; }
shiqiane35fdd92008-12-10 05:08:54 +00003801 int divider() const { return divider_; }
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003802
shiqiane35fdd92008-12-10 05:08:54 +00003803 private:
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003804 int divider_;
shiqiane35fdd92008-12-10 05:08:54 +00003805};
3806
shiqiane35fdd92008-12-10 05:08:54 +00003807PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {
3808 return MakePolymorphicMatcher(DivisibleByImpl(n));
3809}
3810
3811// Tests that when AllOf() fails, only the first failing matcher is
3812// asked to explain why.
3813TEST(ExplainMatchResultTest, AllOf_False_False) {
3814 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003815 EXPECT_EQ("which is 1 modulo 4", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00003816}
3817
3818// Tests that when AllOf() fails, only the first failing matcher is
3819// asked to explain why.
3820TEST(ExplainMatchResultTest, AllOf_False_True) {
3821 const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003822 EXPECT_EQ("which is 2 modulo 4", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003823}
3824
3825// Tests that when AllOf() fails, only the first failing matcher is
3826// asked to explain why.
3827TEST(ExplainMatchResultTest, AllOf_True_False) {
3828 const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003829 EXPECT_EQ("which is 2 modulo 3", Explain(m, 5));
shiqiane35fdd92008-12-10 05:08:54 +00003830}
3831
3832// Tests that when AllOf() succeeds, all matchers are asked to explain
3833// why.
3834TEST(ExplainMatchResultTest, AllOf_True_True) {
3835 const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00003836 EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003837}
3838
3839TEST(ExplainMatchResultTest, AllOf_True_True_2) {
3840 const Matcher<int> m = AllOf(Ge(2), Le(3));
3841 EXPECT_EQ("", Explain(m, 2));
3842}
3843
3844TEST(ExplainmatcherResultTest, MonomorphicMatcher) {
3845 const Matcher<int> m = GreaterThan(5);
zhanyong.wan676e8cc2010-03-16 20:01:51 +00003846 EXPECT_EQ("which is 1 more than 5", Explain(m, 6));
shiqiane35fdd92008-12-10 05:08:54 +00003847}
3848
3849// The following two tests verify that values without a public copy
3850// ctor can be used as arguments to matchers like Eq(), Ge(), and etc
3851// with the help of ByRef().
3852
3853class NotCopyable {
3854 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00003855 explicit NotCopyable(int a_value) : value_(a_value) {}
shiqiane35fdd92008-12-10 05:08:54 +00003856
3857 int value() const { return value_; }
3858
3859 bool operator==(const NotCopyable& rhs) const {
3860 return value() == rhs.value();
3861 }
3862
3863 bool operator>=(const NotCopyable& rhs) const {
3864 return value() >= rhs.value();
3865 }
3866 private:
3867 int value_;
3868
3869 GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable);
3870};
3871
3872TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {
3873 const NotCopyable const_value1(1);
3874 const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));
3875
3876 const NotCopyable n1(1), n2(2);
3877 EXPECT_TRUE(m.Matches(n1));
3878 EXPECT_FALSE(m.Matches(n2));
3879}
3880
3881TEST(ByRefTest, AllowsNotCopyableValueInMatchers) {
3882 NotCopyable value2(2);
3883 const Matcher<NotCopyable&> m = Ge(ByRef(value2));
3884
3885 NotCopyable n1(1), n2(2);
3886 EXPECT_FALSE(m.Matches(n1));
3887 EXPECT_TRUE(m.Matches(n2));
3888}
3889
zhanyong.wan320814a2013-03-01 00:20:30 +00003890TEST(IsEmptyTest, ImplementsIsEmpty) {
3891 vector<int> container;
3892 EXPECT_THAT(container, IsEmpty());
3893 container.push_back(0);
3894 EXPECT_THAT(container, Not(IsEmpty()));
3895 container.push_back(1);
3896 EXPECT_THAT(container, Not(IsEmpty()));
3897}
3898
3899TEST(IsEmptyTest, WorksWithString) {
3900 string text;
3901 EXPECT_THAT(text, IsEmpty());
3902 text = "foo";
3903 EXPECT_THAT(text, Not(IsEmpty()));
3904 text = string("\0", 1);
3905 EXPECT_THAT(text, Not(IsEmpty()));
3906}
3907
3908TEST(IsEmptyTest, CanDescribeSelf) {
3909 Matcher<vector<int> > m = IsEmpty();
3910 EXPECT_EQ("is empty", Describe(m));
3911 EXPECT_EQ("isn't empty", DescribeNegation(m));
3912}
3913
3914TEST(IsEmptyTest, ExplainsResult) {
3915 Matcher<vector<int> > m = IsEmpty();
3916 vector<int> container;
3917 EXPECT_EQ("", Explain(m, container));
3918 container.push_back(0);
3919 EXPECT_EQ("whose size is 1", Explain(m, container));
3920}
3921
zhanyong.wana31d9ce2013-03-01 01:50:17 +00003922TEST(SizeIsTest, ImplementsSizeIs) {
3923 vector<int> container;
3924 EXPECT_THAT(container, SizeIs(0));
3925 EXPECT_THAT(container, Not(SizeIs(1)));
3926 container.push_back(0);
3927 EXPECT_THAT(container, Not(SizeIs(0)));
3928 EXPECT_THAT(container, SizeIs(1));
3929 container.push_back(0);
3930 EXPECT_THAT(container, Not(SizeIs(0)));
3931 EXPECT_THAT(container, SizeIs(2));
3932}
3933
3934TEST(SizeIsTest, WorksWithMap) {
3935 map<string, int> container;
3936 EXPECT_THAT(container, SizeIs(0));
3937 EXPECT_THAT(container, Not(SizeIs(1)));
3938 container.insert(make_pair("foo", 1));
3939 EXPECT_THAT(container, Not(SizeIs(0)));
3940 EXPECT_THAT(container, SizeIs(1));
3941 container.insert(make_pair("bar", 2));
3942 EXPECT_THAT(container, Not(SizeIs(0)));
3943 EXPECT_THAT(container, SizeIs(2));
3944}
3945
3946TEST(SizeIsTest, WorksWithReferences) {
3947 vector<int> container;
3948 Matcher<const vector<int>&> m = SizeIs(1);
3949 EXPECT_THAT(container, Not(m));
3950 container.push_back(0);
3951 EXPECT_THAT(container, m);
3952}
3953
3954TEST(SizeIsTest, CanDescribeSelf) {
3955 Matcher<vector<int> > m = SizeIs(2);
3956 EXPECT_EQ("size is equal to 2", Describe(m));
3957 EXPECT_EQ("size isn't equal to 2", DescribeNegation(m));
3958}
3959
3960TEST(SizeIsTest, ExplainsResult) {
3961 Matcher<vector<int> > m1 = SizeIs(2);
3962 Matcher<vector<int> > m2 = SizeIs(Lt(2u));
3963 Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3));
3964 Matcher<vector<int> > m4 = SizeIs(GreaterThan(1));
3965 vector<int> container;
3966 EXPECT_EQ("whose size 0 doesn't match", Explain(m1, container));
3967 EXPECT_EQ("whose size 0 matches", Explain(m2, container));
3968 EXPECT_EQ("whose size 0 matches", Explain(m3, container));
3969 EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1",
3970 Explain(m4, container));
3971 container.push_back(0);
3972 container.push_back(0);
3973 EXPECT_EQ("whose size 2 matches", Explain(m1, container));
3974 EXPECT_EQ("whose size 2 doesn't match", Explain(m2, container));
3975 EXPECT_EQ("whose size 2 doesn't match", Explain(m3, container));
3976 EXPECT_EQ("whose size 2 matches, which is 1 more than 1",
3977 Explain(m4, container));
3978}
3979
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00003980#if GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00003981// Tests ContainerEq with different container types, and
3982// different element types.
3983
3984template <typename T>
zhanyong.wanb8243162009-06-04 05:48:20 +00003985class ContainerEqTest : public testing::Test {};
zhanyong.wan6a896b52009-01-16 01:13:50 +00003986
3987typedef testing::Types<
zhanyong.wanab5b77c2010-05-17 19:32:48 +00003988 set<int>,
3989 vector<size_t>,
3990 multiset<size_t>,
3991 list<int> >
zhanyong.wan6a896b52009-01-16 01:13:50 +00003992 ContainerEqTestTypes;
3993
3994TYPED_TEST_CASE(ContainerEqTest, ContainerEqTestTypes);
3995
3996// Tests that the filled container is equal to itself.
3997TYPED_TEST(ContainerEqTest, EqualsSelf) {
3998 static const int vals[] = {1, 1, 2, 3, 5, 8};
3999 TypeParam my_set(vals, vals + 6);
4000 const Matcher<TypeParam> m = ContainerEq(my_set);
4001 EXPECT_TRUE(m.Matches(my_set));
4002 EXPECT_EQ("", Explain(m, my_set));
4003}
4004
4005// Tests that missing values are reported.
4006TYPED_TEST(ContainerEqTest, ValueMissing) {
4007 static const int vals[] = {1, 1, 2, 3, 5, 8};
4008 static const int test_vals[] = {2, 1, 8, 5};
4009 TypeParam my_set(vals, vals + 6);
4010 TypeParam test_set(test_vals, test_vals + 4);
4011 const Matcher<TypeParam> m = ContainerEq(my_set);
4012 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004013 EXPECT_EQ("which doesn't have these expected elements: 3",
4014 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004015}
4016
4017// Tests that added values are reported.
4018TYPED_TEST(ContainerEqTest, ValueAdded) {
4019 static const int vals[] = {1, 1, 2, 3, 5, 8};
4020 static const int test_vals[] = {1, 2, 3, 5, 8, 46};
4021 TypeParam my_set(vals, vals + 6);
4022 TypeParam test_set(test_vals, test_vals + 6);
4023 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4024 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004025 EXPECT_EQ("which has these unexpected elements: 46", Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004026}
4027
4028// Tests that added and missing values are reported together.
4029TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {
4030 static const int vals[] = {1, 1, 2, 3, 5, 8};
4031 static const int test_vals[] = {1, 2, 3, 8, 46};
4032 TypeParam my_set(vals, vals + 6);
4033 TypeParam test_set(test_vals, test_vals + 5);
4034 const Matcher<TypeParam> m = ContainerEq(my_set);
4035 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004036 EXPECT_EQ("which has these unexpected elements: 46,\n"
4037 "and doesn't have these expected elements: 5",
4038 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004039}
4040
4041// Tests duplicated value -- expect no explanation.
4042TYPED_TEST(ContainerEqTest, DuplicateDifference) {
4043 static const int vals[] = {1, 1, 2, 3, 5, 8};
4044 static const int test_vals[] = {1, 2, 3, 5, 8};
4045 TypeParam my_set(vals, vals + 6);
4046 TypeParam test_set(test_vals, test_vals + 5);
4047 const Matcher<const TypeParam&> m = ContainerEq(my_set);
4048 // Depending on the container, match may be true or false
4049 // But in any case there should be no explanation.
4050 EXPECT_EQ("", Explain(m, test_set));
4051}
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00004052#endif // GTEST_HAS_TYPED_TEST
zhanyong.wan6a896b52009-01-16 01:13:50 +00004053
4054// Tests that mutliple missing values are reported.
4055// Using just vector here, so order is predicatble.
4056TEST(ContainerEqExtraTest, MultipleValuesMissing) {
4057 static const int vals[] = {1, 1, 2, 3, 5, 8};
4058 static const int test_vals[] = {2, 1, 5};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004059 vector<int> my_set(vals, vals + 6);
4060 vector<int> test_set(test_vals, test_vals + 3);
4061 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004062 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004063 EXPECT_EQ("which doesn't have these expected elements: 3, 8",
4064 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004065}
4066
4067// Tests that added values are reported.
4068// Using just vector here, so order is predicatble.
4069TEST(ContainerEqExtraTest, MultipleValuesAdded) {
4070 static const int vals[] = {1, 1, 2, 3, 5, 8};
4071 static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004072 list<size_t> my_set(vals, vals + 6);
4073 list<size_t> test_set(test_vals, test_vals + 7);
4074 const Matcher<const list<size_t>&> m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004075 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004076 EXPECT_EQ("which has these unexpected elements: 92, 46",
4077 Explain(m, test_set));
zhanyong.wan6a896b52009-01-16 01:13:50 +00004078}
4079
4080// Tests that added and missing values are reported together.
4081TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {
4082 static const int vals[] = {1, 1, 2, 3, 5, 8};
4083 static const int test_vals[] = {1, 2, 3, 92, 46};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004084 list<size_t> my_set(vals, vals + 6);
4085 list<size_t> test_set(test_vals, test_vals + 5);
4086 const Matcher<const list<size_t> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004087 EXPECT_FALSE(m.Matches(test_set));
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004088 EXPECT_EQ("which has these unexpected elements: 92, 46,\n"
4089 "and doesn't have these expected elements: 5, 8",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004090 Explain(m, test_set));
4091}
4092
4093// Tests to see that duplicate elements are detected,
4094// but (as above) not reported in the explanation.
4095TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {
4096 static const int vals[] = {1, 1, 2, 3, 5, 8};
4097 static const int test_vals[] = {1, 2, 3, 5, 8};
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004098 vector<int> my_set(vals, vals + 6);
4099 vector<int> test_set(test_vals, test_vals + 5);
4100 const Matcher<vector<int> > m = ContainerEq(my_set);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004101 EXPECT_TRUE(m.Matches(my_set));
4102 EXPECT_FALSE(m.Matches(test_set));
4103 // There is nothing to report when both sets contain all the same values.
4104 EXPECT_EQ("", Explain(m, test_set));
4105}
4106
4107// Tests that ContainerEq works for non-trivial associative containers,
4108// like maps.
4109TEST(ContainerEqExtraTest, WorksForMaps) {
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004110 map<int, std::string> my_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004111 my_map[0] = "a";
4112 my_map[1] = "b";
4113
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004114 map<int, std::string> test_map;
zhanyong.wan6a896b52009-01-16 01:13:50 +00004115 test_map[0] = "aa";
4116 test_map[1] = "b";
4117
zhanyong.wanab5b77c2010-05-17 19:32:48 +00004118 const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);
zhanyong.wan6a896b52009-01-16 01:13:50 +00004119 EXPECT_TRUE(m.Matches(my_map));
4120 EXPECT_FALSE(m.Matches(test_map));
4121
zhanyong.wanb1c7f932010-03-24 17:35:11 +00004122 EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n"
4123 "and doesn't have these expected elements: (0, \"a\")",
zhanyong.wan6a896b52009-01-16 01:13:50 +00004124 Explain(m, test_map));
4125}
4126
zhanyong.wanb8243162009-06-04 05:48:20 +00004127TEST(ContainerEqExtraTest, WorksForNativeArray) {
4128 int a1[] = { 1, 2, 3 };
4129 int a2[] = { 1, 2, 3 };
4130 int b[] = { 1, 2, 4 };
4131
4132 EXPECT_THAT(a1, ContainerEq(a2));
4133 EXPECT_THAT(a1, Not(ContainerEq(b)));
4134}
4135
4136TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {
4137 const char a1[][3] = { "hi", "lo" };
4138 const char a2[][3] = { "hi", "lo" };
4139 const char b[][3] = { "lo", "hi" };
4140
4141 // Tests using ContainerEq() in the first dimension.
4142 EXPECT_THAT(a1, ContainerEq(a2));
4143 EXPECT_THAT(a1, Not(ContainerEq(b)));
4144
4145 // Tests using ContainerEq() in the second dimension.
4146 EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));
4147 EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));
4148}
4149
4150TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {
4151 const int a1[] = { 1, 2, 3 };
4152 const int a2[] = { 1, 2, 3 };
4153 const int b[] = { 1, 2, 3, 4 };
4154
zhanyong.wan2661c682009-06-09 05:42:12 +00004155 const int* const p1 = a1;
4156 EXPECT_THAT(make_tuple(p1, 3), ContainerEq(a2));
4157 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(b)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004158
4159 const int c[] = { 1, 3, 2 };
zhanyong.wan2661c682009-06-09 05:42:12 +00004160 EXPECT_THAT(make_tuple(p1, 3), Not(ContainerEq(c)));
zhanyong.wanb8243162009-06-04 05:48:20 +00004161}
4162
4163TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {
4164 std::string a1[][3] = {
4165 { "hi", "hello", "ciao" },
4166 { "bye", "see you", "ciao" }
4167 };
4168
4169 std::string a2[][3] = {
4170 { "hi", "hello", "ciao" },
4171 { "bye", "see you", "ciao" }
4172 };
4173
4174 const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);
4175 EXPECT_THAT(a1, m);
4176
4177 a2[0][0] = "ha";
4178 EXPECT_THAT(a1, m);
4179}
4180
zhanyong.wan898725c2011-09-16 16:45:39 +00004181TEST(WhenSortedByTest, WorksForEmptyContainer) {
4182 const vector<int> numbers;
4183 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));
4184 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));
4185}
4186
4187TEST(WhenSortedByTest, WorksForNonEmptyContainer) {
4188 vector<unsigned> numbers;
4189 numbers.push_back(3);
4190 numbers.push_back(1);
4191 numbers.push_back(2);
4192 numbers.push_back(2);
4193 EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(),
4194 ElementsAre(3, 2, 2, 1)));
4195 EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(),
4196 ElementsAre(1, 2, 2, 3))));
4197}
4198
4199TEST(WhenSortedByTest, WorksForNonVectorContainer) {
4200 list<string> words;
4201 words.push_back("say");
4202 words.push_back("hello");
4203 words.push_back("world");
4204 EXPECT_THAT(words, WhenSortedBy(less<string>(),
4205 ElementsAre("hello", "say", "world")));
4206 EXPECT_THAT(words, Not(WhenSortedBy(less<string>(),
4207 ElementsAre("say", "hello", "world"))));
4208}
4209
4210TEST(WhenSortedByTest, WorksForNativeArray) {
4211 const int numbers[] = { 1, 3, 2, 4 };
4212 const int sorted_numbers[] = { 1, 2, 3, 4 };
4213 EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));
4214 EXPECT_THAT(numbers, WhenSortedBy(less<int>(),
4215 ElementsAreArray(sorted_numbers)));
4216 EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));
4217}
4218
4219TEST(WhenSortedByTest, CanDescribeSelf) {
4220 const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2));
4221 EXPECT_EQ("(when sorted) has 2 elements where\n"
4222 "element #0 is equal to 1,\n"
4223 "element #1 is equal to 2",
4224 Describe(m));
4225 EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n"
4226 "element #0 isn't equal to 1, or\n"
4227 "element #1 isn't equal to 2",
4228 DescribeNegation(m));
4229}
4230
4231TEST(WhenSortedByTest, ExplainsMatchResult) {
4232 const int a[] = { 2, 1 };
4233 EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match",
4234 Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));
4235 EXPECT_EQ("which is { 1, 2 } when sorted",
4236 Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));
4237}
4238
4239// WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't
4240// need to test it as exhaustively as we test the latter.
4241
4242TEST(WhenSortedTest, WorksForEmptyContainer) {
4243 const vector<int> numbers;
4244 EXPECT_THAT(numbers, WhenSorted(ElementsAre()));
4245 EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));
4246}
4247
4248TEST(WhenSortedTest, WorksForNonEmptyContainer) {
4249 list<string> words;
4250 words.push_back("3");
4251 words.push_back("1");
4252 words.push_back("2");
4253 words.push_back("2");
4254 EXPECT_THAT(words, WhenSorted(ElementsAre("1", "2", "2", "3")));
4255 EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3", "1", "2", "2"))));
4256}
4257
zhanyong.wana9a59e02013-03-27 16:14:55 +00004258TEST(WhenSortedTest, WorksForMapTypes) {
4259 map<string, int> word_counts;
4260 word_counts["and"] = 1;
4261 word_counts["the"] = 1;
4262 word_counts["buffalo"] = 2;
4263 EXPECT_THAT(word_counts, WhenSorted(ElementsAre(
4264 Pair("and", 1), Pair("buffalo", 2), Pair("the", 1))));
4265 EXPECT_THAT(word_counts, Not(WhenSorted(ElementsAre(
4266 Pair("and", 1), Pair("the", 1), Pair("buffalo", 2)))));
4267}
4268
4269TEST(WhenSortedTest, WorksForMultiMapTypes) {
4270 multimap<int, int> ifib;
4271 ifib.insert(make_pair(8, 6));
4272 ifib.insert(make_pair(2, 3));
4273 ifib.insert(make_pair(1, 1));
4274 ifib.insert(make_pair(3, 4));
4275 ifib.insert(make_pair(1, 2));
4276 ifib.insert(make_pair(5, 5));
4277 EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1),
4278 Pair(1, 2),
4279 Pair(2, 3),
4280 Pair(3, 4),
4281 Pair(5, 5),
4282 Pair(8, 6))));
4283 EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6),
4284 Pair(2, 3),
4285 Pair(1, 1),
4286 Pair(3, 4),
4287 Pair(1, 2),
4288 Pair(5, 5)))));
4289}
4290
4291TEST(WhenSortedTest, WorksForPolymorphicMatcher) {
4292 std::deque<int> d;
4293 d.push_back(2);
4294 d.push_back(1);
4295 EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));
4296 EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));
4297}
4298
4299TEST(WhenSortedTest, WorksForVectorConstRefMatcher) {
4300 std::deque<int> d;
4301 d.push_back(2);
4302 d.push_back(1);
4303 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);
4304 EXPECT_THAT(d, WhenSorted(vector_match));
4305 Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);
4306 EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));
4307}
4308
4309// Deliberately bare pseudo-container.
4310// Offers only begin() and end() accessors, yielding InputIterator.
4311template <typename T>
4312class Streamlike {
4313 private:
4314 class ConstIter;
4315 public:
4316 typedef ConstIter const_iterator;
4317 typedef T value_type;
4318
4319 template <typename InIter>
4320 Streamlike(InIter first, InIter last) : remainder_(first, last) {}
4321
4322 const_iterator begin() const {
4323 return const_iterator(this, remainder_.begin());
4324 }
4325 const_iterator end() const {
4326 return const_iterator(this, remainder_.end());
4327 }
4328
4329 private:
4330 class ConstIter : public std::iterator<std::input_iterator_tag,
4331 value_type,
4332 ptrdiff_t,
4333 const value_type&,
4334 const value_type*> {
4335 public:
4336 ConstIter(const Streamlike* s,
4337 typename std::list<value_type>::iterator pos)
4338 : s_(s), pos_(pos) {}
4339
4340 const value_type& operator*() const { return *pos_; }
4341 const value_type* operator->() const { return &*pos_; }
4342 ConstIter& operator++() {
4343 s_->remainder_.erase(pos_++);
4344 return *this;
4345 }
4346
4347 // *iter++ is required to work (see std::istreambuf_iterator).
4348 // (void)iter++ is also required to work.
4349 class PostIncrProxy {
4350 public:
4351 explicit PostIncrProxy(const value_type& value) : value_(value) {}
4352 value_type operator*() const { return value_; }
4353 private:
4354 value_type value_;
4355 };
4356 PostIncrProxy operator++(int) {
4357 PostIncrProxy proxy(**this);
4358 ++(*this);
4359 return proxy;
4360 }
4361
4362 friend bool operator==(const ConstIter& a, const ConstIter& b) {
4363 return a.s_ == b.s_ && a.pos_ == b.pos_;
4364 }
4365 friend bool operator!=(const ConstIter& a, const ConstIter& b) {
4366 return !(a == b);
4367 }
4368
4369 private:
4370 const Streamlike* s_;
4371 typename std::list<value_type>::iterator pos_;
4372 };
4373
4374 friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {
4375 os << "[";
4376 typedef typename std::list<value_type>::const_iterator Iter;
4377 const char* sep = "";
4378 for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {
4379 os << sep << *it;
4380 sep = ",";
4381 }
4382 os << "]";
4383 return os;
4384 }
4385
4386 mutable std::list<value_type> remainder_; // modified by iteration
4387};
4388
4389TEST(StreamlikeTest, Iteration) {
4390 const int a[5] = { 2, 1, 4, 5, 3 };
4391 Streamlike<int> s(a, a + 5);
4392 Streamlike<int>::const_iterator it = s.begin();
4393 const int* ip = a;
4394 while (it != s.end()) {
4395 SCOPED_TRACE(ip - a);
4396 EXPECT_EQ(*ip++, *it++);
4397 }
4398}
4399
4400TEST(WhenSortedTest, WorksForStreamlike) {
4401 // Streamlike 'container' provides only minimal iterator support.
4402 // Its iterators are tagged with input_iterator_tag.
4403 const int a[5] = { 2, 1, 4, 5, 3 };
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004404 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004405 EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));
4406 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4407}
4408
4409TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {
zhanyong.wanfb25d532013-07-28 08:24:00 +00004410 const int a[] = { 2, 1, 4, 5, 3 };
4411 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
zhanyong.wana9a59e02013-03-27 16:14:55 +00004412 Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);
4413 EXPECT_THAT(s, WhenSorted(vector_match));
4414 EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));
4415}
4416
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004417// Tests using ElementsAre() and ElementsAreArray() with stream-like
4418// "containers".
4419
4420TEST(ElemensAreStreamTest, WorksForStreamlike) {
4421 const int a[5] = { 1, 2, 3, 4, 5 };
4422 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4423 EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));
4424 EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));
4425}
4426
4427TEST(ElemensAreArrayStreamTest, WorksForStreamlike) {
4428 const int a[5] = { 1, 2, 3, 4, 5 };
4429 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4430
4431 vector<int> expected;
4432 expected.push_back(1);
4433 expected.push_back(2);
4434 expected.push_back(3);
4435 expected.push_back(4);
4436 expected.push_back(5);
4437 EXPECT_THAT(s, ElementsAreArray(expected));
4438
4439 expected[3] = 0;
4440 EXPECT_THAT(s, Not(ElementsAreArray(expected)));
4441}
4442
zhanyong.wanfb25d532013-07-28 08:24:00 +00004443// Tests for UnorderedElementsAreArray()
4444
4445TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {
4446 const int a[] = { 0, 1, 2, 3, 4 };
4447 std::vector<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4448 do {
4449 StringMatchResultListener listener;
4450 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a),
4451 s, &listener)) << listener.str();
4452 } while (std::next_permutation(s.begin(), s.end()));
4453}
4454
4455TEST(UnorderedElementsAreArrayTest, VectorBool) {
4456 const bool a[] = { 0, 1, 0, 1, 1 };
4457 const bool b[] = { 1, 0, 1, 1, 0 };
4458 std::vector<bool> expected(a, a + GMOCK_ARRAY_SIZE_(a));
4459 std::vector<bool> actual(b, b + GMOCK_ARRAY_SIZE_(b));
4460 StringMatchResultListener listener;
4461 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected),
4462 actual, &listener)) << listener.str();
4463}
4464
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004465TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {
4466 // Streamlike 'container' provides only minimal iterator support.
4467 // Its iterators are tagged with input_iterator_tag, and it has no
4468 // size() or empty() methods.
4469 const int a[5] = { 2, 1, 4, 5, 3 };
4470 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4471
4472 ::std::vector<int> expected;
4473 expected.push_back(1);
4474 expected.push_back(2);
4475 expected.push_back(3);
4476 expected.push_back(4);
4477 expected.push_back(5);
4478 EXPECT_THAT(s, UnorderedElementsAreArray(expected));
4479
4480 expected.push_back(6);
4481 EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));
4482}
4483
zhanyong.wan1cc1d4b2013-08-08 18:41:51 +00004484#if GTEST_LANG_CXX11
4485
4486TEST(UnorderedElementsAreArrayTest, TakesInitializerList) {
4487 const int a[5] = { 2, 1, 4, 5, 3 };
4488 EXPECT_THAT(a, UnorderedElementsAreArray({ 1, 2, 3, 4, 5 }));
4489 EXPECT_THAT(a, Not(UnorderedElementsAreArray({ 1, 2, 3, 4, 6 })));
4490}
4491
4492TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {
4493 const string a[5] = { "a", "b", "c", "d", "e" };
4494 EXPECT_THAT(a, UnorderedElementsAreArray({ "a", "b", "c", "d", "e" }));
4495 EXPECT_THAT(a, Not(UnorderedElementsAreArray({ "a", "b", "c", "d", "ef" })));
4496}
4497
4498TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {
4499 const int a[5] = { 2, 1, 4, 5, 3 };
4500 EXPECT_THAT(a, UnorderedElementsAreArray(
4501 { Eq(1), Eq(2), Eq(3), Eq(4), Eq(5) }));
4502 EXPECT_THAT(a, Not(UnorderedElementsAreArray(
4503 { Eq(1), Eq(2), Eq(3), Eq(4), Eq(6) })));
4504}
4505
4506TEST(UnorderedElementsAreArrayTest,
4507 TakesInitializerListOfDifferentTypedMatchers) {
4508 const int a[5] = { 2, 1, 4, 5, 3 };
4509 // The compiler cannot infer the type of the initializer list if its
4510 // elements have different types. We must explicitly specify the
4511 // unified element type in this case.
4512 EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >(
4513 { Eq(1), Ne(-2), Ge(3), Le(4), Eq(5) }));
4514 EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >(
4515 { Eq(1), Ne(-2), Ge(3), Le(4), Eq(6) })));
4516}
4517
4518#endif // GTEST_LANG_CXX11
4519
zhanyong.wanfb25d532013-07-28 08:24:00 +00004520class UnorderedElementsAreTest : public testing::Test {
4521 protected:
4522 typedef std::vector<int> IntVec;
4523};
4524
4525TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {
4526 const int a[] = { 1, 2, 3 };
4527 std::vector<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4528 do {
4529 StringMatchResultListener listener;
4530 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4531 s, &listener)) << listener.str();
4532 } while (std::next_permutation(s.begin(), s.end()));
4533}
4534
4535TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {
4536 const int a[] = { 1, 2, 3 };
4537 std::vector<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4538 std::vector<Matcher<int> > mv;
4539 mv.push_back(1);
4540 mv.push_back(2);
4541 mv.push_back(2);
4542 // The element with value '3' matches nothing: fail fast.
4543 StringMatchResultListener listener;
4544 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4545 s, &listener)) << listener.str();
4546}
4547
zhanyong.wan5579c1a2013-07-30 06:16:21 +00004548TEST_F(UnorderedElementsAreTest, WorksForStreamlike) {
4549 // Streamlike 'container' provides only minimal iterator support.
4550 // Its iterators are tagged with input_iterator_tag, and it has no
4551 // size() or empty() methods.
4552 const int a[5] = { 2, 1, 4, 5, 3 };
4553 Streamlike<int> s(a, a + GMOCK_ARRAY_SIZE_(a));
4554
4555 EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));
4556 EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));
4557}
4558
zhanyong.wanfb25d532013-07-28 08:24:00 +00004559// One naive implementation of the matcher runs in O(N!) time, which is too
4560// slow for many real-world inputs. This test shows that our matcher can match
4561// 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158
4562// iterations and obviously effectively incomputable.
4563// [ RUN ] UnorderedElementsAreTest.Performance
4564// [ OK ] UnorderedElementsAreTest.Performance (4 ms)
4565TEST_F(UnorderedElementsAreTest, Performance) {
4566 std::vector<int> s;
4567 std::vector<Matcher<int> > mv;
4568 for (int i = 0; i < 100; ++i) {
4569 s.push_back(i);
4570 mv.push_back(_);
4571 }
4572 mv[50] = Eq(0);
4573 StringMatchResultListener listener;
4574 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4575 s, &listener)) << listener.str();
4576}
4577
4578// Another variant of 'Performance' with similar expectations.
4579// [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict
4580// [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)
4581TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {
4582 std::vector<int> s;
4583 std::vector<Matcher<int> > mv;
4584 for (int i = 0; i < 100; ++i) {
4585 s.push_back(i);
4586 if (i & 1) {
4587 mv.push_back(_);
4588 } else {
4589 mv.push_back(i);
4590 }
4591 }
4592 StringMatchResultListener listener;
4593 EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv),
4594 s, &listener)) << listener.str();
4595}
4596
4597TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {
4598 std::vector<int> v;
4599 v.push_back(4);
4600 StringMatchResultListener listener;
4601 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4602 v, &listener)) << listener.str();
4603 EXPECT_THAT(listener.str(), Eq("which has 1 element"));
4604}
4605
4606TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {
4607 std::vector<int> v;
4608 StringMatchResultListener listener;
4609 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3),
4610 v, &listener)) << listener.str();
4611 EXPECT_THAT(listener.str(), Eq(""));
4612}
4613
4614TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {
4615 std::vector<int> v;
4616 v.push_back(1);
4617 v.push_back(1);
4618 StringMatchResultListener listener;
4619 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4620 v, &listener)) << listener.str();
4621 EXPECT_THAT(
4622 listener.str(),
4623 Eq("where the following matchers don't match any elements:\n"
4624 "matcher #1: is equal to 2"));
4625}
4626
4627TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {
4628 std::vector<int> v;
4629 v.push_back(1);
4630 v.push_back(2);
4631 StringMatchResultListener listener;
4632 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1),
4633 v, &listener)) << listener.str();
4634 EXPECT_THAT(
4635 listener.str(),
4636 Eq("where the following elements don't match any matchers:\n"
4637 "element #1: 2"));
4638}
4639
4640TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {
4641 std::vector<int> v;
4642 v.push_back(2);
4643 v.push_back(3);
4644 StringMatchResultListener listener;
4645 EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2),
4646 v, &listener)) << listener.str();
4647 EXPECT_THAT(
4648 listener.str(),
4649 Eq("where"
4650 " the following matchers don't match any elements:\n"
4651 "matcher #0: is equal to 1\n"
4652 "and"
4653 " where"
4654 " the following elements don't match any matchers:\n"
4655 "element #1: 3"));
4656}
4657
4658// Test helper for formatting element, matcher index pairs in expectations.
4659static string EMString(int element, int matcher) {
4660 stringstream ss;
4661 ss << "(element #" << element << ", matcher #" << matcher << ")";
4662 return ss.str();
4663}
4664
4665TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {
4666 // A situation where all elements and matchers have a match
4667 // associated with them, but the max matching is not perfect.
4668 std::vector<string> v;
4669 v.push_back("a");
4670 v.push_back("b");
4671 v.push_back("c");
4672 StringMatchResultListener listener;
4673 EXPECT_FALSE(ExplainMatchResult(
4674 UnorderedElementsAre("a", "a", AnyOf("b", "c")), v, &listener))
4675 << listener.str();
4676
4677 string prefix =
4678 "where no permutation of the elements can satisfy all matchers, "
4679 "and the closest match is 2 of 3 matchers with the "
4680 "pairings:\n";
4681
4682 // We have to be a bit loose here, because there are 4 valid max matches.
4683 EXPECT_THAT(
4684 listener.str(),
4685 AnyOf(prefix + "{\n " + EMString(0, 0) +
4686 ",\n " + EMString(1, 2) + "\n}",
4687 prefix + "{\n " + EMString(0, 1) +
4688 ",\n " + EMString(1, 2) + "\n}",
4689 prefix + "{\n " + EMString(0, 0) +
4690 ",\n " + EMString(2, 2) + "\n}",
4691 prefix + "{\n " + EMString(0, 1) +
4692 ",\n " + EMString(2, 2) + "\n}"));
4693}
4694
4695TEST_F(UnorderedElementsAreTest, Describe) {
4696 EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()),
4697 Eq("is empty"));
4698 EXPECT_THAT(
4699 Describe<IntVec>(UnorderedElementsAre(345)),
4700 Eq("has 1 element and that element is equal to 345"));
4701 EXPECT_THAT(
4702 Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),
4703 Eq("has 3 elements and there exists some permutation "
4704 "of elements such that:\n"
4705 " - element #0 is equal to 111, and\n"
4706 " - element #1 is equal to 222, and\n"
4707 " - element #2 is equal to 333"));
4708}
4709
4710TEST_F(UnorderedElementsAreTest, DescribeNegation) {
4711 EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),
4712 Eq("isn't empty"));
4713 EXPECT_THAT(
4714 DescribeNegation<IntVec>(UnorderedElementsAre(345)),
4715 Eq("doesn't have 1 element, or has 1 element that isn't equal to 345"));
4716 EXPECT_THAT(
4717 DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),
4718 Eq("doesn't have 3 elements, or there exists no permutation "
4719 "of elements such that:\n"
4720 " - element #0 is equal to 123, and\n"
4721 " - element #1 is equal to 234, and\n"
4722 " - element #2 is equal to 345"));
4723}
4724
4725namespace {
4726
4727// Used as a check on the more complex max flow method used in the
4728// real testing::internal::FindMaxBipartiteMatching. This method is
4729// compatible but runs in worst-case factorial time, so we only
4730// use it in testing for small problem sizes.
4731template <typename Graph>
4732class BacktrackingMaxBPMState {
4733 public:
4734 // Does not take ownership of 'g'.
4735 explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { }
4736
4737 ElementMatcherPairs Compute() {
4738 if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {
4739 return best_so_far_;
4740 }
4741 lhs_used_.assign(graph_->LhsSize(), kUnused);
4742 rhs_used_.assign(graph_->RhsSize(), kUnused);
4743 for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {
4744 matches_.clear();
4745 RecurseInto(irhs);
4746 if (best_so_far_.size() == graph_->RhsSize())
4747 break;
4748 }
4749 return best_so_far_;
4750 }
4751
4752 private:
4753 static const size_t kUnused = static_cast<size_t>(-1);
4754
4755 void PushMatch(size_t lhs, size_t rhs) {
4756 matches_.push_back(ElementMatcherPair(lhs, rhs));
4757 lhs_used_[lhs] = rhs;
4758 rhs_used_[rhs] = lhs;
4759 if (matches_.size() > best_so_far_.size()) {
4760 best_so_far_ = matches_;
4761 }
4762 }
4763
4764 void PopMatch() {
4765 const ElementMatcherPair& back = matches_.back();
4766 lhs_used_[back.first] = kUnused;
4767 rhs_used_[back.second] = kUnused;
4768 matches_.pop_back();
4769 }
4770
4771 bool RecurseInto(size_t irhs) {
4772 if (rhs_used_[irhs] != kUnused) {
4773 return true;
4774 }
4775 for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {
4776 if (lhs_used_[ilhs] != kUnused) {
4777 continue;
4778 }
4779 if (!graph_->HasEdge(ilhs, irhs)) {
4780 continue;
4781 }
4782 PushMatch(ilhs, irhs);
4783 if (best_so_far_.size() == graph_->RhsSize()) {
4784 return false;
4785 }
4786 for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {
4787 if (!RecurseInto(mi)) return false;
4788 }
4789 PopMatch();
4790 }
4791 return true;
4792 }
4793
4794 const Graph* graph_; // not owned
4795 std::vector<size_t> lhs_used_;
4796 std::vector<size_t> rhs_used_;
4797 ElementMatcherPairs matches_;
4798 ElementMatcherPairs best_so_far_;
4799};
4800
4801template <typename Graph>
4802const size_t BacktrackingMaxBPMState<Graph>::kUnused;
4803
4804} // namespace
4805
4806// Implement a simple backtracking algorithm to determine if it is possible
4807// to find one element per matcher, without reusing elements.
4808template <typename Graph>
4809ElementMatcherPairs
4810FindBacktrackingMaxBPM(const Graph& g) {
4811 return BacktrackingMaxBPMState<Graph>(&g).Compute();
4812}
4813
4814class BacktrackingBPMTest : public ::testing::Test { };
4815
4816// Tests the MaxBipartiteMatching algorithm with square matrices.
4817// The single int param is the # of nodes on each of the left and right sides.
4818class BipartiteTest : public ::testing::TestWithParam<int> { };
4819
4820// Verify all match graphs up to some moderate number of edges.
4821TEST_P(BipartiteTest, Exhaustive) {
4822 int nodes = GetParam();
4823 MatchMatrix graph(nodes, nodes);
4824 do {
4825 ElementMatcherPairs matches =
4826 internal::FindMaxBipartiteMatching(graph);
4827 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())
4828 << "graph: " << graph.DebugString();
4829 // Check that all elements of matches are in the graph.
4830 // Check that elements of first and second are unique.
4831 std::vector<bool> seen_element(graph.LhsSize());
4832 std::vector<bool> seen_matcher(graph.RhsSize());
4833 SCOPED_TRACE(PrintToString(matches));
4834 for (size_t i = 0; i < matches.size(); ++i) {
4835 size_t ilhs = matches[i].first;
4836 size_t irhs = matches[i].second;
4837 EXPECT_TRUE(graph.HasEdge(ilhs, irhs));
4838 EXPECT_FALSE(seen_element[ilhs]);
4839 EXPECT_FALSE(seen_matcher[irhs]);
4840 seen_element[ilhs] = true;
4841 seen_matcher[irhs] = true;
4842 }
4843 } while (graph.NextGraph());
4844}
4845
4846INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteTest,
4847 ::testing::Range(0, 5));
4848
4849// Parameterized by a pair interpreted as (LhsSize, RhsSize).
4850class BipartiteNonSquareTest
4851 : public ::testing::TestWithParam<std::pair<size_t, size_t> > {
4852};
4853
4854TEST_F(BipartiteNonSquareTest, SimpleBacktracking) {
4855 // .......
4856 // 0:-----\ :
4857 // 1:---\ | :
4858 // 2:---\ | :
4859 // 3:-\ | | :
4860 // :.......:
4861 // 0 1 2
4862 MatchMatrix g(4, 3);
4863 static const int kEdges[][2] = { {0, 2}, {1, 1}, {2, 1}, {3, 0} };
4864 for (size_t i = 0; i < GMOCK_ARRAY_SIZE_(kEdges); ++i) {
4865 g.SetEdge(kEdges[i][0], kEdges[i][1], true);
4866 }
4867 EXPECT_THAT(FindBacktrackingMaxBPM(g),
4868 ElementsAre(Pair(3, 0),
4869 Pair(AnyOf(1, 2), 1),
4870 Pair(0, 2))) << g.DebugString();
4871}
4872
4873// Verify a few nonsquare matrices.
4874TEST_P(BipartiteNonSquareTest, Exhaustive) {
4875 size_t nlhs = GetParam().first;
4876 size_t nrhs = GetParam().second;
4877 MatchMatrix graph(nlhs, nrhs);
4878 do {
4879 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
4880 internal::FindMaxBipartiteMatching(graph).size())
4881 << "graph: " << graph.DebugString()
4882 << "\nbacktracking: "
4883 << PrintToString(FindBacktrackingMaxBPM(graph))
4884 << "\nmax flow: "
4885 << PrintToString(internal::FindMaxBipartiteMatching(graph));
4886 } while (graph.NextGraph());
4887}
4888
4889INSTANTIATE_TEST_CASE_P(AllGraphs, BipartiteNonSquareTest,
4890 testing::Values(
4891 std::make_pair(1, 2),
4892 std::make_pair(2, 1),
4893 std::make_pair(3, 2),
4894 std::make_pair(2, 3),
4895 std::make_pair(4, 1),
4896 std::make_pair(1, 4),
4897 std::make_pair(4, 3),
4898 std::make_pair(3, 4)));
4899
4900class BipartiteRandomTest
4901 : public ::testing::TestWithParam<std::pair<int, int> > {
4902};
4903
4904// Verifies a large sample of larger graphs.
4905TEST_P(BipartiteRandomTest, LargerNets) {
4906 int nodes = GetParam().first;
4907 int iters = GetParam().second;
4908 MatchMatrix graph(nodes, nodes);
4909
4910 testing::internal::Int32 seed = GTEST_FLAG(random_seed);
4911 if (seed == 0) {
4912 seed = static_cast<testing::internal::Int32>(time(NULL));
4913 }
4914
4915 for (; iters > 0; --iters, ++seed) {
4916 srand(static_cast<int>(seed));
4917 graph.Randomize();
4918 EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),
4919 internal::FindMaxBipartiteMatching(graph).size())
4920 << " graph: " << graph.DebugString()
4921 << "\nTo reproduce the failure, rerun the test with the flag"
4922 " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed;
4923 }
4924}
4925
4926// Test argument is a std::pair<int, int> representing (nodes, iters).
4927INSTANTIATE_TEST_CASE_P(Samples, BipartiteRandomTest,
4928 testing::Values(
4929 std::make_pair(5, 10000),
4930 std::make_pair(6, 5000),
4931 std::make_pair(7, 2000),
4932 std::make_pair(8, 500),
4933 std::make_pair(9, 100)));
4934
zhanyong.wan736baa82010-09-27 17:44:16 +00004935// Tests IsReadableTypeName().
4936
4937TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {
4938 EXPECT_TRUE(IsReadableTypeName("int"));
4939 EXPECT_TRUE(IsReadableTypeName("const unsigned char*"));
4940 EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>"));
4941 EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)"));
4942}
4943
4944TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {
4945 EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName"));
4946 EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]"));
4947 EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass"));
4948}
4949
4950TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {
4951 EXPECT_FALSE(
4952 IsReadableTypeName("basic_string<char, std::char_traits<char> >"));
4953 EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >"));
4954}
4955
4956TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {
4957 EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)"));
4958}
4959
zhanyong.wan4a5330d2009-02-19 00:36:44 +00004960// Tests JoinAsTuple().
4961
4962TEST(JoinAsTupleTest, JoinsEmptyTuple) {
4963 EXPECT_EQ("", JoinAsTuple(Strings()));
4964}
4965
4966TEST(JoinAsTupleTest, JoinsOneTuple) {
4967 const char* fields[] = { "1" };
4968 EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1)));
4969}
4970
4971TEST(JoinAsTupleTest, JoinsTwoTuple) {
4972 const char* fields[] = { "1", "a" };
4973 EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2)));
4974}
4975
4976TEST(JoinAsTupleTest, JoinsTenTuple) {
4977 const char* fields[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
4978 EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)",
4979 JoinAsTuple(Strings(fields, fields + 10)));
4980}
4981
4982// Tests FormatMatcherDescription().
4983
4984TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {
4985 EXPECT_EQ("is even",
zhanyong.wanb4140802010-06-08 22:53:57 +00004986 FormatMatcherDescription(false, "IsEven", Strings()));
4987 EXPECT_EQ("not (is even)",
4988 FormatMatcherDescription(true, "IsEven", Strings()));
zhanyong.wan4a5330d2009-02-19 00:36:44 +00004989
4990 const char* params[] = { "5" };
4991 EXPECT_EQ("equals 5",
zhanyong.wanb4140802010-06-08 22:53:57 +00004992 FormatMatcherDescription(false, "Equals",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00004993 Strings(params, params + 1)));
4994
4995 const char* params2[] = { "5", "8" };
4996 EXPECT_EQ("is in range (5, 8)",
zhanyong.wanb4140802010-06-08 22:53:57 +00004997 FormatMatcherDescription(false, "IsInRange",
zhanyong.wan4a5330d2009-02-19 00:36:44 +00004998 Strings(params2, params2 + 2)));
4999}
5000
zhanyong.wan2b43a9e2009-08-31 23:51:23 +00005001// Tests PolymorphicMatcher::mutable_impl().
5002TEST(PolymorphicMatcherTest, CanAccessMutableImpl) {
5003 PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5004 DivisibleByImpl& impl = m.mutable_impl();
5005 EXPECT_EQ(42, impl.divider());
5006
5007 impl.set_divider(0);
5008 EXPECT_EQ(0, m.mutable_impl().divider());
5009}
5010
5011// Tests PolymorphicMatcher::impl().
5012TEST(PolymorphicMatcherTest, CanAccessImpl) {
5013 const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));
5014 const DivisibleByImpl& impl = m.impl();
5015 EXPECT_EQ(42, impl.divider());
5016}
5017
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005018TEST(MatcherTupleTest, ExplainsMatchFailure) {
5019 stringstream ss1;
5020 ExplainMatchFailureTupleTo(make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),
5021 make_tuple('a', 10), &ss1);
5022 EXPECT_EQ("", ss1.str()); // Successful match.
5023
5024 stringstream ss2;
5025 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5026 make_tuple(2, 'b'), &ss2);
5027 EXPECT_EQ(" Expected arg #0: is > 5\n"
5028 " Actual: 2, which is 3 less than 5\n"
zhanyong.wand60c5f42010-07-21 22:21:07 +00005029 " Expected arg #1: is equal to 'a' (97, 0x61)\n"
5030 " Actual: 'b' (98, 0x62)\n",
zhanyong.wanb1c7f932010-03-24 17:35:11 +00005031 ss2.str()); // Failed match where both arguments need explanation.
5032
5033 stringstream ss3;
5034 ExplainMatchFailureTupleTo(make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),
5035 make_tuple(2, 'a'), &ss3);
5036 EXPECT_EQ(" Expected arg #0: is > 5\n"
5037 " Actual: 2, which is 3 less than 5\n",
5038 ss3.str()); // Failed match where only one argument needs
5039 // explanation.
5040}
5041
zhanyong.wan33605ba2010-04-22 23:37:47 +00005042// Tests Each().
5043
5044TEST(EachTest, ExplainsMatchResultCorrectly) {
5045 set<int> a; // empty
5046
5047 Matcher<set<int> > m = Each(2);
5048 EXPECT_EQ("", Explain(m, a));
5049
zhanyong.wan736baa82010-09-27 17:44:16 +00005050 Matcher<const int(&)[1]> n = Each(1); // NOLINT
zhanyong.wan33605ba2010-04-22 23:37:47 +00005051
5052 const int b[1] = { 1 };
5053 EXPECT_EQ("", Explain(n, b));
5054
5055 n = Each(3);
5056 EXPECT_EQ("whose element #0 doesn't match", Explain(n, b));
5057
5058 a.insert(1);
5059 a.insert(2);
5060 a.insert(3);
5061 m = Each(GreaterThan(0));
5062 EXPECT_EQ("", Explain(m, a));
5063
5064 m = Each(GreaterThan(10));
5065 EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10",
5066 Explain(m, a));
5067}
5068
5069TEST(EachTest, DescribesItselfCorrectly) {
5070 Matcher<vector<int> > m = Each(1);
5071 EXPECT_EQ("only contains elements that is equal to 1", Describe(m));
5072
5073 Matcher<vector<int> > m2 = Not(m);
5074 EXPECT_EQ("contains some element that isn't equal to 1", Describe(m2));
5075}
5076
5077TEST(EachTest, MatchesVectorWhenAllElementsMatch) {
5078 vector<int> some_vector;
5079 EXPECT_THAT(some_vector, Each(1));
5080 some_vector.push_back(3);
5081 EXPECT_THAT(some_vector, Not(Each(1)));
5082 EXPECT_THAT(some_vector, Each(3));
5083 some_vector.push_back(1);
5084 some_vector.push_back(2);
5085 EXPECT_THAT(some_vector, Not(Each(3)));
5086 EXPECT_THAT(some_vector, Each(Lt(3.5)));
5087
5088 vector<string> another_vector;
5089 another_vector.push_back("fee");
5090 EXPECT_THAT(another_vector, Each(string("fee")));
5091 another_vector.push_back("fie");
5092 another_vector.push_back("foe");
5093 another_vector.push_back("fum");
5094 EXPECT_THAT(another_vector, Not(Each(string("fee"))));
5095}
5096
5097TEST(EachTest, MatchesMapWhenAllElementsMatch) {
5098 map<const char*, int> my_map;
5099 const char* bar = "a string";
5100 my_map[bar] = 2;
5101 EXPECT_THAT(my_map, Each(make_pair(bar, 2)));
5102
5103 map<string, int> another_map;
5104 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5105 another_map["fee"] = 1;
5106 EXPECT_THAT(another_map, Each(make_pair(string("fee"), 1)));
5107 another_map["fie"] = 2;
5108 another_map["foe"] = 3;
5109 another_map["fum"] = 4;
5110 EXPECT_THAT(another_map, Not(Each(make_pair(string("fee"), 1))));
5111 EXPECT_THAT(another_map, Not(Each(make_pair(string("fum"), 1))));
5112 EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));
5113}
5114
5115TEST(EachTest, AcceptsMatcher) {
5116 const int a[] = { 1, 2, 3 };
5117 EXPECT_THAT(a, Each(Gt(0)));
5118 EXPECT_THAT(a, Not(Each(Gt(1))));
5119}
5120
5121TEST(EachTest, WorksForNativeArrayAsTuple) {
5122 const int a[] = { 1, 2 };
5123 const int* const pointer = a;
5124 EXPECT_THAT(make_tuple(pointer, 2), Each(Gt(0)));
5125 EXPECT_THAT(make_tuple(pointer, 2), Not(Each(Gt(1))));
5126}
5127
zhanyong.wanab5b77c2010-05-17 19:32:48 +00005128// For testing Pointwise().
5129class IsHalfOfMatcher {
5130 public:
5131 template <typename T1, typename T2>
5132 bool MatchAndExplain(const tuple<T1, T2>& a_pair,
5133 MatchResultListener* listener) const {
5134 if (get<0>(a_pair) == get<1>(a_pair)/2) {
5135 *listener << "where the second is " << get<1>(a_pair);
5136 return true;
5137 } else {
5138 *listener << "where the second/2 is " << get<1>(a_pair)/2;
5139 return false;
5140 }
5141 }
5142
5143 void DescribeTo(ostream* os) const {
5144 *os << "are a pair where the first is half of the second";
5145 }
5146
5147 void DescribeNegationTo(ostream* os) const {
5148 *os << "are a pair where the first isn't half of the second";
5149 }
5150};
5151
5152PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {
5153 return MakePolymorphicMatcher(IsHalfOfMatcher());
5154}
5155
5156TEST(PointwiseTest, DescribesSelf) {
5157 vector<int> rhs;
5158 rhs.push_back(1);
5159 rhs.push_back(2);
5160 rhs.push_back(3);
5161 const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);
5162 EXPECT_EQ("contains 3 values, where each value and its corresponding value "
5163 "in { 1, 2, 3 } are a pair where the first is half of the second",
5164 Describe(m));
5165 EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some "
5166 "index i where x and the i-th value of { 1, 2, 3 } are a pair "
5167 "where the first isn't half of the second",
5168 DescribeNegation(m));
5169}
5170
5171TEST(PointwiseTest, MakesCopyOfRhs) {
5172 list<signed char> rhs;
5173 rhs.push_back(2);
5174 rhs.push_back(4);
5175
5176 int lhs[] = { 1, 2 };
5177 const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs);
5178 EXPECT_THAT(lhs, m);
5179
5180 // Changing rhs now shouldn't affect m, which made a copy of rhs.
5181 rhs.push_back(6);
5182 EXPECT_THAT(lhs, m);
5183}
5184
5185TEST(PointwiseTest, WorksForLhsNativeArray) {
5186 const int lhs[] = { 1, 2, 3 };
5187 vector<int> rhs;
5188 rhs.push_back(2);
5189 rhs.push_back(4);
5190 rhs.push_back(6);
5191 EXPECT_THAT(lhs, Pointwise(Lt(), rhs));
5192 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5193}
5194
5195TEST(PointwiseTest, WorksForRhsNativeArray) {
5196 const int rhs[] = { 1, 2, 3 };
5197 vector<int> lhs;
5198 lhs.push_back(2);
5199 lhs.push_back(4);
5200 lhs.push_back(6);
5201 EXPECT_THAT(lhs, Pointwise(Gt(), rhs));
5202 EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));
5203}
5204
5205TEST(PointwiseTest, RejectsWrongSize) {
5206 const double lhs[2] = { 1, 2 };
5207 const int rhs[1] = { 0 };
5208 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));
5209 EXPECT_EQ("which contains 2 values",
5210 Explain(Pointwise(Gt(), rhs), lhs));
5211
5212 const int rhs2[3] = { 0, 1, 2 };
5213 EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));
5214}
5215
5216TEST(PointwiseTest, RejectsWrongContent) {
5217 const double lhs[3] = { 1, 2, 3 };
5218 const int rhs[3] = { 2, 6, 4 };
5219 EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));
5220 EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, "
5221 "where the second/2 is 3",
5222 Explain(Pointwise(IsHalfOf(), rhs), lhs));
5223}
5224
5225TEST(PointwiseTest, AcceptsCorrectContent) {
5226 const double lhs[3] = { 1, 2, 3 };
5227 const int rhs[3] = { 2, 4, 6 };
5228 EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));
5229 EXPECT_EQ("", Explain(Pointwise(IsHalfOf(), rhs), lhs));
5230}
5231
5232TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {
5233 const double lhs[3] = { 1, 2, 3 };
5234 const int rhs[3] = { 2, 4, 6 };
5235 const Matcher<tuple<const double&, const int&> > m1 = IsHalfOf();
5236 EXPECT_THAT(lhs, Pointwise(m1, rhs));
5237 EXPECT_EQ("", Explain(Pointwise(m1, rhs), lhs));
5238
5239 // This type works as a tuple<const double&, const int&> can be
5240 // implicitly cast to tuple<double, int>.
5241 const Matcher<tuple<double, int> > m2 = IsHalfOf();
5242 EXPECT_THAT(lhs, Pointwise(m2, rhs));
5243 EXPECT_EQ("", Explain(Pointwise(m2, rhs), lhs));
5244}
5245
shiqiane35fdd92008-12-10 05:08:54 +00005246} // namespace gmock_matchers_test
5247} // namespace testing