1 | // 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 | |
31 | // Google Mock - a framework for writing C++ mock classes. |
32 | // |
33 | // This file tests some commonly used argument matchers. |
34 | |
35 | // Silence warning C4244: 'initializing': conversion from 'int' to 'short', |
36 | // possible loss of data and C4100, unreferenced local parameter |
37 | #ifdef _MSC_VER |
38 | # pragma warning(push) |
39 | # pragma warning(disable:4244) |
40 | # pragma warning(disable:4100) |
41 | #endif |
42 | |
43 | #include "gmock/gmock-matchers.h" |
44 | #include "gmock/gmock-more-matchers.h" |
45 | |
46 | #include <string.h> |
47 | #include <time.h> |
48 | #include <deque> |
49 | #include <forward_list> |
50 | #include <functional> |
51 | #include <iostream> |
52 | #include <iterator> |
53 | #include <limits> |
54 | #include <list> |
55 | #include <map> |
56 | #include <memory> |
57 | #include <set> |
58 | #include <sstream> |
59 | #include <string> |
60 | #include <type_traits> |
61 | #include <utility> |
62 | #include <vector> |
63 | #include "gmock/gmock.h" |
64 | #include "gtest/gtest.h" |
65 | #include "gtest/gtest-spi.h" |
66 | |
67 | namespace testing { |
68 | namespace gmock_matchers_test { |
69 | namespace { |
70 | |
71 | using std::greater; |
72 | using std::less; |
73 | using std::list; |
74 | using std::make_pair; |
75 | using std::map; |
76 | using std::multimap; |
77 | using std::multiset; |
78 | using std::ostream; |
79 | using std::pair; |
80 | using std::set; |
81 | using std::stringstream; |
82 | using std::vector; |
83 | using testing::internal::DummyMatchResultListener; |
84 | using testing::internal::ElementMatcherPair; |
85 | using testing::internal::ElementMatcherPairs; |
86 | using testing::internal::ExplainMatchFailureTupleTo; |
87 | using testing::internal::FloatingEqMatcher; |
88 | using testing::internal::FormatMatcherDescription; |
89 | using testing::internal::IsReadableTypeName; |
90 | using testing::internal::MatchMatrix; |
91 | using testing::internal::PredicateFormatterFromMatcher; |
92 | using testing::internal::RE; |
93 | using testing::internal::StreamMatchResultListener; |
94 | using testing::internal::Strings; |
95 | |
96 | // Helper for testing container-valued matchers in mock method context. It is |
97 | // important to test matchers in this context, since it requires additional type |
98 | // deduction beyond what EXPECT_THAT does, thus making it more restrictive. |
99 | struct ContainerHelper { |
100 | MOCK_METHOD1(Call, void(std::vector<std::unique_ptr<int>>)); |
101 | }; |
102 | |
103 | std::vector<std::unique_ptr<int>> MakeUniquePtrs(const std::vector<int>& ints) { |
104 | std::vector<std::unique_ptr<int>> pointers; |
105 | for (int i : ints) pointers.emplace_back(new int(i)); |
106 | return pointers; |
107 | } |
108 | |
109 | // For testing ExplainMatchResultTo(). |
110 | class GreaterThanMatcher : public MatcherInterface<int> { |
111 | public: |
112 | explicit GreaterThanMatcher(int rhs) : rhs_(rhs) {} |
113 | |
114 | void DescribeTo(ostream* os) const override { *os << "is > " << rhs_; } |
115 | |
116 | bool MatchAndExplain(int lhs, MatchResultListener* listener) const override { |
117 | const int diff = lhs - rhs_; |
118 | if (diff > 0) { |
119 | *listener << "which is " << diff << " more than " << rhs_; |
120 | } else if (diff == 0) { |
121 | *listener << "which is the same as " << rhs_; |
122 | } else { |
123 | *listener << "which is " << -diff << " less than " << rhs_; |
124 | } |
125 | |
126 | return lhs > rhs_; |
127 | } |
128 | |
129 | private: |
130 | int rhs_; |
131 | }; |
132 | |
133 | Matcher<int> GreaterThan(int n) { |
134 | return MakeMatcher(new GreaterThanMatcher(n)); |
135 | } |
136 | |
137 | std::string OfType(const std::string& type_name) { |
138 | #if GTEST_HAS_RTTI |
139 | return " (of type " + type_name + ")" ; |
140 | #else |
141 | return "" ; |
142 | #endif |
143 | } |
144 | |
145 | // Returns the description of the given matcher. |
146 | template <typename T> |
147 | std::string Describe(const Matcher<T>& m) { |
148 | return DescribeMatcher<T>(m); |
149 | } |
150 | |
151 | // Returns the description of the negation of the given matcher. |
152 | template <typename T> |
153 | std::string DescribeNegation(const Matcher<T>& m) { |
154 | return DescribeMatcher<T>(m, true); |
155 | } |
156 | |
157 | // Returns the reason why x matches, or doesn't match, m. |
158 | template <typename MatcherType, typename Value> |
159 | std::string Explain(const MatcherType& m, const Value& x) { |
160 | StringMatchResultListener listener; |
161 | ExplainMatchResult(m, x, &listener); |
162 | return listener.str(); |
163 | } |
164 | |
165 | TEST(MonotonicMatcherTest, IsPrintable) { |
166 | stringstream ss; |
167 | ss << GreaterThan(5); |
168 | EXPECT_EQ("is > 5" , ss.str()); |
169 | } |
170 | |
171 | TEST(MatchResultListenerTest, StreamingWorks) { |
172 | StringMatchResultListener listener; |
173 | listener << "hi" << 5; |
174 | EXPECT_EQ("hi5" , listener.str()); |
175 | |
176 | listener.Clear(); |
177 | EXPECT_EQ("" , listener.str()); |
178 | |
179 | listener << 42; |
180 | EXPECT_EQ("42" , listener.str()); |
181 | |
182 | // Streaming shouldn't crash when the underlying ostream is NULL. |
183 | DummyMatchResultListener dummy; |
184 | dummy << "hi" << 5; |
185 | } |
186 | |
187 | TEST(MatchResultListenerTest, CanAccessUnderlyingStream) { |
188 | EXPECT_TRUE(DummyMatchResultListener().stream() == nullptr); |
189 | EXPECT_TRUE(StreamMatchResultListener(nullptr).stream() == nullptr); |
190 | |
191 | EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream()); |
192 | } |
193 | |
194 | TEST(MatchResultListenerTest, IsInterestedWorks) { |
195 | EXPECT_TRUE(StringMatchResultListener().IsInterested()); |
196 | EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested()); |
197 | |
198 | EXPECT_FALSE(DummyMatchResultListener().IsInterested()); |
199 | EXPECT_FALSE(StreamMatchResultListener(nullptr).IsInterested()); |
200 | } |
201 | |
202 | // Makes sure that the MatcherInterface<T> interface doesn't |
203 | // change. |
204 | class EvenMatcherImpl : public MatcherInterface<int> { |
205 | public: |
206 | bool MatchAndExplain(int x, |
207 | MatchResultListener* /* listener */) const override { |
208 | return x % 2 == 0; |
209 | } |
210 | |
211 | void DescribeTo(ostream* os) const override { *os << "is an even number" ; } |
212 | |
213 | // We deliberately don't define DescribeNegationTo() and |
214 | // ExplainMatchResultTo() here, to make sure the definition of these |
215 | // two methods is optional. |
216 | }; |
217 | |
218 | // Makes sure that the MatcherInterface API doesn't change. |
219 | TEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) { |
220 | EvenMatcherImpl m; |
221 | } |
222 | |
223 | // Tests implementing a monomorphic matcher using MatchAndExplain(). |
224 | |
225 | class NewEvenMatcherImpl : public MatcherInterface<int> { |
226 | public: |
227 | bool MatchAndExplain(int x, MatchResultListener* listener) const override { |
228 | const bool match = x % 2 == 0; |
229 | // Verifies that we can stream to a listener directly. |
230 | *listener << "value % " << 2; |
231 | if (listener->stream() != nullptr) { |
232 | // Verifies that we can stream to a listener's underlying stream |
233 | // too. |
234 | *listener->stream() << " == " << (x % 2); |
235 | } |
236 | return match; |
237 | } |
238 | |
239 | void DescribeTo(ostream* os) const override { *os << "is an even number" ; } |
240 | }; |
241 | |
242 | TEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) { |
243 | Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl); |
244 | EXPECT_TRUE(m.Matches(2)); |
245 | EXPECT_FALSE(m.Matches(3)); |
246 | EXPECT_EQ("value % 2 == 0" , Explain(m, 2)); |
247 | EXPECT_EQ("value % 2 == 1" , Explain(m, 3)); |
248 | } |
249 | |
250 | // Tests default-constructing a matcher. |
251 | TEST(MatcherTest, CanBeDefaultConstructed) { |
252 | Matcher<double> m; |
253 | } |
254 | |
255 | // Tests that Matcher<T> can be constructed from a MatcherInterface<T>*. |
256 | TEST(MatcherTest, CanBeConstructedFromMatcherInterface) { |
257 | const MatcherInterface<int>* impl = new EvenMatcherImpl; |
258 | Matcher<int> m(impl); |
259 | EXPECT_TRUE(m.Matches(4)); |
260 | EXPECT_FALSE(m.Matches(5)); |
261 | } |
262 | |
263 | // Tests that value can be used in place of Eq(value). |
264 | TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) { |
265 | Matcher<int> m1 = 5; |
266 | EXPECT_TRUE(m1.Matches(5)); |
267 | EXPECT_FALSE(m1.Matches(6)); |
268 | } |
269 | |
270 | // Tests that NULL can be used in place of Eq(NULL). |
271 | TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) { |
272 | Matcher<int*> m1 = nullptr; |
273 | EXPECT_TRUE(m1.Matches(nullptr)); |
274 | int n = 0; |
275 | EXPECT_FALSE(m1.Matches(&n)); |
276 | } |
277 | |
278 | // Tests that matchers can be constructed from a variable that is not properly |
279 | // defined. This should be illegal, but many users rely on this accidentally. |
280 | struct Undefined { |
281 | virtual ~Undefined() = 0; |
282 | static const int kInt = 1; |
283 | }; |
284 | |
285 | TEST(MatcherTest, CanBeConstructedFromUndefinedVariable) { |
286 | Matcher<int> m1 = Undefined::kInt; |
287 | EXPECT_TRUE(m1.Matches(1)); |
288 | EXPECT_FALSE(m1.Matches(2)); |
289 | } |
290 | |
291 | // Test that a matcher parameterized with an abstract class compiles. |
292 | TEST(MatcherTest, CanAcceptAbstractClass) { Matcher<const Undefined&> m = _; } |
293 | |
294 | // Tests that matchers are copyable. |
295 | TEST(MatcherTest, IsCopyable) { |
296 | // Tests the copy constructor. |
297 | Matcher<bool> m1 = Eq(false); |
298 | EXPECT_TRUE(m1.Matches(false)); |
299 | EXPECT_FALSE(m1.Matches(true)); |
300 | |
301 | // Tests the assignment operator. |
302 | m1 = Eq(true); |
303 | EXPECT_TRUE(m1.Matches(true)); |
304 | EXPECT_FALSE(m1.Matches(false)); |
305 | } |
306 | |
307 | // Tests that Matcher<T>::DescribeTo() calls |
308 | // MatcherInterface<T>::DescribeTo(). |
309 | TEST(MatcherTest, CanDescribeItself) { |
310 | EXPECT_EQ("is an even number" , |
311 | Describe(Matcher<int>(new EvenMatcherImpl))); |
312 | } |
313 | |
314 | // Tests Matcher<T>::MatchAndExplain(). |
315 | TEST(MatcherTest, MatchAndExplain) { |
316 | Matcher<int> m = GreaterThan(0); |
317 | StringMatchResultListener listener1; |
318 | EXPECT_TRUE(m.MatchAndExplain(42, &listener1)); |
319 | EXPECT_EQ("which is 42 more than 0" , listener1.str()); |
320 | |
321 | StringMatchResultListener listener2; |
322 | EXPECT_FALSE(m.MatchAndExplain(-9, &listener2)); |
323 | EXPECT_EQ("which is 9 less than 0" , listener2.str()); |
324 | } |
325 | |
326 | // Tests that a C-string literal can be implicitly converted to a |
327 | // Matcher<std::string> or Matcher<const std::string&>. |
328 | TEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { |
329 | Matcher<std::string> m1 = "hi" ; |
330 | EXPECT_TRUE(m1.Matches("hi" )); |
331 | EXPECT_FALSE(m1.Matches("hello" )); |
332 | |
333 | Matcher<const std::string&> m2 = "hi" ; |
334 | EXPECT_TRUE(m2.Matches("hi" )); |
335 | EXPECT_FALSE(m2.Matches("hello" )); |
336 | } |
337 | |
338 | // Tests that a string object can be implicitly converted to a |
339 | // Matcher<std::string> or Matcher<const std::string&>. |
340 | TEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) { |
341 | Matcher<std::string> m1 = std::string("hi" ); |
342 | EXPECT_TRUE(m1.Matches("hi" )); |
343 | EXPECT_FALSE(m1.Matches("hello" )); |
344 | |
345 | Matcher<const std::string&> m2 = std::string("hi" ); |
346 | EXPECT_TRUE(m2.Matches("hi" )); |
347 | EXPECT_FALSE(m2.Matches("hello" )); |
348 | } |
349 | |
350 | #if GTEST_HAS_ABSL |
351 | // Tests that a C-string literal can be implicitly converted to a |
352 | // Matcher<absl::string_view> or Matcher<const absl::string_view&>. |
353 | TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) { |
354 | Matcher<absl::string_view> m1 = "cats" ; |
355 | EXPECT_TRUE(m1.Matches("cats" )); |
356 | EXPECT_FALSE(m1.Matches("dogs" )); |
357 | |
358 | Matcher<const absl::string_view&> m2 = "cats" ; |
359 | EXPECT_TRUE(m2.Matches("cats" )); |
360 | EXPECT_FALSE(m2.Matches("dogs" )); |
361 | } |
362 | |
363 | // Tests that a std::string object can be implicitly converted to a |
364 | // Matcher<absl::string_view> or Matcher<const absl::string_view&>. |
365 | TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) { |
366 | Matcher<absl::string_view> m1 = std::string("cats" ); |
367 | EXPECT_TRUE(m1.Matches("cats" )); |
368 | EXPECT_FALSE(m1.Matches("dogs" )); |
369 | |
370 | Matcher<const absl::string_view&> m2 = std::string("cats" ); |
371 | EXPECT_TRUE(m2.Matches("cats" )); |
372 | EXPECT_FALSE(m2.Matches("dogs" )); |
373 | } |
374 | |
375 | // Tests that a absl::string_view object can be implicitly converted to a |
376 | // Matcher<absl::string_view> or Matcher<const absl::string_view&>. |
377 | TEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) { |
378 | Matcher<absl::string_view> m1 = absl::string_view("cats" ); |
379 | EXPECT_TRUE(m1.Matches("cats" )); |
380 | EXPECT_FALSE(m1.Matches("dogs" )); |
381 | |
382 | Matcher<const absl::string_view&> m2 = absl::string_view("cats" ); |
383 | EXPECT_TRUE(m2.Matches("cats" )); |
384 | EXPECT_FALSE(m2.Matches("dogs" )); |
385 | } |
386 | #endif // GTEST_HAS_ABSL |
387 | |
388 | // Tests that a std::reference_wrapper<std::string> object can be implicitly |
389 | // converted to a Matcher<std::string> or Matcher<const std::string&> via Eq(). |
390 | TEST(StringMatcherTest, |
391 | CanBeImplicitlyConstructedFromEqReferenceWrapperString) { |
392 | std::string value = "cats" ; |
393 | Matcher<std::string> m1 = Eq(std::ref(value)); |
394 | EXPECT_TRUE(m1.Matches("cats" )); |
395 | EXPECT_FALSE(m1.Matches("dogs" )); |
396 | |
397 | Matcher<const std::string&> m2 = Eq(std::ref(value)); |
398 | EXPECT_TRUE(m2.Matches("cats" )); |
399 | EXPECT_FALSE(m2.Matches("dogs" )); |
400 | } |
401 | |
402 | // Tests that MakeMatcher() constructs a Matcher<T> from a |
403 | // MatcherInterface* without requiring the user to explicitly |
404 | // write the type. |
405 | TEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) { |
406 | const MatcherInterface<int>* dummy_impl = nullptr; |
407 | Matcher<int> m = MakeMatcher(dummy_impl); |
408 | } |
409 | |
410 | // Tests that MakePolymorphicMatcher() can construct a polymorphic |
411 | // matcher from its implementation using the old API. |
412 | const int g_bar = 1; |
413 | class ReferencesBarOrIsZeroImpl { |
414 | public: |
415 | template <typename T> |
416 | bool MatchAndExplain(const T& x, |
417 | MatchResultListener* /* listener */) const { |
418 | const void* p = &x; |
419 | return p == &g_bar || x == 0; |
420 | } |
421 | |
422 | void DescribeTo(ostream* os) const { *os << "g_bar or zero" ; } |
423 | |
424 | void DescribeNegationTo(ostream* os) const { |
425 | *os << "doesn't reference g_bar and is not zero" ; |
426 | } |
427 | }; |
428 | |
429 | // This function verifies that MakePolymorphicMatcher() returns a |
430 | // PolymorphicMatcher<T> where T is the argument's type. |
431 | PolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() { |
432 | return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl()); |
433 | } |
434 | |
435 | TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) { |
436 | // Using a polymorphic matcher to match a reference type. |
437 | Matcher<const int&> m1 = ReferencesBarOrIsZero(); |
438 | EXPECT_TRUE(m1.Matches(0)); |
439 | // Verifies that the identity of a by-reference argument is preserved. |
440 | EXPECT_TRUE(m1.Matches(g_bar)); |
441 | EXPECT_FALSE(m1.Matches(1)); |
442 | EXPECT_EQ("g_bar or zero" , Describe(m1)); |
443 | |
444 | // Using a polymorphic matcher to match a value type. |
445 | Matcher<double> m2 = ReferencesBarOrIsZero(); |
446 | EXPECT_TRUE(m2.Matches(0.0)); |
447 | EXPECT_FALSE(m2.Matches(0.1)); |
448 | EXPECT_EQ("g_bar or zero" , Describe(m2)); |
449 | } |
450 | |
451 | // Tests implementing a polymorphic matcher using MatchAndExplain(). |
452 | |
453 | class PolymorphicIsEvenImpl { |
454 | public: |
455 | void DescribeTo(ostream* os) const { *os << "is even" ; } |
456 | |
457 | void DescribeNegationTo(ostream* os) const { |
458 | *os << "is odd" ; |
459 | } |
460 | |
461 | template <typename T> |
462 | bool MatchAndExplain(const T& x, MatchResultListener* listener) const { |
463 | // Verifies that we can stream to the listener directly. |
464 | *listener << "% " << 2; |
465 | if (listener->stream() != nullptr) { |
466 | // Verifies that we can stream to the listener's underlying stream |
467 | // too. |
468 | *listener->stream() << " == " << (x % 2); |
469 | } |
470 | return (x % 2) == 0; |
471 | } |
472 | }; |
473 | |
474 | PolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() { |
475 | return MakePolymorphicMatcher(PolymorphicIsEvenImpl()); |
476 | } |
477 | |
478 | TEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) { |
479 | // Using PolymorphicIsEven() as a Matcher<int>. |
480 | const Matcher<int> m1 = PolymorphicIsEven(); |
481 | EXPECT_TRUE(m1.Matches(42)); |
482 | EXPECT_FALSE(m1.Matches(43)); |
483 | EXPECT_EQ("is even" , Describe(m1)); |
484 | |
485 | const Matcher<int> not_m1 = Not(m1); |
486 | EXPECT_EQ("is odd" , Describe(not_m1)); |
487 | |
488 | EXPECT_EQ("% 2 == 0" , Explain(m1, 42)); |
489 | |
490 | // Using PolymorphicIsEven() as a Matcher<char>. |
491 | const Matcher<char> m2 = PolymorphicIsEven(); |
492 | EXPECT_TRUE(m2.Matches('\x42')); |
493 | EXPECT_FALSE(m2.Matches('\x43')); |
494 | EXPECT_EQ("is even" , Describe(m2)); |
495 | |
496 | const Matcher<char> not_m2 = Not(m2); |
497 | EXPECT_EQ("is odd" , Describe(not_m2)); |
498 | |
499 | EXPECT_EQ("% 2 == 0" , Explain(m2, '\x42')); |
500 | } |
501 | |
502 | // Tests that MatcherCast<T>(m) works when m is a polymorphic matcher. |
503 | TEST(MatcherCastTest, FromPolymorphicMatcher) { |
504 | Matcher<int> m = MatcherCast<int>(Eq(5)); |
505 | EXPECT_TRUE(m.Matches(5)); |
506 | EXPECT_FALSE(m.Matches(6)); |
507 | } |
508 | |
509 | // For testing casting matchers between compatible types. |
510 | class IntValue { |
511 | public: |
512 | // An int can be statically (although not implicitly) cast to a |
513 | // IntValue. |
514 | explicit IntValue(int a_value) : value_(a_value) {} |
515 | |
516 | int value() const { return value_; } |
517 | private: |
518 | int value_; |
519 | }; |
520 | |
521 | // For testing casting matchers between compatible types. |
522 | bool IsPositiveIntValue(const IntValue& foo) { |
523 | return foo.value() > 0; |
524 | } |
525 | |
526 | // Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T |
527 | // can be statically converted to U. |
528 | TEST(MatcherCastTest, FromCompatibleType) { |
529 | Matcher<double> m1 = Eq(2.0); |
530 | Matcher<int> m2 = MatcherCast<int>(m1); |
531 | EXPECT_TRUE(m2.Matches(2)); |
532 | EXPECT_FALSE(m2.Matches(3)); |
533 | |
534 | Matcher<IntValue> m3 = Truly(IsPositiveIntValue); |
535 | Matcher<int> m4 = MatcherCast<int>(m3); |
536 | // In the following, the arguments 1 and 0 are statically converted |
537 | // to IntValue objects, and then tested by the IsPositiveIntValue() |
538 | // predicate. |
539 | EXPECT_TRUE(m4.Matches(1)); |
540 | EXPECT_FALSE(m4.Matches(0)); |
541 | } |
542 | |
543 | // Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>. |
544 | TEST(MatcherCastTest, FromConstReferenceToNonReference) { |
545 | Matcher<const int&> m1 = Eq(0); |
546 | Matcher<int> m2 = MatcherCast<int>(m1); |
547 | EXPECT_TRUE(m2.Matches(0)); |
548 | EXPECT_FALSE(m2.Matches(1)); |
549 | } |
550 | |
551 | // Tests that MatcherCast<T>(m) works when m is a Matcher<T&>. |
552 | TEST(MatcherCastTest, FromReferenceToNonReference) { |
553 | Matcher<int&> m1 = Eq(0); |
554 | Matcher<int> m2 = MatcherCast<int>(m1); |
555 | EXPECT_TRUE(m2.Matches(0)); |
556 | EXPECT_FALSE(m2.Matches(1)); |
557 | } |
558 | |
559 | // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>. |
560 | TEST(MatcherCastTest, FromNonReferenceToConstReference) { |
561 | Matcher<int> m1 = Eq(0); |
562 | Matcher<const int&> m2 = MatcherCast<const int&>(m1); |
563 | EXPECT_TRUE(m2.Matches(0)); |
564 | EXPECT_FALSE(m2.Matches(1)); |
565 | } |
566 | |
567 | // Tests that MatcherCast<T&>(m) works when m is a Matcher<T>. |
568 | TEST(MatcherCastTest, FromNonReferenceToReference) { |
569 | Matcher<int> m1 = Eq(0); |
570 | Matcher<int&> m2 = MatcherCast<int&>(m1); |
571 | int n = 0; |
572 | EXPECT_TRUE(m2.Matches(n)); |
573 | n = 1; |
574 | EXPECT_FALSE(m2.Matches(n)); |
575 | } |
576 | |
577 | // Tests that MatcherCast<T>(m) works when m is a Matcher<T>. |
578 | TEST(MatcherCastTest, FromSameType) { |
579 | Matcher<int> m1 = Eq(0); |
580 | Matcher<int> m2 = MatcherCast<int>(m1); |
581 | EXPECT_TRUE(m2.Matches(0)); |
582 | EXPECT_FALSE(m2.Matches(1)); |
583 | } |
584 | |
585 | // Tests that MatcherCast<T>(m) works when m is a value of the same type as the |
586 | // value type of the Matcher. |
587 | TEST(MatcherCastTest, FromAValue) { |
588 | Matcher<int> m = MatcherCast<int>(42); |
589 | EXPECT_TRUE(m.Matches(42)); |
590 | EXPECT_FALSE(m.Matches(239)); |
591 | } |
592 | |
593 | // Tests that MatcherCast<T>(m) works when m is a value of the type implicitly |
594 | // convertible to the value type of the Matcher. |
595 | TEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) { |
596 | const int kExpected = 'c'; |
597 | Matcher<int> m = MatcherCast<int>('c'); |
598 | EXPECT_TRUE(m.Matches(kExpected)); |
599 | EXPECT_FALSE(m.Matches(kExpected + 1)); |
600 | } |
601 | |
602 | struct NonImplicitlyConstructibleTypeWithOperatorEq { |
603 | friend bool operator==( |
604 | const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */, |
605 | int rhs) { |
606 | return 42 == rhs; |
607 | } |
608 | friend bool operator==( |
609 | int lhs, |
610 | const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) { |
611 | return lhs == 42; |
612 | } |
613 | }; |
614 | |
615 | // Tests that MatcherCast<T>(m) works when m is a neither a matcher nor |
616 | // implicitly convertible to the value type of the Matcher, but the value type |
617 | // of the matcher has operator==() overload accepting m. |
618 | TEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) { |
619 | Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m1 = |
620 | MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(42); |
621 | EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq())); |
622 | |
623 | Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m2 = |
624 | MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(239); |
625 | EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq())); |
626 | |
627 | // When updating the following lines please also change the comment to |
628 | // namespace convertible_from_any. |
629 | Matcher<int> m3 = |
630 | MatcherCast<int>(NonImplicitlyConstructibleTypeWithOperatorEq()); |
631 | EXPECT_TRUE(m3.Matches(42)); |
632 | EXPECT_FALSE(m3.Matches(239)); |
633 | } |
634 | |
635 | // ConvertibleFromAny does not work with MSVC. resulting in |
636 | // error C2440: 'initializing': cannot convert from 'Eq' to 'M' |
637 | // No constructor could take the source type, or constructor overload |
638 | // resolution was ambiguous |
639 | |
640 | #if !defined _MSC_VER |
641 | |
642 | // The below ConvertibleFromAny struct is implicitly constructible from anything |
643 | // and when in the same namespace can interact with other tests. In particular, |
644 | // if it is in the same namespace as other tests and one removes |
645 | // NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...); |
646 | // then the corresponding test still compiles (and it should not!) by implicitly |
647 | // converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny |
648 | // in m3.Matcher(). |
649 | namespace convertible_from_any { |
650 | // Implicitly convertible from any type. |
651 | struct ConvertibleFromAny { |
652 | ConvertibleFromAny(int a_value) : value(a_value) {} |
653 | template <typename T> |
654 | ConvertibleFromAny(const T& /*a_value*/) : value(-1) { |
655 | ADD_FAILURE() << "Conversion constructor called" ; |
656 | } |
657 | int value; |
658 | }; |
659 | |
660 | bool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) { |
661 | return a.value == b.value; |
662 | } |
663 | |
664 | ostream& operator<<(ostream& os, const ConvertibleFromAny& a) { |
665 | return os << a.value; |
666 | } |
667 | |
668 | TEST(MatcherCastTest, ConversionConstructorIsUsed) { |
669 | Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1); |
670 | EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); |
671 | EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); |
672 | } |
673 | |
674 | TEST(MatcherCastTest, FromConvertibleFromAny) { |
675 | Matcher<ConvertibleFromAny> m = |
676 | MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1))); |
677 | EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); |
678 | EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); |
679 | } |
680 | } // namespace convertible_from_any |
681 | |
682 | #endif // !defined _MSC_VER |
683 | |
684 | struct IntReferenceWrapper { |
685 | IntReferenceWrapper(const int& a_value) : value(&a_value) {} |
686 | const int* value; |
687 | }; |
688 | |
689 | bool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) { |
690 | return a.value == b.value; |
691 | } |
692 | |
693 | TEST(MatcherCastTest, ValueIsNotCopied) { |
694 | int n = 42; |
695 | Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n); |
696 | // Verify that the matcher holds a reference to n, not to its temporary copy. |
697 | EXPECT_TRUE(m.Matches(n)); |
698 | } |
699 | |
700 | class Base { |
701 | public: |
702 | virtual ~Base() {} |
703 | Base() {} |
704 | private: |
705 | GTEST_DISALLOW_COPY_AND_ASSIGN_(Base); |
706 | }; |
707 | |
708 | class Derived : public Base { |
709 | public: |
710 | Derived() : Base() {} |
711 | int i; |
712 | }; |
713 | |
714 | class OtherDerived : public Base {}; |
715 | |
716 | // Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher. |
717 | TEST(SafeMatcherCastTest, FromPolymorphicMatcher) { |
718 | Matcher<char> m2 = SafeMatcherCast<char>(Eq(32)); |
719 | EXPECT_TRUE(m2.Matches(' ')); |
720 | EXPECT_FALSE(m2.Matches('\n')); |
721 | } |
722 | |
723 | // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where |
724 | // T and U are arithmetic types and T can be losslessly converted to |
725 | // U. |
726 | TEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) { |
727 | Matcher<double> m1 = DoubleEq(1.0); |
728 | Matcher<float> m2 = SafeMatcherCast<float>(m1); |
729 | EXPECT_TRUE(m2.Matches(1.0f)); |
730 | EXPECT_FALSE(m2.Matches(2.0f)); |
731 | |
732 | Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a')); |
733 | EXPECT_TRUE(m3.Matches('a')); |
734 | EXPECT_FALSE(m3.Matches('b')); |
735 | } |
736 | |
737 | // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U |
738 | // are pointers or references to a derived and a base class, correspondingly. |
739 | TEST(SafeMatcherCastTest, FromBaseClass) { |
740 | Derived d, d2; |
741 | Matcher<Base*> m1 = Eq(&d); |
742 | Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1); |
743 | EXPECT_TRUE(m2.Matches(&d)); |
744 | EXPECT_FALSE(m2.Matches(&d2)); |
745 | |
746 | Matcher<Base&> m3 = Ref(d); |
747 | Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3); |
748 | EXPECT_TRUE(m4.Matches(d)); |
749 | EXPECT_FALSE(m4.Matches(d2)); |
750 | } |
751 | |
752 | // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>. |
753 | TEST(SafeMatcherCastTest, FromConstReferenceToReference) { |
754 | int n = 0; |
755 | Matcher<const int&> m1 = Ref(n); |
756 | Matcher<int&> m2 = SafeMatcherCast<int&>(m1); |
757 | int n1 = 0; |
758 | EXPECT_TRUE(m2.Matches(n)); |
759 | EXPECT_FALSE(m2.Matches(n1)); |
760 | } |
761 | |
762 | // Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>. |
763 | TEST(SafeMatcherCastTest, FromNonReferenceToConstReference) { |
764 | Matcher<int> m1 = Eq(0); |
765 | Matcher<const int&> m2 = SafeMatcherCast<const int&>(m1); |
766 | EXPECT_TRUE(m2.Matches(0)); |
767 | EXPECT_FALSE(m2.Matches(1)); |
768 | } |
769 | |
770 | // Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>. |
771 | TEST(SafeMatcherCastTest, FromNonReferenceToReference) { |
772 | Matcher<int> m1 = Eq(0); |
773 | Matcher<int&> m2 = SafeMatcherCast<int&>(m1); |
774 | int n = 0; |
775 | EXPECT_TRUE(m2.Matches(n)); |
776 | n = 1; |
777 | EXPECT_FALSE(m2.Matches(n)); |
778 | } |
779 | |
780 | // Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>. |
781 | TEST(SafeMatcherCastTest, FromSameType) { |
782 | Matcher<int> m1 = Eq(0); |
783 | Matcher<int> m2 = SafeMatcherCast<int>(m1); |
784 | EXPECT_TRUE(m2.Matches(0)); |
785 | EXPECT_FALSE(m2.Matches(1)); |
786 | } |
787 | |
788 | #if !defined _MSC_VER |
789 | |
790 | namespace convertible_from_any { |
791 | TEST(SafeMatcherCastTest, ConversionConstructorIsUsed) { |
792 | Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1); |
793 | EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); |
794 | EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); |
795 | } |
796 | |
797 | TEST(SafeMatcherCastTest, FromConvertibleFromAny) { |
798 | Matcher<ConvertibleFromAny> m = |
799 | SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1))); |
800 | EXPECT_TRUE(m.Matches(ConvertibleFromAny(1))); |
801 | EXPECT_FALSE(m.Matches(ConvertibleFromAny(2))); |
802 | } |
803 | } // namespace convertible_from_any |
804 | |
805 | #endif // !defined _MSC_VER |
806 | |
807 | TEST(SafeMatcherCastTest, ValueIsNotCopied) { |
808 | int n = 42; |
809 | Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n); |
810 | // Verify that the matcher holds a reference to n, not to its temporary copy. |
811 | EXPECT_TRUE(m.Matches(n)); |
812 | } |
813 | |
814 | TEST(ExpectThat, TakesLiterals) { |
815 | EXPECT_THAT(1, 1); |
816 | EXPECT_THAT(1.0, 1.0); |
817 | EXPECT_THAT(std::string(), "" ); |
818 | } |
819 | |
820 | TEST(ExpectThat, TakesFunctions) { |
821 | struct Helper { |
822 | static void Func() {} |
823 | }; |
824 | void (*func)() = Helper::Func; |
825 | EXPECT_THAT(func, Helper::Func); |
826 | EXPECT_THAT(func, &Helper::Func); |
827 | } |
828 | |
829 | // Tests that A<T>() matches any value of type T. |
830 | TEST(ATest, MatchesAnyValue) { |
831 | // Tests a matcher for a value type. |
832 | Matcher<double> m1 = A<double>(); |
833 | EXPECT_TRUE(m1.Matches(91.43)); |
834 | EXPECT_TRUE(m1.Matches(-15.32)); |
835 | |
836 | // Tests a matcher for a reference type. |
837 | int a = 2; |
838 | int b = -6; |
839 | Matcher<int&> m2 = A<int&>(); |
840 | EXPECT_TRUE(m2.Matches(a)); |
841 | EXPECT_TRUE(m2.Matches(b)); |
842 | } |
843 | |
844 | TEST(ATest, WorksForDerivedClass) { |
845 | Base base; |
846 | Derived derived; |
847 | EXPECT_THAT(&base, A<Base*>()); |
848 | // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>()); |
849 | EXPECT_THAT(&derived, A<Base*>()); |
850 | EXPECT_THAT(&derived, A<Derived*>()); |
851 | } |
852 | |
853 | // Tests that A<T>() describes itself properly. |
854 | TEST(ATest, CanDescribeSelf) { |
855 | EXPECT_EQ("is anything" , Describe(A<bool>())); |
856 | } |
857 | |
858 | // Tests that An<T>() matches any value of type T. |
859 | TEST(AnTest, MatchesAnyValue) { |
860 | // Tests a matcher for a value type. |
861 | Matcher<int> m1 = An<int>(); |
862 | EXPECT_TRUE(m1.Matches(9143)); |
863 | EXPECT_TRUE(m1.Matches(-1532)); |
864 | |
865 | // Tests a matcher for a reference type. |
866 | int a = 2; |
867 | int b = -6; |
868 | Matcher<int&> m2 = An<int&>(); |
869 | EXPECT_TRUE(m2.Matches(a)); |
870 | EXPECT_TRUE(m2.Matches(b)); |
871 | } |
872 | |
873 | // Tests that An<T>() describes itself properly. |
874 | TEST(AnTest, CanDescribeSelf) { |
875 | EXPECT_EQ("is anything" , Describe(An<int>())); |
876 | } |
877 | |
878 | // Tests that _ can be used as a matcher for any type and matches any |
879 | // value of that type. |
880 | TEST(UnderscoreTest, MatchesAnyValue) { |
881 | // Uses _ as a matcher for a value type. |
882 | Matcher<int> m1 = _; |
883 | EXPECT_TRUE(m1.Matches(123)); |
884 | EXPECT_TRUE(m1.Matches(-242)); |
885 | |
886 | // Uses _ as a matcher for a reference type. |
887 | bool a = false; |
888 | const bool b = true; |
889 | Matcher<const bool&> m2 = _; |
890 | EXPECT_TRUE(m2.Matches(a)); |
891 | EXPECT_TRUE(m2.Matches(b)); |
892 | } |
893 | |
894 | // Tests that _ describes itself properly. |
895 | TEST(UnderscoreTest, CanDescribeSelf) { |
896 | Matcher<int> m = _; |
897 | EXPECT_EQ("is anything" , Describe(m)); |
898 | } |
899 | |
900 | // Tests that Eq(x) matches any value equal to x. |
901 | TEST(EqTest, MatchesEqualValue) { |
902 | // 2 C-strings with same content but different addresses. |
903 | const char a1[] = "hi" ; |
904 | const char a2[] = "hi" ; |
905 | |
906 | Matcher<const char*> m1 = Eq(a1); |
907 | EXPECT_TRUE(m1.Matches(a1)); |
908 | EXPECT_FALSE(m1.Matches(a2)); |
909 | } |
910 | |
911 | // Tests that Eq(v) describes itself properly. |
912 | |
913 | class Unprintable { |
914 | public: |
915 | Unprintable() : c_('a') {} |
916 | |
917 | bool operator==(const Unprintable& /* rhs */) const { return true; } |
918 | // -Wunused-private-field: dummy accessor for `c_`. |
919 | char dummy_c() { return c_; } |
920 | private: |
921 | char c_; |
922 | }; |
923 | |
924 | TEST(EqTest, CanDescribeSelf) { |
925 | Matcher<Unprintable> m = Eq(Unprintable()); |
926 | EXPECT_EQ("is equal to 1-byte object <61>" , Describe(m)); |
927 | } |
928 | |
929 | // Tests that Eq(v) can be used to match any type that supports |
930 | // comparing with type T, where T is v's type. |
931 | TEST(EqTest, IsPolymorphic) { |
932 | Matcher<int> m1 = Eq(1); |
933 | EXPECT_TRUE(m1.Matches(1)); |
934 | EXPECT_FALSE(m1.Matches(2)); |
935 | |
936 | Matcher<char> m2 = Eq(1); |
937 | EXPECT_TRUE(m2.Matches('\1')); |
938 | EXPECT_FALSE(m2.Matches('a')); |
939 | } |
940 | |
941 | // Tests that TypedEq<T>(v) matches values of type T that's equal to v. |
942 | TEST(TypedEqTest, ChecksEqualityForGivenType) { |
943 | Matcher<char> m1 = TypedEq<char>('a'); |
944 | EXPECT_TRUE(m1.Matches('a')); |
945 | EXPECT_FALSE(m1.Matches('b')); |
946 | |
947 | Matcher<int> m2 = TypedEq<int>(6); |
948 | EXPECT_TRUE(m2.Matches(6)); |
949 | EXPECT_FALSE(m2.Matches(7)); |
950 | } |
951 | |
952 | // Tests that TypedEq(v) describes itself properly. |
953 | TEST(TypedEqTest, CanDescribeSelf) { |
954 | EXPECT_EQ("is equal to 2" , Describe(TypedEq<int>(2))); |
955 | } |
956 | |
957 | // Tests that TypedEq<T>(v) has type Matcher<T>. |
958 | |
959 | // Type<T>::IsTypeOf(v) compiles if and only if the type of value v is T, where |
960 | // T is a "bare" type (i.e. not in the form of const U or U&). If v's type is |
961 | // not T, the compiler will generate a message about "undefined reference". |
962 | template <typename T> |
963 | struct Type { |
964 | static bool IsTypeOf(const T& /* v */) { return true; } |
965 | |
966 | template <typename T2> |
967 | static void IsTypeOf(T2 v); |
968 | }; |
969 | |
970 | TEST(TypedEqTest, HasSpecifiedType) { |
971 | // Verfies that the type of TypedEq<T>(v) is Matcher<T>. |
972 | Type<Matcher<int> >::IsTypeOf(TypedEq<int>(5)); |
973 | Type<Matcher<double> >::IsTypeOf(TypedEq<double>(5)); |
974 | } |
975 | |
976 | // Tests that Ge(v) matches anything >= v. |
977 | TEST(GeTest, ImplementsGreaterThanOrEqual) { |
978 | Matcher<int> m1 = Ge(0); |
979 | EXPECT_TRUE(m1.Matches(1)); |
980 | EXPECT_TRUE(m1.Matches(0)); |
981 | EXPECT_FALSE(m1.Matches(-1)); |
982 | } |
983 | |
984 | // Tests that Ge(v) describes itself properly. |
985 | TEST(GeTest, CanDescribeSelf) { |
986 | Matcher<int> m = Ge(5); |
987 | EXPECT_EQ("is >= 5" , Describe(m)); |
988 | } |
989 | |
990 | // Tests that Gt(v) matches anything > v. |
991 | TEST(GtTest, ImplementsGreaterThan) { |
992 | Matcher<double> m1 = Gt(0); |
993 | EXPECT_TRUE(m1.Matches(1.0)); |
994 | EXPECT_FALSE(m1.Matches(0.0)); |
995 | EXPECT_FALSE(m1.Matches(-1.0)); |
996 | } |
997 | |
998 | // Tests that Gt(v) describes itself properly. |
999 | TEST(GtTest, CanDescribeSelf) { |
1000 | Matcher<int> m = Gt(5); |
1001 | EXPECT_EQ("is > 5" , Describe(m)); |
1002 | } |
1003 | |
1004 | // Tests that Le(v) matches anything <= v. |
1005 | TEST(LeTest, ImplementsLessThanOrEqual) { |
1006 | Matcher<char> m1 = Le('b'); |
1007 | EXPECT_TRUE(m1.Matches('a')); |
1008 | EXPECT_TRUE(m1.Matches('b')); |
1009 | EXPECT_FALSE(m1.Matches('c')); |
1010 | } |
1011 | |
1012 | // Tests that Le(v) describes itself properly. |
1013 | TEST(LeTest, CanDescribeSelf) { |
1014 | Matcher<int> m = Le(5); |
1015 | EXPECT_EQ("is <= 5" , Describe(m)); |
1016 | } |
1017 | |
1018 | // Tests that Lt(v) matches anything < v. |
1019 | TEST(LtTest, ImplementsLessThan) { |
1020 | Matcher<const std::string&> m1 = Lt("Hello" ); |
1021 | EXPECT_TRUE(m1.Matches("Abc" )); |
1022 | EXPECT_FALSE(m1.Matches("Hello" )); |
1023 | EXPECT_FALSE(m1.Matches("Hello, world!" )); |
1024 | } |
1025 | |
1026 | // Tests that Lt(v) describes itself properly. |
1027 | TEST(LtTest, CanDescribeSelf) { |
1028 | Matcher<int> m = Lt(5); |
1029 | EXPECT_EQ("is < 5" , Describe(m)); |
1030 | } |
1031 | |
1032 | // Tests that Ne(v) matches anything != v. |
1033 | TEST(NeTest, ImplementsNotEqual) { |
1034 | Matcher<int> m1 = Ne(0); |
1035 | EXPECT_TRUE(m1.Matches(1)); |
1036 | EXPECT_TRUE(m1.Matches(-1)); |
1037 | EXPECT_FALSE(m1.Matches(0)); |
1038 | } |
1039 | |
1040 | // Tests that Ne(v) describes itself properly. |
1041 | TEST(NeTest, CanDescribeSelf) { |
1042 | Matcher<int> m = Ne(5); |
1043 | EXPECT_EQ("isn't equal to 5" , Describe(m)); |
1044 | } |
1045 | |
1046 | class MoveOnly { |
1047 | public: |
1048 | explicit MoveOnly(int i) : i_(i) {} |
1049 | MoveOnly(const MoveOnly&) = delete; |
1050 | MoveOnly(MoveOnly&&) = default; |
1051 | MoveOnly& operator=(const MoveOnly&) = delete; |
1052 | MoveOnly& operator=(MoveOnly&&) = default; |
1053 | |
1054 | bool operator==(const MoveOnly& other) const { return i_ == other.i_; } |
1055 | bool operator!=(const MoveOnly& other) const { return i_ != other.i_; } |
1056 | bool operator<(const MoveOnly& other) const { return i_ < other.i_; } |
1057 | bool operator<=(const MoveOnly& other) const { return i_ <= other.i_; } |
1058 | bool operator>(const MoveOnly& other) const { return i_ > other.i_; } |
1059 | bool operator>=(const MoveOnly& other) const { return i_ >= other.i_; } |
1060 | |
1061 | private: |
1062 | int i_; |
1063 | }; |
1064 | |
1065 | struct MoveHelper { |
1066 | MOCK_METHOD1(Call, void(MoveOnly)); |
1067 | }; |
1068 | |
1069 | TEST(ComparisonBaseTest, WorksWithMoveOnly) { |
1070 | MoveOnly m{0}; |
1071 | MoveHelper helper; |
1072 | |
1073 | EXPECT_CALL(helper, Call(Eq(ByRef(m)))); |
1074 | helper.Call(MoveOnly(0)); |
1075 | EXPECT_CALL(helper, Call(Ne(ByRef(m)))); |
1076 | helper.Call(MoveOnly(1)); |
1077 | EXPECT_CALL(helper, Call(Le(ByRef(m)))); |
1078 | helper.Call(MoveOnly(0)); |
1079 | EXPECT_CALL(helper, Call(Lt(ByRef(m)))); |
1080 | helper.Call(MoveOnly(-1)); |
1081 | EXPECT_CALL(helper, Call(Ge(ByRef(m)))); |
1082 | helper.Call(MoveOnly(0)); |
1083 | EXPECT_CALL(helper, Call(Gt(ByRef(m)))); |
1084 | helper.Call(MoveOnly(1)); |
1085 | } |
1086 | |
1087 | // Tests that IsNull() matches any NULL pointer of any type. |
1088 | TEST(IsNullTest, MatchesNullPointer) { |
1089 | Matcher<int*> m1 = IsNull(); |
1090 | int* p1 = nullptr; |
1091 | int n = 0; |
1092 | EXPECT_TRUE(m1.Matches(p1)); |
1093 | EXPECT_FALSE(m1.Matches(&n)); |
1094 | |
1095 | Matcher<const char*> m2 = IsNull(); |
1096 | const char* p2 = nullptr; |
1097 | EXPECT_TRUE(m2.Matches(p2)); |
1098 | EXPECT_FALSE(m2.Matches("hi" )); |
1099 | |
1100 | Matcher<void*> m3 = IsNull(); |
1101 | void* p3 = nullptr; |
1102 | EXPECT_TRUE(m3.Matches(p3)); |
1103 | EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef))); |
1104 | } |
1105 | |
1106 | TEST(IsNullTest, StdFunction) { |
1107 | const Matcher<std::function<void()>> m = IsNull(); |
1108 | |
1109 | EXPECT_TRUE(m.Matches(std::function<void()>())); |
1110 | EXPECT_FALSE(m.Matches([]{})); |
1111 | } |
1112 | |
1113 | // Tests that IsNull() describes itself properly. |
1114 | TEST(IsNullTest, CanDescribeSelf) { |
1115 | Matcher<int*> m = IsNull(); |
1116 | EXPECT_EQ("is NULL" , Describe(m)); |
1117 | EXPECT_EQ("isn't NULL" , DescribeNegation(m)); |
1118 | } |
1119 | |
1120 | // Tests that NotNull() matches any non-NULL pointer of any type. |
1121 | TEST(NotNullTest, MatchesNonNullPointer) { |
1122 | Matcher<int*> m1 = NotNull(); |
1123 | int* p1 = nullptr; |
1124 | int n = 0; |
1125 | EXPECT_FALSE(m1.Matches(p1)); |
1126 | EXPECT_TRUE(m1.Matches(&n)); |
1127 | |
1128 | Matcher<const char*> m2 = NotNull(); |
1129 | const char* p2 = nullptr; |
1130 | EXPECT_FALSE(m2.Matches(p2)); |
1131 | EXPECT_TRUE(m2.Matches("hi" )); |
1132 | } |
1133 | |
1134 | TEST(NotNullTest, LinkedPtr) { |
1135 | const Matcher<std::shared_ptr<int>> m = NotNull(); |
1136 | const std::shared_ptr<int> null_p; |
1137 | const std::shared_ptr<int> non_null_p(new int); |
1138 | |
1139 | EXPECT_FALSE(m.Matches(null_p)); |
1140 | EXPECT_TRUE(m.Matches(non_null_p)); |
1141 | } |
1142 | |
1143 | TEST(NotNullTest, ReferenceToConstLinkedPtr) { |
1144 | const Matcher<const std::shared_ptr<double>&> m = NotNull(); |
1145 | const std::shared_ptr<double> null_p; |
1146 | const std::shared_ptr<double> non_null_p(new double); |
1147 | |
1148 | EXPECT_FALSE(m.Matches(null_p)); |
1149 | EXPECT_TRUE(m.Matches(non_null_p)); |
1150 | } |
1151 | |
1152 | TEST(NotNullTest, StdFunction) { |
1153 | const Matcher<std::function<void()>> m = NotNull(); |
1154 | |
1155 | EXPECT_TRUE(m.Matches([]{})); |
1156 | EXPECT_FALSE(m.Matches(std::function<void()>())); |
1157 | } |
1158 | |
1159 | // Tests that NotNull() describes itself properly. |
1160 | TEST(NotNullTest, CanDescribeSelf) { |
1161 | Matcher<int*> m = NotNull(); |
1162 | EXPECT_EQ("isn't NULL" , Describe(m)); |
1163 | } |
1164 | |
1165 | // Tests that Ref(variable) matches an argument that references |
1166 | // 'variable'. |
1167 | TEST(RefTest, MatchesSameVariable) { |
1168 | int a = 0; |
1169 | int b = 0; |
1170 | Matcher<int&> m = Ref(a); |
1171 | EXPECT_TRUE(m.Matches(a)); |
1172 | EXPECT_FALSE(m.Matches(b)); |
1173 | } |
1174 | |
1175 | // Tests that Ref(variable) describes itself properly. |
1176 | TEST(RefTest, CanDescribeSelf) { |
1177 | int n = 5; |
1178 | Matcher<int&> m = Ref(n); |
1179 | stringstream ss; |
1180 | ss << "references the variable @" << &n << " 5" ; |
1181 | EXPECT_EQ(ss.str(), Describe(m)); |
1182 | } |
1183 | |
1184 | // Test that Ref(non_const_varialbe) can be used as a matcher for a |
1185 | // const reference. |
1186 | TEST(RefTest, CanBeUsedAsMatcherForConstReference) { |
1187 | int a = 0; |
1188 | int b = 0; |
1189 | Matcher<const int&> m = Ref(a); |
1190 | EXPECT_TRUE(m.Matches(a)); |
1191 | EXPECT_FALSE(m.Matches(b)); |
1192 | } |
1193 | |
1194 | // Tests that Ref(variable) is covariant, i.e. Ref(derived) can be |
1195 | // used wherever Ref(base) can be used (Ref(derived) is a sub-type |
1196 | // of Ref(base), but not vice versa. |
1197 | |
1198 | TEST(RefTest, IsCovariant) { |
1199 | Base base, base2; |
1200 | Derived derived; |
1201 | Matcher<const Base&> m1 = Ref(base); |
1202 | EXPECT_TRUE(m1.Matches(base)); |
1203 | EXPECT_FALSE(m1.Matches(base2)); |
1204 | EXPECT_FALSE(m1.Matches(derived)); |
1205 | |
1206 | m1 = Ref(derived); |
1207 | EXPECT_TRUE(m1.Matches(derived)); |
1208 | EXPECT_FALSE(m1.Matches(base)); |
1209 | EXPECT_FALSE(m1.Matches(base2)); |
1210 | } |
1211 | |
1212 | TEST(RefTest, ExplainsResult) { |
1213 | int n = 0; |
1214 | EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n), |
1215 | StartsWith("which is located @" )); |
1216 | |
1217 | int m = 0; |
1218 | EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m), |
1219 | StartsWith("which is located @" )); |
1220 | } |
1221 | |
1222 | // Tests string comparison matchers. |
1223 | |
1224 | TEST(StrEqTest, MatchesEqualString) { |
1225 | Matcher<const char*> m = StrEq(std::string("Hello" )); |
1226 | EXPECT_TRUE(m.Matches("Hello" )); |
1227 | EXPECT_FALSE(m.Matches("hello" )); |
1228 | EXPECT_FALSE(m.Matches(nullptr)); |
1229 | |
1230 | Matcher<const std::string&> m2 = StrEq("Hello" ); |
1231 | EXPECT_TRUE(m2.Matches("Hello" )); |
1232 | EXPECT_FALSE(m2.Matches("Hi" )); |
1233 | |
1234 | #if GTEST_HAS_ABSL |
1235 | Matcher<const absl::string_view&> m3 = StrEq("Hello" ); |
1236 | EXPECT_TRUE(m3.Matches(absl::string_view("Hello" ))); |
1237 | EXPECT_FALSE(m3.Matches(absl::string_view("hello" ))); |
1238 | EXPECT_FALSE(m3.Matches(absl::string_view())); |
1239 | |
1240 | Matcher<const absl::string_view&> m_empty = StrEq("" ); |
1241 | EXPECT_TRUE(m_empty.Matches(absl::string_view("" ))); |
1242 | EXPECT_TRUE(m_empty.Matches(absl::string_view())); |
1243 | EXPECT_FALSE(m_empty.Matches(absl::string_view("hello" ))); |
1244 | #endif // GTEST_HAS_ABSL |
1245 | } |
1246 | |
1247 | TEST(StrEqTest, CanDescribeSelf) { |
1248 | Matcher<std::string> m = StrEq("Hi-\'\"?\\\a\b\f\n\r\t\v\xD3" ); |
1249 | EXPECT_EQ("is equal to \"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\"" , |
1250 | Describe(m)); |
1251 | |
1252 | std::string str("01204500800" ); |
1253 | str[3] = '\0'; |
1254 | Matcher<std::string> m2 = StrEq(str); |
1255 | EXPECT_EQ("is equal to \"012\\04500800\"" , Describe(m2)); |
1256 | str[0] = str[6] = str[7] = str[9] = str[10] = '\0'; |
1257 | Matcher<std::string> m3 = StrEq(str); |
1258 | EXPECT_EQ("is equal to \"\\012\\045\\0\\08\\0\\0\"" , Describe(m3)); |
1259 | } |
1260 | |
1261 | TEST(StrNeTest, MatchesUnequalString) { |
1262 | Matcher<const char*> m = StrNe("Hello" ); |
1263 | EXPECT_TRUE(m.Matches("" )); |
1264 | EXPECT_TRUE(m.Matches(nullptr)); |
1265 | EXPECT_FALSE(m.Matches("Hello" )); |
1266 | |
1267 | Matcher<std::string> m2 = StrNe(std::string("Hello" )); |
1268 | EXPECT_TRUE(m2.Matches("hello" )); |
1269 | EXPECT_FALSE(m2.Matches("Hello" )); |
1270 | |
1271 | #if GTEST_HAS_ABSL |
1272 | Matcher<const absl::string_view> m3 = StrNe("Hello" ); |
1273 | EXPECT_TRUE(m3.Matches(absl::string_view("" ))); |
1274 | EXPECT_TRUE(m3.Matches(absl::string_view())); |
1275 | EXPECT_FALSE(m3.Matches(absl::string_view("Hello" ))); |
1276 | #endif // GTEST_HAS_ABSL |
1277 | } |
1278 | |
1279 | TEST(StrNeTest, CanDescribeSelf) { |
1280 | Matcher<const char*> m = StrNe("Hi" ); |
1281 | EXPECT_EQ("isn't equal to \"Hi\"" , Describe(m)); |
1282 | } |
1283 | |
1284 | TEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) { |
1285 | Matcher<const char*> m = StrCaseEq(std::string("Hello" )); |
1286 | EXPECT_TRUE(m.Matches("Hello" )); |
1287 | EXPECT_TRUE(m.Matches("hello" )); |
1288 | EXPECT_FALSE(m.Matches("Hi" )); |
1289 | EXPECT_FALSE(m.Matches(nullptr)); |
1290 | |
1291 | Matcher<const std::string&> m2 = StrCaseEq("Hello" ); |
1292 | EXPECT_TRUE(m2.Matches("hello" )); |
1293 | EXPECT_FALSE(m2.Matches("Hi" )); |
1294 | |
1295 | #if GTEST_HAS_ABSL |
1296 | Matcher<const absl::string_view&> m3 = StrCaseEq(std::string("Hello" )); |
1297 | EXPECT_TRUE(m3.Matches(absl::string_view("Hello" ))); |
1298 | EXPECT_TRUE(m3.Matches(absl::string_view("hello" ))); |
1299 | EXPECT_FALSE(m3.Matches(absl::string_view("Hi" ))); |
1300 | EXPECT_FALSE(m3.Matches(absl::string_view())); |
1301 | #endif // GTEST_HAS_ABSL |
1302 | } |
1303 | |
1304 | TEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) { |
1305 | std::string str1("oabocdooeoo" ); |
1306 | std::string str2("OABOCDOOEOO" ); |
1307 | Matcher<const std::string&> m0 = StrCaseEq(str1); |
1308 | EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\0'))); |
1309 | |
1310 | str1[3] = str2[3] = '\0'; |
1311 | Matcher<const std::string&> m1 = StrCaseEq(str1); |
1312 | EXPECT_TRUE(m1.Matches(str2)); |
1313 | |
1314 | str1[0] = str1[6] = str1[7] = str1[10] = '\0'; |
1315 | str2[0] = str2[6] = str2[7] = str2[10] = '\0'; |
1316 | Matcher<const std::string&> m2 = StrCaseEq(str1); |
1317 | str1[9] = str2[9] = '\0'; |
1318 | EXPECT_FALSE(m2.Matches(str2)); |
1319 | |
1320 | Matcher<const std::string&> m3 = StrCaseEq(str1); |
1321 | EXPECT_TRUE(m3.Matches(str2)); |
1322 | |
1323 | EXPECT_FALSE(m3.Matches(str2 + "x" )); |
1324 | str2.append(1, '\0'); |
1325 | EXPECT_FALSE(m3.Matches(str2)); |
1326 | EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9))); |
1327 | } |
1328 | |
1329 | TEST(StrCaseEqTest, CanDescribeSelf) { |
1330 | Matcher<std::string> m = StrCaseEq("Hi" ); |
1331 | EXPECT_EQ("is equal to (ignoring case) \"Hi\"" , Describe(m)); |
1332 | } |
1333 | |
1334 | TEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) { |
1335 | Matcher<const char*> m = StrCaseNe("Hello" ); |
1336 | EXPECT_TRUE(m.Matches("Hi" )); |
1337 | EXPECT_TRUE(m.Matches(nullptr)); |
1338 | EXPECT_FALSE(m.Matches("Hello" )); |
1339 | EXPECT_FALSE(m.Matches("hello" )); |
1340 | |
1341 | Matcher<std::string> m2 = StrCaseNe(std::string("Hello" )); |
1342 | EXPECT_TRUE(m2.Matches("" )); |
1343 | EXPECT_FALSE(m2.Matches("Hello" )); |
1344 | |
1345 | #if GTEST_HAS_ABSL |
1346 | Matcher<const absl::string_view> m3 = StrCaseNe("Hello" ); |
1347 | EXPECT_TRUE(m3.Matches(absl::string_view("Hi" ))); |
1348 | EXPECT_TRUE(m3.Matches(absl::string_view())); |
1349 | EXPECT_FALSE(m3.Matches(absl::string_view("Hello" ))); |
1350 | EXPECT_FALSE(m3.Matches(absl::string_view("hello" ))); |
1351 | #endif // GTEST_HAS_ABSL |
1352 | } |
1353 | |
1354 | TEST(StrCaseNeTest, CanDescribeSelf) { |
1355 | Matcher<const char*> m = StrCaseNe("Hi" ); |
1356 | EXPECT_EQ("isn't equal to (ignoring case) \"Hi\"" , Describe(m)); |
1357 | } |
1358 | |
1359 | // Tests that HasSubstr() works for matching string-typed values. |
1360 | TEST(HasSubstrTest, WorksForStringClasses) { |
1361 | const Matcher<std::string> m1 = HasSubstr("foo" ); |
1362 | EXPECT_TRUE(m1.Matches(std::string("I love food." ))); |
1363 | EXPECT_FALSE(m1.Matches(std::string("tofo" ))); |
1364 | |
1365 | const Matcher<const std::string&> m2 = HasSubstr("foo" ); |
1366 | EXPECT_TRUE(m2.Matches(std::string("I love food." ))); |
1367 | EXPECT_FALSE(m2.Matches(std::string("tofo" ))); |
1368 | |
1369 | const Matcher<std::string> m_empty = HasSubstr("" ); |
1370 | EXPECT_TRUE(m_empty.Matches(std::string())); |
1371 | EXPECT_TRUE(m_empty.Matches(std::string("not empty" ))); |
1372 | } |
1373 | |
1374 | // Tests that HasSubstr() works for matching C-string-typed values. |
1375 | TEST(HasSubstrTest, WorksForCStrings) { |
1376 | const Matcher<char*> m1 = HasSubstr("foo" ); |
1377 | EXPECT_TRUE(m1.Matches(const_cast<char*>("I love food." ))); |
1378 | EXPECT_FALSE(m1.Matches(const_cast<char*>("tofo" ))); |
1379 | EXPECT_FALSE(m1.Matches(nullptr)); |
1380 | |
1381 | const Matcher<const char*> m2 = HasSubstr("foo" ); |
1382 | EXPECT_TRUE(m2.Matches("I love food." )); |
1383 | EXPECT_FALSE(m2.Matches("tofo" )); |
1384 | EXPECT_FALSE(m2.Matches(nullptr)); |
1385 | |
1386 | const Matcher<const char*> m_empty = HasSubstr("" ); |
1387 | EXPECT_TRUE(m_empty.Matches("not empty" )); |
1388 | EXPECT_TRUE(m_empty.Matches("" )); |
1389 | EXPECT_FALSE(m_empty.Matches(nullptr)); |
1390 | } |
1391 | |
1392 | #if GTEST_HAS_ABSL |
1393 | // Tests that HasSubstr() works for matching absl::string_view-typed values. |
1394 | TEST(HasSubstrTest, WorksForStringViewClasses) { |
1395 | const Matcher<absl::string_view> m1 = HasSubstr("foo" ); |
1396 | EXPECT_TRUE(m1.Matches(absl::string_view("I love food." ))); |
1397 | EXPECT_FALSE(m1.Matches(absl::string_view("tofo" ))); |
1398 | EXPECT_FALSE(m1.Matches(absl::string_view())); |
1399 | |
1400 | const Matcher<const absl::string_view&> m2 = HasSubstr("foo" ); |
1401 | EXPECT_TRUE(m2.Matches(absl::string_view("I love food." ))); |
1402 | EXPECT_FALSE(m2.Matches(absl::string_view("tofo" ))); |
1403 | EXPECT_FALSE(m2.Matches(absl::string_view())); |
1404 | |
1405 | const Matcher<const absl::string_view&> m3 = HasSubstr("" ); |
1406 | EXPECT_TRUE(m3.Matches(absl::string_view("foo" ))); |
1407 | EXPECT_TRUE(m3.Matches(absl::string_view("" ))); |
1408 | EXPECT_TRUE(m3.Matches(absl::string_view())); |
1409 | } |
1410 | #endif // GTEST_HAS_ABSL |
1411 | |
1412 | // Tests that HasSubstr(s) describes itself properly. |
1413 | TEST(HasSubstrTest, CanDescribeSelf) { |
1414 | Matcher<std::string> m = HasSubstr("foo\n\"" ); |
1415 | EXPECT_EQ("has substring \"foo\\n\\\"\"" , Describe(m)); |
1416 | } |
1417 | |
1418 | TEST(KeyTest, CanDescribeSelf) { |
1419 | Matcher<const pair<std::string, int>&> m = Key("foo" ); |
1420 | EXPECT_EQ("has a key that is equal to \"foo\"" , Describe(m)); |
1421 | EXPECT_EQ("doesn't have a key that is equal to \"foo\"" , DescribeNegation(m)); |
1422 | } |
1423 | |
1424 | TEST(KeyTest, ExplainsResult) { |
1425 | Matcher<pair<int, bool> > m = Key(GreaterThan(10)); |
1426 | EXPECT_EQ("whose first field is a value which is 5 less than 10" , |
1427 | Explain(m, make_pair(5, true))); |
1428 | EXPECT_EQ("whose first field is a value which is 5 more than 10" , |
1429 | Explain(m, make_pair(15, true))); |
1430 | } |
1431 | |
1432 | TEST(KeyTest, MatchesCorrectly) { |
1433 | pair<int, std::string> p(25, "foo" ); |
1434 | EXPECT_THAT(p, Key(25)); |
1435 | EXPECT_THAT(p, Not(Key(42))); |
1436 | EXPECT_THAT(p, Key(Ge(20))); |
1437 | EXPECT_THAT(p, Not(Key(Lt(25)))); |
1438 | } |
1439 | |
1440 | TEST(KeyTest, WorksWithMoveOnly) { |
1441 | pair<std::unique_ptr<int>, std::unique_ptr<int>> p; |
1442 | EXPECT_THAT(p, Key(Eq(nullptr))); |
1443 | } |
1444 | |
1445 | template <size_t I> |
1446 | struct Tag {}; |
1447 | |
1448 | struct PairWithGet { |
1449 | int member_1; |
1450 | std::string member_2; |
1451 | using first_type = int; |
1452 | using second_type = std::string; |
1453 | |
1454 | const int& GetImpl(Tag<0>) const { return member_1; } |
1455 | const std::string& GetImpl(Tag<1>) const { return member_2; } |
1456 | }; |
1457 | template <size_t I> |
1458 | auto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag<I>())) { |
1459 | return value.GetImpl(Tag<I>()); |
1460 | } |
1461 | TEST(PairTest, MatchesPairWithGetCorrectly) { |
1462 | PairWithGet p{25, "foo" }; |
1463 | EXPECT_THAT(p, Key(25)); |
1464 | EXPECT_THAT(p, Not(Key(42))); |
1465 | EXPECT_THAT(p, Key(Ge(20))); |
1466 | EXPECT_THAT(p, Not(Key(Lt(25)))); |
1467 | |
1468 | std::vector<PairWithGet> v = {{11, "Foo" }, {29, "gMockIsBestMock" }}; |
1469 | EXPECT_THAT(v, Contains(Key(29))); |
1470 | } |
1471 | |
1472 | TEST(KeyTest, SafelyCastsInnerMatcher) { |
1473 | Matcher<int> is_positive = Gt(0); |
1474 | Matcher<int> is_negative = Lt(0); |
1475 | pair<char, bool> p('a', true); |
1476 | EXPECT_THAT(p, Key(is_positive)); |
1477 | EXPECT_THAT(p, Not(Key(is_negative))); |
1478 | } |
1479 | |
1480 | TEST(KeyTest, InsideContainsUsingMap) { |
1481 | map<int, char> container; |
1482 | container.insert(make_pair(1, 'a')); |
1483 | container.insert(make_pair(2, 'b')); |
1484 | container.insert(make_pair(4, 'c')); |
1485 | EXPECT_THAT(container, Contains(Key(1))); |
1486 | EXPECT_THAT(container, Not(Contains(Key(3)))); |
1487 | } |
1488 | |
1489 | TEST(KeyTest, InsideContainsUsingMultimap) { |
1490 | multimap<int, char> container; |
1491 | container.insert(make_pair(1, 'a')); |
1492 | container.insert(make_pair(2, 'b')); |
1493 | container.insert(make_pair(4, 'c')); |
1494 | |
1495 | EXPECT_THAT(container, Not(Contains(Key(25)))); |
1496 | container.insert(make_pair(25, 'd')); |
1497 | EXPECT_THAT(container, Contains(Key(25))); |
1498 | container.insert(make_pair(25, 'e')); |
1499 | EXPECT_THAT(container, Contains(Key(25))); |
1500 | |
1501 | EXPECT_THAT(container, Contains(Key(1))); |
1502 | EXPECT_THAT(container, Not(Contains(Key(3)))); |
1503 | } |
1504 | |
1505 | TEST(PairTest, Typing) { |
1506 | // Test verifies the following type conversions can be compiled. |
1507 | Matcher<const pair<const char*, int>&> m1 = Pair("foo" , 42); |
1508 | Matcher<const pair<const char*, int> > m2 = Pair("foo" , 42); |
1509 | Matcher<pair<const char*, int> > m3 = Pair("foo" , 42); |
1510 | |
1511 | Matcher<pair<int, const std::string> > m4 = Pair(25, "42" ); |
1512 | Matcher<pair<const std::string, int> > m5 = Pair("25" , 42); |
1513 | } |
1514 | |
1515 | TEST(PairTest, CanDescribeSelf) { |
1516 | Matcher<const pair<std::string, int>&> m1 = Pair("foo" , 42); |
1517 | EXPECT_EQ("has a first field that is equal to \"foo\"" |
1518 | ", and has a second field that is equal to 42" , |
1519 | Describe(m1)); |
1520 | EXPECT_EQ("has a first field that isn't equal to \"foo\"" |
1521 | ", or has a second field that isn't equal to 42" , |
1522 | DescribeNegation(m1)); |
1523 | // Double and triple negation (1 or 2 times not and description of negation). |
1524 | Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42)); |
1525 | EXPECT_EQ("has a first field that isn't equal to 13" |
1526 | ", and has a second field that is equal to 42" , |
1527 | DescribeNegation(m2)); |
1528 | } |
1529 | |
1530 | TEST(PairTest, CanExplainMatchResultTo) { |
1531 | // If neither field matches, Pair() should explain about the first |
1532 | // field. |
1533 | const Matcher<pair<int, int> > m = Pair(GreaterThan(0), GreaterThan(0)); |
1534 | EXPECT_EQ("whose first field does not match, which is 1 less than 0" , |
1535 | Explain(m, make_pair(-1, -2))); |
1536 | |
1537 | // If the first field matches but the second doesn't, Pair() should |
1538 | // explain about the second field. |
1539 | EXPECT_EQ("whose second field does not match, which is 2 less than 0" , |
1540 | Explain(m, make_pair(1, -2))); |
1541 | |
1542 | // If the first field doesn't match but the second does, Pair() |
1543 | // should explain about the first field. |
1544 | EXPECT_EQ("whose first field does not match, which is 1 less than 0" , |
1545 | Explain(m, make_pair(-1, 2))); |
1546 | |
1547 | // If both fields match, Pair() should explain about them both. |
1548 | EXPECT_EQ("whose both fields match, where the first field is a value " |
1549 | "which is 1 more than 0, and the second field is a value " |
1550 | "which is 2 more than 0" , |
1551 | Explain(m, make_pair(1, 2))); |
1552 | |
1553 | // If only the first match has an explanation, only this explanation should |
1554 | // be printed. |
1555 | const Matcher<pair<int, int> > explain_first = Pair(GreaterThan(0), 0); |
1556 | EXPECT_EQ("whose both fields match, where the first field is a value " |
1557 | "which is 1 more than 0" , |
1558 | Explain(explain_first, make_pair(1, 0))); |
1559 | |
1560 | // If only the second match has an explanation, only this explanation should |
1561 | // be printed. |
1562 | const Matcher<pair<int, int> > explain_second = Pair(0, GreaterThan(0)); |
1563 | EXPECT_EQ("whose both fields match, where the second field is a value " |
1564 | "which is 1 more than 0" , |
1565 | Explain(explain_second, make_pair(0, 1))); |
1566 | } |
1567 | |
1568 | TEST(PairTest, MatchesCorrectly) { |
1569 | pair<int, std::string> p(25, "foo" ); |
1570 | |
1571 | // Both fields match. |
1572 | EXPECT_THAT(p, Pair(25, "foo" )); |
1573 | EXPECT_THAT(p, Pair(Ge(20), HasSubstr("o" ))); |
1574 | |
1575 | // 'first' doesnt' match, but 'second' matches. |
1576 | EXPECT_THAT(p, Not(Pair(42, "foo" ))); |
1577 | EXPECT_THAT(p, Not(Pair(Lt(25), "foo" ))); |
1578 | |
1579 | // 'first' matches, but 'second' doesn't match. |
1580 | EXPECT_THAT(p, Not(Pair(25, "bar" ))); |
1581 | EXPECT_THAT(p, Not(Pair(25, Not("foo" )))); |
1582 | |
1583 | // Neither field matches. |
1584 | EXPECT_THAT(p, Not(Pair(13, "bar" ))); |
1585 | EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr("a" )))); |
1586 | } |
1587 | |
1588 | TEST(PairTest, WorksWithMoveOnly) { |
1589 | pair<std::unique_ptr<int>, std::unique_ptr<int>> p; |
1590 | p.second.reset(new int(7)); |
1591 | EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr))); |
1592 | } |
1593 | |
1594 | TEST(PairTest, SafelyCastsInnerMatchers) { |
1595 | Matcher<int> is_positive = Gt(0); |
1596 | Matcher<int> is_negative = Lt(0); |
1597 | pair<char, bool> p('a', true); |
1598 | EXPECT_THAT(p, Pair(is_positive, _)); |
1599 | EXPECT_THAT(p, Not(Pair(is_negative, _))); |
1600 | EXPECT_THAT(p, Pair(_, is_positive)); |
1601 | EXPECT_THAT(p, Not(Pair(_, is_negative))); |
1602 | } |
1603 | |
1604 | TEST(PairTest, InsideContainsUsingMap) { |
1605 | map<int, char> container; |
1606 | container.insert(make_pair(1, 'a')); |
1607 | container.insert(make_pair(2, 'b')); |
1608 | container.insert(make_pair(4, 'c')); |
1609 | EXPECT_THAT(container, Contains(Pair(1, 'a'))); |
1610 | EXPECT_THAT(container, Contains(Pair(1, _))); |
1611 | EXPECT_THAT(container, Contains(Pair(_, 'a'))); |
1612 | EXPECT_THAT(container, Not(Contains(Pair(3, _)))); |
1613 | } |
1614 | |
1615 | TEST(ContainsTest, WorksWithMoveOnly) { |
1616 | ContainerHelper helper; |
1617 | EXPECT_CALL(helper, Call(Contains(Pointee(2)))); |
1618 | helper.Call(MakeUniquePtrs({1, 2})); |
1619 | } |
1620 | |
1621 | TEST(PairTest, UseGetInsteadOfMembers) { |
1622 | PairWithGet pair{7, "ABC" }; |
1623 | EXPECT_THAT(pair, Pair(7, "ABC" )); |
1624 | EXPECT_THAT(pair, Pair(Ge(7), HasSubstr("AB" ))); |
1625 | EXPECT_THAT(pair, Not(Pair(Lt(7), "ABC" ))); |
1626 | |
1627 | std::vector<PairWithGet> v = {{11, "Foo" }, {29, "gMockIsBestMock" }}; |
1628 | EXPECT_THAT(v, |
1629 | ElementsAre(Pair(11, std::string("Foo" )), Pair(Ge(10), Not("" )))); |
1630 | } |
1631 | |
1632 | // Tests StartsWith(s). |
1633 | |
1634 | TEST(StartsWithTest, MatchesStringWithGivenPrefix) { |
1635 | const Matcher<const char*> m1 = StartsWith(std::string("" )); |
1636 | EXPECT_TRUE(m1.Matches("Hi" )); |
1637 | EXPECT_TRUE(m1.Matches("" )); |
1638 | EXPECT_FALSE(m1.Matches(nullptr)); |
1639 | |
1640 | const Matcher<const std::string&> m2 = StartsWith("Hi" ); |
1641 | EXPECT_TRUE(m2.Matches("Hi" )); |
1642 | EXPECT_TRUE(m2.Matches("Hi Hi!" )); |
1643 | EXPECT_TRUE(m2.Matches("High" )); |
1644 | EXPECT_FALSE(m2.Matches("H" )); |
1645 | EXPECT_FALSE(m2.Matches(" Hi" )); |
1646 | |
1647 | #if GTEST_HAS_ABSL |
1648 | const Matcher<absl::string_view> m_empty = StartsWith("" ); |
1649 | EXPECT_TRUE(m_empty.Matches(absl::string_view())); |
1650 | EXPECT_TRUE(m_empty.Matches(absl::string_view("" ))); |
1651 | EXPECT_TRUE(m_empty.Matches(absl::string_view("not empty" ))); |
1652 | #endif // GTEST_HAS_ABSL |
1653 | } |
1654 | |
1655 | TEST(StartsWithTest, CanDescribeSelf) { |
1656 | Matcher<const std::string> m = StartsWith("Hi" ); |
1657 | EXPECT_EQ("starts with \"Hi\"" , Describe(m)); |
1658 | } |
1659 | |
1660 | // Tests EndsWith(s). |
1661 | |
1662 | TEST(EndsWithTest, MatchesStringWithGivenSuffix) { |
1663 | const Matcher<const char*> m1 = EndsWith("" ); |
1664 | EXPECT_TRUE(m1.Matches("Hi" )); |
1665 | EXPECT_TRUE(m1.Matches("" )); |
1666 | EXPECT_FALSE(m1.Matches(nullptr)); |
1667 | |
1668 | const Matcher<const std::string&> m2 = EndsWith(std::string("Hi" )); |
1669 | EXPECT_TRUE(m2.Matches("Hi" )); |
1670 | EXPECT_TRUE(m2.Matches("Wow Hi Hi" )); |
1671 | EXPECT_TRUE(m2.Matches("Super Hi" )); |
1672 | EXPECT_FALSE(m2.Matches("i" )); |
1673 | EXPECT_FALSE(m2.Matches("Hi " )); |
1674 | |
1675 | #if GTEST_HAS_ABSL |
1676 | const Matcher<const absl::string_view&> m4 = EndsWith("" ); |
1677 | EXPECT_TRUE(m4.Matches("Hi" )); |
1678 | EXPECT_TRUE(m4.Matches("" )); |
1679 | EXPECT_TRUE(m4.Matches(absl::string_view())); |
1680 | EXPECT_TRUE(m4.Matches(absl::string_view("" ))); |
1681 | #endif // GTEST_HAS_ABSL |
1682 | } |
1683 | |
1684 | TEST(EndsWithTest, CanDescribeSelf) { |
1685 | Matcher<const std::string> m = EndsWith("Hi" ); |
1686 | EXPECT_EQ("ends with \"Hi\"" , Describe(m)); |
1687 | } |
1688 | |
1689 | // Tests MatchesRegex(). |
1690 | |
1691 | TEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) { |
1692 | const Matcher<const char*> m1 = MatchesRegex("a.*z" ); |
1693 | EXPECT_TRUE(m1.Matches("az" )); |
1694 | EXPECT_TRUE(m1.Matches("abcz" )); |
1695 | EXPECT_FALSE(m1.Matches(nullptr)); |
1696 | |
1697 | const Matcher<const std::string&> m2 = MatchesRegex(new RE("a.*z" )); |
1698 | EXPECT_TRUE(m2.Matches("azbz" )); |
1699 | EXPECT_FALSE(m2.Matches("az1" )); |
1700 | EXPECT_FALSE(m2.Matches("1az" )); |
1701 | |
1702 | #if GTEST_HAS_ABSL |
1703 | const Matcher<const absl::string_view&> m3 = MatchesRegex("a.*z" ); |
1704 | EXPECT_TRUE(m3.Matches(absl::string_view("az" ))); |
1705 | EXPECT_TRUE(m3.Matches(absl::string_view("abcz" ))); |
1706 | EXPECT_FALSE(m3.Matches(absl::string_view("1az" ))); |
1707 | EXPECT_FALSE(m3.Matches(absl::string_view())); |
1708 | const Matcher<const absl::string_view&> m4 = MatchesRegex("" ); |
1709 | EXPECT_TRUE(m4.Matches(absl::string_view("" ))); |
1710 | EXPECT_TRUE(m4.Matches(absl::string_view())); |
1711 | #endif // GTEST_HAS_ABSL |
1712 | } |
1713 | |
1714 | TEST(MatchesRegexTest, CanDescribeSelf) { |
1715 | Matcher<const std::string> m1 = MatchesRegex(std::string("Hi.*" )); |
1716 | EXPECT_EQ("matches regular expression \"Hi.*\"" , Describe(m1)); |
1717 | |
1718 | Matcher<const char*> m2 = MatchesRegex(new RE("a.*" )); |
1719 | EXPECT_EQ("matches regular expression \"a.*\"" , Describe(m2)); |
1720 | |
1721 | #if GTEST_HAS_ABSL |
1722 | Matcher<const absl::string_view> m3 = MatchesRegex(new RE("0.*" )); |
1723 | EXPECT_EQ("matches regular expression \"0.*\"" , Describe(m3)); |
1724 | #endif // GTEST_HAS_ABSL |
1725 | } |
1726 | |
1727 | // Tests ContainsRegex(). |
1728 | |
1729 | TEST(ContainsRegexTest, MatchesStringContainingGivenRegex) { |
1730 | const Matcher<const char*> m1 = ContainsRegex(std::string("a.*z" )); |
1731 | EXPECT_TRUE(m1.Matches("az" )); |
1732 | EXPECT_TRUE(m1.Matches("0abcz1" )); |
1733 | EXPECT_FALSE(m1.Matches(nullptr)); |
1734 | |
1735 | const Matcher<const std::string&> m2 = ContainsRegex(new RE("a.*z" )); |
1736 | EXPECT_TRUE(m2.Matches("azbz" )); |
1737 | EXPECT_TRUE(m2.Matches("az1" )); |
1738 | EXPECT_FALSE(m2.Matches("1a" )); |
1739 | |
1740 | #if GTEST_HAS_ABSL |
1741 | const Matcher<const absl::string_view&> m3 = ContainsRegex(new RE("a.*z" )); |
1742 | EXPECT_TRUE(m3.Matches(absl::string_view("azbz" ))); |
1743 | EXPECT_TRUE(m3.Matches(absl::string_view("az1" ))); |
1744 | EXPECT_FALSE(m3.Matches(absl::string_view("1a" ))); |
1745 | EXPECT_FALSE(m3.Matches(absl::string_view())); |
1746 | const Matcher<const absl::string_view&> m4 = ContainsRegex("" ); |
1747 | EXPECT_TRUE(m4.Matches(absl::string_view("" ))); |
1748 | EXPECT_TRUE(m4.Matches(absl::string_view())); |
1749 | #endif // GTEST_HAS_ABSL |
1750 | } |
1751 | |
1752 | TEST(ContainsRegexTest, CanDescribeSelf) { |
1753 | Matcher<const std::string> m1 = ContainsRegex("Hi.*" ); |
1754 | EXPECT_EQ("contains regular expression \"Hi.*\"" , Describe(m1)); |
1755 | |
1756 | Matcher<const char*> m2 = ContainsRegex(new RE("a.*" )); |
1757 | EXPECT_EQ("contains regular expression \"a.*\"" , Describe(m2)); |
1758 | |
1759 | #if GTEST_HAS_ABSL |
1760 | Matcher<const absl::string_view> m3 = ContainsRegex(new RE("0.*" )); |
1761 | EXPECT_EQ("contains regular expression \"0.*\"" , Describe(m3)); |
1762 | #endif // GTEST_HAS_ABSL |
1763 | } |
1764 | |
1765 | // Tests for wide strings. |
1766 | #if GTEST_HAS_STD_WSTRING |
1767 | TEST(StdWideStrEqTest, MatchesEqual) { |
1768 | Matcher<const wchar_t*> m = StrEq(::std::wstring(L"Hello" )); |
1769 | EXPECT_TRUE(m.Matches(L"Hello" )); |
1770 | EXPECT_FALSE(m.Matches(L"hello" )); |
1771 | EXPECT_FALSE(m.Matches(nullptr)); |
1772 | |
1773 | Matcher<const ::std::wstring&> m2 = StrEq(L"Hello" ); |
1774 | EXPECT_TRUE(m2.Matches(L"Hello" )); |
1775 | EXPECT_FALSE(m2.Matches(L"Hi" )); |
1776 | |
1777 | Matcher<const ::std::wstring&> m3 = StrEq(L"\xD3\x576\x8D3\xC74D" ); |
1778 | EXPECT_TRUE(m3.Matches(L"\xD3\x576\x8D3\xC74D" )); |
1779 | EXPECT_FALSE(m3.Matches(L"\xD3\x576\x8D3\xC74E" )); |
1780 | |
1781 | ::std::wstring str(L"01204500800" ); |
1782 | str[3] = L'\0'; |
1783 | Matcher<const ::std::wstring&> m4 = StrEq(str); |
1784 | EXPECT_TRUE(m4.Matches(str)); |
1785 | str[0] = str[6] = str[7] = str[9] = str[10] = L'\0'; |
1786 | Matcher<const ::std::wstring&> m5 = StrEq(str); |
1787 | EXPECT_TRUE(m5.Matches(str)); |
1788 | } |
1789 | |
1790 | TEST(StdWideStrEqTest, CanDescribeSelf) { |
1791 | Matcher< ::std::wstring> m = StrEq(L"Hi-\'\"?\\\a\b\f\n\r\t\v" ); |
1792 | EXPECT_EQ("is equal to L\"Hi-\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\"" , |
1793 | Describe(m)); |
1794 | |
1795 | Matcher< ::std::wstring> m2 = StrEq(L"\xD3\x576\x8D3\xC74D" ); |
1796 | EXPECT_EQ("is equal to L\"\\xD3\\x576\\x8D3\\xC74D\"" , |
1797 | Describe(m2)); |
1798 | |
1799 | ::std::wstring str(L"01204500800" ); |
1800 | str[3] = L'\0'; |
1801 | Matcher<const ::std::wstring&> m4 = StrEq(str); |
1802 | EXPECT_EQ("is equal to L\"012\\04500800\"" , Describe(m4)); |
1803 | str[0] = str[6] = str[7] = str[9] = str[10] = L'\0'; |
1804 | Matcher<const ::std::wstring&> m5 = StrEq(str); |
1805 | EXPECT_EQ("is equal to L\"\\012\\045\\0\\08\\0\\0\"" , Describe(m5)); |
1806 | } |
1807 | |
1808 | TEST(StdWideStrNeTest, MatchesUnequalString) { |
1809 | Matcher<const wchar_t*> m = StrNe(L"Hello" ); |
1810 | EXPECT_TRUE(m.Matches(L"" )); |
1811 | EXPECT_TRUE(m.Matches(nullptr)); |
1812 | EXPECT_FALSE(m.Matches(L"Hello" )); |
1813 | |
1814 | Matcher< ::std::wstring> m2 = StrNe(::std::wstring(L"Hello" )); |
1815 | EXPECT_TRUE(m2.Matches(L"hello" )); |
1816 | EXPECT_FALSE(m2.Matches(L"Hello" )); |
1817 | } |
1818 | |
1819 | TEST(StdWideStrNeTest, CanDescribeSelf) { |
1820 | Matcher<const wchar_t*> m = StrNe(L"Hi" ); |
1821 | EXPECT_EQ("isn't equal to L\"Hi\"" , Describe(m)); |
1822 | } |
1823 | |
1824 | TEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) { |
1825 | Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L"Hello" )); |
1826 | EXPECT_TRUE(m.Matches(L"Hello" )); |
1827 | EXPECT_TRUE(m.Matches(L"hello" )); |
1828 | EXPECT_FALSE(m.Matches(L"Hi" )); |
1829 | EXPECT_FALSE(m.Matches(nullptr)); |
1830 | |
1831 | Matcher<const ::std::wstring&> m2 = StrCaseEq(L"Hello" ); |
1832 | EXPECT_TRUE(m2.Matches(L"hello" )); |
1833 | EXPECT_FALSE(m2.Matches(L"Hi" )); |
1834 | } |
1835 | |
1836 | TEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) { |
1837 | ::std::wstring str1(L"oabocdooeoo" ); |
1838 | ::std::wstring str2(L"OABOCDOOEOO" ); |
1839 | Matcher<const ::std::wstring&> m0 = StrCaseEq(str1); |
1840 | EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\0'))); |
1841 | |
1842 | str1[3] = str2[3] = L'\0'; |
1843 | Matcher<const ::std::wstring&> m1 = StrCaseEq(str1); |
1844 | EXPECT_TRUE(m1.Matches(str2)); |
1845 | |
1846 | str1[0] = str1[6] = str1[7] = str1[10] = L'\0'; |
1847 | str2[0] = str2[6] = str2[7] = str2[10] = L'\0'; |
1848 | Matcher<const ::std::wstring&> m2 = StrCaseEq(str1); |
1849 | str1[9] = str2[9] = L'\0'; |
1850 | EXPECT_FALSE(m2.Matches(str2)); |
1851 | |
1852 | Matcher<const ::std::wstring&> m3 = StrCaseEq(str1); |
1853 | EXPECT_TRUE(m3.Matches(str2)); |
1854 | |
1855 | EXPECT_FALSE(m3.Matches(str2 + L"x" )); |
1856 | str2.append(1, L'\0'); |
1857 | EXPECT_FALSE(m3.Matches(str2)); |
1858 | EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9))); |
1859 | } |
1860 | |
1861 | TEST(StdWideStrCaseEqTest, CanDescribeSelf) { |
1862 | Matcher< ::std::wstring> m = StrCaseEq(L"Hi" ); |
1863 | EXPECT_EQ("is equal to (ignoring case) L\"Hi\"" , Describe(m)); |
1864 | } |
1865 | |
1866 | TEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) { |
1867 | Matcher<const wchar_t*> m = StrCaseNe(L"Hello" ); |
1868 | EXPECT_TRUE(m.Matches(L"Hi" )); |
1869 | EXPECT_TRUE(m.Matches(nullptr)); |
1870 | EXPECT_FALSE(m.Matches(L"Hello" )); |
1871 | EXPECT_FALSE(m.Matches(L"hello" )); |
1872 | |
1873 | Matcher< ::std::wstring> m2 = StrCaseNe(::std::wstring(L"Hello" )); |
1874 | EXPECT_TRUE(m2.Matches(L"" )); |
1875 | EXPECT_FALSE(m2.Matches(L"Hello" )); |
1876 | } |
1877 | |
1878 | TEST(StdWideStrCaseNeTest, CanDescribeSelf) { |
1879 | Matcher<const wchar_t*> m = StrCaseNe(L"Hi" ); |
1880 | EXPECT_EQ("isn't equal to (ignoring case) L\"Hi\"" , Describe(m)); |
1881 | } |
1882 | |
1883 | // Tests that HasSubstr() works for matching wstring-typed values. |
1884 | TEST(StdWideHasSubstrTest, WorksForStringClasses) { |
1885 | const Matcher< ::std::wstring> m1 = HasSubstr(L"foo" ); |
1886 | EXPECT_TRUE(m1.Matches(::std::wstring(L"I love food." ))); |
1887 | EXPECT_FALSE(m1.Matches(::std::wstring(L"tofo" ))); |
1888 | |
1889 | const Matcher<const ::std::wstring&> m2 = HasSubstr(L"foo" ); |
1890 | EXPECT_TRUE(m2.Matches(::std::wstring(L"I love food." ))); |
1891 | EXPECT_FALSE(m2.Matches(::std::wstring(L"tofo" ))); |
1892 | } |
1893 | |
1894 | // Tests that HasSubstr() works for matching C-wide-string-typed values. |
1895 | TEST(StdWideHasSubstrTest, WorksForCStrings) { |
1896 | const Matcher<wchar_t*> m1 = HasSubstr(L"foo" ); |
1897 | EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L"I love food." ))); |
1898 | EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L"tofo" ))); |
1899 | EXPECT_FALSE(m1.Matches(nullptr)); |
1900 | |
1901 | const Matcher<const wchar_t*> m2 = HasSubstr(L"foo" ); |
1902 | EXPECT_TRUE(m2.Matches(L"I love food." )); |
1903 | EXPECT_FALSE(m2.Matches(L"tofo" )); |
1904 | EXPECT_FALSE(m2.Matches(nullptr)); |
1905 | } |
1906 | |
1907 | // Tests that HasSubstr(s) describes itself properly. |
1908 | TEST(StdWideHasSubstrTest, CanDescribeSelf) { |
1909 | Matcher< ::std::wstring> m = HasSubstr(L"foo\n\"" ); |
1910 | EXPECT_EQ("has substring L\"foo\\n\\\"\"" , Describe(m)); |
1911 | } |
1912 | |
1913 | // Tests StartsWith(s). |
1914 | |
1915 | TEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) { |
1916 | const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L"" )); |
1917 | EXPECT_TRUE(m1.Matches(L"Hi" )); |
1918 | EXPECT_TRUE(m1.Matches(L"" )); |
1919 | EXPECT_FALSE(m1.Matches(nullptr)); |
1920 | |
1921 | const Matcher<const ::std::wstring&> m2 = StartsWith(L"Hi" ); |
1922 | EXPECT_TRUE(m2.Matches(L"Hi" )); |
1923 | EXPECT_TRUE(m2.Matches(L"Hi Hi!" )); |
1924 | EXPECT_TRUE(m2.Matches(L"High" )); |
1925 | EXPECT_FALSE(m2.Matches(L"H" )); |
1926 | EXPECT_FALSE(m2.Matches(L" Hi" )); |
1927 | } |
1928 | |
1929 | TEST(StdWideStartsWithTest, CanDescribeSelf) { |
1930 | Matcher<const ::std::wstring> m = StartsWith(L"Hi" ); |
1931 | EXPECT_EQ("starts with L\"Hi\"" , Describe(m)); |
1932 | } |
1933 | |
1934 | // Tests EndsWith(s). |
1935 | |
1936 | TEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) { |
1937 | const Matcher<const wchar_t*> m1 = EndsWith(L"" ); |
1938 | EXPECT_TRUE(m1.Matches(L"Hi" )); |
1939 | EXPECT_TRUE(m1.Matches(L"" )); |
1940 | EXPECT_FALSE(m1.Matches(nullptr)); |
1941 | |
1942 | const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L"Hi" )); |
1943 | EXPECT_TRUE(m2.Matches(L"Hi" )); |
1944 | EXPECT_TRUE(m2.Matches(L"Wow Hi Hi" )); |
1945 | EXPECT_TRUE(m2.Matches(L"Super Hi" )); |
1946 | EXPECT_FALSE(m2.Matches(L"i" )); |
1947 | EXPECT_FALSE(m2.Matches(L"Hi " )); |
1948 | } |
1949 | |
1950 | TEST(StdWideEndsWithTest, CanDescribeSelf) { |
1951 | Matcher<const ::std::wstring> m = EndsWith(L"Hi" ); |
1952 | EXPECT_EQ("ends with L\"Hi\"" , Describe(m)); |
1953 | } |
1954 | |
1955 | #endif // GTEST_HAS_STD_WSTRING |
1956 | |
1957 | typedef ::std::tuple<long, int> Tuple2; // NOLINT |
1958 | |
1959 | // Tests that Eq() matches a 2-tuple where the first field == the |
1960 | // second field. |
1961 | TEST(Eq2Test, MatchesEqualArguments) { |
1962 | Matcher<const Tuple2&> m = Eq(); |
1963 | EXPECT_TRUE(m.Matches(Tuple2(5L, 5))); |
1964 | EXPECT_FALSE(m.Matches(Tuple2(5L, 6))); |
1965 | } |
1966 | |
1967 | // Tests that Eq() describes itself properly. |
1968 | TEST(Eq2Test, CanDescribeSelf) { |
1969 | Matcher<const Tuple2&> m = Eq(); |
1970 | EXPECT_EQ("are an equal pair" , Describe(m)); |
1971 | } |
1972 | |
1973 | // Tests that Ge() matches a 2-tuple where the first field >= the |
1974 | // second field. |
1975 | TEST(Ge2Test, MatchesGreaterThanOrEqualArguments) { |
1976 | Matcher<const Tuple2&> m = Ge(); |
1977 | EXPECT_TRUE(m.Matches(Tuple2(5L, 4))); |
1978 | EXPECT_TRUE(m.Matches(Tuple2(5L, 5))); |
1979 | EXPECT_FALSE(m.Matches(Tuple2(5L, 6))); |
1980 | } |
1981 | |
1982 | // Tests that Ge() describes itself properly. |
1983 | TEST(Ge2Test, CanDescribeSelf) { |
1984 | Matcher<const Tuple2&> m = Ge(); |
1985 | EXPECT_EQ("are a pair where the first >= the second" , Describe(m)); |
1986 | } |
1987 | |
1988 | // Tests that Gt() matches a 2-tuple where the first field > the |
1989 | // second field. |
1990 | TEST(Gt2Test, MatchesGreaterThanArguments) { |
1991 | Matcher<const Tuple2&> m = Gt(); |
1992 | EXPECT_TRUE(m.Matches(Tuple2(5L, 4))); |
1993 | EXPECT_FALSE(m.Matches(Tuple2(5L, 5))); |
1994 | EXPECT_FALSE(m.Matches(Tuple2(5L, 6))); |
1995 | } |
1996 | |
1997 | // Tests that Gt() describes itself properly. |
1998 | TEST(Gt2Test, CanDescribeSelf) { |
1999 | Matcher<const Tuple2&> m = Gt(); |
2000 | EXPECT_EQ("are a pair where the first > the second" , Describe(m)); |
2001 | } |
2002 | |
2003 | // Tests that Le() matches a 2-tuple where the first field <= the |
2004 | // second field. |
2005 | TEST(Le2Test, MatchesLessThanOrEqualArguments) { |
2006 | Matcher<const Tuple2&> m = Le(); |
2007 | EXPECT_TRUE(m.Matches(Tuple2(5L, 6))); |
2008 | EXPECT_TRUE(m.Matches(Tuple2(5L, 5))); |
2009 | EXPECT_FALSE(m.Matches(Tuple2(5L, 4))); |
2010 | } |
2011 | |
2012 | // Tests that Le() describes itself properly. |
2013 | TEST(Le2Test, CanDescribeSelf) { |
2014 | Matcher<const Tuple2&> m = Le(); |
2015 | EXPECT_EQ("are a pair where the first <= the second" , Describe(m)); |
2016 | } |
2017 | |
2018 | // Tests that Lt() matches a 2-tuple where the first field < the |
2019 | // second field. |
2020 | TEST(Lt2Test, MatchesLessThanArguments) { |
2021 | Matcher<const Tuple2&> m = Lt(); |
2022 | EXPECT_TRUE(m.Matches(Tuple2(5L, 6))); |
2023 | EXPECT_FALSE(m.Matches(Tuple2(5L, 5))); |
2024 | EXPECT_FALSE(m.Matches(Tuple2(5L, 4))); |
2025 | } |
2026 | |
2027 | // Tests that Lt() describes itself properly. |
2028 | TEST(Lt2Test, CanDescribeSelf) { |
2029 | Matcher<const Tuple2&> m = Lt(); |
2030 | EXPECT_EQ("are a pair where the first < the second" , Describe(m)); |
2031 | } |
2032 | |
2033 | // Tests that Ne() matches a 2-tuple where the first field != the |
2034 | // second field. |
2035 | TEST(Ne2Test, MatchesUnequalArguments) { |
2036 | Matcher<const Tuple2&> m = Ne(); |
2037 | EXPECT_TRUE(m.Matches(Tuple2(5L, 6))); |
2038 | EXPECT_TRUE(m.Matches(Tuple2(5L, 4))); |
2039 | EXPECT_FALSE(m.Matches(Tuple2(5L, 5))); |
2040 | } |
2041 | |
2042 | // Tests that Ne() describes itself properly. |
2043 | TEST(Ne2Test, CanDescribeSelf) { |
2044 | Matcher<const Tuple2&> m = Ne(); |
2045 | EXPECT_EQ("are an unequal pair" , Describe(m)); |
2046 | } |
2047 | |
2048 | TEST(PairMatchBaseTest, WorksWithMoveOnly) { |
2049 | using Pointers = std::tuple<std::unique_ptr<int>, std::unique_ptr<int>>; |
2050 | Matcher<Pointers> matcher = Eq(); |
2051 | Pointers pointers; |
2052 | // Tested values don't matter; the point is that matcher does not copy the |
2053 | // matched values. |
2054 | EXPECT_TRUE(matcher.Matches(pointers)); |
2055 | } |
2056 | |
2057 | // Tests that FloatEq() matches a 2-tuple where |
2058 | // FloatEq(first field) matches the second field. |
2059 | TEST(FloatEq2Test, MatchesEqualArguments) { |
2060 | typedef ::std::tuple<float, float> Tpl; |
2061 | Matcher<const Tpl&> m = FloatEq(); |
2062 | EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); |
2063 | EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f))); |
2064 | EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); |
2065 | } |
2066 | |
2067 | // Tests that FloatEq() describes itself properly. |
2068 | TEST(FloatEq2Test, CanDescribeSelf) { |
2069 | Matcher<const ::std::tuple<float, float>&> m = FloatEq(); |
2070 | EXPECT_EQ("are an almost-equal pair" , Describe(m)); |
2071 | } |
2072 | |
2073 | // Tests that NanSensitiveFloatEq() matches a 2-tuple where |
2074 | // NanSensitiveFloatEq(first field) matches the second field. |
2075 | TEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) { |
2076 | typedef ::std::tuple<float, float> Tpl; |
2077 | Matcher<const Tpl&> m = NanSensitiveFloatEq(); |
2078 | EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); |
2079 | EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), |
2080 | std::numeric_limits<float>::quiet_NaN()))); |
2081 | EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); |
2082 | EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN()))); |
2083 | EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f))); |
2084 | } |
2085 | |
2086 | // Tests that NanSensitiveFloatEq() describes itself properly. |
2087 | TEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) { |
2088 | Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatEq(); |
2089 | EXPECT_EQ("are an almost-equal pair" , Describe(m)); |
2090 | } |
2091 | |
2092 | // Tests that DoubleEq() matches a 2-tuple where |
2093 | // DoubleEq(first field) matches the second field. |
2094 | TEST(DoubleEq2Test, MatchesEqualArguments) { |
2095 | typedef ::std::tuple<double, double> Tpl; |
2096 | Matcher<const Tpl&> m = DoubleEq(); |
2097 | EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0))); |
2098 | EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1))); |
2099 | EXPECT_FALSE(m.Matches(Tpl(1.1, 1.0))); |
2100 | } |
2101 | |
2102 | // Tests that DoubleEq() describes itself properly. |
2103 | TEST(DoubleEq2Test, CanDescribeSelf) { |
2104 | Matcher<const ::std::tuple<double, double>&> m = DoubleEq(); |
2105 | EXPECT_EQ("are an almost-equal pair" , Describe(m)); |
2106 | } |
2107 | |
2108 | // Tests that NanSensitiveDoubleEq() matches a 2-tuple where |
2109 | // NanSensitiveDoubleEq(first field) matches the second field. |
2110 | TEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) { |
2111 | typedef ::std::tuple<double, double> Tpl; |
2112 | Matcher<const Tpl&> m = NanSensitiveDoubleEq(); |
2113 | EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); |
2114 | EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), |
2115 | std::numeric_limits<double>::quiet_NaN()))); |
2116 | EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f))); |
2117 | EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN()))); |
2118 | EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f))); |
2119 | } |
2120 | |
2121 | // Tests that DoubleEq() describes itself properly. |
2122 | TEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) { |
2123 | Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleEq(); |
2124 | EXPECT_EQ("are an almost-equal pair" , Describe(m)); |
2125 | } |
2126 | |
2127 | // Tests that FloatEq() matches a 2-tuple where |
2128 | // FloatNear(first field, max_abs_error) matches the second field. |
2129 | TEST(FloatNear2Test, MatchesEqualArguments) { |
2130 | typedef ::std::tuple<float, float> Tpl; |
2131 | Matcher<const Tpl&> m = FloatNear(0.5f); |
2132 | EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); |
2133 | EXPECT_TRUE(m.Matches(Tpl(1.3f, 1.0f))); |
2134 | EXPECT_FALSE(m.Matches(Tpl(1.8f, 1.0f))); |
2135 | } |
2136 | |
2137 | // Tests that FloatNear() describes itself properly. |
2138 | TEST(FloatNear2Test, CanDescribeSelf) { |
2139 | Matcher<const ::std::tuple<float, float>&> m = FloatNear(0.5f); |
2140 | EXPECT_EQ("are an almost-equal pair" , Describe(m)); |
2141 | } |
2142 | |
2143 | // Tests that NanSensitiveFloatNear() matches a 2-tuple where |
2144 | // NanSensitiveFloatNear(first field) matches the second field. |
2145 | TEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) { |
2146 | typedef ::std::tuple<float, float> Tpl; |
2147 | Matcher<const Tpl&> m = NanSensitiveFloatNear(0.5f); |
2148 | EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); |
2149 | EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f))); |
2150 | EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), |
2151 | std::numeric_limits<float>::quiet_NaN()))); |
2152 | EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f))); |
2153 | EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN()))); |
2154 | EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f))); |
2155 | } |
2156 | |
2157 | // Tests that NanSensitiveFloatNear() describes itself properly. |
2158 | TEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) { |
2159 | Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatNear(0.5f); |
2160 | EXPECT_EQ("are an almost-equal pair" , Describe(m)); |
2161 | } |
2162 | |
2163 | // Tests that FloatEq() matches a 2-tuple where |
2164 | // DoubleNear(first field, max_abs_error) matches the second field. |
2165 | TEST(DoubleNear2Test, MatchesEqualArguments) { |
2166 | typedef ::std::tuple<double, double> Tpl; |
2167 | Matcher<const Tpl&> m = DoubleNear(0.5); |
2168 | EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0))); |
2169 | EXPECT_TRUE(m.Matches(Tpl(1.3, 1.0))); |
2170 | EXPECT_FALSE(m.Matches(Tpl(1.8, 1.0))); |
2171 | } |
2172 | |
2173 | // Tests that DoubleNear() describes itself properly. |
2174 | TEST(DoubleNear2Test, CanDescribeSelf) { |
2175 | Matcher<const ::std::tuple<double, double>&> m = DoubleNear(0.5); |
2176 | EXPECT_EQ("are an almost-equal pair" , Describe(m)); |
2177 | } |
2178 | |
2179 | // Tests that NanSensitiveDoubleNear() matches a 2-tuple where |
2180 | // NanSensitiveDoubleNear(first field) matches the second field. |
2181 | TEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) { |
2182 | typedef ::std::tuple<double, double> Tpl; |
2183 | Matcher<const Tpl&> m = NanSensitiveDoubleNear(0.5f); |
2184 | EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f))); |
2185 | EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f))); |
2186 | EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), |
2187 | std::numeric_limits<double>::quiet_NaN()))); |
2188 | EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f))); |
2189 | EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN()))); |
2190 | EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f))); |
2191 | } |
2192 | |
2193 | // Tests that NanSensitiveDoubleNear() describes itself properly. |
2194 | TEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) { |
2195 | Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleNear(0.5f); |
2196 | EXPECT_EQ("are an almost-equal pair" , Describe(m)); |
2197 | } |
2198 | |
2199 | // Tests that Not(m) matches any value that doesn't match m. |
2200 | TEST(NotTest, NegatesMatcher) { |
2201 | Matcher<int> m; |
2202 | m = Not(Eq(2)); |
2203 | EXPECT_TRUE(m.Matches(3)); |
2204 | EXPECT_FALSE(m.Matches(2)); |
2205 | } |
2206 | |
2207 | // Tests that Not(m) describes itself properly. |
2208 | TEST(NotTest, CanDescribeSelf) { |
2209 | Matcher<int> m = Not(Eq(5)); |
2210 | EXPECT_EQ("isn't equal to 5" , Describe(m)); |
2211 | } |
2212 | |
2213 | // Tests that monomorphic matchers are safely cast by the Not matcher. |
2214 | TEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) { |
2215 | // greater_than_5 is a monomorphic matcher. |
2216 | Matcher<int> greater_than_5 = Gt(5); |
2217 | |
2218 | Matcher<const int&> m = Not(greater_than_5); |
2219 | Matcher<int&> m2 = Not(greater_than_5); |
2220 | Matcher<int&> m3 = Not(m); |
2221 | } |
2222 | |
2223 | // Helper to allow easy testing of AllOf matchers with num parameters. |
2224 | void AllOfMatches(int num, const Matcher<int>& m) { |
2225 | SCOPED_TRACE(Describe(m)); |
2226 | EXPECT_TRUE(m.Matches(0)); |
2227 | for (int i = 1; i <= num; ++i) { |
2228 | EXPECT_FALSE(m.Matches(i)); |
2229 | } |
2230 | EXPECT_TRUE(m.Matches(num + 1)); |
2231 | } |
2232 | |
2233 | // Tests that AllOf(m1, ..., mn) matches any value that matches all of |
2234 | // the given matchers. |
2235 | TEST(AllOfTest, MatchesWhenAllMatch) { |
2236 | Matcher<int> m; |
2237 | m = AllOf(Le(2), Ge(1)); |
2238 | EXPECT_TRUE(m.Matches(1)); |
2239 | EXPECT_TRUE(m.Matches(2)); |
2240 | EXPECT_FALSE(m.Matches(0)); |
2241 | EXPECT_FALSE(m.Matches(3)); |
2242 | |
2243 | m = AllOf(Gt(0), Ne(1), Ne(2)); |
2244 | EXPECT_TRUE(m.Matches(3)); |
2245 | EXPECT_FALSE(m.Matches(2)); |
2246 | EXPECT_FALSE(m.Matches(1)); |
2247 | EXPECT_FALSE(m.Matches(0)); |
2248 | |
2249 | m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3)); |
2250 | EXPECT_TRUE(m.Matches(4)); |
2251 | EXPECT_FALSE(m.Matches(3)); |
2252 | EXPECT_FALSE(m.Matches(2)); |
2253 | EXPECT_FALSE(m.Matches(1)); |
2254 | EXPECT_FALSE(m.Matches(0)); |
2255 | |
2256 | m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7)); |
2257 | EXPECT_TRUE(m.Matches(0)); |
2258 | EXPECT_TRUE(m.Matches(1)); |
2259 | EXPECT_FALSE(m.Matches(3)); |
2260 | |
2261 | // The following tests for varying number of sub-matchers. Due to the way |
2262 | // the sub-matchers are handled it is enough to test every sub-matcher once |
2263 | // with sub-matchers using the same matcher type. Varying matcher types are |
2264 | // checked for above. |
2265 | AllOfMatches(2, AllOf(Ne(1), Ne(2))); |
2266 | AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3))); |
2267 | AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4))); |
2268 | AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5))); |
2269 | AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6))); |
2270 | AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7))); |
2271 | AllOfMatches(8, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), |
2272 | Ne(8))); |
2273 | AllOfMatches(9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), |
2274 | Ne(8), Ne(9))); |
2275 | AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), |
2276 | Ne(9), Ne(10))); |
2277 | AllOfMatches( |
2278 | 50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9), |
2279 | Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), Ne(16), Ne(17), |
2280 | Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), Ne(23), Ne(24), Ne(25), |
2281 | Ne(26), Ne(27), Ne(28), Ne(29), Ne(30), Ne(31), Ne(32), Ne(33), |
2282 | Ne(34), Ne(35), Ne(36), Ne(37), Ne(38), Ne(39), Ne(40), Ne(41), |
2283 | Ne(42), Ne(43), Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49), |
2284 | Ne(50))); |
2285 | } |
2286 | |
2287 | |
2288 | // Tests that AllOf(m1, ..., mn) describes itself properly. |
2289 | TEST(AllOfTest, CanDescribeSelf) { |
2290 | Matcher<int> m; |
2291 | m = AllOf(Le(2), Ge(1)); |
2292 | EXPECT_EQ("(is <= 2) and (is >= 1)" , Describe(m)); |
2293 | |
2294 | m = AllOf(Gt(0), Ne(1), Ne(2)); |
2295 | std::string expected_descr1 = |
2296 | "(is > 0) and (isn't equal to 1) and (isn't equal to 2)" ; |
2297 | EXPECT_EQ(expected_descr1, Describe(m)); |
2298 | |
2299 | m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3)); |
2300 | std::string expected_descr2 = |
2301 | "(is > 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't equal " |
2302 | "to 3)" ; |
2303 | EXPECT_EQ(expected_descr2, Describe(m)); |
2304 | |
2305 | m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7)); |
2306 | std::string expected_descr3 = |
2307 | "(is >= 0) and (is < 10) and (isn't equal to 3) and (isn't equal to 5) " |
2308 | "and (isn't equal to 7)" ; |
2309 | EXPECT_EQ(expected_descr3, Describe(m)); |
2310 | } |
2311 | |
2312 | // Tests that AllOf(m1, ..., mn) describes its negation properly. |
2313 | TEST(AllOfTest, CanDescribeNegation) { |
2314 | Matcher<int> m; |
2315 | m = AllOf(Le(2), Ge(1)); |
2316 | std::string expected_descr4 = "(isn't <= 2) or (isn't >= 1)" ; |
2317 | EXPECT_EQ(expected_descr4, DescribeNegation(m)); |
2318 | |
2319 | m = AllOf(Gt(0), Ne(1), Ne(2)); |
2320 | std::string expected_descr5 = |
2321 | "(isn't > 0) or (is equal to 1) or (is equal to 2)" ; |
2322 | EXPECT_EQ(expected_descr5, DescribeNegation(m)); |
2323 | |
2324 | m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3)); |
2325 | std::string expected_descr6 = |
2326 | "(isn't > 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)" ; |
2327 | EXPECT_EQ(expected_descr6, DescribeNegation(m)); |
2328 | |
2329 | m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7)); |
2330 | std::string expected_desr7 = |
2331 | "(isn't >= 0) or (isn't < 10) or (is equal to 3) or (is equal to 5) or " |
2332 | "(is equal to 7)" ; |
2333 | EXPECT_EQ(expected_desr7, DescribeNegation(m)); |
2334 | |
2335 | m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9), |
2336 | Ne(10), Ne(11)); |
2337 | AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); |
2338 | EXPECT_THAT(Describe(m), EndsWith("and (isn't equal to 11)" )); |
2339 | AllOfMatches(11, m); |
2340 | } |
2341 | |
2342 | // Tests that monomorphic matchers are safely cast by the AllOf matcher. |
2343 | TEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) { |
2344 | // greater_than_5 and less_than_10 are monomorphic matchers. |
2345 | Matcher<int> greater_than_5 = Gt(5); |
2346 | Matcher<int> less_than_10 = Lt(10); |
2347 | |
2348 | Matcher<const int&> m = AllOf(greater_than_5, less_than_10); |
2349 | Matcher<int&> m2 = AllOf(greater_than_5, less_than_10); |
2350 | Matcher<int&> m3 = AllOf(greater_than_5, m2); |
2351 | |
2352 | // Tests that BothOf works when composing itself. |
2353 | Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10); |
2354 | Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10); |
2355 | } |
2356 | |
2357 | TEST(AllOfTest, ExplainsResult) { |
2358 | Matcher<int> m; |
2359 | |
2360 | // Successful match. Both matchers need to explain. The second |
2361 | // matcher doesn't give an explanation, so only the first matcher's |
2362 | // explanation is printed. |
2363 | m = AllOf(GreaterThan(10), Lt(30)); |
2364 | EXPECT_EQ("which is 15 more than 10" , Explain(m, 25)); |
2365 | |
2366 | // Successful match. Both matchers need to explain. |
2367 | m = AllOf(GreaterThan(10), GreaterThan(20)); |
2368 | EXPECT_EQ("which is 20 more than 10, and which is 10 more than 20" , |
2369 | Explain(m, 30)); |
2370 | |
2371 | // Successful match. All matchers need to explain. The second |
2372 | // matcher doesn't given an explanation. |
2373 | m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20)); |
2374 | EXPECT_EQ("which is 15 more than 10, and which is 5 more than 20" , |
2375 | Explain(m, 25)); |
2376 | |
2377 | // Successful match. All matchers need to explain. |
2378 | m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30)); |
2379 | EXPECT_EQ("which is 30 more than 10, and which is 20 more than 20, " |
2380 | "and which is 10 more than 30" , |
2381 | Explain(m, 40)); |
2382 | |
2383 | // Failed match. The first matcher, which failed, needs to |
2384 | // explain. |
2385 | m = AllOf(GreaterThan(10), GreaterThan(20)); |
2386 | EXPECT_EQ("which is 5 less than 10" , Explain(m, 5)); |
2387 | |
2388 | // Failed match. The second matcher, which failed, needs to |
2389 | // explain. Since it doesn't given an explanation, nothing is |
2390 | // printed. |
2391 | m = AllOf(GreaterThan(10), Lt(30)); |
2392 | EXPECT_EQ("" , Explain(m, 40)); |
2393 | |
2394 | // Failed match. The second matcher, which failed, needs to |
2395 | // explain. |
2396 | m = AllOf(GreaterThan(10), GreaterThan(20)); |
2397 | EXPECT_EQ("which is 5 less than 20" , Explain(m, 15)); |
2398 | } |
2399 | |
2400 | // Helper to allow easy testing of AnyOf matchers with num parameters. |
2401 | static void AnyOfMatches(int num, const Matcher<int>& m) { |
2402 | SCOPED_TRACE(Describe(m)); |
2403 | EXPECT_FALSE(m.Matches(0)); |
2404 | for (int i = 1; i <= num; ++i) { |
2405 | EXPECT_TRUE(m.Matches(i)); |
2406 | } |
2407 | EXPECT_FALSE(m.Matches(num + 1)); |
2408 | } |
2409 | |
2410 | static void AnyOfStringMatches(int num, const Matcher<std::string>& m) { |
2411 | SCOPED_TRACE(Describe(m)); |
2412 | EXPECT_FALSE(m.Matches(std::to_string(0))); |
2413 | |
2414 | for (int i = 1; i <= num; ++i) { |
2415 | EXPECT_TRUE(m.Matches(std::to_string(i))); |
2416 | } |
2417 | EXPECT_FALSE(m.Matches(std::to_string(num + 1))); |
2418 | } |
2419 | |
2420 | // Tests that AnyOf(m1, ..., mn) matches any value that matches at |
2421 | // least one of the given matchers. |
2422 | TEST(AnyOfTest, MatchesWhenAnyMatches) { |
2423 | Matcher<int> m; |
2424 | m = AnyOf(Le(1), Ge(3)); |
2425 | EXPECT_TRUE(m.Matches(1)); |
2426 | EXPECT_TRUE(m.Matches(4)); |
2427 | EXPECT_FALSE(m.Matches(2)); |
2428 | |
2429 | m = AnyOf(Lt(0), Eq(1), Eq(2)); |
2430 | EXPECT_TRUE(m.Matches(-1)); |
2431 | EXPECT_TRUE(m.Matches(1)); |
2432 | EXPECT_TRUE(m.Matches(2)); |
2433 | EXPECT_FALSE(m.Matches(0)); |
2434 | |
2435 | m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3)); |
2436 | EXPECT_TRUE(m.Matches(-1)); |
2437 | EXPECT_TRUE(m.Matches(1)); |
2438 | EXPECT_TRUE(m.Matches(2)); |
2439 | EXPECT_TRUE(m.Matches(3)); |
2440 | EXPECT_FALSE(m.Matches(0)); |
2441 | |
2442 | m = AnyOf(Le(0), Gt(10), 3, 5, 7); |
2443 | EXPECT_TRUE(m.Matches(0)); |
2444 | EXPECT_TRUE(m.Matches(11)); |
2445 | EXPECT_TRUE(m.Matches(3)); |
2446 | EXPECT_FALSE(m.Matches(2)); |
2447 | |
2448 | // The following tests for varying number of sub-matchers. Due to the way |
2449 | // the sub-matchers are handled it is enough to test every sub-matcher once |
2450 | // with sub-matchers using the same matcher type. Varying matcher types are |
2451 | // checked for above. |
2452 | AnyOfMatches(2, AnyOf(1, 2)); |
2453 | AnyOfMatches(3, AnyOf(1, 2, 3)); |
2454 | AnyOfMatches(4, AnyOf(1, 2, 3, 4)); |
2455 | AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5)); |
2456 | AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6)); |
2457 | AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7)); |
2458 | AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8)); |
2459 | AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9)); |
2460 | AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); |
2461 | } |
2462 | |
2463 | // Tests the variadic version of the AnyOfMatcher. |
2464 | TEST(AnyOfTest, VariadicMatchesWhenAnyMatches) { |
2465 | // Also make sure AnyOf is defined in the right namespace and does not depend |
2466 | // on ADL. |
2467 | Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); |
2468 | |
2469 | EXPECT_THAT(Describe(m), EndsWith("or (is equal to 11)" )); |
2470 | AnyOfMatches(11, m); |
2471 | AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, |
2472 | 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, |
2473 | 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, |
2474 | 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, |
2475 | 41, 42, 43, 44, 45, 46, 47, 48, 49, 50)); |
2476 | AnyOfStringMatches( |
2477 | 50, AnyOf("1" , "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" , "10" , "11" , "12" , |
2478 | "13" , "14" , "15" , "16" , "17" , "18" , "19" , "20" , "21" , "22" , |
2479 | "23" , "24" , "25" , "26" , "27" , "28" , "29" , "30" , "31" , "32" , |
2480 | "33" , "34" , "35" , "36" , "37" , "38" , "39" , "40" , "41" , "42" , |
2481 | "43" , "44" , "45" , "46" , "47" , "48" , "49" , "50" )); |
2482 | } |
2483 | |
2484 | // Tests the variadic version of the ElementsAreMatcher |
2485 | TEST(ElementsAreTest, HugeMatcher) { |
2486 | vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; |
2487 | |
2488 | EXPECT_THAT(test_vector, |
2489 | ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7), |
2490 | Eq(8), Eq(9), Eq(10), Gt(1), Eq(12))); |
2491 | } |
2492 | |
2493 | // Tests the variadic version of the UnorderedElementsAreMatcher |
2494 | TEST(ElementsAreTest, HugeMatcherStr) { |
2495 | vector<std::string> test_vector{ |
2496 | "literal_string" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" , "" }; |
2497 | |
2498 | EXPECT_THAT(test_vector, UnorderedElementsAre("literal_string" , _, _, _, _, _, |
2499 | _, _, _, _, _, _)); |
2500 | } |
2501 | |
2502 | // Tests the variadic version of the UnorderedElementsAreMatcher |
2503 | TEST(ElementsAreTest, HugeMatcherUnordered) { |
2504 | vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10}; |
2505 | |
2506 | EXPECT_THAT(test_vector, UnorderedElementsAre( |
2507 | Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7), |
2508 | Eq(3), Eq(9), Eq(12), Eq(11), Ne(122))); |
2509 | } |
2510 | |
2511 | |
2512 | // Tests that AnyOf(m1, ..., mn) describes itself properly. |
2513 | TEST(AnyOfTest, CanDescribeSelf) { |
2514 | Matcher<int> m; |
2515 | m = AnyOf(Le(1), Ge(3)); |
2516 | |
2517 | EXPECT_EQ("(is <= 1) or (is >= 3)" , |
2518 | Describe(m)); |
2519 | |
2520 | m = AnyOf(Lt(0), Eq(1), Eq(2)); |
2521 | EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2)" , Describe(m)); |
2522 | |
2523 | m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3)); |
2524 | EXPECT_EQ("(is < 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)" , |
2525 | Describe(m)); |
2526 | |
2527 | m = AnyOf(Le(0), Gt(10), 3, 5, 7); |
2528 | EXPECT_EQ( |
2529 | "(is <= 0) or (is > 10) or (is equal to 3) or (is equal to 5) or (is " |
2530 | "equal to 7)" , |
2531 | Describe(m)); |
2532 | } |
2533 | |
2534 | // Tests that AnyOf(m1, ..., mn) describes its negation properly. |
2535 | TEST(AnyOfTest, CanDescribeNegation) { |
2536 | Matcher<int> m; |
2537 | m = AnyOf(Le(1), Ge(3)); |
2538 | EXPECT_EQ("(isn't <= 1) and (isn't >= 3)" , |
2539 | DescribeNegation(m)); |
2540 | |
2541 | m = AnyOf(Lt(0), Eq(1), Eq(2)); |
2542 | EXPECT_EQ("(isn't < 0) and (isn't equal to 1) and (isn't equal to 2)" , |
2543 | DescribeNegation(m)); |
2544 | |
2545 | m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3)); |
2546 | EXPECT_EQ( |
2547 | "(isn't < 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't " |
2548 | "equal to 3)" , |
2549 | DescribeNegation(m)); |
2550 | |
2551 | m = AnyOf(Le(0), Gt(10), 3, 5, 7); |
2552 | EXPECT_EQ( |
2553 | "(isn't <= 0) and (isn't > 10) and (isn't equal to 3) and (isn't equal " |
2554 | "to 5) and (isn't equal to 7)" , |
2555 | DescribeNegation(m)); |
2556 | } |
2557 | |
2558 | // Tests that monomorphic matchers are safely cast by the AnyOf matcher. |
2559 | TEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) { |
2560 | // greater_than_5 and less_than_10 are monomorphic matchers. |
2561 | Matcher<int> greater_than_5 = Gt(5); |
2562 | Matcher<int> less_than_10 = Lt(10); |
2563 | |
2564 | Matcher<const int&> m = AnyOf(greater_than_5, less_than_10); |
2565 | Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10); |
2566 | Matcher<int&> m3 = AnyOf(greater_than_5, m2); |
2567 | |
2568 | // Tests that EitherOf works when composing itself. |
2569 | Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10); |
2570 | Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10); |
2571 | } |
2572 | |
2573 | TEST(AnyOfTest, ExplainsResult) { |
2574 | Matcher<int> m; |
2575 | |
2576 | // Failed match. Both matchers need to explain. The second |
2577 | // matcher doesn't give an explanation, so only the first matcher's |
2578 | // explanation is printed. |
2579 | m = AnyOf(GreaterThan(10), Lt(0)); |
2580 | EXPECT_EQ("which is 5 less than 10" , Explain(m, 5)); |
2581 | |
2582 | // Failed match. Both matchers need to explain. |
2583 | m = AnyOf(GreaterThan(10), GreaterThan(20)); |
2584 | EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20" , |
2585 | Explain(m, 5)); |
2586 | |
2587 | // Failed match. All matchers need to explain. The second |
2588 | // matcher doesn't given an explanation. |
2589 | m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30)); |
2590 | EXPECT_EQ("which is 5 less than 10, and which is 25 less than 30" , |
2591 | Explain(m, 5)); |
2592 | |
2593 | // Failed match. All matchers need to explain. |
2594 | m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30)); |
2595 | EXPECT_EQ("which is 5 less than 10, and which is 15 less than 20, " |
2596 | "and which is 25 less than 30" , |
2597 | Explain(m, 5)); |
2598 | |
2599 | // Successful match. The first matcher, which succeeded, needs to |
2600 | // explain. |
2601 | m = AnyOf(GreaterThan(10), GreaterThan(20)); |
2602 | EXPECT_EQ("which is 5 more than 10" , Explain(m, 15)); |
2603 | |
2604 | // Successful match. The second matcher, which succeeded, needs to |
2605 | // explain. Since it doesn't given an explanation, nothing is |
2606 | // printed. |
2607 | m = AnyOf(GreaterThan(10), Lt(30)); |
2608 | EXPECT_EQ("" , Explain(m, 0)); |
2609 | |
2610 | // Successful match. The second matcher, which succeeded, needs to |
2611 | // explain. |
2612 | m = AnyOf(GreaterThan(30), GreaterThan(20)); |
2613 | EXPECT_EQ("which is 5 more than 20" , Explain(m, 25)); |
2614 | } |
2615 | |
2616 | // The following predicate function and predicate functor are for |
2617 | // testing the Truly(predicate) matcher. |
2618 | |
2619 | // Returns non-zero if the input is positive. Note that the return |
2620 | // type of this function is not bool. It's OK as Truly() accepts any |
2621 | // unary function or functor whose return type can be implicitly |
2622 | // converted to bool. |
2623 | int IsPositive(double x) { |
2624 | return x > 0 ? 1 : 0; |
2625 | } |
2626 | |
2627 | // This functor returns true if the input is greater than the given |
2628 | // number. |
2629 | class IsGreaterThan { |
2630 | public: |
2631 | explicit IsGreaterThan(int threshold) : threshold_(threshold) {} |
2632 | |
2633 | bool operator()(int n) const { return n > threshold_; } |
2634 | |
2635 | private: |
2636 | int threshold_; |
2637 | }; |
2638 | |
2639 | // For testing Truly(). |
2640 | const int foo = 0; |
2641 | |
2642 | // This predicate returns true if and only if the argument references foo and |
2643 | // has a zero value. |
2644 | bool ReferencesFooAndIsZero(const int& n) { |
2645 | return (&n == &foo) && (n == 0); |
2646 | } |
2647 | |
2648 | // Tests that Truly(predicate) matches what satisfies the given |
2649 | // predicate. |
2650 | TEST(TrulyTest, MatchesWhatSatisfiesThePredicate) { |
2651 | Matcher<double> m = Truly(IsPositive); |
2652 | EXPECT_TRUE(m.Matches(2.0)); |
2653 | EXPECT_FALSE(m.Matches(-1.5)); |
2654 | } |
2655 | |
2656 | // Tests that Truly(predicate_functor) works too. |
2657 | TEST(TrulyTest, CanBeUsedWithFunctor) { |
2658 | Matcher<int> m = Truly(IsGreaterThan(5)); |
2659 | EXPECT_TRUE(m.Matches(6)); |
2660 | EXPECT_FALSE(m.Matches(4)); |
2661 | } |
2662 | |
2663 | // A class that can be implicitly converted to bool. |
2664 | class ConvertibleToBool { |
2665 | public: |
2666 | explicit ConvertibleToBool(int number) : number_(number) {} |
2667 | operator bool() const { return number_ != 0; } |
2668 | |
2669 | private: |
2670 | int number_; |
2671 | }; |
2672 | |
2673 | ConvertibleToBool IsNotZero(int number) { |
2674 | return ConvertibleToBool(number); |
2675 | } |
2676 | |
2677 | // Tests that the predicate used in Truly() may return a class that's |
2678 | // implicitly convertible to bool, even when the class has no |
2679 | // operator!(). |
2680 | TEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) { |
2681 | Matcher<int> m = Truly(IsNotZero); |
2682 | EXPECT_TRUE(m.Matches(1)); |
2683 | EXPECT_FALSE(m.Matches(0)); |
2684 | } |
2685 | |
2686 | // Tests that Truly(predicate) can describe itself properly. |
2687 | TEST(TrulyTest, CanDescribeSelf) { |
2688 | Matcher<double> m = Truly(IsPositive); |
2689 | EXPECT_EQ("satisfies the given predicate" , |
2690 | Describe(m)); |
2691 | } |
2692 | |
2693 | // Tests that Truly(predicate) works when the matcher takes its |
2694 | // argument by reference. |
2695 | TEST(TrulyTest, WorksForByRefArguments) { |
2696 | Matcher<const int&> m = Truly(ReferencesFooAndIsZero); |
2697 | EXPECT_TRUE(m.Matches(foo)); |
2698 | int n = 0; |
2699 | EXPECT_FALSE(m.Matches(n)); |
2700 | } |
2701 | |
2702 | // Tests that Matches(m) is a predicate satisfied by whatever that |
2703 | // matches matcher m. |
2704 | TEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) { |
2705 | EXPECT_TRUE(Matches(Ge(0))(1)); |
2706 | EXPECT_FALSE(Matches(Eq('a'))('b')); |
2707 | } |
2708 | |
2709 | // Tests that Matches(m) works when the matcher takes its argument by |
2710 | // reference. |
2711 | TEST(MatchesTest, WorksOnByRefArguments) { |
2712 | int m = 0, n = 0; |
2713 | EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n)); |
2714 | EXPECT_FALSE(Matches(Ref(m))(n)); |
2715 | } |
2716 | |
2717 | // Tests that a Matcher on non-reference type can be used in |
2718 | // Matches(). |
2719 | TEST(MatchesTest, WorksWithMatcherOnNonRefType) { |
2720 | Matcher<int> eq5 = Eq(5); |
2721 | EXPECT_TRUE(Matches(eq5)(5)); |
2722 | EXPECT_FALSE(Matches(eq5)(2)); |
2723 | } |
2724 | |
2725 | // Tests Value(value, matcher). Since Value() is a simple wrapper for |
2726 | // Matches(), which has been tested already, we don't spend a lot of |
2727 | // effort on testing Value(). |
2728 | TEST(ValueTest, WorksWithPolymorphicMatcher) { |
2729 | EXPECT_TRUE(Value("hi" , StartsWith("h" ))); |
2730 | EXPECT_FALSE(Value(5, Gt(10))); |
2731 | } |
2732 | |
2733 | TEST(ValueTest, WorksWithMonomorphicMatcher) { |
2734 | const Matcher<int> is_zero = Eq(0); |
2735 | EXPECT_TRUE(Value(0, is_zero)); |
2736 | EXPECT_FALSE(Value('a', is_zero)); |
2737 | |
2738 | int n = 0; |
2739 | const Matcher<const int&> ref_n = Ref(n); |
2740 | EXPECT_TRUE(Value(n, ref_n)); |
2741 | EXPECT_FALSE(Value(1, ref_n)); |
2742 | } |
2743 | |
2744 | TEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) { |
2745 | StringMatchResultListener listener1; |
2746 | EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1)); |
2747 | EXPECT_EQ("% 2 == 0" , listener1.str()); |
2748 | |
2749 | StringMatchResultListener listener2; |
2750 | EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2)); |
2751 | EXPECT_EQ("" , listener2.str()); |
2752 | } |
2753 | |
2754 | TEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) { |
2755 | const Matcher<int> is_even = PolymorphicIsEven(); |
2756 | StringMatchResultListener listener1; |
2757 | EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1)); |
2758 | EXPECT_EQ("% 2 == 0" , listener1.str()); |
2759 | |
2760 | const Matcher<const double&> is_zero = Eq(0); |
2761 | StringMatchResultListener listener2; |
2762 | EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2)); |
2763 | EXPECT_EQ("" , listener2.str()); |
2764 | } |
2765 | |
2766 | MATCHER_P(Really, inner_matcher, "" ) { |
2767 | return ExplainMatchResult(inner_matcher, arg, result_listener); |
2768 | } |
2769 | |
2770 | TEST(ExplainMatchResultTest, WorksInsideMATCHER) { |
2771 | EXPECT_THAT(0, Really(Eq(0))); |
2772 | } |
2773 | |
2774 | TEST(DescribeMatcherTest, WorksWithValue) { |
2775 | EXPECT_EQ("is equal to 42" , DescribeMatcher<int>(42)); |
2776 | EXPECT_EQ("isn't equal to 42" , DescribeMatcher<int>(42, true)); |
2777 | } |
2778 | |
2779 | TEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) { |
2780 | const Matcher<int> monomorphic = Le(0); |
2781 | EXPECT_EQ("is <= 0" , DescribeMatcher<int>(monomorphic)); |
2782 | EXPECT_EQ("isn't <= 0" , DescribeMatcher<int>(monomorphic, true)); |
2783 | } |
2784 | |
2785 | TEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) { |
2786 | EXPECT_EQ("is even" , DescribeMatcher<int>(PolymorphicIsEven())); |
2787 | EXPECT_EQ("is odd" , DescribeMatcher<int>(PolymorphicIsEven(), true)); |
2788 | } |
2789 | |
2790 | TEST(AllArgsTest, WorksForTuple) { |
2791 | EXPECT_THAT(std::make_tuple(1, 2L), AllArgs(Lt())); |
2792 | EXPECT_THAT(std::make_tuple(2L, 1), Not(AllArgs(Lt()))); |
2793 | } |
2794 | |
2795 | TEST(AllArgsTest, WorksForNonTuple) { |
2796 | EXPECT_THAT(42, AllArgs(Gt(0))); |
2797 | EXPECT_THAT('a', Not(AllArgs(Eq('b')))); |
2798 | } |
2799 | |
2800 | class AllArgsHelper { |
2801 | public: |
2802 | AllArgsHelper() {} |
2803 | |
2804 | MOCK_METHOD2(Helper, int(char x, int y)); |
2805 | |
2806 | private: |
2807 | GTEST_DISALLOW_COPY_AND_ASSIGN_(AllArgsHelper); |
2808 | }; |
2809 | |
2810 | TEST(AllArgsTest, WorksInWithClause) { |
2811 | AllArgsHelper helper; |
2812 | ON_CALL(helper, Helper(_, _)) |
2813 | .With(AllArgs(Lt())) |
2814 | .WillByDefault(Return(1)); |
2815 | EXPECT_CALL(helper, Helper(_, _)); |
2816 | EXPECT_CALL(helper, Helper(_, _)) |
2817 | .With(AllArgs(Gt())) |
2818 | .WillOnce(Return(2)); |
2819 | |
2820 | EXPECT_EQ(1, helper.Helper('\1', 2)); |
2821 | EXPECT_EQ(2, helper.Helper('a', 1)); |
2822 | } |
2823 | |
2824 | class OptionalMatchersHelper { |
2825 | public: |
2826 | OptionalMatchersHelper() {} |
2827 | |
2828 | MOCK_METHOD0(NoArgs, int()); |
2829 | |
2830 | MOCK_METHOD1(OneArg, int(int y)); |
2831 | |
2832 | MOCK_METHOD2(TwoArgs, int(char x, int y)); |
2833 | |
2834 | MOCK_METHOD1(Overloaded, int(char x)); |
2835 | MOCK_METHOD2(Overloaded, int(char x, int y)); |
2836 | |
2837 | private: |
2838 | GTEST_DISALLOW_COPY_AND_ASSIGN_(OptionalMatchersHelper); |
2839 | }; |
2840 | |
2841 | TEST(AllArgsTest, WorksWithoutMatchers) { |
2842 | OptionalMatchersHelper helper; |
2843 | |
2844 | ON_CALL(helper, NoArgs).WillByDefault(Return(10)); |
2845 | ON_CALL(helper, OneArg).WillByDefault(Return(20)); |
2846 | ON_CALL(helper, TwoArgs).WillByDefault(Return(30)); |
2847 | |
2848 | EXPECT_EQ(10, helper.NoArgs()); |
2849 | EXPECT_EQ(20, helper.OneArg(1)); |
2850 | EXPECT_EQ(30, helper.TwoArgs('\1', 2)); |
2851 | |
2852 | EXPECT_CALL(helper, NoArgs).Times(1); |
2853 | EXPECT_CALL(helper, OneArg).WillOnce(Return(100)); |
2854 | EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200)); |
2855 | EXPECT_CALL(helper, TwoArgs).Times(0); |
2856 | |
2857 | EXPECT_EQ(10, helper.NoArgs()); |
2858 | EXPECT_EQ(100, helper.OneArg(1)); |
2859 | EXPECT_EQ(200, helper.OneArg(17)); |
2860 | } |
2861 | |
2862 | // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value |
2863 | // matches the matcher. |
2864 | TEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) { |
2865 | ASSERT_THAT(5, Ge(2)) << "This should succeed." ; |
2866 | ASSERT_THAT("Foo" , EndsWith("oo" )); |
2867 | EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << "This should succeed too." ; |
2868 | EXPECT_THAT("Hello" , StartsWith("Hell" )); |
2869 | } |
2870 | |
2871 | // Tests that ASSERT_THAT() and EXPECT_THAT() work when the value |
2872 | // doesn't match the matcher. |
2873 | TEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) { |
2874 | // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(), |
2875 | // which cannot reference auto variables. |
2876 | static unsigned short n; // NOLINT |
2877 | n = 5; |
2878 | |
2879 | // VC++ prior to version 8.0 SP1 has a bug where it will not see any |
2880 | // functions declared in the namespace scope from within nested classes. |
2881 | // EXPECT/ASSERT_(NON)FATAL_FAILURE macros use nested classes so that all |
2882 | // namespace-level functions invoked inside them need to be explicitly |
2883 | // resolved. |
2884 | EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Gt(10)), |
2885 | "Value of: n\n" |
2886 | "Expected: is > 10\n" |
2887 | " Actual: 5" + OfType("unsigned short" )); |
2888 | n = 0; |
2889 | EXPECT_NONFATAL_FAILURE( |
2890 | EXPECT_THAT(n, ::testing::AllOf(::testing::Le(7), ::testing::Ge(5))), |
2891 | "Value of: n\n" |
2892 | "Expected: (is <= 7) and (is >= 5)\n" |
2893 | " Actual: 0" + OfType("unsigned short" )); |
2894 | } |
2895 | |
2896 | // Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument |
2897 | // has a reference type. |
2898 | TEST(MatcherAssertionTest, WorksForByRefArguments) { |
2899 | // We use a static variable here as EXPECT_FATAL_FAILURE() cannot |
2900 | // reference auto variables. |
2901 | static int n; |
2902 | n = 0; |
2903 | EXPECT_THAT(n, AllOf(Le(7), Ref(n))); |
2904 | EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))), |
2905 | "Value of: n\n" |
2906 | "Expected: does not reference the variable @" ); |
2907 | // Tests the "Actual" part. |
2908 | EXPECT_FATAL_FAILURE(ASSERT_THAT(n, ::testing::Not(::testing::Ref(n))), |
2909 | "Actual: 0" + OfType("int" ) + ", which is located @" ); |
2910 | } |
2911 | |
2912 | // Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is |
2913 | // monomorphic. |
2914 | TEST(MatcherAssertionTest, WorksForMonomorphicMatcher) { |
2915 | Matcher<const char*> starts_with_he = StartsWith("he" ); |
2916 | ASSERT_THAT("hello" , starts_with_he); |
2917 | |
2918 | Matcher<const std::string&> ends_with_ok = EndsWith("ok" ); |
2919 | ASSERT_THAT("book" , ends_with_ok); |
2920 | const std::string bad = "bad" ; |
2921 | EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok), |
2922 | "Value of: bad\n" |
2923 | "Expected: ends with \"ok\"\n" |
2924 | " Actual: \"bad\"" ); |
2925 | Matcher<int> is_greater_than_5 = Gt(5); |
2926 | EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5), |
2927 | "Value of: 5\n" |
2928 | "Expected: is > 5\n" |
2929 | " Actual: 5" + OfType("int" )); |
2930 | } |
2931 | |
2932 | // Tests floating-point matchers. |
2933 | template <typename RawType> |
2934 | class FloatingPointTest : public testing::Test { |
2935 | protected: |
2936 | typedef testing::internal::FloatingPoint<RawType> Floating; |
2937 | typedef typename Floating::Bits Bits; |
2938 | |
2939 | FloatingPointTest() |
2940 | : max_ulps_(Floating::kMaxUlps), |
2941 | zero_bits_(Floating(0).bits()), |
2942 | one_bits_(Floating(1).bits()), |
2943 | infinity_bits_(Floating(Floating::Infinity()).bits()), |
2944 | close_to_positive_zero_( |
2945 | Floating::ReinterpretBits(zero_bits_ + max_ulps_/2)), |
2946 | close_to_negative_zero_( |
2947 | -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_/2)), |
2948 | further_from_negative_zero_(-Floating::ReinterpretBits( |
2949 | zero_bits_ + max_ulps_ + 1 - max_ulps_/2)), |
2950 | close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)), |
2951 | further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)), |
2952 | infinity_(Floating::Infinity()), |
2953 | close_to_infinity_( |
2954 | Floating::ReinterpretBits(infinity_bits_ - max_ulps_)), |
2955 | further_from_infinity_( |
2956 | Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)), |
2957 | max_(Floating::Max()), |
2958 | nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)), |
2959 | nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) { |
2960 | } |
2961 | |
2962 | void TestSize() { |
2963 | EXPECT_EQ(sizeof(RawType), sizeof(Bits)); |
2964 | } |
2965 | |
2966 | // A battery of tests for FloatingEqMatcher::Matches. |
2967 | // matcher_maker is a pointer to a function which creates a FloatingEqMatcher. |
2968 | void TestMatches( |
2969 | testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) { |
2970 | Matcher<RawType> m1 = matcher_maker(0.0); |
2971 | EXPECT_TRUE(m1.Matches(-0.0)); |
2972 | EXPECT_TRUE(m1.Matches(close_to_positive_zero_)); |
2973 | EXPECT_TRUE(m1.Matches(close_to_negative_zero_)); |
2974 | EXPECT_FALSE(m1.Matches(1.0)); |
2975 | |
2976 | Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_); |
2977 | EXPECT_FALSE(m2.Matches(further_from_negative_zero_)); |
2978 | |
2979 | Matcher<RawType> m3 = matcher_maker(1.0); |
2980 | EXPECT_TRUE(m3.Matches(close_to_one_)); |
2981 | EXPECT_FALSE(m3.Matches(further_from_one_)); |
2982 | |
2983 | // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above. |
2984 | EXPECT_FALSE(m3.Matches(0.0)); |
2985 | |
2986 | Matcher<RawType> m4 = matcher_maker(-infinity_); |
2987 | EXPECT_TRUE(m4.Matches(-close_to_infinity_)); |
2988 | |
2989 | Matcher<RawType> m5 = matcher_maker(infinity_); |
2990 | EXPECT_TRUE(m5.Matches(close_to_infinity_)); |
2991 | |
2992 | // This is interesting as the representations of infinity_ and nan1_ |
2993 | // are only 1 DLP apart. |
2994 | EXPECT_FALSE(m5.Matches(nan1_)); |
2995 | |
2996 | // matcher_maker can produce a Matcher<const RawType&>, which is needed in |
2997 | // some cases. |
2998 | Matcher<const RawType&> m6 = matcher_maker(0.0); |
2999 | EXPECT_TRUE(m6.Matches(-0.0)); |
3000 | EXPECT_TRUE(m6.Matches(close_to_positive_zero_)); |
3001 | EXPECT_FALSE(m6.Matches(1.0)); |
3002 | |
3003 | // matcher_maker can produce a Matcher<RawType&>, which is needed in some |
3004 | // cases. |
3005 | Matcher<RawType&> m7 = matcher_maker(0.0); |
3006 | RawType x = 0.0; |
3007 | EXPECT_TRUE(m7.Matches(x)); |
3008 | x = 0.01f; |
3009 | EXPECT_FALSE(m7.Matches(x)); |
3010 | } |
3011 | |
3012 | // Pre-calculated numbers to be used by the tests. |
3013 | |
3014 | const Bits max_ulps_; |
3015 | |
3016 | const Bits zero_bits_; // The bits that represent 0.0. |
3017 | const Bits one_bits_; // The bits that represent 1.0. |
3018 | const Bits infinity_bits_; // The bits that represent +infinity. |
3019 | |
3020 | // Some numbers close to 0.0. |
3021 | const RawType close_to_positive_zero_; |
3022 | const RawType close_to_negative_zero_; |
3023 | const RawType further_from_negative_zero_; |
3024 | |
3025 | // Some numbers close to 1.0. |
3026 | const RawType close_to_one_; |
3027 | const RawType further_from_one_; |
3028 | |
3029 | // Some numbers close to +infinity. |
3030 | const RawType infinity_; |
3031 | const RawType close_to_infinity_; |
3032 | const RawType further_from_infinity_; |
3033 | |
3034 | // Maximum representable value that's not infinity. |
3035 | const RawType max_; |
3036 | |
3037 | // Some NaNs. |
3038 | const RawType nan1_; |
3039 | const RawType nan2_; |
3040 | }; |
3041 | |
3042 | // Tests floating-point matchers with fixed epsilons. |
3043 | template <typename RawType> |
3044 | class FloatingPointNearTest : public FloatingPointTest<RawType> { |
3045 | protected: |
3046 | typedef FloatingPointTest<RawType> ParentType; |
3047 | |
3048 | // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon. |
3049 | // matcher_maker is a pointer to a function which creates a FloatingEqMatcher. |
3050 | void TestNearMatches( |
3051 | testing::internal::FloatingEqMatcher<RawType> |
3052 | (*matcher_maker)(RawType, RawType)) { |
3053 | Matcher<RawType> m1 = matcher_maker(0.0, 0.0); |
3054 | EXPECT_TRUE(m1.Matches(0.0)); |
3055 | EXPECT_TRUE(m1.Matches(-0.0)); |
3056 | EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_)); |
3057 | EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_)); |
3058 | EXPECT_FALSE(m1.Matches(1.0)); |
3059 | |
3060 | Matcher<RawType> m2 = matcher_maker(0.0, 1.0); |
3061 | EXPECT_TRUE(m2.Matches(0.0)); |
3062 | EXPECT_TRUE(m2.Matches(-0.0)); |
3063 | EXPECT_TRUE(m2.Matches(1.0)); |
3064 | EXPECT_TRUE(m2.Matches(-1.0)); |
3065 | EXPECT_FALSE(m2.Matches(ParentType::close_to_one_)); |
3066 | EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_)); |
3067 | |
3068 | // Check that inf matches inf, regardless of the of the specified max |
3069 | // absolute error. |
3070 | Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0); |
3071 | EXPECT_TRUE(m3.Matches(ParentType::infinity_)); |
3072 | EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_)); |
3073 | EXPECT_FALSE(m3.Matches(-ParentType::infinity_)); |
3074 | |
3075 | Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0); |
3076 | EXPECT_TRUE(m4.Matches(-ParentType::infinity_)); |
3077 | EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_)); |
3078 | EXPECT_FALSE(m4.Matches(ParentType::infinity_)); |
3079 | |
3080 | // Test various overflow scenarios. |
3081 | Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_); |
3082 | EXPECT_TRUE(m5.Matches(ParentType::max_)); |
3083 | EXPECT_FALSE(m5.Matches(-ParentType::max_)); |
3084 | |
3085 | Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_); |
3086 | EXPECT_FALSE(m6.Matches(ParentType::max_)); |
3087 | EXPECT_TRUE(m6.Matches(-ParentType::max_)); |
3088 | |
3089 | Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0); |
3090 | EXPECT_TRUE(m7.Matches(ParentType::max_)); |
3091 | EXPECT_FALSE(m7.Matches(-ParentType::max_)); |
3092 | |
3093 | Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0); |
3094 | EXPECT_FALSE(m8.Matches(ParentType::max_)); |
3095 | EXPECT_TRUE(m8.Matches(-ParentType::max_)); |
3096 | |
3097 | // The difference between max() and -max() normally overflows to infinity, |
3098 | // but it should still match if the max_abs_error is also infinity. |
3099 | Matcher<RawType> m9 = matcher_maker( |
3100 | ParentType::max_, ParentType::infinity_); |
3101 | EXPECT_TRUE(m8.Matches(-ParentType::max_)); |
3102 | |
3103 | // matcher_maker can produce a Matcher<const RawType&>, which is needed in |
3104 | // some cases. |
3105 | Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0); |
3106 | EXPECT_TRUE(m10.Matches(-0.0)); |
3107 | EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_)); |
3108 | EXPECT_FALSE(m10.Matches(ParentType::close_to_one_)); |
3109 | |
3110 | // matcher_maker can produce a Matcher<RawType&>, which is needed in some |
3111 | // cases. |
3112 | Matcher<RawType&> m11 = matcher_maker(0.0, 1.0); |
3113 | RawType x = 0.0; |
3114 | EXPECT_TRUE(m11.Matches(x)); |
3115 | x = 1.0f; |
3116 | EXPECT_TRUE(m11.Matches(x)); |
3117 | x = -1.0f; |
3118 | EXPECT_TRUE(m11.Matches(x)); |
3119 | x = 1.1f; |
3120 | EXPECT_FALSE(m11.Matches(x)); |
3121 | x = -1.1f; |
3122 | EXPECT_FALSE(m11.Matches(x)); |
3123 | } |
3124 | }; |
3125 | |
3126 | // Instantiate FloatingPointTest for testing floats. |
3127 | typedef FloatingPointTest<float> FloatTest; |
3128 | |
3129 | TEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) { |
3130 | TestMatches(&FloatEq); |
3131 | } |
3132 | |
3133 | TEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) { |
3134 | TestMatches(&NanSensitiveFloatEq); |
3135 | } |
3136 | |
3137 | TEST_F(FloatTest, FloatEqCannotMatchNaN) { |
3138 | // FloatEq never matches NaN. |
3139 | Matcher<float> m = FloatEq(nan1_); |
3140 | EXPECT_FALSE(m.Matches(nan1_)); |
3141 | EXPECT_FALSE(m.Matches(nan2_)); |
3142 | EXPECT_FALSE(m.Matches(1.0)); |
3143 | } |
3144 | |
3145 | TEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) { |
3146 | // NanSensitiveFloatEq will match NaN. |
3147 | Matcher<float> m = NanSensitiveFloatEq(nan1_); |
3148 | EXPECT_TRUE(m.Matches(nan1_)); |
3149 | EXPECT_TRUE(m.Matches(nan2_)); |
3150 | EXPECT_FALSE(m.Matches(1.0)); |
3151 | } |
3152 | |
3153 | TEST_F(FloatTest, FloatEqCanDescribeSelf) { |
3154 | Matcher<float> m1 = FloatEq(2.0f); |
3155 | EXPECT_EQ("is approximately 2" , Describe(m1)); |
3156 | EXPECT_EQ("isn't approximately 2" , DescribeNegation(m1)); |
3157 | |
3158 | Matcher<float> m2 = FloatEq(0.5f); |
3159 | EXPECT_EQ("is approximately 0.5" , Describe(m2)); |
3160 | EXPECT_EQ("isn't approximately 0.5" , DescribeNegation(m2)); |
3161 | |
3162 | Matcher<float> m3 = FloatEq(nan1_); |
3163 | EXPECT_EQ("never matches" , Describe(m3)); |
3164 | EXPECT_EQ("is anything" , DescribeNegation(m3)); |
3165 | } |
3166 | |
3167 | TEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) { |
3168 | Matcher<float> m1 = NanSensitiveFloatEq(2.0f); |
3169 | EXPECT_EQ("is approximately 2" , Describe(m1)); |
3170 | EXPECT_EQ("isn't approximately 2" , DescribeNegation(m1)); |
3171 | |
3172 | Matcher<float> m2 = NanSensitiveFloatEq(0.5f); |
3173 | EXPECT_EQ("is approximately 0.5" , Describe(m2)); |
3174 | EXPECT_EQ("isn't approximately 0.5" , DescribeNegation(m2)); |
3175 | |
3176 | Matcher<float> m3 = NanSensitiveFloatEq(nan1_); |
3177 | EXPECT_EQ("is NaN" , Describe(m3)); |
3178 | EXPECT_EQ("isn't NaN" , DescribeNegation(m3)); |
3179 | } |
3180 | |
3181 | // Instantiate FloatingPointTest for testing floats with a user-specified |
3182 | // max absolute error. |
3183 | typedef FloatingPointNearTest<float> FloatNearTest; |
3184 | |
3185 | TEST_F(FloatNearTest, FloatNearMatches) { |
3186 | TestNearMatches(&FloatNear); |
3187 | } |
3188 | |
3189 | TEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) { |
3190 | TestNearMatches(&NanSensitiveFloatNear); |
3191 | } |
3192 | |
3193 | TEST_F(FloatNearTest, FloatNearCanDescribeSelf) { |
3194 | Matcher<float> m1 = FloatNear(2.0f, 0.5f); |
3195 | EXPECT_EQ("is approximately 2 (absolute error <= 0.5)" , Describe(m1)); |
3196 | EXPECT_EQ( |
3197 | "isn't approximately 2 (absolute error > 0.5)" , DescribeNegation(m1)); |
3198 | |
3199 | Matcher<float> m2 = FloatNear(0.5f, 0.5f); |
3200 | EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)" , Describe(m2)); |
3201 | EXPECT_EQ( |
3202 | "isn't approximately 0.5 (absolute error > 0.5)" , DescribeNegation(m2)); |
3203 | |
3204 | Matcher<float> m3 = FloatNear(nan1_, 0.0); |
3205 | EXPECT_EQ("never matches" , Describe(m3)); |
3206 | EXPECT_EQ("is anything" , DescribeNegation(m3)); |
3207 | } |
3208 | |
3209 | TEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) { |
3210 | Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f); |
3211 | EXPECT_EQ("is approximately 2 (absolute error <= 0.5)" , Describe(m1)); |
3212 | EXPECT_EQ( |
3213 | "isn't approximately 2 (absolute error > 0.5)" , DescribeNegation(m1)); |
3214 | |
3215 | Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f); |
3216 | EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)" , Describe(m2)); |
3217 | EXPECT_EQ( |
3218 | "isn't approximately 0.5 (absolute error > 0.5)" , DescribeNegation(m2)); |
3219 | |
3220 | Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f); |
3221 | EXPECT_EQ("is NaN" , Describe(m3)); |
3222 | EXPECT_EQ("isn't NaN" , DescribeNegation(m3)); |
3223 | } |
3224 | |
3225 | TEST_F(FloatNearTest, FloatNearCannotMatchNaN) { |
3226 | // FloatNear never matches NaN. |
3227 | Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f); |
3228 | EXPECT_FALSE(m.Matches(nan1_)); |
3229 | EXPECT_FALSE(m.Matches(nan2_)); |
3230 | EXPECT_FALSE(m.Matches(1.0)); |
3231 | } |
3232 | |
3233 | TEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) { |
3234 | // NanSensitiveFloatNear will match NaN. |
3235 | Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f); |
3236 | EXPECT_TRUE(m.Matches(nan1_)); |
3237 | EXPECT_TRUE(m.Matches(nan2_)); |
3238 | EXPECT_FALSE(m.Matches(1.0)); |
3239 | } |
3240 | |
3241 | // Instantiate FloatingPointTest for testing doubles. |
3242 | typedef FloatingPointTest<double> DoubleTest; |
3243 | |
3244 | TEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) { |
3245 | TestMatches(&DoubleEq); |
3246 | } |
3247 | |
3248 | TEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) { |
3249 | TestMatches(&NanSensitiveDoubleEq); |
3250 | } |
3251 | |
3252 | TEST_F(DoubleTest, DoubleEqCannotMatchNaN) { |
3253 | // DoubleEq never matches NaN. |
3254 | Matcher<double> m = DoubleEq(nan1_); |
3255 | EXPECT_FALSE(m.Matches(nan1_)); |
3256 | EXPECT_FALSE(m.Matches(nan2_)); |
3257 | EXPECT_FALSE(m.Matches(1.0)); |
3258 | } |
3259 | |
3260 | TEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) { |
3261 | // NanSensitiveDoubleEq will match NaN. |
3262 | Matcher<double> m = NanSensitiveDoubleEq(nan1_); |
3263 | EXPECT_TRUE(m.Matches(nan1_)); |
3264 | EXPECT_TRUE(m.Matches(nan2_)); |
3265 | EXPECT_FALSE(m.Matches(1.0)); |
3266 | } |
3267 | |
3268 | TEST_F(DoubleTest, DoubleEqCanDescribeSelf) { |
3269 | Matcher<double> m1 = DoubleEq(2.0); |
3270 | EXPECT_EQ("is approximately 2" , Describe(m1)); |
3271 | EXPECT_EQ("isn't approximately 2" , DescribeNegation(m1)); |
3272 | |
3273 | Matcher<double> m2 = DoubleEq(0.5); |
3274 | EXPECT_EQ("is approximately 0.5" , Describe(m2)); |
3275 | EXPECT_EQ("isn't approximately 0.5" , DescribeNegation(m2)); |
3276 | |
3277 | Matcher<double> m3 = DoubleEq(nan1_); |
3278 | EXPECT_EQ("never matches" , Describe(m3)); |
3279 | EXPECT_EQ("is anything" , DescribeNegation(m3)); |
3280 | } |
3281 | |
3282 | TEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) { |
3283 | Matcher<double> m1 = NanSensitiveDoubleEq(2.0); |
3284 | EXPECT_EQ("is approximately 2" , Describe(m1)); |
3285 | EXPECT_EQ("isn't approximately 2" , DescribeNegation(m1)); |
3286 | |
3287 | Matcher<double> m2 = NanSensitiveDoubleEq(0.5); |
3288 | EXPECT_EQ("is approximately 0.5" , Describe(m2)); |
3289 | EXPECT_EQ("isn't approximately 0.5" , DescribeNegation(m2)); |
3290 | |
3291 | Matcher<double> m3 = NanSensitiveDoubleEq(nan1_); |
3292 | EXPECT_EQ("is NaN" , Describe(m3)); |
3293 | EXPECT_EQ("isn't NaN" , DescribeNegation(m3)); |
3294 | } |
3295 | |
3296 | // Instantiate FloatingPointTest for testing floats with a user-specified |
3297 | // max absolute error. |
3298 | typedef FloatingPointNearTest<double> DoubleNearTest; |
3299 | |
3300 | TEST_F(DoubleNearTest, DoubleNearMatches) { |
3301 | TestNearMatches(&DoubleNear); |
3302 | } |
3303 | |
3304 | TEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) { |
3305 | TestNearMatches(&NanSensitiveDoubleNear); |
3306 | } |
3307 | |
3308 | TEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) { |
3309 | Matcher<double> m1 = DoubleNear(2.0, 0.5); |
3310 | EXPECT_EQ("is approximately 2 (absolute error <= 0.5)" , Describe(m1)); |
3311 | EXPECT_EQ( |
3312 | "isn't approximately 2 (absolute error > 0.5)" , DescribeNegation(m1)); |
3313 | |
3314 | Matcher<double> m2 = DoubleNear(0.5, 0.5); |
3315 | EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)" , Describe(m2)); |
3316 | EXPECT_EQ( |
3317 | "isn't approximately 0.5 (absolute error > 0.5)" , DescribeNegation(m2)); |
3318 | |
3319 | Matcher<double> m3 = DoubleNear(nan1_, 0.0); |
3320 | EXPECT_EQ("never matches" , Describe(m3)); |
3321 | EXPECT_EQ("is anything" , DescribeNegation(m3)); |
3322 | } |
3323 | |
3324 | TEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) { |
3325 | EXPECT_EQ("" , Explain(DoubleNear(2.0, 0.1), 2.05)); |
3326 | EXPECT_EQ("which is 0.2 from 2" , Explain(DoubleNear(2.0, 0.1), 2.2)); |
3327 | EXPECT_EQ("which is -0.3 from 2" , Explain(DoubleNear(2.0, 0.1), 1.7)); |
3328 | |
3329 | const std::string explanation = |
3330 | Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10); |
3331 | // Different C++ implementations may print floating-point numbers |
3332 | // slightly differently. |
3333 | EXPECT_TRUE(explanation == "which is 1.2e-10 from 2.1" || // GCC |
3334 | explanation == "which is 1.2e-010 from 2.1" ) // MSVC |
3335 | << " where explanation is \"" << explanation << "\"." ; |
3336 | } |
3337 | |
3338 | TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) { |
3339 | Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5); |
3340 | EXPECT_EQ("is approximately 2 (absolute error <= 0.5)" , Describe(m1)); |
3341 | EXPECT_EQ( |
3342 | "isn't approximately 2 (absolute error > 0.5)" , DescribeNegation(m1)); |
3343 | |
3344 | Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5); |
3345 | EXPECT_EQ("is approximately 0.5 (absolute error <= 0.5)" , Describe(m2)); |
3346 | EXPECT_EQ( |
3347 | "isn't approximately 0.5 (absolute error > 0.5)" , DescribeNegation(m2)); |
3348 | |
3349 | Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1); |
3350 | EXPECT_EQ("is NaN" , Describe(m3)); |
3351 | EXPECT_EQ("isn't NaN" , DescribeNegation(m3)); |
3352 | } |
3353 | |
3354 | TEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) { |
3355 | // DoubleNear never matches NaN. |
3356 | Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1); |
3357 | EXPECT_FALSE(m.Matches(nan1_)); |
3358 | EXPECT_FALSE(m.Matches(nan2_)); |
3359 | EXPECT_FALSE(m.Matches(1.0)); |
3360 | } |
3361 | |
3362 | TEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) { |
3363 | // NanSensitiveDoubleNear will match NaN. |
3364 | Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1); |
3365 | EXPECT_TRUE(m.Matches(nan1_)); |
3366 | EXPECT_TRUE(m.Matches(nan2_)); |
3367 | EXPECT_FALSE(m.Matches(1.0)); |
3368 | } |
3369 | |
3370 | TEST(PointeeTest, RawPointer) { |
3371 | const Matcher<int*> m = Pointee(Ge(0)); |
3372 | |
3373 | int n = 1; |
3374 | EXPECT_TRUE(m.Matches(&n)); |
3375 | n = -1; |
3376 | EXPECT_FALSE(m.Matches(&n)); |
3377 | EXPECT_FALSE(m.Matches(nullptr)); |
3378 | } |
3379 | |
3380 | TEST(PointeeTest, RawPointerToConst) { |
3381 | const Matcher<const double*> m = Pointee(Ge(0)); |
3382 | |
3383 | double x = 1; |
3384 | EXPECT_TRUE(m.Matches(&x)); |
3385 | x = -1; |
3386 | EXPECT_FALSE(m.Matches(&x)); |
3387 | EXPECT_FALSE(m.Matches(nullptr)); |
3388 | } |
3389 | |
3390 | TEST(PointeeTest, ReferenceToConstRawPointer) { |
3391 | const Matcher<int* const &> m = Pointee(Ge(0)); |
3392 | |
3393 | int n = 1; |
3394 | EXPECT_TRUE(m.Matches(&n)); |
3395 | n = -1; |
3396 | EXPECT_FALSE(m.Matches(&n)); |
3397 | EXPECT_FALSE(m.Matches(nullptr)); |
3398 | } |
3399 | |
3400 | TEST(PointeeTest, ReferenceToNonConstRawPointer) { |
3401 | const Matcher<double* &> m = Pointee(Ge(0)); |
3402 | |
3403 | double x = 1.0; |
3404 | double* p = &x; |
3405 | EXPECT_TRUE(m.Matches(p)); |
3406 | x = -1; |
3407 | EXPECT_FALSE(m.Matches(p)); |
3408 | p = nullptr; |
3409 | EXPECT_FALSE(m.Matches(p)); |
3410 | } |
3411 | |
3412 | MATCHER_P(FieldIIs, inner_matcher, "" ) { |
3413 | return ExplainMatchResult(inner_matcher, arg.i, result_listener); |
3414 | } |
3415 | |
3416 | #if GTEST_HAS_RTTI |
3417 | TEST(WhenDynamicCastToTest, SameType) { |
3418 | Derived derived; |
3419 | derived.i = 4; |
3420 | |
3421 | // Right type. A pointer is passed down. |
3422 | Base* as_base_ptr = &derived; |
3423 | EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull()))); |
3424 | EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4)))); |
3425 | EXPECT_THAT(as_base_ptr, |
3426 | Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5))))); |
3427 | } |
3428 | |
3429 | TEST(WhenDynamicCastToTest, WrongTypes) { |
3430 | Base base; |
3431 | Derived derived; |
3432 | OtherDerived other_derived; |
3433 | |
3434 | // Wrong types. NULL is passed. |
3435 | EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_)))); |
3436 | EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull())); |
3437 | Base* as_base_ptr = &derived; |
3438 | EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_)))); |
3439 | EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull())); |
3440 | as_base_ptr = &other_derived; |
3441 | EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_)))); |
3442 | EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull())); |
3443 | } |
3444 | |
3445 | TEST(WhenDynamicCastToTest, AlreadyNull) { |
3446 | // Already NULL. |
3447 | Base* as_base_ptr = nullptr; |
3448 | EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull())); |
3449 | } |
3450 | |
3451 | struct AmbiguousCastTypes { |
3452 | class VirtualDerived : public virtual Base {}; |
3453 | class DerivedSub1 : public VirtualDerived {}; |
3454 | class DerivedSub2 : public VirtualDerived {}; |
3455 | class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {}; |
3456 | }; |
3457 | |
3458 | TEST(WhenDynamicCastToTest, AmbiguousCast) { |
3459 | AmbiguousCastTypes::DerivedSub1 sub1; |
3460 | AmbiguousCastTypes::ManyDerivedInHierarchy many_derived; |
3461 | // Multiply derived from Base. dynamic_cast<> returns NULL. |
3462 | Base* as_base_ptr = |
3463 | static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived); |
3464 | EXPECT_THAT(as_base_ptr, |
3465 | WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull())); |
3466 | as_base_ptr = &sub1; |
3467 | EXPECT_THAT( |
3468 | as_base_ptr, |
3469 | WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull()))); |
3470 | } |
3471 | |
3472 | TEST(WhenDynamicCastToTest, Describe) { |
3473 | Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_)); |
3474 | const std::string prefix = |
3475 | "when dynamic_cast to " + internal::GetTypeName<Derived*>() + ", " ; |
3476 | EXPECT_EQ(prefix + "points to a value that is anything" , Describe(matcher)); |
3477 | EXPECT_EQ(prefix + "does not point to a value that is anything" , |
3478 | DescribeNegation(matcher)); |
3479 | } |
3480 | |
3481 | TEST(WhenDynamicCastToTest, Explain) { |
3482 | Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_)); |
3483 | Base* null = nullptr; |
3484 | EXPECT_THAT(Explain(matcher, null), HasSubstr("NULL" )); |
3485 | Derived derived; |
3486 | EXPECT_TRUE(matcher.Matches(&derived)); |
3487 | EXPECT_THAT(Explain(matcher, &derived), HasSubstr("which points to " )); |
3488 | |
3489 | // With references, the matcher itself can fail. Test for that one. |
3490 | Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_); |
3491 | EXPECT_THAT(Explain(ref_matcher, derived), |
3492 | HasSubstr("which cannot be dynamic_cast" )); |
3493 | } |
3494 | |
3495 | TEST(WhenDynamicCastToTest, GoodReference) { |
3496 | Derived derived; |
3497 | derived.i = 4; |
3498 | Base& as_base_ref = derived; |
3499 | EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4))); |
3500 | EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5)))); |
3501 | } |
3502 | |
3503 | TEST(WhenDynamicCastToTest, BadReference) { |
3504 | Derived derived; |
3505 | Base& as_base_ref = derived; |
3506 | EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_))); |
3507 | } |
3508 | #endif // GTEST_HAS_RTTI |
3509 | |
3510 | // Minimal const-propagating pointer. |
3511 | template <typename T> |
3512 | class ConstPropagatingPtr { |
3513 | public: |
3514 | typedef T element_type; |
3515 | |
3516 | ConstPropagatingPtr() : val_() {} |
3517 | explicit ConstPropagatingPtr(T* t) : val_(t) {} |
3518 | ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {} |
3519 | |
3520 | T* get() { return val_; } |
3521 | T& operator*() { return *val_; } |
3522 | // Most smart pointers return non-const T* and T& from the next methods. |
3523 | const T* get() const { return val_; } |
3524 | const T& operator*() const { return *val_; } |
3525 | |
3526 | private: |
3527 | T* val_; |
3528 | }; |
3529 | |
3530 | TEST(PointeeTest, WorksWithConstPropagatingPointers) { |
3531 | const Matcher< ConstPropagatingPtr<int> > m = Pointee(Lt(5)); |
3532 | int three = 3; |
3533 | const ConstPropagatingPtr<int> co(&three); |
3534 | ConstPropagatingPtr<int> o(&three); |
3535 | EXPECT_TRUE(m.Matches(o)); |
3536 | EXPECT_TRUE(m.Matches(co)); |
3537 | *o = 6; |
3538 | EXPECT_FALSE(m.Matches(o)); |
3539 | EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>())); |
3540 | } |
3541 | |
3542 | TEST(PointeeTest, NeverMatchesNull) { |
3543 | const Matcher<const char*> m = Pointee(_); |
3544 | EXPECT_FALSE(m.Matches(nullptr)); |
3545 | } |
3546 | |
3547 | // Tests that we can write Pointee(value) instead of Pointee(Eq(value)). |
3548 | TEST(PointeeTest, MatchesAgainstAValue) { |
3549 | const Matcher<int*> m = Pointee(5); |
3550 | |
3551 | int n = 5; |
3552 | EXPECT_TRUE(m.Matches(&n)); |
3553 | n = -1; |
3554 | EXPECT_FALSE(m.Matches(&n)); |
3555 | EXPECT_FALSE(m.Matches(nullptr)); |
3556 | } |
3557 | |
3558 | TEST(PointeeTest, CanDescribeSelf) { |
3559 | const Matcher<int*> m = Pointee(Gt(3)); |
3560 | EXPECT_EQ("points to a value that is > 3" , Describe(m)); |
3561 | EXPECT_EQ("does not point to a value that is > 3" , |
3562 | DescribeNegation(m)); |
3563 | } |
3564 | |
3565 | TEST(PointeeTest, CanExplainMatchResult) { |
3566 | const Matcher<const std::string*> m = Pointee(StartsWith("Hi" )); |
3567 | |
3568 | EXPECT_EQ("" , Explain(m, static_cast<const std::string*>(nullptr))); |
3569 | |
3570 | const Matcher<long*> m2 = Pointee(GreaterThan(1)); // NOLINT |
3571 | long n = 3; // NOLINT |
3572 | EXPECT_EQ("which points to 3" + OfType("long" ) + ", which is 2 more than 1" , |
3573 | Explain(m2, &n)); |
3574 | } |
3575 | |
3576 | TEST(PointeeTest, AlwaysExplainsPointee) { |
3577 | const Matcher<int*> m = Pointee(0); |
3578 | int n = 42; |
3579 | EXPECT_EQ("which points to 42" + OfType("int" ), Explain(m, &n)); |
3580 | } |
3581 | |
3582 | // An uncopyable class. |
3583 | class Uncopyable { |
3584 | public: |
3585 | Uncopyable() : value_(-1) {} |
3586 | explicit Uncopyable(int a_value) : value_(a_value) {} |
3587 | |
3588 | int value() const { return value_; } |
3589 | void set_value(int i) { value_ = i; } |
3590 | |
3591 | private: |
3592 | int value_; |
3593 | GTEST_DISALLOW_COPY_AND_ASSIGN_(Uncopyable); |
3594 | }; |
3595 | |
3596 | // Returns true if and only if x.value() is positive. |
3597 | bool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; } |
3598 | |
3599 | MATCHER_P(UncopyableIs, inner_matcher, "" ) { |
3600 | return ExplainMatchResult(inner_matcher, arg.value(), result_listener); |
3601 | } |
3602 | |
3603 | // A user-defined struct for testing Field(). |
3604 | struct AStruct { |
3605 | AStruct() : x(0), y(1.0), z(5), p(nullptr) {} |
3606 | AStruct(const AStruct& rhs) |
3607 | : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {} |
3608 | |
3609 | int x; // A non-const field. |
3610 | const double y; // A const field. |
3611 | Uncopyable z; // An uncopyable field. |
3612 | const char* p; // A pointer field. |
3613 | |
3614 | private: |
3615 | GTEST_DISALLOW_ASSIGN_(AStruct); |
3616 | }; |
3617 | |
3618 | // A derived struct for testing Field(). |
3619 | struct DerivedStruct : public AStruct { |
3620 | char ch; |
3621 | |
3622 | private: |
3623 | GTEST_DISALLOW_ASSIGN_(DerivedStruct); |
3624 | }; |
3625 | |
3626 | // Tests that Field(&Foo::field, ...) works when field is non-const. |
3627 | TEST(FieldTest, WorksForNonConstField) { |
3628 | Matcher<AStruct> m = Field(&AStruct::x, Ge(0)); |
3629 | Matcher<AStruct> m_with_name = Field("x" , &AStruct::x, Ge(0)); |
3630 | |
3631 | AStruct a; |
3632 | EXPECT_TRUE(m.Matches(a)); |
3633 | EXPECT_TRUE(m_with_name.Matches(a)); |
3634 | a.x = -1; |
3635 | EXPECT_FALSE(m.Matches(a)); |
3636 | EXPECT_FALSE(m_with_name.Matches(a)); |
3637 | } |
3638 | |
3639 | // Tests that Field(&Foo::field, ...) works when field is const. |
3640 | TEST(FieldTest, WorksForConstField) { |
3641 | AStruct a; |
3642 | |
3643 | Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0)); |
3644 | Matcher<AStruct> m_with_name = Field("y" , &AStruct::y, Ge(0.0)); |
3645 | EXPECT_TRUE(m.Matches(a)); |
3646 | EXPECT_TRUE(m_with_name.Matches(a)); |
3647 | m = Field(&AStruct::y, Le(0.0)); |
3648 | m_with_name = Field("y" , &AStruct::y, Le(0.0)); |
3649 | EXPECT_FALSE(m.Matches(a)); |
3650 | EXPECT_FALSE(m_with_name.Matches(a)); |
3651 | } |
3652 | |
3653 | // Tests that Field(&Foo::field, ...) works when field is not copyable. |
3654 | TEST(FieldTest, WorksForUncopyableField) { |
3655 | AStruct a; |
3656 | |
3657 | Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive)); |
3658 | EXPECT_TRUE(m.Matches(a)); |
3659 | m = Field(&AStruct::z, Not(Truly(ValueIsPositive))); |
3660 | EXPECT_FALSE(m.Matches(a)); |
3661 | } |
3662 | |
3663 | // Tests that Field(&Foo::field, ...) works when field is a pointer. |
3664 | TEST(FieldTest, WorksForPointerField) { |
3665 | // Matching against NULL. |
3666 | Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr)); |
3667 | AStruct a; |
3668 | EXPECT_TRUE(m.Matches(a)); |
3669 | a.p = "hi" ; |
3670 | EXPECT_FALSE(m.Matches(a)); |
3671 | |
3672 | // Matching a pointer that is not NULL. |
3673 | m = Field(&AStruct::p, StartsWith("hi" )); |
3674 | a.p = "hill" ; |
3675 | EXPECT_TRUE(m.Matches(a)); |
3676 | a.p = "hole" ; |
3677 | EXPECT_FALSE(m.Matches(a)); |
3678 | } |
3679 | |
3680 | // Tests that Field() works when the object is passed by reference. |
3681 | TEST(FieldTest, WorksForByRefArgument) { |
3682 | Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0)); |
3683 | |
3684 | AStruct a; |
3685 | EXPECT_TRUE(m.Matches(a)); |
3686 | a.x = -1; |
3687 | EXPECT_FALSE(m.Matches(a)); |
3688 | } |
3689 | |
3690 | // Tests that Field(&Foo::field, ...) works when the argument's type |
3691 | // is a sub-type of Foo. |
3692 | TEST(FieldTest, WorksForArgumentOfSubType) { |
3693 | // Note that the matcher expects DerivedStruct but we say AStruct |
3694 | // inside Field(). |
3695 | Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0)); |
3696 | |
3697 | DerivedStruct d; |
3698 | EXPECT_TRUE(m.Matches(d)); |
3699 | d.x = -1; |
3700 | EXPECT_FALSE(m.Matches(d)); |
3701 | } |
3702 | |
3703 | // Tests that Field(&Foo::field, m) works when field's type and m's |
3704 | // argument type are compatible but not the same. |
3705 | TEST(FieldTest, WorksForCompatibleMatcherType) { |
3706 | // The field is an int, but the inner matcher expects a signed char. |
3707 | Matcher<const AStruct&> m = Field(&AStruct::x, |
3708 | Matcher<signed char>(Ge(0))); |
3709 | |
3710 | AStruct a; |
3711 | EXPECT_TRUE(m.Matches(a)); |
3712 | a.x = -1; |
3713 | EXPECT_FALSE(m.Matches(a)); |
3714 | } |
3715 | |
3716 | // Tests that Field() can describe itself. |
3717 | TEST(FieldTest, CanDescribeSelf) { |
3718 | Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0)); |
3719 | |
3720 | EXPECT_EQ("is an object whose given field is >= 0" , Describe(m)); |
3721 | EXPECT_EQ("is an object whose given field isn't >= 0" , DescribeNegation(m)); |
3722 | } |
3723 | |
3724 | TEST(FieldTest, CanDescribeSelfWithFieldName) { |
3725 | Matcher<const AStruct&> m = Field("field_name" , &AStruct::x, Ge(0)); |
3726 | |
3727 | EXPECT_EQ("is an object whose field `field_name` is >= 0" , Describe(m)); |
3728 | EXPECT_EQ("is an object whose field `field_name` isn't >= 0" , |
3729 | DescribeNegation(m)); |
3730 | } |
3731 | |
3732 | // Tests that Field() can explain the match result. |
3733 | TEST(FieldTest, CanExplainMatchResult) { |
3734 | Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0)); |
3735 | |
3736 | AStruct a; |
3737 | a.x = 1; |
3738 | EXPECT_EQ("whose given field is 1" + OfType("int" ), Explain(m, a)); |
3739 | |
3740 | m = Field(&AStruct::x, GreaterThan(0)); |
3741 | EXPECT_EQ( |
3742 | "whose given field is 1" + OfType("int" ) + ", which is 1 more than 0" , |
3743 | Explain(m, a)); |
3744 | } |
3745 | |
3746 | TEST(FieldTest, CanExplainMatchResultWithFieldName) { |
3747 | Matcher<const AStruct&> m = Field("field_name" , &AStruct::x, Ge(0)); |
3748 | |
3749 | AStruct a; |
3750 | a.x = 1; |
3751 | EXPECT_EQ("whose field `field_name` is 1" + OfType("int" ), Explain(m, a)); |
3752 | |
3753 | m = Field("field_name" , &AStruct::x, GreaterThan(0)); |
3754 | EXPECT_EQ("whose field `field_name` is 1" + OfType("int" ) + |
3755 | ", which is 1 more than 0" , |
3756 | Explain(m, a)); |
3757 | } |
3758 | |
3759 | // Tests that Field() works when the argument is a pointer to const. |
3760 | TEST(FieldForPointerTest, WorksForPointerToConst) { |
3761 | Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0)); |
3762 | |
3763 | AStruct a; |
3764 | EXPECT_TRUE(m.Matches(&a)); |
3765 | a.x = -1; |
3766 | EXPECT_FALSE(m.Matches(&a)); |
3767 | } |
3768 | |
3769 | // Tests that Field() works when the argument is a pointer to non-const. |
3770 | TEST(FieldForPointerTest, WorksForPointerToNonConst) { |
3771 | Matcher<AStruct*> m = Field(&AStruct::x, Ge(0)); |
3772 | |
3773 | AStruct a; |
3774 | EXPECT_TRUE(m.Matches(&a)); |
3775 | a.x = -1; |
3776 | EXPECT_FALSE(m.Matches(&a)); |
3777 | } |
3778 | |
3779 | // Tests that Field() works when the argument is a reference to a const pointer. |
3780 | TEST(FieldForPointerTest, WorksForReferenceToConstPointer) { |
3781 | Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0)); |
3782 | |
3783 | AStruct a; |
3784 | EXPECT_TRUE(m.Matches(&a)); |
3785 | a.x = -1; |
3786 | EXPECT_FALSE(m.Matches(&a)); |
3787 | } |
3788 | |
3789 | // Tests that Field() does not match the NULL pointer. |
3790 | TEST(FieldForPointerTest, DoesNotMatchNull) { |
3791 | Matcher<const AStruct*> m = Field(&AStruct::x, _); |
3792 | EXPECT_FALSE(m.Matches(nullptr)); |
3793 | } |
3794 | |
3795 | // Tests that Field(&Foo::field, ...) works when the argument's type |
3796 | // is a sub-type of const Foo*. |
3797 | TEST(FieldForPointerTest, WorksForArgumentOfSubType) { |
3798 | // Note that the matcher expects DerivedStruct but we say AStruct |
3799 | // inside Field(). |
3800 | Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0)); |
3801 | |
3802 | DerivedStruct d; |
3803 | EXPECT_TRUE(m.Matches(&d)); |
3804 | d.x = -1; |
3805 | EXPECT_FALSE(m.Matches(&d)); |
3806 | } |
3807 | |
3808 | // Tests that Field() can describe itself when used to match a pointer. |
3809 | TEST(FieldForPointerTest, CanDescribeSelf) { |
3810 | Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0)); |
3811 | |
3812 | EXPECT_EQ("is an object whose given field is >= 0" , Describe(m)); |
3813 | EXPECT_EQ("is an object whose given field isn't >= 0" , DescribeNegation(m)); |
3814 | } |
3815 | |
3816 | TEST(FieldForPointerTest, CanDescribeSelfWithFieldName) { |
3817 | Matcher<const AStruct*> m = Field("field_name" , &AStruct::x, Ge(0)); |
3818 | |
3819 | EXPECT_EQ("is an object whose field `field_name` is >= 0" , Describe(m)); |
3820 | EXPECT_EQ("is an object whose field `field_name` isn't >= 0" , |
3821 | DescribeNegation(m)); |
3822 | } |
3823 | |
3824 | // Tests that Field() can explain the result of matching a pointer. |
3825 | TEST(FieldForPointerTest, CanExplainMatchResult) { |
3826 | Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0)); |
3827 | |
3828 | AStruct a; |
3829 | a.x = 1; |
3830 | EXPECT_EQ("" , Explain(m, static_cast<const AStruct*>(nullptr))); |
3831 | EXPECT_EQ("which points to an object whose given field is 1" + OfType("int" ), |
3832 | Explain(m, &a)); |
3833 | |
3834 | m = Field(&AStruct::x, GreaterThan(0)); |
3835 | EXPECT_EQ("which points to an object whose given field is 1" + OfType("int" ) + |
3836 | ", which is 1 more than 0" , Explain(m, &a)); |
3837 | } |
3838 | |
3839 | TEST(FieldForPointerTest, CanExplainMatchResultWithFieldName) { |
3840 | Matcher<const AStruct*> m = Field("field_name" , &AStruct::x, Ge(0)); |
3841 | |
3842 | AStruct a; |
3843 | a.x = 1; |
3844 | EXPECT_EQ("" , Explain(m, static_cast<const AStruct*>(nullptr))); |
3845 | EXPECT_EQ( |
3846 | "which points to an object whose field `field_name` is 1" + OfType("int" ), |
3847 | Explain(m, &a)); |
3848 | |
3849 | m = Field("field_name" , &AStruct::x, GreaterThan(0)); |
3850 | EXPECT_EQ("which points to an object whose field `field_name` is 1" + |
3851 | OfType("int" ) + ", which is 1 more than 0" , |
3852 | Explain(m, &a)); |
3853 | } |
3854 | |
3855 | // A user-defined class for testing Property(). |
3856 | class AClass { |
3857 | public: |
3858 | AClass() : n_(0) {} |
3859 | |
3860 | // A getter that returns a non-reference. |
3861 | int n() const { return n_; } |
3862 | |
3863 | void set_n(int new_n) { n_ = new_n; } |
3864 | |
3865 | // A getter that returns a reference to const. |
3866 | const std::string& s() const { return s_; } |
3867 | |
3868 | const std::string& s_ref() const & { return s_; } |
3869 | |
3870 | void set_s(const std::string& new_s) { s_ = new_s; } |
3871 | |
3872 | // A getter that returns a reference to non-const. |
3873 | double& x() const { return x_; } |
3874 | |
3875 | private: |
3876 | int n_; |
3877 | std::string s_; |
3878 | |
3879 | static double x_; |
3880 | }; |
3881 | |
3882 | double AClass::x_ = 0.0; |
3883 | |
3884 | // A derived class for testing Property(). |
3885 | class DerivedClass : public AClass { |
3886 | public: |
3887 | int k() const { return k_; } |
3888 | private: |
3889 | int k_; |
3890 | }; |
3891 | |
3892 | // Tests that Property(&Foo::property, ...) works when property() |
3893 | // returns a non-reference. |
3894 | TEST(PropertyTest, WorksForNonReferenceProperty) { |
3895 | Matcher<const AClass&> m = Property(&AClass::n, Ge(0)); |
3896 | Matcher<const AClass&> m_with_name = Property("n" , &AClass::n, Ge(0)); |
3897 | |
3898 | AClass a; |
3899 | a.set_n(1); |
3900 | EXPECT_TRUE(m.Matches(a)); |
3901 | EXPECT_TRUE(m_with_name.Matches(a)); |
3902 | |
3903 | a.set_n(-1); |
3904 | EXPECT_FALSE(m.Matches(a)); |
3905 | EXPECT_FALSE(m_with_name.Matches(a)); |
3906 | } |
3907 | |
3908 | // Tests that Property(&Foo::property, ...) works when property() |
3909 | // returns a reference to const. |
3910 | TEST(PropertyTest, WorksForReferenceToConstProperty) { |
3911 | Matcher<const AClass&> m = Property(&AClass::s, StartsWith("hi" )); |
3912 | Matcher<const AClass&> m_with_name = |
3913 | Property("s" , &AClass::s, StartsWith("hi" )); |
3914 | |
3915 | AClass a; |
3916 | a.set_s("hill" ); |
3917 | EXPECT_TRUE(m.Matches(a)); |
3918 | EXPECT_TRUE(m_with_name.Matches(a)); |
3919 | |
3920 | a.set_s("hole" ); |
3921 | EXPECT_FALSE(m.Matches(a)); |
3922 | EXPECT_FALSE(m_with_name.Matches(a)); |
3923 | } |
3924 | |
3925 | // Tests that Property(&Foo::property, ...) works when property() is |
3926 | // ref-qualified. |
3927 | TEST(PropertyTest, WorksForRefQualifiedProperty) { |
3928 | Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith("hi" )); |
3929 | Matcher<const AClass&> m_with_name = |
3930 | Property("s" , &AClass::s_ref, StartsWith("hi" )); |
3931 | |
3932 | AClass a; |
3933 | a.set_s("hill" ); |
3934 | EXPECT_TRUE(m.Matches(a)); |
3935 | EXPECT_TRUE(m_with_name.Matches(a)); |
3936 | |
3937 | a.set_s("hole" ); |
3938 | EXPECT_FALSE(m.Matches(a)); |
3939 | EXPECT_FALSE(m_with_name.Matches(a)); |
3940 | } |
3941 | |
3942 | // Tests that Property(&Foo::property, ...) works when property() |
3943 | // returns a reference to non-const. |
3944 | TEST(PropertyTest, WorksForReferenceToNonConstProperty) { |
3945 | double x = 0.0; |
3946 | AClass a; |
3947 | |
3948 | Matcher<const AClass&> m = Property(&AClass::x, Ref(x)); |
3949 | EXPECT_FALSE(m.Matches(a)); |
3950 | |
3951 | m = Property(&AClass::x, Not(Ref(x))); |
3952 | EXPECT_TRUE(m.Matches(a)); |
3953 | } |
3954 | |
3955 | // Tests that Property(&Foo::property, ...) works when the argument is |
3956 | // passed by value. |
3957 | TEST(PropertyTest, WorksForByValueArgument) { |
3958 | Matcher<AClass> m = Property(&AClass::s, StartsWith("hi" )); |
3959 | |
3960 | AClass a; |
3961 | a.set_s("hill" ); |
3962 | EXPECT_TRUE(m.Matches(a)); |
3963 | |
3964 | a.set_s("hole" ); |
3965 | EXPECT_FALSE(m.Matches(a)); |
3966 | } |
3967 | |
3968 | // Tests that Property(&Foo::property, ...) works when the argument's |
3969 | // type is a sub-type of Foo. |
3970 | TEST(PropertyTest, WorksForArgumentOfSubType) { |
3971 | // The matcher expects a DerivedClass, but inside the Property() we |
3972 | // say AClass. |
3973 | Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0)); |
3974 | |
3975 | DerivedClass d; |
3976 | d.set_n(1); |
3977 | EXPECT_TRUE(m.Matches(d)); |
3978 | |
3979 | d.set_n(-1); |
3980 | EXPECT_FALSE(m.Matches(d)); |
3981 | } |
3982 | |
3983 | // Tests that Property(&Foo::property, m) works when property()'s type |
3984 | // and m's argument type are compatible but different. |
3985 | TEST(PropertyTest, WorksForCompatibleMatcherType) { |
3986 | // n() returns an int but the inner matcher expects a signed char. |
3987 | Matcher<const AClass&> m = Property(&AClass::n, |
3988 | Matcher<signed char>(Ge(0))); |
3989 | |
3990 | Matcher<const AClass&> m_with_name = |
3991 | Property("n" , &AClass::n, Matcher<signed char>(Ge(0))); |
3992 | |
3993 | AClass a; |
3994 | EXPECT_TRUE(m.Matches(a)); |
3995 | EXPECT_TRUE(m_with_name.Matches(a)); |
3996 | a.set_n(-1); |
3997 | EXPECT_FALSE(m.Matches(a)); |
3998 | EXPECT_FALSE(m_with_name.Matches(a)); |
3999 | } |
4000 | |
4001 | // Tests that Property() can describe itself. |
4002 | TEST(PropertyTest, CanDescribeSelf) { |
4003 | Matcher<const AClass&> m = Property(&AClass::n, Ge(0)); |
4004 | |
4005 | EXPECT_EQ("is an object whose given property is >= 0" , Describe(m)); |
4006 | EXPECT_EQ("is an object whose given property isn't >= 0" , |
4007 | DescribeNegation(m)); |
4008 | } |
4009 | |
4010 | TEST(PropertyTest, CanDescribeSelfWithPropertyName) { |
4011 | Matcher<const AClass&> m = Property("fancy_name" , &AClass::n, Ge(0)); |
4012 | |
4013 | EXPECT_EQ("is an object whose property `fancy_name` is >= 0" , Describe(m)); |
4014 | EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0" , |
4015 | DescribeNegation(m)); |
4016 | } |
4017 | |
4018 | // Tests that Property() can explain the match result. |
4019 | TEST(PropertyTest, CanExplainMatchResult) { |
4020 | Matcher<const AClass&> m = Property(&AClass::n, Ge(0)); |
4021 | |
4022 | AClass a; |
4023 | a.set_n(1); |
4024 | EXPECT_EQ("whose given property is 1" + OfType("int" ), Explain(m, a)); |
4025 | |
4026 | m = Property(&AClass::n, GreaterThan(0)); |
4027 | EXPECT_EQ( |
4028 | "whose given property is 1" + OfType("int" ) + ", which is 1 more than 0" , |
4029 | Explain(m, a)); |
4030 | } |
4031 | |
4032 | TEST(PropertyTest, CanExplainMatchResultWithPropertyName) { |
4033 | Matcher<const AClass&> m = Property("fancy_name" , &AClass::n, Ge(0)); |
4034 | |
4035 | AClass a; |
4036 | a.set_n(1); |
4037 | EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int" ), Explain(m, a)); |
4038 | |
4039 | m = Property("fancy_name" , &AClass::n, GreaterThan(0)); |
4040 | EXPECT_EQ("whose property `fancy_name` is 1" + OfType("int" ) + |
4041 | ", which is 1 more than 0" , |
4042 | Explain(m, a)); |
4043 | } |
4044 | |
4045 | // Tests that Property() works when the argument is a pointer to const. |
4046 | TEST(PropertyForPointerTest, WorksForPointerToConst) { |
4047 | Matcher<const AClass*> m = Property(&AClass::n, Ge(0)); |
4048 | |
4049 | AClass a; |
4050 | a.set_n(1); |
4051 | EXPECT_TRUE(m.Matches(&a)); |
4052 | |
4053 | a.set_n(-1); |
4054 | EXPECT_FALSE(m.Matches(&a)); |
4055 | } |
4056 | |
4057 | // Tests that Property() works when the argument is a pointer to non-const. |
4058 | TEST(PropertyForPointerTest, WorksForPointerToNonConst) { |
4059 | Matcher<AClass*> m = Property(&AClass::s, StartsWith("hi" )); |
4060 | |
4061 | AClass a; |
4062 | a.set_s("hill" ); |
4063 | EXPECT_TRUE(m.Matches(&a)); |
4064 | |
4065 | a.set_s("hole" ); |
4066 | EXPECT_FALSE(m.Matches(&a)); |
4067 | } |
4068 | |
4069 | // Tests that Property() works when the argument is a reference to a |
4070 | // const pointer. |
4071 | TEST(PropertyForPointerTest, WorksForReferenceToConstPointer) { |
4072 | Matcher<AClass* const&> m = Property(&AClass::s, StartsWith("hi" )); |
4073 | |
4074 | AClass a; |
4075 | a.set_s("hill" ); |
4076 | EXPECT_TRUE(m.Matches(&a)); |
4077 | |
4078 | a.set_s("hole" ); |
4079 | EXPECT_FALSE(m.Matches(&a)); |
4080 | } |
4081 | |
4082 | // Tests that Property() does not match the NULL pointer. |
4083 | TEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) { |
4084 | Matcher<const AClass*> m = Property(&AClass::x, _); |
4085 | EXPECT_FALSE(m.Matches(nullptr)); |
4086 | } |
4087 | |
4088 | // Tests that Property(&Foo::property, ...) works when the argument's |
4089 | // type is a sub-type of const Foo*. |
4090 | TEST(PropertyForPointerTest, WorksForArgumentOfSubType) { |
4091 | // The matcher expects a DerivedClass, but inside the Property() we |
4092 | // say AClass. |
4093 | Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0)); |
4094 | |
4095 | DerivedClass d; |
4096 | d.set_n(1); |
4097 | EXPECT_TRUE(m.Matches(&d)); |
4098 | |
4099 | d.set_n(-1); |
4100 | EXPECT_FALSE(m.Matches(&d)); |
4101 | } |
4102 | |
4103 | // Tests that Property() can describe itself when used to match a pointer. |
4104 | TEST(PropertyForPointerTest, CanDescribeSelf) { |
4105 | Matcher<const AClass*> m = Property(&AClass::n, Ge(0)); |
4106 | |
4107 | EXPECT_EQ("is an object whose given property is >= 0" , Describe(m)); |
4108 | EXPECT_EQ("is an object whose given property isn't >= 0" , |
4109 | DescribeNegation(m)); |
4110 | } |
4111 | |
4112 | TEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) { |
4113 | Matcher<const AClass*> m = Property("fancy_name" , &AClass::n, Ge(0)); |
4114 | |
4115 | EXPECT_EQ("is an object whose property `fancy_name` is >= 0" , Describe(m)); |
4116 | EXPECT_EQ("is an object whose property `fancy_name` isn't >= 0" , |
4117 | DescribeNegation(m)); |
4118 | } |
4119 | |
4120 | // Tests that Property() can explain the result of matching a pointer. |
4121 | TEST(PropertyForPointerTest, CanExplainMatchResult) { |
4122 | Matcher<const AClass*> m = Property(&AClass::n, Ge(0)); |
4123 | |
4124 | AClass a; |
4125 | a.set_n(1); |
4126 | EXPECT_EQ("" , Explain(m, static_cast<const AClass*>(nullptr))); |
4127 | EXPECT_EQ( |
4128 | "which points to an object whose given property is 1" + OfType("int" ), |
4129 | Explain(m, &a)); |
4130 | |
4131 | m = Property(&AClass::n, GreaterThan(0)); |
4132 | EXPECT_EQ("which points to an object whose given property is 1" + |
4133 | OfType("int" ) + ", which is 1 more than 0" , |
4134 | Explain(m, &a)); |
4135 | } |
4136 | |
4137 | TEST(PropertyForPointerTest, CanExplainMatchResultWithPropertyName) { |
4138 | Matcher<const AClass*> m = Property("fancy_name" , &AClass::n, Ge(0)); |
4139 | |
4140 | AClass a; |
4141 | a.set_n(1); |
4142 | EXPECT_EQ("" , Explain(m, static_cast<const AClass*>(nullptr))); |
4143 | EXPECT_EQ("which points to an object whose property `fancy_name` is 1" + |
4144 | OfType("int" ), |
4145 | Explain(m, &a)); |
4146 | |
4147 | m = Property("fancy_name" , &AClass::n, GreaterThan(0)); |
4148 | EXPECT_EQ("which points to an object whose property `fancy_name` is 1" + |
4149 | OfType("int" ) + ", which is 1 more than 0" , |
4150 | Explain(m, &a)); |
4151 | } |
4152 | |
4153 | // Tests ResultOf. |
4154 | |
4155 | // Tests that ResultOf(f, ...) compiles and works as expected when f is a |
4156 | // function pointer. |
4157 | std::string IntToStringFunction(int input) { |
4158 | return input == 1 ? "foo" : "bar" ; |
4159 | } |
4160 | |
4161 | TEST(ResultOfTest, WorksForFunctionPointers) { |
4162 | Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string("foo" ))); |
4163 | |
4164 | EXPECT_TRUE(matcher.Matches(1)); |
4165 | EXPECT_FALSE(matcher.Matches(2)); |
4166 | } |
4167 | |
4168 | // Tests that ResultOf() can describe itself. |
4169 | TEST(ResultOfTest, CanDescribeItself) { |
4170 | Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq("foo" )); |
4171 | |
4172 | EXPECT_EQ("is mapped by the given callable to a value that " |
4173 | "is equal to \"foo\"" , Describe(matcher)); |
4174 | EXPECT_EQ("is mapped by the given callable to a value that " |
4175 | "isn't equal to \"foo\"" , DescribeNegation(matcher)); |
4176 | } |
4177 | |
4178 | // Tests that ResultOf() can explain the match result. |
4179 | int IntFunction(int input) { return input == 42 ? 80 : 90; } |
4180 | |
4181 | TEST(ResultOfTest, CanExplainMatchResult) { |
4182 | Matcher<int> matcher = ResultOf(&IntFunction, Ge(85)); |
4183 | EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int" ), |
4184 | Explain(matcher, 36)); |
4185 | |
4186 | matcher = ResultOf(&IntFunction, GreaterThan(85)); |
4187 | EXPECT_EQ("which is mapped by the given callable to 90" + OfType("int" ) + |
4188 | ", which is 5 more than 85" , Explain(matcher, 36)); |
4189 | } |
4190 | |
4191 | // Tests that ResultOf(f, ...) compiles and works as expected when f(x) |
4192 | // returns a non-reference. |
4193 | TEST(ResultOfTest, WorksForNonReferenceResults) { |
4194 | Matcher<int> matcher = ResultOf(&IntFunction, Eq(80)); |
4195 | |
4196 | EXPECT_TRUE(matcher.Matches(42)); |
4197 | EXPECT_FALSE(matcher.Matches(36)); |
4198 | } |
4199 | |
4200 | // Tests that ResultOf(f, ...) compiles and works as expected when f(x) |
4201 | // returns a reference to non-const. |
4202 | double& DoubleFunction(double& input) { return input; } // NOLINT |
4203 | |
4204 | Uncopyable& RefUncopyableFunction(Uncopyable& obj) { // NOLINT |
4205 | return obj; |
4206 | } |
4207 | |
4208 | TEST(ResultOfTest, WorksForReferenceToNonConstResults) { |
4209 | double x = 3.14; |
4210 | double x2 = x; |
4211 | Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x)); |
4212 | |
4213 | EXPECT_TRUE(matcher.Matches(x)); |
4214 | EXPECT_FALSE(matcher.Matches(x2)); |
4215 | |
4216 | // Test that ResultOf works with uncopyable objects |
4217 | Uncopyable obj(0); |
4218 | Uncopyable obj2(0); |
4219 | Matcher<Uncopyable&> matcher2 = |
4220 | ResultOf(&RefUncopyableFunction, Ref(obj)); |
4221 | |
4222 | EXPECT_TRUE(matcher2.Matches(obj)); |
4223 | EXPECT_FALSE(matcher2.Matches(obj2)); |
4224 | } |
4225 | |
4226 | // Tests that ResultOf(f, ...) compiles and works as expected when f(x) |
4227 | // returns a reference to const. |
4228 | const std::string& StringFunction(const std::string& input) { return input; } |
4229 | |
4230 | TEST(ResultOfTest, WorksForReferenceToConstResults) { |
4231 | std::string s = "foo" ; |
4232 | std::string s2 = s; |
4233 | Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s)); |
4234 | |
4235 | EXPECT_TRUE(matcher.Matches(s)); |
4236 | EXPECT_FALSE(matcher.Matches(s2)); |
4237 | } |
4238 | |
4239 | // Tests that ResultOf(f, m) works when f(x) and m's |
4240 | // argument types are compatible but different. |
4241 | TEST(ResultOfTest, WorksForCompatibleMatcherTypes) { |
4242 | // IntFunction() returns int but the inner matcher expects a signed char. |
4243 | Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85))); |
4244 | |
4245 | EXPECT_TRUE(matcher.Matches(36)); |
4246 | EXPECT_FALSE(matcher.Matches(42)); |
4247 | } |
4248 | |
4249 | // Tests that the program aborts when ResultOf is passed |
4250 | // a NULL function pointer. |
4251 | TEST(ResultOfDeathTest, DiesOnNullFunctionPointers) { |
4252 | EXPECT_DEATH_IF_SUPPORTED( |
4253 | ResultOf(static_cast<std::string (*)(int dummy)>(nullptr), |
4254 | Eq(std::string("foo" ))), |
4255 | "NULL function pointer is passed into ResultOf\\(\\)\\." ); |
4256 | } |
4257 | |
4258 | // Tests that ResultOf(f, ...) compiles and works as expected when f is a |
4259 | // function reference. |
4260 | TEST(ResultOfTest, WorksForFunctionReferences) { |
4261 | Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq("foo" )); |
4262 | EXPECT_TRUE(matcher.Matches(1)); |
4263 | EXPECT_FALSE(matcher.Matches(2)); |
4264 | } |
4265 | |
4266 | // Tests that ResultOf(f, ...) compiles and works as expected when f is a |
4267 | // function object. |
4268 | struct Functor { |
4269 | std::string operator()(int input) const { |
4270 | return IntToStringFunction(input); |
4271 | } |
4272 | }; |
4273 | |
4274 | TEST(ResultOfTest, WorksForFunctors) { |
4275 | Matcher<int> matcher = ResultOf(Functor(), Eq(std::string("foo" ))); |
4276 | |
4277 | EXPECT_TRUE(matcher.Matches(1)); |
4278 | EXPECT_FALSE(matcher.Matches(2)); |
4279 | } |
4280 | |
4281 | // Tests that ResultOf(f, ...) compiles and works as expected when f is a |
4282 | // functor with more than one operator() defined. ResultOf() must work |
4283 | // for each defined operator(). |
4284 | struct PolymorphicFunctor { |
4285 | typedef int result_type; |
4286 | int operator()(int n) { return n; } |
4287 | int operator()(const char* s) { return static_cast<int>(strlen(s)); } |
4288 | std::string operator()(int *p) { return p ? "good ptr" : "null" ; } |
4289 | }; |
4290 | |
4291 | TEST(ResultOfTest, WorksForPolymorphicFunctors) { |
4292 | Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5)); |
4293 | |
4294 | EXPECT_TRUE(matcher_int.Matches(10)); |
4295 | EXPECT_FALSE(matcher_int.Matches(2)); |
4296 | |
4297 | Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5)); |
4298 | |
4299 | EXPECT_TRUE(matcher_string.Matches("long string" )); |
4300 | EXPECT_FALSE(matcher_string.Matches("shrt" )); |
4301 | } |
4302 | |
4303 | TEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) { |
4304 | Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), "good ptr" ); |
4305 | |
4306 | int n = 0; |
4307 | EXPECT_TRUE(matcher.Matches(&n)); |
4308 | EXPECT_FALSE(matcher.Matches(nullptr)); |
4309 | } |
4310 | |
4311 | TEST(ResultOfTest, WorksForLambdas) { |
4312 | Matcher<int> matcher = ResultOf( |
4313 | [](int str_len) { |
4314 | return std::string(static_cast<size_t>(str_len), 'x'); |
4315 | }, |
4316 | "xxx" ); |
4317 | EXPECT_TRUE(matcher.Matches(3)); |
4318 | EXPECT_FALSE(matcher.Matches(1)); |
4319 | } |
4320 | |
4321 | const int* ReferencingFunction(const int& n) { return &n; } |
4322 | |
4323 | struct ReferencingFunctor { |
4324 | typedef const int* result_type; |
4325 | result_type operator()(const int& n) { return &n; } |
4326 | }; |
4327 | |
4328 | TEST(ResultOfTest, WorksForReferencingCallables) { |
4329 | const int n = 1; |
4330 | const int n2 = 1; |
4331 | Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n)); |
4332 | EXPECT_TRUE(matcher2.Matches(n)); |
4333 | EXPECT_FALSE(matcher2.Matches(n2)); |
4334 | |
4335 | Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n)); |
4336 | EXPECT_TRUE(matcher3.Matches(n)); |
4337 | EXPECT_FALSE(matcher3.Matches(n2)); |
4338 | } |
4339 | |
4340 | class DivisibleByImpl { |
4341 | public: |
4342 | explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {} |
4343 | |
4344 | // For testing using ExplainMatchResultTo() with polymorphic matchers. |
4345 | template <typename T> |
4346 | bool MatchAndExplain(const T& n, MatchResultListener* listener) const { |
4347 | *listener << "which is " << (n % divider_) << " modulo " |
4348 | << divider_; |
4349 | return (n % divider_) == 0; |
4350 | } |
4351 | |
4352 | void DescribeTo(ostream* os) const { |
4353 | *os << "is divisible by " << divider_; |
4354 | } |
4355 | |
4356 | void DescribeNegationTo(ostream* os) const { |
4357 | *os << "is not divisible by " << divider_; |
4358 | } |
4359 | |
4360 | void set_divider(int a_divider) { divider_ = a_divider; } |
4361 | int divider() const { return divider_; } |
4362 | |
4363 | private: |
4364 | int divider_; |
4365 | }; |
4366 | |
4367 | PolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) { |
4368 | return MakePolymorphicMatcher(DivisibleByImpl(n)); |
4369 | } |
4370 | |
4371 | // Tests that when AllOf() fails, only the first failing matcher is |
4372 | // asked to explain why. |
4373 | TEST(ExplainMatchResultTest, AllOf_False_False) { |
4374 | const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3)); |
4375 | EXPECT_EQ("which is 1 modulo 4" , Explain(m, 5)); |
4376 | } |
4377 | |
4378 | // Tests that when AllOf() fails, only the first failing matcher is |
4379 | // asked to explain why. |
4380 | TEST(ExplainMatchResultTest, AllOf_False_True) { |
4381 | const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3)); |
4382 | EXPECT_EQ("which is 2 modulo 4" , Explain(m, 6)); |
4383 | } |
4384 | |
4385 | // Tests that when AllOf() fails, only the first failing matcher is |
4386 | // asked to explain why. |
4387 | TEST(ExplainMatchResultTest, AllOf_True_False) { |
4388 | const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3)); |
4389 | EXPECT_EQ("which is 2 modulo 3" , Explain(m, 5)); |
4390 | } |
4391 | |
4392 | // Tests that when AllOf() succeeds, all matchers are asked to explain |
4393 | // why. |
4394 | TEST(ExplainMatchResultTest, AllOf_True_True) { |
4395 | const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3)); |
4396 | EXPECT_EQ("which is 0 modulo 2, and which is 0 modulo 3" , Explain(m, 6)); |
4397 | } |
4398 | |
4399 | TEST(ExplainMatchResultTest, AllOf_True_True_2) { |
4400 | const Matcher<int> m = AllOf(Ge(2), Le(3)); |
4401 | EXPECT_EQ("" , Explain(m, 2)); |
4402 | } |
4403 | |
4404 | TEST(ExplainmatcherResultTest, MonomorphicMatcher) { |
4405 | const Matcher<int> m = GreaterThan(5); |
4406 | EXPECT_EQ("which is 1 more than 5" , Explain(m, 6)); |
4407 | } |
4408 | |
4409 | // The following two tests verify that values without a public copy |
4410 | // ctor can be used as arguments to matchers like Eq(), Ge(), and etc |
4411 | // with the help of ByRef(). |
4412 | |
4413 | class NotCopyable { |
4414 | public: |
4415 | explicit NotCopyable(int a_value) : value_(a_value) {} |
4416 | |
4417 | int value() const { return value_; } |
4418 | |
4419 | bool operator==(const NotCopyable& rhs) const { |
4420 | return value() == rhs.value(); |
4421 | } |
4422 | |
4423 | bool operator>=(const NotCopyable& rhs) const { |
4424 | return value() >= rhs.value(); |
4425 | } |
4426 | private: |
4427 | int value_; |
4428 | |
4429 | GTEST_DISALLOW_COPY_AND_ASSIGN_(NotCopyable); |
4430 | }; |
4431 | |
4432 | TEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) { |
4433 | const NotCopyable const_value1(1); |
4434 | const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1)); |
4435 | |
4436 | const NotCopyable n1(1), n2(2); |
4437 | EXPECT_TRUE(m.Matches(n1)); |
4438 | EXPECT_FALSE(m.Matches(n2)); |
4439 | } |
4440 | |
4441 | TEST(ByRefTest, AllowsNotCopyableValueInMatchers) { |
4442 | NotCopyable value2(2); |
4443 | const Matcher<NotCopyable&> m = Ge(ByRef(value2)); |
4444 | |
4445 | NotCopyable n1(1), n2(2); |
4446 | EXPECT_FALSE(m.Matches(n1)); |
4447 | EXPECT_TRUE(m.Matches(n2)); |
4448 | } |
4449 | |
4450 | TEST(IsEmptyTest, ImplementsIsEmpty) { |
4451 | vector<int> container; |
4452 | EXPECT_THAT(container, IsEmpty()); |
4453 | container.push_back(0); |
4454 | EXPECT_THAT(container, Not(IsEmpty())); |
4455 | container.push_back(1); |
4456 | EXPECT_THAT(container, Not(IsEmpty())); |
4457 | } |
4458 | |
4459 | TEST(IsEmptyTest, WorksWithString) { |
4460 | std::string text; |
4461 | EXPECT_THAT(text, IsEmpty()); |
4462 | text = "foo" ; |
4463 | EXPECT_THAT(text, Not(IsEmpty())); |
4464 | text = std::string("\0" , 1); |
4465 | EXPECT_THAT(text, Not(IsEmpty())); |
4466 | } |
4467 | |
4468 | TEST(IsEmptyTest, CanDescribeSelf) { |
4469 | Matcher<vector<int> > m = IsEmpty(); |
4470 | EXPECT_EQ("is empty" , Describe(m)); |
4471 | EXPECT_EQ("isn't empty" , DescribeNegation(m)); |
4472 | } |
4473 | |
4474 | TEST(IsEmptyTest, ExplainsResult) { |
4475 | Matcher<vector<int> > m = IsEmpty(); |
4476 | vector<int> container; |
4477 | EXPECT_EQ("" , Explain(m, container)); |
4478 | container.push_back(0); |
4479 | EXPECT_EQ("whose size is 1" , Explain(m, container)); |
4480 | } |
4481 | |
4482 | TEST(IsEmptyTest, WorksWithMoveOnly) { |
4483 | ContainerHelper helper; |
4484 | EXPECT_CALL(helper, Call(IsEmpty())); |
4485 | helper.Call({}); |
4486 | } |
4487 | |
4488 | TEST(IsTrueTest, IsTrueIsFalse) { |
4489 | EXPECT_THAT(true, IsTrue()); |
4490 | EXPECT_THAT(false, IsFalse()); |
4491 | EXPECT_THAT(true, Not(IsFalse())); |
4492 | EXPECT_THAT(false, Not(IsTrue())); |
4493 | EXPECT_THAT(0, Not(IsTrue())); |
4494 | EXPECT_THAT(0, IsFalse()); |
4495 | EXPECT_THAT(nullptr, Not(IsTrue())); |
4496 | EXPECT_THAT(nullptr, IsFalse()); |
4497 | EXPECT_THAT(-1, IsTrue()); |
4498 | EXPECT_THAT(-1, Not(IsFalse())); |
4499 | EXPECT_THAT(1, IsTrue()); |
4500 | EXPECT_THAT(1, Not(IsFalse())); |
4501 | EXPECT_THAT(2, IsTrue()); |
4502 | EXPECT_THAT(2, Not(IsFalse())); |
4503 | int a = 42; |
4504 | EXPECT_THAT(a, IsTrue()); |
4505 | EXPECT_THAT(a, Not(IsFalse())); |
4506 | EXPECT_THAT(&a, IsTrue()); |
4507 | EXPECT_THAT(&a, Not(IsFalse())); |
4508 | EXPECT_THAT(false, Not(IsTrue())); |
4509 | EXPECT_THAT(true, Not(IsFalse())); |
4510 | EXPECT_THAT(std::true_type(), IsTrue()); |
4511 | EXPECT_THAT(std::true_type(), Not(IsFalse())); |
4512 | EXPECT_THAT(std::false_type(), IsFalse()); |
4513 | EXPECT_THAT(std::false_type(), Not(IsTrue())); |
4514 | EXPECT_THAT(nullptr, Not(IsTrue())); |
4515 | EXPECT_THAT(nullptr, IsFalse()); |
4516 | std::unique_ptr<int> null_unique; |
4517 | std::unique_ptr<int> nonnull_unique(new int(0)); |
4518 | EXPECT_THAT(null_unique, Not(IsTrue())); |
4519 | EXPECT_THAT(null_unique, IsFalse()); |
4520 | EXPECT_THAT(nonnull_unique, IsTrue()); |
4521 | EXPECT_THAT(nonnull_unique, Not(IsFalse())); |
4522 | } |
4523 | |
4524 | TEST(SizeIsTest, ImplementsSizeIs) { |
4525 | vector<int> container; |
4526 | EXPECT_THAT(container, SizeIs(0)); |
4527 | EXPECT_THAT(container, Not(SizeIs(1))); |
4528 | container.push_back(0); |
4529 | EXPECT_THAT(container, Not(SizeIs(0))); |
4530 | EXPECT_THAT(container, SizeIs(1)); |
4531 | container.push_back(0); |
4532 | EXPECT_THAT(container, Not(SizeIs(0))); |
4533 | EXPECT_THAT(container, SizeIs(2)); |
4534 | } |
4535 | |
4536 | TEST(SizeIsTest, WorksWithMap) { |
4537 | map<std::string, int> container; |
4538 | EXPECT_THAT(container, SizeIs(0)); |
4539 | EXPECT_THAT(container, Not(SizeIs(1))); |
4540 | container.insert(make_pair("foo" , 1)); |
4541 | EXPECT_THAT(container, Not(SizeIs(0))); |
4542 | EXPECT_THAT(container, SizeIs(1)); |
4543 | container.insert(make_pair("bar" , 2)); |
4544 | EXPECT_THAT(container, Not(SizeIs(0))); |
4545 | EXPECT_THAT(container, SizeIs(2)); |
4546 | } |
4547 | |
4548 | TEST(SizeIsTest, WorksWithReferences) { |
4549 | vector<int> container; |
4550 | Matcher<const vector<int>&> m = SizeIs(1); |
4551 | EXPECT_THAT(container, Not(m)); |
4552 | container.push_back(0); |
4553 | EXPECT_THAT(container, m); |
4554 | } |
4555 | |
4556 | TEST(SizeIsTest, WorksWithMoveOnly) { |
4557 | ContainerHelper helper; |
4558 | EXPECT_CALL(helper, Call(SizeIs(3))); |
4559 | helper.Call(MakeUniquePtrs({1, 2, 3})); |
4560 | } |
4561 | |
4562 | // SizeIs should work for any type that provides a size() member function. |
4563 | // For example, a size_type member type should not need to be provided. |
4564 | struct MinimalistCustomType { |
4565 | int size() const { return 1; } |
4566 | }; |
4567 | TEST(SizeIsTest, WorksWithMinimalistCustomType) { |
4568 | MinimalistCustomType container; |
4569 | EXPECT_THAT(container, SizeIs(1)); |
4570 | EXPECT_THAT(container, Not(SizeIs(0))); |
4571 | } |
4572 | |
4573 | TEST(SizeIsTest, CanDescribeSelf) { |
4574 | Matcher<vector<int> > m = SizeIs(2); |
4575 | EXPECT_EQ("size is equal to 2" , Describe(m)); |
4576 | EXPECT_EQ("size isn't equal to 2" , DescribeNegation(m)); |
4577 | } |
4578 | |
4579 | TEST(SizeIsTest, ExplainsResult) { |
4580 | Matcher<vector<int> > m1 = SizeIs(2); |
4581 | Matcher<vector<int> > m2 = SizeIs(Lt(2u)); |
4582 | Matcher<vector<int> > m3 = SizeIs(AnyOf(0, 3)); |
4583 | Matcher<vector<int> > m4 = SizeIs(GreaterThan(1)); |
4584 | vector<int> container; |
4585 | EXPECT_EQ("whose size 0 doesn't match" , Explain(m1, container)); |
4586 | EXPECT_EQ("whose size 0 matches" , Explain(m2, container)); |
4587 | EXPECT_EQ("whose size 0 matches" , Explain(m3, container)); |
4588 | EXPECT_EQ("whose size 0 doesn't match, which is 1 less than 1" , |
4589 | Explain(m4, container)); |
4590 | container.push_back(0); |
4591 | container.push_back(0); |
4592 | EXPECT_EQ("whose size 2 matches" , Explain(m1, container)); |
4593 | EXPECT_EQ("whose size 2 doesn't match" , Explain(m2, container)); |
4594 | EXPECT_EQ("whose size 2 doesn't match" , Explain(m3, container)); |
4595 | EXPECT_EQ("whose size 2 matches, which is 1 more than 1" , |
4596 | Explain(m4, container)); |
4597 | } |
4598 | |
4599 | #if GTEST_HAS_TYPED_TEST |
4600 | // Tests ContainerEq with different container types, and |
4601 | // different element types. |
4602 | |
4603 | template <typename T> |
4604 | class ContainerEqTest : public testing::Test {}; |
4605 | |
4606 | typedef testing::Types< |
4607 | set<int>, |
4608 | vector<size_t>, |
4609 | multiset<size_t>, |
4610 | list<int> > |
4611 | ContainerEqTestTypes; |
4612 | |
4613 | TYPED_TEST_SUITE(ContainerEqTest, ContainerEqTestTypes); |
4614 | |
4615 | // Tests that the filled container is equal to itself. |
4616 | TYPED_TEST(ContainerEqTest, EqualsSelf) { |
4617 | static const int vals[] = {1, 1, 2, 3, 5, 8}; |
4618 | TypeParam my_set(vals, vals + 6); |
4619 | const Matcher<TypeParam> m = ContainerEq(my_set); |
4620 | EXPECT_TRUE(m.Matches(my_set)); |
4621 | EXPECT_EQ("" , Explain(m, my_set)); |
4622 | } |
4623 | |
4624 | // Tests that missing values are reported. |
4625 | TYPED_TEST(ContainerEqTest, ValueMissing) { |
4626 | static const int vals[] = {1, 1, 2, 3, 5, 8}; |
4627 | static const int test_vals[] = {2, 1, 8, 5}; |
4628 | TypeParam my_set(vals, vals + 6); |
4629 | TypeParam test_set(test_vals, test_vals + 4); |
4630 | const Matcher<TypeParam> m = ContainerEq(my_set); |
4631 | EXPECT_FALSE(m.Matches(test_set)); |
4632 | EXPECT_EQ("which doesn't have these expected elements: 3" , |
4633 | Explain(m, test_set)); |
4634 | } |
4635 | |
4636 | // Tests that added values are reported. |
4637 | TYPED_TEST(ContainerEqTest, ValueAdded) { |
4638 | static const int vals[] = {1, 1, 2, 3, 5, 8}; |
4639 | static const int test_vals[] = {1, 2, 3, 5, 8, 46}; |
4640 | TypeParam my_set(vals, vals + 6); |
4641 | TypeParam test_set(test_vals, test_vals + 6); |
4642 | const Matcher<const TypeParam&> m = ContainerEq(my_set); |
4643 | EXPECT_FALSE(m.Matches(test_set)); |
4644 | EXPECT_EQ("which has these unexpected elements: 46" , Explain(m, test_set)); |
4645 | } |
4646 | |
4647 | // Tests that added and missing values are reported together. |
4648 | TYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) { |
4649 | static const int vals[] = {1, 1, 2, 3, 5, 8}; |
4650 | static const int test_vals[] = {1, 2, 3, 8, 46}; |
4651 | TypeParam my_set(vals, vals + 6); |
4652 | TypeParam test_set(test_vals, test_vals + 5); |
4653 | const Matcher<TypeParam> m = ContainerEq(my_set); |
4654 | EXPECT_FALSE(m.Matches(test_set)); |
4655 | EXPECT_EQ("which has these unexpected elements: 46,\n" |
4656 | "and doesn't have these expected elements: 5" , |
4657 | Explain(m, test_set)); |
4658 | } |
4659 | |
4660 | // Tests duplicated value -- expect no explanation. |
4661 | TYPED_TEST(ContainerEqTest, DuplicateDifference) { |
4662 | static const int vals[] = {1, 1, 2, 3, 5, 8}; |
4663 | static const int test_vals[] = {1, 2, 3, 5, 8}; |
4664 | TypeParam my_set(vals, vals + 6); |
4665 | TypeParam test_set(test_vals, test_vals + 5); |
4666 | const Matcher<const TypeParam&> m = ContainerEq(my_set); |
4667 | // Depending on the container, match may be true or false |
4668 | // But in any case there should be no explanation. |
4669 | EXPECT_EQ("" , Explain(m, test_set)); |
4670 | } |
4671 | #endif // GTEST_HAS_TYPED_TEST |
4672 | |
4673 | // Tests that multiple missing values are reported. |
4674 | // Using just vector here, so order is predictable. |
4675 | TEST(ContainerEqExtraTest, MultipleValuesMissing) { |
4676 | static const int vals[] = {1, 1, 2, 3, 5, 8}; |
4677 | static const int test_vals[] = {2, 1, 5}; |
4678 | vector<int> my_set(vals, vals + 6); |
4679 | vector<int> test_set(test_vals, test_vals + 3); |
4680 | const Matcher<vector<int> > m = ContainerEq(my_set); |
4681 | EXPECT_FALSE(m.Matches(test_set)); |
4682 | EXPECT_EQ("which doesn't have these expected elements: 3, 8" , |
4683 | Explain(m, test_set)); |
4684 | } |
4685 | |
4686 | // Tests that added values are reported. |
4687 | // Using just vector here, so order is predictable. |
4688 | TEST(ContainerEqExtraTest, MultipleValuesAdded) { |
4689 | static const int vals[] = {1, 1, 2, 3, 5, 8}; |
4690 | static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46}; |
4691 | list<size_t> my_set(vals, vals + 6); |
4692 | list<size_t> test_set(test_vals, test_vals + 7); |
4693 | const Matcher<const list<size_t>&> m = ContainerEq(my_set); |
4694 | EXPECT_FALSE(m.Matches(test_set)); |
4695 | EXPECT_EQ("which has these unexpected elements: 92, 46" , |
4696 | Explain(m, test_set)); |
4697 | } |
4698 | |
4699 | // Tests that added and missing values are reported together. |
4700 | TEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) { |
4701 | static const int vals[] = {1, 1, 2, 3, 5, 8}; |
4702 | static const int test_vals[] = {1, 2, 3, 92, 46}; |
4703 | list<size_t> my_set(vals, vals + 6); |
4704 | list<size_t> test_set(test_vals, test_vals + 5); |
4705 | const Matcher<const list<size_t> > m = ContainerEq(my_set); |
4706 | EXPECT_FALSE(m.Matches(test_set)); |
4707 | EXPECT_EQ("which has these unexpected elements: 92, 46,\n" |
4708 | "and doesn't have these expected elements: 5, 8" , |
4709 | Explain(m, test_set)); |
4710 | } |
4711 | |
4712 | // Tests to see that duplicate elements are detected, |
4713 | // but (as above) not reported in the explanation. |
4714 | TEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) { |
4715 | static const int vals[] = {1, 1, 2, 3, 5, 8}; |
4716 | static const int test_vals[] = {1, 2, 3, 5, 8}; |
4717 | vector<int> my_set(vals, vals + 6); |
4718 | vector<int> test_set(test_vals, test_vals + 5); |
4719 | const Matcher<vector<int> > m = ContainerEq(my_set); |
4720 | EXPECT_TRUE(m.Matches(my_set)); |
4721 | EXPECT_FALSE(m.Matches(test_set)); |
4722 | // There is nothing to report when both sets contain all the same values. |
4723 | EXPECT_EQ("" , Explain(m, test_set)); |
4724 | } |
4725 | |
4726 | // Tests that ContainerEq works for non-trivial associative containers, |
4727 | // like maps. |
4728 | TEST(ContainerEqExtraTest, WorksForMaps) { |
4729 | map<int, std::string> my_map; |
4730 | my_map[0] = "a" ; |
4731 | my_map[1] = "b" ; |
4732 | |
4733 | map<int, std::string> test_map; |
4734 | test_map[0] = "aa" ; |
4735 | test_map[1] = "b" ; |
4736 | |
4737 | const Matcher<const map<int, std::string>&> m = ContainerEq(my_map); |
4738 | EXPECT_TRUE(m.Matches(my_map)); |
4739 | EXPECT_FALSE(m.Matches(test_map)); |
4740 | |
4741 | EXPECT_EQ("which has these unexpected elements: (0, \"aa\"),\n" |
4742 | "and doesn't have these expected elements: (0, \"a\")" , |
4743 | Explain(m, test_map)); |
4744 | } |
4745 | |
4746 | TEST(ContainerEqExtraTest, WorksForNativeArray) { |
4747 | int a1[] = {1, 2, 3}; |
4748 | int a2[] = {1, 2, 3}; |
4749 | int b[] = {1, 2, 4}; |
4750 | |
4751 | EXPECT_THAT(a1, ContainerEq(a2)); |
4752 | EXPECT_THAT(a1, Not(ContainerEq(b))); |
4753 | } |
4754 | |
4755 | TEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) { |
4756 | const char a1[][3] = {"hi" , "lo" }; |
4757 | const char a2[][3] = {"hi" , "lo" }; |
4758 | const char b[][3] = {"lo" , "hi" }; |
4759 | |
4760 | // Tests using ContainerEq() in the first dimension. |
4761 | EXPECT_THAT(a1, ContainerEq(a2)); |
4762 | EXPECT_THAT(a1, Not(ContainerEq(b))); |
4763 | |
4764 | // Tests using ContainerEq() in the second dimension. |
4765 | EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1]))); |
4766 | EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1]))); |
4767 | } |
4768 | |
4769 | TEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) { |
4770 | const int a1[] = {1, 2, 3}; |
4771 | const int a2[] = {1, 2, 3}; |
4772 | const int b[] = {1, 2, 3, 4}; |
4773 | |
4774 | const int* const p1 = a1; |
4775 | EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2)); |
4776 | EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b))); |
4777 | |
4778 | const int c[] = {1, 3, 2}; |
4779 | EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c))); |
4780 | } |
4781 | |
4782 | TEST(ContainerEqExtraTest, CopiesNativeArrayParameter) { |
4783 | std::string a1[][3] = { |
4784 | {"hi" , "hello" , "ciao" }, |
4785 | {"bye" , "see you" , "ciao" } |
4786 | }; |
4787 | |
4788 | std::string a2[][3] = { |
4789 | {"hi" , "hello" , "ciao" }, |
4790 | {"bye" , "see you" , "ciao" } |
4791 | }; |
4792 | |
4793 | const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2); |
4794 | EXPECT_THAT(a1, m); |
4795 | |
4796 | a2[0][0] = "ha" ; |
4797 | EXPECT_THAT(a1, m); |
4798 | } |
4799 | |
4800 | TEST(WhenSortedByTest, WorksForEmptyContainer) { |
4801 | const vector<int> numbers; |
4802 | EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre())); |
4803 | EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1)))); |
4804 | } |
4805 | |
4806 | TEST(WhenSortedByTest, WorksForNonEmptyContainer) { |
4807 | vector<unsigned> numbers; |
4808 | numbers.push_back(3); |
4809 | numbers.push_back(1); |
4810 | numbers.push_back(2); |
4811 | numbers.push_back(2); |
4812 | EXPECT_THAT(numbers, WhenSortedBy(greater<unsigned>(), |
4813 | ElementsAre(3, 2, 2, 1))); |
4814 | EXPECT_THAT(numbers, Not(WhenSortedBy(greater<unsigned>(), |
4815 | ElementsAre(1, 2, 2, 3)))); |
4816 | } |
4817 | |
4818 | TEST(WhenSortedByTest, WorksForNonVectorContainer) { |
4819 | list<std::string> words; |
4820 | words.push_back("say" ); |
4821 | words.push_back("hello" ); |
4822 | words.push_back("world" ); |
4823 | EXPECT_THAT(words, WhenSortedBy(less<std::string>(), |
4824 | ElementsAre("hello" , "say" , "world" ))); |
4825 | EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(), |
4826 | ElementsAre("say" , "hello" , "world" )))); |
4827 | } |
4828 | |
4829 | TEST(WhenSortedByTest, WorksForNativeArray) { |
4830 | const int numbers[] = {1, 3, 2, 4}; |
4831 | const int sorted_numbers[] = {1, 2, 3, 4}; |
4832 | EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4))); |
4833 | EXPECT_THAT(numbers, WhenSortedBy(less<int>(), |
4834 | ElementsAreArray(sorted_numbers))); |
4835 | EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4)))); |
4836 | } |
4837 | |
4838 | TEST(WhenSortedByTest, CanDescribeSelf) { |
4839 | const Matcher<vector<int> > m = WhenSortedBy(less<int>(), ElementsAre(1, 2)); |
4840 | EXPECT_EQ("(when sorted) has 2 elements where\n" |
4841 | "element #0 is equal to 1,\n" |
4842 | "element #1 is equal to 2" , |
4843 | Describe(m)); |
4844 | EXPECT_EQ("(when sorted) doesn't have 2 elements, or\n" |
4845 | "element #0 isn't equal to 1, or\n" |
4846 | "element #1 isn't equal to 2" , |
4847 | DescribeNegation(m)); |
4848 | } |
4849 | |
4850 | TEST(WhenSortedByTest, ExplainsMatchResult) { |
4851 | const int a[] = {2, 1}; |
4852 | EXPECT_EQ("which is { 1, 2 } when sorted, whose element #0 doesn't match" , |
4853 | Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a)); |
4854 | EXPECT_EQ("which is { 1, 2 } when sorted" , |
4855 | Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a)); |
4856 | } |
4857 | |
4858 | // WhenSorted() is a simple wrapper on WhenSortedBy(). Hence we don't |
4859 | // need to test it as exhaustively as we test the latter. |
4860 | |
4861 | TEST(WhenSortedTest, WorksForEmptyContainer) { |
4862 | const vector<int> numbers; |
4863 | EXPECT_THAT(numbers, WhenSorted(ElementsAre())); |
4864 | EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1)))); |
4865 | } |
4866 | |
4867 | TEST(WhenSortedTest, WorksForNonEmptyContainer) { |
4868 | list<std::string> words; |
4869 | words.push_back("3" ); |
4870 | words.push_back("1" ); |
4871 | words.push_back("2" ); |
4872 | words.push_back("2" ); |
4873 | EXPECT_THAT(words, WhenSorted(ElementsAre("1" , "2" , "2" , "3" ))); |
4874 | EXPECT_THAT(words, Not(WhenSorted(ElementsAre("3" , "1" , "2" , "2" )))); |
4875 | } |
4876 | |
4877 | TEST(WhenSortedTest, WorksForMapTypes) { |
4878 | map<std::string, int> word_counts; |
4879 | word_counts["and" ] = 1; |
4880 | word_counts["the" ] = 1; |
4881 | word_counts["buffalo" ] = 2; |
4882 | EXPECT_THAT(word_counts, |
4883 | WhenSorted(ElementsAre(Pair("and" , 1), Pair("buffalo" , 2), |
4884 | Pair("the" , 1)))); |
4885 | EXPECT_THAT(word_counts, |
4886 | Not(WhenSorted(ElementsAre(Pair("and" , 1), Pair("the" , 1), |
4887 | Pair("buffalo" , 2))))); |
4888 | } |
4889 | |
4890 | TEST(WhenSortedTest, WorksForMultiMapTypes) { |
4891 | multimap<int, int> ifib; |
4892 | ifib.insert(make_pair(8, 6)); |
4893 | ifib.insert(make_pair(2, 3)); |
4894 | ifib.insert(make_pair(1, 1)); |
4895 | ifib.insert(make_pair(3, 4)); |
4896 | ifib.insert(make_pair(1, 2)); |
4897 | ifib.insert(make_pair(5, 5)); |
4898 | EXPECT_THAT(ifib, WhenSorted(ElementsAre(Pair(1, 1), |
4899 | Pair(1, 2), |
4900 | Pair(2, 3), |
4901 | Pair(3, 4), |
4902 | Pair(5, 5), |
4903 | Pair(8, 6)))); |
4904 | EXPECT_THAT(ifib, Not(WhenSorted(ElementsAre(Pair(8, 6), |
4905 | Pair(2, 3), |
4906 | Pair(1, 1), |
4907 | Pair(3, 4), |
4908 | Pair(1, 2), |
4909 | Pair(5, 5))))); |
4910 | } |
4911 | |
4912 | TEST(WhenSortedTest, WorksForPolymorphicMatcher) { |
4913 | std::deque<int> d; |
4914 | d.push_back(2); |
4915 | d.push_back(1); |
4916 | EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2))); |
4917 | EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1)))); |
4918 | } |
4919 | |
4920 | TEST(WhenSortedTest, WorksForVectorConstRefMatcher) { |
4921 | std::deque<int> d; |
4922 | d.push_back(2); |
4923 | d.push_back(1); |
4924 | Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2); |
4925 | EXPECT_THAT(d, WhenSorted(vector_match)); |
4926 | Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1); |
4927 | EXPECT_THAT(d, Not(WhenSorted(not_vector_match))); |
4928 | } |
4929 | |
4930 | // Deliberately bare pseudo-container. |
4931 | // Offers only begin() and end() accessors, yielding InputIterator. |
4932 | template <typename T> |
4933 | class Streamlike { |
4934 | private: |
4935 | class ConstIter; |
4936 | public: |
4937 | typedef ConstIter const_iterator; |
4938 | typedef T value_type; |
4939 | |
4940 | template <typename InIter> |
4941 | Streamlike(InIter first, InIter last) : remainder_(first, last) {} |
4942 | |
4943 | const_iterator begin() const { |
4944 | return const_iterator(this, remainder_.begin()); |
4945 | } |
4946 | const_iterator end() const { |
4947 | return const_iterator(this, remainder_.end()); |
4948 | } |
4949 | |
4950 | private: |
4951 | class ConstIter : public std::iterator<std::input_iterator_tag, |
4952 | value_type, |
4953 | ptrdiff_t, |
4954 | const value_type*, |
4955 | const value_type&> { |
4956 | public: |
4957 | ConstIter(const Streamlike* s, |
4958 | typename std::list<value_type>::iterator pos) |
4959 | : s_(s), pos_(pos) {} |
4960 | |
4961 | const value_type& operator*() const { return *pos_; } |
4962 | const value_type* operator->() const { return &*pos_; } |
4963 | ConstIter& operator++() { |
4964 | s_->remainder_.erase(pos_++); |
4965 | return *this; |
4966 | } |
4967 | |
4968 | // *iter++ is required to work (see std::istreambuf_iterator). |
4969 | // (void)iter++ is also required to work. |
4970 | class PostIncrProxy { |
4971 | public: |
4972 | explicit PostIncrProxy(const value_type& value) : value_(value) {} |
4973 | value_type operator*() const { return value_; } |
4974 | private: |
4975 | value_type value_; |
4976 | }; |
4977 | PostIncrProxy operator++(int) { |
4978 | PostIncrProxy proxy(**this); |
4979 | ++(*this); |
4980 | return proxy; |
4981 | } |
4982 | |
4983 | friend bool operator==(const ConstIter& a, const ConstIter& b) { |
4984 | return a.s_ == b.s_ && a.pos_ == b.pos_; |
4985 | } |
4986 | friend bool operator!=(const ConstIter& a, const ConstIter& b) { |
4987 | return !(a == b); |
4988 | } |
4989 | |
4990 | private: |
4991 | const Streamlike* s_; |
4992 | typename std::list<value_type>::iterator pos_; |
4993 | }; |
4994 | |
4995 | friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) { |
4996 | os << "[" ; |
4997 | typedef typename std::list<value_type>::const_iterator Iter; |
4998 | const char* sep = "" ; |
4999 | for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) { |
5000 | os << sep << *it; |
5001 | sep = "," ; |
5002 | } |
5003 | os << "]" ; |
5004 | return os; |
5005 | } |
5006 | |
5007 | mutable std::list<value_type> remainder_; // modified by iteration |
5008 | }; |
5009 | |
5010 | TEST(StreamlikeTest, Iteration) { |
5011 | const int a[5] = {2, 1, 4, 5, 3}; |
5012 | Streamlike<int> s(a, a + 5); |
5013 | Streamlike<int>::const_iterator it = s.begin(); |
5014 | const int* ip = a; |
5015 | while (it != s.end()) { |
5016 | SCOPED_TRACE(ip - a); |
5017 | EXPECT_EQ(*ip++, *it++); |
5018 | } |
5019 | } |
5020 | |
5021 | TEST(BeginEndDistanceIsTest, WorksWithForwardList) { |
5022 | std::forward_list<int> container; |
5023 | EXPECT_THAT(container, BeginEndDistanceIs(0)); |
5024 | EXPECT_THAT(container, Not(BeginEndDistanceIs(1))); |
5025 | container.push_front(0); |
5026 | EXPECT_THAT(container, Not(BeginEndDistanceIs(0))); |
5027 | EXPECT_THAT(container, BeginEndDistanceIs(1)); |
5028 | container.push_front(0); |
5029 | EXPECT_THAT(container, Not(BeginEndDistanceIs(0))); |
5030 | EXPECT_THAT(container, BeginEndDistanceIs(2)); |
5031 | } |
5032 | |
5033 | TEST(BeginEndDistanceIsTest, WorksWithNonStdList) { |
5034 | const int a[5] = {1, 2, 3, 4, 5}; |
5035 | Streamlike<int> s(a, a + 5); |
5036 | EXPECT_THAT(s, BeginEndDistanceIs(5)); |
5037 | } |
5038 | |
5039 | TEST(BeginEndDistanceIsTest, CanDescribeSelf) { |
5040 | Matcher<vector<int> > m = BeginEndDistanceIs(2); |
5041 | EXPECT_EQ("distance between begin() and end() is equal to 2" , Describe(m)); |
5042 | EXPECT_EQ("distance between begin() and end() isn't equal to 2" , |
5043 | DescribeNegation(m)); |
5044 | } |
5045 | |
5046 | TEST(BeginEndDistanceIsTest, WorksWithMoveOnly) { |
5047 | ContainerHelper helper; |
5048 | EXPECT_CALL(helper, Call(BeginEndDistanceIs(2))); |
5049 | helper.Call(MakeUniquePtrs({1, 2})); |
5050 | } |
5051 | |
5052 | TEST(BeginEndDistanceIsTest, ExplainsResult) { |
5053 | Matcher<vector<int> > m1 = BeginEndDistanceIs(2); |
5054 | Matcher<vector<int> > m2 = BeginEndDistanceIs(Lt(2)); |
5055 | Matcher<vector<int> > m3 = BeginEndDistanceIs(AnyOf(0, 3)); |
5056 | Matcher<vector<int> > m4 = BeginEndDistanceIs(GreaterThan(1)); |
5057 | vector<int> container; |
5058 | EXPECT_EQ("whose distance between begin() and end() 0 doesn't match" , |
5059 | Explain(m1, container)); |
5060 | EXPECT_EQ("whose distance between begin() and end() 0 matches" , |
5061 | Explain(m2, container)); |
5062 | EXPECT_EQ("whose distance between begin() and end() 0 matches" , |
5063 | Explain(m3, container)); |
5064 | EXPECT_EQ( |
5065 | "whose distance between begin() and end() 0 doesn't match, which is 1 " |
5066 | "less than 1" , |
5067 | Explain(m4, container)); |
5068 | container.push_back(0); |
5069 | container.push_back(0); |
5070 | EXPECT_EQ("whose distance between begin() and end() 2 matches" , |
5071 | Explain(m1, container)); |
5072 | EXPECT_EQ("whose distance between begin() and end() 2 doesn't match" , |
5073 | Explain(m2, container)); |
5074 | EXPECT_EQ("whose distance between begin() and end() 2 doesn't match" , |
5075 | Explain(m3, container)); |
5076 | EXPECT_EQ( |
5077 | "whose distance between begin() and end() 2 matches, which is 1 more " |
5078 | "than 1" , |
5079 | Explain(m4, container)); |
5080 | } |
5081 | |
5082 | TEST(WhenSortedTest, WorksForStreamlike) { |
5083 | // Streamlike 'container' provides only minimal iterator support. |
5084 | // Its iterators are tagged with input_iterator_tag. |
5085 | const int a[5] = {2, 1, 4, 5, 3}; |
5086 | Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a)); |
5087 | EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5))); |
5088 | EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3)))); |
5089 | } |
5090 | |
5091 | TEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) { |
5092 | const int a[] = {2, 1, 4, 5, 3}; |
5093 | Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a)); |
5094 | Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5); |
5095 | EXPECT_THAT(s, WhenSorted(vector_match)); |
5096 | EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3)))); |
5097 | } |
5098 | |
5099 | TEST(IsSupersetOfTest, WorksForNativeArray) { |
5100 | const int subset[] = {1, 4}; |
5101 | const int superset[] = {1, 2, 4}; |
5102 | const int disjoint[] = {1, 0, 3}; |
5103 | EXPECT_THAT(subset, IsSupersetOf(subset)); |
5104 | EXPECT_THAT(subset, Not(IsSupersetOf(superset))); |
5105 | EXPECT_THAT(superset, IsSupersetOf(subset)); |
5106 | EXPECT_THAT(subset, Not(IsSupersetOf(disjoint))); |
5107 | EXPECT_THAT(disjoint, Not(IsSupersetOf(subset))); |
5108 | } |
5109 | |
5110 | TEST(IsSupersetOfTest, WorksWithDuplicates) { |
5111 | const int not_enough[] = {1, 2}; |
5112 | const int enough[] = {1, 1, 2}; |
5113 | const int expected[] = {1, 1}; |
5114 | EXPECT_THAT(not_enough, Not(IsSupersetOf(expected))); |
5115 | EXPECT_THAT(enough, IsSupersetOf(expected)); |
5116 | } |
5117 | |
5118 | TEST(IsSupersetOfTest, WorksForEmpty) { |
5119 | vector<int> numbers; |
5120 | vector<int> expected; |
5121 | EXPECT_THAT(numbers, IsSupersetOf(expected)); |
5122 | expected.push_back(1); |
5123 | EXPECT_THAT(numbers, Not(IsSupersetOf(expected))); |
5124 | expected.clear(); |
5125 | numbers.push_back(1); |
5126 | numbers.push_back(2); |
5127 | EXPECT_THAT(numbers, IsSupersetOf(expected)); |
5128 | expected.push_back(1); |
5129 | EXPECT_THAT(numbers, IsSupersetOf(expected)); |
5130 | expected.push_back(2); |
5131 | EXPECT_THAT(numbers, IsSupersetOf(expected)); |
5132 | expected.push_back(3); |
5133 | EXPECT_THAT(numbers, Not(IsSupersetOf(expected))); |
5134 | } |
5135 | |
5136 | TEST(IsSupersetOfTest, WorksForStreamlike) { |
5137 | const int a[5] = {1, 2, 3, 4, 5}; |
5138 | Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a)); |
5139 | |
5140 | vector<int> expected; |
5141 | expected.push_back(1); |
5142 | expected.push_back(2); |
5143 | expected.push_back(5); |
5144 | EXPECT_THAT(s, IsSupersetOf(expected)); |
5145 | |
5146 | expected.push_back(0); |
5147 | EXPECT_THAT(s, Not(IsSupersetOf(expected))); |
5148 | } |
5149 | |
5150 | TEST(IsSupersetOfTest, TakesStlContainer) { |
5151 | const int actual[] = {3, 1, 2}; |
5152 | |
5153 | ::std::list<int> expected; |
5154 | expected.push_back(1); |
5155 | expected.push_back(3); |
5156 | EXPECT_THAT(actual, IsSupersetOf(expected)); |
5157 | |
5158 | expected.push_back(4); |
5159 | EXPECT_THAT(actual, Not(IsSupersetOf(expected))); |
5160 | } |
5161 | |
5162 | TEST(IsSupersetOfTest, Describe) { |
5163 | typedef std::vector<int> IntVec; |
5164 | IntVec expected; |
5165 | expected.push_back(111); |
5166 | expected.push_back(222); |
5167 | expected.push_back(333); |
5168 | EXPECT_THAT( |
5169 | Describe<IntVec>(IsSupersetOf(expected)), |
5170 | Eq("a surjection from elements to requirements exists such that:\n" |
5171 | " - an element is equal to 111\n" |
5172 | " - an element is equal to 222\n" |
5173 | " - an element is equal to 333" )); |
5174 | } |
5175 | |
5176 | TEST(IsSupersetOfTest, DescribeNegation) { |
5177 | typedef std::vector<int> IntVec; |
5178 | IntVec expected; |
5179 | expected.push_back(111); |
5180 | expected.push_back(222); |
5181 | expected.push_back(333); |
5182 | EXPECT_THAT( |
5183 | DescribeNegation<IntVec>(IsSupersetOf(expected)), |
5184 | Eq("no surjection from elements to requirements exists such that:\n" |
5185 | " - an element is equal to 111\n" |
5186 | " - an element is equal to 222\n" |
5187 | " - an element is equal to 333" )); |
5188 | } |
5189 | |
5190 | TEST(IsSupersetOfTest, MatchAndExplain) { |
5191 | std::vector<int> v; |
5192 | v.push_back(2); |
5193 | v.push_back(3); |
5194 | std::vector<int> expected; |
5195 | expected.push_back(1); |
5196 | expected.push_back(2); |
5197 | StringMatchResultListener listener; |
5198 | ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener)) |
5199 | << listener.str(); |
5200 | EXPECT_THAT(listener.str(), |
5201 | Eq("where the following matchers don't match any elements:\n" |
5202 | "matcher #0: is equal to 1" )); |
5203 | |
5204 | v.push_back(1); |
5205 | listener.Clear(); |
5206 | ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener)) |
5207 | << listener.str(); |
5208 | EXPECT_THAT(listener.str(), Eq("where:\n" |
5209 | " - element #0 is matched by matcher #1,\n" |
5210 | " - element #2 is matched by matcher #0" )); |
5211 | } |
5212 | |
5213 | TEST(IsSupersetOfTest, WorksForRhsInitializerList) { |
5214 | const int numbers[] = {1, 3, 6, 2, 4, 5}; |
5215 | EXPECT_THAT(numbers, IsSupersetOf({1, 2})); |
5216 | EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0}))); |
5217 | } |
5218 | |
5219 | TEST(IsSupersetOfTest, WorksWithMoveOnly) { |
5220 | ContainerHelper helper; |
5221 | EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)}))); |
5222 | helper.Call(MakeUniquePtrs({1, 2})); |
5223 | EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)})))); |
5224 | helper.Call(MakeUniquePtrs({2})); |
5225 | } |
5226 | |
5227 | TEST(IsSubsetOfTest, WorksForNativeArray) { |
5228 | const int subset[] = {1, 4}; |
5229 | const int superset[] = {1, 2, 4}; |
5230 | const int disjoint[] = {1, 0, 3}; |
5231 | EXPECT_THAT(subset, IsSubsetOf(subset)); |
5232 | EXPECT_THAT(subset, IsSubsetOf(superset)); |
5233 | EXPECT_THAT(superset, Not(IsSubsetOf(subset))); |
5234 | EXPECT_THAT(subset, Not(IsSubsetOf(disjoint))); |
5235 | EXPECT_THAT(disjoint, Not(IsSubsetOf(subset))); |
5236 | } |
5237 | |
5238 | TEST(IsSubsetOfTest, WorksWithDuplicates) { |
5239 | const int not_enough[] = {1, 2}; |
5240 | const int enough[] = {1, 1, 2}; |
5241 | const int actual[] = {1, 1}; |
5242 | EXPECT_THAT(actual, Not(IsSubsetOf(not_enough))); |
5243 | EXPECT_THAT(actual, IsSubsetOf(enough)); |
5244 | } |
5245 | |
5246 | TEST(IsSubsetOfTest, WorksForEmpty) { |
5247 | vector<int> numbers; |
5248 | vector<int> expected; |
5249 | EXPECT_THAT(numbers, IsSubsetOf(expected)); |
5250 | expected.push_back(1); |
5251 | EXPECT_THAT(numbers, IsSubsetOf(expected)); |
5252 | expected.clear(); |
5253 | numbers.push_back(1); |
5254 | numbers.push_back(2); |
5255 | EXPECT_THAT(numbers, Not(IsSubsetOf(expected))); |
5256 | expected.push_back(1); |
5257 | EXPECT_THAT(numbers, Not(IsSubsetOf(expected))); |
5258 | expected.push_back(2); |
5259 | EXPECT_THAT(numbers, IsSubsetOf(expected)); |
5260 | expected.push_back(3); |
5261 | EXPECT_THAT(numbers, IsSubsetOf(expected)); |
5262 | } |
5263 | |
5264 | TEST(IsSubsetOfTest, WorksForStreamlike) { |
5265 | const int a[5] = {1, 2}; |
5266 | Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a)); |
5267 | |
5268 | vector<int> expected; |
5269 | expected.push_back(1); |
5270 | EXPECT_THAT(s, Not(IsSubsetOf(expected))); |
5271 | expected.push_back(2); |
5272 | expected.push_back(5); |
5273 | EXPECT_THAT(s, IsSubsetOf(expected)); |
5274 | } |
5275 | |
5276 | TEST(IsSubsetOfTest, TakesStlContainer) { |
5277 | const int actual[] = {3, 1, 2}; |
5278 | |
5279 | ::std::list<int> expected; |
5280 | expected.push_back(1); |
5281 | expected.push_back(3); |
5282 | EXPECT_THAT(actual, Not(IsSubsetOf(expected))); |
5283 | |
5284 | expected.push_back(2); |
5285 | expected.push_back(4); |
5286 | EXPECT_THAT(actual, IsSubsetOf(expected)); |
5287 | } |
5288 | |
5289 | TEST(IsSubsetOfTest, Describe) { |
5290 | typedef std::vector<int> IntVec; |
5291 | IntVec expected; |
5292 | expected.push_back(111); |
5293 | expected.push_back(222); |
5294 | expected.push_back(333); |
5295 | |
5296 | EXPECT_THAT( |
5297 | Describe<IntVec>(IsSubsetOf(expected)), |
5298 | Eq("an injection from elements to requirements exists such that:\n" |
5299 | " - an element is equal to 111\n" |
5300 | " - an element is equal to 222\n" |
5301 | " - an element is equal to 333" )); |
5302 | } |
5303 | |
5304 | TEST(IsSubsetOfTest, DescribeNegation) { |
5305 | typedef std::vector<int> IntVec; |
5306 | IntVec expected; |
5307 | expected.push_back(111); |
5308 | expected.push_back(222); |
5309 | expected.push_back(333); |
5310 | EXPECT_THAT( |
5311 | DescribeNegation<IntVec>(IsSubsetOf(expected)), |
5312 | Eq("no injection from elements to requirements exists such that:\n" |
5313 | " - an element is equal to 111\n" |
5314 | " - an element is equal to 222\n" |
5315 | " - an element is equal to 333" )); |
5316 | } |
5317 | |
5318 | TEST(IsSubsetOfTest, MatchAndExplain) { |
5319 | std::vector<int> v; |
5320 | v.push_back(2); |
5321 | v.push_back(3); |
5322 | std::vector<int> expected; |
5323 | expected.push_back(1); |
5324 | expected.push_back(2); |
5325 | StringMatchResultListener listener; |
5326 | ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener)) |
5327 | << listener.str(); |
5328 | EXPECT_THAT(listener.str(), |
5329 | Eq("where the following elements don't match any matchers:\n" |
5330 | "element #1: 3" )); |
5331 | |
5332 | expected.push_back(3); |
5333 | listener.Clear(); |
5334 | ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener)) |
5335 | << listener.str(); |
5336 | EXPECT_THAT(listener.str(), Eq("where:\n" |
5337 | " - element #0 is matched by matcher #1,\n" |
5338 | " - element #1 is matched by matcher #2" )); |
5339 | } |
5340 | |
5341 | TEST(IsSubsetOfTest, WorksForRhsInitializerList) { |
5342 | const int numbers[] = {1, 2, 3}; |
5343 | EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4})); |
5344 | EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2}))); |
5345 | } |
5346 | |
5347 | TEST(IsSubsetOfTest, WorksWithMoveOnly) { |
5348 | ContainerHelper helper; |
5349 | EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)}))); |
5350 | helper.Call(MakeUniquePtrs({1})); |
5351 | EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)})))); |
5352 | helper.Call(MakeUniquePtrs({2})); |
5353 | } |
5354 | |
5355 | // Tests using ElementsAre() and ElementsAreArray() with stream-like |
5356 | // "containers". |
5357 | |
5358 | TEST(ElemensAreStreamTest, WorksForStreamlike) { |
5359 | const int a[5] = {1, 2, 3, 4, 5}; |
5360 | Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a)); |
5361 | EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5)); |
5362 | EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3))); |
5363 | } |
5364 | |
5365 | TEST(ElemensAreArrayStreamTest, WorksForStreamlike) { |
5366 | const int a[5] = {1, 2, 3, 4, 5}; |
5367 | Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a)); |
5368 | |
5369 | vector<int> expected; |
5370 | expected.push_back(1); |
5371 | expected.push_back(2); |
5372 | expected.push_back(3); |
5373 | expected.push_back(4); |
5374 | expected.push_back(5); |
5375 | EXPECT_THAT(s, ElementsAreArray(expected)); |
5376 | |
5377 | expected[3] = 0; |
5378 | EXPECT_THAT(s, Not(ElementsAreArray(expected))); |
5379 | } |
5380 | |
5381 | TEST(ElementsAreTest, WorksWithUncopyable) { |
5382 | Uncopyable objs[2]; |
5383 | objs[0].set_value(-3); |
5384 | objs[1].set_value(1); |
5385 | EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive))); |
5386 | } |
5387 | |
5388 | TEST(ElementsAreTest, WorksWithMoveOnly) { |
5389 | ContainerHelper helper; |
5390 | EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2)))); |
5391 | helper.Call(MakeUniquePtrs({1, 2})); |
5392 | |
5393 | EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)}))); |
5394 | helper.Call(MakeUniquePtrs({3, 4})); |
5395 | } |
5396 | |
5397 | TEST(ElementsAreTest, TakesStlContainer) { |
5398 | const int actual[] = {3, 1, 2}; |
5399 | |
5400 | ::std::list<int> expected; |
5401 | expected.push_back(3); |
5402 | expected.push_back(1); |
5403 | expected.push_back(2); |
5404 | EXPECT_THAT(actual, ElementsAreArray(expected)); |
5405 | |
5406 | expected.push_back(4); |
5407 | EXPECT_THAT(actual, Not(ElementsAreArray(expected))); |
5408 | } |
5409 | |
5410 | // Tests for UnorderedElementsAreArray() |
5411 | |
5412 | TEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) { |
5413 | const int a[] = {0, 1, 2, 3, 4}; |
5414 | std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a)); |
5415 | do { |
5416 | StringMatchResultListener listener; |
5417 | EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a), |
5418 | s, &listener)) << listener.str(); |
5419 | } while (std::next_permutation(s.begin(), s.end())); |
5420 | } |
5421 | |
5422 | TEST(UnorderedElementsAreArrayTest, VectorBool) { |
5423 | const bool a[] = {0, 1, 0, 1, 1}; |
5424 | const bool b[] = {1, 0, 1, 1, 0}; |
5425 | std::vector<bool> expected(a, a + GTEST_ARRAY_SIZE_(a)); |
5426 | std::vector<bool> actual(b, b + GTEST_ARRAY_SIZE_(b)); |
5427 | StringMatchResultListener listener; |
5428 | EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected), |
5429 | actual, &listener)) << listener.str(); |
5430 | } |
5431 | |
5432 | TEST(UnorderedElementsAreArrayTest, WorksForStreamlike) { |
5433 | // Streamlike 'container' provides only minimal iterator support. |
5434 | // Its iterators are tagged with input_iterator_tag, and it has no |
5435 | // size() or empty() methods. |
5436 | const int a[5] = {2, 1, 4, 5, 3}; |
5437 | Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a)); |
5438 | |
5439 | ::std::vector<int> expected; |
5440 | expected.push_back(1); |
5441 | expected.push_back(2); |
5442 | expected.push_back(3); |
5443 | expected.push_back(4); |
5444 | expected.push_back(5); |
5445 | EXPECT_THAT(s, UnorderedElementsAreArray(expected)); |
5446 | |
5447 | expected.push_back(6); |
5448 | EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected))); |
5449 | } |
5450 | |
5451 | TEST(UnorderedElementsAreArrayTest, TakesStlContainer) { |
5452 | const int actual[] = {3, 1, 2}; |
5453 | |
5454 | ::std::list<int> expected; |
5455 | expected.push_back(1); |
5456 | expected.push_back(2); |
5457 | expected.push_back(3); |
5458 | EXPECT_THAT(actual, UnorderedElementsAreArray(expected)); |
5459 | |
5460 | expected.push_back(4); |
5461 | EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected))); |
5462 | } |
5463 | |
5464 | |
5465 | TEST(UnorderedElementsAreArrayTest, TakesInitializerList) { |
5466 | const int a[5] = {2, 1, 4, 5, 3}; |
5467 | EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5})); |
5468 | EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6}))); |
5469 | } |
5470 | |
5471 | TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) { |
5472 | const std::string a[5] = {"a" , "b" , "c" , "d" , "e" }; |
5473 | EXPECT_THAT(a, UnorderedElementsAreArray({"a" , "b" , "c" , "d" , "e" })); |
5474 | EXPECT_THAT(a, Not(UnorderedElementsAreArray({"a" , "b" , "c" , "d" , "ef" }))); |
5475 | } |
5476 | |
5477 | TEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) { |
5478 | const int a[5] = {2, 1, 4, 5, 3}; |
5479 | EXPECT_THAT(a, UnorderedElementsAreArray( |
5480 | {Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)})); |
5481 | EXPECT_THAT(a, Not(UnorderedElementsAreArray( |
5482 | {Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)}))); |
5483 | } |
5484 | |
5485 | TEST(UnorderedElementsAreArrayTest, |
5486 | TakesInitializerListOfDifferentTypedMatchers) { |
5487 | const int a[5] = {2, 1, 4, 5, 3}; |
5488 | // The compiler cannot infer the type of the initializer list if its |
5489 | // elements have different types. We must explicitly specify the |
5490 | // unified element type in this case. |
5491 | EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int> >( |
5492 | {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)})); |
5493 | EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int> >( |
5494 | {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)}))); |
5495 | } |
5496 | |
5497 | |
5498 | TEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) { |
5499 | ContainerHelper helper; |
5500 | EXPECT_CALL(helper, |
5501 | Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)}))); |
5502 | helper.Call(MakeUniquePtrs({2, 1})); |
5503 | } |
5504 | |
5505 | class UnorderedElementsAreTest : public testing::Test { |
5506 | protected: |
5507 | typedef std::vector<int> IntVec; |
5508 | }; |
5509 | |
5510 | TEST_F(UnorderedElementsAreTest, WorksWithUncopyable) { |
5511 | Uncopyable objs[2]; |
5512 | objs[0].set_value(-3); |
5513 | objs[1].set_value(1); |
5514 | EXPECT_THAT(objs, |
5515 | UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3))); |
5516 | } |
5517 | |
5518 | TEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) { |
5519 | const int a[] = {1, 2, 3}; |
5520 | std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a)); |
5521 | do { |
5522 | StringMatchResultListener listener; |
5523 | EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), |
5524 | s, &listener)) << listener.str(); |
5525 | } while (std::next_permutation(s.begin(), s.end())); |
5526 | } |
5527 | |
5528 | TEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) { |
5529 | const int a[] = {1, 2, 3}; |
5530 | std::vector<int> s(a, a + GTEST_ARRAY_SIZE_(a)); |
5531 | std::vector<Matcher<int> > mv; |
5532 | mv.push_back(1); |
5533 | mv.push_back(2); |
5534 | mv.push_back(2); |
5535 | // The element with value '3' matches nothing: fail fast. |
5536 | StringMatchResultListener listener; |
5537 | EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv), |
5538 | s, &listener)) << listener.str(); |
5539 | } |
5540 | |
5541 | TEST_F(UnorderedElementsAreTest, WorksForStreamlike) { |
5542 | // Streamlike 'container' provides only minimal iterator support. |
5543 | // Its iterators are tagged with input_iterator_tag, and it has no |
5544 | // size() or empty() methods. |
5545 | const int a[5] = {2, 1, 4, 5, 3}; |
5546 | Streamlike<int> s(a, a + GTEST_ARRAY_SIZE_(a)); |
5547 | |
5548 | EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5)); |
5549 | EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5))); |
5550 | } |
5551 | |
5552 | TEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) { |
5553 | ContainerHelper helper; |
5554 | EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2)))); |
5555 | helper.Call(MakeUniquePtrs({2, 1})); |
5556 | } |
5557 | |
5558 | // One naive implementation of the matcher runs in O(N!) time, which is too |
5559 | // slow for many real-world inputs. This test shows that our matcher can match |
5560 | // 100 inputs very quickly (a few milliseconds). An O(100!) is 10^158 |
5561 | // iterations and obviously effectively incomputable. |
5562 | // [ RUN ] UnorderedElementsAreTest.Performance |
5563 | // [ OK ] UnorderedElementsAreTest.Performance (4 ms) |
5564 | TEST_F(UnorderedElementsAreTest, Performance) { |
5565 | std::vector<int> s; |
5566 | std::vector<Matcher<int> > mv; |
5567 | for (int i = 0; i < 100; ++i) { |
5568 | s.push_back(i); |
5569 | mv.push_back(_); |
5570 | } |
5571 | mv[50] = Eq(0); |
5572 | StringMatchResultListener listener; |
5573 | EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), |
5574 | s, &listener)) << listener.str(); |
5575 | } |
5576 | |
5577 | // Another variant of 'Performance' with similar expectations. |
5578 | // [ RUN ] UnorderedElementsAreTest.PerformanceHalfStrict |
5579 | // [ OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms) |
5580 | TEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) { |
5581 | std::vector<int> s; |
5582 | std::vector<Matcher<int> > mv; |
5583 | for (int i = 0; i < 100; ++i) { |
5584 | s.push_back(i); |
5585 | if (i & 1) { |
5586 | mv.push_back(_); |
5587 | } else { |
5588 | mv.push_back(i); |
5589 | } |
5590 | } |
5591 | StringMatchResultListener listener; |
5592 | EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), |
5593 | s, &listener)) << listener.str(); |
5594 | } |
5595 | |
5596 | TEST_F(UnorderedElementsAreTest, FailMessageCountWrong) { |
5597 | std::vector<int> v; |
5598 | v.push_back(4); |
5599 | StringMatchResultListener listener; |
5600 | EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), |
5601 | v, &listener)) << listener.str(); |
5602 | EXPECT_THAT(listener.str(), Eq("which has 1 element" )); |
5603 | } |
5604 | |
5605 | TEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) { |
5606 | std::vector<int> v; |
5607 | StringMatchResultListener listener; |
5608 | EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), |
5609 | v, &listener)) << listener.str(); |
5610 | EXPECT_THAT(listener.str(), Eq("" )); |
5611 | } |
5612 | |
5613 | TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) { |
5614 | std::vector<int> v; |
5615 | v.push_back(1); |
5616 | v.push_back(1); |
5617 | StringMatchResultListener listener; |
5618 | EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), |
5619 | v, &listener)) << listener.str(); |
5620 | EXPECT_THAT( |
5621 | listener.str(), |
5622 | Eq("where the following matchers don't match any elements:\n" |
5623 | "matcher #1: is equal to 2" )); |
5624 | } |
5625 | |
5626 | TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) { |
5627 | std::vector<int> v; |
5628 | v.push_back(1); |
5629 | v.push_back(2); |
5630 | StringMatchResultListener listener; |
5631 | EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1), |
5632 | v, &listener)) << listener.str(); |
5633 | EXPECT_THAT( |
5634 | listener.str(), |
5635 | Eq("where the following elements don't match any matchers:\n" |
5636 | "element #1: 2" )); |
5637 | } |
5638 | |
5639 | TEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) { |
5640 | std::vector<int> v; |
5641 | v.push_back(2); |
5642 | v.push_back(3); |
5643 | StringMatchResultListener listener; |
5644 | EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), |
5645 | v, &listener)) << listener.str(); |
5646 | EXPECT_THAT( |
5647 | listener.str(), |
5648 | Eq("where" |
5649 | " the following matchers don't match any elements:\n" |
5650 | "matcher #0: is equal to 1\n" |
5651 | "and" |
5652 | " where" |
5653 | " the following elements don't match any matchers:\n" |
5654 | "element #1: 3" )); |
5655 | } |
5656 | |
5657 | // Test helper for formatting element, matcher index pairs in expectations. |
5658 | static std::string EMString(int element, int matcher) { |
5659 | stringstream ss; |
5660 | ss << "(element #" << element << ", matcher #" << matcher << ")" ; |
5661 | return ss.str(); |
5662 | } |
5663 | |
5664 | TEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) { |
5665 | // A situation where all elements and matchers have a match |
5666 | // associated with them, but the max matching is not perfect. |
5667 | std::vector<std::string> v; |
5668 | v.push_back("a" ); |
5669 | v.push_back("b" ); |
5670 | v.push_back("c" ); |
5671 | StringMatchResultListener listener; |
5672 | EXPECT_FALSE(ExplainMatchResult( |
5673 | UnorderedElementsAre("a" , "a" , AnyOf("b" , "c" )), v, &listener)) |
5674 | << listener.str(); |
5675 | |
5676 | std::string prefix = |
5677 | "where no permutation of the elements can satisfy all matchers, " |
5678 | "and the closest match is 2 of 3 matchers with the " |
5679 | "pairings:\n" ; |
5680 | |
5681 | // We have to be a bit loose here, because there are 4 valid max matches. |
5682 | EXPECT_THAT( |
5683 | listener.str(), |
5684 | AnyOf(prefix + "{\n " + EMString(0, 0) + |
5685 | ",\n " + EMString(1, 2) + "\n}" , |
5686 | prefix + "{\n " + EMString(0, 1) + |
5687 | ",\n " + EMString(1, 2) + "\n}" , |
5688 | prefix + "{\n " + EMString(0, 0) + |
5689 | ",\n " + EMString(2, 2) + "\n}" , |
5690 | prefix + "{\n " + EMString(0, 1) + |
5691 | ",\n " + EMString(2, 2) + "\n}" )); |
5692 | } |
5693 | |
5694 | TEST_F(UnorderedElementsAreTest, Describe) { |
5695 | EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()), |
5696 | Eq("is empty" )); |
5697 | EXPECT_THAT( |
5698 | Describe<IntVec>(UnorderedElementsAre(345)), |
5699 | Eq("has 1 element and that element is equal to 345" )); |
5700 | EXPECT_THAT( |
5701 | Describe<IntVec>(UnorderedElementsAre(111, 222, 333)), |
5702 | Eq("has 3 elements and there exists some permutation " |
5703 | "of elements such that:\n" |
5704 | " - element #0 is equal to 111, and\n" |
5705 | " - element #1 is equal to 222, and\n" |
5706 | " - element #2 is equal to 333" )); |
5707 | } |
5708 | |
5709 | TEST_F(UnorderedElementsAreTest, DescribeNegation) { |
5710 | EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()), |
5711 | Eq("isn't empty" )); |
5712 | EXPECT_THAT( |
5713 | DescribeNegation<IntVec>(UnorderedElementsAre(345)), |
5714 | Eq("doesn't have 1 element, or has 1 element that isn't equal to 345" )); |
5715 | EXPECT_THAT( |
5716 | DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)), |
5717 | Eq("doesn't have 3 elements, or there exists no permutation " |
5718 | "of elements such that:\n" |
5719 | " - element #0 is equal to 123, and\n" |
5720 | " - element #1 is equal to 234, and\n" |
5721 | " - element #2 is equal to 345" )); |
5722 | } |
5723 | |
5724 | namespace { |
5725 | |
5726 | // Used as a check on the more complex max flow method used in the |
5727 | // real testing::internal::FindMaxBipartiteMatching. This method is |
5728 | // compatible but runs in worst-case factorial time, so we only |
5729 | // use it in testing for small problem sizes. |
5730 | template <typename Graph> |
5731 | class BacktrackingMaxBPMState { |
5732 | public: |
5733 | // Does not take ownership of 'g'. |
5734 | explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) { } |
5735 | |
5736 | ElementMatcherPairs Compute() { |
5737 | if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) { |
5738 | return best_so_far_; |
5739 | } |
5740 | lhs_used_.assign(graph_->LhsSize(), kUnused); |
5741 | rhs_used_.assign(graph_->RhsSize(), kUnused); |
5742 | for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) { |
5743 | matches_.clear(); |
5744 | RecurseInto(irhs); |
5745 | if (best_so_far_.size() == graph_->RhsSize()) |
5746 | break; |
5747 | } |
5748 | return best_so_far_; |
5749 | } |
5750 | |
5751 | private: |
5752 | static const size_t kUnused = static_cast<size_t>(-1); |
5753 | |
5754 | void PushMatch(size_t lhs, size_t rhs) { |
5755 | matches_.push_back(ElementMatcherPair(lhs, rhs)); |
5756 | lhs_used_[lhs] = rhs; |
5757 | rhs_used_[rhs] = lhs; |
5758 | if (matches_.size() > best_so_far_.size()) { |
5759 | best_so_far_ = matches_; |
5760 | } |
5761 | } |
5762 | |
5763 | void PopMatch() { |
5764 | const ElementMatcherPair& back = matches_.back(); |
5765 | lhs_used_[back.first] = kUnused; |
5766 | rhs_used_[back.second] = kUnused; |
5767 | matches_.pop_back(); |
5768 | } |
5769 | |
5770 | bool RecurseInto(size_t irhs) { |
5771 | if (rhs_used_[irhs] != kUnused) { |
5772 | return true; |
5773 | } |
5774 | for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) { |
5775 | if (lhs_used_[ilhs] != kUnused) { |
5776 | continue; |
5777 | } |
5778 | if (!graph_->HasEdge(ilhs, irhs)) { |
5779 | continue; |
5780 | } |
5781 | PushMatch(ilhs, irhs); |
5782 | if (best_so_far_.size() == graph_->RhsSize()) { |
5783 | return false; |
5784 | } |
5785 | for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) { |
5786 | if (!RecurseInto(mi)) return false; |
5787 | } |
5788 | PopMatch(); |
5789 | } |
5790 | return true; |
5791 | } |
5792 | |
5793 | const Graph* graph_; // not owned |
5794 | std::vector<size_t> lhs_used_; |
5795 | std::vector<size_t> rhs_used_; |
5796 | ElementMatcherPairs matches_; |
5797 | ElementMatcherPairs best_so_far_; |
5798 | }; |
5799 | |
5800 | template <typename Graph> |
5801 | const size_t BacktrackingMaxBPMState<Graph>::kUnused; |
5802 | |
5803 | } // namespace |
5804 | |
5805 | // Implement a simple backtracking algorithm to determine if it is possible |
5806 | // to find one element per matcher, without reusing elements. |
5807 | template <typename Graph> |
5808 | ElementMatcherPairs |
5809 | FindBacktrackingMaxBPM(const Graph& g) { |
5810 | return BacktrackingMaxBPMState<Graph>(&g).Compute(); |
5811 | } |
5812 | |
5813 | class BacktrackingBPMTest : public ::testing::Test { }; |
5814 | |
5815 | // Tests the MaxBipartiteMatching algorithm with square matrices. |
5816 | // The single int param is the # of nodes on each of the left and right sides. |
5817 | class BipartiteTest : public ::testing::TestWithParam<size_t> {}; |
5818 | |
5819 | // Verify all match graphs up to some moderate number of edges. |
5820 | TEST_P(BipartiteTest, Exhaustive) { |
5821 | size_t nodes = GetParam(); |
5822 | MatchMatrix graph(nodes, nodes); |
5823 | do { |
5824 | ElementMatcherPairs matches = |
5825 | internal::FindMaxBipartiteMatching(graph); |
5826 | EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size()) |
5827 | << "graph: " << graph.DebugString(); |
5828 | // Check that all elements of matches are in the graph. |
5829 | // Check that elements of first and second are unique. |
5830 | std::vector<bool> seen_element(graph.LhsSize()); |
5831 | std::vector<bool> seen_matcher(graph.RhsSize()); |
5832 | SCOPED_TRACE(PrintToString(matches)); |
5833 | for (size_t i = 0; i < matches.size(); ++i) { |
5834 | size_t ilhs = matches[i].first; |
5835 | size_t irhs = matches[i].second; |
5836 | EXPECT_TRUE(graph.HasEdge(ilhs, irhs)); |
5837 | EXPECT_FALSE(seen_element[ilhs]); |
5838 | EXPECT_FALSE(seen_matcher[irhs]); |
5839 | seen_element[ilhs] = true; |
5840 | seen_matcher[irhs] = true; |
5841 | } |
5842 | } while (graph.NextGraph()); |
5843 | } |
5844 | |
5845 | INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteTest, |
5846 | ::testing::Range(size_t{0}, size_t{5})); |
5847 | |
5848 | // Parameterized by a pair interpreted as (LhsSize, RhsSize). |
5849 | class BipartiteNonSquareTest |
5850 | : public ::testing::TestWithParam<std::pair<size_t, size_t> > { |
5851 | }; |
5852 | |
5853 | TEST_F(BipartiteNonSquareTest, SimpleBacktracking) { |
5854 | // ....... |
5855 | // 0:-----\ : |
5856 | // 1:---\ | : |
5857 | // 2:---\ | : |
5858 | // 3:-\ | | : |
5859 | // :.......: |
5860 | // 0 1 2 |
5861 | MatchMatrix g(4, 3); |
5862 | static const size_t kEdges[][2] = {{0, 2}, {1, 1}, {2, 1}, {3, 0}}; |
5863 | for (size_t i = 0; i < GTEST_ARRAY_SIZE_(kEdges); ++i) { |
5864 | g.SetEdge(kEdges[i][0], kEdges[i][1], true); |
5865 | } |
5866 | EXPECT_THAT(FindBacktrackingMaxBPM(g), |
5867 | ElementsAre(Pair(3, 0), |
5868 | Pair(AnyOf(1, 2), 1), |
5869 | Pair(0, 2))) << g.DebugString(); |
5870 | } |
5871 | |
5872 | // Verify a few nonsquare matrices. |
5873 | TEST_P(BipartiteNonSquareTest, Exhaustive) { |
5874 | size_t nlhs = GetParam().first; |
5875 | size_t nrhs = GetParam().second; |
5876 | MatchMatrix graph(nlhs, nrhs); |
5877 | do { |
5878 | EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), |
5879 | internal::FindMaxBipartiteMatching(graph).size()) |
5880 | << "graph: " << graph.DebugString() |
5881 | << "\nbacktracking: " |
5882 | << PrintToString(FindBacktrackingMaxBPM(graph)) |
5883 | << "\nmax flow: " |
5884 | << PrintToString(internal::FindMaxBipartiteMatching(graph)); |
5885 | } while (graph.NextGraph()); |
5886 | } |
5887 | |
5888 | INSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteNonSquareTest, |
5889 | testing::Values( |
5890 | std::make_pair(1, 2), |
5891 | std::make_pair(2, 1), |
5892 | std::make_pair(3, 2), |
5893 | std::make_pair(2, 3), |
5894 | std::make_pair(4, 1), |
5895 | std::make_pair(1, 4), |
5896 | std::make_pair(4, 3), |
5897 | std::make_pair(3, 4))); |
5898 | |
5899 | class BipartiteRandomTest |
5900 | : public ::testing::TestWithParam<std::pair<int, int> > { |
5901 | }; |
5902 | |
5903 | // Verifies a large sample of larger graphs. |
5904 | TEST_P(BipartiteRandomTest, LargerNets) { |
5905 | int nodes = GetParam().first; |
5906 | int iters = GetParam().second; |
5907 | MatchMatrix graph(static_cast<size_t>(nodes), static_cast<size_t>(nodes)); |
5908 | |
5909 | auto seed = static_cast<testing::internal::UInt32>(GTEST_FLAG(random_seed)); |
5910 | if (seed == 0) { |
5911 | seed = static_cast<testing::internal::UInt32>(time(nullptr)); |
5912 | } |
5913 | |
5914 | for (; iters > 0; --iters, ++seed) { |
5915 | srand(static_cast<unsigned int>(seed)); |
5916 | graph.Randomize(); |
5917 | EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), |
5918 | internal::FindMaxBipartiteMatching(graph).size()) |
5919 | << " graph: " << graph.DebugString() |
5920 | << "\nTo reproduce the failure, rerun the test with the flag" |
5921 | " --" << GTEST_FLAG_PREFIX_ << "random_seed=" << seed; |
5922 | } |
5923 | } |
5924 | |
5925 | // Test argument is a std::pair<int, int> representing (nodes, iters). |
5926 | INSTANTIATE_TEST_SUITE_P(Samples, BipartiteRandomTest, |
5927 | testing::Values( |
5928 | std::make_pair(5, 10000), |
5929 | std::make_pair(6, 5000), |
5930 | std::make_pair(7, 2000), |
5931 | std::make_pair(8, 500), |
5932 | std::make_pair(9, 100))); |
5933 | |
5934 | // Tests IsReadableTypeName(). |
5935 | |
5936 | TEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) { |
5937 | EXPECT_TRUE(IsReadableTypeName("int" )); |
5938 | EXPECT_TRUE(IsReadableTypeName("const unsigned char*" )); |
5939 | EXPECT_TRUE(IsReadableTypeName("MyMap<int, void*>" )); |
5940 | EXPECT_TRUE(IsReadableTypeName("void (*)(int, bool)" )); |
5941 | } |
5942 | |
5943 | TEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) { |
5944 | EXPECT_TRUE(IsReadableTypeName("my_long_namespace::MyClassName" )); |
5945 | EXPECT_TRUE(IsReadableTypeName("int [5][6][7][8][9][10][11]" )); |
5946 | EXPECT_TRUE(IsReadableTypeName("my_namespace::MyOuterClass::MyInnerClass" )); |
5947 | } |
5948 | |
5949 | TEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) { |
5950 | EXPECT_FALSE( |
5951 | IsReadableTypeName("basic_string<char, std::char_traits<char> >" )); |
5952 | EXPECT_FALSE(IsReadableTypeName("std::vector<int, std::alloc_traits<int> >" )); |
5953 | } |
5954 | |
5955 | TEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) { |
5956 | EXPECT_FALSE(IsReadableTypeName("void (&)(int, bool, char, float)" )); |
5957 | } |
5958 | |
5959 | // Tests FormatMatcherDescription(). |
5960 | |
5961 | TEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) { |
5962 | EXPECT_EQ("is even" , |
5963 | FormatMatcherDescription(false, "IsEven" , Strings())); |
5964 | EXPECT_EQ("not (is even)" , |
5965 | FormatMatcherDescription(true, "IsEven" , Strings())); |
5966 | |
5967 | const char* params[] = {"5" }; |
5968 | EXPECT_EQ("equals 5" , |
5969 | FormatMatcherDescription(false, "Equals" , |
5970 | Strings(params, params + 1))); |
5971 | |
5972 | const char* params2[] = {"5" , "8" }; |
5973 | EXPECT_EQ("is in range (5, 8)" , |
5974 | FormatMatcherDescription(false, "IsInRange" , |
5975 | Strings(params2, params2 + 2))); |
5976 | } |
5977 | |
5978 | // Tests PolymorphicMatcher::mutable_impl(). |
5979 | TEST(PolymorphicMatcherTest, CanAccessMutableImpl) { |
5980 | PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42)); |
5981 | DivisibleByImpl& impl = m.mutable_impl(); |
5982 | EXPECT_EQ(42, impl.divider()); |
5983 | |
5984 | impl.set_divider(0); |
5985 | EXPECT_EQ(0, m.mutable_impl().divider()); |
5986 | } |
5987 | |
5988 | // Tests PolymorphicMatcher::impl(). |
5989 | TEST(PolymorphicMatcherTest, CanAccessImpl) { |
5990 | const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42)); |
5991 | const DivisibleByImpl& impl = m.impl(); |
5992 | EXPECT_EQ(42, impl.divider()); |
5993 | } |
5994 | |
5995 | TEST(MatcherTupleTest, ExplainsMatchFailure) { |
5996 | stringstream ss1; |
5997 | ExplainMatchFailureTupleTo( |
5998 | std::make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)), |
5999 | std::make_tuple('a', 10), &ss1); |
6000 | EXPECT_EQ("" , ss1.str()); // Successful match. |
6001 | |
6002 | stringstream ss2; |
6003 | ExplainMatchFailureTupleTo( |
6004 | std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))), |
6005 | std::make_tuple(2, 'b'), &ss2); |
6006 | EXPECT_EQ(" Expected arg #0: is > 5\n" |
6007 | " Actual: 2, which is 3 less than 5\n" |
6008 | " Expected arg #1: is equal to 'a' (97, 0x61)\n" |
6009 | " Actual: 'b' (98, 0x62)\n" , |
6010 | ss2.str()); // Failed match where both arguments need explanation. |
6011 | |
6012 | stringstream ss3; |
6013 | ExplainMatchFailureTupleTo( |
6014 | std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))), |
6015 | std::make_tuple(2, 'a'), &ss3); |
6016 | EXPECT_EQ(" Expected arg #0: is > 5\n" |
6017 | " Actual: 2, which is 3 less than 5\n" , |
6018 | ss3.str()); // Failed match where only one argument needs |
6019 | // explanation. |
6020 | } |
6021 | |
6022 | // Tests Each(). |
6023 | |
6024 | TEST(EachTest, ExplainsMatchResultCorrectly) { |
6025 | set<int> a; // empty |
6026 | |
6027 | Matcher<set<int> > m = Each(2); |
6028 | EXPECT_EQ("" , Explain(m, a)); |
6029 | |
6030 | Matcher<const int(&)[1]> n = Each(1); // NOLINT |
6031 | |
6032 | const int b[1] = {1}; |
6033 | EXPECT_EQ("" , Explain(n, b)); |
6034 | |
6035 | n = Each(3); |
6036 | EXPECT_EQ("whose element #0 doesn't match" , Explain(n, b)); |
6037 | |
6038 | a.insert(1); |
6039 | a.insert(2); |
6040 | a.insert(3); |
6041 | m = Each(GreaterThan(0)); |
6042 | EXPECT_EQ("" , Explain(m, a)); |
6043 | |
6044 | m = Each(GreaterThan(10)); |
6045 | EXPECT_EQ("whose element #0 doesn't match, which is 9 less than 10" , |
6046 | Explain(m, a)); |
6047 | } |
6048 | |
6049 | TEST(EachTest, DescribesItselfCorrectly) { |
6050 | Matcher<vector<int> > m = Each(1); |
6051 | EXPECT_EQ("only contains elements that is equal to 1" , Describe(m)); |
6052 | |
6053 | Matcher<vector<int> > m2 = Not(m); |
6054 | EXPECT_EQ("contains some element that isn't equal to 1" , Describe(m2)); |
6055 | } |
6056 | |
6057 | TEST(EachTest, MatchesVectorWhenAllElementsMatch) { |
6058 | vector<int> some_vector; |
6059 | EXPECT_THAT(some_vector, Each(1)); |
6060 | some_vector.push_back(3); |
6061 | EXPECT_THAT(some_vector, Not(Each(1))); |
6062 | EXPECT_THAT(some_vector, Each(3)); |
6063 | some_vector.push_back(1); |
6064 | some_vector.push_back(2); |
6065 | EXPECT_THAT(some_vector, Not(Each(3))); |
6066 | EXPECT_THAT(some_vector, Each(Lt(3.5))); |
6067 | |
6068 | vector<std::string> another_vector; |
6069 | another_vector.push_back("fee" ); |
6070 | EXPECT_THAT(another_vector, Each(std::string("fee" ))); |
6071 | another_vector.push_back("fie" ); |
6072 | another_vector.push_back("foe" ); |
6073 | another_vector.push_back("fum" ); |
6074 | EXPECT_THAT(another_vector, Not(Each(std::string("fee" )))); |
6075 | } |
6076 | |
6077 | TEST(EachTest, MatchesMapWhenAllElementsMatch) { |
6078 | map<const char*, int> my_map; |
6079 | const char* bar = "a string" ; |
6080 | my_map[bar] = 2; |
6081 | EXPECT_THAT(my_map, Each(make_pair(bar, 2))); |
6082 | |
6083 | map<std::string, int> another_map; |
6084 | EXPECT_THAT(another_map, Each(make_pair(std::string("fee" ), 1))); |
6085 | another_map["fee" ] = 1; |
6086 | EXPECT_THAT(another_map, Each(make_pair(std::string("fee" ), 1))); |
6087 | another_map["fie" ] = 2; |
6088 | another_map["foe" ] = 3; |
6089 | another_map["fum" ] = 4; |
6090 | EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fee" ), 1)))); |
6091 | EXPECT_THAT(another_map, Not(Each(make_pair(std::string("fum" ), 1)))); |
6092 | EXPECT_THAT(another_map, Each(Pair(_, Gt(0)))); |
6093 | } |
6094 | |
6095 | TEST(EachTest, AcceptsMatcher) { |
6096 | const int a[] = {1, 2, 3}; |
6097 | EXPECT_THAT(a, Each(Gt(0))); |
6098 | EXPECT_THAT(a, Not(Each(Gt(1)))); |
6099 | } |
6100 | |
6101 | TEST(EachTest, WorksForNativeArrayAsTuple) { |
6102 | const int a[] = {1, 2}; |
6103 | const int* const pointer = a; |
6104 | EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0))); |
6105 | EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1)))); |
6106 | } |
6107 | |
6108 | TEST(EachTest, WorksWithMoveOnly) { |
6109 | ContainerHelper helper; |
6110 | EXPECT_CALL(helper, Call(Each(Pointee(Gt(0))))); |
6111 | helper.Call(MakeUniquePtrs({1, 2})); |
6112 | } |
6113 | |
6114 | // For testing Pointwise(). |
6115 | class IsHalfOfMatcher { |
6116 | public: |
6117 | template <typename T1, typename T2> |
6118 | bool MatchAndExplain(const std::tuple<T1, T2>& a_pair, |
6119 | MatchResultListener* listener) const { |
6120 | if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) { |
6121 | *listener << "where the second is " << std::get<1>(a_pair); |
6122 | return true; |
6123 | } else { |
6124 | *listener << "where the second/2 is " << std::get<1>(a_pair) / 2; |
6125 | return false; |
6126 | } |
6127 | } |
6128 | |
6129 | void DescribeTo(ostream* os) const { |
6130 | *os << "are a pair where the first is half of the second" ; |
6131 | } |
6132 | |
6133 | void DescribeNegationTo(ostream* os) const { |
6134 | *os << "are a pair where the first isn't half of the second" ; |
6135 | } |
6136 | }; |
6137 | |
6138 | PolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() { |
6139 | return MakePolymorphicMatcher(IsHalfOfMatcher()); |
6140 | } |
6141 | |
6142 | TEST(PointwiseTest, DescribesSelf) { |
6143 | vector<int> rhs; |
6144 | rhs.push_back(1); |
6145 | rhs.push_back(2); |
6146 | rhs.push_back(3); |
6147 | const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs); |
6148 | EXPECT_EQ("contains 3 values, where each value and its corresponding value " |
6149 | "in { 1, 2, 3 } are a pair where the first is half of the second" , |
6150 | Describe(m)); |
6151 | EXPECT_EQ("doesn't contain exactly 3 values, or contains a value x at some " |
6152 | "index i where x and the i-th value of { 1, 2, 3 } are a pair " |
6153 | "where the first isn't half of the second" , |
6154 | DescribeNegation(m)); |
6155 | } |
6156 | |
6157 | TEST(PointwiseTest, MakesCopyOfRhs) { |
6158 | list<signed char> rhs; |
6159 | rhs.push_back(2); |
6160 | rhs.push_back(4); |
6161 | |
6162 | int lhs[] = {1, 2}; |
6163 | const Matcher<const int (&)[2]> m = Pointwise(IsHalfOf(), rhs); |
6164 | EXPECT_THAT(lhs, m); |
6165 | |
6166 | // Changing rhs now shouldn't affect m, which made a copy of rhs. |
6167 | rhs.push_back(6); |
6168 | EXPECT_THAT(lhs, m); |
6169 | } |
6170 | |
6171 | TEST(PointwiseTest, WorksForLhsNativeArray) { |
6172 | const int lhs[] = {1, 2, 3}; |
6173 | vector<int> rhs; |
6174 | rhs.push_back(2); |
6175 | rhs.push_back(4); |
6176 | rhs.push_back(6); |
6177 | EXPECT_THAT(lhs, Pointwise(Lt(), rhs)); |
6178 | EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs))); |
6179 | } |
6180 | |
6181 | TEST(PointwiseTest, WorksForRhsNativeArray) { |
6182 | const int rhs[] = {1, 2, 3}; |
6183 | vector<int> lhs; |
6184 | lhs.push_back(2); |
6185 | lhs.push_back(4); |
6186 | lhs.push_back(6); |
6187 | EXPECT_THAT(lhs, Pointwise(Gt(), rhs)); |
6188 | EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs))); |
6189 | } |
6190 | |
6191 | // Test is effective only with sanitizers. |
6192 | TEST(PointwiseTest, WorksForVectorOfBool) { |
6193 | vector<bool> rhs(3, false); |
6194 | rhs[1] = true; |
6195 | vector<bool> lhs = rhs; |
6196 | EXPECT_THAT(lhs, Pointwise(Eq(), rhs)); |
6197 | rhs[0] = true; |
6198 | EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs))); |
6199 | } |
6200 | |
6201 | |
6202 | TEST(PointwiseTest, WorksForRhsInitializerList) { |
6203 | const vector<int> lhs{2, 4, 6}; |
6204 | EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3})); |
6205 | EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7}))); |
6206 | } |
6207 | |
6208 | |
6209 | TEST(PointwiseTest, RejectsWrongSize) { |
6210 | const double lhs[2] = {1, 2}; |
6211 | const int rhs[1] = {0}; |
6212 | EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs))); |
6213 | EXPECT_EQ("which contains 2 values" , |
6214 | Explain(Pointwise(Gt(), rhs), lhs)); |
6215 | |
6216 | const int rhs2[3] = {0, 1, 2}; |
6217 | EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2))); |
6218 | } |
6219 | |
6220 | TEST(PointwiseTest, RejectsWrongContent) { |
6221 | const double lhs[3] = {1, 2, 3}; |
6222 | const int rhs[3] = {2, 6, 4}; |
6223 | EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs))); |
6224 | EXPECT_EQ("where the value pair (2, 6) at index #1 don't match, " |
6225 | "where the second/2 is 3" , |
6226 | Explain(Pointwise(IsHalfOf(), rhs), lhs)); |
6227 | } |
6228 | |
6229 | TEST(PointwiseTest, AcceptsCorrectContent) { |
6230 | const double lhs[3] = {1, 2, 3}; |
6231 | const int rhs[3] = {2, 4, 6}; |
6232 | EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs)); |
6233 | EXPECT_EQ("" , Explain(Pointwise(IsHalfOf(), rhs), lhs)); |
6234 | } |
6235 | |
6236 | TEST(PointwiseTest, AllowsMonomorphicInnerMatcher) { |
6237 | const double lhs[3] = {1, 2, 3}; |
6238 | const int rhs[3] = {2, 4, 6}; |
6239 | const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf(); |
6240 | EXPECT_THAT(lhs, Pointwise(m1, rhs)); |
6241 | EXPECT_EQ("" , Explain(Pointwise(m1, rhs), lhs)); |
6242 | |
6243 | // This type works as a std::tuple<const double&, const int&> can be |
6244 | // implicitly cast to std::tuple<double, int>. |
6245 | const Matcher<std::tuple<double, int>> m2 = IsHalfOf(); |
6246 | EXPECT_THAT(lhs, Pointwise(m2, rhs)); |
6247 | EXPECT_EQ("" , Explain(Pointwise(m2, rhs), lhs)); |
6248 | } |
6249 | |
6250 | MATCHER(PointeeEquals, "Points to an equal value" ) { |
6251 | return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)), |
6252 | ::testing::get<0>(arg), result_listener); |
6253 | } |
6254 | |
6255 | TEST(PointwiseTest, WorksWithMoveOnly) { |
6256 | ContainerHelper helper; |
6257 | EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2}))); |
6258 | helper.Call(MakeUniquePtrs({1, 2})); |
6259 | } |
6260 | |
6261 | TEST(UnorderedPointwiseTest, DescribesSelf) { |
6262 | vector<int> rhs; |
6263 | rhs.push_back(1); |
6264 | rhs.push_back(2); |
6265 | rhs.push_back(3); |
6266 | const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs); |
6267 | EXPECT_EQ( |
6268 | "has 3 elements and there exists some permutation of elements such " |
6269 | "that:\n" |
6270 | " - element #0 and 1 are a pair where the first is half of the second, " |
6271 | "and\n" |
6272 | " - element #1 and 2 are a pair where the first is half of the second, " |
6273 | "and\n" |
6274 | " - element #2 and 3 are a pair where the first is half of the second" , |
6275 | Describe(m)); |
6276 | EXPECT_EQ( |
6277 | "doesn't have 3 elements, or there exists no permutation of elements " |
6278 | "such that:\n" |
6279 | " - element #0 and 1 are a pair where the first is half of the second, " |
6280 | "and\n" |
6281 | " - element #1 and 2 are a pair where the first is half of the second, " |
6282 | "and\n" |
6283 | " - element #2 and 3 are a pair where the first is half of the second" , |
6284 | DescribeNegation(m)); |
6285 | } |
6286 | |
6287 | TEST(UnorderedPointwiseTest, MakesCopyOfRhs) { |
6288 | list<signed char> rhs; |
6289 | rhs.push_back(2); |
6290 | rhs.push_back(4); |
6291 | |
6292 | int lhs[] = {2, 1}; |
6293 | const Matcher<const int (&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs); |
6294 | EXPECT_THAT(lhs, m); |
6295 | |
6296 | // Changing rhs now shouldn't affect m, which made a copy of rhs. |
6297 | rhs.push_back(6); |
6298 | EXPECT_THAT(lhs, m); |
6299 | } |
6300 | |
6301 | TEST(UnorderedPointwiseTest, WorksForLhsNativeArray) { |
6302 | const int lhs[] = {1, 2, 3}; |
6303 | vector<int> rhs; |
6304 | rhs.push_back(4); |
6305 | rhs.push_back(6); |
6306 | rhs.push_back(2); |
6307 | EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs)); |
6308 | EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs))); |
6309 | } |
6310 | |
6311 | TEST(UnorderedPointwiseTest, WorksForRhsNativeArray) { |
6312 | const int rhs[] = {1, 2, 3}; |
6313 | vector<int> lhs; |
6314 | lhs.push_back(4); |
6315 | lhs.push_back(2); |
6316 | lhs.push_back(6); |
6317 | EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs)); |
6318 | EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs))); |
6319 | } |
6320 | |
6321 | |
6322 | TEST(UnorderedPointwiseTest, WorksForRhsInitializerList) { |
6323 | const vector<int> lhs{2, 4, 6}; |
6324 | EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3})); |
6325 | EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7}))); |
6326 | } |
6327 | |
6328 | |
6329 | TEST(UnorderedPointwiseTest, RejectsWrongSize) { |
6330 | const double lhs[2] = {1, 2}; |
6331 | const int rhs[1] = {0}; |
6332 | EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs))); |
6333 | EXPECT_EQ("which has 2 elements" , |
6334 | Explain(UnorderedPointwise(Gt(), rhs), lhs)); |
6335 | |
6336 | const int rhs2[3] = {0, 1, 2}; |
6337 | EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2))); |
6338 | } |
6339 | |
6340 | TEST(UnorderedPointwiseTest, RejectsWrongContent) { |
6341 | const double lhs[3] = {1, 2, 3}; |
6342 | const int rhs[3] = {2, 6, 6}; |
6343 | EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs))); |
6344 | EXPECT_EQ("where the following elements don't match any matchers:\n" |
6345 | "element #1: 2" , |
6346 | Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs)); |
6347 | } |
6348 | |
6349 | TEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) { |
6350 | const double lhs[3] = {1, 2, 3}; |
6351 | const int rhs[3] = {2, 4, 6}; |
6352 | EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs)); |
6353 | } |
6354 | |
6355 | TEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) { |
6356 | const double lhs[3] = {1, 2, 3}; |
6357 | const int rhs[3] = {6, 4, 2}; |
6358 | EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs)); |
6359 | } |
6360 | |
6361 | TEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) { |
6362 | const double lhs[3] = {1, 2, 3}; |
6363 | const int rhs[3] = {4, 6, 2}; |
6364 | const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf(); |
6365 | EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs)); |
6366 | |
6367 | // This type works as a std::tuple<const double&, const int&> can be |
6368 | // implicitly cast to std::tuple<double, int>. |
6369 | const Matcher<std::tuple<double, int>> m2 = IsHalfOf(); |
6370 | EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs)); |
6371 | } |
6372 | |
6373 | TEST(UnorderedPointwiseTest, WorksWithMoveOnly) { |
6374 | ContainerHelper helper; |
6375 | EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(), |
6376 | std::vector<int>{1, 2}))); |
6377 | helper.Call(MakeUniquePtrs({2, 1})); |
6378 | } |
6379 | |
6380 | // Sample optional type implementation with minimal requirements for use with |
6381 | // Optional matcher. |
6382 | template <typename T> |
6383 | class SampleOptional { |
6384 | public: |
6385 | using value_type = T; |
6386 | explicit SampleOptional(T value) |
6387 | : value_(std::move(value)), has_value_(true) {} |
6388 | SampleOptional() : value_(), has_value_(false) {} |
6389 | operator bool() const { return has_value_; } |
6390 | const T& operator*() const { return value_; } |
6391 | |
6392 | private: |
6393 | T value_; |
6394 | bool has_value_; |
6395 | }; |
6396 | |
6397 | TEST(OptionalTest, DescribesSelf) { |
6398 | const Matcher<SampleOptional<int>> m = Optional(Eq(1)); |
6399 | EXPECT_EQ("value is equal to 1" , Describe(m)); |
6400 | } |
6401 | |
6402 | TEST(OptionalTest, ExplainsSelf) { |
6403 | const Matcher<SampleOptional<int>> m = Optional(Eq(1)); |
6404 | EXPECT_EQ("whose value 1 matches" , Explain(m, SampleOptional<int>(1))); |
6405 | EXPECT_EQ("whose value 2 doesn't match" , Explain(m, SampleOptional<int>(2))); |
6406 | } |
6407 | |
6408 | TEST(OptionalTest, MatchesNonEmptyOptional) { |
6409 | const Matcher<SampleOptional<int>> m1 = Optional(1); |
6410 | const Matcher<SampleOptional<int>> m2 = Optional(Eq(2)); |
6411 | const Matcher<SampleOptional<int>> m3 = Optional(Lt(3)); |
6412 | SampleOptional<int> opt(1); |
6413 | EXPECT_TRUE(m1.Matches(opt)); |
6414 | EXPECT_FALSE(m2.Matches(opt)); |
6415 | EXPECT_TRUE(m3.Matches(opt)); |
6416 | } |
6417 | |
6418 | TEST(OptionalTest, DoesNotMatchNullopt) { |
6419 | const Matcher<SampleOptional<int>> m = Optional(1); |
6420 | SampleOptional<int> empty; |
6421 | EXPECT_FALSE(m.Matches(empty)); |
6422 | } |
6423 | |
6424 | TEST(OptionalTest, WorksWithMoveOnly) { |
6425 | Matcher<SampleOptional<std::unique_ptr<int>>> m = Optional(Eq(nullptr)); |
6426 | EXPECT_TRUE(m.Matches(SampleOptional<std::unique_ptr<int>>(nullptr))); |
6427 | } |
6428 | |
6429 | class SampleVariantIntString { |
6430 | public: |
6431 | SampleVariantIntString(int i) : i_(i), has_int_(true) {} |
6432 | SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {} |
6433 | |
6434 | template <typename T> |
6435 | friend bool holds_alternative(const SampleVariantIntString& value) { |
6436 | return value.has_int_ == std::is_same<T, int>::value; |
6437 | } |
6438 | |
6439 | template <typename T> |
6440 | friend const T& get(const SampleVariantIntString& value) { |
6441 | return value.get_impl(static_cast<T*>(nullptr)); |
6442 | } |
6443 | |
6444 | private: |
6445 | const int& get_impl(int*) const { return i_; } |
6446 | const std::string& get_impl(std::string*) const { return s_; } |
6447 | |
6448 | int i_; |
6449 | std::string s_; |
6450 | bool has_int_; |
6451 | }; |
6452 | |
6453 | TEST(VariantTest, DescribesSelf) { |
6454 | const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); |
6455 | EXPECT_THAT(Describe(m), ContainsRegex("is a variant<> with value of type " |
6456 | "'.*' and the value is equal to 1" )); |
6457 | } |
6458 | |
6459 | TEST(VariantTest, ExplainsSelf) { |
6460 | const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); |
6461 | EXPECT_THAT(Explain(m, SampleVariantIntString(1)), |
6462 | ContainsRegex("whose value 1" )); |
6463 | EXPECT_THAT(Explain(m, SampleVariantIntString("A" )), |
6464 | HasSubstr("whose value is not of type '" )); |
6465 | EXPECT_THAT(Explain(m, SampleVariantIntString(2)), |
6466 | "whose value 2 doesn't match" ); |
6467 | } |
6468 | |
6469 | TEST(VariantTest, FullMatch) { |
6470 | Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); |
6471 | EXPECT_TRUE(m.Matches(SampleVariantIntString(1))); |
6472 | |
6473 | m = VariantWith<std::string>(Eq("1" )); |
6474 | EXPECT_TRUE(m.Matches(SampleVariantIntString("1" ))); |
6475 | } |
6476 | |
6477 | TEST(VariantTest, TypeDoesNotMatch) { |
6478 | Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); |
6479 | EXPECT_FALSE(m.Matches(SampleVariantIntString("1" ))); |
6480 | |
6481 | m = VariantWith<std::string>(Eq("1" )); |
6482 | EXPECT_FALSE(m.Matches(SampleVariantIntString(1))); |
6483 | } |
6484 | |
6485 | TEST(VariantTest, InnerDoesNotMatch) { |
6486 | Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1)); |
6487 | EXPECT_FALSE(m.Matches(SampleVariantIntString(2))); |
6488 | |
6489 | m = VariantWith<std::string>(Eq("1" )); |
6490 | EXPECT_FALSE(m.Matches(SampleVariantIntString("2" ))); |
6491 | } |
6492 | |
6493 | class SampleAnyType { |
6494 | public: |
6495 | explicit SampleAnyType(int i) : index_(0), i_(i) {} |
6496 | explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {} |
6497 | |
6498 | template <typename T> |
6499 | friend const T* any_cast(const SampleAnyType* any) { |
6500 | return any->get_impl(static_cast<T*>(nullptr)); |
6501 | } |
6502 | |
6503 | private: |
6504 | int index_; |
6505 | int i_; |
6506 | std::string s_; |
6507 | |
6508 | const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; } |
6509 | const std::string* get_impl(std::string*) const { |
6510 | return index_ == 1 ? &s_ : nullptr; |
6511 | } |
6512 | }; |
6513 | |
6514 | TEST(AnyWithTest, FullMatch) { |
6515 | Matcher<SampleAnyType> m = AnyWith<int>(Eq(1)); |
6516 | EXPECT_TRUE(m.Matches(SampleAnyType(1))); |
6517 | } |
6518 | |
6519 | TEST(AnyWithTest, TestBadCastType) { |
6520 | Matcher<SampleAnyType> m = AnyWith<std::string>(Eq("fail" )); |
6521 | EXPECT_FALSE(m.Matches(SampleAnyType(1))); |
6522 | } |
6523 | |
6524 | TEST(AnyWithTest, TestUseInContainers) { |
6525 | std::vector<SampleAnyType> a; |
6526 | a.emplace_back(1); |
6527 | a.emplace_back(2); |
6528 | a.emplace_back(3); |
6529 | EXPECT_THAT( |
6530 | a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)})); |
6531 | |
6532 | std::vector<SampleAnyType> b; |
6533 | b.emplace_back("hello" ); |
6534 | b.emplace_back("merhaba" ); |
6535 | b.emplace_back("salut" ); |
6536 | EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>("hello" ), |
6537 | AnyWith<std::string>("merhaba" ), |
6538 | AnyWith<std::string>("salut" )})); |
6539 | } |
6540 | TEST(AnyWithTest, TestCompare) { |
6541 | EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0))); |
6542 | } |
6543 | |
6544 | TEST(AnyWithTest, DescribesSelf) { |
6545 | const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1)); |
6546 | EXPECT_THAT(Describe(m), ContainsRegex("is an 'any' type with value of type " |
6547 | "'.*' and the value is equal to 1" )); |
6548 | } |
6549 | |
6550 | TEST(AnyWithTest, ExplainsSelf) { |
6551 | const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1)); |
6552 | |
6553 | EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex("whose value 1" )); |
6554 | EXPECT_THAT(Explain(m, SampleAnyType("A" )), |
6555 | HasSubstr("whose value is not of type '" )); |
6556 | EXPECT_THAT(Explain(m, SampleAnyType(2)), "whose value 2 doesn't match" ); |
6557 | } |
6558 | |
6559 | TEST(PointeeTest, WorksOnMoveOnlyType) { |
6560 | std::unique_ptr<int> p(new int(3)); |
6561 | EXPECT_THAT(p, Pointee(Eq(3))); |
6562 | EXPECT_THAT(p, Not(Pointee(Eq(2)))); |
6563 | } |
6564 | |
6565 | TEST(NotTest, WorksOnMoveOnlyType) { |
6566 | std::unique_ptr<int> p(new int(3)); |
6567 | EXPECT_THAT(p, Pointee(Eq(3))); |
6568 | EXPECT_THAT(p, Not(Pointee(Eq(2)))); |
6569 | } |
6570 | |
6571 | // Tests Args<k0, ..., kn>(m). |
6572 | |
6573 | TEST(ArgsTest, AcceptsZeroTemplateArg) { |
6574 | const std::tuple<int, bool> t(5, true); |
6575 | EXPECT_THAT(t, Args<>(Eq(std::tuple<>()))); |
6576 | EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>())))); |
6577 | } |
6578 | |
6579 | TEST(ArgsTest, AcceptsOneTemplateArg) { |
6580 | const std::tuple<int, bool> t(5, true); |
6581 | EXPECT_THAT(t, Args<0>(Eq(std::make_tuple(5)))); |
6582 | EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(true)))); |
6583 | EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(false))))); |
6584 | } |
6585 | |
6586 | TEST(ArgsTest, AcceptsTwoTemplateArgs) { |
6587 | const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT |
6588 | |
6589 | EXPECT_THAT(t, (Args<0, 1>(Lt()))); |
6590 | EXPECT_THAT(t, (Args<1, 2>(Lt()))); |
6591 | EXPECT_THAT(t, Not(Args<0, 2>(Gt()))); |
6592 | } |
6593 | |
6594 | TEST(ArgsTest, AcceptsRepeatedTemplateArgs) { |
6595 | const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT |
6596 | EXPECT_THAT(t, (Args<0, 0>(Eq()))); |
6597 | EXPECT_THAT(t, Not(Args<1, 1>(Ne()))); |
6598 | } |
6599 | |
6600 | TEST(ArgsTest, AcceptsDecreasingTemplateArgs) { |
6601 | const std::tuple<short, int, long> t(4, 5, 6L); // NOLINT |
6602 | EXPECT_THAT(t, (Args<2, 0>(Gt()))); |
6603 | EXPECT_THAT(t, Not(Args<2, 1>(Lt()))); |
6604 | } |
6605 | |
6606 | MATCHER(SumIsZero, "" ) { |
6607 | return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0; |
6608 | } |
6609 | |
6610 | TEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) { |
6611 | EXPECT_THAT(std::make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero()))); |
6612 | EXPECT_THAT(std::make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero()))); |
6613 | } |
6614 | |
6615 | TEST(ArgsTest, CanBeNested) { |
6616 | const std::tuple<short, int, long, int> t(4, 5, 6L, 6); // NOLINT |
6617 | EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq())))); |
6618 | EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt())))); |
6619 | } |
6620 | |
6621 | TEST(ArgsTest, CanMatchTupleByValue) { |
6622 | typedef std::tuple<char, int, int> Tuple3; |
6623 | const Matcher<Tuple3> m = Args<1, 2>(Lt()); |
6624 | EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2))); |
6625 | EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2))); |
6626 | } |
6627 | |
6628 | TEST(ArgsTest, CanMatchTupleByReference) { |
6629 | typedef std::tuple<char, char, int> Tuple3; |
6630 | const Matcher<const Tuple3&> m = Args<0, 1>(Lt()); |
6631 | EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2))); |
6632 | EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2))); |
6633 | } |
6634 | |
6635 | // Validates that arg is printed as str. |
6636 | MATCHER_P(PrintsAs, str, "" ) { |
6637 | return testing::PrintToString(arg) == str; |
6638 | } |
6639 | |
6640 | TEST(ArgsTest, AcceptsTenTemplateArgs) { |
6641 | EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9), |
6642 | (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>( |
6643 | PrintsAs("(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)" )))); |
6644 | EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9), |
6645 | Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>( |
6646 | PrintsAs("(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)" )))); |
6647 | } |
6648 | |
6649 | TEST(ArgsTest, DescirbesSelfCorrectly) { |
6650 | const Matcher<std::tuple<int, bool, char> > m = Args<2, 0>(Lt()); |
6651 | EXPECT_EQ("are a tuple whose fields (#2, #0) are a pair where " |
6652 | "the first < the second" , |
6653 | Describe(m)); |
6654 | } |
6655 | |
6656 | TEST(ArgsTest, DescirbesNestedArgsCorrectly) { |
6657 | const Matcher<const std::tuple<int, bool, char, int>&> m = |
6658 | Args<0, 2, 3>(Args<2, 0>(Lt())); |
6659 | EXPECT_EQ("are a tuple whose fields (#0, #2, #3) are a tuple " |
6660 | "whose fields (#2, #0) are a pair where the first < the second" , |
6661 | Describe(m)); |
6662 | } |
6663 | |
6664 | TEST(ArgsTest, DescribesNegationCorrectly) { |
6665 | const Matcher<std::tuple<int, char> > m = Args<1, 0>(Gt()); |
6666 | EXPECT_EQ("are a tuple whose fields (#1, #0) aren't a pair " |
6667 | "where the first > the second" , |
6668 | DescribeNegation(m)); |
6669 | } |
6670 | |
6671 | TEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) { |
6672 | const Matcher<std::tuple<bool, int, int> > m = Args<1, 2>(Eq()); |
6673 | EXPECT_EQ("whose fields (#1, #2) are (42, 42)" , |
6674 | Explain(m, std::make_tuple(false, 42, 42))); |
6675 | EXPECT_EQ("whose fields (#1, #2) are (42, 43)" , |
6676 | Explain(m, std::make_tuple(false, 42, 43))); |
6677 | } |
6678 | |
6679 | // For testing Args<>'s explanation. |
6680 | class LessThanMatcher : public MatcherInterface<std::tuple<char, int> > { |
6681 | public: |
6682 | void DescribeTo(::std::ostream* /*os*/) const override {} |
6683 | |
6684 | bool MatchAndExplain(std::tuple<char, int> value, |
6685 | MatchResultListener* listener) const override { |
6686 | const int diff = std::get<0>(value) - std::get<1>(value); |
6687 | if (diff > 0) { |
6688 | *listener << "where the first value is " << diff |
6689 | << " more than the second" ; |
6690 | } |
6691 | return diff < 0; |
6692 | } |
6693 | }; |
6694 | |
6695 | Matcher<std::tuple<char, int> > LessThan() { |
6696 | return MakeMatcher(new LessThanMatcher); |
6697 | } |
6698 | |
6699 | TEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) { |
6700 | const Matcher<std::tuple<char, int, int> > m = Args<0, 2>(LessThan()); |
6701 | EXPECT_EQ( |
6702 | "whose fields (#0, #2) are ('a' (97, 0x61), 42), " |
6703 | "where the first value is 55 more than the second" , |
6704 | Explain(m, std::make_tuple('a', 42, 42))); |
6705 | EXPECT_EQ("whose fields (#0, #2) are ('\\0', 43)" , |
6706 | Explain(m, std::make_tuple('\0', 42, 43))); |
6707 | } |
6708 | |
6709 | class PredicateFormatterFromMatcherTest : public ::testing::Test { |
6710 | protected: |
6711 | enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky }; |
6712 | |
6713 | // A matcher that can return different results when used multiple times on the |
6714 | // same input. No real matcher should do this; but this lets us test that we |
6715 | // detect such behavior and fail appropriately. |
6716 | class MockMatcher : public MatcherInterface<Behavior> { |
6717 | public: |
6718 | bool MatchAndExplain(Behavior behavior, |
6719 | MatchResultListener* listener) const override { |
6720 | *listener << "[MatchAndExplain]" ; |
6721 | switch (behavior) { |
6722 | case kInitialSuccess: |
6723 | // The first call to MatchAndExplain should use a "not interested" |
6724 | // listener; so this is expected to return |true|. There should be no |
6725 | // subsequent calls. |
6726 | return !listener->IsInterested(); |
6727 | |
6728 | case kAlwaysFail: |
6729 | return false; |
6730 | |
6731 | case kFlaky: |
6732 | // The first call to MatchAndExplain should use a "not interested" |
6733 | // listener; so this will return |false|. Subsequent calls should have |
6734 | // an "interested" listener; so this will return |true|, thus |
6735 | // simulating a flaky matcher. |
6736 | return listener->IsInterested(); |
6737 | } |
6738 | |
6739 | GTEST_LOG_(FATAL) << "This should never be reached" ; |
6740 | return false; |
6741 | } |
6742 | |
6743 | void DescribeTo(ostream* os) const override { *os << "[DescribeTo]" ; } |
6744 | |
6745 | void DescribeNegationTo(ostream* os) const override { |
6746 | *os << "[DescribeNegationTo]" ; |
6747 | } |
6748 | }; |
6749 | |
6750 | AssertionResult RunPredicateFormatter(Behavior behavior) { |
6751 | auto matcher = MakeMatcher(new MockMatcher); |
6752 | PredicateFormatterFromMatcher<Matcher<Behavior>> predicate_formatter( |
6753 | matcher); |
6754 | return predicate_formatter("dummy-name" , behavior); |
6755 | } |
6756 | }; |
6757 | |
6758 | TEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) { |
6759 | AssertionResult result = RunPredicateFormatter(kInitialSuccess); |
6760 | EXPECT_TRUE(result); // Implicit cast to bool. |
6761 | std::string expect; |
6762 | EXPECT_EQ(expect, result.message()); |
6763 | } |
6764 | |
6765 | TEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) { |
6766 | AssertionResult result = RunPredicateFormatter(kAlwaysFail); |
6767 | EXPECT_FALSE(result); // Implicit cast to bool. |
6768 | std::string expect = |
6769 | "Value of: dummy-name\nExpected: [DescribeTo]\n" |
6770 | " Actual: 1, [MatchAndExplain]" ; |
6771 | EXPECT_EQ(expect, result.message()); |
6772 | } |
6773 | |
6774 | TEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) { |
6775 | AssertionResult result = RunPredicateFormatter(kFlaky); |
6776 | EXPECT_FALSE(result); // Implicit cast to bool. |
6777 | std::string expect = |
6778 | "Value of: dummy-name\nExpected: [DescribeTo]\n" |
6779 | " The matcher failed on the initial attempt; but passed when rerun to " |
6780 | "generate the explanation.\n" |
6781 | " Actual: 2, [MatchAndExplain]" ; |
6782 | EXPECT_EQ(expect, result.message()); |
6783 | } |
6784 | |
6785 | } // namespace |
6786 | } // namespace gmock_matchers_test |
6787 | } // namespace testing |
6788 | |
6789 | #ifdef _MSC_VER |
6790 | # pragma warning(pop) |
6791 | #endif |
6792 | |